drawing on a jpanel
I am trying to make a jpanel that has a paint method in it, and has images in that method..
so here's the class that i created
publicclass CanvasPanelextends JPanel{
Image[] images =new Image[10];
int frame = 0;
public CanvasPanel(){
setSize(200,200);
images[0] = Toolkit.getDefaultToolkit().getImage("1.gif");
}
publicvoid paintComponent (Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g.drawImage(images[0], 0, 0,this);
g2.fillRect(0,0,50,50);
g2.drawLine(0,0,350,450);
g.drawString("String", 0, 20);
}
}
I also tried using paint method, but nothing's working...
and I am adding this panel to another class that extends JApplet
so, that class has a panel in it, that adds the panel from that above class..
but it does not show drawing..
I tried many different ways, but..
wondering if anyone can fix this for me?>
I would be really thankful =P
[1536 byte] By [
verostikaa] at [2007-11-26 21:10:55]

> i can just see a blank panel, with nothing on it...
Here is your code with a really nasty main() method added so it can be compiled
and run:import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class CanvasPanel extends JPanel {
Image[] images = new Image[10];
int frame = 0;
public CanvasPanel() {
setSize(200,200);
images[0] = Toolkit.getDefaultToolkit().getImage("1.gif");
}
public void paintComponent (Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g.drawImage(images[0], 0, 0, this);
g2.fillRect(0,0,50,50);
g2.drawLine(0,0,350,450);
g.drawString("String", 0, 20);
}
public static void main(String args[]) {
JFrame test = new JFrame("Test");
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.add(new CanvasPanel());
test.setVisible(true);
}
}
When run the rectangle, line and image all appear. If you don't see them,
then the problem is with the code you haven't posted yet.
A few thoughts:
There is no explicit repaint() call in this code: generally you let the runtime decide
what needs repainting and when. repaint() is useful when you want to inform the
runtime that something needs repainting because it has changed.
Why is this thing a panel, and not a component? As the API documentation says "A
component is an object having a graphical representation that can be displayed on
the screen and that can interact with the user". We use a panel when we want a
thing that we can attach other components to. If you start attaching other
components to this panel it will interfere with the paintComponent() code.
(Finally, this should have been posted in the Swing forum, where more
knowledgable help is available. You've started here, so that's OK - but it's in
everybody's interests if questions are directed to the right place.)