gpt4 book ai didi

java - 如何在 ActionListener 中将 .getSource() 与多个 JButton 一起使用

转载 作者:行者123 更新时间:2023-12-01 10:09:42 25 4
gpt4 key购买 nike

基本上是一个带有几个整数的对象。我希望当按下相应的按钮时,整数会发生变化。例如,如果您按 JButton 2,则第二个 int 应根据 actionPerformed 方法中的 if 语句中的方法进行更改。不知道我做错了什么,但按钮现在绝对没有任何作用。

public class Object {

public int someInt;
//public int someOtherInt;
//etc. I have a few different ints that I do the same thing with throughout the code, each JButton changes a different int

public Object() {

this.someInt = someInt;

JFrame frame = new JFrame();
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(3);
frame.setSize(325, 180);
frame.setVisible(true);
frame.setTitle("Title");

//String message = blah blah
JLabel confirmMessage = new JLabel(message);
JButton button1 = new JButton("1");
JButton button2 = new JButton("2");
JButton button3 = new JButton("3");

//creating action listener and adding it to buttons and adding buttons to frame

}

public class listen implements ActionListener {

private int someInt;
private int someOtherInt;

public listen(int someInt, int someOtherInt) {

this.someInt = someInt;
this.someOtherInt = someOtherInt;
}

public void actionPerformed() {
if (aE.getSource() == button1) {
//change someInt
}
//same thing for other buttons
}
}
}

最佳答案

标准做法是为每个按钮附加一个单独的监听器:

// syntax for Java 1.8:
button1.addActionListener(e -> {
// do whatever
});

// syntax for Java 1.7 and earlier:
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// do whatever
}
});

关于java - 如何在 ActionListener 中将 .getSource() 与多个 JButton 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36208276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com