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