gpt4 book ai didi

java - 如何在JPanel上获取图像的坐标

转载 作者:行者123 更新时间:2023-12-02 08:34:16 25 4
gpt4 key购买 nike

这个问题与我之前的问题How to generate Cartesian Coordinate (x,y) from GridBaglayout?相关。

我已经成功获取了每张图片的坐标,但是当我通过(System.out.println)检查坐标以及图像在屏幕上的位置时,它似乎是错误的。例如如果在屏幕上很明显第一张图片的x点在单元格2上,坐标为20,但程序显示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());
}

最佳答案

您可以使用SwingUtilities convertPointToScreen()convertPointFromScreen() 在屏幕坐标和组件坐标之间进行转换。

附录:这是我在尝试了解码件如何在布局管理器的影响下移动和调整大小时使用的一个简单示例。

public class MyPanel extends JPanel {

public MyPanel() {
super(new GridLayout(4, 4));
for (int i = 0; i < 16; i++) {
JPanel panel = new JPanel(new GridLayout());
panel.add(new CenterLabel());
this.add(panel);
}
}

private static void create() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new MyPanel());
f.pack();
f.setVisible(true);
}

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {

@Override
public void run() {
create();
}
});
}

private static class CenterLabel extends JLabel {

public CenterLabel() {
this.setHorizontalAlignment(JLabel.CENTER);
this.setVerticalAlignment(JLabel.CENTER);
this.setOpaque(true);
this.setBackground(Color.lightGray);
this.setBorder(BorderFactory.createLineBorder(Color.blue));
this.setPreferredSize(new Dimension(160, 100));
this.addComponentListener(new ComponentAdapter() {

@Override
public void componentResized(ComponentEvent e) {
int w = e.getComponent().getWidth();
int h = e.getComponent().getHeight();
CenterLabel.this.setText("[" + w/2 + "\u253C" + h/2 + "]");
}
});
}
}
}

关于java - 如何在JPanel上获取图像的坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2397034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com