简体   繁体   中英

Adding ImageIcon to a specific JPanel in an array

I have started over with my chessgame, and are now facing new problems. Like I tried to explain in the title of the question;

I made 64 squares, like a chessboard normally would have. They are given numbers by an array, and now I wish to add a piece onto the board in square number 3.

My code:

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Frame;
import java.awt.GridLayout;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Chess extends JPanel implements config {

/**
 * @param <MyMethods>
 * @param args
 */

public static void main(String[] args) {

    int[] squareArray;

    squareArray = new int[64];

    int i = 0;

    JFrame frame = new JFrame("Chessboard");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new GridLayout(SQUARE / ROWS, 0, 2, 2));

    for (i = 0; i < SQUARE; i++) {
        squareArray[i] = i;
        JPanel b = new JPanel(new BorderLayout());

        frame.add(b);

        int row = (i / 8) % 2;

        if (row == 0) {
            b.setBackground(i % 2 == 0 ? config.P1Color : config.P2Color);
        } else {
            b.setBackground(i % 2 == 0 ? config.P2Color : config.P1Color);
        }

        frame.setSize(800, 800);
        frame.setVisible(true);
    }

    JLabel piece = new JLabel(new ImageIcon("pawn.png"));
    JPanel panel = (JPanel) i.getComponent(3);
    panel.add(piece);
}

}

The error occurs at " JPanel panel = (JPanel) i.getComponent(3); " in the bottom of the code. The error goes like this; " i cannot be resolved ".

I have the feeling that I have messed up things here and started working with things I don't really have competence to work with. My guess is that either getComponent is the wrong way to access the array, or i .getComponent(3) is the wrong variable to use.

All help is deeply appreciated, and feel free to ask me anything if I forgot to add something here. I must admit that I'm sorry for asking these kind of stupid questions, but I find it really, really hard to understand java and work with it.

for (i = 0; i < SQUARE; i++) {
        squareArray[i] = i;
        JPanel b = new JPanel(new BorderLayout());  // ...

The poorly named b is defined as being local to that loop. While..

JPanel panel = (JPanel) b.getComponent(3);

Is after the end of the loop, outside the scope needed to access the variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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