Java Graphics Not Executing Paint Function Without extends

耗尽温柔 提交于 2021-01-28 04:20:48

问题


I've been battling a bit (or a lot) with Java's Graphics, I've been going through the documentation and tutorials for drawing Java Graphics.

Every example I've found seems to have a main class that extends a JPanel and then calls itself which executes the paint function somehow.

Is it possible to draw graphics without using extends at all? I have a basic program

import javax.swing.*;
import awt.Graphics;

public class basicWindow {

    public static void main(String[] args) {

        JFrame frame = new JFrame();
        frame.setTitle("Basic Window");
        frame.setSize(300, 300);
        frame.setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);

        JPanel panel = new JPanel();

        frame.add(panel);

        frame.setVisible(true);

    }

    public void paint(Graphics g) {

        g.fillRect(5, 15, 50, 75);

    }

}

This opens a window but doesn't draw anything which I was I expect because I don't know how to execute the paint function.

If I try

Graphics graphic = new Graphics();

paint(graphic);

It doesn't work because it's complaining about the class being abstract.


回答1:


Is it possible to draw graphics without using extends at all?

Yes, it sure is possible. As mentioned by @HovercraftFullOfEels in a comment:

You can draw on a BufferedImage..

If you display that image in a JLabel (lets call it label) then to get the screen to update after the image has changed, simply call:

label.repaint();



回答2:


You will want to read the tutorials and follow them. Java Swing uses passive graphics, and your code needs to respect this.

  • As per the tutorials, have your drawing class extend JPanel.
  • Draw within the paintComponent method override
  • Don't forget the @Override annotation.

Regarding,

Is it possible to draw graphics without using extends at all?

  • You can draw on a BufferedImage and display that within the paintComponent method. This still requires that you extend the component.
  • You can draw with a Graphics object obtained by calling getGraphics() on a component, however if you do this, the image will not be stable, and you risk throwing a NPE, and so this is not recommended.


来源:https://stackoverflow.com/questions/35484267/java-graphics-not-executing-paint-function-without-extends

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!