Is it possible to make JToggle text depend on its state?

Junaid Hassan picture Junaid Hassan · May 3, 2013 · Viewed 7.4k times · Source

Is it possible for me to set the text on JToggle button to "ON" if it is selected and if not, as "OFF"? I'm trying with this code:

    if(togbut.isSelected()){
        togbut.setText("ON");
    }
     else if(!togbut.isSelected()){
           togbut.setText("OFF");
    }

But it doesn't work. I use NetBeans 7.3.

Answer

Gilbert Le Blanc picture Gilbert Le Blanc · May 3, 2013

Your code is almost correct.

It has to be put in the change listener of your toggle button.

    toggleButton.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent event) {
            if (toggleButton.isSelected()){
                toggleButton.setText("ON");
            } else {
                toggleButton.setText("OFF");
            }
        }
    });