0

我是 Java GUI 的新手,我正在尝试放置一个 7 x 12 Jlabels/Boxes 的网格。然后我需要能够获得每个框的 X 和 Y 坐标。当我运行下面的代码时,它会将每个框显示为 0,0 ... 任何帮助将不胜感激。

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;

import javax.swing.*;


public class GridPanel extends JPanel{

private final int HEIGHT = 7;
private final int WIDTH = 12;
private final int TOTAL_BOXES = HEIGHT * WIDTH;
JLabel box[];

public GridPanel()
{
    setLayout(new GridLayout(7,12));


     box = new JLabel[TOTAL_BOXES];

        for (int x = 0;x<box.length;x++){

            box[x]=new JLabel("");
            box[x].setOpaque(true);
            box[x].setPreferredSize(new Dimension(30,30));
            box[x].setBackground(Color.white);
            box[x].setBorder(BorderFactory.createLineBorder(Color.black));
            int a = box[x].getX();
            int b = box[x].getY();
            String test = b + "," + a;
            box[x].setText(test);


        }

        System.out.println(box[45].getX());

        for (int x = 0;x<box.length;x++)
            add(box[x]);

}

}

4

0 回答 0