java - 通过按JButton问题将JButton添加到JPanel
问题描述
我正在创建一个用于练习的餐桌预订程序。我遇到了下一个问题:当我单击“创建新表”按钮时,应该在 centerPanel 上添加一个按钮,但它没有出现在那里。
这是代码
import javax.swing.*;
import java.awt.event.*;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
public class CreateNewFloorV2 extends JFrame implements ActionListener{
JFrame frame=new JFrame("Create new table");
BorderLayout borderLayout=new BorderLayout();
JPanel centerPanel=new JPanel();
SpringLayout centerPanelLayout=new SpringLayout();
JPanel bottomPanel=new JPanel();
GridLayout bottomPanelLayout=new GridLayout(1,2);
JButton btn1=new JButton("Create new table");
JButton btn2=new JButton("Delete table");
//Constructor
public CreateNewFloorV2() {
frame.setSize(600, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
//Create layout
frame.setLayout(borderLayout);
frame.getContentPane().add(centerPanel, BorderLayout.CENTER);
centerPanel.setLayout(centerPanelLayout);
frame.getContentPane().add(bottomPanel, BorderLayout.SOUTH);
bottomPanel.setLayout(bottomPanelLayout);
bottomPanel.add(btn1);
bottomPanel.add(btn2);
btn1.addActionListener(this);
btn2.addActionListener(this);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
//ActionListener
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btn1) {
JButton newTable=new JButton("Table X");
centerPanel.add(newTable);
}
}
public static void main(String[] args) {
CreateNewFloorV2 newFloor=new CreateNewFloorV2();
}
}
我试过把
JButton newTable=new JButton("Table X");
centerPanel.add(newTable);
进入构造函数 CreateNewFloorV2() 然后它确实出现了。但是我不知道为什么当我点击按钮 btn1 时它没有出现,我应该如何修复它?
解决方案
简单地添加组件是不够的 - 您必须告诉窗口工具包重新绘制框架。尝试使用这样的东西:
if(e.getSource()==btn1) {
JButton newTable=new JButton("Table X");
centerPanel.add(newTable);
centerPanel.invalidate();
centerPanel.repaint();
}
另请参阅https://www.oracle.com/technetwork/java/painting-140037.html
推荐阅读
- javascript - 通过 $Emit 更新子组件和父组件数据
- python - 在列表python中查找最小和最大元素的最后一个索引
- android - FMX [Android] 使多个标签加粗
- python - 在python中循环可选参数(字符串)
- ansible - 使用 Ansible 从开始值和结束值生成 IP 地址列表
- python - 加载 conda 时出错....请给出一些想法
- sql - 从采购表和销售表中计算按几列分组的库存
- date - VBscript - 多行 IF 语句产生错误
- java - 执行任务直到 Java 中没有异常
- reactjs - 我正在尝试解决 React 语法错误,但没有任何效果