Reputation: 11
How can I draw on JLabel with icon? In my code oval replaced the image, there is only oval and canvas, not image. I want to draw on image. What should I do?
public void go() {
String IMAGE_PATH = "start_phone.jpg";
URL imgUrl = getClass().getResource(IMAGE_PATH);
JFrame frame = new JFrame();
JPanel panel = new JPanel();
MyLabel imageLabel = new MyLabel();
ImageIcon icon = new ImageIcon(getClass().getResource(IMAGE_PATH));
imageLabel.setIcon(icon);
imageLabel.add(panel);
frame.add(imageLabel);
frame.setSize(1200, 1200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class MyLabel extends JLabel {
public void paintComponent(Graphics g) {
g.setColor(Color.green);
g.fillOval(100, 100, 100, 100);
}
}
Upvotes: 0
Views: 2086
Reputation: 347184
If all you want to do is draw onto the icon, then use a BufferedImage
, for example...
try {
BufferedImage phone = ImageIO.read(Main.class.getResource("/test/phone.png"));
Graphics2D g2d = phone.createGraphics();
g2d.setColor(Color.RED);
g2d.fillOval(phone.getWidth() - 17, 0, 16, 16);
g2d.dispose();
JLabel label = new JLabel("Phone");
label.setIcon(new ImageIcon(phone));
JOptionPane.showMessageDialog(null, label);
} catch (IOException ex) {
ex.printStackTrace();
}
In your code, you could either load the image directly as a BufferedImage
, as the example above does, or load it as a ImageIcon
and paint that onto a new BufferedImage
, depending on your needs
If, instead, you want to paint onto of the label, well, that's more complicated. Remember a JLabel
is a complex component, with icon, text and placement logic. The problem with all this is, you can't gain access to the information used to layout individual elements.
The important thing is, call super.paintComponent
. This is actually painting the icon and text...
public static class ExampleLabel extends JLabel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.RED);
g2d.fillOval(getWidth() - 17, 0, 16, 16);
g2d.dispose();
}
}
and then simply use it...
try {
BufferedImage phone = ImageIO.read(Main.class.getResource("/test/phone.png"));
JLabel label = new ExampleLabel();
label.setText("Phone");
label.setIcon(new ImageIcon(phone));
JOptionPane.showMessageDialog(null, label);
} catch (IOException ex) {
ex.printStackTrace();
}
So, the answer to your question is, it depends on what you want to achieve...
Upvotes: 2