使用Canvas在Java中绘图

我想用Java的Canvas画画,但不能让它工作,因为我不知道我在做什么。 这是我的简单代码:

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); } } 

窗口上没有任何内容。

我觉得Canvas是纸,而Graphics是我的铅笔,我错了吗? 它是如何工作的?

建议:

  • 不要使用Canvas,因为您不应该不必要地将AWT与Swing组件混合使用。
  • 而是使用JPanel或JComponent。
  • 不要通过在组件上调用getGraphics()来获取Graphics对象,因为获得的Graphics对象将是瞬态的。
  • 在JPanel的paintComponent()方法中绘制。
  • 所有这些都在很容易找到的几个教程中得到了很好的解释。 在尝试猜测这些东西之前,为什么不先读它们呢?

关键教程链接:

  • 基础教程: 课程:执行自定义绘画
  • 更高级的信息: AWT和Swing绘画

你必须覆盖Canvas的paint(Graphics g)方法并在那里执行绘图。 请参阅paint()文档。

正如它所述,默认操作是清除canvas,因此您对canvas的图形对象的调用不会像您期望的那样执行。

为什么第一种方式不起作用。 创建Canvas对象并设置大小并设置grahpics。 我总觉得这很奇怪。 此外,如果类扩展JComponent,您可以覆盖

 paintComponent(){ super... } 

然后你不应该在另一个类中创建类的实例,然后只需调用NewlycreateinstanceOfAnyClass.repaint();

我已经尝试过这种方法用于我一直在工作的一些游戏编程,它似乎没有像我认为的那样工作。

道格豪夫

以下应该有效:

 public static void main(String[] args) { final String title = "Test Window"; final int width = 1200; final int height = width / 16 * 9; //Creating the frame. JFrame frame = new JFrame(title); frame.setSize(width, height); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setResizable(false); frame.setVisible(true); //Creating the canvas. Canvas canvas = new Canvas(); canvas.setSize(width, height); canvas.setBackground(Color.BLACK); canvas.setVisible(true); canvas.setFocusable(false); //Putting it all together. frame.add(canvas); canvas.createBufferStrategy(3); boolean running = true; BufferStrategy bufferStrategy; Graphics graphics; while (running) { bufferStrategy = canvas.getBufferStrategy(); graphics = bufferStrategy.getDrawGraphics(); graphics.clearRect(0, 0, width, height); graphics.setColor(Color.GREEN); graphics.drawString("This is some text placed in the top left corner.", 5, 15); bufferStrategy.show(); graphics.dispose(); } }