如何将按钮添加到 JFrame Gui

How to add a button to a JFrame Gui

我正在尝试将按钮添加到框架 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();
    }
}

变化:

JButton button;
JPanel panel;

至:

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

您还可以在 JButton() 构造函数中传递一个 String 值,以便在 JButton.

上显示该字符串值

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

示例代码:

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();
    }
}

输出:

注:

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

If you can Change this Program, You can adjust the button place also

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