Introduction to a .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.
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
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 class javax.swing.undo support Cancel Swing package is the biggest package provided by Swing, which contains nearly 100 classes and 25 interfaces, almost all. Swing components are in a 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.
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.
1.1MVC (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.
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. 1.2: Cableable support
All SWING components implements Accessible interfaces, providing support for accessibility, allowing accessibility such as screen readers to get information from Swing components.
1.3 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.
1.4 set the 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.
1.5: Using Icon (icon)
Unlike AWT parts, many Swing components such as buttons, labels, in addition to using text, can also use icons to modify yourself.
II. Swings program structure
example:
Import javax.swing. *;
// introduce Swing package name
// Import com.sun.java.swing. *;
// Use JDK 1.2 Beta 4 and all Swing 1.1 beta 3 //
Version, introducing Swing package names.
Import java.awt. *;
Import java.awt.event. *;
Public class swingspplication {
Private static string labelprefix = "NUMBER OF button CLICKS:"
Private int numclicks = 0;
/ / Counter, calculate the number of 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 ()); // Set the 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);}} Swing program is generally performed according to 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 2.1.swing components and containers In Swing not only replaces components in the AWT, but also some other features are included in Swing alternative components. 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. 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. 2.1 Unlike the AWT components with Swing, 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 into Frame content panel 2.3: root panel (JRootpane) java.lang.object java.awt.component java.awt.container javax.swing.jcompanent javax.swing.jcompane root panel by a glass panel ( Glasspane, a content panel, and an optional menu bar (JMenubar), and the content panel and the optional 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 glass panel 2.4: Facing panel (JLAYEREDPANE) java.lang. Object java.awt.component java.awt.container javax.swing.jcomponent Javax.swing.jlayeredPaneSwing offers two hierarchical panels: JLayeredPane 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). 2.5: JPANEL is a lightweight container assembly that is the same as panels, for accommodating interface elements to accommodate more components under the setting of the layout manager, to achieve 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.jpanel2.6: Scroll window (JScrollpane) Java .lang.object java.awt.component java.awt.container javax.swing.jcomponent javax.swing.jscrollpane 2.7: 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 are:
AddImpl (Component Comp, Object Constraints, INDEX)
/ / Add a designated component
SettopComponent (Component CoMP)
// Set the top components
SetDiVIDERSIZE (int newsize)
// Set the size of the split
SETUI (Splitpaneui UI)
// Set the appearance and feel
2.8: The option panel (JTABBedpane) JTabbedpane provides a set of on-to-user to select labels or icons. Common methods: add (string title, component component) // Add a component AddChangelistener (ChangeListener L) // tab with a specific tag to register a change listener 2.9: Toolbar (JToolbar) toolbar in the upper left Toolbar in 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 section of a specified number 2.10: Internal Framework (JinternalFrame) Internal Framework JinternalFrame is like One window inside the other window, which features the internal framework to 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 framework The container is displayed together; 3) You must set the frame size with setsize () or pack () or setbounds, 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 value is 0, 0, that is, the upper left corner of the container; Using JDIALOG as a top window, you must use a JOPTIONPANE or JINTERNALFRAME; 7) The internal framework cannot listen to the window event, 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 an optional frame.setContentPane (Desktop); // Set Desktop to Frame Content Panel 2.11: Button (JButton) button is A common component, buttons can take labels or images.
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) // Display icon jButton (String text) // displays the character jbutton (String text, icon) // on the button and display the icon and display character 2.11: Table ( The JTable) Table is Swing added components, 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; 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.awt *;. 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 stored table data jtable table = new jtable (mymodel); // Table Object Table data source is MyModel object Table.SetPreferRedscrollableViewPortsize (New Dimension (500, 70)); // Table display size // Generate one Panel JscrollPane Scrollpane = New Jscrollpane (Table); // Add (Scrollpane, BorderLayout.center); addwindowlistener (new windowAdapter () {// registration window Listener public void windowclosing (windowEvent e) {system.exit (0);}});} // Put the data to display in the table and the Class MyTableModel Extends AbstractTractableModel Extends AbstractTractTableModel {// table in the Object array in the table. The content to be displayed in the first line is placed in the string array columnnames in Final String [] ColumnNames = {"First Name", "Position", "Telephone", "MONthlyPay", "married"}; // Save in 2D Array DATA Final Object [] [] Data = {{"WANGDONG", "Executive", "01068790231", New Integer (5000), New Boolean (false)}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} , 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)}}}}}}}}}}}}}}}}}}}} Write the method in AbstractTableModel,
Its main purpose is to be called by the JTable object to display correctly in the table. The programmer must be properly implemented according to the type of data used.
// Number of Public INT getColumn ()} // Get a column name, the name of the column, the name of the column is obtained, and the name of each column is obtained Save Public String getColumnNames (int co) {return columnnames (} // obtained data in a string array columnnnames, and data saved in an object array data Public object getValueat (int Row, int COL) {RETURN DATA [ROW] [COL];} // Judgment the type of PUBLIC CLASS GETVALUMNCLASS (INT C). Getclass ();} // State the form as editable Public Boolean ISCELEDITABLE (INT ROW, INT COL) {IF (Col <2) {Return False;}}}} // Change the value of a data PUBLIC VOID SETVALUEAT (Object Value, int Row, Int Coll) {If (debug) {system.out.println ("SETTING VALUE AT" ROW "," Col "To" Value "(AN Instance of" Value.getClass ) ")");} If (Data [0] instance &&! (Value instanceof integer) {Try {data [row] [color (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);} f (debug) {system.out.println ("
NEW VALUE OF DATA: "); PrintDebugdata ();}} private void printdebugdata () {int nuMrows = getRowcount (); int Numcols = getColumnCount (); for (int i = 0; i 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 III. 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 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);