Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8592709
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T23:48:53+00:00 2026-06-11T23:48:53+00:00

I have made a small program where the user gives the address of an

  • 0

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 🙂

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T23:48:54+00:00Added an answer on June 11, 2026 at 11:48 pm

    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();
                }
            });
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Problem: Have made a small mail program which works perfectly on my developer pc
I have made a program which is a small library operated via software. When
I am studying memory management, and I have made a small program which manages
I made small program, which you don't have to install. So when I want
I have made a small program in c# called Registry.exe. Now i my c++
i have made a small opengl program using the d programming language. what i
I have a small self made gallery which im still working on it: http://springbreak.enteratenorte.com
I have made a small program in C# that I want to run in
I have made a small function which should print some InfoPath files. It is
I made this small Java program using eclipse IDE. I have set the workspace

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.