Teach you how to use Java Swing to implement game development

Source: Internet
Author: User
Tags command line implement interface version window
The Java Café has been open for quite some time, and if you already like the taste of Java coffee, remember to come here often. This time, we have a big cup of coffee for everyone--it will be based on the development of a "watch" game, and you learn the use of swing in Java, when you carefully taste this cup of coffee, you will find that not only Java this cup of coffee also has a flavor, but also learned how to develop professional games , it's a good both worlds!

In order for everyone to sneak peek, the picture below is a screenshot of the game. You can download the game demo (download the game program; Download the source file) and then run it using Java-jar kyodai.jar on the command line. You can also download a stand-alone version of the game and a mobile version of my homepage http://www.ismyway.com (see Figure 1).

The Java Café has previously introduced AWT knowledge, so what is the difference between swing and AWT? People who study Java may hear or see the word Heavyweight and lightweight controls, and AWT is the heavyweight control we usually refer to, and swing is a lightweight control.

We all know that Java's slogan is "Write, run everywhere," which requires that in our program, try to use pure Java code. Unfortunately, AWT relies on the interface with the local platform, so using AWT-made interfaces on different operating systems may look slightly different.

Swing is completely different, and swing is written in pure Java, so the interface written using swing guarantees the same look on all platforms. Here's another tip: in JDK, for the sake of distinction, all swing controls start with a capital letter J, such as JButton (a button in AWT), so you can easily distinguish between swing controls and AWT controls.

  Swing First Experience

For friends who want to learn about swing programming, we have a few tips for everyone. First of all, downloading and reading the code is extremely necessary. Since this is a tutorial on swing, we're just trying to talk about some of the swing-related content, and nothing that has anything to do with swing is generally not involved, such as the algorithmic part.

Second, the space limit, it is not possible to write every part of the code is complete, so, we also need to look at the complete code. Finally, in order to make it easier for everyone to focus on swing learning, we also put the resources needed in the game development in the download file, you can download and then compile and run to see the results of the implementation. (download game source files)

  1, top layer container

What is a top level container? When we use Java for graphic programming, where does the diagram draw? We need a container that can provide graphics, a container that is called a top-level container, and you can think of it as a window. Top-level containers are the basis for graphic programming, and everything that is graphical must be included in the top-level container. In swing, we have three top-level containers that we can use, respectively:

· JFrame: Used to design an application similar to a window form in a Windows system.

· JDialog: Similar to JFrame, except that JDialog is used to design dialog boxes.

· JApplet: Used to design Java applets that can be embedded in a Web page.

If you need to use swing to make a window class program, our code should look like this:

       
        
         
        Import javax.swing.*;p ublic class Kyodaiuiextends JFrame {...}
       
        

  2. Control

