这个问题与我之前的问题How to generate Cartesian Coordinate (x,y) from GridBaglayout有关?
我已经成功获得了每张图片的坐标,但是当我通过(System.out.println)检查坐标以及图像在屏幕上的位置时,似乎是错误的。例如,如果在屏幕上很明显第一张图片的 x 点位于坐标为 20 的单元格 2 上,但程序显示 x=1。
以下是部分代码:
public Grid (){
setPreferredSize(new Dimension(600,600));
....
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.weightx = 1d;
gc.weighty = 1d;
gc.insets = new Insets(0, 0, 0, 0);//top, left, bottom, and right
gc.fill = GridBagConstraints.BOTH;
JLabel[][] label = new JLabel[ROWS][COLS];
Random rand = new Random();
// fill the panel with labels
for (int i=0;i<IMAGES;i++){
ImageIcon icon = createImageIcon("myPics.jpg");
int r, c;
do{
//pick random cell which is empty
r = (int)Math.floor(Math.random() * ROWS);
c = (int)Math.floor(Math.random() * COLS);
} while (label[r][c]!=null);
//randomly scale the images
int x = rand.nextInt(50)+30;
int y = rand.nextInt(50)+30;
Image image = icon.getImage().getScaledInstance(x,y, Image.SCALE_SMOOTH);
icon.setImage(image);
JLabel lbl = new JLabel(icon); // Instantiate GUI components
gc.gridx = r;
gc.gridy = c;
add(lbl, gc); //add(component, constraintObj);
label[r][c] = lbl;
}
我通过这段代码检查了坐标:
Component[] components = getComponents();
for (Component component : components) {
System.out.println(component.getBounds());
}