更新:
感谢一些乐于助人的人,找到了解决方案。
我现在正在创建如下按钮,并添加事件:
for(String s: new String[]{"7", "8", "9", "4", "5", "6", "1", "2","3", "0", ".", "=" }) {// change here, as per your need
JButton btn = new JButton(s);
numButtonPanel.add(btn);
btn.addActionListener(new EventListener());
}
注意:
EventListener是一个创建的类(向下滚动到答案,你可以看到那里的课程)
我正在使用JAVA Swing库创建一个计算器,我目前在gridlayout中有数字按钮。
我的问题是,鉴于以下代码,我如何将点击事件添加到我的JButtons?
我的JButtons示例:
numButtonPanel.add(new JButton("8"));
numButtonPanel.add(new JButton("9"));
numButtonPanel.add(new JButton("4"));
numButtonPanel.add(new JButton("5"));
numButtonPanel.add(new JButton("6"));
如你所见,我在gridlayout中创建它们......我不只是添加已经创建的JButtons。
如果有人可以提供帮助,那就太棒了!
谢谢!
答案 0 :(得分:1)
看一下How to Use Actions,它们是自我配置和自包含的动作......
public class NumberAction extends AbstractAction {
private int value;
public NumberAction(int value) {
put(NAME, Integer.toString(value));
}
@Override
public void actionPerformed(ActionEvent evt) {
// Do some work here...
}
}
然后只需将它们应用于按钮
即可numButtonPanel.add(new JButton(new NumberAction(8)));
numButtonPanel.add(new JButton(new NumberAction(9)));
numButtonPanel.add(new JButton(new NumberAction(4)));
numButtonPanel.add(new JButton(new NumberAction(5)));
numButtonPanel.add(new JButton(new NumberAction(6)));
答案 1 :(得分:0)
您应该创建一个引用并添加对布局的引用,以便稍后可以在按钮上添加动作侦听器,如
JButton yourButton = new JButton("8")
然后将其添加到您的面板
numButtonPanel.add(yourButton);
答案 2 :(得分:0)
像这样创建你的监听器类
class SampleActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e)
{
}
}
并将监听器添加到如下按钮
String buttonLabels = new String[]{"8", "9", "4", "5", "6"};
for(String s:buttonLabels)
JButton comp = new JButton(s);
comp.addActionListener(new SampleActionListener());
numButtonPanel.add(comp);
}
答案 3 :(得分:0)
尝试使用循环:
for(String s: new String[]{"8", "9", "4", "5"}) {// change here, as per your need
JButton btn = new JButton(s);
numButtonPanel.add(btn);
btn.addActionListener(new YourActionListener());//<-- change here, as per your need
}
答案 4 :(得分:0)
如果以这种方式创建对象,则无法在类中的任何位置获取对象的引用。您需要创建每个对象以执行某些特定任务。我确信你的所有按钮都不会执行相同的操作。您应该检查以下代码,它会对您有所帮助。
构造函数或初始化方法如下所示:
public Class_name() //in my case constructor
{
JButton btn1 = new JButton("Print Hello");
JButton btn2 = new JButton("Print Welcome");
btn1.addActionListener((ActionEvent e)-> {
System.out.print("Hello");
});
btn2.addActionListener((ActionEvent e)-> {
System.out.println(" Welcome");
});
}
正如您所看到的,每个按钮执行不同的任务。在您的情况下,如果您没有指定对按钮的引用,则无法让按钮执行不同的任务。
对于我的上述观点,我会告诉你哪里会卡住。 ActionPerformed方法,上面的代码用重写方法替换内部内容。
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==btn1) //here you cannot identify which object generated the event
{
System.out.print("Hello");
}
if(e.getSource()==btn2)
{
System.out.println(" Welcome");
}
}