我一直在为我的一个课程编写蛇程序。除一个小问题外,它运行得很好:在View中(扩展JLabel),在构造函数中将背景设置为Color.WHITE,将opaque设置为true,将边框设置为Color.GREEN。这些行似乎都没有影响GUI。

这是代码:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.BorderFactory;
import javax.swing.JLabel;

public class View extends JLabel {
    private Snake snake;
    private Fruit fruit;
    private Game game;

    public View(int size, Game g) {
        int W = Game.SIZE * Snake.SIZE;
        int H = Game.SIZE * Snake.SIZE;
        this.setOpaque(true);
        this.setBounds((Game.WIDTH-W)/2, (Game.HEIGHT-H)/2, W, H);
        this.setBackground(Color.WHITE);
        this.setBorder(BorderFactory.createLineBorder(Color.GREEN));
        snake = new Snake(Snake.SIZE, Snake.SIZE);
        fruit = new Fruit();
        game = g;

    }

    public void start() {
        boolean flag = true;
        snake.start();

        while(flag) {
            snake.move();
            repaint();
            try {
                Thread.sleep(100);
            }catch(Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void move(int dir) {
        snake.move(dir);
    }

    public void doDrawing(Graphics2D g) {
        int s = snake.SIZE;
        int fx = fruit.getX();
        int fy = fruit.getY();
        g.setColor(Game.SNAKE_COLOR);
        Snake sn = snake;
        boolean flag = true;
        while(flag) {
            g.fillRect(sn.getX(), sn.getY(), s, s);
            if(sn.hasTail()) {
                sn = sn.getTail();
            }
            else flag = false;
        }

        g.setColor(Game.FRUIT_COLOR);
        g.fillRect(fx, fy, s, s);

        if(snake.getX() == fx && snake.getY() == fy) {
            snake.ate();
            fruit.create();
        }
    }

    public void paint(Graphics g) {
        game.repaint();
        Graphics2D d = (Graphics2D) g;
        doDrawing(d);
    }
}

最佳答案

您正在重写paint方法,但是永远不要调用super.paint()来让父类执行其绘画操作。 More information available here.

其他一些改进建议:


而不是使用paint(),您应该覆盖paintComponent(),并在方法的第一行中调用父绘制例程super.paintComponent(g)
您可能考虑扩展JPanelJComponent而不是JLabel,因为您似乎没有使用此类的任何功能。
不要在您的绘画方法中调用重绘

07-24 09:45
查看更多