首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >可以将JLabels添加到数组中吗?

可以将JLabels添加到数组中吗?
EN

Stack Overflow用户
提问于 2018-06-09 08:55:34
回答 2查看 168关注 0票数 -1

我想要清理我的代码,我想知道我是否可以将这些JLabels放到一个ArrayList中。这将用于一个do-while循环,在这个循环中,我的玩家的碰撞将被检查。

下面是GamePane类。这段代码中有移动的玩家,也有碰撞的代码。这就是我创建ArrayList的地方

代码语言:javascript
复制
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

/**
 * This class Holds the game pane that has the moving player. It also contains
 * the GamePane
 * 
 * @author 602052004
 *
 */

public class GamePane extends JPanel implements ActionListener, KeyListener {// *change GamePane to GamePane
    // This is were the game screen is made and the player is created.

    private static final long serialVersionUID = 1L;
    JLabel player = new JLabel();
    JLabel finish = new JLabel();

    // This is were the JLabels for the walls are created
    //JLabel wall1 = new JLabel();
    //ArrayList<JLabel> array = new ArrayList<>();

 ArrayList<JLabel> array = new ArrayList<>();
 array.add(wall1);
    JLabel wall1 = new JLabel();
    JLabel wall2 = new JLabel();
    JLabel wall3 = new JLabel();
    JLabel wall4 = new JLabel();
    JLabel wall5 = new JLabel();
    JLabel wall6 = new JLabel();
    JLabel wall7 = new JLabel();
    JLabel wall8 = new JLabel();
    JLabel wall9 = new JLabel();
    JLabel wall10 = new JLabel();
    JLabel wall11 = new JLabel();
    JLabel wall12 = new JLabel();
    JLabel wall13 = new JLabel();
    JLabel wall14 = new JLabel();
    JLabel wall15 = new JLabel();
    JLabel wall16 = new JLabel();
    JLabel wall17 = new JLabel();
    JLabel wall18 = new JLabel();
    JLabel wall19 = new JLabel();
    JLabel wall20 = new JLabel();
    JLabel wall21 = new JLabel();
    JLabel wall22 = new JLabel();
    JLabel wall23 = new JLabel();
    JLabel wall24 = new JLabel();
    int playerSpeed = 5;
    int FPS = 40;
    private final Set<Integer> keys = new HashSet<>();

    // The keys set holds the keys being pressed

