Search code examples
javaswinglayoutlayout-managerjcheckbox

How to make two checkboxes sit next to each other in Swing?


I have two JCheckBox's and one JEditorPane. I am looking for an output as under

enter image description here

But my current code is somewhat messy for which I am not able to

private void createContents()
  {    
    JEditorPane  license;
    JCheckBox confirmBox;
    JCheckBox declineBox;   

    license = new JEditorPane("text/html", "");
    license.setText (buildEulaText());
    license.setEditable(false);   
    confirmBox = new JCheckBox("I accept.", false); 
    declineBox = new JCheckBox("I decline.", false); 
    add(license, BorderLayout.CENTER);
    add(confirmBox, BorderLayout.SOUTH); 
    add(declineBox, BorderLayout.NORTH);   //I know this is wrong 
  } 

Solution

  • A simple solution is to compose the layouts using a new JPanel with a FlowLayout.

    add(license, BorderLayout.CENTER);
    JPanel boxes = new JPanel(new FlowLayout());
    // FlowLayout is the JPanel default layout manager, so
    // boxes = new JPanel(); works too :)
    boxes.add(confirmBox);
    boxes.add(declineBox);
    add(boxes, BorderLayout.SOUTH);
    

    But you can also take a look at the GridBagLayout.