简体   繁体   English

添加了JButton但在运行时未显示

[英]JButton added but not showing up at runtime

I'm using a book to learn java. 我正在用书来学习Java。 I'm have made a Swing window but when I try to make JButtons, they are not visible at runtime. 我已经创建了一个Swing窗口,但是当我尝试创建JButton时,它们在运行时不可见。 I've copied the code exactly as it is, but it is still not visible. 我已经完全复制了代码,但是仍然看不到。 Here is the code: 这是代码:

import javax.swing.*;
class Buttons extends JFrame
{
    JPanel pnl = new JPanel();
    public Buttons()
    {
        super("Swing Window");
        setSize(500,200);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        add(pnl);
        setVisible(true);
        pnl.add(new JButton("Click Me"));
    }
    public static void main(String[] args)
    {
        Window gui = new Window();
    }
}

Change: 更改:

    setVisible(true);
    pnl.add(new JButton("Click Me"));

To: 至:

    pnl.add(new JButton("Click Me"));
    pack(); // very important!
    setVisible(true); // should be last!

Change Window to Buttons and it works fine!!! 将窗口更改为按钮,它可以正常工作!!!

import javax.swing.*;    

class Buttons extends JFrame
{
JPanel pnl = new JPanel();
public Buttons()
 {
    super("Swing Window");
    setSize(500,200);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    add(pnl);
    setVisible(true);
    pnl.add(new JButton("Click Me"));
}
public static void main(String[] args)
{
    Buttons gui = new Buttons();
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM