有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在Java中初始化图形?

我有一些这样的代码:

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类做什么,解释一下会有帮助


共 (2) 个答案

  1. # 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. # 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);
    }
    

    对不起,如果我在田野里弄错了。我记不得了