Java Swing-based game design (1)

Source: Internet
Author: User

Source: computer enthusiasts Author: Zhang Jian

Who knows how much sand stone is consumed by the tower of Babylon in tongtian? Who knows how many days and nights Rome has been built? The only thing we know is that there is no great wall in the winding way without the building of bricks and stones. Without the accumulation of stones and clay, there will be no immutable pyramid. It can be seen that the preparation of basic knowledge is crucial for us to learn everything, so let's start from understanding some basic functions of Swing and start us to build a great project in Rome!

Preface

The Java cafe has been open for a long time. If you already like the taste of Java coffee, remember to come. This time, we have prepared a large cup of fragrant coffee for you. We will take the development of a "continuous watching" game as the blueprint and learn the usage of Swing in Java together, when you taste this cup of coffee carefully, you will find that not only does Java have a different flavor, but you have also learned how to develop professional games, which is the best of both worlds!

In order to make everyone better, it is a game. You can download the game trial (download the game program; download the source file) and run it using java-jar kyodai. jar in the command line mode. In addition, you can also go to my home http://www.ismyway.com to download this game single-host and mobile version for trial (see figure 1 ).

Java cafe has previously introduced AWT knowledge. What is the difference between Swing and AWT? Everyone who learns Java may have heard or seen the word heavyweight control and lightweight control. AWT is the heavyweight control we usually refer to, while Swing is a lightweight control. We all know that Java is a "one-time writing and running everywhere", which requires that we use Java-only code as much as possible in our programs. Unfortunately, AWT depends on the interface of the local platform. Therefore, on different operating systems, the interface created using AWT may look slightly different. Swing is completely different. Swing is written in pure Java. Therefore, the interface written in Swing ensures the same appearance on all platforms. Here is another tip: in JDK, for convenience, all Swing controls start with an uppercase letter J, for example, JButton (which corresponds to a Button in AWT ), in this way, you can easily distinguish between Swing controls and AWT controls.

Initial Swing experience

For those who want to learn Swing programming, We have specially prepared some tips for you. First, it is essential to download and read the code. Since this is a tutorial on Swing, we just try to explain some Swing-related content as much as possible. The content irrelevant to Swing is generally not involved, such as the algorithm part. Second, Due to space limitations, it is impossible to fully write every part of the code here. Therefore, you also need to check the complete code. Finally, in order to make it easier for everyone to focus on Swing learning, we also put the resources required for game development in the download file. After downloading, You can compile and run the game and see the execution results.

  1. Top-layer container

What is a top-level container? When we use Java for graph programming, where can we draw a graph? We need a container that provides graphic rendering. This container is called a top-layer container. You can also think of it as a window. The top-layer container is the basis for Graphic programming. All graphical items must be included in the top-layer container. In Swing, we have three top-level containers that can be used:

· JFrame: it is used to design applications similar to Windows.
· JDialog: similar to JFrame, but JDialog is used to design a dialog box.
· JApplet: used to design Java applets that can be embedded in webpages.

If you need to use Swing to create a window program, our code should look like this:

Import javax. swing .*;

Public class KyodaiUI
Extends JFrame {
......
}

  2. Controls

Controls are the basic elements of the application interface, including buttons, text boxes, and progress bars. Controls (only visual controls are discussed here) can be divided into container controls and non-container controls. Literally, a container control is a special control that can contain other controls. For example, a JPanel control in Java is a container control, we can place buttons, text boxes, and other non-container controls in JPanel. You can even place several JPanel controls in JPanel. (It is worth noting that the top-layer container is also a container control, each Window application can have only one top-level container control. In other words, the top-level container cannot be included in other controls ).

There are many container controls in Java. In addition to the JPanel mentioned earlier, there are also JTabbedPane and JScrollPane. Non-container controls include JButton, JLabel, and JTextField. If you need to add a control to a container-type control, you can use the add (Component comp) method to implement it, such:

JPanel panel = new JPanel ();
JButton button = new JButton ();
Panel. add (button );

  3. Layout

What is layout? Layout is an interface management system used in Java to control the widget arrangement. When people who have used other visual programming languages first came into contact with the Java interface design, they always felt awkward in the Java Interface Design: they did not provide the WYSIWYG method for setting control coordinates! However, it turns out that the layout management system provided by Java can also fulfill our needs well and be more advantageous in cross-platform development.

Common la s include:

· BorderLayout: a management system that divides the interface into upper, lower, and middle areas. In the BorderLayout layout, you can only put up to five controls. If there are more than five, we recommend that you use another layout system.
· GridLayout: GridLayout is a layout management system that splits the user interface into a board. If we want to design a calculator software similar to Windows, GridLayout is undoubtedly the best choice.
· FlowLayout: FlowLayout is not the same as the preceding two types of layout management systems. In FlowLayout, you do not need to specify where each control is stored. You only need to add the control to FlowLayout, flowLayout will place controls in sequence based on the order in which you add controls. If there is not enough space, it will automatically wrap the lines.

After having a basic understanding of these layout management systems, let's take a look at the interface design. After carefully observing the settings of "continuous viewing" In QQ games, we can find that the entire interface is divided into three areas, with the system menu area at the top, covering the largest area of the user's game area, there is also a user interaction zone, each of which consists of several controls.

