java - 当另一个 JButton 被按下时添加一个 JButton

标签 java swing button jbutton actionlistener

我有一个 JButton,我想在按下它时创建一个新的 JButton,我添加了一个如下所示的 ActionListener,但它没有添加另一个 JButton。

public void actionPerformed(ActionEvent e){
        Object command = e.getSource();
        if(command.equals(play)){
            ImageIcon i1 = new ImageIcon("NewGame.png");
            width = i1.getIconWidth();
            height = i1.getIconWidth();
            newGame = new JButton(i1);
            newGame.setBorderPainted(false);
            newGame.setContentAreaFilled(false);
            newGame.setSize(width, height);
            newGame.setLocation(600,100);
            add(newGame);
            System.out.println("It Works");
        } 
    } 

我该如何做到这一点,以便当我按下已经存在的 JButton 时会添加这个 JButton?

最佳答案

确保在添加按钮后重新验证重新绘制

revalidate();
repaint();

setSizesetLocation 的使用来看,您似乎正在使用绝对定位或 null 布局。使用布局管理器。

关于java - 当另一个 JButton 被按下时添加一个 JButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16304888/

相关文章:

java - SonarQube - 是否有一个 API 可以为您拥有的所有项目获取一部分分析?

java - 如何使用 Quarkus 在 Swagger 中生成请求示例

java - 初始循环后循环打印输出两次

java - 在一个程序中使用多个 Swing 定时器是不是很糟糕

html - 如何在移动设备上单击区域时使底部导航全宽

c# - 阻止 asp :Button OnClick event in C# from the OnClientClick event in JavaScript?

java - hibernate 的国家代表

Java(图形2D): triangle drawn by created Graphics2D not visible until second repaint

java - Mig 布局 : bad alignment

html - CSS:将文本向下移动几个像素但保持背景不变?