Search code examples
javaswingjcheckboxtext-alignment

Align text and checkbox of a JCheckBox on opposite sides of parent


Is there a simple way to align just the checkbox of a JCheckBox to the right without creating a separate label and check box component? I am aware of setHorizontalTextPosition(SwingConstants.LEADING); This only results in the box being on the right side of the text, but not right aligned.

What I want:

| Some sample text                                          ☑ |

instead of

| Some sample text ☑                                          |

Thanks in advance!


Solution

  • You can separate the label and checkbox in a suitable layout. I've made the enclosing frame wider by an arbitrary factor to show the effect.

    Addendum: As noted here, "clicking the label doesn't check the box." A suitable MouseListener can toggle the check box in response to a mouse press anywhere in the enclosing panel.

    image

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.EventQueue;
    import java.awt.GridLayout;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.BorderFactory;
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    
    /**
     * @see https://stackoverflow.com/a/36369035/230513
     * @see http://stackoverflow.com/a/2933256/230513
     */
    public class Test {
    
        public static void main(String args[]) {
            EventQueue.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    JFrame frame = new JFrame();
                    frame.setLayout(new GridLayout(0, 1));
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(createPanel("Some label"));
                    frame.add(createPanel("Another label"));
                    frame.add(createPanel("Yet another label"));
                    frame.pack();
                    frame.setSize(frame.getWidth() * 2, frame.getHeight());
                    frame.setLocationByPlatform(true);
                    frame.setVisible(true);
                }
    
                private JPanel createPanel(String s) {
                    JPanel panel = new JPanel(new BorderLayout());
                    JCheckBox check = new JCheckBox();
                    panel.addMouseListener(new MouseAdapter() {
                        @Override
                        public void mousePressed(MouseEvent e) {
                            check.setSelected(!check.isSelected());
                        }
                    });
                    panel.add(new JLabel(s, JLabel.LEFT), BorderLayout.WEST);
                    panel.add(check, BorderLayout.EAST);
                    panel.setBorder(BorderFactory.createLineBorder(Color.blue));
                    return panel;
                }
            });
        }
    }