【问题标题】:Panel and button are added in the frame but not appearing in the frame面板和按钮已添加到框架中但未出现在框架中
【发布时间】:2019-11-14 16:29:21
【问题描述】:

面板和按钮已添加到框架中,但未出现在框架输出中。

import javax.swing.*;
import java.awt.*;
public class frameeg
{

    public static void main(String s[])
    {
        JFrame frame = new JFrame("Frame eq");
        JPanel panel = new JPanel();               //panel not working
        panel.setLayout(new FlowLayout());
        JLabel label = new JLabel("JFrame by example");
        JButton button = new JButton();
        button.setText("Button");
        panel.add(label);
        panel.add(button);
        frame.add(panel);
        frame.setLayout(null);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(200,300);
    }
}

【问题讨论】:

  • 只有两个建议,无需测试代码... frame.setLayout(null);可能是原因? frame.Show() 或类似的没有被调用。
  • 欢迎来到 StackOverflow!为了清晰和简洁,我编辑了标题,并格式化了代码。粘贴代码时,将其粘贴进去,选择它,然后单击{} 小部件以将其呈现为代码。这将其向右移动了 4 个空格。避免在所有代码的左侧出现过多的缩进。
  • @Alex75,你不应该使用 show() 方法。阅读 API 以获取更多信息。该代码使用 setVisible(true) 方法,这是正确使用的方法。但是,您关于 null 布局的观点是正确的。

标签: java swing jframe jpanel jbutton


【解决方案1】:

您决定使用null-layout,这要求您指定内部所有元素的边界(setBounds(...)),否则它将显示为width = 0height = 0

但是你不应该使用null-layout,作为it's evil,当你在不同的PLAFs/屏幕尺寸/分辨率/等下运行你的程序时,会导致一些有趣/奇怪/难以解决的问题,例如this one

为此,我建议您删除此行:

frame.setLayout(null);

替换这一行:

frame.setSize(200,300);

对于这个:

frame.pack();

并将这一行移到main 方法的最后:

frame.setVisible(true);

并且不要忘记将您的程序放在 EDT 上(如链接答案所示)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多