public Keypad() {
setLayout(new GridLayout(4,3));
for(int i=9; i>=0; i--){
JButton tmp = new JButton(Integer.toString(i));
add(tmp);
tmp.addActionListener(this);
}
JButton btnPoint = new JButton(".");
JButton btnEqual = new JButton("=");
add(btnPoint);
btnPoint.addActionListener(this);
add(btnEqual);
btnEqual.addActionListener(this);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
}
public void actionPerformed(ActionEvent event) {
System.out.println(event.getSource());
}
作为JFrame的初学者,我尝试创建一些带有for循环的JButton。但是,我不知道如何处理对应按钮的actionPerformed,因为它们具有相同的变量名称"tmp",所以if(event.getSource() == tmp)
可能不适合这种情况。
在actionPerformed中,我尝试通过单击不同的按钮打印出源,结果是:javax.swing.JButton[,0,0,75x29,alignmentX=0.0,alignmentY=0.5,border=com.apple.laf.AquaButtonBorder$Dynamic@4be40942,flags=288,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=0,left=2,bottom=0,right=2],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=false,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=9,defaultCapable=true]
当我点击按钮"9"时,它似乎可以正确地获得按钮标签text=9
。所以我可以做一些像if(event.getSource().getText() == "9")
这样的事情吗?
如何处理对应按钮执行的动作,因为它们具有相同的变量名称"tmp">
实际上tmp
的作用域是Keypad
类构造函数中的for
循环。因此你不能在方法actionPerformed
中引用它。
您将相同的ActionListener
分配给所有JButton
,并且您想要一种方法来确定在actionPerformed
方法中单击了哪个JButton
。由于您创建的每个JButton
都有不同的文本,因此获取JButton
文本的想法似乎是一种方法。那么,如何获得在actionPerformed
方法中单击的JButton
的文本呢?
JButton
有一个ButtonModel,它有一个动作命令,这是一个字符串。默认情况下,JButton
的文本也是它的操作命令。ActionEvent
,即方法actionPerformed
的参数,声明方法getActionCommand,该方法返回被单击的JButton
的操作命令。因此,在actionPerformed
方法中获取JButton
文本的最简单方法是在actionPerformed
方法参数上调用getActionCommand
方法。
public void actionPerformed(java.awt.event.ActionEvent event) {
String buttonText = event.getActionCommand();
switch (buttonText) {
case "1":
// Handle button "1".
break;
// Remaining cases...
}
}
如何编写动作监听器
或者,您可以为每个JButton
分配一个单独的ActionListener
。自Java 8以来,使用方法引用很容易做到这一点,因为ActionListener
是一个功能接口。
public Keypad() {
setLayout(new GridLayout(4,3));
for(int i=9; i>=0; i--){
JButton tmp = new JButton(Integer.toString(i));
add(tmp);
switch (i) {
case 1:
tmp.addActionListener(this::handleButton1);
break;
// Remaining cases...
}
tmp.addActionListener(this);
}
}
private void handleButton1(java.awt.event.ActionEvent event) {
// No need to check the "event" source since the source is always the same.
}
为了成为有效的方法引用,方法handleButton1
必须返回与方法actionPerformed
相同的值——即void
,并且它必须具有与方法actionPerformed
相同的参数。