我不习惯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
}
}
答案 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
界面?