Search code examples
javajlabelsetbounds

How to put texts one on top of the other using JLabels?


I'm trying to make a list of texts that looks like this:

image1

I have this code:

panelPunts = new JPanel();
panelPunts.setBackground(Color.GRAY);
biggerPanel.add(panelPunts, BorderLayout.EAST);

JLabel titol = new JLabel();
titol.setText("<html><h1><u> Points</u></h1></html>");
titol.setBounds(0, 0, 200, 50);
panelPunts.add(titol);

JLabel etnia1 = new JLabel();
etnia1.setText("Team A: 20");
etnia1.setBounds(0, 20, 200, 50);
panelPunts.add(etnia1);

JLabel etnia2 = new JLabel();
etnia2.setText("Team A: 10");
etnia2.setBounds(0, 40, 200, 50);
panelPunts.add(etnia2);

However, it looks like this:

image2

I've read that the second parameter in the setBounds() method is the Y position, however it doesn't change if I make it really high. Why doesn't it show properly?


Solution

  • Try with

    JPanel panelPunts = new JPanel();
    
    panelPunts.setLayout(new GridLayout(3,1));
    

    JPanel by default uses FlowLayout and Never use setBounds(). Leave it for layout manager to set the position of the components

    For more sample code have a look at A Visual Guide to Layout Managers


    Hint: Just separate out the last two labels from the header. Add labels in another JPanel

    Sample code : (using GridBagLayout)

        JPanel panelPunts = new JPanel();
        panelPunts.setLayout(new GridBagLayout());
        panelPunts.setBackground(Color.GRAY);
    
        GridBagConstraints gc = new GridBagConstraints();
        gc.gridx = 0;
        gc.gridy = 0;
        gc.anchor = GridBagConstraints.NORTH;
        gc.insets = new Insets(5, 5, 5, 5);
    
        JLabel titol = new JLabel();
        titol.setText("<html><h1><u> Points</u></h1></html>");
        panelPunts.add(titol, gc);
    
        gc.gridy = 1;
        JLabel etnia1 = new JLabel();
        etnia1.setText("Team A: 20");
        panelPunts.add(etnia1, gc);
    
        gc.gridy = 2;
        JLabel etnia2 = new JLabel();
        etnia2.setText("Team A: 10");
        panelPunts.add(etnia2, gc);