如何在java中建立一个简单的基于网格的游戏板?

如何在java中建立一个简单的基于网格的游戏板?,java,arrays,layout,matrix,grid,Java,Arrays,Layout,Matrix,Grid,我目前正在学习Swing,我想制作一个游戏会让这个过程对我来说更有趣。我已经用菜单和工具栏设置了我的JFrame,但是现在我正在构建一个JPanel作为游戏区,在这种情况下,我想创建一个网格。我可以使用以下工具在面板上轻松绘制一个: protected void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.black); for(int x = 0 ; x <= ge

我目前正在学习Swing,我想制作一个游戏会让这个过程对我来说更有趣。我已经用菜单和工具栏设置了我的JFrame,但是现在我正在构建一个JPanel作为游戏区,在这种情况下,我想创建一个网格。我可以使用以下工具在面板上轻松绘制一个:

protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    g.setColor(Color.black);
    for(int x = 0 ; x <= getWidth() ; x += 16 ) {
         g.drawLine( x , 0 , x , getHeight() );
     }
    g.setColor(Color.black);
    for(int y = 0 ; y <= getHeight() ; y += 16 ) {
          g.drawLine( 0 , y , getWidth() , y );
受保护的组件(图形g){
超级组件(g);
g、 设置颜色(颜色为黑色);

对于(int x=0;x使用尺寸创建图像,或者根据设置网格线的规则放置精灵

//Declare some extra variables
int coordX;
int coordY;
final BufferedImage image = ImageIO.read(new FileInputStream("picture.jpg"));
PointerInfo a = MouseInfo.getPointerInfo();

//Call this every time the mouse is clicked.
Point b = a.getLocation();    
int mouseClickX = (int) b.getX();
int mouseClickY = (int) b.getY();

void place() {//Make a function that establishes ranges to be clicked
    if(mouseClickX < 16 && mouseClickX > 0 && mouseClickY < 16 && mouseClickY > 0)
       coordX = coordY = 0; //places at top corner
    else if()//slot 2, 3, etc...
}



//paintComponent method:
g.drawImage(image, coordX, coordY, this); //set coordinates in 0,0
//声明一些额外的变量
int-coordX;
国际协调;
final buffereImage image=ImageIO.read(新文件输入流(“picture.jpg”);
PointerInfo a=MouseInfo.getPointerInfo();
//每次单击鼠标时调用此选项。
点b=a.getLocation();
int mouseClickX=(int)b.getX();
int mouseClickY=(int)b.getY();
void place(){//生成一个函数,用于建立要单击的范围
if(mouseClickX<16&&mouseClickX>0&&mouseClickY<16&&mouseClickY>0)
coordX=coordY=0;//位于上角
else if()//插槽2、3等。。。
}
//组件方法:
g、 drawImage(image,coordX,coordY,this);//设置0,0中的坐标
除了你现在的选择 如果你想让你的游戏元素成为Swing组件,那么这就是你要寻找的。虽然这需要一点习惯,但它是Swing提供的最可定制的布局


可以找到有关使用GridBagLayout的更多信息。

您可以创建一个包含所有GridBagLayout的JPanel的网格。如果您希望每个单元格都包含一张可拖动的图片,请将图像放在ImageIcon中,将图标放在JLabel中,然后将JLabel添加到JPanel网格的一个单元格中。如果单元格使用GridBagLayout,则一个JLabel将默认情况下,将显示在JPanel单元格的中心。若要拖放,请指定JLabels MouseListener和MouseMotionListener。如果单击,则从JPanel中删除JLabel并将其移动到顶层窗口的玻璃窗格。等等