繁体   English   中英

如何找到一部分网格的坐标?

[英]How to find the co-ordinates of a portion of grid?

我编写了一个小程序,用户在其中给出了图像的地址,该图像已加载到ImageIcon上并显示有网格。

现在,我希望在鼠标单击图片的情况下获取网格的位置或x,y坐标。

这是我的代码

import java.awt.*;
import java.awt.image.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.imageio.ImageIO;
import javax.swing.*;

class GridLines {

public static void main(String[] args) throws IOException {
    System.out.println("Enter image name\n");
    BufferedReader bf=new BufferedReader(new
            InputStreamReader(System.in));
    String imageName= null;
    try {
        imageName = bf.readLine();
    } catch (IOException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    }
    File input = new File(imageName);

    Dimension imgDim = new Dimension(200,200);
    BufferedImage mazeImage = new BufferedImage(imgDim.width, imgDim.height, BufferedImage.TYPE_INT_RGB);
    mazeImage = ImageIO.read(input);
    Integer k = mazeImage.getHeight();
    Integer l = mazeImage.getWidth();
    Graphics2D g2d = mazeImage.createGraphics();
    g2d.setBackground(Color.WHITE);
    //g2d.fillRect(0, 0, imgDim.width, imgDim.height);
    g2d.setColor(Color.RED);
    BasicStroke bs = new BasicStroke(1);
    g2d.setStroke(bs);
    // draw the black vertical and horizontal lines
    for(int i=0;i<21;i++){
        // unless divided by some factor, these lines were being
        // drawn outside the bound of the image..
            g2d.drawLine((l+2)/4*i, 0, (l+2)/4*i,k-1);
            g2d.drawLine(0, (k+2)/5*i, l-1, (k+2)/5*i);
    }

    ImageIcon ii = new ImageIcon(mazeImage);
    JOptionPane.showMessageDialog(null, ii);
}

}

希望我能有所帮助。 提前致谢 :)

基本思想是将MouseListener添加到组件。 在您的情况下,您使用了JOptionPane,它不提供对显示组件的访问。 无论如何,JOptionPane并非为此目的而制作。

因此,我自由地以不同的角度来解决这个问题。 该代码远非完美(例如,所有内容都在同一个类中),但是它为您提供了如何启动的提示。 我认为这将提供一个更好的起点。

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileFilter;

class GridLines {

    private JFrame frame;

    class MyGridPanel extends JPanel {
        private static final int ROWS = 4;
        private static final int COLS = 5;

        class CellPanel extends JPanel {
            int x;
            int y;

            public CellPanel(final int x, final int y) {
                setOpaque(false);
                this.x = x;
                this.y = y;
                MouseListener mouseListener = new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent e) {
                        JOptionPane.showMessageDialog(CellPanel.this, "You pressed the cell with coordinates: x=" + x + " y=" + y);
                    }
                };
                setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.RED));
                addMouseListener(mouseListener);
            }

        }

        private final ImageIcon image;

        public MyGridPanel(ImageIcon imageIcon) {
            super(new GridLayout(ROWS, COLS));
            this.image = imageIcon;
            for (int i = 0; i < ROWS; i++) {
                for (int j = 0; j < COLS; j++) {
                    add(new CellPanel(i, j));
                }
            }
            // Call to setPreferredSize must be made carefully. This case is a good reason.
            setPreferredSize(new Dimension(imageIcon.getIconWidth(), imageIcon.getIconHeight()));
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(image.getImage(), 0, 0, this);
        }
    }

    protected void initUI() {
        frame = new JFrame(GridLines.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        File file = selectImageFile();
        if (file != null) {
            ImageIcon selectedImage = new ImageIcon(file.getAbsolutePath());
            frame.add(new MyGridPanel(selectedImage));
            frame.pack();
            frame.setVisible(true);
        } else {
            System.exit(0);
        }
    }

    public File selectImageFile() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fileChooser.setFileFilter(new FileFilter() {

            @Override
            public String getDescription() {
                return "Images files (GIF, PNG, JPEG)";
            }

            @Override
            public boolean accept(File f) {
                if (f.isDirectory()) {
                    return true;
                }
                String fileName = f.getName().toLowerCase();
                return fileName.endsWith("gif") || fileName.endsWith("png") || fileName.endsWith("jpg") || fileName.endsWith("jpeg");
            }
        });
        int retval = fileChooser.showOpenDialog(frame);
        if (retval == JFileChooser.APPROVE_OPTION) {
            return fileChooser.getSelectedFile();
        }
        return null; // Cancelled or closed
    }

    public static void main(String[] args) throws IOException {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (UnsupportedLookAndFeelException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                new GridLines().initUI();
            }
        });
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM