You could try painting something onto the Graphics
.
You shouldn't be loading images inside the paint
method, this will only slow down the repaints and potentially consume more resources. Load the image once and maintain a reference to it.
class Tracker extends JPanel
{
String imageFile = "areal view.JPG";
private Image image;
public Tracker()
{
super();
init();
}
public Tracker(String image)
{
super();
this.imageFile = image;
init();
}
public Tracker(LayoutManager layout)
{
super(layout);
init();
}
protected void init() {
ImageIcon imageicon = new ImageIcon(getClass().getResource(imageFile));
image = imageicon.getImage();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if (image != null) {
g.drawImage(image, 100, 50, 700, 600, this);
g.setColor(Color.RED);
g.fillOval(290, 215, 20, 20);
}
}
}
I'd recommend that you take a look at Performing Custom Painting and 2D Graphics
Update with additional example
From you comments, I would suggest using a JLayeredPane
. It will allow you to place custom components at arbitrary locations over your image.
public class Tracker {
public static void main(String[] args) {
new Tracker();
}
public Tracker() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
// 247x178
MapPane mapPane = new MapPane();
Marker marker = new Marker();
marker.setToolTipText(
"<html><table><tr><td valign=top><img src='" + getClass().getResource("/Earth.png") + "'>" +
"</td><td valign=top><b>Earth</b><br>Mostly Harmless</td></tr></table></html>"
);
marker.setSize(marker.getPreferredSize());
marker.setLocation(237, 188 - marker.getHeight());
mapPane.add(marker);
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(mapPane);
frame.setResizable(false);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class Marker extends JLabel {
public Marker() {
try {
setIcon(new ImageIcon(ImageIO.read(getClass().getResource("/Marker.png"))));
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public class MapPane extends JLayeredPane {
private BufferedImage map;
public MapPane() {
try {
map = ImageIO.read(getClass().getResource("/SolarSystem.jpg"));
} catch (Exception e) {
}
}
@Override
public Dimension getPreferredSize() {
return map == null ? super.getPreferredSize() : new Dimension(map.getWidth(), map.getHeight());
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (map != null) {
g.drawImage(map, 0, 0, this);
}
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…