MyCheckBoxUI.java Source code

Java tutorial

Introduction

Here is the source code for MyCheckBoxUI.java

Source

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.AbstractButton;
import javax.swing.ButtonModel;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicCheckBoxUI;

public class MyCheckBoxUI extends BasicCheckBoxUI implements java.io.Serializable, MouseListener {

    private final static MyCheckBoxUI buttonUI = new MyCheckBoxUI();

    public MyCheckBoxUI() {
    }

    public static ComponentUI createUI(JComponent c) {
        return buttonUI;
    }

    public void installUI(JComponent c) {
        super.installUI(c);
        c.setBackground(Color.red);
        c.addMouseListener(this);
    }

    public void uninstallUI(JComponent c) {
        super.uninstallUI(c);
        c.removeMouseListener(this);
    }

    public void paint(Graphics g, JComponent c) {
        AbstractButton b = (AbstractButton) c;
        ButtonModel model = b.getModel();
        Dimension d = b.getSize();

        g.setFont(c.getFont());
        FontMetrics fm = g.getFontMetrics();
        g.setColor(Color.white);
        g.drawString("Am I a check box", 10, 10);

    }

    public void mouseClicked(MouseEvent e) {
    }

    public void mousePressed(MouseEvent e) {
    }

    public void mouseReleased(MouseEvent e) {
    }

    public void mouseEntered(MouseEvent e) {
        JComponent c = (JComponent) e.getComponent();
        c.setBackground(Color.blue);
        c.repaint();
    }

    public void mouseExited(MouseEvent e) {
        JComponent c = (JComponent) e.getComponent();
        c.setBackground(Color.red);
        c.repaint();
    }

    public static void main(String[] argv) {
        JFrame f = new JFrame();
        f.setSize(400, 300);
        f.getContentPane().setLayout(new FlowLayout());

        JPanel p = new JPanel();
        JCheckBox bt1 = new JCheckBox("Click Me");
        bt1.setUI(new MyCheckBoxUI());
        p.add(bt1);
        f.getContentPane().add(p);
        WindowListener wndCloser = new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        };
        f.addWindowListener(wndCloser);
        f.setVisible(true);
    }

}