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

发布于 2024-08-23 17:46:55 字数 1660 浏览 6 评论 0原文

这个问题与我之前的问题相关 如何生成笛卡尔坐标 (x, y) 来自 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());
}

This question is related to my previous question How to generate Cartesian Coordinate (x,y) from GridBaglayout?

I have successfully get the coordinate of each pictures, however when I checked the coordinate through (System.out.println) and the placement of the images on the screen, it seems to be wrong. e.g. if on the screen it was obvious that the x point of the first picture is on cell 2 which is on coordinate of 20, but the program shows x=1.

Here is part of the code:

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; 
}

I checked the coordinate through this code:

Component[] components = getComponents();     
for (Component component : components) {
   System.out.println(component.getBounds());
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我的奇迹 2024-08-30 17:46:55

您可以使用 SwingUtilities< /a> 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 + "]");
                }
            });
        }
    }
}

You can use SwingUtilities convertPointToScreen() and convertPointFromScreen() to convert between screen and component coordinates.

Addendum: Here's a simple example I used when trying to understand how components move and resize under the influence of a layout manager.

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 + "]");
                }
            });
        }
    }
}
少钕鈤記 2024-08-30 17:46:55

如果在屏幕上很明显
第一张图片的x点在
单元格 2 位于坐标 20 上,
但程序显示x=1。

第一个图像的 x/y 坐标为 0/0。第二个图像的坐标为 1/0。从 0 开始偏移的 X/Y 值。这就是你所说的吗?

或者您的侦听器是否添加到图像而不是面板,在这种情况下您需要将图像坐标转换为面板坐标。检查我们的 SwingUtilities 类以获取执行此操作的方法。

如果您需要更多帮助,请发布您的 SSCCE

if on the screen it was obvious that
the x point of the first picture is on
cell 2 which is on coordinate of 20,
but the program shows x=1.

The first image will have x/y coordinates of 0/0. The second images will have coordinates of 1/0. The X/Y values of offset from 0. Is that what you are talking about?

Or is your listener added to the image not the panel in which case you need to convert the image coordinates to the panel coordinates. Check our the SwingUtilities class for methods to do this.

If you need more help post your SSCCE.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文