Where can we start with so many controls? Since other controls can be placed in the container control, we only need to determine the container control to be placed. Now that we know the number of container controls to be used, let's go to the layout management system. Use GridLayout? It seems a little stubborn. Use FlowLayout? Are there any better options? By the way, you must have thought of BorderLayout, as shown in figure 2.

Before starting, you must note that the size of the interface should be considered first, whether it is the size of the main program interface or the size of each area. If no proper size is designed, changes will be very painful in the future.

The following is the source program:

Import java. awt .*;
Import javax. swing .*;

Public class KyodaiUI extends JFrame {
Public KyodaiUI (){
This. setSize (780,500); // set the form size to 780*500
This. setdefaclocloseoperation (JFrame. EXIT_ON_CLOSE );
This. setResizable (false); // the size of the form cannot be changed.
This. setTitle ("continuous playback"); // you can specify the title.

JPanel toolBar = new JPanel ();
ToolBar. setBackground (Color. white );
ToolBar. setPreferredSize (new Dimension (780, 48 ));

JPanel actionPanel = new JPanel (); // create a JPanel widget
ActionPanel. setBackground (Color. yellow); // sets the background Color.
ActionPanel. setPreferredSize (new Dimension (160,380); // set the size.

JPanel contentPanel = new JPanel ();
ContentPanel. setBackground (Color. blue );
ContentPanel. setPreferredSize (new Dimension (620,380 ));
This. getContentPane (). add (toolBar, BorderLayout. NORTH );
This. getContentPane (). add (actionPanel, BorderLayout. EAST );
This. getContentPane (). add (contentPanel, BorderLayout. CENTER );
}

  
Public static void main (String [] args) throws HeadlessException {
KyodaiUI kyodaiUI = new KyodaiUI ();
KyodaiUI. show ();
}
}

Let's take a look at how the above program runs. First, extends JFrame indicates that this is inherited from JFrame, and JFrame is the most basic top-layer container control. In fact, in JDK, all the controls with the letter J headers are Swing controls. The container attributes are set. setDefaultCloseOperation (JFrame. EXIT_ON_CLOSE) is used to tell the Java Virtual Machine to close the window process when you click "close" in the upper-right corner of the form. If you do not do this, you will find that although you can close the window, the program does not exit. In the following code, we added three Panel containers to the top-layer container. Note that in AWT, we can directly write it as add (toolBar, BorderLayout. in Swing, it must be written as getContentPane (). add (toolBar, BorderLayout. NORTH), otherwise the program will have an error.

Now, let's take a look at compilation and running. Is it the same as my running results (see figure 3 )?

  4. Border

Although we use different foreground views to distinguish different regions, we do not have a sense of excitement, and the border will certainly be much more beautiful.

In Java, all Swing controls with J headers can use the setBorder method to set borders for themselves. There are many kinds of borders, such as linear, raised, concave, and empty. You can even combine them to form a personal style. All Border must be created using the static method provided in javax. swing. BorderFactory. For example:

Border border = BorderFactory. createBevelBorder (BevelBorder. LOWERED,
New Color (45, 92,162 ),
New Color (43, 66, 97 ),
New Color (45, 92,162 ),
New Color (1, 84,123,200 ));

Now, we change toolBar. setBackground (Color. white) to toolBar. setBorder (border). Does the stereoscopic effect already show?

  Practice-write your name

Now we have an interface that can run. Although it can't do anything, please don't worry. Rome was not built in one day.

Now let's provide a "about" menu in the menu area to display program information. Don't you want others to know your name? Swing itself provides the ready-made button control JButton. We only need to create a new button: JButton about = new JButton ("about "); how can I put this button in the menu area instead of somewhere else? We can add the following code: toolBar. add (about); done. How can I click the button without response? This is because you have not told the program what to do when you click the button. To add event response for the button, you must first use about. addActionListener (this) tells the program to listen to the event when the button is pressed. Because ActionListener is a program interface, we have to make a small modification in the declaration of the class: public class KyodaiUI extends JFrame implements ActionListener {...} the ActionListener interface is implemented to tell the program that I want to handle the event. Of course, we have to add the code to respond to the event:

Public void actionreceivmed (ActionEvent e ){
If (e. getSource () = about ){
JOptionPane. showMessageDialog (this, "my name", "about ",
JOptionPane. INFORMATION_MESSAGE );
Return;
}
}

E. getSource () indicates the current control that triggers the event. Because our program usually has more than one control, these controls may generate events, therefore, we must use this method to find the control that generates the event.

  Summary

Let's take a look at what we have learned today: First, we understand the top-layer container, the controls are divided into container controls and non-container controls, and the border is used. Finally, we also handled the button event in a small way.

Let me leave some homework to help you consolidate what you have learned today: the buttons we added above are not beautiful in the middle of the menu bar, please try it on the left or right.

Finally, we will provide you with some good references:

● Creating a GUI with JFC/Swing
  
Http://java.sun.com/docs/books/tutorial/uiswing/index.html
● 2D Graphics
  
Http://java.sun.com/docs/books/tutorial/2d/index.html
● JDK API
  
Http://java.sun.com/j2se/1.4.2/docs/api/index.html

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.