0

I want to create a button with checkbox in the right side of it. i tried this but checkbox stays on the center of button on the top of button label text.

Any ideas welkom.

thanks in advance:

public class MainTest extends JPanel {
    JButton button;
    JPanel panel;
    public MainTest() {
        createComponents();
        layoutComponents();
    }

    public void createComponents() {
        // attempting to add checkbox to button
        button = new JButton("Print with Edge");
        JCheckBox checkBox = new JCheckBox();
        jcb.setHorizontalAlignment(SwingConstants.RIGHT);
        button.add(checkBox,new BorderLayout());
        panel = new JPanel(new BorderLayout());
    }

    public void layoutComponents() {
        panel.add(button,BorderLayout.SOUTH);
        add(panel);
    }

    public static void main(String[] args) {
        MainTest demo = new MainTest();
        JFrame frame = new JFrame();
        Container cp = frame.getContentPane();
        cp.add(demo);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 500);
        frame.setLocation(500, 500);
        frame.setVisible(true);
    }
} 
michdraft
  • 556
  • 3
  • 11
  • 31

2 Answers2

2

You can wrap a JCheckBox inside a JPanel and make the JPanel look like a button. For example:

enter image description here

public class Test {

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setSize(new Dimension(100, 100));

    JCheckBox button = new JCheckBox();

    final JPanel buttonWrapper = new JPanel();
    buttonWrapper.add(new JLabel("Button Text"));
    buttonWrapper.add(button);
    buttonWrapper.setBorder(BorderFactory.createRaisedBevelBorder());
    buttonWrapper.addMouseListener(new MouseAdapter() {

        @Override
        public void mousePressed(MouseEvent me) {
            buttonWrapper.setBorder(BorderFactory.createEtchedBorder());
        }



        @Override
        public void mouseReleased(MouseEvent me) {
            buttonWrapper.setBorder(BorderFactory.createRaisedBevelBorder());
        }



        @Override
        public void mouseClicked(MouseEvent me) {
            System.out.println("mouse clicked");
        }
    });

    JPanel mainPanel = new JPanel();
    mainPanel.add(buttonWrapper);

    frame.getContentPane().add(mainPanel);
    frame.setVisible(true);
}

}

martinez314
  • 12,162
  • 5
  • 36
  • 63
1

I want to create a button with checkbox in the right side of it.

Maybe you just want the checkbox on the right side of the text?

If so you can do:

JCheckBox cb = new JCheckBox("Print with Edge");
cb.setHorizontalTextPosition(SwingConstants.LEADING);
camickr
  • 321,443
  • 19
  • 166
  • 288