2D数组和JButton [英] 2D array AND JButton
问题描述
现在我需要编写一个8谜题的游戏,看起来[像这样]
Now I need to write a 8-puzzle game, which looks [like this]
讲师要求我们编写三个不同的类,分别是Piece.java,EightPuzzle.java和EightPuzzlePanel.java.如你看到的,Piece.java在这八个拼图板上代表每个单独的片断,例如"1","2";EightPuzzle.java代表游戏板,可容纳这9个部件/按钮.ThreePuzzlePanel.java是GUI的东西.
The instructor asked us to write three different classes, which are Piece.java, EightPuzzle.java, and EightPuzzlePanel.java. As you can see, Piece.java represents each individual piece like "1", "2" in this eight puzzle board; EightPuzzle.java represents the the game board to hold these 9 pieces/buttons. EightPuzzlePanel.java is the GUI stuff.
所以我的问题是,因为我们需要创建一个Piece [] [] piece = new Piece [] [](一个2D数组),并且还需要将这些块布置在板上.我以为我可以创建9个JButton,并将2D数组与9个JButton链接在一起(或者有更好的方法对2D数组进行排序),但是我不知道该怎么做.
So my question is, since we need to create a Piece[][] piece = new Piece[][], a 2D array, and we also need to arrange these piece on the board. I thought I could create 9 JButtons and put the 2D array in link with the 9 JButtons (or there have a better way to sort the 2D-array), but I don't know how to do that.
此外,还需要同时通过鼠标和键盘来控制按钮.这对我来说是另一个挑战.
Also the buttons need to be controlled by both mouse and keyboard. This is another challenge for me.
推荐答案
由于这是家庭作业,因此我不会详细介绍,但这是我的处理方式:
Since this is homework I will not go into much detail, but this is how I would go about it:
- 使
Piece
扩展JButton
类.Piece
对象可以显示文本以及要渲染的图像的位置.您应该可以在网上找到很多有关如何将图像添加到JButton
的示例. - 使
EightPuzzle
扩展JPanel
类,并使用
- Make
Piece
extends theJButton
class. ThePiece
object takes the text to display and also the location of the image you would like it to render. You should be able to find plenty of examples online on how to add an image to aJButton
. - Make
EightPuzzle
extend theJPanel
class and also use the Grid Layout to render the Pieces neatly in a grid. This class takes on a 2D array ofPiece
objects which it will then render. - Make
EightPuzzlePanel
also extend theJPanel
class. This class takes in another JPanel (EightPuzzle
) and appends any other buttons you might need. - Finally create a Main class which extends
JFrame
and then I append theEightPuzzlePanel
to it (which should in turn contain the other panel with the other buttons).
这篇关于2D数组和JButton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!