【问题标题】:How to initialise graphics in Java?如何在 Java 中初始化图形?
【发布时间】:2013-10-30 12:38:55
【问题描述】:

我有一些这样的代码:

public void paintComponent(Graphics graphics){
    graphics.setColor(Color.WHITE);
    for (GameObject object : GameArea.objects){
        graphics.fillRect(object.position.x, object.position.y,object.width, object.height);
    }
    graphics.setColor(Color.BLUE);
    graphics.fillRect(GameArea.square.position.x,GameArea.square.position.y,GameArea.square.width, GameArea.square.height);
    for(GameObject object2 : GameArea.objects){
       graphics.fillRect(object2.position.x, object2.position.y,object2.width, object.height);
    }
}

它在一个名为 FieldPanel 的类中。我从 MainGame 类中这样调用它:

Timer t = new Timer(50, new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                //The following line does not work:
                fieldPanel.paintComponent(Graphics g);
            }
});

但是,行不通的线路给我带来了问题。如何创建新的图形对象以传递给其他类的方法?而且,当我创建它时,它应该具有哪些属性等?我不完全确定 Graphics 类的作用,解释会有所帮助。

【问题讨论】:

  • 1) 为了尽快获得更好的帮助,请发帖 SSCCE。 2) 对代码块使用一致且符合逻辑的缩进。代码的缩进是为了帮助人们理解程序流程。

标签: java graphics paint init


【解决方案1】:

paintComponent(Graphics g) 方法自动调用。你不能在任何地方调用它。但是如果你想绘制新的图形,你可以像这样在 fieldPanel 中使用repaint() 方法。

fieldPanel

public void draw(){
   GameArea.add(new GameObject());
   repaint();
}

MainGame

  Timer t = new Timer(50, new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent e) {
                    fieldPanel.draw();
                }
    });

【讨论】:

    【解决方案2】:

    您可以使用双重缓冲。把它放在你的课堂上

    BufferedImage bmp = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
    Graphics gf = bmp.getGraphics();
    

    并使用此 gf 进行绘图。 使用计时器重绘您的 JComponent

      Timer t = new Timer(50, new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        yourJComponent.repaint();
                    }
        });
    

    并像您的第一个代码清单一样覆盖 paintComponent() 方法:

    public void paintComponent(Graphics graphics){
       graphics.drawImage(bmp,
       0, 0, yourJComponent.width, yourJComponent.height,
       0, 0, bmp.width, bmp.height,
       null);
    }
    

    对不起,如果我在字段中弄错了。我不记得了。

    【讨论】:

      猜你喜欢
      • 2012-11-09
      • 1970-01-01
      • 1970-01-01
      • 2011-02-03
      • 2018-08-29
      • 1970-01-01
      • 1970-01-01
      • 2016-11-23
      • 1970-01-01
      相关资源
      最近更新 更多