我已经全局初始化了一个 GridBagLayout,然后在我的类构造函数中实例化了它并添加了一些按钮等。
事后如何添加内容?简单类扩展了 JFrame。每当我在事后尝试 class.add(stuff, gridbagconstraints) 时(在构造函数中仅使用 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();//?
}
}
更新 2:这似乎是 java 的传递值性质和我试图添加到我的布局中的另一个类(画布)的问题。如果我找到解决方案会更新。
Update3:这是一个线程问题,我正在调用的类正在挂起主窗口。
编辑:我提供了代码作为参考,并尽量完整以提供完整的图片,不要轻易自行编译。感谢所有提供帮助的人。
更新4:成功!他们的关键是 mediaplayer 类做了一个“isDisplayable()”检查,如果它被添加到的框架没有被添加到 gridbaglayout,它会导致它挂起程序。一系列不幸的通过值传递(JInternalFrames),将内部框架预先添加到 gridbaglayout 和从另一种方法远程启动媒体允许我正在寻求工作。