-1

What I have implemented till now in java is ask the user to upload an image from the directory. My next step is that when the image is loaded a grid is placed above that image just for visual purpose so that the image gets divided in a, say 10 x 10 grids. How do I implement this stuff? Here's what I have implemented till now.

        JFileChooser choose=new JFileChooser();
        choose.showOpenDialog(null);
        File f=choose.getSelectedFile();
        String filename=f.getAbsolutePath();
        path.setText(filename);        
        BufferedImage img;
        try {
            img=ImageIO.read(f);
            Image dimg = img.getScaledInstance(500,500,Image.SCALE_SMOOTH);
            ImageIcon imageIcon = new ImageIcon(dimg);
            image_label.setIcon(imageIcon);
            }
        catch(Exception e) { 
            System.out.println(e);
        }
mKorbel
  • 109,525
  • 20
  • 134
  • 319
jayesh.doolani
  • 39
  • 1
  • 10
  • 1) [What have you tried?](http://www.whathaveyoutried.com/) Showing your effort will encourage others to help. 2) For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete and Verifiable Example). 3) One way to get image(s) for an example is to hot-link to the images seen in [this answer](http://stackoverflow.com/a/19209651/418556). – Andrew Thompson Mar 29 '14 at 07:54
  • JFileChooser choose=new JFileChooser(); choose.showOpenDialog(null); File f=choose.getSelectedFile(); String filename=f.getAbsolutePath(); path.setText(filename); BufferedImage img; img=ImageIO.read(f); Image dimg = img.getScaledInstance(500,500,Image.SCALE_SMOOTH); ImageIcon imageIcon = new ImageIcon(dimg); image_label.setIcon(imageIcon); Above code accepts an image from the directory and scales the image to fit in a jLabel of size 500x500. My next step is to overlay a grid on this image. – jayesh.doolani Mar 29 '14 at 08:03
  • You need to edit your post with your code. Don't put it in a comment – Paul Samsotha Mar 29 '14 at 08:04
  • Don't post code in a comment. It is unreadable. Instead [edit the question](http://stackoverflow.com/posts/22728431/edit). Also post an MCVE rather than uncompilable code snippets. – Andrew Thompson Mar 29 '14 at 08:05
  • But you're going to ignore me about posting a runnable example (an MCVE) that hot-links to an image? – Andrew Thompson Mar 29 '14 at 08:14
  • @AndrewThompson So should I post the whole runnable code? Because I am doing this in netbeans which has a jFrame and the code is too long. – jayesh.doolani Mar 29 '14 at 08:21
  • *"So should I post the whole runnable code?"* So did you read the link? I thought it made it pretty clear. – Andrew Thompson Mar 29 '14 at 09:24

1 Answers1

3
  • paint the image in a panel

    protected void paintComponent(Grapchics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, this);
    }
    
  • Then based on the the number of cells you want, say 10x10, just draw 100 cells (drawRect()) over the image. Something like

    protected void paintComponent(Grapchics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, this);
        int cellHeight = (int)(getHeight() / 10);
        int cellWidth = (int)(getWidth() / 10);
        for (int y = 0; y < getWidth(); y += cellHeight) {
            for (int x = 0; x < getHeight(); x += cellWidth){
                g.drawRect(x, y, cellWidth, cellHeight);
            }
        }
    }
    

I haven't test it, but the basic concept is there. You may also want to use variables (a constant probably) for the 10.

UPDATE 1

enter image description here

You can see the precision's a little off because I used int, but you can use doubles and draw by using Grapchics2D Rectangle2D.Double. I'm too lazy to change it

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class ImageGrid extends JPanel {

    private static final int CELLS = 10;

    BufferedImage img;

    public ImageGrid() {
        try {
            img = ImageIO.read(getClass().getResource("/resources/stackoverflow5.png"));
        } catch (IOException ex) {
            Logger.getLogger(ImageGrid.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (img != null) {
            g.drawImage(img, 0, 0, this);
            int cellHeight = (int) (getHeight() / CELLS); 
            int cellWidth = (int) (getWidth() / CELLS);
            for (int y = 0; y < getHeight(); y += cellHeight) {
                for (int x = 0; x < getWidth(); x += cellWidth) {
                    g.drawRect(x, y, cellWidth, cellHeight);

                }
            }
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return img == null ? new Dimension(300, 300) 
                : new Dimension(img.getWidth(), img.getHeight());
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame();
                JPanel wrapperPanel = new JPanel(new GridBagLayout());
                wrapperPanel.add(new ImageGrid());
                frame.add(wrapperPanel);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}

UPDATE 2

With JLabel
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class ImageGrid extends JLabel {

    private static final int CELLS = 10;

    BufferedImage img;

    public ImageGrid() {
        try {
            img = ImageIO.read(getClass().getResource("/resources/stackoverflow5.png"));
            setIcon(new ImageIcon(img));
        } catch (IOException ex) {
            Logger.getLogger(ImageGrid.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (img != null) {
            int cellHeight = (int) (getHeight() / CELLS); 
            int cellWidth = (int) (getWidth() / CELLS);
            for (int y = 0; y < getHeight(); y += cellHeight) {
                for (int x = 0; x < getWidth(); x += cellWidth) {
                    g.drawRect(x, y, cellWidth, cellHeight);

                }
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame();
                JPanel wrapperPanel = new JPanel(new GridBagLayout());
                wrapperPanel.add(new ImageGrid());
                frame.add(wrapperPanel);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • Can I draw the grids on an image which is as an icon on a jLabel? – jayesh.doolani Mar 29 '14 at 08:16
  • Sure you can. You can use the icon as the background of the frame, and just add a panel over it, where you draw the grid. Or directly paint on the label by override it's paintCompoent like I did with my panel. You can a few options. – Paul Samsotha Mar 29 '14 at 08:20
  • You can see my **UPDATE 2** with a `JLabel`. Not that much difference except for I use `setIcon` and I don't have to override `getPreferredSize()` and `JLabel` does that based of its content, in this case the icon – Paul Samsotha Mar 29 '14 at 08:28
  • Ok I'll try doing that and let you know soon. – jayesh.doolani Mar 29 '14 at 08:34
  • If you are using the GUI Builder tool, you can edit the auto-generated code. See [here](http://stackoverflow.com/a/22214485/2587435). Just edit the code of the label that you drag and drop – Paul Samsotha Mar 29 '14 at 08:38