0

我的代码有什么问题?我的按钮和标签没有出现。

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class HelloPanelLabel extends JFrame {

    public static void main(String[] args) {
        new HelloPanelLabel(); // creates an instance of frame class
    }

    public HelloPanelLabel() {

        this.setSize(200, 100);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setTitle("Hello World!");
        this.setVisible(true);

        Toolkit tk=Toolkit.getDefaultToolkit();
        Dimension d= tk.getScreenSize();
        int x=(d.height/2);
        int y=(d.width/2);
        this.setLocation(x, y);
        //JPanel panel1 = new JPanel();
        JLabel label1 = new JLabel("hello, world");
        //panel1.add(label1);
        JButton button1 = new JButton("Click me!");
        //panel1.add(button1);
        this.setVisible(true);

    }

}
4

3 回答 3

1

没有显示JButtonand的原因JLabel是你没有添加JPanel包含这两个组件的JFrame. 你只需要在你的代码中做一点修改。这是:

panel1.add(label1);
JButton button1 = new JButton("Click me!");
panel1.add(button1);
getContentPane().add(panel1);//Add to ContentPane of JFrame
this.setVisible(true);

并删除程序中的前this.setVisible(true)一行。

于 2013-06-14T13:42:44.407 回答
1

您需要设置布局并将组件添加到框架中。

setLayout(new FlowLayout());
//JPanel panel1 = new JPanel();
JLabel label1 = new JLabel("hello, world");
add(label1);
//panel1.add(label1);
JButton button1 = new JButton("Click me!");
add(button1);
//panel1.add(button1);
 this.setVisible(true);

如评论所述,您必须致电pack(). 但是,如果要定义更复杂的布局,则必须创建更复杂的布局。

于 2013-06-14T13:28:26.723 回答
0

如果你想JPanel为你的组件使用

public class HelloPanelLabel extends JFrame {

    public static void main(String[] args) {
        new HelloPanelLabel().setVisible(true);
    }

    public HelloPanelLabel() {
        //The same as setTitle.
        super("Hello World!");

        JPanel panel1 = new JPanel();
        JLabel label1 = new JLabel("hello, world");
        panel1.add(label1);
        JButton button1 = new JButton("Click me!");
        panel1.add(button1);
        add(panel1);
        //Size the frame to fit the components
        pack();

        //Center the frame.
        setLocationRelativeTo(null);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    }
}

或者,您可以将它们直接添加contentPaneJFrame.

    setLayout(new FlowLayout());

    JLabel label1 = new JLabel("hello, world");
    add(label1);
    JButton button1 = new JButton("Click me!");
    add(button1);

    Toolkit theKit = getToolkit();
    Dimension wndSize = theKit.getScreenSize();

    setSize(wndSize.width / 8, wndSize.height / 12);

    setLocationRelativeTo(null);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
于 2013-06-14T13:53:16.597 回答