java - 我怎样才能创建一个 JButton?

标签 java jbutton

在创建 JButton 并将其设置为 Visible 之后,我不明白为什么我在窗口中看不到它。:/

import java.awt.Color;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Window extends JFrame{

    public static int width = 350;
    public static int height  = 480;

    public static void main (String args[]) {
        JFrame window = new JFrame();
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setSize(width, height);
        window.setVisible(true);
        window.setTitle("Virtual World");
        window.setLocationRelativeTo(null);
        window.setResizable(false);
        window.getContentPane().setBackground(new Color(80,80,240));

        JButton enter = new JButton();
        enter.setVisible(true);


    }

}       

最佳答案

正如@Tunaki 在评论中已经提到的,您需要先将 JButton 添加到面板。

试试这个

public class Test extends JFrame{

    public static int width = 350;
    public static int height  = 480;

    public static void main (String args[]) {
        JFrame window = new JFrame();
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setSize(width, height);

        window.setTitle("Virtual World");
        window.setLocationRelativeTo(null);
        window.setResizable(false);
        window.getContentPane().setBackground(new Color(80,80,240));

        JButton enter = new JButton("Ok");
        enter.setVisible(true);
        JPanel panel = new JPanel();
        window.add(panel);
        panel.add(enter);
        window.setVisible(true);

    }

}       

您需要在您的JFrame中添加一个JPanel。然后您可以将您的JButton添加到JPanel .

关于java - 我怎样才能创建一个 JButton?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33742116/

相关文章:

java - 其他类中的 JButton 操作

java - 在处理事件后保持 Java ActionListener 运行?

java - 非 Activity View 中的警报对话框

java - join 和 CountDownLatch 有什么区别?

Java SMPP 客户端实现

java - 从 ActionListener 内部的 JOptionPane 初始化字符串

java - 如何通过点击JButton 添加JPanel?

java - 单击按钮修改表

java - 如何使用 Lombok ?

java - 如何加快java.net.ServerSocket和java.net.Socket效率?