Question

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.

Was it helpful?

Solution

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

OTHER TIPS

You have to attach an ItemListener to that toggle button:

final JToggleButton togbut = new JToggleButton();
togbut.addItemListener(new ItemListener() {

    @Override
    public void itemStateChanged(ItemEvent e) {
        if (e.getStateChange() == ItemEvent.SELECTED) {
            togbut.setText("ON");
        } else {
            togbut.setText("OFF");
        }
    }
});

Um Try this:

JToggleButton togbut = new JToggleButton("Click");
togbut.addItemListener(new ItemListener() {
   public void itemStateChanged(ItemEvent ev) {
      if(ev.getStateChange()==ItemEvent.SELECTED){
        togbut.setText("ON");
      } else if(ev.getStateChange()==ItemEvent.DESELECTED){
        togbut.setText("OFF");
      }
   }
});

Just add an action listener to your togbut:

togbut.AddActionListener(this);

And add your code in the ActionPerformed() method.
Also I don't think a JToggleButton can have other state than Selected and !Selected So you can changee your if structure to this:

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

You need to add ItemListener interface to the class, where you use your JToggleButton. The implementation should like this:

public class MyClassThatUsesToggleButton implements  ItemListener{

    //
    // some code
    //
    JToggleButton toggleButton;

    public void itemStateChanged(ItemEvent e) {
        if(e.getStateChange() == ItemEvent.SELECTED)
        {
            toggleButton.setText("On!");
            totalGUI.setBackground(Color.green);
        }
        else
        {
            toggleButton.setText("Off");
            totalGUI.setBackground(Color.red);
        } 
    //
    // some more code
    //
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top