简体   繁体   English

将JLabel添加到JPanel

[英]Adding JLabel to JPanel

I am trying to make a checkers game. 我正在尝试制作一个跳棋游戏。 I know the basics of inserting an ImageIcon in a JLabel and putting it in a JPanel . 我知道在JLabel中插入ImageIcon并将其放入JPanel的基本知识。

What I have here is a grid with a JPanel in each cell. 我在这里有一个在每个单元格中都有一个JPanel的网格。 I managed to assign the array of the JLabels to the JPanels by placing the code in the drawsBoard() method (NOT IN THE CODE BELOW) . 通过将代码放置在drawsBoard()方法中 drawsBoard()的代码中drawsBoard()我设法将JLabel数组分配给drawsBoard()

However I need to do this in a seperate method to make things look nicer. 但是,我需要使用一种单独的方法来使事情看起来更好。 When I tried to run the code below, no chips show up on the board unlike before. 当我尝试运行以下代码时,与以前不同,板上没有任何芯片。 What am I missing? 我想念什么? You can compile it and see for yourself. 您可以编译它并自己查看。

Here is my code: 这是我的代码:

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.File;
import java.io.IOException;
import javax.swing.JTextField;

public class Main extends JFrame {

    private JPanel contentPane;

    ImageIcon p1Chip;

    JPanel[][] board = new JPanel[8][8];
    JLabel[][] label = new JLabel[8][8];


    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Main frame = new Main();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public Main() throws IOException {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 800, 800);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        startGame();
    }


    //Start Game!
        public void startGame() throws IOException{

            getAssets();
            drawBoard();
            drawChips();            
        }

    //ASSETS
        public void getAssets(){
            System.out.println("Getting assets!");
            p1Chip = new ImageIcon("C:/Users/Trifecta/Desktop/Java Exercises/Checkers/src/checkers/P1ChipNormal.png");
        }   


//******************************DRAWS BOARD******************************\\

 //Draws the board
    public void drawBoard() throws IOException{

        System.out.println("Start Drawing Board!");

        getContentPane().setLayout(new GridLayout(8,8));


        int colorAssignRow = 0; 
        int colorAssignCol = 0;

        for(int r = 0; r < 8; r++){

            colorAssignRow++;
            colorAssignCol = 0;

            for(int c = 0; c < 8; c++){

                colorAssignCol++;

                board[r][c] = new JPanel();


                if(colorAssignRow%2!=0){
                    if(colorAssignCol%2==0)board[r][c].setBackground(Color.RED);
                        else board[r][c].setBackground(Color.BLACK);
                }
                else if(colorAssignRow%2==0){
                    if(colorAssignCol%2==0)board[r][c].setBackground(Color.BLACK);
                    else board[r][c].setBackground(Color.RED);
                }

                getContentPane().add(board[r][c]);

            }

        }

        System.out.println("Board Drawing Done!");


    }

//******************************END OF DRAWING BOARD******************************\\

//THIS IS THE PART THAT IS NOT WORKING  
//******************************DRAWING CHIPS******************************\\

    public void drawChips(){


    /*
     * Put Chip When:   (r and c)
     *                  0 and even
     *                  1 and odd
     *                  2 and even
     */

    //Drawing Player One Chips\\
        for(int r = 0; r < 8; r++){ 
            for(int c = 0; c < 8; c++){
            label[r][c].setIcon(p1Chip);
                label[r][c] = new JLabel();
                board[r][c] = new JPanel();


                if(r==0 && c%2==0){
                    board[r][c].add(label[r][c]);

                }
                else if(r==1 && c%2!=0 && c!=0){    
                    board[r][c].add(label[r][c]);

                }
                else if(r==2 && c%2==0){
                    board[r][c].add(label[r][c]);

                }
                 revalidate();
                 repaint();

            }

        }
    //End Of Drawing Player One Chips\\

    }

//******************************END OF DRAWING CHIPS******************************\\

}

UPDATE: 更新:

This is the error I get when i remove 这是我删除时遇到的错误

label[r][c] = new JLabel();

board[r][c] = new JPanel();

java.lang.NullPointerException
    at checkers.Main.drawChips(Main.java:145)
    at checkers.Main.startGame(Main.java:69)
    at checkers.Main.<init>(Main.java:60)
    at checkers.Main$1.run(Main.java:43)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$200(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

It stops when the drawChips() method is called. 当调用drawChips()方法时,它将停止。

Your code draws the board, initializing all the panels, and then does the following: 您的代码绘制了面板,初始化了所有面板,然后执行以下操作:

label[r][c].setIcon(p1Chip); // set the icon of the label
label[r][c] = new JLabel(); // replace the label in the array, containing the icon, by a new one, without any icon
board[r][c] = new JPanel(); // replace the already initialized panel in the board by a new, empty one

...

board[r][c].add(label[r][c]); // add the empty label to the empty panel.

So, remove these lines, which don't make sense: 因此,请删除这些没有意义的行:

label[r][c] = new JLabel();
board[r][c] = new JPanel();

And also remove these lines, which are useless: 并删除这些无用的行:

revalidate();
repaint();

EDIT, based on your code, I thought the array of labels was already populated. 编辑,根据您的代码,我认为标签数组已经填充。 This is not the case, so you need to remove 事实并非如此,因此您需要删除

board[r][c] = new JPanel();

and to flip those two instructions: 并翻转这两个指令:

label[r][c].setIcon(p1Chip); // set the icon of the label
label[r][c] = new JLabel(); // create the label

The label must be created before setting its icon. 必须先设置标签,然后再设置其图标。 So it should be 所以应该

label[r][c] = new JLabel(); // create the label
label[r][c].setIcon(p1Chip); // set the icon of the label

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM