1

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

}

希望我能得到一些帮助。提前致谢 :)

4

1 回答 1

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();
            }
        });
    }
}
于 2012-09-26T14:55:39.853 回答