How do I split getActionCommand () to get the first item in the line?

There are groups in my program JRadioButton

.

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

      

I've added buttons here:

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

      

This is how I create the button:

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;  
}

      

The button label is located here: button.add(new JLabel(group.name()

<--- it is a label that is in another class and has a name like "Front", "Middle" or whatever.

Now my task is:

  • To get the label of a radio button from an event (I use getActionCommand()

    to get the label)
  • Get the group name from the label (I need to split the string by space and get the first string in the returned array).
  • Find a group by name: Find a group with a name

So , I do it like this:

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();
            }
        }
    }
}

      

Unfortunately it doesn't work and I can't find where the error is. Could you give me any advice on this task? What am I doing wrong?

ps this line of code String[] words = e.getActionCommand().split(" ");

doesn't do what i want. I tried System.out.println(words[0])

and it is empty but there should be a group name :(

+3


source to share


1 answer


It...

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

      

It doesn't make sense. You must use ...

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

      



AND...

button.setActionCommand(group.name());

      

If you don't care, the rest of the text ...

+2


source







All Articles