在绘制使用Canvas的Java [英] Drawing in Java using Canvas
本文介绍了在绘制使用Canvas的Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在Java的帆布画,但不能得到它的工作怎么我不知道我在做什么。这里是我的简单code:
I want to draw in Java's Canvas but can't get it work coz 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是一张纸,图形是我的铅笔吗?是,它是如何工作?
Am I wrong to think that Canvas is a paper and Graphics is my Pencil? Is that how it works?
推荐答案
建议:
- 请不要使用画布,你不应该与Swing组件混合不必要的AWT。
- 而是使用一个JPanel或者JComponent的。
- 请不要通过调用让您的Graphics对象
的getGraphics()
为得到的图形对象将是短暂的一个组件。 - 绘制在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?
关键环节教程:
- Basic Tutorial: Lesson: Performing Custom Painting
- More advanced information: Painting in AWT and Swing
这篇关于在绘制使用Canvas的Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文