【问题标题】:How do I split the getActionCommand() in order to get the first element in the string?如何拆分 getActionCommand() 以获取字符串中的第一个元素?
【发布时间】:2015-05-06 03:56:49
【问题描述】:

我的程序中有一组JRadioButton

public class SalePanel extends JPanel  implements View { 
    private JTextField sell = new JTextField(5);
    private ButtonGroup buttons = new ButtonGroup();
    private Stadium stadium;

我在这里添加了按钮:

private void build(Stadium stadium){
    add(buttonBox(stadium));
}

这就是我创建按钮的方式:

private Box buttonBox(Stadium stadium)
{   Box box = Box.createVerticalBox();
    SaleListener listener = new SaleListener();
    for (Group group: stadium.groups()) {
        box.add(button(group, listener));

    }
    return box;
}   


private JRadioButton button(Group group, SaleListener listener){
    JRadioButton button  = new JRadioButton();
    button.addActionListener(listener);
    buttons.add(button);
    button.add(Box.createHorizontalStrut(35));
    button.add(new JLabel(group.name() + " @ $"+ formatted(group.price())));
    return button;  
}

按钮的标签在这里:button.add(new JLabel(group.name()

我现在的任务是:

  1. 从事件中获取单选按钮标签(我使用getActionCommand()获取标签)
  2. 从标签中获取组名(我需要用空格分割字符串,并获取返回数组中的第一个字符串)。
  3. 根据名称查找组: 查找给定名称的组

所以,我的做法如下:

private class SaleListener implements ActionListener { 
    public void actionPerformed(ActionEvent e) { 

        String[] words = e.getActionCommand().split(" ");
        String groupName  = words[0];
        for (Group group: stadium.groups()) {
            if (group.matches(groupName)){
                group.sell(sale());
                update();
            }
        }
    }
}

不幸的是,它不起作用,我找不到错误在哪里。 你能给我关于这个任务的任何建议吗?我做错了什么?

附言这行代码String[] words = e.getActionCommand().split(" "); 没有做我想做的事。我试过System.out.println(words[0]),它是空的,但应该有组的名称:(

【问题讨论】:

  • 为了尽快获得更好的帮助,请发布MCVE(最小完整可验证示例)或SSCCE(简短、自包含、正确示例)。

标签: java swing split


【解决方案1】:

这...

button.add(new JLabel(group.name() + " @ $"+ formatted(group.price())));

没有意义。你应该使用...

button.setText(group.name() + " @ $"+ formatted(group.price()));

还有……

button.setActionCommand(group.name());

如果你不关心文本的其余部分...

【讨论】:

  • 哇!非常感谢。这条线有帮助:button.setActionCommand(group.name());我很感激! p.s. button.add(new JLabel(group.name() + " @ $"+ formatted(group.price()))); - 在我的程序中它确实有意义 :) 我将标签添加到按钮并且它可以工作!
  • 但是JRadioButton已经有了标签,支持助记符(键盘快捷键),所以不行,一般没有意义
猜你喜欢
  • 2015-11-12
  • 2014-02-27
  • 1970-01-01
  • 2021-10-22
  • 1970-01-01
  • 2018-12-26
  • 2016-09-20
  • 2020-07-01
  • 2020-08-25
相关资源
最近更新 更多