Reputation: 79
So, i have a class called MainClass in which extends Canvas. I am trying to let's say draw a filled rectangle on the Canvas without Overriding the paint method. Is there a way to do that or i must override the paint method and put all i want to draw there?
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
public class MainClass extends Canvas {
MainClass()
{
JFrame MainWindow = new JFrame("Main Window");
MainWindow.setVisible(true);
MainWindow.setSize(500, 500);
MainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MainWindow.add(this);
}
public void paint(Graphics g)
{
super.paint(g);
}
public static void main(String[] args)
{
MainClass temp = new MainClass();
Graphics g = (Graphics2D)temp.getGraphics();
g.setColor(Color.red);
g.fillRect(0, 0, 400, 400);
temp.repaint();
}
}
The idea is that i have this class and i can get the graphic object of the canvas and draw on it directly and repaint. Or maybe i was thinking of passing shapes and objects into a method that will do the painting at certain position for me.
Upvotes: 1
Views: 3134
Reputation: 285403
getGraphics()
on a component, you will obtain a short-lived Graphics context that might work right at that time, but will fail to work if any repaints occur (and these are not under your control), leading to either a program graphics failure or a NullPointerException. You should avoid doing this unless you have dire need and know what you're doing. To "know what you're doing", read the book Filthy Rich Clients by Haase and Guy.paintComponent(...)
method override.Upvotes: 4