Java图形无法执行绘画功能而无需扩展 [英] Java Graphics Not Executing Paint Function Without extends
问题描述
我一直在与Java的图形系统作斗争(或很多),我一直在研究用于绘制Java图形的文档和教程.
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.
我发现的每个示例似乎都有一个主类,该主类扩展了JPanel,然后调用自身以某种方式执行paint函数.
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.
如果我尝试
Graphics graphic = new Graphics();
paint(graphic);
这是行不通的,因为它抱怨类是抽象的.
It doesn't work because it's complaining about the class being abstract.
推荐答案
是否可以完全不使用扩展来绘制图形?
Is it possible to draw graphics without using extends at all?
是的,肯定有可能.正如@HovercraftFullOfEels在评论中提到的:
Yes, it sure is possible. As mentioned by @HovercraftFullOfEels in a comment:
您可以在
BufferedImage
上绘制..
如果您在 JLabel
中显示该图像(将其称为 label
),则要在图像更改后更新屏幕,只需调用:
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();
这篇关于Java图形无法执行绘画功能而无需扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!