将jLabel移到jPanel中的其他位置(类似Pacman的游戏) [英] Moving jLabel to a different place in the jPanel (Pacman like game)

查看:91
本文介绍了将jLabel移到jPanel中的其他位置(类似Pacman的游戏)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作类似pacman的游戏,到目前为止,我只是从网格开始.我开始使用网格,但是我需要弄清楚如何将某些东西移动到网格中的其他位置,以便当用户单击或我的幻影移动时,它将显示在屏幕上.我该如何移动?我尝试了很多不同的方法,但是没有一种对我有用.

I'm making a game like pacman and so far I am just starting with the grid. I got the grid started but I need to figure out how to move something to a different place in the grid so that when the user clicks or my ghosts move, it will display on the screen. How do I make it move? I have tried a bunch of different ways but none worked for me.

import java.awt.*;

import javax.swing.*;
import javax.swing.border.BevelBorder;


public class GUI {

public static void main(String[] args) {
    final JFrame f = new JFrame("Frame Test");
    GridLayout Layout = new GridLayout(50,50);

    JPanel panel = new JPanel(new GridLayout(50, 50, 1, 1));

    //Not sure if I need this or not?
    //panel.setLayout(new GridBagLayout());

    //first set of black
    for (int i = 0; i < 1000; i++) {
        JLabel a = new JLabel(new ImageIcon("black-square.jpg"), JLabel.CENTER);
        panel.add(a);

    }

    //adds pacman
    JLabel b = new JLabel(new ImageIcon("pacman.png"), JLabel.CENTER);
    panel.add(b);

    //next set of black
    for (int i = 0; i < 1000; i++) {
        JLabel c = new JLabel(new ImageIcon("black-square.jpg"), JLabel.CENTER);
        panel.add(c);
    }


   //do the thing 
    f.setContentPane(panel);
    f.setSize(1000, 1000);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);


}

}

推荐答案

首先查看如何使用Swing计时器

您将要遇到的下一个问题是容器处于LayoutManager的控制之下.虽然可以使用它来实现移动,但是它会很块状,因为每个组件都会跳出单元格.

The next problem you're going to have is the fact that the container is under the control of a LayoutManager. While it's possible to achieve movement using this, it will be blocky, as each component will jump cells.

如果要平滑移动,则必须设计自己的布局逻辑,这可能会非常复杂.

If you want smooth movement, you're going to have to devise your own layout logic, this can be very complicated.

同样,您应该瞄准的是保持游戏的虚拟"视角.这样,您无需与UI进行大量比较即可了解迷宫的形状和角色的位置.然后,您应该简单地呈现此虚拟"视图或模型的状态

None the less, what you should be aiming for is maintaining the a "virtual" view of the game. This allows you to know the shape of the maze and the position of the characters without need to do a lot of comparisons with the UI. You should then simply render the state of this "virtual" view or model

已更新为VERY BASIC示例

这是一个基本示例,它使用GridLayoutsetComponentZOrder移至面板周围的组件...没有碰撞检测,并且"AI"很可悲...

This is a basic example, which uses a GridLayout and setComponentZOrder to move to components about the panel...There is no collision detection and the "AI" is pathetic...

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class PacMan101 {

    public static void main(String[] args) {
        new PacMan101();
    }

    public PacMan101() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new MazePane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class MazePane extends JPanel {

        private JLabel pacMan;
        private JLabel ghost;

        public MazePane() {
            pacMan = new JLabel(new ImageIcon(getClass().getResource("/PacMan.png")));
            ghost = new JLabel(new ImageIcon(getClass().getResource("/Ghost.png")));

            setLayout(new GridLayout(8, 8));
            add(pacMan);

            for (int index = 1; index < (8 * 8) - 1; index++) {
                add(new JPanel() {

                    @Override
                    public Dimension getPreferredSize() {
                        return new Dimension(32, 32);
                    }

                });
            }

            add(ghost);

            Timer timer = new Timer(500, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    move(pacMan);
                    move(ghost);
                    revalidate();
                    repaint();
                }

                protected void move(Component obj) {
                    int order = getComponentZOrder(obj);
                    int row = order / 8;
                    int col = order - (row * 8);

                    boolean moved = false;
                    while (!moved) {
                        int direction = (int) (Math.round(Math.random() * 3));
                        int nextRow = row;
                        int nextCol = col;
                        switch (direction) {
                            case 0:
                                nextRow--;
                                break;
                            case 1:
                                nextCol++;
                                break;
                            case 2:
                                nextRow++;
                                break;
                            case 3:
                                nextCol--;
                                break;
                        }

                        if (nextRow >= 0 && nextRow < 8 && nextCol >= 0 && nextCol < 8) {
                            row = nextRow;
                            col = nextCol;
                            moved = true;
                        }
                    }

                    order = (row * 8) + col;
                    setComponentZOrder(obj, order);

                }
            });
            timer.start();
        }

    }

}

这篇关于将jLabel移到jPanel中的其他位置(类似Pacman的游戏)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