我在做一个连接四个游戏。余由6 7阵列JPanel
对象,将持有或者为空或满(红或蓝)空间的图像,将图像作为一个网格,以使板并在一个播放机将从空切换到特定的颜色选择那一栏(我在Java中不太好,我决定不做移动对象)。我在填充网格时出现空格问题。如何使用GridLayout将JPanel数组添加到JPanel?
我对如何做到这一点困惑,我有一个面板; gridPanel
,具有6 7 GridLayout
,我将使用包含Images
板阵列。我想将6乘7阵列添加到6乘7的面板,可以这样做吗?
我也遇到麻烦构建板阵列,我会(在方法:createGrid
)做正确吗?
问题:没有图像出现在与GridLayout
的面板中。
我的代码去如下:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ConnectFour{
static JButton colOne = new JButton("Drop");
static JButton colTwo = new JButton("Drop");
static JButton colThree = new JButton("Drop");
static JButton colFour = new JButton("Drop");
static JButton colFive = new JButton("Drop");
static JButton colSix = new JButton("Drop");
static JButton colSeven = new JButton("Drop");
static JPanel[][] gridComponent = new JPanel[6][7];
static JPanel gridPanel = new JPanel();
static JPanel emptySlot = new JPanel();
static JPanel redSlot = new JPanel();
static JPanel blueSlot = new JPanel();
public static void main(String[] args){
JPanel mainPanel = new JPanel();
JPanel buttonPanel = new JPanel();
//Creation of the 3 possible slot images
ImageIcon emptyCircle = new ImageIcon("emptyCircle.png");
ImageIcon redCircle = new ImageIcon("redCircle.png");
ImageIcon blueCircle = new ImageIcon("blueCircle.png");
JLabel emptyLabel = new JLabel(emptyCircle);
JLabel redLabel = new JLabel(redCircle);
JLabel blueLabel = new JLabel(blueCircle);
emptySlot.add(emptyLabel);
redSlot.add(redLabel);
blueSlot.add(blueLabel);
mainPanel.setLayout(new BorderLayout());
gridPanel.setLayout(new GridLayout(6, 7));
buttonPanel.setLayout(new GridLayout(1, 7));
mainPanel.add(gridPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.NORTH);
buttonPanel.add(colOne);
buttonPanel.add(colTwo);
buttonPanel.add(colThree);
buttonPanel.add(colFour);
buttonPanel.add(colFive);
buttonPanel.add(colSix);
buttonPanel.add(colSeven);
//Properties of the JFrame
JFrame window = new JFrame("Connect Four"); //Title
window.setContentPane(mainPanel); //content pane set to mainPanel
window.setSize(500,500); //JFrame size
window.setLocation(0,0); //Location of appearance
window.setVisible(true); //Set to be visable
window.setResizable(true); //Set to be resizeable
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Program ends upon exiting window
createGrid();
clearBoard();
}
public static void createGrid(){
for(int a=0; a<6; a++){
for(int b=0; b<7; b++){
gridComponent[a][b] = new JPanel();
gridPanel.add(gridComponent[a][b]);
}
}
}
public static void clearBoard(){
for(int a=0; a<6; a++){
for(int b=0; b<7; b++){
gridComponent[a][b] = emptySlot;
}
}
}
}
不知道是否重复,但[此线程](http://stackoverflow.com/questions/21070555/java-making-connect-four-game-panel)张贴只是几分钟前。 – PakkuDon
似乎是一个不同的家伙,具有相同的功课;)至少这个代码解决了另一个线程的问题。 –
@OP:您目前发布的问题是什么?你不能指望我们扫描你的代码,找出可能存在的问题。你有错误的行为吗?或错误? –