【问题标题】:The JLabel not showing in my code [closed]JLabel 未显示在我的代码中[关闭]
【发布时间】:2026-01-15 10:00:01
【问题描述】:

如何显示jlabel文本

JFrame frame = new JFrame("number adition");
JButton button1  = new JButton("add");

button1.setBounds(110, 250, 70, 20);
frame.add(button1);

frame.setSize(500, 400);
frame.setLayout(null);
frame.setVisible(true);

JButton button2  = new JButton("Clear");

button2.setBounds(210, 250, 70, 20);
frame.add(button2);

JButton button3  = new JButton("Exit");

button3.setBounds(210, 280, 70, 20);
frame.add(button3);

JLabel label1= new JLabel("First", JLabel.NORTH_EAST);
label1.setAlignmentX(0);
label1.setAlignmentY(0);
frame.add(label1);

【问题讨论】:

  • 与所有与此主题相关的问题一样,应在建立 UI 后最后调用 frame.setVisible(true);。否则你需要调用revalidaterepaint,但是由于你已经扔掉了布局管理器,revalidate将不起作用
  • 避免使用null 布局,像素完美的布局是现代用户界面设计中的一种错觉。影响组件单个尺寸的因素太多,您无法控制。 Swing 旨在与核心布局管理器一起工作,丢弃这些将导致无穷无尽的问题和问题,您将花费越来越多的时间来尝试纠正

标签: java eclipse swing jlabel


【解决方案1】:

在空布局中,每个组件都需要调整大小。因为你没有设置标签的边界,所以它没有显示。

顺便说一句,使用空布局是一种非常糟糕的做法。我建议您学习如何使用布局管理器并为您的情况选择最合适的一种。 Using Layout Managers

【讨论】: