且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用JLayeredPane创建棋盘游戏布局

更新时间:2023-02-02 18:51:49

为了初始化我要在其中放置图像的网格单元格,我不需要在这些位置手动添加它们吗?

In order to initialize the cells of the grid that i want to have images in, don't i need to add them manually in those positions?

如果使用 GridLayout ,则每个单元格都必须具有一个组件,并且必须按顺序添加这些组件.也就是说,添加组件后,它们将根据需要自动包装到下一行.

If you use a GridLayout every cell must have a component and the components must be added in sequential order. That is as components are added they will wrap automatically to the next row as required.

因此,即使您不希望在单元格中放置图像,也需要添加一个虚拟组件,比如说一个没有文本/图标的JLabel.

So even if you don't want an image in a cell you would need to add a dummy component, lets say a JLabel with no text/icon.

一种更简单的方法可能是使用 GridBagLayout .可以将 GridBagLayout 配置为为没有组件的单元格保留"空间.因此,您可以将组件添加到特定的单元格.

An easier approach might be to use a GridBagLayout. The GridBagLayout can be configured to "reserve" space for cells that don't have components. So you can add a component to a specific cell.

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

public class GridBagLayoutSparse extends JPanel
{
    public GridBagLayoutSparse()
    {
        setBorder( new LineBorder(Color.RED) );

        GridBagLayout gbl = new GridBagLayout();
        setLayout( gbl );
/*
    //  Set up a grid with 5 rows and columns.
        //  The minimimum width of a column is 50 pixels
        //  and the minimum height of a row is 20 pixels.

        int[] columns = new int[5];
        Arrays.fill(columns, 50);
        gbl.columnWidths = columns;

        int[] rows = new int[5];
        Arrays.fill(rows, 20);
        gbl.rowHeights = rows;
*/
        //  Add components to the grid at top/left and bottom/right

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.BOTH;

        gbc.gridx = 0;
        gbc.gridy = 0;
        addLabel("Cell 0:0", gbc);

        gbc.gridx = 3;
        gbc.gridy = 4;
        addLabel("Cell 3:4", gbc);
    }

    private void addLabel(String text, GridBagConstraints gbc)
    {
        JLabel label = new JLabel(text);
        label.setBorder( new LineBorder(Color.BLUE) );

        add(label, gbc);
    }

    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("GridBagLayoutSparse");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout( new GridBagLayout() );
        frame.add(new GridBagLayoutSparse());
        frame.setSize(300, 300);
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args) throws Exception
    {
        java.awt.EventQueue.invokeLater( () -> createAndShowGUI() );
    }
}

  1. 按原样运行代码,组件将在中心分组在一起.
  2. 取消注释块注释,然后再次运行.组件将放置在适当的单元格中.