Controls are the basic elements that make up the application interface, such as buttons, text boxes, progress bars, and so on, which are controls. Control (we only discuss visual controls here) and can be divided into container controls and non-container controls. In a literal sense, a container control is a special control that can contain other controls, for example, a JPanel control in Java is a container-type control, where we can place non-container controls such as buttons, text boxes, and so on, and you can even place several JPanel controls in JPanel ( It is noteworthy that the top-level container is also a container-type control, and that there is only one top-level container control in each window application, in other words, the top-level container cannot be included in other controls.

There are a lot of container controls in Java, in addition to the JPanel mentioned just now, there are JTabbedPane, JScrollPane, and so on, non-container controls have JButton, JLabel, JTextField, and so on. If you need to add a control to a container-type control, you can use the Add (Component Comp) method to implement it, such as:

       
        
         
        JPanel panel = new JPanel (); JButton button = new JButton ();p anel.add (button);
       
        

  3. Layout

What is a layout? A layout is an interface management system used in Java to control the placement of controls. People who have used other visual programming development languages will always feel awkward with Java interface design when they first touch the Java interface design: There is no way to set the control coordinates as you see it! However, it turns out that the layout management system provided by Java itself is also capable of performing our needs well, and is more competitive across platforms.

The common layouts are:

· BorderLayout: The interface is divided into the top and bottom of the management system in the middle of a region, in the BorderLayout layout, you can only put 5 controls, if more than 5 controls, it is recommended to choose other layout system.

· Gridlayout:gridlayout is a layout management system that cuts the user interface into a chessboard. If we're going to design a calculator software similar to that in Windows, GridLayout is definitely the best choice.

· Flowlayout:flowlayout and the two types of layout management systems are not the same, in FlowLayout, you do not have to specify where each control is placed, you just need to add controls to the FlowLayout, FlowLayout will place the control according to the order in which you add the controls, and if there is not enough space, the line will be automatically wrapped.

After the basic understanding of these several layout management systems, we will come into the interface design. After careful observation of the QQ game "repeatedly see" the setting, we can find that the entire interface is divided into three areas, the top is the System menu area, the largest area is the user game area, there is also a user interaction area, each area is composed of several controls.

So many controls, where do we start? Because other controls can be placed in a container control, we just need to determine which container controls are placed.

Now that we know the number of container controls that need to be used, let's move on to the choice of the layout management system. With GridLayout? Seems a little reluctant, with FlowLayout? Do you have a better choice? Yes, I think you must have thought of it as BorderLayout, as shown in Figure 2 below.

Before you start, you must note that the interface design to consider the size, whether the main program interface size or size of each area, if not designed to fit the size of the future changes will be very painful. The following are the corresponding source programs:

 
        
          Import java.awt.*;import javax.swing.*;p ublic class Kyodaiui extends JFrame {public kyodaiui () {this. SetSize (780, 500); Set the size of the form to 780*500this.setdefaultcloseoperation (Jframe.exit_on_close); this.setresizable (false); Form cannot change size this.settitle ("See Again");/Set title JPanel ToolBar = new JPanel (); Toolbar.setbackground (Color.White);  Toolbar.setpreferredsize (New Dimension (780, 48)); JPanel Actionpanel = new JPanel ();//new JPanel type Control Actionpanel.setbackground (Color.yellow); Sets the background color actionpanel.setpreferredsize (new Dimension (160, 380)); Set 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 works. First, extends JFrame shows that this is inherited from JFrame, and that JFrame is the most basic top-level container control. In fact, in JDK, controls that start with the letter J are swing controls.

The container's properties are then set, where Setdefaultcloseoperation (Jframe.exit_on_close) is used to tell the Java virtual machine to close the window process when the user clicks the Close button in the upper-right corner of the form. If you do not, you will find that although you can close the window, but the program does not exit.

In the next code, we added three panel containers to the top-level container. It is important to note that in AWT we can write directly as add (ToolBar, Borderlayout.north), while in Swing it must be written as Getcontentpane (). Add (ToolBar, Borderlayout.north), or the program will go wrong.

Now you can put it on the compile run to see if it's the same as my running results (see Figure 3)

4. Border

Although we use different foreground colors to distinguish different areas, but there is no sense of hierarchy, plus the border will certainly be much more beautiful.

In Java, all swing controls that start with J can use the SetBorder method to set a border for themselves. There are many kinds of borders, line style, raised, sunken, empty, you can even freely combine to form a personal style. All border must be created using the static method provided in Javax.swing.BorderFactory, such as:

       
        
         
        Border Border = Borderfactory.createbevelborder (bevelborder.lowered,new color (162), new color (in), new Color (162, MB), new color (84, 123, 200));
       
        

Now, we will change Toolbar.setbackground (Color.White) to Toolbar.setborder (border), the stereo effect has already appeared?

Combat-Write your name

Now that we have an interface to run, although it can not do anything, but please do not panic, Rome was not built in a day.

Now let's provide a "about" menu in the menu area to display information about the program, don't you want to let people know your name? Swing itself provides out-of-the-box button control JButton, we just need to create a new button: JButton about = new JButton ("about"); How does this button fit into the menu area instead of somewhere else?

We can add the following code: Toolbar.add (about); Hey, how come the button doesn't respond? This is because you haven't told the program what to do when you click the button. To add an event response to a button, you first need to use About.addactionlistener (this) to tell the program when the Listener button is pressed, because ActionListener is a program interface, so we have to make a little change 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, finally we have to add the code that responds to the event:

       
        
         
        public void actionperformed (ActionEvent e) {if (E.getsource () = about) {Joptionpane.showmessagedialog (this, "My Name", "about ", joptionpane.information_message); return;}}
       
        

where E.getsource () represents the control that is currently triggering the event, because there are often more than one control in our program, these controls can produce events, so we have to use this method to find the control that produces things.

  Summary

Let's look back at what we learned today: first we learned about the top-level container, we know that the controls are divided into container controls and non container controls, and we also know that borders are used, and finally, we handle the button's events a little bit.

Learn while learning, not also said, let me save a little homework, to help you consolidate what we learned today: The above we added buttons in the middle of the menu bar, not beautiful, please put to the left or right to try.

Finally, to 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



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.