有 Java 编程相关的问题?

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

java SwingReplacement在GridBagLayout上放置组件

我花了几个小时寻找答案,尝试了我知道的每一种方法,但都没有找到答案
我正在使用eclipse,我的类正在扩展JFrame,我正在尝试替换我添加到框架中的两个组件(使用gridbaglayout)
当我删除第一个时,我无法将第二个添加到第一个的位置
组件是带有图像的JButton。 我如何在任何需要的地方添加和删除组件?(已尝试使用GridBagConstraints将其添加到我刚从中删除组件的位置)


共 (1) 个答案

  1. # 1 楼答案

    作为一种解决方法,您可以将带有按钮的继承面板添加到主面板(使用GridbagLayout)。然后,当您要更换这些按钮(或任何组件)时,您不需要更换主面板上的按钮。可以在继承的面板中替换它们。由于您没有向我们提供代码,因此一种伪代码如下所示:

    JButton myBtn = new JButton(); //Theinitial button
    JPanel mainPanel = new JPanel(new GridBagLayout()); //main panel
    JPanel inheritedPanel = new JPanel(new BorderLayout())//borderlayout to fill the entire panel.
    inheritedPanel.add(myBtn,BorderLayout.CENTER);
    mainPanel.add(inheritedPanel, myConstraints);
    
    JButton replacementBtn = new JButton;
    inheritedPanel.remove(myBtn);
    inheritedPanel.add(replacementBtn);
    inheritedPanel.repaint();
    inheritedPanel.revalidate();