Follow me to learn Java Swing game Design (2) _java programming

Source: Internet
Author: User
Article Source: Computer enthusiasts Author: Zhang Jian

Do you remember the minicooper in the steal, the elf-like shuttle in the Hollywood traffic? Mark Wahlberg and Sally Saillon is driving it under the enemy's nose to carry away the value of tens of millions of gold. But what would you think if you were to put a minicooper shell in front of you now? Is it still the spirit that swims freely? Today, let's assemble the parts for the Minicooper at 1.1 o ' Day and let it run.

  Objective

From the beginning of this period, we provide you with complete game source code (click to download). Java Café advocates both theory and practice, we will give you a series of key technologies and implementation of ideas, friends of their own combination of reading source code, like a newspaper while drinking coffee, this is the drop of Shannon is still not done.

  Game layout

"Repeatedly see" belongs to a two-dimensional war board game, to design a chessboard class game, GridLayout should be the choice. Now let's take a look at the GridLayout constructor:

· GridLayout (): By default, the layout area is divided into the size of the 1*1
· GridLayout (int rows,int cols): Specifies the number of squares, horizontal and vertical, of the layout area
· GridLayout (int rows,int cols,int hgap,int vgap): Ibid., and also specifies horizontal spacing hgap and longitudinal spacing between each lattice vgap

Do not let these three constructors scare you, in fact, as long as you like, you can confidently use any one of them, even if not careful with the "wrong", there are ways to adjust. The only thing to note is that when you add a control, the default order is GridLayout from the top left to the right.

Now let's determine the number of squares for the game. How many squares are more suitable? Too little can reduce the difficulty of the game, too much will cause visual impact. Therefore, we should use a pair of constants to show that in the future even if we want to change, it is a lift.

In Java, the definition of a constant needs to be written as public final static, and if we specify that the chessboard of the game has 8 squares horizontally and 8 squares lengthwise, then we should define this:

Public final static int ROW = 8;

Public final static int COLUMN = 8;

We then 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 game area (Contentpanel) to the above layout:

Contentpanel.setlayout (gridLayout);

If you compile and run the program at this time, you may be surprised: the interface has not changed anything, is it wrong? Although we have specified the layout, but what controls are not added, of course, can not see the change. Now let's add a button to the layout:

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

Try running the program again, is it the same as mine (see Figure 1)?

 Skillfully use JButton to make a fuss

JButton is a button control, and it's also a normal, mundane control in swing, but we still need to take a little effort to understand and use it, because when you're proficient with JButton, you'll find that other swing controls are similar.

If you have just written the program to run, you will find: The game area of the button is always full, which is very inconvenient to the actual operation of the game, so we have to find a way to let some of the grid empty out. GridLayout layout is good, that is, when adding controls can not skip a certain lattice, this how to do?

In fact, this is not difficult, since the GridLayout do not let skip, if we let a lattice added control and GridLayout layout of the background, so that the vision to achieve a consistent effect. In addition, if someone accidentally clicks on this lattice, the button will still be true, we have to find ways to make the button can not be clicked, this requires the use of JButton setenabled () method. Finally, for the buttons that can be clicked, when they are clicked, we have to distinguish which button is clicked.

When we last implemented the "about" feature, we used the E.getsource () method to determine the source of the mouse click event, however, it is only more effective for the named control. Here, using an array representation button is definitely the best way to start by modifying the code above:

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 dots are defined and used, however, this only tells the program that we need to use some JButton, but these JButton are still not initialized. At the same time, we have not only used Setactioncommand () for the button to develop the event name, but also used the addActionListener () method for each button with the event response processing.

For the code on the event response, we can add it 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;
Joptionpane.showmessagedialog (This, "row=" +row+ ", col="
+ col, "button", joptionpane.information_message);
}

In the above code, the E.getsource () instanceof JButton is used to determine whether the resulting event was generated by a JButton-type control, and then the control that produced the source of the event was coerced class-converted, and then used Integer.parseint ( The Button.getactioncommand () method converts the obtained event name to an integer, and the following code restores that integer to the row and column information.

OK, now run the program, and then click each button to see if there will be a dialog box like the right picture?

Note that our subscript starts at 0. Current Program source code (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 text. Have time and patience of friends can do their own personality pictures, just to pay attention to maintain the size of each picture consistent, otherwise it would be too ugly. If you want to be easy, you can also use the pictures provided in the download package directly.

In swing, you can use the SetIcon (image image) method to set a picture for JButton, where the parameter image is the picture object that we want to set, and there are several ways that this object can be obtained:

• Use the Toolkit class to obtain:
Image = Toolkit.getdefaulttoolkit (). GetImage (URL);
• Use the GetImage () method of the ImageIcon class to obtain:
Image = New ImageIcon (GetClass (). getresource (filename)). GetImage ();

We choose the first method here. To make it easier to get 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 is much more convenient to use the picture later, isn't it?

Now that the picture is available, we can display the map information in the Map.java in the source code package in the form of a picture. Because this code is about the game's algorithm code, so no longer enumerate the code, here to explain the details of how to do it! In Map.java, we use two-dimensional array map[][] to save picture information, and we also use one-dimensional array images[] to save each image object, each element in the map has a value that not only indicates the value of the button in the game interface, It also shows that the button uses the number of the picture in the images[] array, and the program runs a much prettier interface.

  Summary

Today we introduced the JButton control in swing. For most swing controls, the JButton usage can be replicated. Don't underestimate this jbutton, when you have a good grasp of it, your swing skills have been elevated a step. In addition, we have learned to load picture files in Java in two ways. Finally, we also combine the above two parts to create a beautiful game interface. Although I did not write the complete code here, but I believe that you refer to my source program, through their own efforts, will be able to achieve the goal. If the problem is not solved, you can contact me through leftmoon@163.com mailbox.

I wonder if you feel satisfied with the content of today? Wonderful still in the back, we want to continue to patronize our café Oh!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.