Search code examples
javaimageswingjpanelpaintcomponent

Draw JPanel picture - Swing


I have a problem to draw a point on JPanel. I want to put point with her position. Because on the panel I load a picture. For each click on button I would to add point on panel.

But i don't appear on the panel.

File simpleIHM :

import java.awt.*; 
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;

import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class simpleIHM extends JFrame{


  JPanel JpLeft = new JPanel();
  JPanel JpRight = new JPanel();
  JButton btn1 = new JButton("Show");
  JLabel msgX = new JLabel("X :");
  JLabel msgY = new JLabel("Y :");
  JTextField textX = new JTextField(5);
  JTextField textY = new JTextField(5);

  public static int x,y = 0;

  JLabel img = null;
  BufferedImage image;

  public simpleIHM(){
        img = new JLabel(new ImageIcon("Centre.png"));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());
        JpLeft.add(img);
        PanelIMG imgPanel = new PanelIMG();
        JpLeft.add(imgPanel);
        getContentPane().add(JpLeft, BorderLayout.WEST);
        JpRight.add(msgX);
        JpRight.add(textX);
        JpRight.add(msgY);
        JpRight.add(textY);
        JpRight.add(btn1);
        JpRight.setLayout(new GridLayout(3, 2));
        getContentPane().add(JpRight, BorderLayout.EAST);
        pack();
        setVisible(true);
        showIMG("./Centre.png");
        //!!
        btn1.addMouseListener(new MouseAdapter() 
                                {
                                    public void mouseClicked(MouseEvent e) 
                                    {
                                        System.out.println("CLICK!");
                                        x = Integer.parseInt(textX.getText());
                                        y = Integer.parseInt(textY.getText());
                                        System.out.println("X "+x+ "| Y "+y); img.repaint();
                                    }

                                });
  }

    public void showIMG(String test){
        try
        {
            File input = new File("Centre.png");
            image = ImageIO.read(input);
        }
        catch (IOException ie)
        {
        System.out.println("Error:" + ie.getMessage());
        }
    }

  public static void main(String [ ] arg) {
        simpleIHM IHM = new simpleIHM();
       } 
}

File PanelIMG

import javax.swing.JPanel;
import java.awt.*;
import javax.swing.*;


public class PanelIMG extends JPanel{

public PanelIMG()
{

}

@Override
public void paintComponent(Graphics g)
{
    super.paintComponent(g);

    g.drawOval(simpleIHM.x, simpleIHM.y, 5, 5);
    System.out.println("Paint Component");
}
}

Thanks in advance


Solution

  • I may have misinterpreted the question, but it seems that you want to paint a point over an image. But in the posted code, you actually painting an image in one panel and the point in another.

    You can create a panel with a background image and paint a point in that panel. Below is the example that demonstrates.

    Also please note some minor comments:

    • There is no need to extend top level container JFrame unless you add new functionality;
    • Use DocumentFilter, JFormattedTextField or handle exception in case of invalid input from user (ie NumberFormatException thrown from Integer.parseInt());
    • The trick with public static x,y members that are used by other classes is a dirty hack, avoid it.
    • Get familiar with Java Code Conventions, Naming Conventions section in particular.

    Here is a demo:

    import java.awt.*;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    
    import java.net.URL;
    import java.text.NumberFormat;
    
    class ImagePanelDemo {
        static class ImagePanel extends JPanel {
            private Image image;
            private Point point;
    
            ImagePanel(Image image, Point point) {
                this.image = image;
                this.point = point;
            }
    
            public void setPoint(Point point) {
                this.point = point;
                repaint();
            }
    
            @Override
            public Dimension getPreferredSize() {
                if (image != null)
                    return new Dimension(image.getWidth(this), 
                            image.getHeight(this));
                return super.getPreferredSize();
            }
    
            @Override
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
    
                if (image != null)
                    g.drawImage(image,0,0,getWidth(),getHeight(),this);
                if (point != null)
                    g.fillOval(point.x, point.y, 5, 5);
            }
        }
    
        private static void createAndShowUI() {
            try {
                JFrame frame = new JFrame("Image");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLocationRelativeTo(null);
    
                Image image = ImageIO.read(new URL(
                    "https://duke.kenai.com/comfyChair/ComfyChairRadSmall.jpg"));           
    
                final ImagePanel imagePanel = new ImagePanel(image, 
                        new Point(10, 10));
    
                frame.add(imagePanel);
    
                JPanel buttonPanel = new JPanel();
    
                final JFormattedTextField xField = new JFormattedTextField(
                        NumberFormat.getNumberInstance());
                xField.setColumns(5);
                final JFormattedTextField yField = new JFormattedTextField(
                        NumberFormat.getNumberInstance());
                yField.setColumns(5);
    
                JButton updateButton = new JButton("Update");
    
                buttonPanel.add(new JLabel("x:"));
                buttonPanel.add(xField);
                buttonPanel.add(new JLabel("y:"));
                buttonPanel.add(yField);
                buttonPanel.add(updateButton);
    
                updateButton.addMouseListener(new MouseAdapter() 
                {
                    public void mouseClicked(MouseEvent e) {
                        try {
                        imagePanel.setPoint(new Point(
                                Integer.parseInt(xField.getText()), 
                                Integer.parseInt(yField.getText())));
                        } catch(NumberFormatException ex) {
                            ex.printStackTrace();
                        }
                    }
                });
    
                frame.add(buttonPanel, BorderLayout.SOUTH);
    
                frame.pack();
                frame.setVisible(true);
            } 
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        public static void main(String[] args) {
    
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowUI();
                }
            });
        }
    }