user3689034
user3689034

Reputation: 79

JAVA - Help drawing on an extending canvas

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

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

  1. Don't use a Canvas.
  2. Instead extend JPanel
  3. And override the JPanel's paintComponent method, not the paint method (and why not override the methods? What is your objection to painting inside of them?).
  4. Google the Java Swing painting tutorials and go through them. Here's the link.
  5. By calling 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.
  6. Note that you could always draw directly on a BufferedImage using a Graphics object derived from the image, but then you still should draw the BufferedImage in your paintComponent(...) method override.

Upvotes: 4

Related Questions