如何向JFrame Gui添加按钮

时间:2015-07-06 12:00:58

标签: java swing button jframe

我试图在框架gui上添加一个按钮 我尝试制作一个面板并将其添加到该面板,但它不起作用。 请帮忙!

这是我的代码:

import javax.swing.*;

public class Agui extends JFrame {
    public Agui() {
        setTitle("My Gui");
        setSize(400, 400);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        JButton button;
        JPanel panel;

        // my error lines are under the "panel" and  "button"
        // it says i must implement the variables. what does that mean???
        panel.add(button);
    }
    public static void main(String[] args) {
        Agui a = new Agui();
    }
}

3 个答案:

答案 0 :(得分:4)

变化:

JButton button;
JPanel panel;

为:

JButton button = new JButton();
JPanel panel = new JPanel();

您还可以在String构造函数中传递JButton()值,以便在JButton上显示该字符串值。

示例: JButton button = new JButton("I am a JButton");

答案 1 :(得分:1)

示例代码:

import javax.swing.*;

public class Agui extends JFrame {

    public Agui() {

        setTitle("My Gui");
        setSize(400, 400);

        // Create JButton and JPanel
        JButton button = new JButton("Click here!");
        JPanel panel = new JPanel();

        // Add button to JPanel
        panel.add(button);
        // And JPanel needs to be added to the JFrame itself!
        this.getContentPane().add(panel);

        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {

        Agui a = new Agui();
    }
}

<强>输出:

Image

注意:

  • 使用new JButton("...");new JPanel()
  • 创建JButton和JPanel
  • 使用getContentPane().add(...);
  • 将JPanel添加到JFrame的内容窗格中

答案 2 :(得分:0)

  

如果可以更改此程序,还可以调整按钮位置

import java.awt.*;

import javax.swing.*;

import java.awt.event.*;



public class agui extends JFrame

{

agui()
{
    setTitle("My GUI");
    setSize(400,400);
    setLayout(null);

    JButton button = new JButton("Click Here..!");
    button.setBounds(50,100,100,50); /*Distance from left,           
                      Distance from top,length of button, height of button*/
    add(button);

    setVisible(true);

}

public static void main(String[] args)
{

     JFrame agui = new agui();



}

}

Output