我目前有 2 个 JPanel 添加到 JFrame 中。调整窗口大小时,只有最近添加的 JPanel 才会调整大小。如何确保所有 JPanel 都能调整大小?在我的程序中,我发射烟花并有网格线。我希望每个人都拥抱屏幕底部。
使用此代码,发射的烟花会调整大小以拥抱,但网格线不会:
JFrame frame = new JFrame();
frame.setSize(950,800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GuiTest test = new GuiTest();
frame.add(test, BorderLayout.PAGE_END);
frame.setVisible(true);
Grid grid = new Grid();
frame.add(grid);
frame.setVisible(true);
FireworkP canvas = new FireworkP(150, 45, 7, 2);
frame.add(canvas);
frame.setVisible(true);
frame.getContentPane().setBackground(Color.BLACK);
frame.setVisible(true);
使用此代码,会发生相反的情况:
JFrame frame = new JFrame();
frame.setSize(950,800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GuiTest test = new GuiTest();
frame.add(test, BorderLayout.PAGE_END);
frame.setVisible(true);
FireworkP canvas = new FireworkP(150, 45, 7, 2);
frame.add(canvas);
frame.setVisible(true);
frame.getContentPane().setBackground(Color.BLACK);
frame.setVisible(true);
Grid grid = new Grid();
frame.add(grid);
frame.setVisible(true);
默认状态:/image/0gCpV.png
代码 1 调整大小:/image/Y4gf5.png
代码 2 调整大小:/image/ZR8Kd.png
最佳答案
So is there any way to have a separate grid line class or should I just combine them?
你们建立了 parent / child 的关系。
所以你的逻辑会是这样的:
FireworkP foreground = new FireworkP(150, 45, 7, 2);
foreground.setOpaque( false );
Grid background = new Grid();
background.add(foreground);
frame.add(background);
frame.setVisible(true);
以上假设:
- 您的 FireworkP 和 Grid 类是 JPanel,您可以在其中进行自定义绘画。
- 您的类使用适当的布局管理器
现在你的 GUI 的结构如下:
- frame
- background
- foreground
因此,您拥有可以在 Z 轴上将自身重叠绘制的组件。
如果向同一面板添加多个组件,则这些组件将绘制在 X/Y 轴上
关于java - 如何在调整大小时重新绘制所有 JPanel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53309020/