我是Java GUI的新手,我正在尝试放置一个7 x 12 Jlabels / Box的网格。我需要能够得到每个盒子的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]);
}
}