JToggleButton - how to get selected state?

1.4k views Asked by At

I'm making a BMR calculator and one of my panels gives the user an option to change how they wish to enter their height, from cm to ft/inches.

Here's the block of code that deals with said panel.

    // Height JComponents
    heightLabel = new JLabel("Height:");
    heightCMField = new JTextField(4);
    heightFTField = new JTextField(3);
    heightFTLabel = new JLabel("ft");
    heightINCHLabel = new JLabel("inch");
    heightINCHField = new JTextField(3);
    cmButton = new JToggleButton("cm");
    feetButton = new JToggleButton("feet");
    heightPanel.add(heightLabel);


    if (cmButton.isSelected()) {
        heightPanel.add(heightCMField);
    } else if (feetButton.isSelected()) {
        heightPanel.add(heightFTField);
        heightPanel.add(heightFTLabel);
        heightPanel.add(heightINCHField);
        heightPanel.add(heightINCHLabel);
    } 

    heightPanel.add(cmButton);
    heightPanel.add(feetButton);

My problem is, when I press the kg or cm button, the text fields do not appear so I'm thinking I've used isSelected() wrong somehow.

An image of how this appears is below. You can see that no text fields appear even when feet is selected. What can I do to fix this?

enter image description here

1

There are 1 answers

5
Aditya Singh On

You need to add a listener:

cmButton.addActionListener(event->{

    /**
     * Code to show heightCMField.
     */
});

feetButton.addActionListener(event-> {

    /**
     * COde to show heightFTField and heightINCHField 
     */
});  

And if you are using JToggleButton, I suppose you want to use just one ToggleButton that switches your GUI. So if thats the case, delete cmButton and feetButton. And add only one new ToggleButton that does it all.

JToggleButton switchButton = new JToggleButton();
switchButton.setText("cm");  

switchButton.addActionListener(event->{

    if(switchButton.getText().equals("feet")) {

        switchButton.setText("cm");
        /* Code to show heightFTField and heightINCHField */
    } else if(switchButton.getText().equals("cm")) {

        switchButton.setText("feet");
        /* Code to show heightCMField */
    }
});  

You can also go for `ItemListener`.