如何在另一个 JPanel 的中心添加一个 JPanel?

How to add a JPanel in the center of another JPanel?

我想在中心的另一个 JPanel WorldView 之上添加一个 JPanel 地图,就像这样

这是我的代码:

public class WorldView extends JPanel implements ActionListener{

private JPanel map;

public WorldView() throws IOException{
    this.setSize(1024,768);
    this.setBackground(Color.BLACK);
    map = new JPanel();
    this.add(map);
}

在构造函数中添加: setLayout(new FlowLayout(FlowLayout.CENTER));

您可以使用 GridBagLayout 并修改 GridBagConstraints#insetsEmptyBorder 以结合 GridBagLayout 或其他一些布局(如 BorderLayout 例如

有关详细信息,请参阅 How to Use GridBagLayout and How to Use Borders