本文介绍了使用 Canvas 在 Java 中绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 Java 的 Canvas 中绘图但无法使用它,因为我不知道我在做什么.这是我的简单代码:
I want to draw in Java's Canvas but can't get it work because I don't know what I'm doing. Here's my simple code:
import javax.swing.JFrame;
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Color;
public class Program
{
public static void main(String[] args)
{
JFrame frmMain = new JFrame();
frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmMain.setSize(400, 400);
Canvas cnvs = new Canvas();
cnvs.setSize(400, 400);
frmMain.add(cnvs);
frmMain.setVisible(true);
Graphics g = cnvs.getGraphics();
g.setColor(new Color(255, 0, 0));
g.drawString("Hello", 200, 200);
}
}
窗口上没有显示任何内容.
Nothing appears on the window.
我是否错误地认为 Canvas 是一张纸而 Graphics 是我的铅笔?是这样操作的吗?
Am I wrong to think that Canvas is a paper and Graphics is my Pencil? Is that how it works?
推荐答案
建议:
- 不要使用 Canvas,因为您不应该将 AWT 与 Swing 组件不必要地混合在一起.
- 改为使用 JPanel 或 JComponent.
- 不要通过在组件上调用
getGraphics()
来获取 Graphics 对象,因为获取的 Graphics 对象将是瞬态的. - 在 JPanel 的
paintComponent()
方法中绘制. - 所有这些都在很容易找到的几个教程中得到了很好的解释.在尝试猜测这些东西之前,为什么不先阅读它们?
- Don't use Canvas as you shouldn't mix AWT with Swing components unnecessarily.
- Instead use a JPanel or JComponent.
- Don't get your Graphics object by calling
getGraphics()
on a component as the Graphics object obtained will be transient. - Draw in the JPanel's
paintComponent()
method. - All this is well explained in several tutorials that are easily found. Why not read them first before trying to guess at this stuff?
关键教程链接:
- 基础教程:课程:执行自定义绘画
- 更多高级信息:在 AWT 和 Swing 中绘画
这篇关于使用 Canvas 在 Java 中绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!