【问题标题】:How to add icon to JFrame [duplicate]如何将图标添加到JFrame [重复]
【发布时间】:2025-12-28 13:40:11
【问题描述】:

如何在这个贪吃蛇游戏中添加一个图标,我应该把它放在哪里,以及在这么多点之后如何提高游戏速度?下面的代码是我认为这两段代码应该放在的类。

    import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.swing.JFrame;


public class SnakeGame extends JFrame {


    private static final long FRAME_TIME = 1000L / 50L;

    private static final int MIN_SNAKE_LENGTH = 5;

    private static final int MAX_DIRECTIONS = 3;

    private BoardPanel board;

    private SidePanel side;

    private Random random;

    private Clock logicTimer;

    private boolean isNewGame;

    private boolean isGameOver;

    private boolean isPaused;

    private LinkedList<Point> snake;

    private LinkedList<Direction> directions;

    private int score;

    private int foodsEaten;

    private int nextFoodScore;

    private SnakeGame() {
        super("Snake");
        setLayout(new BorderLayout());
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);

        this.board = new BoardPanel(this);
        this.side = new SidePanel(this);

        add(board, BorderLayout.CENTER);
        add(side, BorderLayout.EAST);

        addKeyListener(new KeyAdapter() {

            @Override
            public void keyPressed(KeyEvent e) {
                switch(e.getKeyCode()) {

                case KeyEvent.VK_W:
                case KeyEvent.VK_UP:
                    if(!isPaused && !isGameOver) {
                        if(directions.size() < MAX_DIRECTIONS) {
                            Direction last = directions.peekLast();
                            if(last != Direction.South && last != Direction.North) {
                                directions.addLast(Direction.North);
                            }
                        }
                    }
                    break;


                case KeyEvent.VK_S:
                case KeyEvent.VK_DOWN:
                    if(!isPaused && !isGameOver) {
                        if(directions.size() < MAX_DIRECTIONS) {
                            Direction last = directions.peekLast();
                            if(last != Direction.North && last != Direction.South) {
                                directions.addLast(Direction.South);
                            }
                        }
                    }
                    break;

                case KeyEvent.VK_A:
                case KeyEvent.VK_LEFT:
                    if(!isPaused && !isGameOver) {
                        if(directions.size() < MAX_DIRECTIONS) {
                            Direction last = directions.peekLast();
                            if(last != Direction.East && last != Direction.West) {
                                directions.addLast(Direction.West);
                            }
                        }
                    }
                    break;

                case KeyEvent.VK_D:
                case KeyEvent.VK_RIGHT:
                    if(!isPaused && !isGameOver) {
                        if(directions.size() < MAX_DIRECTIONS) {
                            Direction last = directions.peekLast();
                            if(last != Direction.West && last != Direction.East) {
                                directions.addLast(Direction.East);
                            }
                        }
                    }
                    break;

                case KeyEvent.VK_P:
                    if(!isGameOver) {
                        isPaused = !isPaused;
                        logicTimer.setPaused(isPaused);
                    }
                    break;

                case KeyEvent.VK_ENTER:
                    if(isNewGame || isGameOver) {
                        resetGame();
                    }
                    break;
                }
            }

        });


        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }


    private void startGame() {

        this.random = new Random();
        this.snake = new LinkedList<>();
        this.directions = new LinkedList<>();
        this.logicTimer = new Clock(10.0f);
        //////////////////////////////////////////////////////////////////////////////////////////////////
        this.isNewGame = true;


        logicTimer.setPaused(true);

        while(true) {
            long start = System.nanoTime();

            logicTimer.update();

            if(logicTimer.hasElapsedCycle()) {
                updateGame();
            }

            board.repaint();
            side.repaint();

            long delta = (System.nanoTime() - start) / 1000000L;
            if(delta < FRAME_TIME) {
                try {
                    Thread.sleep(FRAME_TIME - delta);
                } catch(Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    private void updateGame() {

        TileType collision = updateSnake();

        if(collision == TileType.Food) {
            foodsEaten++;
            score += nextFoodScore;
            spawnFood();
        } else if(collision == TileType.SnakeBody) {
            isGameOver = true;
            logicTimer.setPaused(true);
        } else if(nextFoodScore > 10) {
        }
    }


    private TileType updateSnake() {


        Direction direction = directions.peekFirst();               

        Point head = new Point(snake.peekFirst());
        switch(direction) {
        case North:
            head.y--;
            break;

        case South:
            head.y++;
            break;

        case West:
            head.x--;
            break;

        case East:
            head.x++;
            break;
        }


        if(head.x < 0 || head.x >= BoardPanel.COL_COUNT || head.y < 0 || head.y >= BoardPanel.ROW_COUNT) {
            return TileType.SnakeBody;
        }


        TileType old = board.getTile(head.x, head.y);
        if(old != TileType.Food && snake.size() > MIN_SNAKE_LENGTH) {
            Point tail = snake.removeLast();
            board.setTile(tail, null);
            old = board.getTile(head.x, head.y);
        }


        if(old != TileType.SnakeBody) {
            board.setTile(snake.peekFirst(), TileType.SnakeBody);
            snake.push(head);
            board.setTile(head, TileType.SnakeHead);
            if(directions.size() > 1) {
                directions.poll();
            }
        }

        return old;
    }


    private void resetGame() {

        this.score = 0;
        this.foodsEaten = 0;


        this.isNewGame = false;
        this.isGameOver = false;

        Point head = new Point(BoardPanel.COL_COUNT / 2, BoardPanel.ROW_COUNT / 2);


        snake.clear();
        snake.add(head);

        board.clearBoard();
        board.setTile(head, TileType.SnakeHead);

        directions.clear();
        directions.add(Direction.North);

        logicTimer.reset();

        spawnFood();
    }


    public boolean isNewGame() {
        return isNewGame;
    }


    public boolean isGameOver() {
        return isGameOver;
    }


    public boolean isPaused() {
        return isPaused;
    }


    private void spawnFood() {
        this.nextFoodScore = 10;

        int index = random.nextInt(BoardPanel.COL_COUNT * BoardPanel.ROW_COUNT - snake.size());

        int freeFound = -1;
        for(int x = 0; x < BoardPanel.COL_COUNT; x++) {
            for(int y = 0; y < BoardPanel.ROW_COUNT; y++) {
                TileType type = board.getTile(x, y);
                if(type == null || type == TileType.Food) {
                    if(++freeFound == index) {
                        board.setTile(x, y, TileType.Food);
                        break;
                    }
                }
            }
        }
    }


    public int getScore() {
        return score;
    }


    public int getFoodsEaten() {
        return foodsEaten;
    }


    public int getNextFoodScore() {
        return nextFoodScore;
    }


    public Direction getDirection() {
        return directions.peek();
    }

    public static void main(String[] args) {
        SnakeGame snake = new SnakeGame();
        snake.startGame();
    }

}

【问题讨论】:

  • “我如何在这个贪吃蛇游戏中添加一个图标,我应该把它放在哪里,..” 你从JFrame 的 Java 文档中发现了什么? “..还有我如何提高速度..” SO 不是帮助台,而是一个问答网站,每个线程都应该有一个问题,至少有一个明确的答案。如果您有两个问题,请启动两个问题线程。

标签: java performance swing icons


【解决方案1】:

像这样创建一个新的 ImageIcon 对象:

ImageIcon img = new ImageIcon(pathToFileOnDisk);

然后使用 setIconImage() 将其设置为您的 JFrame:

myFrame.setIconImage(img.getImage());

还可以检查 setIconImages() ,它采用 List 代替。

How to change JFrame icon

这不是我的答案!!!!

【讨论】: