【发布时间】:2011-09-07 16:33:32
【问题描述】:
我已经全局初始化了一个 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();//?
}
}
Update2:这似乎是 java 的传递值性质和我试图添加到我的布局中的另一个类(画布)的问题。如果我找到解决方案会更新。
Update3:这是一个线程问题,我正在调用的类正在挂起主窗口。
编辑:我提供了代码作为参考,并尽量完整提供完整的图片,不要轻易自行编译。感谢所有提供帮助的人。
更新4:成功!他们的关键是 mediaplayer 类做了一个“isDisplayable()”检查,如果它被添加到的框架没有被添加到 gridbaglayout,它会导致它挂起程序。一系列看起来很不幸的传递值(JInternalFrames),将内部框架预先添加到 gridbaglayout 以及从另一种方法远程启动媒体允许我正在寻求工作。
【问题讨论】:
-
您发布的代码甚至无法编译。我没有时间修复你的编译错误!此外,您不应该使用静态变量。
-
@Time,MediaPlayer 与什么有什么关系?我们不是头脑读者,这就是为什么您发布的代码应该被编译并展示您遇到的问题的原因。几行代码对我们毫无用处,除非我们知道代码是如何使用的上下文。
标签: java swing layout layout-manager gridbaglayout