2012-03-08 351 views
9

我想绘制Java的Canvas,但无法使它工作,因为我不知道自己在做什么。以下是我的简单代码:使用Canvas使用Java绘图

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是一张纸,图形是我的铅笔?它是如何工作的?

+0

你只是想绘制图形? – John 2012-03-08 04:03:55

回答

31

建议:

  • 不要使用画布,你不应该与Swing组件混合不必要AWT。
  • 改为使用JPanel或JComponent。
  • 不要因为Graphics对象获得的将是短暂的一个组件上调用getGraphics()让你的图形对象。
  • 在JPanel的paintComponent()方法中绘制。
  • 所有这些在很多容易找到的教程中都有很好的解释。为什么不在猜测这些东西之前先阅读它们?

主要教程链接:

+5

谢谢!我确实在网上搜索。是的,他们很容易找到,但不容易理解。 – dpp 2012-03-08 04:51:53

+0

希望我可以放弃对每个点的赞赏,但似乎不使用Canvas for Swing首先占有重要的地位。 – 2012-03-08 08:04:33

+0

+1好的答案,我认为这个信息有助于提问 – John 2012-03-09 02:18:52

6

你得重写你的画布的paint(Graphics g)方法,有执行绘图。见the paint() documentation.

正如它指出,默认操作是清除画布,所以你到画布图形调用对象不执行你所期望的。

1

为什么第一种方式行不通。画布对象被创建并且尺寸被设置并且图形被设置。我总是觉得这很奇怪。此外,如果一个类扩展JComponent的可以覆盖

paintComponent(){ 
    super... 
} 

,然后你不应该能够创建和实例类的另一个类的内部,然后就打电话NewlycreateinstanceOfAnyClass.repaint();

我已经试过这种方法对于一些游戏编程,我一直在努力,它似乎并不像我认为的那样工作。

道格Hauf

1

下面应该工作:

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