Hello,
I have a program that I want to draw different graphics depending on which
button is pressed.
I have set up all of the GUI and the ActionListeners for the buttons but I'm
not sure how to draw the graphics without having to use the method:
public void paintComponent(Graphics comp) {}
For example when the button with the text "rectangle" is pressed, I want to
draw a rectangle graphic on the screen. I have tried this simply adding this
code into the ActionListener. The code compiles but on runtime throughs a
java.lang.NullPointerException.
Graphics comp;
Graphics2D comp2D;
comp2D = (Graphics2D) comp;
Rectangle2D.Float rr = new Rectangle2D.Float(245F, 65F, 200F, 100F);
comp2D.fill(rr);
If any one knows of how to draw graphics from an Action rather than just
drawing them when the prgram starts running or knows where a good tutorial
may be it would be greatly appreciated.
Many thanks
Ryan Stewart - 02 Feb 2004 23:34 GMT
> Hello,
> I have a program that I want to draw different graphics depending on which
[quoted text clipped - 19 lines]
>
> Many thanks
Drawing from within an Event method is not a good idea. And even if you got
it working, what good would it do? As soon as your GUI is repainted, it will
disappear. I'm not sure, but that would probably be almost instantly.
One way to get the effect you're looking for would be to declare an instance
variable of type Shape which will hold which shape you want to draw. Then
override the paintComponent method like so:
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (shape != null) {
((Graphics2D)g).fill(shape);
}
}
That will cause your shape to be drawn any time the GUI is repainted, which
is necessary if you ever want to see it. Then, obviously, in your Event
handlers, you set your shape variable to whatever shape you want to draw.