java - 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 >.<
解决方案
您还必须将 添加pnlMain
到JFrame
的内容窗格或将其设置为框架的内容窗格。
推荐阅读
- python - 如何使用python替换excel中单元格中的多个值?
- ios - 无法在 Xcode 中打印到控制台
- machine-learning - 每个神经元中具有线性激活函数的浅层多层网络的输出在权重上是线性的 -> FALSE?
- bash - 带有“and”运算符的“If”语句 - 白天
- php - Laravel / MySQL 错误:SQLSTATE[HY000]:一般错误:1835 格式错误的通信数据包
- html - 面包屑中的链接变得更大
- python - 创建汽车对象会产生 TypeError Python
- c# - Azure 表泛型 - ExecuteQuery 不支持操作
- ios - 关于指南 1.3 - 安全 - 儿童类别应用拒绝
- c# - 捕获 System.ComponentModel.Win32Exception