Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

CheckBox icon

JörgFeb 13 2012 — edited Feb 14 2012
Hello,

the following code shows a JCheckBox which changes its background colour when selected, thus serving as an eye catcher in a frame with several columns of checkboxes.
The only thing I would like to improve is that the ceckbox should keep the normal ocean LAF when unselected. Even when I comment out the special colouring and just do a super.paintIcon(...), it remains flat gray. Any ideas why?
import java.awt.*;  
import java.awt.event.*;  
import javax.swing.*;

public class HighlightedCheckBox extends JFrame {
  JCheckBox cbx;

  public HighlightedCheckBox() {
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    setSize(300,200);
    setLayout(new FlowLayout(FlowLayout.LEFT, 40, 40));
    cbx= new JCheckBox("The modified checkbox");
    HighlightOnSelectIcon icon= new HighlightOnSelectIcon(cbx);
    cbx.setIcon(icon);
    JCheckBox cb= new JCheckBox("Above checkbox enabled", true);
    cb.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
	cbx.setEnabled(!cbx.isEnabled());
      }
    });
    add(cbx);
    add(cb, BorderLayout.SOUTH);
    setVisible(true);
  }


  public static void main(String args[]) {
    EventQueue.invokeLater(new Runnable() {
      public void run() {
	new HighlightedCheckBox();
      }
    });
  }


  class HighlightOnSelectIcon extends javax.swing.plaf.metal.MetalCheckBoxIcon {
    JCheckBox cb;

    public HighlightOnSelectIcon(JCheckBox cb) {
      this.cb= cb;
    }

    protected void drawCheck(Component c, Graphics g, int x, int y) {
      g.setColor(Color.BLACK);
      super.drawCheck(c,g,x,y);
    }

    public void paintIcon(Component c, Graphics g, int x, int y) {
//      if (cb.isSelected()) g.setColor(Color.GREEN);
//      g.fillRect(x,y,getIconWidth()-3,getIconHeight()-1);
      super.paintIcon(c,g,x,y);
    }
  }

}
This post has been answered by darrylburke on Feb 14 2012
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 13 2012
Added on Feb 13 2012
3 comments
2,327 views