因此我尝试制作战舰游戏,并实现了一个10x10的网格,其中包含一些像素化水的gif图像。现在,我想做的是将网格向下和向右偏移一个单元,以便像在真正的战舰游戏中一样,将数字和字母沿侧面和顶部放置。问题是,当我尝试抵消它时,它将删除整个右侧的单元格列并相应地减小窗口,反之亦然。这是我的代码:
编辑3:我已经替换了gif,以便每个人都可以使用它,只需复制代码并运行它。
public class ButtonGrid {
JFrame frame=new JFrame(); //creates frame
JLabel[][] grid; //names the grid of buttons
public ButtonGrid(int width, int length) throws MalformedURLException{
URL urlPic = new URL("http://i47.tinypic.com/14wswi9.gif");
ImageIcon urlPicture = new ImageIcon(urlPic);
frame.setLayout(new GridLayout(width,length)); //set layout
grid=new JLabel[width][length]; //allocate the size of grid
for(int y=0; y<length; y++){
for(int x=0; x<width; x++){
grid[x][y]= new JLabel(urlPicture); //creates new button
frame.add(grid[x][y]); //adds button to grid
}
}
grid[1][1].setForeground(Color.red);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(270, 400);
frame.pack(); //sets appropriate size for frame
frame.setVisible(true); //makes frame visible
}
public static void main(String[] args) throws MalformedURLException{
new ButtonGrid(11,11);//makes new ButtonGrid with 2 parameters
}
}
编辑:看来我可能还没有说清楚。在真正的战舰游戏中,有一排数字和一列字母。网格的其余部分只是水,里面有船。使用我提供的代码,整个网格都是水,我想像在真正的战舰板上一样偏移以放置一行数字和一列字母。如果我尝试将任何东西放置在当前网格的顶部,它不会改变任何东西。我试图更改前景色,甚至将其中一个单元格的图片更改为不同的颜色,并且网格仍然保持不变。一个11 x 11的动画像素水网格。
第二次编辑:我重写了代码,在窗口的顶部和左侧绘制了一个网格,但是现在我得到了一个空指针异常。我不完全知道这是怎么回事:
编辑四:删除了不需要的代码。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句