更新java布局管理器



我已经全局初始化了GridBagLayout,然后在我的类构造函数中实例化了它,并添加了一些按钮等。

我如何在事实之后添加东西?简单类扩展JFrame。每当我尝试上课。add(stuff, gribagconstraints) after fact(在构造函数中使用add(stuff, gribagconstraints))什么都没有发生,也没有添加到我的布局中。

我需要"刷新"布局管理器之类的吗?全局声明。

更新:我已经尝试过revalidate(),但它似乎不工作,这里是我的代码的简化版本与测试按钮在适当的概念证明:

public class MainGUI extends JPanel{
    static GridBagConstraints c;
    static MainGUI mainGUIclass;
    static JFrame mainGUIframe;
    public MainGUI() {
    this.setLayout(new GridBagLayout());
    c = new GridBagConstraints();
    saveButton = new JButton("Save and Exit");
    saveButton.setPreferredSize(new Dimension(200, 30));
    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 4;
    add(saveButton, c);
    }
public static void main(String[] args) {
    mainGUIframe = new JFrame("Message");
    mainGUIframe.setSize(800,800);
    mainGUIclass = new MainGUI();
    mainGUIframe.add(mainGUIclass);
    mainGUIframe.setVisible(true);

   //now the addition
    JButton newButton = new JButton("New Button");  
    newButton.setPreferredSize(new Dimension(200, 30));

    c.gridx = 5;
    c.gridy = 0;
    c.gridwidth = 4;
    mainGUIclass.add(newButton,c);
    //none of this seems to work
    mainGUIclass.revalidate();//?
    mainGUIclass.repaint();//?
  }
}

Update2:这似乎是java和另一个类(画布)的passbyvalue性质的问题,我试图添加到我的布局。如果我找到解决方案,我会更新的。

Update3:这是一个线程问题,我正在调用的类正在挂起主窗口。

编辑:我提供的代码作为参考,并试图是完整的,以提供一个完整的画面,而不是容易编译自己。感谢所有提供帮助的人。

Update4:成功!关键是mediaplayer类执行了"isDisplayable()"检查,如果要添加的帧没有添加到gridbaglayout中,则会导致挂起程序。一系列不幸的通过值(JInternalFrames),预先将internalframe添加到griddbaglayout和从另一种方法远程启动媒体允许我正在寻找的工作。

您将调用容器上的revalidate()(如果它派生自JComponent,例如JPanel),它使用布局来重新设置它们包含的组件。这应该递归地遍历该布局所持有的所有容器,并且它们也应该更新其组件布局。我所知道的主要例外是JScrollPanes中持有的组件,为此,您需要在scrollpanes的JViewport上调用revalidate。

而且,有时您需要在revalidate()之后调用repaint(),特别是如果您已经删除了容器中保存的任何组件。

在您的示例中,您正在添加一个与前一个按钮完全相同的GridBagConstraints按钮。当我试着运行代码时,你的按钮是一个接一个的,所以你只能看到其中一个。试着改变你的GridBagConstraints,这样你添加的第二个按钮被放置在另一个位置。建议为每个受约束的组件实例化一个新的GridBagConstraints,以消除发生此类编程错误的机会。

此外,关于您的更新,JFrame没有revalidate()功能。

最新更新