好的,如果我有以下代码:
protected void makebutton(String name){
JButton button = new JButton(name);
mypanel.add(button);
}
然后:
makebutton("Button1");
makebutton("Button2");
makebutton("Button3");
如何才能将ActionListener添加到它们中。我应该使用哪个名称来表示ActionListener,尝试了许多组合,但都没有成功。
发布于 2013-12-14 19:13:56
你可以做的就是让方法返回一个Button。这样你就可以在程序中的其他地方使用按钮变量了。在您的例子中发生的情况是按钮被封装。因此,您不能从代码中的任何其他位置访问。像这样的东西
private JButton makeButton(String name){
JButton button = new JButton(name);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
// code action to perform
}
});
return button;
}
您可以在声明按钮时使用该方法
JButton aButton = makeButton();
panel.add(aButton);
更合理的方法是在没有方法的情况下创建按钮。
JButtton button = new JButton("Button");
panel.add(button);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
// code action to perform
}
});
我真的不认为有必要使用一种方法。
另一种选择是创建自定义监听器类
public class GUI {
JButton button1;
JButton button2;
public GUI(){
button1 = new JButton();
button2 = new JButton();
button1.addActionListner(new ButtonListener());
button2.addActionListner(new ButtonListener());
}
private class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e){
if (e.getSource() == button1){
// do something
} else if (e.getSource() == button2){
// something
}
}
}
}
发布于 2013-12-14 22:04:25
protected void makebutton(String name){
final String n = name;
JButton button = new JButton(name);
mypanel.add(button);
button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
if(n=="Button1"){
button1ActionListener();
}else if(n=="Button2"){
button2ActionListener();
}
}
});
}
你必须为每个按钮创建更多的方法。我认为peeskillet的第二个代码是最好的。
https://stackoverflow.com/questions/20582366
复制相似问题