Jpanel and Canvas
My assignment is to create an image editor using Swing. I have
proceeded as follows:
1. I created a JFrame subclass myFrame, a JPanel subclass myPanel and
a canvas subclass myCanvas.
2. The instantiation of class myPanel creates a new instance of the
class myCanvas. I created a new instance of myPanel and added it to
the content pane of myFrame.
3. Now the code of class myCanvas is as follows:
class myCanvas extends Canvas {
private static final long serialVersionUID = 0;
BufferedImage img;
myPanel pane;
myCanvas(myPanel pane) {
this.pane = pane;
File imgFile = new File("chess.jpg");
try {
img = ImageIO.read(imgFile);
} catch (Exception e) {
JOptionPane.showMessageDialog(pane, "Caught Exception" + e);
}
JOptionPane.showMessageDialog(pane, img.getWidth() + "\n" +
img.getHeight());
repaint();
}
public void paint(Graphics g) {
JOptionPane.showMessageDialog(pane, "Inside paint");
g.setColor(Color.red);
g.fillRect(10, 10, 350, 350);
g.drawImage(img, 0, 0, null);
}
}
However, the problem is that the program never enters the paint()
method of the myCanvas class. I tried calling the repaint() method
from other locations of the program long after the constructor of
myCanvas had finished executing. Yet the paint function was not
entered.
Could someone please point out my mistake. I have been trying to
remove this bug for more many hours and its really driving me nuts.
Thank you in advance.