添加 JPanel 的 JFrame 执行时间
我正在使用 JFrame
按以下方式动态添加 JPanel
实例:
private void addBox(int x, int y){
JPanel panel = new JPanel();
panel.setBackground(Color.RED);
panel.setSize(10, 10);
panel.setVisible(true);
panel.setLocation(x, y);
this.getContentPane().add(panel);
}
问题是,当我使用 addBox
方法时,>JPanel
实例不会出现在 JFrame
中。我可以看到该框的唯一方法是手动调整窗口大小。
注意:我尝试使用 this.pack();
,但这不起作用。
I'm working with a JFrame
adding JPanel
instances dynamically in the following way:
private void addBox(int x, int y){
JPanel panel = new JPanel();
panel.setBackground(Color.RED);
panel.setSize(10, 10);
panel.setVisible(true);
panel.setLocation(x, y);
this.getContentPane().add(panel);
}
The problem is, when I use addBox
method, the JPanel
instance does not appear in the JFrame
. The only way I can see the box I need to manualy resize the window.
Note: I tried using this.pack();
, but this did not work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在对 GUI 进行此类结构更改后,您需要调用
revalidate()
和repaint()
。请注意,
setSize
和setLocation
最好由布局管理器处理。相关链接:
You need to call
revalidate()
andrepaint()
after such structural changes to the GUI.Note that
setSize
andsetLocation
should preferrably be handled by the layout manager.Related link:
盒子的目的是什么?
如果它们纯粹是视觉的,并且您不打算向其添加组件,那么最好定义
box
class(或使用a 。或者,将它们绘制到
Graphics
bufferedimage
的对象,然后将图像添加到jlabel
,如图所示在这里< /a>。What are the purpose of the boxes?
If they are purely visual, and you don't intend to add components to them, it would be better to define a
Box
class (or use a Rectangle2D) and draw or fill them at time ofpaintComponent()
.Alternately, draw them to the
Graphics
object of aBufferedImage
and add the image to aJLabel
, as shown here.此示例显示 add/emove/pack 可能会有所帮助。
This example showing add/remove/pack may help.