Domanda

I need to align the checkboxes in my GUI, but I'm having trouble finding the right command or method. I have written a short example that is simpler to read:

public class GUI {

JFrame window = new JFrame();
JPanel mainPanel = new JPanel();
JPanel[] rowPanel = new JPanel[5];
JCheckBox[] check = new JCheckBox[5];

public GUI () { 
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setExtendedState(window.MAXIMIZED_BOTH);
        window.setVisible(true);
        window.add(mainPanel);
        mainPanel.setLayout(new GridLayout(5, 1));

        for(int i = 0; i < 5; i++) 
        {
        rowPanel[i] = new JPanel();
        mainPanel.add(rowPanel[i]);
        }

        check[0] = new JCheckBox("red");
        check[1] = new JCheckBox("violet");
        check[2] = new JCheckBox("pink");
        check[3] = new JCheckBox("magenta");
        check[4] = new JCheckBox("every color");

        for(int i = 0; i < 5; i++) 
        {
            rowPanel[i].add(check[i]);
        }   
    }
}

I have tried .setHorizontalTextPosition() and .setHorizontalAlignment(), but neither have worked. I want all of the boxes to be aligned vertically on the right side of their labels.

È stato utile?

Soluzione

Stop adding all of those panels. Use one panel, and add the check boxes to that panel, and set the alignment on that panel. I have modified your GUI constructor.

public GUI() {

    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setExtendedState(window.MAXIMIZED_BOTH);
    window.setVisible(true);
    window.add(mainPanel);
    mainPanel.setLayout(new GridLayout(5, 1));
    mainPanel.setAlignmentY(JComponent.LEFT_ALIGNMENT);

    check[0] = new JCheckBox("red");
    check[1] = new JCheckBox("violet");
    check[2] = new JCheckBox("pink");
    check[3] = new JCheckBox("magenta");
    check[4] = new JCheckBox("every color");

    for (int i = 0; i < 5; i++) {
        mainPanel.add(check[i]);
    }

}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top