Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Titled border with the title as a JCheckBox

Tags:

java

swing

I want to create a titled border with the title as a CheckBox.

this is a kind of border i am looking for

How do i do that?

like image 960
Kaushik Balasubramanain Avatar asked Nov 10 '11 08:11

Kaushik Balasubramanain


2 Answers

This tutorial is exactly what you need: CLICK

Unfortunately the images are no longer online, but you can launch the Webstart application.

like image 74
Stephan Avatar answered Nov 05 '22 15:11

Stephan


Credit to JavaLobby and Stephan for the basis of this answer.

However, this is a cut-down example that provides a simple implementation of a TitledBorder with a JCheckBox:

public class CheckBoxTitledBorder extends AbstractBorder {

  private final TitledBorder _parent;
  private final JCheckBox _checkBox;

  public CheckBoxTitledBorder(String title, boolean selected) {
    _parent = BorderFactory.createTitledBorder(title);
    _checkBox = new JCheckBox(title, selected);
    _checkBox.setHorizontalTextPosition(SwingConstants.LEFT);
  }

  public boolean isSelected() {
    return _checkBox.isSelected();
  }

  public void addActionListener(ActionListener listener) {
    _checkBox.addActionListener(listener);
  }

  @Override
  public boolean isBorderOpaque() {
    return true;
  }

  @Override
  public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
    Insets borderInsets = _parent.getBorderInsets(c);
    Insets insets = getBorderInsets(c);
    int temp = (insets.top - borderInsets.top) / 2;
    _parent.paintBorder(c, g, x, y + temp, width, height - temp);
    Dimension size = _checkBox.getPreferredSize();
    final Rectangle rectangle = new Rectangle(5, 0, size.width, size.height);

    final Container container = (Container) c;
    container.addMouseListener(new MouseAdapter() {
      private void dispatchEvent(MouseEvent me) {
        if (rectangle.contains(me.getX(), me.getY())) {
          Point pt = me.getPoint();
          pt.translate(-5, 0);
          _checkBox.setBounds(rectangle);
          _checkBox.dispatchEvent(new MouseEvent(_checkBox, me.getID(),
            me.getWhen(), me.getModifiers(), pt.x, pt.y, me.getClickCount(), me.isPopupTrigger(), me.getButton()));
          if (!_checkBox.isValid()) {
            container.repaint();
          }
        }
      }

      public void mousePressed(MouseEvent me) {
        dispatchEvent(me);
      }

      public void mouseReleased(MouseEvent me) {
        dispatchEvent(me);
      }
    });
    SwingUtilities.paintComponent(g, _checkBox, container, rectangle);
  }

  @Override
  public Insets getBorderInsets(Component c) {
    Insets insets = _parent.getBorderInsets(c);
    insets.top = Math.max(insets.top, _checkBox.getPreferredSize().height);
    return insets;
  }
}
like image 24
amaidment Avatar answered Nov 05 '22 15:11

amaidment