How can we set a border to JCheckBox in Java?


A JCheckBox is a component that can extend JToggleButton and an object of JCheckBox represents an option that can be checked or unchecked. If there are two or more options then any combination of these options can be selected at the same time. We can set a border to the JCheckBox component by using the setBorder() method and make sure that setBorderPainted() method set to true.

Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class BorderedJCheckBoxTest extends JFrame {
   private JCheckBox jcb;
   public BorderedJCheckBoxTest() throws Exception {
      setTitle("JCheckBox Test");
      setLayout(new FlowLayout());

      jcb = new JCheckBox("BorderedJCheckBox Test");
      jcb.setBorderPainted(true);
      jcb.setBorder(BorderFactory.createLineBorder(Color.red)); // set the border

      add(jcb);
      setSize(375, 250);
      setLocationRelativeTo(null);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
   }
   public static void main(String args[]) throws Exception {
      new BorderedJCheckBoxTest();
   }
}

Output

raja
Published on 15-Jul-2019 18:15:39
Advertisements