0

I'm not used to Java and JFrame as I'm just starting to learn.

My question is that, I have error at the method actionPerformed. The error given is at the e.getsource == b I believe.

From what I understand, the button I created at the public static void main(String[] args) doesn't passed the value of the button to the actionPerformed.

I'm sorry if my question is not clear.

Here is my code

public static void main(String[] args){

    JButton b = new JButton("Click here");

    JFrame newWindow = new JFrame("Test");

    newWindow.setVisible(true);
    newWindow.setSize(250,250);
    newWindow.setLayout(null);

    newWindow.add(b);

    b.addActionListener(this);

}

Here is another part of my code

public void actionPerformed(ActionEvent e)
{
    if ( e.getSource() == b )
    { 
        //do something 
    }
}
4

2 回答 2

2

据我了解,我在 public static void main(String[] args) 创建的按钮没有将按钮的值传递给 actionPerformed。

的,你是对的。JButton 对象在方法b中不可见。actionPerformed您需要b全局声明。

   class MyClass extends JFrame implements ActionListener{
      // Declare here to make visible to actionPerformed
      JButton b = new JButton("Click here"); 

       MyClass(){    
        super("Test");
        b.addActionListener(this);
        add(b);
        setVisible(true);
        setSize(250,250);    
       }

       public void actionPerformed(ActionEvent e){
         if ( e.getSource() == b ){ 
         //do something 
         }
       }
       public static void main(String[] args){
            new MyClass();
       }
   }
于 2013-11-14T17:01:38.717 回答
0

它是e.getSource()。它是一种方法,所有方法都以括号结尾()

此外,b在 中不可见actionperformed()。使其成为全局变量,即在外部定义它main()并使其static能够在其中访问它main()

另外,正如所Masud问的,你的类是否实现了ActionListener接口?

于 2013-11-14T16:59:13.883 回答