    public static void main(String[] args) {
        // Open the GUI window
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                // Create a new object and
                // run its go() method
                new GamePane().go();
            }
        });
    }

    GamePane() {
        // Run the parent class constructor
        super();
        // Allow the panel to get focus
        setFocusable(true);
        // Don't let keys change the focus
    }

    /**
     * The frame that shows my game. It contains the game frame which holds my
     * JPanel GameStage and ButtonPane.
     */
    protected void go() {
        setLayout(new CardLayout());
        // Setup the window
        JFrame GameFrame = new JFrame();
        // Add this panel to the window
        GameFrame.setLayout(new CardLayout());
        GameFrame.add(this, "main");
        GameFrame.setContentPane(this);

        // Set's the window properties
        GameFrame.setTitle("main");
        GameFrame.setSize(800, 600);
        GameFrame.setLocationRelativeTo(null);
        GameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        GameFrame.setVisible(true);
        GameFrame.add(new ButtonPane(GameFrame), "buttons");
        // Creates the new JPanel that will hold the game.
        JPanel gamestage = new JPanel();
        gamestage.setBackground(Color.darkGray);
        GameFrame.add(gamestage, "game");
        gamestage.setLayout(null);
        // *Move the setup of the player and the timer under the walls
        // Get a sample of collisions going so that i can do it over the weekend
        // Setup the movable box
        player.setBounds(25, 25, 20, 20);
        player.setVisible(true);
        player.setBackground(Color.cyan);
        // Opaque makes the background visible
        player.setOpaque(true);

        // Setup the key listener
        addKeyListener(this);
        // Null layout allows moving objects!!!
        gamestage.add(player);
        // Set the timer
        Timer tm = new Timer(1000 / FPS, this);
        tm.start();

        wall1.setBounds(10, 15, 10, 480);
        wall1.setVisible(true);
        wall1.setBackground(Color.white);
        wall1.setOpaque(true);
        gamestage.add(wall1);

        wall2.setBounds(10, 10, 755, 10);
        wall2.setVisible(true);
        wall2.setBackground(Color.white);
        wall2.setOpaque(true);
        gamestage.add(wall2);
        // wall3.setBounds(x, y, width, height);
        wall3.setBounds(10, 100, 100, 10);
        wall3.setVisible(true);
        wall3.setBackground(Color.white);
        wall3.setOpaque(true);
        gamestage.add(wall3);

        wall4.setBounds(100, 60, 10, 40);
        wall4.setVisible(true);
        wall4.setBackground(Color.white);
        wall4.setOpaque(true);
        gamestage.add(wall4);

        wall5.setBounds(70, 60, 35, 10);
        wall5.setVisible(true);
        wall5.setBackground(Color.white);
        wall5.setOpaque(true);
        gamestage.add(wall5);

        wall6.setBounds(60, 100, 10, 90);
        wall6.setVisible(true);
        wall6.setBackground(Color.white);
        wall6.setOpaque(true);
        gamestage.add(wall6);

        wall7.setBounds(10, 230, 60, 10);
        wall7.setVisible(true);
        wall7.setBackground(Color.white);
        wall7.setOpaque(true);
        gamestage.add(wall7);

        wall8.setBounds(60, 230, 10, 65);
        wall8.setVisible(true);
        wall8.setBackground(Color.white);
        wall8.setOpaque(true);
        gamestage.add(wall8);

        wall9.setBounds(60, 290, 125, 10);
        wall9.setVisible(true);
        wall9.setBackground(Color.white);
        wall9.setOpaque(true);
        gamestage.add(wall9);

        wall10.setBounds(175, 300, 10, 45);
        wall10.setVisible(true);
        wall10.setBackground(Color.white);
        wall10.setOpaque(true);
        gamestage.add(wall10);

        wall11.setBounds(130, 335, 45, 10);
        wall11.setVisible(true);
        wall11.setBackground(Color.white);
        wall11.setOpaque(true);
        gamestage.add(wall11);

        wall12.setBounds(10, 335, 70, 10);
        wall12.setVisible(true);
        wall12.setBackground(Color.white);
        wall12.setOpaque(true);
        gamestage.add(wall12);

        wall13.setBounds(10, 435, 60, 10);
        wall13.setVisible(true);
        wall13.setBackground(Color.white);
        wall13.setOpaque(true);
        gamestage.add(wall13);

        wall14.setBounds(10, 385, 230, 10);
        wall14.setVisible(true);
        wall14.setBackground(Color.white);
        wall14.setOpaque(true);
        gamestage.add(wall14);

        wall15.setBounds(60, 390, 10, 50);
        wall15.setVisible(true);
        wall15.setBackground(Color.white);
        wall15.setOpaque(true);
        gamestage.add(wall15);

        wall16.setBounds(230, 290, 10, 155);
        wall16.setVisible(true);
        wall16.setBackground(Color.white);
        wall16.setOpaque(true);
        gamestage.add(wall16);

        wall17.setBounds(10, 485, 750, 10);
        wall17.setVisible(true);
        wall17.setBackground(Color.white);
        wall17.setOpaque(true);
        gamestage.add(wall17);

        wall18.setBounds(70, 180, 60, 10);
        wall18.setVisible(true);
        wall18.setBackground(Color.white);
        wall18.setOpaque(true);
        gamestage.add(wall18);

        wall19.setBounds(120, 180, 10, 55);
        wall19.setVisible(true);
        wall19.setBackground(Color.white);
        wall19.setOpaque(true);
        gamestage.add(wall19);
    }

    public boolean areColliding(JLabel a, JLabel b) {
        return a.getBounds().intersects(b.getBounds());
    }

    /**
     * this method makes the player move. It takes the players speed and subtracts
     * or adds the player speed to the current position of the player. It also
     * figures out were the player is at currently aswell.
     * 
     * @param arg0
     */
    @Override
    public void actionPerformed(ActionEvent arg0) {
        // Move up if W is pressed
        if (keys.contains(KeyEvent.VK_W)) {
            player.setLocation(player.getX(), player.getY() - playerSpeed);
        }
        // Move right if D is pressed
        if (keys.contains(KeyEvent.VK_D)) {
            player.setLocation(player.getX() + playerSpeed, player.getY());
        }
        // Move down if S is pressed
        if (keys.contains(KeyEvent.VK_S)) {
            player.setLocation(player.getX(), player.getY() + playerSpeed);
        }
        // Move left if A is pressed
        if (keys.contains(KeyEvent.VK_A)) {
            player.setLocation(player.getX() - playerSpeed, player.getY());
        }

            // Check for collisions
        if (areColliding(wall1, player)) {
            // Reposition the target
            int newX = (int) (25);
            int newY = (int) (25);
            player.setLocation(newX, newY);
        }else 

        // Check for collisions
                if (areColliding(wall2, player)) {
                    // Reposition the target
                    int newX = (int) (25);
                    int newY = (int) (25);
                    player.setLocation(newX, newY);
                }else
        // Check for collisions
        if (areColliding(wall3, player)) {
            // Reposition the target
            int newX = (int) (25);
            int newY = (int) (25);
            player.setLocation(newX, newY);
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {
        // Add the key to the list
        // of pressed keys
        if (!keys.contains(e.getKeyCode())) {
            keys.add(e.getKeyCode());
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        // Remove the key from the
        // list of pressed keys
        keys.remove((Integer) e.getKeyCode());
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }
}

下面是ButtonPane类。它控制屏幕切换。切换的两个屏幕是GamePaneButtonPaneGamePane包含运行游戏所需的墙壁和所有代码。ButtonPane类如下所示:

代码语言:javascript
复制
/**
 * This pane contains the button and sets up the button pane
 */
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ButtonPane extends JPanel {

    private JButton startBTN;// Calls the JButton
    JFrame game;

    public ButtonPane(JFrame g) {
        game = g;
        setLayout(new GridBagLayout());
        setBackground(Color.gray);// Sets the menu stages color blue
        startBTN = new JButton("Start");// Creates a new button
        add(startBTN);// Adds the button on the startStage

        startBTN.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (game.getContentPane().getLayout() instanceof CardLayout) {
                    CardLayout layout = (CardLayout) getParent().getLayout();
                    layout.show(game.getContentPane(), "game");

                }
            }
        });
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-06-09 09:05:16

您可以在JLabel循环中使用for s初始化一个ArrayList,如下所示:

代码语言:javascript
复制
ArrayList<JLabel> array = new ArrayList<>();

for (int i = 0, i < numberOfLabels, i++)
{
    array.add(new JLabel());
}

要从ArrayList中检索元素,只需使用:

代码语言:javascript
复制
array.get(elementIndex);

如果您想将已经创建的JLabels放入一个ArrayList中,您可以这样做:

代码语言:javascript
复制
array.add(labelObject);

对于您希望在ArrayList中使用的每个JLabel对象。

票数 0
EN

Stack Overflow用户

发布于 2018-06-09 11:18:14

您可以使用ArrayList存储您的JLabel

但是在将一个已经存在的JLabel添加到数组列表中时,您将遇到困难(因为,当您拿回它时,您不知道要访问哪个索引)。

追踪JLabel的更好方法是创建地图,您通常需要为JLabel指定文本,以便可以使用它来标识JLabel

代码语言:javascript
复制
Map<String, JLabel> map = new HashMap<>();

map.put(your-label-name, new JLabel(your-label-name));

如果您知道您的标签将被复制,则在您的JLabel密钥中添加前缀。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50769993

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档