7.1 Swing Introduction
7.1.1 Introduction
The fifth lecture we learned AWT, AWT is the foundation of Swing. The main reason for SWING is that AWT does not meet the development of graphical user interface. The original intention of the AWT design is to support the simple user interface for developing a small app. For example, AWT lacks the characteristics such as clipboard, print support, keyboard navigation, and the original AWT does not even include basic elements such as popss menus or scroll panes.
In addition, AWT still has serious defects, and people make AWT to inherit, and have significant flexible event models, and the independent architecture is also a fatal weakness.
With the development of development, Swing has appeared, and Swing components are almost lightweight components. Compared with weight components, there is no local peer components, unlike weight components to be drawn, lightweight in their own local opaque form. The components are drawn in the window of their weight components.
This lecture us to talk about the basic Swing component usage and use the SWING component to create a preliminary method of user interface.
Swing is implemented by 100% pure Java, the Swing component is a light-weight component implemented by Java, no local code, does not rely on the operating system support, this is the greatest difference from the AWT component. Since the AWT component is implemented by the peer-related peer (Peer) associated with the specific platform, Swing has stronger practicality than the AWT component. Swing is consistent on different platforms and is capable of providing other features that are not supported by local window systems.
Swing uses a MVC design paradigm, "Model-View-Controller", where the model is used to save content, the view is used to display content, and the controller is used to control the user input.
Swing appearance feels using the insertable appearance (Pluggable Look and Feel, PL & F)
In the AWT component, since the peer-to-peer class of the control component is related to the specific platform, the AWT component is always only the appearance associated with the unit. Swing makes the program can have different appearances when running on a platform. Users can choose the appearance of your habits. The following three figures are different in the same operating system.
Metal style
MotiF style
Windows style
7.1.2 Swing class hierarchy
In a javax.swing package, two types of components are defined: the top container (JFrame, Japplet, JDIALOG, and JWINDOW) and lightweight components. The Swing components are all direct subclasses and indirect subscms of the Container class of the AWT. Java.awt.component -java.awt.container -java.awt.window -java.awt.frame-javax.swing.jframe -javax.dialog-javax.swing.jdialog-javax.swing.jwindow -java.awt. Applet-javax.swing.japplet -javax.swing.box -javax.swing.jcomponet
Swing package is part of JFC (Java Foundation Classes, consisting of many packets, as follows:
Package description com.sum.swing.plaf.motif user interface representative class, which implements Motif interface style com.sum.java.swing.plaf.windows user interface representative class, which implements Windows interface style Javax.swing Swing Components and Tools Javax.swing.border Swing Lightweight Component Border Javax.swing.colorchooser JColorchooser's support class / interface javax.swing.Event event and listener class javax.swing.Filechooser JFilechooser support class / interface javax.swing.pending Fully implemented Swing Components Javax.swing.plaf Abstract Class, Define the behavior of the UI representative javax.swing.plaf.basic implements the base class of all standard interface style public features Javax.swing.plaf.Metal user interface representative class, they implement Metal Interface style javax.swing.table jtable component javax.swing.text supports document display and editing javax.swing.text.html Support display and editing HTML document javax.swing.text.html.Parser HTML document analyzer Javax.swing .Text.rtf supports the support of the RTF file Javax.swing.Tree JTREE component support class Javax.swing.undo supports the cancel operation (in JDK1.3, the first, second and pending packets are not, add PLAF. MULTI package, main function: add additional L & f to the default L & f, such as a Multibuttonui instance can handle Motifbuttonui and Audiobuttonui at the same time.)
The Swing package is the biggest package provided by Swing, which contains nearly 100 classes and 25 interfaces, almost all Swing components are in the swing package, only JtableHeader and JtextComponent are exception, they are in swing.table and swing.text, respectively. Events and event listener classes are defined in the Swing.Border package, similar to the Event packet of the AWT. They all include event classes and listener interfaces. The swing.pending package contains a Swing component that is not fully implemented. The Swing.Table package mainly includes a support class for the table formation (JTABLE). Swing.tree is also a support class for JTree. Swing.text, swing.text.html, swing.text.html.Parser and Swing.Text.rtf are all packaged for display and editing documents. 7.1.3 Diversification of SWING Components
Swing is an extension of AWT, which provides a number of new graphical interface components. The Swing component starts with "J", in addition to the basic components such as the AWT, TABEL (JLabel), check boxes (JCheckbox), Menu (JMenu), etc., also adds a rich high-level component collection, As a table (JTABLE), JTREE. 7.1.4 MVC (Model-View-Control) Architecture
The main advantage of Swing is over AWT is the common use of the MVC architecture. In an MVC user interface, three communication objects: models, views, and controls. The model is a specified logical representation, and the view is a visual representation of the model, and the control specifies how to handle user input. When the model changes, it notifies all views depending on its view, and the view uses the control to specify its corresponding mechanism. In order to simplify the design of the component, the view and controls in the Swing component are integrated. Each component has a associated separation model and the interface it uses (including views and controls). For example, the button JButton has a separation model ButtonModel object that stores its status. Components' models are automatically set, for example, JButton is usually used instead of using the ButtonModel object. In addition, by the subclass of the MODEL class or by implementing an appropriate interface, they can establish their own models for components. Connect the data model to the component with the setmodel () method. MVC is a general idea for making graphical user interfaces in existing programming languages, and its idea is to separate the content itself of the data and the display method so that the display of data is more flexible. For example, the number of students in each class of each class is data, and the display mode is a variety of, which can be displayed in a column chart, or the pie chart is displayed, and a direct data output can also be used. Therefore, it is very helpful to consider the data and display mode when designing, which is very helpful for implementing a variety of displays.
7.1.5 Cableable Support
All SWING components implements Accessible interfaces, providing support for accessibility, allowing accessibility such as screen readers to get information from Swing components.
7.1.6 Support keyboard operation
In the Swing component, the REGOSTERKEYBOARDACTION () method of the JComponent class can enable the user to replace the corresponding action of the SWING component on the mouse drive in the mouse drive. Some classes provide a more convenient way for keyboard operations.
In fact, this is equivalent to the hotkey, so that the user can operate only with the keyboard.
7.1.7 Setting Border
One and multiple borders can be set to the SWING component. Swing provides a wide range of borders for users to choose, and can also create a combined border or its own design border. A blank border can increase the component to assist layout managers to make reasonable layouts on components in the container. 7.1.8 Using Icons (icon)
Unlike AWT parts, many Swing components such as buttons, labels, in addition to using text, can also use icons to modify yourself.
Example 7.1: Import javax.swing. *; // Introduced Swing Package // Import com.sun.java.swing. *; // Using JDK 1.2 Beta 4 and all Swing 1.1 beta 3 // Previous versions Introduce the Swing package name. import java.awt *; import java.awt.event *; public class SwingApplication {private static String labelPrefix = "Number of button clicks:";.. private int numClicks = 0; // counters, counting clicks public Component createComponents ( ) {Final Jlabel Label = New Jlabel (LabelpRefix "0");
JButton Button = New JButton ("I'm A Swing Button!"); Button.setmnemonic (KeyEvent.vk_i); // Setting the button of the hotkey for 'i' Button.AddActionListener (New ActionListener () {Public Void ActionPerformed ActionEvent E) {NumClicks ; Label.Settext (Labelprefix NumClicks); // Displays the number of clicks}}}}); Label.SetLabelFor (Button); / * The common way to place space between the top container and its content is Add content to JPANel, and JPanel itself does not have a border. * /
JPanel Pane = New jPanel (); Pane.SetBorder (BorderFactory.createemptyborder (30, // TOP 30, // Left 10, // Bottom 30) // Right); Pane.setLayout (New GridLayout (0, 1)) ; // single column multi-line Pane.Add (Button); Pane.Add (Label); Return Pane;}
Public static void main (string [] args) {try {uimanager.setlookandfeel (uimanager.getcrossplatformlookandfeelclassname ()); // Setting window style} catch (Exception E) {}
// Create a top-level container and add content JFrame frame = new JFrame ( "SwingApplication");. SwingApplication app = new SwingApplication (); Component contents = app.createComponents ();. Frame.getContentPane () add (contents, BorderLayout.CENTER );
// Window setting end, start display frame.addwindowlistener (new windowadapter () {// anonymous class for registration listener public void windowclosing (windowevent e) {system.exit (0);}}); frame.pack () Frame.setVisible (TRUE);}}
View Run 7.1.9 Swing Program Structure Introduction
Swing programming can generally be performed in accordance with the following procedures: 1. The Swing package 2 is introduced. Select "Appearance and Feeling" 3. Set the top container 4. Set buttons and labels 5. Add component 6 to the container. Add a boundary 7 around the component. Event processing
Example 7.1 illustrates the structure of the Swing medium and the most basic components Button and Label. In the program, we build a Swing style window and add a button in it. Save a counter in the program to calculate the number of times the button is clicked, and use a Label after each click. In this program we can see the use of the use of the Swing component consistent with the basic method of the AWT component, and the event processing mechanism used is exactly the same. These have been talked in front of the AWT, and will not be described again. 7.2 SWING components and containers
Alternatively, some of the other features are included in the Swing components in SWING, but also some of the other features are included in the AWT. For example, Swing buttons and tags can display icons and text, and AWT's buttons and tags can only display text. Most components in Swing have a "J" plus "J" in front of the AWT component name. 7.2.1 Classification of Components
Components from functional division
Special function division of the JComponent class
JComponent is an abstract class that defines the general method of all subclass components, and its hierarchical structure is as follows:
Java.lang.Object | - java.awt.component | - java.awt.container | - javax.swing.jcomponent
Not all SWING components are inherited in the JComponent class, and the JComponent class inherits in the Container class, so that such components can be used as a container.
Components can be divided into:
1) Top container: JFrame, Japplet, JDialog, Jwindow total 4
2) Intermediate container: JPanel, JscrollPane, Jsplitpane, JToolbar
3) Special containers: Intermediate layers of special role in GUI, such as JinternalFrame, JLayeredPane, JRootpane.
4) Basic controls: Implement interpersonal interaction components such as JButton, Jcombobox, Jlist, JMenu, Jslider, JtextField.
5) Display that cannot be editable: Displays components that cannot be editable information to users, such as Jlabel, JProgressBar, Tooltip.
6) Display of editable information: Displays components that can be edited to formatted information, such as Jcolorchooser, Jfilechoose, JFilechooser, JTable, Jtextarea.
The special features of the JComponent class are divided into:
1) Border setting: Use the setBorder () method to set the frame peripheral frame, using an EmptyBorder object to leave a blank around the component.
2) Double buffer: Use dual buffer technology to improve frequently changing components display effect. Unlike the AWT components, the JComponent component defaults double buffer, and does not have to rewrite the code. If you want to close the dual buffer, you can apply a setDoublebuffered (false) method on the component.
3) Tip information: Use the settooltext () method to set the prompt information to the user to the user.
4) Keyboard Navigation: Use the registerKeyboardAction () method to drive the components with the keyboard instead of the mouse. Sub-class AbstractButton for JComponent classes also provides a convenient way - using the setmnemonic () method to specify a character, and activate the button action through this character and a special modification of the current L & F. 5) Insert L & F: Each JComponent object has a corresponding ComponentUI object that completes all paintings, event processing, and decision size. The Componentui object relies on the current L & F that can be set with the UIManager.SetLookAndfeel () method to set the required L & f.
6) Support layout: By setting the maximum, minimum, recommended size method and setting X, Y alignment parameter value, specify the constraints of the layout manager, and supports the layout. 7.2.2 Basic rules using SWING
Unlike AWT components, Swing components cannot be added directly to the top container, which must be added to a content panel associated with the Swing top container. The content panel is a normal container contained in the top container, which is a lightweight component. The basic rules are as follows: (1) Put the SWING component into the content panel of a top Swing container (2) Avoid using non-Swing heavyweight components.
There are two ways to add components for JFrame: 1) Get JFrame's content panel with getContentPane () method, add components to the component: frame.getContentPane (). Add (childcomponent) 2) Create an intermediate container such as JPanel or JDESKTOPA Add the components to the container, with the setContentPane () method to set the container as the content panel of JFrame: jPanel contentpane = new jPanel (); ... // Add other components to JPANEL; Frame.setContentPane (ContentPane); // Set the ContentPane object to the content panel of Frame 7.2.3 Various container panels and components
7.2.3.1. Root panel (JRootpane)
The root panel consists of a glass panel, a content panel, and a selectable menu bar (JMenubar), while the content panel and the selectable menu bar are placed in the same layer. The glass panel is completely transparent, the default is invisible, providing a mouse event and a drawing on all components.
The method provided by the root panel: Container getContentPane (); // Get the content panel setContentPane (Container); // Setting the content surface JMenuBar getmenubar (); // Active menu strip setmenubar (jMenubar); // Set the menu step JLAYEREDPANE GetLayeredPane () ; // Get a layered panel setLayeredPane (JLayeredPane); // Set the layered panel Component getGlassPane (); // Get glass panel setglasspane (Component); // Set the glass panel 7.2.3.2 Differential panel (JLayeredPane)
Swing provides two layered panels: JlayredPane and JDESKTOPPANE. JDESKTOPPANE is a subclass of JLayeredPane, which is set to accommodate the internal framework (JinternalFrame). Add components to a layered panel, which requires which layer to add it, indicate that the component is in this layer: Add (Component C, Integer Layer, int position).
7.2.3.3 Panel (JPANEL)
The panel (JPANEL) is a lightweight container assembly, which is the same as panel, used to accommodate interface elements to accommodate more components under the setting of the layout manager, and implement the nested container. JPanel, JScrollPane, JSPLITPANE, JINTERALFRAME are all common intermediate containers, which are light components. JPanel's default layout manager is FlowLayout.
Java.lang.object | - java.awt.component | - java.awt.container | - javax.swing.jcomponent | - javax.swing.jpanel
7.2.3.4 Rolling window (JScrollpane)
JscrollPane is a panel with a scroll bar, mainly by moving JVIEWPORT. JViewPort is a special object that is used to view the basement component. The scroll bar is actually moving along the component, while depicting it "see" below. 7.2.3.5 Splitter (JSPLITPANE)
Java.lang.object | - java.awt.component | - java.awt.container | - javax.swing.jcomponent | - javax.swing.jsplitpane
JSPLITPANE provides a split window that supports horizontal splitting and vertical split and has a slider. Common methods include: addImpl (Component Comp, Object ConsTraints, int index) // Adds the specified component settopComponent (Component CoMP) // Setting the top component setDividersize (int newsize) // Setting the Split Split Setui / Splitpaneui UI) / / Set the appearance and feel 7.2.3.6 Options panel (JTABBedPane)
JTabbedpane offers a set of keyboards with labels or icons for users. Common methods: add (string title, component component) // Add a component AddChangeListener (ChangeListener L) // tab with a specific tag to register a change listener 7.2.3.7 toolbar (JTOOLBAR) toolbar in the upper left corner
Toolbar on the right side
JToolBar is a container for displaying common tool controls. Users can drag out a separate window of the display tool control. Common methods include: JToolbar (String Name) // Structure GetComponentIndex (Component C) // Returns a component GetComponentAnsDex (INT i) // Get a specified number of components 7.2.3.8 Internal Framework (JinternalFrame) Internal Framework JinternalFrame As one window is inside the other window, the features are as follows: 1) You must add the internal frame to a container (usually jdesktoppane), otherwise it is not displayed; 2) Do not need to call the show () or setvisible () method, the internal framework The container is displayed together; 3) The frame size must be set with setsize () or pack () or setbounds method, otherwise the size is zero, the frame cannot be displayed; 4) You can set the internal frame in the container with setLocation () or setbounds () method. The location, the default is 0, 0, that is, the upper left corner of the container; 5) Like the top-level JFRAME, adding components to the internal framework to add the content panel; 6) Create a dialog in the internal framework, You cannot use JDIALOG as a top window, you must use JOPANE or JINTERNALFRAME; 7) The internal framework cannot listen to window events, and can process the internal frame window by listening to the internal framework similar to the window event (jinternalFrameEvent).
JFrame frame = new JFrame ( "InternalFrameDemo"); // instantiate window JDesktopPane desktop = new JDesktopPane (); // instantiate container JDesktopPane MyInternalFrame myframe = new MyInternalFrame (); // instantiate the inside of the window desktop.add (myframe) ; // Add the internal window to myFrame.setSelected (TRUE) in the container; // The internal panel is the optional frame.setContentPane (Desktop); // Set Desktop 7.2.3.9 button (JButton)
The button is a common component, buttons can be labeled or image.
Java.lang.Object | - java.awt.component | - java.awt.container | - javax.swing.jcomponent | - javax.swing.abstractButton | - javax.swing.jbutton
Commonly used constructors include: JButton (icon icon) // displays the icon jbutton // button on the display character jbutton (String text, icon) // on the button to display the icon and display character
Example 7.2 public class ButtonDemo extends Jpanel implements ActionListener {JButton b1, b2, b3; public ButtonDemo () {super (); ImageIcon leftButtonIcon = new ImageIcon ( "images / right.gif); // displayed on the left button IMAGECION MIDDLEBUTTONICON = new imageicon ("images / middle.gif); // Display icon on the intermediate button ImageICON MIDDLEBUTTON = new imageicon (" imageless / left.gif); // Display icon on the right button B1 = New JButton ("Disable Middle Button"; // The button B1 is displayed simultaneously on the text and icon B1.SetVerticalTextPosition (AbstractButton.center); // The text on the button B1 is a central alignment B1.SethorizontalTextPosition (AbstractButton) in the vertical direction. LEFT); // The text on the button B1 is the left aligned B1.SetmNemonic ('d'); // set the alternative keyboard button of the button B1 is 'd' b1.setActionCommand ("diaable"); ...}} 7.2.3.10 checkbox (JCheckbox)
The checkbox provides a simple "ON / OFF" switch, next to the text tab.
7.2.3.11 radio box (JRADIOBUTTON)
The radio block JRADIOBUTTON is similar to the checkbox group function in the AWT. 7.2.3.12 Select Box (JCOMBOBOX)
JCOMBOBOX can only select one of them, but edit each of the contents, and each item can be arbitrary, and it is no longer limited to String.
7.2.3.13 File Selector (JFilechooser)
JFilechooser has "Open", "Storage", and can define other types of dialogs themselves.
7.2.3.14 Tags (JLabel)
Provide graphic labels
7.2.3.15 List (LIST)
Suitable for more options display in a list, and the items inside can be constructed of any type object. Support radio and multi-selection. 7.2.3.16 Menu (JMenu)
The difference between JMenu and AWT menu Menu is that it can be placed in any place in the container via setjmenubar (menubar). 7.2.3.17 Processes (JProgressBar)
The process strip is a process of providing an intuitive graphical schedule, from "empty" to "full" process. 7.2.3.18 Sliding strip (JSLIDER)
The slider allows the user to enter data through a slider. 7.2.3.19 Form (JTABLE)
The form is a newly added component of Swing. The main function is to display the data in the form of a two-dimensional table. Using the table, according to the MVC's idea, it is best to represent the data of a MyTableModel type, which is inherited from the AbstractTableModel class. There are several ways to rewrite, such as getColumncount, GetRowcount, getColumnname, GetValueat. Because JTable will automatically obtain the data necessary to display the data from this object, the object of the AbstractTableModel class is responsible for the determination of the size of the table (line, column), the content of the content, the value, the detection of the table unit update, etc. Everything is related to the table content Attributes and their operations. The object generated by the JTABLE class is used by this TableModel and is responsible for displaying the data in the TableModel object in the form of a table. The common method of the JTABLE class has: getModel () // Gets the data source object of the table contains the data // below the table to display the data // below the table, the first parameter is data, The second parameter is the content displayed in the first line of the table (Object [] rowdata, object [] columnnams; jtable (Vector [] [] rowdata, vector [] columnnams;
Example 7.3 RecorderOfWorkers import javax.swing.JTable; import javax.swing.table.AbstractTableModel; import javax.swing.JScrollPane; import javax.swing.JFrame; import javax.swing.SwingUtilities; import javax.swing.JOptionPane; import java. IMPORT JAVA.AWT.EVENT. *;
public class TableDemo extends JFrame {private boolean DEBUG = true; public TableDemo () {// constructor implemented super ( "RecorderOfWorkers"); // call the parent class constructor first JFrame generating a window MyTableModel myModel = new MyTableModel (); // mymodel storage table data jtable table = new jtable (mymodel); // Table object Table data source is the MyModel object Table.SetPreferredScrollableViewPortsize (New Dimension (500, 70)); // Table display size
// Generate a panel JScrollPane scrollpane = new jscrollpane (table) with a scroll bar;
// Add the panel of the scroll bar to getContentPane (). Add (scrollpane, borderlayout.center);
AddWindowListener (New Windowadapter () {// Register window listener public void window listener (WindowEvent E) {system.exit (0);}});} // Put the data to display in the table and Object The contents of the first line in the Class MyTableModel Extends AbstractTableModel Extends AbstractTableModel {// table are placed in a string array columnNames in the character string [] columnnames = {"first name", "position", "telephone", "MONthlyPay", " Married "}; // Save content in each line in the table in 2D array DATA Final Object [] [] Data = {" WANGDONG "," Executive "," 01068790231 ", New Integer (5000), New Boolean (false )} {"Lihong", "Secretary", "01069785321", New Integer (3500), New Boolean (TRUE)}, {"Lirui", "Manager", "01065498732", New Integer (4500), New Boolean (False)}} {"Zhaoxin", "Safeguard", "01062796879", New Integer (2000), New Boolean (TRUE)}, {"Chenlei", "Salesman", "01063541298", New Integer (4000), New boolean (false)}}; // The following method is to rewrite the party in AbstractTableModel Method, its main use is called by the JTable object to display correctly in the form. The programmer must be properly implemented according to the type of data used. // Receive the number of PUBLIC INT getColumnCount () {Return ColumnNames.Length;}
// Get the number of lines public int getrowcount () {return data.length;}
// Get a column name, and the names of the current columns are saved in the string array columnnames PUBLIC STRING GETCOLUMNNAME (INT COL) {Return ColumnNames [col];
// Get the data of a column of a row, and the data is saved in the object array data in the target array DATA PUBLIC OBJECT GETVALUEAT (INT ROW, INT COL) {Return Data [Row] [col];
/ / Judgment the type of PUBLIC CLASS GETVALUMNCLASS (0, c) .Getclass ();} //} //} // State the table as editable public boolean iscelleditable (int Row, int co) {
IF (col <2) {return false;} else {return true;}}
/ / Change the value of a data public void setValueat (Object Value, int Row, int co {if (debug) {system.out.println ("Setting value at" row ", col " to " Value " Value.getClass () ") ");
IF (Data [0] [col] instanceof integer &&! (value instanceof integer) {Try {data [row] [col] = new integer (value.tostring ()); fiRetablecellupdated (row, col);} catch NumberFormatException e) {JOptionPane.showMessageDialog (TableDemo.this, "The /" " getColumnName (col) " / "column accepts only integer values");.}} else {data [row] [col] = value; fireTableCellUpdated (row, col);
IF (debug) {system.out.println ("New Value of Data:"); PrintDebugdata ();}}
Private void printdebugdata () {Int nuMrows = getrowcount (); int numcols = getColumnCount ();
For (int i = 0; i If you want to display a hierarchical diced set of data, with a tree map representation to give the user an intuitive and easy-to-use feel, the JTree class is like the left half of the Windows resource manager, by clicking can "open", "Close "Folder, expand the chart data of the tree structure. JTREE is also designed according to M-V-C's idea, and the main function of JTREE is to display data according to the tree, and its data is derived from other objects, and its display effect is usually shown below: Below is an example of a tree containing six branch points to demonstrate the implementation of JTREE. Import java.awt. *; import java.awt.Event. *; import javax.swing. *; import javax.swing.tree. *; class branch {defaultmutabletreenode r; // defaultmutabletreenode is a general node in the data structure of the tree The node can also have multiple child nodes. Public branch (String [] data) {r = new defaultmutabletreenode (data [0]); for (int i = 1; i (Defaultmutabletreenode) // Select Child's parent node tree.getlastSelectedPathComponent (); if (chosen == null) chosen = root; model.insertnodeinto (child, chosen, 0); // Add Child Add to Chosen}}};); Test.setBackground; // Button Test Settings Background Color for Blue Test.setForeground (Color.White); // Button Test Settings For White JPanel P = New JPanel (); // Panel P Initialization P.ADD (TEST); // Add the button to the panel P in the panel P; // Add the panel P to Trees} public static void main (string args []) {jframe jf = new JFrame ("JTree Demo"); JF.GetContentPane (). Add (new trees (), borderLayout.center; // Add the TREES object to the central JF.setsize of the JFrame object; JF.setVisible (TRUE) }} The result is a variety of diverse, related to the order of the user click on the button, one of which is as follows 7.2.4 Layout Manager and AWT, in order to achieve the automatic reasonable arrangement of the platform in the container, SWING also uses the layout manager to manage the emissions, position, size of the component, and will be displayed on this basis. The style has been improved. Another difference between Swing, although there is a top container, but we cannot add the components directly to the top container, and the SWING form contains a container called the content panel, put the content panel on the top container, and then put the components Add to the Content Panel, how to get and set the content panel in front. So, in Swing, the Setting Layout Manager is for the content panel, and the other Swing adds a BoxLayout Layout Manager. The display is slightly different from AWT, as shown below: Now briefly introduce the BoxLayout layout manager The BoxLayout Layout Manager sequentially adds the components in order of the top and down (Y-axis) or from left to right (x-axis). To create a boxlayout object, you must indicate two parameters: the container and the spindle of the BoxLayout. By default, the components are aligned in the longitudinal axis direction. The way to set the layout manager is as follows: Pane.setLayout (New BoxLayout (PANE, BOXLAYOUT.Y-AXIS); JScrollPane listScroller = new JScrollPane (list); listScroller.setPreferredSize (new Demension (250,80)); listScroller.setMinimumSize (new Dimension (250,80)); listScroller.setAlignmentX (LEFT_ALIGNMENT); ...... // top to bottom Set the label and scroll board. JPanel Listpane = new jPanel (); listpane.setLayout (Listpanae, BoxLayout, y_axis)); jlabel label = new Jlabel (LABELTEXT); Listpane.Add (Label); Listpane.Add (Box) .Createrigidarea (New Demension (0,5))); Listpane.Add (ListScroller); ListPane.CreateMptyBorder (10, 10, 10, 10); // From left to right Set button JPanel ButtonPane = New JPanel (); buttonPane.setLayout (new BoxLayout (buttonPane, Boxlayout.X_AXIS)); buttonPane.setBoder (BorderFactory.createEmptyBorder (0,10,10,10)); buttonPane.add (Box.createHorizontalGlue ()); buttonPane.add (cancelButton); buttonPane.add (Box.createRigiArea (new Dimension (10,0))); buttonPane.add (setButton); Container contentPane = getContentPane (); contentPane.add (listPane, BorderLayout.CENTER); contentPane.add (ButtonPane, BorderLayout.sou TH); [This Summary] For AWT, Java 1.1 to Java 1.2 is the biggest change is all libraries in Java. When Java 1.1 is included in the new event model and Java Beans, the platform is set - now it can be dragged into the visualized application build tool to create a GUI component. In addition, the design and beans of the event model are undoubtedly beneficial to the relaxed programming and maintainable code. For Swing components, cross-platform GUI programming can become a meaningful attempt. This chapter mainly introduces some new features of Swing, which different methods and applications are compared to AWT, focusing on Swing features and containers, and give specific descriptions in the form of graphics, and introducing the classification of components. Using Swing's basic rules, various container panels, and layout managers, because Swing is a new feature of Java2, it provides a huge and complex class library support for graphical user interface, and can be developed and practical, but also need to do A large number of work, using the API's help, gradually explore its law, start from components and containers, and master the characteristics. From another perspective, Swing and AWT are all well-familiar with the layout manager or the event handling mechanism, and the retention and use of some weight containers. The principle we have made a detailed introduction in the AWT chapter. Therefore, AWT as a foundation of Swing, it is necessary to master it, I hope everyone can explore new methods and new techniques in the continuous design application.