Learn game design of Java swing from me (2)

Remember the minicooper who shuttles through the traffic of Hollywood like an elf in stealing the day? Mark Walberg and Sally Theron drove it to carry away tens of millions of gold under the enemy's nose. However, if you put the body of a minicooper that can't run in front of you now, what would you think of it? Is it still the elf who can walk freely? Today, let's assemble parts for this minicooper bit by bit and let it run.

Foreword

From the beginning of this issue, we will provide you with complete game source code (click to download). Java Cafe advocates that you pay equal attention to theory and practice. We will introduce you to key technologies and implementation ideas in the serial. Friends can read the source code in combination with articles by themselves, just like drinking coffee while reading newspapers. This is the fragrance of every drop.

Game layout

"Lianliankan" is a two-dimensional chess game. To design a board game, GridLayout should be the best choice. Now let's take a look at the GridLayout constructor:

・ gridlayout(): by default, the layout area is divided into a size of 1 * 1 ・ GridLayout (int rows, int cols): Specifies the number of horizontal and vertical grids in the layout area ・ GridLayout (int rows, int cols, int hgap, int vgap): the same as above, and also specifies the horizontal spacing hgap and vertical spacing vgap between each grid

Don't let these three constructors scare you. In fact, as long as you like, you can safely and boldly use any of them. Even if you accidentally use "wrong", there are ways to adjust them in the future. The only thing to note is that when adding controls to GridLayout, the default order is from the top left to the bottom right.

Now let's determine the number of squares in the game. How many squares are more suitable? Too little will reduce the difficulty of the game, and too much will have a visual impact. Therefore, we should express it through a pair of constants. Even if we want to modify it in the future, it is a small effort.

In Java, the definition of constants needs to be written in the form of public final static. If we specify that the chessboard of the game has 8 grids horizontally and 8 grids vertically, we should define it as follows:

public final static int ROW = 8; public final static int COLUMN = 8;

Then, we use the second constructor of GridLayout to create the layout:

GridLayout gridLayout = new GridLayout(ROW, COLUMN);

Finally, we need to change the layout of the content panel to the above layout:

contentPanel. setLayout(gridLayout);

If you compile and run the program at this time, you may wonder: why hasn't the interface changed? Is there something wrong? Although we specified the layout, no controls were added. Of course, we can't see the change. Now let's add buttons to the layout:

for (int i = 0; i < ROW * COLUMN; i++) { JButton button = new JButton("Kyodai"); contentPanel.add(button); }

Run the program again. Is it the same as mine (see Figure 1)?

Skillfully using JButton to do articles

JButton is a button control. It is also an ordinary control in swing. Nevertheless, we still need to spend a little effort to understand and use it, because when you can skillfully use JButton, you will find that other swing controls are so similar.

If you run the program you just wrote, you will find that the buttons in the game area are always full, which is very inconvenient for the operation of the actual game. Therefore, we have to find a way to empty part of the grid. The GridLayout layout is good for everything, that is, you can't skip a grid when adding controls. What can you do?

In fact, this is not difficult. Since GridLayout does not allow skipping, if we integrate the controls added in a grid with the background of the GridLayout layout, we can achieve a consistent visual effect. In addition, if someone accidentally clicks on this grid, the button will still show its original shape. We have to find a way to prevent the button from being clicked, which requires JButton's setenabled() method. Finally, for the buttons that can be clicked, when they are clicked, we have to distinguish which button is clicked.

The last time we implemented the "about" function, we used the E. getsource () method to determine the source of the mouse click event. However, it is only effective for the named controls. Here, it is undoubtedly the best way to use an array to represent buttons. First, let's modify the above code:

JButton[] dots = new JButton[ROW * COLUMN]; for (int i = 0; i < ROW * COLUMN; i++) { dots[i] = new JButton("Kyodai"); dots[i].setActionCommand("" + i); contentPanel.add(dots[i]); dots[i].addActionListener(this); }

Don't forget to write dots [i] = new JButton ("Kyodai") in the loop body. Although the number of dots groups is defined and used earlier, it just tells the program that we need to use some jbuttons, but these jbuttons are still not initialized. At the same time, we not only use setactioncommand () to specify the event name for the button, but also use the addactionlistener () method to add event response processing for each button.

For the code of event response, we can add the following after the original actionperformed() event code:

If (e.getsource() instanceof JButton) {JButton button = (JButton) e.getsource(); int offset = integer.parseint (button. Getactioncommand()); int row, col; row = math.round (offset / column); col = offset - row * column; jooptionpane.showmessagedialog (this, "row =" + row + ", col =" + col, "button", jooptionpane. Information_message);}

In the above code, e.getsource () instanceof JButton is used to judge whether the generated event is generated by a JButton type control, and then force the class conversion of the control that generates the event source, and then use integer The parseInt (button. Getactioncommand()) method converts the obtained event name into an integer, and the following code restores this integer into row and column information.

OK, now run the program, and then click each button to see if the dialog box as shown in the right figure will appear?

Note that our subscript starts from 0. The program source code of this issue (click to download).

Using pictures in swing

At present, we have solved the problem of user operation. In order to make the interface beautiful, we need to use pictures instead of words. Friends who have time and patience can make their own personality pictures. Just pay attention to keeping each picture the same size, otherwise it will be too ugly. If you want to save trouble, you can also directly use the pictures provided in the download package.

In swing, you can use the seticon (image) method to set the image for JButton. The parameter image is the image object we want to set. There are many methods to get this object:

・ use toolkit class to obtain: image = toolkit getDefaultToolkit(). getImage(url); ・ use the getimage() method of imageicon class to obtain: image = new imageicon (getclass() getResource(filename)). getImage();

We choose the first method here. In order to obtain the image object again in the future, we can write this as a function:

Image getImage(String filename){ urlclassloader urlLoader = (urlclassloader) this.getClass().getClassLoader(); URL url = null; Image image = null; url = urlLoader.findResource(filename); image = Toolkit.getDefaultToolkit().getImage(url); return image; }

With this function, it's much more convenient to use pictures in the future, isn't it?

Now that the picture is available, we can add the source code package to map The map information in Java is expressed in the form of pictures. Since this code is about the algorithm code of the game, I won't enumerate the code. I'll roughly explain how to do it here! In map In Java, we use the two-dimensional array map [] [] to save image information. At the same time, we also use the one-dimensional array images [] to save each image object. Each element in the map has a value. This value not only indicates the corresponding value of the button in the game interface, but also indicates that the button uses the image number in the images [] array, The program running interface is much more beautiful.

Summary

Today we introduced the JButton control in swing. For most swing controls, the usage of JButton can be copied in the past. Don't underestimate this JButton. When you can master it well, your swing skills have been improved to a higher level. In addition, we also learned two methods to load picture files in Java. Finally, we also combine the above two parts to create a beautiful game interface. Although I didn't write a complete code here, I believe you can refer to my source program and achieve your goal through your own efforts. If you encounter problems that cannot be solved, you can leftmoon@163.com Email me.

I wonder if you are satisfied with today's content? The highlights are still behind. We should continue to patronize our cafe!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>