0

I want to have a button that when pressed, a method will be invoked. Here is some code

public class Tester extends JPanel {              
    public void paintComponent(Graphics g){
        super.paintComponent(g);            
        g.fillRect(10, 10, 10, 10);

    }
    //The method which I wand invoke but can't, I don't know why.
    void setWidth(){
        //width -= 10 ;
        repaint();
    }

    public static void main(String[] args) {
            //Here some JFrame...
            Tester paint = new Tester();
            frame.add(paint);
            JButton click = new JButton("Click");

            click.addActionListener(new ActionListener(){

                @Override
                public void actionPerformed(ActionEvent e) {
                    paint.setWidth();//Here I Want invoke that method
                }

            });
    }
}

I want that ActionListener will invoke the method setWidth(), but it doesn't. Don't know why.

user1803551
  • 12,965
  • 5
  • 47
  • 74
user3491167
  • 91
  • 3
  • 13
  • Well, for starters, in the code you're showing, you don't add the listener to the button. Also, you don't add the button to anything. – Vince Apr 30 '14 at 23:35
  • @VinceEmigh Why do you say he doesn't add the listener? to me it seems perfect. Well your second note is true. – Mordechai Apr 30 '14 at 23:47

1 Answers1

0

paint variable is not in the scope of the anonyomous ActionListener class try changing paint Class to make it implement ActionListener interface and make it's instance be the action listener for the "Click" button, also attach the button to the panel instance like this:

public class Tester extends JPanel implements ActionListener {              

   @Override
   public void actionPerformed(ActionEvent e) {
         setWidth();
   }

    public static void main(String[] args) {
            //Here some JFrame...
            Tester paint = new Tester();            
            frame.add(paint);

            JButton click = new JButton("Click");
            paint.add(click);
            click.addActionListener(paint);

    }
}
guilhebl
  • 8,330
  • 10
  • 47
  • 66