I am trying to load an Image of any map in a JLabel and when clicking on this map a "pointer" is drawn exactly where I clicked and this image is edited with the new pointer, for this I am using a MouseListener , but my program does not draw nothing on click.
package mapa;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Signal {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Signal window = new Signal();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*
* @throws IOException
*/
public Signal() throws IOException {
initialize();
}
/**
* Initialize the contents of the frame.
*
* @throws IOException
*/
private void initialize() throws IOException {
BufferedImage image1 = ImageIO.read(new File("C:\\Users\\BryanPC\\Desktop\\SanFierro.jpg"));
Graphics2D map = image1.createGraphics();
frame = new JFrame();
frame.setBounds(100, 100, 477, 450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 461, 400);
frame.getContentPane().add(panel);
panel.setLayout(null);
JLabel containerImg = new JLabel(new ImageIcon(image1));
containerImg.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
BufferedImage pointer = null;
try {
pointer = ImageIO.read(new File("C:\\Users\\BryanPC\\Desktop\\smallPointer.png"));
map.drawImage(pointer, e.getX(), e.getY(), null);
map.drawOval(e.getX(), e.getY(), 50, 50);
} catch (IOException e1) {
System.out.println("The url is invalid");
}
}
});
panel.add(containerImg);
containerImg.setBounds(10, 11, 441, 318);
;
}
}
Change the line where you draw the oval in the lines of code:
By:
So you draw on top of the window that has the image. Or the other option is to first draw the oval on the image and then paint the image, you would have to change the order of the lines in the mouse event.