Reputation: 11
I'm trying to add an ImageIcon to a panel through paintComponent, but it doesn't work. The panel i'm trying to add it to is set to a GridLayout. Could this be why? or is it being drawn over? Or my path could be set incorrectly... I've never
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Frame implements MouseListener, KeyListener {
JFrame f = new JFrame();
JPanel p = new JPanel();
JPanel[][] panel = new JPanel[10][10];
int k = 1;
Color previous;
ImageIcon icon = new ImageIcon("/Users/Admin/Desktop/stickFigure.jpg");
static String title = "Grid World";
public Frame(String s) {
f.setTitle(s);
p.setLayout(new GridLayout(10, 10));
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
panel[i][j] = new JPanel();
p.add(panel[i][j], i, j);
panel[i][j].addMouseListener(this);
panel[i][j].setBackground(Color.WHITE);
}
}
p.setSize(500, 500);
f.add(p);
f.setSize(490, 492);
f.setVisible(true);
f.setResizable(false);
f.setDefaultCloseOperation(3);
f.addKeyListener(this);
f.setLocationRelativeTo(null);
}
public void paintComponent(Graphics g) {
icon.paintIcon(f, g, 100, 100);
}
Upvotes: 1
Views: 3158
Reputation: 285450
You've got a paintComponent method in a class that does not extend JPanel, JComponent or any similar object, and thus it will never be called and serve no purpose. If you want paintComponent to work as intended, it must be in a class that extends JComponent or one of its children such as JPanel. And then you must use that JPanel in your GUI. Please read the Swing painting tutorials to see how to do this correctly.
Edit
Another way to display an ImageIcon is to simply add it to a JLabel and then display the JLabel in a Swing GUI.
Edit 2
Also, even if your class extended JPanel, it still wouldn't work since your icon is never added to anything. I've not seen graphics done as you're doing -- by calling the icon's paintIcon(...)
method. I can't say that it's wrong; just that I haven't seen done this way.
Upvotes: 3