I studied with the Game Design Java Swing
Abstract: I studied with the Game Design Java Swing
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width="677" border="0"> <tr> <td width = " 395 ">
Who knows sky tower of Babylon spent a number of gravel? Who knows Rome experienced the completion of the number of day and night? We only know that there is no one piece of masonry features, there will be no winding Miles of the Great Wall; no boulder clay and the accumulation, there is no time immemorial unchanged pyramid. Thus, the basic knowledge for learning anything we are of the utmost importance, then, let us recognize Swing from some of the basic features, we have started the construction of Rome's great project!
Foreword
Java cafe has opened a lot of time, if you are already fond of the Java cup of coffee flavor, often to remember oh. This time, we all prepared for a large cup aromatic coffee - will be the development of a "Lianliankan" modelled on the game, and we learn together in Java Swing usage, when you taste carefully cup of coffee, you will found that not only Java cup of coffee also have some other flavor, but also learned the professional game development, is the best of both worlds!
</ Td> <td width="272" align="center"> </ td> </ tr> </ table>In order to let everyone see in advance the facilities, the chart is the title game. Members can download the game demo (download games; download source files), then use the command line mode java-jar kyodai.jar to run. In addition, I can go to the Home http://www.ismyway.com download stand-alone version of the game as well as a demo version of mobile phones (see Figure 1).
Java cafe previously introduced AWT knowledge, Swing and AWT then what is the difference? Learning Java people may have heard or seen a heavyweight controls and controls lightweight word AWT is that we usually referred to the heavyweight controls, it is lightweight Swing controls. We all know that Java is the slogan of "one preparation, running everywhere," which will require our procedures, to make the best use of pure Java code. Unfortunately, AWT rely on the local interface platform, therefore, in different operating systems, making use of AWT interface may seem there are some subtle differences. Swing is completely different, using pure Java Swing is prepared, therefore, prepared by the use of Swing interface can be guaranteed in all platforms have the same appearance. There is also a Tips: JDK, in order to facilitate the distinction between all Swing controls all capital letters J to the beginning, for instance, JButton (AWT in the corresponding Button is), so you can easily distinguish between AWT Swing controls and controls the.
Swing early experience
For those who want to learn Swing programming friends, we are all specially prepared for some tips. First, download and read the code is very necessary. Since this is a tutorial on the Swing, therefore, we are just as much as possible on some of the contents of the Swing, Swing has nothing to do with the content of the general will not be involved, for example, some algorithm. Secondly, to space restrictions, it will not be possible here will be part of the code is written in every End integrity of the whole, therefore, we also need to control integrity of the code. Finally, in order to make it easier for you to concentrate on Swing learning, we will also required in game development resources on the downloaded file, you can download after compiler operation, to see the results.
1. Top containers
What is the top containers? When we use graphical programming Java, where plans drawn? We need to provide a graphic containers, the containers are called top-level containers, and you can imagine it as a window. Top container is the foundation for graphical programming, and all graphical things will inevitably included in the top container. In Swing, we have the top three can be used in containers, they are:
JFrame: similar to the Windows operating system used to design window in the form of applications.
JDialog: JFrame and similar, but JDialog is used to design the dialog box.
JApplet: design can be used in embedded in the Web page Java applets.
If you need to use a window of Swing production processes, we should be the code looks like this:
Import javax.swing .*; Public class KyodaiUI (Extends JFrame …… )
2. Control
Control is an Application Program Interface of the basic elements, buttons, text boxes, such as the progress of these controls are. Controls (here we only discuss visualization Control) containers can be divided into control and non-control containers. From the literal meaning of understanding, containers can contain other controls that controls the special controls, for example, in Java JPanel controls on the type of vessel control, we can JPanel placed buttons, text boxes, and other non-container control , you can even further in the JPanel placed several JPanel Control (It is worth noting that the top container-type containers also controls every window in the application and there can be only one top containers controls, in other words , the top containers could not be included in the other controls).
Java containers in a lot of controls, in addition to the JPanel just mentioned, there are JTabbedPane, JScrollPane, a non-container control JButton, JLabel, such as JTextField. If you need to control a certain type of containers to add controls, you can use the add (Component comp) method to achieve, such as:
JPanel panel = new JPanel (); JButton button = new JButton (); Panel.add (button);
3. Layout
What is the layout? Java is the layout of controls are used to control the location of an interface management system. The use of other visual programming language Java in the initial contact interface design, always feel very uncomfortable Java interface design: there were no controls to provide WYSIWYG settings coordinate method! However, facts have proved that the layout of Java itself provide the same management system can be successfully fulfilled our needs, but also in cross-platform performance when there are more advantages.
The layout of commonly used are:
BorderLayout: interface will be divided into upper and lower middle, as well as about a regional management system, in BorderLayout layout, the most you can only put five controls, if more than five controls, the proposed distribution or use other systems it.
GridLayout: GridLayout user interface is the same cutting board for the distribution management system. If we are to design a similar built-in calculator in Windows software, GridLayout is undoubtedly the best option.
FlowLayout: FlowLayout layout with the above-mentioned two types of management systems do not, as in FlowLayout, you do not have to specify on which each control, you need only to control into FlowLayout, FlowLayout will, in accordance with you to add controls Controls placed the order, if the space is insufficient, will be automatically newline.
In the layout of this management system has several basic understanding, we have to design an interface to enter it. QQ in the careful observation of the game "Lianliankan" settings, we can be found, the entire interface is divided into three zones, is the top menu system, the area is the largest user games, in addition to a user Interactive areas, in each region by the number of control components.
So many controls, where we start with the beginning? The containers can be placed in the control of other controls, therefore, we have only to make sure the containers placed controls on it. Since it has been aware of the need to control the number of containers used, let us enter the next distribution management system. With GridLayout? Seems to be some reluctance by FlowLayout? There are better options? Right, I think you have thought of is BorderLayout bar, as shown in Figure 2.
Before hands, we must pay attention to is that the interface design must consider good size, is the main program interface regardless of the size or the size of each region, in the absence of good design appropriate size, with future changes will be very painful.
Below is the corresponding source:
Import java.awt .*; Import javax.swing .*; Public class KyodaiUI extends JFrame ( Public KyodaiUI () ( This.setSize (780, 500) / / set to form the size of 780 * 500 This.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); This.setResizable (false); / / size of the form can not be changed This.setTitle ( "Lianliankan"); / / Set Title JPanel toolBar = new JPanel (); ToolBar.setBackground (Color.white); ToolBar.setPreferredSize (new Dimension (780, 48)); JPanel actionPanel = new JPanel (); / / JPanel new type of control ActionPanel.setBackground (Color.yellow); / / Set the background color ActionPanel.setPreferredSize (new Dimension (160, 380)); / / size settings 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 us look at the above is how this process operates. First of all, this extends JFrame that is inherited from the JFrame, JFrame top container is the most basic controls. In fact, in the JDK, beginning with the letter J controls are Swing controls. And then set up a container attributes, including setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE) is used to tell the Java Virtual Machine, when users click on the upper right corner of the form "off" button, the process of closing the window. If we do not do so, you will find that although you can be dispatched window closed, but did not withdraw from the process. In the next code, we added three top containers Panel containers. It should be noted that in the AWT, we can write directly to add (toolBar, BorderLayout.NORTH), and it must be in the Swing wrote getContentPane (). Add (toolBar, BorderLayout.NORTH), otherwise the process will be wrong.
Now we can look at the operation on the compiler, and I was not running the same as (see Figure 3)?
4. Borders
Although we use different Jianjingse to distinguish between different regions, but did not layered with beautiful borders will be many.
In Java, all J beginning of the Swing controls can be used for setBorder ways to set up their own borders. There are many types of borders, linear, convex, Waxia, air, and you can even free combination formed personal style. All Border javax.swing.BorderFactory must be provided in the use of the static method to create, 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 (84, 123, 200));
Now, we will toolBar.setBackground (Color.white) to toolBar.setBorder (border), the three-dimensional effect is not there have been?
Actual combat - write their own name
Now we have a functioning interface, although it do anything, but please Biehuang, Rome was not built in one day.
Let us now in the area to provide a menu "on the" menu, the procedures used to display information, can you do not want to let others know your name? Swing itself provides a ready JButton button control, we only need to create a new button: JButton about = new JButton ( ""); how this button into the menu area and not elsewhere? We can join the following code: toolBar.add (about); Yi, how push of a button does not respond? This is because you have not told the procedures to be done at the click of a button is what happened. Add the button to respond to the incident, first of all, need to use about.addActionListener (this) to tell procedures eavesdropping button pressed the incident, due ActionListener is a procedural interface Therefore, we stated in the category have to do a bit of local small Laws: public class KyodaiUI extends JFrame implements ActionListener {…} achieve ActionListener interface to tell the procedures I have to carry out the deal with the incident. Of course, we must add the final response to the incident code:
Public void actionPerformed (ActionEvent e) ( If (e.getSource () == about) ( JOptionPane.showMessageDialog (this, "My name", "on", JOptionPane.INFORMATION_MESSAGE); Return; ) )
Among them, e.getSource () that controls the current trigger events, as we often have procedures in a number of the above controls, these controls are likely to produce the event, we must use this method to find an issues Control.
Summary
Let us together look at the content of today: First, we know the top-level containers, know that the control is divided into control and non-container vessel control, but also noted that the use of frames, finally, we also deal with minor a touch of a button events.
When learning of the school and not between also said that, let me leave small operations to help consolidate what we have learned today: Add button above us in the middle of the menu bar is not handsome, please put Try the right or left.
Next: Java Swing with me in the game design (2)
Remember "plays an activist miner" as in the Wizard shuttle traffic in Hollywood in the Minicooper? Makewoerbage and Shali Sialon is driving its enemies under the nose removed 10 million worth of gold. However, if one can not now Minicooper appearances on the Mercedes-Benz in front of you, how would you treat it? It is the same ease of migration wizard? Today, let us point to 1.1 for这辆Minicooper parts on the assembly and let it run up.
Foreword
Starting from this issue, we provide you with complete source code of the game (click to download). Java cafe advocacy we both theory and practice, we will introduce series of key technologies and the realization of ideas, and friends, read the article with their own source code, like the side of a cup of coffee while reading newspapers, and this is never drops of aromatic Italy do.
Game layout
"Lianliankan" is a two-dimensional Zhanji games, it is necessary to design the chessboard of the game, should be GridLayout Mr Chong. Now let us look at a GridLayout to the constructor function:
GridLayout (): the default case, the layout of the region into the size of 1 * 1
GridLayout (int rows, int cols): designation of the regional distribution of horizontal and vertical grid of
GridLayout (int rows, int cols, int hgap, int vgap): Ditto, and also designated each lattice spacing between the horizontal and vertical spacing vgap hgap
Do not let the three million constructor function deterred you to the fact, as long as you like, can rest assured bold use of any one of which, if not carefully used "wrong", also after adjustment approach. Only need to pay attention to that, in addition GridLayout control, the default order is from the upper left to lower right were added.
Let us now to determine the number of games lattice. Lattice how many more appropriate? Too little will reduce the difficulty of the game, too much will cause visual impact. Therefore, we should, through a constant for the future even if changes are Jushouzhilao.
In Java, the constant need for the definition of public final static written in the form of the game if we stipulate that the board has eight in the horizontal grid, there are also eight vertical lattice, then we should take this definition:
Public final static int ROW = 8; Public final static int COLUMN = 8;
Then, we use the second constructor function GridLayout to create layout:
GridLayout gridLayout = new GridLayout (ROW, COLUMN);
Finally, we also need to play area (contentPanel) to the layout of the layout:
ContentPanel.setLayout (gridLayout);
If you compile and run a program at this time, you may be surprised: Interface how there had not been any change, which is not wrong? Although we designated the layout, but also did not add any controls, of course, to see changes. Let us together in the layout on the Add button bar:
For (int i = 0; i <ROW * COLUMN; i + +) ( JButton button = new JButton ( "Kyodai"); ContentPanel.add (button); )
Try to run a program, and I was not the same (see Figure 1)?
Using make a fuss about JButton
JButton is a button control, it is common in Swing are not ordinary longer controls, nevertheless, we still need to spend some effort to understand and use it, because when you can skillfully use JButton, you will find that other Swing Control is also so similar.
If you have written operating procedures used, you will find: the game is always a very full button, and it is very real inconvenience to the operation of the game, so we have to find ways to let out some air lattice. GridLayout layout of what is good, adding that the controls when not skip a certain lattice, Yanxiage how do?
In fact, this will not be difficult, since GridLayout from Skip, if we allow the addition of a lattice GridLayout layout of the controls and the integration background, so that the visual reach a consensus on the results. In addition, if people accidentally click on this lattice, the button still will be reversed and we have to try to not let the button is clicked, and this requires the use JButton setEnabled () method. Finally, can click on the button, and when they are clicked, we need to distinguish between what is out which button was clicked on.
In the last to achieve the "on" function, we used the e.getSource () method to determine your mouse, click on the source of the incident, however. That good name has been on the controls more effective. Here, the use of an array of buttons that is the best way to, first of all, let us amend the above code:
JButton [] = new JButton dots [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 in the circle of dots on the [i] = new JButton ( "Kyodai"), although in the previous definition, the use of a group of dots, but it is only just told procedures we need to use some of JButton, but these JButton but still have not been initialized. At the same time, we not only use setActionCommand () for the development of the incident button name, also used the addActionListener () method for each button with the incident response handling.
On the incident response code, we can in the original actionPerformed () code inserted after the incident:
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 used to determine whether the incident is JButton the type of control, and then the source will produce the event-type controls to mandatory conversion, re-use Integer.parseInt (button.getActionCommand ()) method to obtain the name of the incident into integer, as the code will make the trip and the integer reduction in the information.
Well, operational procedures, and then click each button to see whether there will be any of the dialog box as pictured?
Attention Oh, our next objective is to start from zero.
Swing in the use of picture
At present we have solved the problem of the user operation. To handsome interface, we need to use the picture to replace text. Have the time and patience of friends can do their own personalized picture, but should pay attention to each picture the same size, otherwise difficult Kanla. Think it can be easy to use packages downloaded directly in the picture.
In Swing, you can use setIcon (Image image) method to set up JButton picture, which is that the parameters of image we want to set the picture object, and this object can be a number of ways:
Use Toolkit class to be:
Image = Toolkit.getDefaultToolkit (). GetImage (url);
Use ImageIcon class getImage () method to obtain:
Image = new ImageIcon (getClass (). GetResource (filename)). GetImage ();
Here we use the first method. In order to facilitate future access to the Image object again, 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, the picture later on to use more convenient, is not it?
Picture now have, then we would be in the source code package Map.Java map information in the form of performance using picture out. Because this section of the game is code algorithm code, it is no longer listed code, and here is broadly explain how specific do! In Map.Java, we used two-dimensional array map [] [] to preserve picture information, and we also use the one-dimensional images [] array to preserve a picture of each object, a map of each element are have a value, this value has not only shown that in the game interface buttons corresponding value, this button also shows that the use of images in the picture [] array of numbers, it is running pretty many interface.
Summary
Today, we introduced the Swing of JButton controls. For most Swing controls, the use of JButton can copy the past. Do not underestimate this JButton, when you can grasp it very well when you have the Swing on the foundation of the upgrade to a higher level. In addition, we also learned in Java loading image files are two methods. Finally, we will be part of the contents of the above two together and created a beautiful interface of the game. Although I am not here to write integrity of the code, but I believe that the reference to the source, through its own efforts, we can achieve our goals. If they can not solve the problems, you can contact me leftmoon@163.com Box
↑ Back
Tags: java game, java swing






