我制作了一个小程序,用户给出加载在 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);
}
}
希望我能得到一些帮助。提前致谢 :)