Search code examples
javaswingjpaneljlabellayout-manager

Set label layout in panels


in my Frame, i'm adding labels thanks to a for, in a panel. the problem i can't solve is that it is adding the label on the same line whereas i want to add a \n between one and another so to generate a column! I've no idea how to do it. any help? Thank you!


Solution

  • The key I believe will be the layout of the container that is holding the JLabels. If you give that container the proper layout such as a BoxLayout oriented along the PAGE_AXIS, or a GridLayout(0, 1) for one column with variable number of rows, then the JLabels will stack one on top of the other.

    e.g.,

    import java.awt.GridLayout;
    import javax.swing.*;
    
    public class StackingLabels extends JPanel {
        public static final String[] TEXTS = { "Sunday", "Monday", "Tuesday",
                "Wednesday", "Thursday", "Friday", "Saturday" };
    
        public StackingLabels() {
            setLayout(new GridLayout(0, 1));
            for (String text : TEXTS) {
                add(new JLabel(text));
            }
        }
    
        private static void createAndShowGui() {
            StackingLabels mainPanel = new StackingLabels();
    
            JFrame frame = new JFrame("StackingLabels");
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.getContentPane().add(mainPanel);
            frame.pack();
            frame.setLocationByPlatform(true);
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGui();
                }
            });
        }
    }
    

    Another thought is to use a JList to display the Strings rather than stacked JLabels.