Java JFrame actionPerformed

时间:2013-11-14 16:56:59

标签: java swing compiler-errors jframe

我不习惯Java和JFrame,因为我刚开始学习。

我的问题是,我在方法actionPerformed上有错误。给出的错误是我认为的e.getsource == b

根据我的理解,我在public static void main(String[] args)创建的按钮未将按钮的值传递给actionPerformed

如果我的问题不明确,我很抱歉。

这是我的代码

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);

}

这是我的代码的另一部分

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

2 个答案:

答案 0 :(得分:2)

  

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

,你是对的。在b方法中看不到JButton对象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();
       }
   }

答案 1 :(得分:0)

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

此外,b中无法显示actionperformed()。将其设为全局变量,即在main()之外定义并将其设为static,以便能够在main()

中访问它

另外,当问Masud时,您的班级是否实现了ActionListener界面?