java - 如何在Java中初始化图形?

标签 java graphics paint init

我有一些这样的代码:

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 类的作用,解释会很有帮助。

最佳答案

自动调用

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

关于java - 如何在Java中初始化图形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19682491/

相关文章:

java简单的画图程序鼠标监听器

java - 绘制 JPanel 并将 JPanel 添加到 JFrame

java - 如何绘制多条线,看起来像划分面板Java的扇区?

java - 如何从链接到 .jar 文件的 java 数组中删除值?

java - 从 Java 代码调用 Spring 组件

java - 单击 JButton 时将不同的图像绘制到 JButton

algorithm - 是否有一个好的整数线光栅化算法?

java - 为什么我的 jbutton 不再添加自己?

Java 继承设计与 HttpServlet - 会导致问题吗

java - 从 XSD 获取完整的 XML 结构