【问题标题】:how to print on a JPanel / JLabel [duplicate]如何在 JPanel / JLabel 上打印 [重复]
【发布时间】:2014-05-12 04:19:06
【问题描述】:

所以我的代码在 JPanel 上垂直打印球员姓名和得分,首先是所有球员,然后是他们的所有分数。我想知道如何在他们的分数旁边一个接一个地打印。例如。

Name1 Score1
Name2 Score2
Name3 Score3
Name4 Score4

我的代码是为前 10 名球员/得分制作的,所以我在这个方法中使用了数组。我的代码是:

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

如您所见,我有 2 个面板。我设置了一个东和一个西,但没有奏效。我也向南尝试了两者。我需要帮助修复我的代码或添加其他代码,以便它与它的伴侣垂直打印。提前致谢!

【问题讨论】:

  • 不,那是在 JLabel 中打印的方法,但它像我在问题中提到的那样打印出所有水平的。我需要另一种方法来打印出来。感谢您的关心

标签: java swing jpanel jlabel arrays


【解决方案1】:

我会使用JTable

有关更多信息和工作示例,请参阅 How to Use Tables 上的 Swing 教程部分。

此外,请遵循 Java 命名约定。变量名不应以大写字符开头。

【讨论】:

  • 1+ 是的,正如我在评论 here 中推荐的那样,你应该看看 Rob。很高兴他终于回来了。
【解决方案2】:

当您想要排列标签和/或字段时,您首先想到的应该是使用GridBagLayout

您还应该使用小写字母来启动 Java 字段。这是Java Naming Conventions

这是您的代码。您需要在定义 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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-08
    相关资源
    最近更新 更多