英文:
How do I execute a function in an ActionListener through the button which is clicked
问题
以下是翻译好的代码部分:
这是我正在使用的类
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SudokuFeld extends JFrame {
private JPanel secondaryPanel;
private JButton button1;
private JButton button2;
private JButton button3;
private JButton button4;
private JButton button5;
private JButton button6;
private JButton button7;
private JButton button8;
private JButton button9;
private JButton[] bArr = new JButton[]{button1, button2, button3, button4, button5, button6, button7, button8, button9};
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 在此处执行通过被点击的按钮获取属性的操作
}
};
public SudokuFeld() throws HeadlessException {
int var = 0;
for (JButton val : bArr) {
val.putClientProperty("number", var);
val.addActionListener(listener);
var++;
}
}
}
请注意,我在注释中指示在actionPerformed
方法内执行通过被点击的按钮获取属性的操作,以输出分配给按钮的数字。
英文:
This is the class I'm using
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SudokuFeld extends JFrame{
private JPanel secondaryPanel;
private JButton button1;
private JButton button2;
private JButton button3;
private JButton button4;
private JButton button5;
private JButton button6;
private JButton button7;
private JButton button8;
private JButton button9;
private JButton[] bArr = new JButton[] {button1, button2, button3, button4, button5,button6, button7, button8, button9};
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
}
};
public SudokuFeld() throws HeadlessException {
int var = 0;
for(JButton val : bArr ) {
val.putClientProperty("number", var);
val.addActionListener(listener);
var++;
}
}
}
And what I want is to execute getClientProperty() in the ActionListener listener through the button which was clicked
I expected the number assigned to the button as output
答案1
得分: 1
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JButton jb = (JButton) e.getSource();
Integer value = (Integer) jb.getClientProperty("number");
... // whatever else you need to do
}
};
英文:
Try
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JButton jb = (JButton) e.getSource();
Integer value = (Integer) jb.getClientProperty("number");
... // whatever else you need to do
}
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论