有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java通过按JButton问题向JPanel添加JButton

我正在创建一个为练习预定桌子的程序。我遇到了下一个问题:当我单击“创建新表”按钮时,应该在中心面板上添加一个按钮,但它没有出现在那里

这是密码

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时它不会出现,我应该如何修复它


共 (1) 个答案

  1. # 1 楼答案

    仅仅添加组件是不够的——你必须告诉窗口工具包重新绘制框架。尝试使用类似以下内容:

    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