Question about graphics in Java?
I am trying to learn how to do graphics in java and I've written a simple program which does not work as I wish. I have one class called MyCanvas which extends JPanel and is the "surface" which I am trying to draw on. I have another class which creates a frame and an instance of MyCanvas and adds that object to the frame. I see the red circle which is drawn when paint is called which happens when the object is added to the frame. I do not see the blue circle when i call the drawOval method from MyCanvas though. The graphics object is defined in MyCanvas though. I have tried using both the update method and the repaint method. Neither work. Any help?
import java.awt.*;
import javax.swing.*;
public class Test {
JFrame frame;
MyCanvas canvas;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Test();
}
public Test(){
frame = new JFrame("Test");
canvas = new MyCanvas();
//Sets conditions for frame
frame.add(canvas);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
//Should draw blue circle on screen
canvas.drawOval(10,10,100,100);
}
}
------------------------------------------------------------------------------------------------------
import java.awt.*;
import javax.swing.*;
public class MyCanvas extends JPanel {
public MyCanvas(){
super();
}
public void drawOval(int x, int y, int width, int height){
Graphics g = getGraphics();
g.setColor(Color.blue);
g.fillOval(x,y,width,height);
update(g);
}
public void paint(Graphics g) {
g.setColor(Color.red);
g.fillOval(100, 100, 200, 200);
}
}
@Teku I know the canvas size is not 0x0. First off I can see the red circle which is being painted by the paint method when I add the object to the frame. Second I previously thought this may be a problem and defined the size to fit the frame and still not blue circle. I merely took that out to be more succinct but I believe it automatically makes the panel the size of the frame unless otherwise specified.
@anuk Even removing update/repaint doesn't help. I know I could just do this all in paint but I don't want to do that. I'm trying to cause the component to update without using paint. Other programs must do this. There is no way some advanced programs in Java could handle every bit of graphics in the paint method. So I'm trying to find a way to do that.