用Java最简单的绘图方法是什么?
用Java最简单的绘图方法是什么?
import java.awt.*;
import javax.swing.*;
public class Canvas
{
private JFrame frame;
private Graphics2D graphic;
private JPanel canvas;
public Canvas()
{
frame = new JFrame("A title");
canvas = new JPanel();
frame.setContentPane(canvas);
frame.pack();
frame.setVisible(true);
}
public void paint(Graphics g){
BufferedImage offImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Grapics2D g2 = offImg.createGraphics();
g2.setColor(new Color(255,0,0));
g2.fillRect(10,10,200,50);
}
}
这不起作用,我不知道如何让任何东西出现。
What is the simplest way to draw in Java?
import java.awt.*;
import javax.swing.*;
public class Canvas
{
private JFrame frame;
private Graphics2D graphic;
private JPanel canvas;
public Canvas()
{
frame = new JFrame("A title");
canvas = new JPanel();
frame.setContentPane(canvas);
frame.pack();
frame.setVisible(true);
}
public void paint(Graphics g){
BufferedImage offImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Grapics2D g2 = offImg.createGraphics();
g2.setColor(new Color(255,0,0));
g2.fillRect(10,10,200,50);
}
}
This doesn't work and I have no idea how to get anything to appear.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
jjnguy 已经写了如何正确执行此操作...但这里为什么它在您的示例中不起作用:
这里您有一个与 Swing 或 AWT 没有任何关系的类。
(顺便说一下,您可能需要选择另一个名称以避免与 java.awt.Canvas 混淆。)
在这里,您将创建一个新的 JPanel(为了混淆也命名为 canvas) ),并将其添加到框架中。
这是该面板的
paint
和paintComponent
方法,当系统显示框架时调用它们。这个绘制方法根本不会被使用(因为它不是组件的一部分),如果调用它,那么您只是绘制到一些 BufferedImage,而不是绘制到屏幕。
jjnguy already wrote how to do it right ... but here why it does not work in your example:
Here you have a class which does not relate in any way to Swing or AWT.
(By the way, you may want to select another name to avoid confusion with
java.awt.Canvas
.)Here you are creating a new JPanel (for confusion also named
canvas
), and add it to the frame.Is is this panel's
paint
andpaintComponent
methods which are called when the system shows your frame.This paint method is never used at all (since it is not part of a component), and if it would be called, then you are only painting to some BufferedImage, not to the screen.
最简单的方法:
您只需扩展
JPanel
并重写面板的paintComponent
方法即可。我想重申,您不应该覆盖
paint
方法。这是一个非常简单且有效的示例。
Easiest way:
You simply need to extend
JPanel
and override thepaintComponent
method of the panel.I'd like to reiterate that you should not be overriding the
paint
method.Here is a very minimalistic example that works.
要使某些内容出现在 Paint(Graphics g) 中,您需要调用该 Graphics 上的绘图方法(如 fillRect)。您正在创建位图,然后绘制到位图,而不是屏幕。
To make something appear in paint(Graphics g) you need to call the drawing methods (like fillRect) on that Graphics. You are creating a bitmap and then drawing to the bitmap, not the screen.