[英]How to get JButton label text by actionPerformed?
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
中引用它。
您正在为所有JButton
分配相同的ActionListener
并且您想要一种方法来确定在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
相同的参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.