[英]Java GUI - Buttons not showing up in JPanel
I'm learning how to make GUIs in Java. 我正在学习如何用Java制作GUI。 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.
现在,我想做的是在JPanel中制作一个小盒子,两个按钮彼此相邻(它们之间可能有10px的填充)。 When I run this program in JGrasp I just get an empty window.
当我在JGrasp中运行该程序时,我只会得到一个空窗口。 What am I doing wrong?
我究竟做错了什么?
MyButtons.java 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 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 >.<
我所做的就是在MyButtons.Java的底部添加一行。
您还必须将pnlMain
添加到JFrame
的内容窗格或将其设置为框架的内容窗格。
Create Button's Object as given below. 创建按钮的对象,如下所示。
JButton btn1 = new JButton("Button 1");
JButton btn2 = new JButton("Button 2");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.