gpt4 book ai didi

java - 为什么我的 jradiobutton 只使用一次?

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

我没有对 jradiobuttons 进行分组,以便用户可以选择多个选项,并且我可以存储在节点数组中..但它只读取一次。代码有什么问题吗?请赐教

private String[] showGUIForNodeDeletion() {

JPanel panel = new JPanel();
panel.setLayout(new GridLayout(map.size(), 1));
ButtonGroup btnGrp = new ButtonGroup();
final String nodes[] = new String[10];
Set<String> keySet = map.keySet();

for (String name : keySet) {

btnRadio = new JRadioButton(name);
btnRadio.setActionCommand(map.get(name).x + "," + map.get(name).y + "," + name);
//btnGrp.add(btnRadio);
panel.add(btnRadio);
}

btnRadio.addActionListener(new ActionListener() {
int x = 0;

public void actionPerformed(ActionEvent e) {

nodes[x] = ((JRadioButton) e.getSource()).getActionCommand();
System.out.println("Node counting " + x);
x++;
}
});

if (keySet.isEmpty()) {
JOptionPane.showMessageDialog(AnotherGuiSample.this, "Work Space is empty", "Error", JOptionPane.ERROR_MESSAGE);
} else {
JOptionPane.showMessageDialog(AnotherGuiSample.this, panel, "Select node to remove", JOptionPane.INFORMATION_MESSAGE);
}
for(int x = 0; x < nodes.length; x++ )
System.out.println("node is " + nodes[x]);

return nodes;
}

最佳答案

你的for循环代码应该是这样的:

更新

Set<String> rbSet = new TreeSet<String>();
for (String name : keySet) {

btnRadio = new JRadioButton(name);
btnRadio.setActionCommand(map.get(name).x + "," + map.get(name).y + "," + name);
btnRadio.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
JRadioButton obj = (JRadioButton)evt.getSource();
if (obj.isSelected())
{
rbSet.add(obj.getActionCommand());
}
else
{
rbSet.remove(obj.getActionCommand());
}
}
});
panel.add(btnRadio);
}
int counter = 0 ;
for (String action : rbSet )
{
nodes[counter++] = action;
}

发生了什么,您正在使用 for 循环中创建的最后一个对象注册 ActionListener ,因为您是在 for 循环之后执行的。这就是为什么它仅针对创建并添加到 JPanel 的 lat JRaioButton 对象触发。您应该在 for 循环中注册 ActionListener 并在循环中创建每个 JRadioButton。这使得 ActionEvent 为您添加到 JPanel 的每个 JRadioButton 触发。

关于java - 为什么我的 jradiobutton 只使用一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15597020/

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