Frage

So my code prints players names and scores all vertically on the JPanel, all the players first, then all their scores. I want to know how to print one after another alongside their scores. For Example.

Name1 Score1
Name2 Score2
Name3 Score3
Name4 Score4

My code is made for top 10 players/scores so i use arrays for this method. My code is :

for (int x = 0; x < 10; x++)
         {
            JSingleplayer[x] = new JLabel (Singleplayer[x]);
            EndPanelplayer.add(JSingleplayer[x],BorderLayout.EAST);
            JSingleScore[x] = new JLabel (SingleScore[x]);
            EndPanelscore.add(JSingleScore[x],BorderLayout.WEST);
         }
            EndFrame.add(EndPanelplayer);
            EndFrame.add(EndPanelscore);

As you can see, i have 2 panels. I set one east and one west but that did not work. I also tried south for both. I need help fixing my code or adding additional code in order for it to print vertically with its mate. Thanks in advance!

War es hilfreich?

Lösung

I would use a JTable.

See the section from the Swing tutorial on How to Use Tables for more information and working examples.

Also, follow Java naming conventions. Variable names should NOT start with an upper case character.

Andere Tipps

Whenever you want to line up labels and or fields, your immediate first thought should be to use the GridBagLayout.

You should also use lower case to start a Java field. Here are the Java Naming Conventions.

And here's your code. You'll need to set the layout when you define the JPanel.

private static final Insets bottomInsets    = 
        new Insets(0, 0, 6, 0);

private void addLabels() {
    int gridy = 0;

    for (int x = 0; x < 10; x++) {
        jSingleplayer[x] = new JLabel(singleplayer[x]);
        addComponent(mainPanel, jSingleScore[x], 0, gridy, 1, 1,
                bottomInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.NONE);

        jSingleScore[x] = new JLabel(singleScore[x]);
        addComponent(mainPanel, jSingleScore[x], 1, gridy++, 1, 1,
                bottomInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.NONE);
    }
}

private void addComponent(Container container, Component component,
        int gridx, int gridy, int gridwidth, int gridheight, 
        Insets insets, int anchor, int fill) {
    GridBagConstraints gbc = new GridBagConstraints(gridx, gridy,
            gridwidth, gridheight, 1.0D, 1.0D, anchor, fill, 
            insets, 0, 0);
    container.add(component, gbc);
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top