添加 JPanel 的 JFrame 执行时间

发布于 2024-12-05 06:50:39 字数 472 浏览 0 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

绿光 2024-12-12 06:50:39

在对 GUI 进行此类结构更改后,您需要调用 revalidate()repaint()

请注意,setSizesetLocation 最好由布局管理器处理。

相关链接:

You need to call revalidate() and repaint() after such structural changes to the GUI.

Note that setSize and setLocation should preferrably be handled by the layout manager.

Related link:

扭转时空 2024-12-12 06:50:39

盒子的目的是什么?

如果它们纯粹是视觉的,并且您不打算向其添加组件,那么最好定义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 of paintComponent().

Alternately, draw them to the Graphics object of a BufferedImage and add the image to a JLabel, as shown here.

enter image description here

太阳公公是暖光 2024-12-12 06:50:39

此示例显示 add/emove/pack 可能会有所帮助。

private void addBox(int x, int y){
   JPanel panel = new JPanel();
   panel.setBackground(Color.RED);
   add(panel);
   //If there isn't another JPanel, then this way you'll occupy 
   //the whole JFrame area; by defalut, JFrame has BorderLayout,
   //and only one JComponent can occupy the central area 
   revalidate();
   repaint();
}

This example showing add/remove/pack may help.

private void addBox(int x, int y){
   JPanel panel = new JPanel();
   panel.setBackground(Color.RED);
   add(panel);
   //If there isn't another JPanel, then this way you'll occupy 
   //the whole JFrame area; by defalut, JFrame has BorderLayout,
   //and only one JComponent can occupy the central area 
   revalidate();
   repaint();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文