首页 > 解决方案 > Java GUI - Buttons not showing up in JPanel

问题描述

I'm learning how to make GUIs in Java. Right now what I'm trying to do is make a small box with 2 buttons next to each other (with maybe.. 10px of padding between them) inside a JPanel. When I run this program in JGrasp I just get an empty window. What am I doing wrong?

MyButtons.java

import javax.swing.*;
import java.awt.*;
public class MyButtons extends JFrame{
    public MyButtons(){
        JPanel pnlMain = new JPanel();
        this.setTitle("MyButtons");
        JButton btn1 = new JButton("Button 1");
        JButton  btn2 = new JButton("Button 2");
        pnlMain.add(btn1);
        pnlMain.add(btn2);
        this.add(pnlMain);
    }
}

TestMyButtons.java

import javax.swing.*;   // for JFrame, JPanel, JLabel, JTextField, 
import java.awt.*;      // for BorderLayout
public class TestMyButtons {
    public static void main(String[] args) {    
        MyButtons test = new MyButtons();
        test.setVisible(true);
        test.setSize(1000,300);
        test.setLocation(200,300);
        test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

EDIT: Revised to show the correct code. Answer marked below. All I did was add one line to the bottom of MyButtons.Java >.<

标签: javaswingjframejpanel

解决方案


您还必须将 添加pnlMainJFrame的内容窗格或将其设置为框架的内容窗格。


推荐阅读