1

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.

Bridge
  • 29,818
  • 9
  • 60
  • 82
Igor N.
  • 31
  • 4

2 Answers2

3

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

   }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Nice trick. I will use it in another part of my app. But actually not what I wanted. When toggle button is selected there is slight blue lighting and I want to disable it but without disabling Windows OS buttons style. – Igor N. Sep 02 '12 at 09:48
3

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.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433