我可以将JLabel添加到数组中吗?

时间:2018-06-09 00:55:34

标签: java arrays swing graphics jlabel

我想清理我的代码,我想知道是否可以将这些JLabels放入ArrayList。 这将用于do-while循环,其中将检查我的播放器的冲突。

以下是GamePane课程。此代码中包含移动播放器,并具有冲突代码。这是我创建ArrayList

的地方
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类如下:

/**
 * 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");

                }
            }
        });
    }
}

2 个答案:

答案 0 :(得分:0)

您可以在for循环中使用Object.keys(response[0]);初始化ArrayList,如下所示:

JLabel

要从ArrayList<JLabel> array = new ArrayList<>(); for (int i = 0, i < numberOfLabels, i++) { array.add(new JLabel()); } 检索元素,只需使用:

ArrayList

如果您想将已创建的array.get(elementIndex); 放入JLabels,您可以执行以下操作:

ArrayList

对于array.add(labelObject); 中所需的每个JLabel对象。

答案 1 :(得分:0)

您可以使用ArrayList存储JLabel

但是在向你的arraylist添加一个已经存在的JLabel时你会很困难(因为,当你找回它时你不知道要访问哪个索引)。

跟踪JLabel的更好方法是创建地图,您经常需要为JLabel指定文字,以便用它来识别您的JLabel:< / p>

Map<String, JLabel> map = new HashMap<>();

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

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