Seventh talks about Swing user interface design

xiaoxiao2021-03-06  39

Course index

[Before class think] 1. What is Swing? What is the advantage of it and AWT? What is the difference in use? 2. What is the characteristic of Swing component hierarchy? How is it realized? 3. What are the common components of SWING? how to use? 4. How many containers have SWING? What is the functional characteristics? 5. What is the characteristics of Swing Layout Manager? What is the difference between AWT?

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.

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.

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.

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

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 Swing The main advantage of AWT is the general 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. That is, the hotkey is set.

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 times the button is clicked}); label.setLabelFor (Button);

/ * The common way to place space between the top container and its content is to add the content to the 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 displaying frame.addwindowlistener (new windowadapter () {// anonymous class for registration listener public void windowclosing (windowevent e) {system.exit (0);}}); frame.pack (); Frame.setvisible (true);}}

7.1.9 Structure of SWING Structure

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

7.2 SWING components and containers

7.2.1 Classification of Components

JComponent is an abstract class that defines a general method for all subclass components, and its class hierarchies are as follows: java.lang.object | - java.awt.component | - java.awt.container | --javax.swing.jcomponent is not all Swing components 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 Containers: JPanel, JScrollpane, JSPLITPANE, JTOOLBAR 3) Special Containers: Intermediate Layers for special effects on GUI , Such as JinternalFrame, JLAYEREDPANE, JROOTPANE. 4) Basic controls: Implementing interpersonal interactions such as JButton, Jslider, 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 also divided into: 1) Border settings: Use the setBorder () method to set the frame periphery of the component, 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. ComponentUI object relies on the current L & F that uses the UIManager.SetLookandFeel () method to set the required L & F. 6) Support layout: The method can be specified by setting the maximum, minimum, recommended size method and setting X, Y alignment parameter value. Manager constraints provide support for 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.

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)

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 Board (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) // option board with a specific tag to register a changing listener

7.2.3.7 Toolbar (JToolbar)

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 component 7.2.3.8 Internal Framework (jinternalframe)

The internal framework jinternalFrame is like a window inside the other window, which features the internal framework must be added to a container (usually JDESKTOPPANE), otherwise it is not displayed; 2) Do not need to call the show () or setvisible () method The internal frame is displayed along with the container; 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 with setLocation () or setbounds () method settings The position of the internal frame in the container, the default value is 0, 0, that is, the upper left corner of the container; Establish a dialog box, you cannot use JDIALOG as a top window, you must use JOPTITIONPANE or JINTERNALFRAME; 7) The internal framework cannot listen to window events, which can process the internal frame window by listening to the internal framework similar to window events. 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 to Frame Content Panel

7.2.3.9 Button (JButton)

The button is a common component, buttons can be labeled or image.

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

7.2.3.10 checkbox (jcheckbox)

7.2.3.11 radio box (JRADIOBUTTON)

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)

7.2.3.15 List (LIST) Applicable to the number of options to display in the list, and the items inside can be constructed of any type of 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)

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;

7.2.3.20 Tree (JTREE)

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, the main function of JTREE is to display data according to the tree, and its data comes from other objects.

7.2.4 Layout Manager

As with AWT, in order to implement the platform-independent automatic rational arrangement in the container, Swing also uses the layout manager to manage the emissions, position, size of the component, and the display style is improved on this basis. 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 BoxLayout Layout Manager sequentially adds the component in order to the top (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); [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.

转载请注明原文地址:https://www.9cbs.com/read-117740.html

New Post(0)