协调这个问题是涉及到我刚才的问题How to generate Cartesian Coordinate (x,y) from GridBaglayout?如何获得图像的上的JPanel
我已经顺利拿到然而,每个图片的坐标,当我检查过的坐标(的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());
}
谢谢...在我的情况下,我想它关于gridbagconstraint ...我想坐标跟随JPanel坐标不是整个屏幕,所以我重新检查它,我通过更改gc.fill = GridBagConstraints来修复它。 NONE而不是BOTH – Jessy 2010-03-07 19:01:19