I have made a small program where the user gives the address of an image which is loaded on the ImageIcon and is displayed with a grid on it.
I now wish to get the position or the x,y cordinates of the grid in case of a mouse click on the picture.
Here's my code
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);
}
}
Hope i get some help. Thanks in advance :)
The basic idea is to add a MouseListener to a component. In your case, you used a JOptionPane which does not provide access to the displayed components. Anyway, JOptionPane are not made for that purpose.
So I took the liberty to tackle this with a whole different angle. The code is far from perfect (for example, everything is in a single class), but it gives you a hint on how you could start. I think this will provide a better base to start from.
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();
}
});
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.