javaswingjbuttonjtogglebutton

Disabling Enabled Effect on JToggleButton


I've got an application that is using Swing for it's UI. I want a button that switch the type of communication that the app is using. I want to use a Toggle Button to identify the type of communication that's selected.

My problem is that I don't want the color of the button to change after it's been clicked. Currently the button looks like this... Non-Selected

https://i.sstatic.net/Ccdie.png

And then when clicked it looks like this...

Selected

https://i.sstatic.net/Q5yp4.png

The text changing is what I want, but I would prefer them to have the same color / style.

Here's my code for this...

    JToggleButton tglbtnCommunicationType = new JToggleButton("AlwaysOn");
    tglbtnCommunicationType.setFocusPainted(false);
    tglbtnCommunicationType.addChangeListener(new ChangeListener( ) {
        public void stateChanged(ChangeEvent tgl) {
            System.out.println("ChangeEvent!");
            if(tglbtnCommunicationType.isSelected()){
                tglbtnCommunicationType.setText("REST");
                tglbtnCommunicationType.setBackground(UIManager.getColor("Button.background"));
            }
            else
            {
                tglbtnCommunicationType.setText("AlwaysOn");
            };
        }
    });

My thought is that setting the background when it is selected to the standard background color would fix that, but it doesn't look like it. Any ideas?

Thanks!

Answer: I switched to a JButton instead, thanks for the help everyone!

JButton btnCommunicationType = new JButton("AlwaysOn");
    btnCommunicationType.setFocusPainted(false);
    btnCommunicationType.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if(btnCommunicationType.getText().equals("AlwaysOn"))
            {
                btnCommunicationType.setText("REST");
                //TODO:  Insert Code for Switching Communication to REST here
            }
            else if(btnCommunicationType.getText().equals("REST")){
                btnCommunicationType.setText("AlwaysOn");
                //TODO: Insert Code for Switching Communication to AlwaysOne here
            }
        }
    });
    btnCommunicationType.setBounds(275, 199, 97, 25);
    thingWorxConnectionPanel.add(btnCommunicationType);

Solution

  • you can do it by using JButton only instead of JToggleButton ,

    JButton showButton = new JButton("AlwaysOn");
    showButton.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
         String currentText = showButton.getText();
         if("AlwaysOn".equals(currentText)){
              showButton.setText("REST");
         }else{
              showButton.setText("AlwaysOn");
          }
      }
    });