Igor N.
Igor N.

Reputation: 31

Disable standard repainting of JToggleButton when It is selected

I want my JToggleButton not to repaint when It is selected. I indicate state changing by pair of words ("check/next"). Standard behavior is blue lighting but I want to disable it.

Upvotes: 1

Views: 871

Answers (2)

Andrew Thompson
Andrew Thompson

Reputation: 168825

See: AbstractButton.setContentAreaFilled(false).

But note that users generally prefer a GUI element that follows the 'path of least surprise'. This type of rendering might be better described as going off on a bit of a crash-bang through the undergrowth beside that path.

Upvotes: 3

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Perhaps you could show the words on ImageIcons. For example:

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JToggleButton;

public class ToggleFun {
   private static final Color BACKGROUND_COLOR = new Color(200, 200, 255);

   public static void main(String[] args) {
      int biWidth = 60;
      int biHeight = 30;
      BufferedImage checkImg = new BufferedImage(biWidth, biHeight, BufferedImage.TYPE_INT_RGB);
      BufferedImage nextImg = new BufferedImage(biWidth, biHeight, BufferedImage.TYPE_INT_RGB);

      Graphics2D g2 = checkImg.createGraphics();
      g2.setColor(BACKGROUND_COLOR);
      g2.fillRect(0, 0, biWidth, biHeight);
      g2.setColor(Color.black);
      g2.drawString("Check", 10, 20);
      g2.dispose();

      g2 = nextImg.createGraphics();
      g2.setColor(BACKGROUND_COLOR);
      g2.fillRect(0, 0, biWidth, biHeight);
      g2.setColor(Color.black);
      g2.drawString("Next", 15, 20);
      g2.dispose();

      ImageIcon checkIcon = new ImageIcon(checkImg);
      ImageIcon nextIcon = new ImageIcon(nextImg);

      JToggleButton toggleBtn = new JToggleButton(checkIcon);
      toggleBtn.setSelectedIcon(nextIcon);
      toggleBtn.setContentAreaFilled(false);
      toggleBtn.setBorder(BorderFactory.createLineBorder(Color.black));

      JPanel panel = new JPanel();
      panel.add(toggleBtn);
      JOptionPane.showMessageDialog(null, panel);

   }
}

Upvotes: 3

Related Questions