gpt4 book ai didi

java - JPanel 未正确显示

转载 作者:行者123 更新时间:2023-12-01 08:11:13 27 4
gpt4 key购买 nike

所以,我从基本的可视化 Java 组件开始,但很难准确地使用它们。

这是我的新问题:我正在尝试实现一个由 3 部分组成的面板:东、中、西,但无法正确显示中心面板。这是我的一段代码:

基本上“panelUpMiddle”不可见,所以我想知道为什么?...

public class TestCode_Web {


public static void main(String[] args) {

JFrame window = new JFrame("Test");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(400, 400);

JPanel innerPanel = new JPanel(new BorderLayout());
JPanel panelUp = new JPanel(new BorderLayout());

JPanel panelUpLeft = new JPanel();
JPanel panelUpMiddle = new JPanel();

window.add(innerPanel, BorderLayout.NORTH);
innerPanel.add(panelUp, BorderLayout.NORTH);

panelUp.add(panelUpLeft, BorderLayout.WEST);
panelUp.add(panelUpMiddle, BorderLayout.CENTER);

JLabel label1 = new JLabel("Label 1");

JLabel label11 = new JLabel("Label 11");
JLabel label12 = new JLabel("Label 12");

panelUp.add(label1);
panelUpLeft.add(label11);
panelUpMiddle.add(label12);

panelUp.setBackground(new Color(200, 240, 200));

panelUpLeft.setBackground(new Color(200, 240, 0));
panelUpMiddle.setBackground(new Color(100, 240, 200));

panelUp.setPreferredSize(new Dimension(window.getWidth(), 160));
panelUpLeft.setPreferredSize(new Dimension(160, 120));

window.setVisible(true);
}

}

最佳答案

试试这个代码。我更新了面板和标签的命名,使其更加清晰。

    JFrame window = new JFrame("Test");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(400, 400);

JPanel centerPanel = new JPanel(new BorderLayout());
JPanel eastPanel = new JPanel(new BorderLayout());
JPanel westPanel = new JPanel(new BorderLayout());

window.add(centerPanel, BorderLayout.CENTER);
window.add(eastPanel, BorderLayout.EAST);
window.add(westPanel, BorderLayout.WEST);

JLabel centerLabel = new JLabel("Center");
JLabel eastLabel = new JLabel("East");
JLabel westLabel = new JLabel("West");

eastPanel.add(eastLabel);
westPanel.add(westLabel);
centerPanel.add(centerLabel);

centerPanel.setPreferredSize(new Dimension(200, 400));
eastPanel.setPreferredSize(new Dimension(100, 400));
westPanel.setPreferredSize(new Dimension(100, 400));
eastPanel.setBackground(new Color(200, 240, 200));
westPanel.setBackground(new Color(200, 240, 0));

window.setVisible(true);

关于java - JPanel 未正确显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17164728/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com