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

时间:2012-09-26 14:11:37

标签: java swing imageicon

我制作了一个小程序,用户在其中提供加载在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);
}

}

希望我能得到一些帮助。在此先感谢:)

1 个答案:

答案 0 :(得分:5)

基本思想是向组件添加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();
            }
        });
    }
}