我正在尝试在 JLabel 中加载任何地图的图像,当单击此地图时,会在我单击的位置准确绘制“指针”,并使用新指针编辑此图像,为此我使用的是 MouseListener ,但我的程序单击时不绘制任何内容。
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);
;
}
}
更改在代码行中绘制椭圆的行:
经过:
因此,您在具有图像的窗口顶部绘制。或者另一种选择是首先在图像上绘制椭圆然后绘制图像,您必须更改鼠标事件中线条的顺序。