![](/img/trans.png)
[英]How do I “getActionCommand” from a JTextField? I SEE it when debugging but
[英]How do I split the getActionCommand() in order to get the first element in the string?
我的程序中有一組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()
<---這是另一個類中的標簽,其名稱類似於“Front”,“Middle”或其他。
我現在的任務是:
getActionCommand()
來獲取標簽) 所以 ,我這樣做的方式如下:
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();
}
}
}
}
不幸的是,它不起作用,我無法找到錯誤的地方。 你能否就這項任務給出任何建議? 我究竟做錯了什么?
ps這行代碼String[] words = e.getActionCommand().split(" ");
沒有做我想做的事。 我嘗試了System.out.println(words[0])
並且它是空的,但應該有該組的名稱:(
這個...
button.add(new JLabel(group.name() + " @ $"+ formatted(group.price())));
沒有意義。 你應該用...
button.setText(group.name() + " @ $"+ formatted(group.price()));
和...
button.setActionCommand(group.name());
如果你不關心文本的其余部分......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.