Introduction to Java Swing game design (2)

Source: Internet
Author: User

Source: computer enthusiasts Author: Zhang Jian

Do you still remember Minicooper, a wizard in "steal the sky for the day", in Hollywood traffic? Mark walberger and Sally saelong are driving it to deliver ten millions of gold worth under the enemy's nose. However, what would you think if you put a Minicooper shell that cannot be running in front of you? Is it still the walking genie? Today, let's assemble parts for this Minicooper at and let it run.

  Preface

Starting from this issue, we will provide you with the complete game source code (click to download ). Java cafe advocates both theory and practice. In the serialization, we will introduce key technologies and Implementation ideas to you. Friends can read the source code by themselves, like reading newspapers and drinking coffee, this is the lingering charm.

  Game Layout

"Continuous watching" 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 1*1.
· GridLayout (int rows, int cols): number of grids in the horizontal and vertical layout s of the layout area
· GridLayout (int rows, int cols, int hgap, int vgap): Same as above, and also specifies the horizontal distance between each grid.

Don't let these three constructors scare you. In fact, if you like it, you can use either of them with confidence, even if you accidentally use "wrong, there will also be ways to make adjustments later. Note that when adding a control, GridLayout adds the control sequentially from the top left to the bottom right.

Now let's determine the number of game grids. How many grids are suitable? Too little will reduce the difficulty of the game, and too much will cause visual impact. Therefore, we should use a pair of constants to indicate that in the future, even if we want to modify them, we will do our best.

In Java, the definition of constants must be written in the form of public final static. If we stipulate that the game board has eight grids horizontally and eight grids vertically, we should define this 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 game zone (contentPanel) to the above layout:

ContentPanel. setLayout (gridLayout );

If you compile and run the program at this time, you may wonder: why didn't the interface be changed? Although we have specified the layout, but no controls are added, of course there will be no changes. 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 )?

 Use JButton to write articles

JButton is a button control, which is also a common control in Swing. However, we still need to spend a little effort to understand and use it, when you are familiar with JButton, you will find that other Swing controls are similar.

If you run the program you just wrote, you will find that the buttons in the game area are always full, which is inconvenient for actual game operations, we have to find a way to empty some grids. GridLayout has a good layout. When adding a control, you cannot skip a grid. What can you do?

In fact, this is not difficult. Since GridLayout does not allow skipping, if we integrate the control added in a grid with the background of the GridLayout layout, we can achieve visual consistency. In addition, if someone accidentally clicks the button on this grid, the button will still be invisible, and we have to find a way to prevent the button from being clicked. This requires the setEnabled () method of JButton. Finally, when the buttons that can be clicked are clicked, we have to identify which button is clicked.

We used e. the getSource () method is used to determine the source generated by the mouse click event. However, it is only effective for the named control. Here, using arrays to represent buttons is undoubtedly the best method. 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 );
}

Do not forget to write dots [I] = new JButton ("Kyodai") in the loop body. Although the number of dots groups is defined and used, this only 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 to each button.

For the event response code, we can add the following code after the original actionreceivmed () 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, e. getSource () instanceof JButton is used to determine whether the event is generated by a JButton control. Then, the control that generates the event source is converted into a forced class and Integer is used. parseInt (button. the getActionCommand () method converts the obtained event name to an integer. The code that follows restores the integer to the information of rows and columns.

Now, run the program and click each button to see if the dialog box shown in the right figure is displayed?

Note that our subscript starts from 0. Source code of the current program (click to download ).

 Use images in Swing

Currently, we have solved user operations. To make the interface look beautiful, we need to use images instead of text. If you have time and patience, you can make a sexual image by yourself. You just need to make sure that the size of each image is the same. Otherwise, it will be too ugly. To save trouble, you can directly use the images provided in the downloaded package.

In Swing, you can use the setIcon (Image image) method to set images for the JButton. The image parameter is the Image object we want to set. This object can be obtained through multiple methods:

· Use the Toolkit class to obtain:
Image = Toolkit. getdefatooltoolkit (). getImage (url );
· Use the getImage () method of the ImageIcon class to obtain:
  
Image = new ImageIcon (getClass (). getResource (filename). getImage ();

The first method is used here. To help you 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. getdefatooltoolkit (). getImage (url );
Return image;
}

With this function, it is much easier to use images later, isn't it?

Now that the image is available, we can display the Map information in Map. Java in the source code package in the form of an image. Because this code is about the game's algorithm code, I will not list the Code any more. Here I will explain how to do it! In Map. in Java, we use a two-dimensional array map [] [] To Save image information. At the same time, we also use a one-dimensional array images [] to save each image object, each element in map has a value. This value not only indicates the value corresponding to the button in the game interface, but also indicates the number of the image in the images [] array used by the button, the program running interface is much more beautiful.

  Summary

Today, we introduced the JButton control in Swing. For most Swing controls, JButton can be copied in the same way. Don't underestimate this JButton. When you can master it well, your Swing skills have been improved. In addition, we also learned two ways to load image files in Java. Finally, we combined the above two parts to create a beautiful game interface. Although I did not write the complete code here, I believe that you will be able to achieve your goal by referring to my source program. If the problem cannot be solved, you can contact me through the leftmoon@163.com mailbox.

Do you feel satisfied with today's content? The highlights are still behind. We will continue to patronize our coffee shop!

Related Article

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.