Question

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?

Was it helpful?

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);

OTHER TIPS

Please do not use the NullLayoutbut any other LayoutManager (consider using the GridLayout). The FlowLayout which is standard layout when initializing a JPanel and which you are using is not suitable for this task. Also your setBounds method calls are only relevant when using NullLayout... which you should not. Also you could implement this with a JList and not multiple JLabels. Please consider changing your code with this information and if there a questions left update your answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top