gpt4 book ai didi

java - 有没有办法把JPanel放在JPanel上?

转载 作者:行者123 更新时间:2023-12-02 18:26:41 24 4
gpt4 key购买 nike

我正在尝试将 JPanel 放入 JPanel 内部或放在 JPanel 上,无论哪种情况,最终我只是希望它像这样工作 Insanely well painted description of the problem

如图所示,红线是一个 JFrame,里面有 2 个 JPanel,绿色的 JPanel 上有一些不同的 JPanel。

我需要有关绿色 JPanel 和其中的小 JPanel 的帮助。有什么办法可以让它像这样工作吗?

任何帮助将不胜感激!

==============编辑1==============

这里有一些代码,向您展示我迄今为止在@hfontanez 的帮助下所做的事情。

import javax.swing.*;
import java.awt.*;
import java.io.IOException;

public class Main
{
public static void main(String[] args)
{
//JFrame
JFrame jframe = new JFrame();
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setSize(1920, 1080);
jframe.setResizable(false);
jframe.setLocationRelativeTo(null);
jframe.setVisible(true);

//parentJpanel - This is the main panel
JPanel parentJpanel = new JPanel();
parentJpanel.setBackground(Color.YELLOW);
parentJpanel.setSize(1920, 1080);
parentJpanel.setLayout(new BorderLayout());

//smallPanel - This is the little panel on the bottom
JPanel smallPanel = new JPanel();
smallPanel.setBackground(Color.GREEN);
smallPanel.setSize(1920, 300);
smallPanel.setLocation(0, 780);
smallPanel.setLayout(new BoxLayout(smallPanel, BoxLayout.PAGE_AXIS));

parentJpanel.add(smallPanel);
jframe.add(parentJpanel);
}
}

The result of the code below

我原以为顶部是黄色的,底部的小部分是绿色的,但整个东西都变成了绿色。我做错了什么?

最佳答案

enter image description here

图中的 GUI 是使用三个面板创建的。

  1. 黄色面板是游戏区域。它没有布局,没有组件(定义自己的首选尺寸)并且是自定义绘制的,因此它定义了一个合理的首选尺寸以向布局管理器报告。
  2. GREEN 面板包含控件。它使用FlowLayout
  3. RED 面板使用 BorderLayout,并将 YELLOW 面板放在 CENTER 中, PAGE_END 中的 >GREEN 面板。

代码

这是制作上面屏幕截图的代码。

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;

public class GameLayout {

GameLayout() {
// The main GUI. Everything else is added to this panel
JPanel gui = new JPanel(new BorderLayout(5, 5));
gui.setBorder(new EmptyBorder(4, 4, 4, 4));
gui.setBackground(Color.RED);

// The custom painted area - it is a panel that defines its preferred size.
gui.add(new GamePanel());

JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
buttonPanel.setBackground(Color.GREEN);
for (int ii = 1; ii<5; ii++) {
buttonPanel.add(new JButton("B " + ii));
}
gui.add(buttonPanel,BorderLayout.PAGE_END);

JFrame f = new JFrame("Game Layout");
f.setContentPane(gui);
f.setLocationByPlatform(true);
f.pack();
f.setVisible(true);
}

public static void main(String[] args) {
Runnable r = () -> new GameLayout();
SwingUtilities.invokeLater(r);
}
}

class GamePanel extends JPanel {
GamePanel() {
setBackground(Color.YELLOW);
}

@Override
public Dimension getPreferredSize() {
return new Dimension(400, 100);
}
}

关于java - 有没有办法把JPanel放在JPanel上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70048520/

24 4 0