Java GUI LogiC语言 不理解添加到 JFrame



我有一个非常简单的问题。可以请向我解释为什么以下 JFrame 没有显示 Hello(屏幕左侧的 100,100 像素和屏幕右侧的世界(100,100 像素(,因为我使用的是边框布局。

  • 我创建了一个 JFrame
  • 为其分配了边框布局的布局
  • 创建了 2 个
  • 带有 2 个标签的面板,并分配了要左右对齐的面板。
  • 将面板添加到 JFrame
  • 显示 JFrame

我错过了什么?

JFrame frame = new JFrame("FrameDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 500);
frame.setLayout(new BorderLayout());
frame.setVisible(true);
JPanel panel1 = new JPanel();
panel1.setPreferredSize(new Dimension(100,100));
panel1.setBackground(Color.BLUE);
JLabel label1 = new JLabel("Hello");
label1.setBackground(Color.YELLOW); 
label1.setForeground(Color.WHITE);
panel1.add(label1,BorderLayout.LINE_START);
frame.add(panel1);
JPanel panel2 = new JPanel();
panel2.setPreferredSize(new Dimension(100,100));
panel2.setBackground(Color.RED);
JLabel label2 = new JLabel("World");
label2.setBackground(Color.CYAN);
label2.setForeground(Color.WHITE);
panel2.add(label2,BorderLayout.LINE_END);
frame.add(panel2);

您在错误的面板上设置了布局约束。

而不是panel2.add(label2,BorderLayout.LINE_END);它应该是panel2.add(label2)的,而不是frame.add(panel2);它应该是frame.add(panel2, BorderLayout.LINE_END);

.panel1也一样。

最新更新