Source of article: Computer Enthusiast Author: Zhang Jian
Who knows how much sand and stone was used to build the Tower of Babel? Who knows how many days and nights it took to build Rome? The only thing we know is that without the bricks and stones, there would be no Great Wall that winds thousands of miles; without the accumulation of boulders and clay, there would be no eternal pyramids. It can be seen that the preparation of basic knowledge is crucial for us to learn anything. So, let us start by understanding some basic functions of Swing and start our great project of building Rome!
Preface
Java Cafe has been open for a long time. If you already like the taste of Java's cup of coffee, remember to come often. This time, we have prepared a large cup of fragrant coffee for everyone - based on the development of a "Lianliankan" game, we will learn how to use Swing in Java with you. When you taste this cup of coffee carefully, you will I discovered that not only does Java have a unique flavor to my cup of coffee, but I also learned how to develop professional games. It’s really the best of both worlds!
To give you a sneak peek, the picture below is a screenshot of the game. You can download the game to try out (download the game program; download the source file), and then use java -jar kyodai.jar to run it in the command line mode. In addition, you can also go to my homepage http://www.ismyway.com to download the stand-alone version and mobile version of this game for trial play (see Figure 1).
Java Cafe has introduced the knowledge of AWT before, so what is the difference between Swing and AWT? Anyone who studies Java may have heard or seen the terms heavyweight controls and lightweight controls. AWT is what we usually refer to as heavyweight controls, and Swing is a lightweight control. We all know that the slogan of Java is "write once, run anywhere", which also requires that we use pure Java code as much as possible in our programs. Unfortunately, AWT relies on an interface to the native platform, so interfaces made with AWT may look slightly different on different operating systems. Swing is completely different. Swing is written in pure Java. Therefore, the interface written in Swing can ensure the same appearance on all platforms. Here's another trick: In the JDK, for easy differentiation, all Swing controls start with a capital letter J, such as JButton (the corresponding equivalent in AWT is Button), so that you can easily distinguish Swing controls from AWT controls.
Swing first experience
For those who want to learn Swing programming, we have specially prepared some tips for you. First, it is extremely necessary to download and read the code. Since this is a tutorial about Swing, we only try to explain some Swing-related content as much as possible. Contents unrelated to Swing will generally not be covered, such as the algorithm part. Secondly, due to space limitations, it is impossible to write every part of the code completely here, so you also need to compare it with the complete code. Finally, in order to make it easier for everyone to focus on learning Swing, we have also put the resources needed for game development in the download file. After downloading, you can compile and run it and see the execution results.
1. Top-level container
What is a top-level container? When we use Java for graphics programming, where are the diagrams drawn? We need a container that can provide graphics drawing. This container is called the top-level container. You can also think of it as a window. The top-level container is the basis for graphics programming. All graphical things must be included in the top-level container. In Swing, we have three top-level containers that can be used, they are:
・JFrame: Used to design applications similar to the window form in Windows systems.
・JDialog: Similar to JFrame, except that JDialog is used to design dialog boxes.
・JApplet: Used to design Java applets that can be embedded in web pages.
If we need to use Swing to create a window class program, our code should look like this:
import javax.swing.*;
public class KyodaiUI
extends JFrame {
…
}
2.Controls
Controls are the basic elements that make up the application interface. Buttons, text boxes, progress bars, etc., are all controls. Controls (here we only discuss visual controls) can be divided into container controls and non-container controls. Literally understood, a container control is a special control that can contain other controls. For example, the JPanel control in Java is a container control. We can place non-container controls such as buttons and text boxes in JPanel. You can even place non-container controls such as buttons and text boxes in JPanel. Place several JPanel controls in it (it is worth noting that the top-level container is also a container-type control. Each window application has and can only have 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 just mentioned, there are also JTabbedPane, JScrollPane, etc. Non-container controls include JButton, JLabel, JTextField, etc. If you need to add a control to a container type control, you can use the add(Component comp) method to achieve this, such as:
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 arrangement and position of controls. People who have used other visual programming development languages will always feel that Java interface design is awkward when they first come into contact with it: there is no WYSIWYG method for setting control coordinates! However, it turns out that the layout management system provided by Java itself can also fulfill our needs well, and it has more advantages in cross-platform performance.
Commonly used layouts are:
・BorderLayout: A management system that divides the interface into upper, lower, left, right and middle areas. In the BorderLayout layout, you can only place a maximum of 5 controls. If there are more than 5 controls, it is recommended to use other layout systems.
・GridLayout: GridLayout is a layout management system that cuts the user interface into a chessboard-like layout. If we want to design a calculator software similar to the one that comes with Windows, GridLayout is undoubtedly the best choice.
・FlowLayout: FlowLayout is different from the above two types of layout management systems. In FlowLayout, you do not have to specify where to place each control. You only need to add the controls to FlowLayout, and FlowLayout will place them in order according to the order in which you add the controls. The control will wrap automatically if there is not enough space.
After having a basic understanding of these layout management systems, let's get into interface design together. After carefully observing the settings of "Lianliankan" in QQ games, 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, and there is also a user interaction area. Areas, each area is composed of several controls.
With so many controls, where do we start? Since other controls can be placed in the container control, we only need to determine the container control to place first. Now that we know the number of container controls we need to use, let's go into the selection of the layout management system. Use GridLayout? It seems a bit forced, using FlowLayout? Is there a better option? By the way, I think you must have thought of BorderLayout, as shown in Figure 2 below.
Before getting started, everyone must pay attention to the fact that the interface design must first consider the size, whether it is the size of the main program interface or the size of each area. If the appropriate size is not designed, it will be very painful to change it in the future.
The following is the corresponding source program:
import java.awt.*;
import javax.swing.*;
public class KyodaiUI extends JFrame {
public KyodaUI() {
this.setSize(780, 500); //Set the size of the form to 780*500
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false); //The form cannot be resized
this.setTitle("Lianliankan"); //Set the title
JPanel toolBar = new JPanel();
toolBar.setBackground(Color.white);
toolBar.setPreferredSize(new Dimension(780, 48));
JPanel actionPanel = new JPanel(); //Create a new JPanel type control
actionPanel.setBackground(Color.yellow); //Set 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 works. First of all, extends JFrame indicates that it is inherited from JFrame, which is the most basic top-level container control. In fact, in the JDK, controls starting with the letter J are Swing controls. Then set the properties of the container. Among them, 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 don't do this, you will find that although you can click to close the window, the program does not exit. In the following code, we add three Panel containers to the top-level container. It should be noted that in AWT, we can directly write it as add(toolBar, BorderLayout.NORTH), but in Swing, it must be written as getContentPane(). add(toolBar, BorderLayout.NORTH), otherwise the program will go wrong.
Now you can compile and run it to see if it is the same as my running result (see Figure 3)?
4. Border
Although we use different foreground colors to distinguish different areas, there is no sense of hierarchy. It will be much more beautiful with a border.
In Java, all Swing controls starting with J can use the setBorder method to set borders for themselves. There are many kinds of borders, linear, raised, concave, and empty. You can even combine them freely to form your own style. All Borders must be created using the static methods provided in javax.swing.BorderFactory, such as:
Border border = BorderFactory.createBevelBorder(BevelBorder.LOWERED,
newColor(45, 92, 162),
newColor(43, 66, 97),
newColor(45, 92, 162),
new Color(84, 123, 200));
Now, we change toolBar.setBackground(Color.white) to toolBar.setBorder(border). Has the three-dimensional effect already appeared?
Practical combat - write your own name
Now we have a working interface. Although it can't do anything, don't panic. Rome wasn't built in a day.
Now let's provide an "About" menu in the menu area to display program information. Don't you want others to know your name? Swing itself provides a ready-made button control JButton. We only need to create a new button: JButton about = new JButton("about"); How should this button be placed in the menu area instead of elsewhere? We can add the following code: toolBar.add(about); Hey, why is there no response when clicking the button? 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 to listen for events when the button is pressed. Since ActionListener is a program interface, we also have to do a little bit in the declaration of the class. Modification: public class KyodaiUI extends JFrame implements ActionListener {...} The purpose of implementing the ActionListener interface is to tell the program that I want to handle events. Of course, finally we have to add the code to respond to the event:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == about) {
JOptionPane.showMessageDialog(this, "My name", "About",
JOptionPane.INFORMATION_MESSAGE);
return ;
}
}
Among them, e.getSource() represents the control that currently triggers the event. Since there are often more than one control in our program, these controls may generate events, so we must use this method to find the control that generated the event.
summary
Let's review what we learned today: First, we understand the top-level container, and we also know that controls are divided into container controls and non-container controls. We also know how to use borders. Finally, we also dealt with the buttons a little. event.
It goes without saying that you learn and practice as you go, so let me leave you with some small homework to help you consolidate what you have learned today: the button we added above is in the middle of the menu bar and is not beautiful. Please put it in Try it on the left or right.
Finally, I would like to provide you with some better reference materials:
●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