gpt4 book ai didi

java - 我想从我的 JButton 扩展中检索值

转载 作者:行者123 更新时间:2023-12-02 07:27:20 25 4
gpt4 key购买 nike

我读过ActionEvents 返回事件对象的引用。我想知道如何从该引用资料中提取一条信息。我确信答案就在那里,我只是不确定如何表达我的问题才能得到答案。

我创建了一个扩展 JButton 的新类。我希望我创建的每个按钮都存储一个用于数学运算的整数值。

import javax.swing.JButton;
public class NewButton extends JButton {
int value;
public NewButton(String writing, int value) {
this.setText(writing);
this.value = value;
}

public int getValue() {
return value;
}
}

我想使用 ActionListener 检查点击,然后我想在控制台中显示 int value。这是我的图形用户界面:

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class MyGui {
public static void main(String[] args) {

JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);

NewButton button = new NewButton("ten", 10);
panel.add(button);

ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button) {
System.out.println(button.getValue());
}
}
};

button.addActionListener(listener);

frame.setVisible(true);
frame.setSize(100,100);
}
}

所以这对一个按钮来说效果很好。

现在我们(终于)解决了我的问题。我想制作另一个 NewButton,button2 。我想我会更改我的 ActionListener 部分。我想我可以为两个按钮添加一条语句,因为它们属于同一类。

        ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button1 || e.getSource() == button2) {
System.out.println(e.getSource().getValue());
}
}
};

但这行不通。

我的推理是因为我可以检查:

e.getSource() == button

那么引用 e.getSource() 应该可以让我访问我的 getValue()

有谁知道从 e.getSource() 获取 value 的方法吗?我的目标是看看我是否可以避免为每个按钮制作单独的 if 语句或 Action 监听器。

最佳答案

您可以将 JButton 转换为 NewButton,然后调用您的方法。

public void actionPerformed(ActionEvent e) {
NewButton newBtn = (NewButton) e.getSource();
int value = newBtn.getValue();
}

话虽如此,我自己还是不想扩展 JButton,而是扩展 AbstractAction。例如:

import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.event.ActionEvent;

public class MyGui {
public static void main(String[] args) {
String[] texts = { "One", "Two", "Three", "Four", "Five" };
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();

for (int i = 0; i < texts.length; i++) {
int value = i + 1;
panel.add(new JButton(new NewAction(value, texts[i])));
}

frame.add(panel);

frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}

class NewAction extends AbstractAction {
private int value;

public NewAction(int value, String name) {
super(name);
this.value = value;
}

@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Value: " + value);
}
}

关于java - 我想从我的 JButton 扩展中检索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26558219/

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