首页 > 解决方案 > 通过按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 时它没有出现,我应该如何修复它?

标签: java

解决方案


简单地添加组件是不够的 - 您必须告诉窗口工具包重新绘制框架。尝试使用这样的东西:

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


推荐阅读