javaswinglayout-managerjcheckboxgrouplayout

Make the checkbox on a mult-line JCheckbox align with the first line, not the center


I am running a program that adds multiple different JCheckBoxes to a GroupLayout JPanel on a JFrame and I've hit a slight problem. With the following code the program will successfully make a multi-line JCheckBox, but the checkbox vertically aligns in the center of the 4 lines and I want it to align with the first line:

    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    import java.io.*;
    import javax.swing.*; 
    import javax.swing.JCheckBox;
    import javax.swing.GroupLayout;

    public class MainClass {

    public static void main(String[] args) {
            JFrame f = new JFrame("Survey");
            JPanel p = new JPanel();

            GroupLayout layout = new GroupLayout(p);
            GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup();
            GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup();

            p.setLayout(layout);

            JCheckBox example = new JCheckBox();
            example.setText("<html><body>lorum ipsum lorum ipsum lorum ipsum lorum ipsum lorum ipsum");

            hGroup.addComponent(example, 0,150,150);
            vGroup.addComponent(example);

            layout.setHorizontalGroup(hGroup);
            layout.setVerticalGroup(vGroup); 
            f.add(p);
            f.setVisible(true);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
            f.setExtendedState(f.getExtendedState() | JFrame.MAXIMIZED_BOTH);
        }  
    }

Output:

Output

I want it to look like this (Mind my terrible image editing skills and the fact that its randomly a different shade of grey):

Desired result

As you can see I use GroupLayout, if possible I would like to retain this because I want to apply this to a much larger program and restructuring my entire layout is less than ideal. Thanks


Solution

  • Take a look at the AbstractButton API.

    There are several methods that allow you to control the location of the text relative to the icon.

    For example:

    JCheckBox example = new JCheckBox();
    example.setText("<html><body>lorum ipsum lorum ipsum lorum ipsum lorum ipsum lorum ipsum");
    example.setVerticalTextPosition(SwingConstants.TOP);