The of Java graphical interface programming -- Swing

1. Swing overview

Swing is implemented in 100% pure Java and no longer depends on the GUI of the local platform, so it can maintain the same interface appearance on all platforms. Swing components that are independent of the local platform are called lightweight components, while components that depend on the local platform are called heavyweight components.

Because all components of Swing are implemented in Java and no longer call the GUI of the local platform, the display speed of Swing graphical interface is slower than that of AWT graphical interface. However, compared with the rapidly developing hardware facilities, this difference in the speed of smile is not harmful.

Advantages of using Swing:

  • Swing components no longer depend on the GUI of the local platform and do not need to adopt the GUI intersection of various platforms. Therefore, swing provides a large number of graphical interface components, far exceeding the set of graphical interface components provided by AWT;
  • Swing components no longer depend on the local platform GUI, so there will be no platform related bug s;
  • Swing components can ensure the same graphical interface appearance when running on various platforms.

These advantages provided by Swing make the Java graphical interface program truly achieve the goal of "Write Once, Run Anywhere".

Swing features:

  1. Swing components adopt MVC (Model view controller) design pattern: Model: used to maintain various states of components; View: visual representation of components; Controller: used to control the response to various events and components. When the Model changes, it will notify all views that depend on it, and the view will update itself according to the Model data. Swing uses UI agents to wrap views and controllers, and a Model object to maintain the state of the component. For example, button JButton has a Model ButtonModel object that maintains its state information, and the Model of swing component is set automatically. Therefore, JButton is generally used without caring about the ButtonModel object.
  2. Swing performs consistently on different platforms and has the ability to provide a display appearance that is not supported by the local platform. Because swing uses MVC mode to maintain components, when the appearance of components is changed, it has no impact on the status information of components (maintained by the model). Therefore, swing can use pluggable look and feel (plaf) to control the appearance of components, so that swing graphical interface can have different appearance when running on the same platform, and users can choose the appearance they like. In contrast, in the AWT graphical interface, because the peer class that controls the appearance of components is related to the specific platform, AWT components always have the same appearance as the local platform.

2. Usage of Swing basic components

2.1 Swing component hierarchy

Swing component inheritance system diagram:

Most Swing components are direct or indirect subclasses of JComponent abstract class (not all Swing components). JComponent class defines the general methods of all subclass components. JComponent class is Java in AWT awt. A subclass of the Container class, which is also one of the links between AWT and Swing. Most Swing component classes inherit the Container class, so Swing components can be used as containers (JFrame class inherits the Frame class).

Correspondence between Swing components and AWT components: in most cases, you only need to add a J before the name of AWT components to get the corresponding Swing component name, with several exceptions:

  • JComboBox: corresponds to the Choice component in AWT, but has more functions than the Choice component;
  • JFileChooser: corresponds to the FileDialog component in AWT;
  • JScrollBar: corresponds to the ScrollBar component in AWT. Note the case difference of the b letter in the class names of the two components;
  • Jccheckbox: corresponds to the Checkbox component in AWT. Note the case difference of the b letter in the class names of the two components;
  • Jccheckboxmenuitem: corresponds to the CheckboxMenuItem component in AWT. Note the case difference of the b letter in the class names of the two components.

Swing components are classified by function:

  • Top level containers: JFrame, JApplet, JDialog, and JWindow.
  • Intermediate containers: JPanel, JScrollPane, JSplitPane, JToolBar, etc.
  • Special containers: intermediate containers with special functions on the user interface, such as JInternalFrame, JRootPane, JLayeredPane, jdesktopane, etc.
  • Basic components: components that realize human-computer interaction, such as JButton, JComboBox, JList, JMenu, JSlider, etc.
  • Display components of non editable information: components that display non editable information to users, such as JLabel, jpprogressbar, JToolTip, etc.
  • Display components of editable information: components that display formatted information that can be edited to users, such as JTable, JTextArea, JTextField, etc.
  • Special dialog components: components that can directly generate special dialog boxes, such as JColorChooser and JFileChooser.

2.2 Swing implementation of AWT components

Swing provides corresponding implementations for all AWT components except Canvas. Swing components are more powerful than AWT components. Compared with AWT components, swing components have the following four additional functions:

  1. You can set prompt information for Swing components. Use setToolTipText() method to set prompt information that is helpful to users for components.
  2. Many Swing components, such as buttons, labels and menu items, can use icons to decorate themselves in addition to text. In order to allow icons to be used in Swing components, Swing provides an implementation class for the Icon interface: ImageIcon, which represents an image Icon.
  3. Support plug-in appearance style. Each JComponent object has a corresponding ComponentUI object to complete all painting, event processing, size determination, etc. The ComponentUI object depends on the currently used PLAF and uses uimanager The setlookandfeel () method can change the appearance style of the graphical interface.
  4. Support setting border. Swing components can set one or more borders. Swing provides a variety of borders for users to use. You can also create combined borders or set borders yourself. A blank border can be used to increase components and assist the layout manager to reasonably layout components in the container.

Each Swing component has a corresponding UI class. For example, the JButton component has a corresponding ButtonUI class as the UI proxy. For the class name of the UI agent of each Swing component, always remove the J of the Swing component class name, and then add the UI suffix. UI proxy class is usually an abstract base class. Different plafs have different UI proxy implementation classes. The Swing class library contains several sets of UI agents, which are placed under different packages. Each set of UI agent contains the ComponentUI implementation of almost all Swing components. Each set of such implementation is called a PLAF implementation.

Code demonstration:

package Package2;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class PLAFDemo {
    //Create window JFrame
    JFrame jFrame = new JFrame("test Swing Basic components");

    //create menu
    JMenuBar jMenuBar = new JMenuBar();
    JMenu fileMenu = new JMenu("file");
    JMenu editMenu = new JMenu("edit");
    JMenuItem autoItem = new JMenuItem("Auto wrap");
    JMenuItem copyItem = new JMenuItem("copy");
    JMenuItem pasteItem = new JMenuItem("paste");
    JMenu formatMenu = new JMenu("format");
    JMenuItem commentItem = new JMenuItem("notes");
    JMenuItem cancelCommentItem = new JMenuItem("note off");

    //Create text field
    JTextArea jTextArea = new JTextArea(8,20);

    String[] colors = {"gules","green","blue"};
    //Create list box
    JList<String> colorList = new JList<String>(colors);

    //Create and select related components
    JComboBox<String> colorSelect = new JComboBox<String>();
    ButtonGroup buttonGroup = new ButtonGroup();
    JRadioButton male = new JRadioButton("male",false);
    JRadioButton female = new JRadioButton("female",true);
    JCheckBox isMarried = new JCheckBox("Are you married?",true);

    //Declaration text box
    JTextField jTextField = new JTextField(40);
    JButton ok = new JButton("determine");
    //JButton ok = new JButton("OK", new ImageIcon("file path \ \ file name. png");

    //Declaration context menu
    JPopupMenu jPopupMenu = new JPopupMenu();
    ButtonGroup popupButtonGroup = new ButtonGroup();
    JRadioButtonMenuItem metalItem = new JRadioButtonMenuItem("Metal style");
    JRadioButtonMenuItem nimbusItem = new JRadioButtonMenuItem("Nimbus style");
    JRadioButtonMenuItem windowsItem = new JRadioButtonMenuItem("Windows style",true);
    JRadioButtonMenuItem windowsClassicItem = new JRadioButtonMenuItem("Windows Classic style");
    JRadioButtonMenuItem motifItem = new JRadioButtonMenuItem("Motif style");

    //Initialization interface, assembly view
    public void init() {
        //Assemble top menu
        formatMenu.add(commentItem);
        formatMenu.add(cancelCommentItem);
        editMenu.add(autoItem);
        editMenu.addSeparator(); //Add split line
        editMenu.add(copyItem);
        editMenu.add(pasteItem);
        editMenu.addSeparator();
        editMenu.add(formatMenu);
        jMenuBar.add(fileMenu);
        jMenuBar.add(editMenu);
        jFrame.setJMenuBar(jMenuBar);

        //Assembly right-click menu
        popupButtonGroup.add(metalItem);
        popupButtonGroup.add(nimbusItem);
        popupButtonGroup.add(windowsItem);
        popupButtonGroup.add(windowsClassicItem);
        popupButtonGroup.add(motifItem);
        ActionListener listener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //Which style is currently selected
                String actionCommand = e.getActionCommand();
                try {
                    changeStyle(actionCommand); //change appearance
                } catch (UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                } catch (ClassNotFoundException ex) {
                    ex.printStackTrace();
                } catch (InstantiationException ex) {
                    ex.printStackTrace();
                } catch (IllegalAccessException ex) {
                    ex.printStackTrace();
                }
            }
        };
        metalItem.addActionListener(listener);
        nimbusItem.addActionListener(listener);
        windowsItem.addActionListener(listener);
        windowsClassicItem.addActionListener(listener);
        motifItem.addActionListener(listener);
        jPopupMenu.add(metalItem);
        jPopupMenu.add(nimbusItem);
        jPopupMenu.add(windowsItem);
        jPopupMenu.add(windowsClassicItem);
        jPopupMenu.add(motifItem);

        //There is no need to listen for mouse events
        jTextArea.setComponentPopupMenu(jPopupMenu);

        //Assembly selection related components
        JPanel selectPanel = new JPanel();
        colorSelect.addItem("gules");
        colorSelect.addItem("green");
        colorSelect.addItem("blue");
        selectPanel.add(colorSelect);
        buttonGroup.add(male);
        buttonGroup.add(female);
        selectPanel.add(male);
        selectPanel.add(female);
        selectPanel.add(isMarried);

        //Assemble text fields and select related components
        Box topLeftBox = Box.createVerticalBox();
        topLeftBox.add(jTextArea);
        topLeftBox.add(selectPanel);

        //Assemble top
        Box topBox = Box.createHorizontalBox();
        topBox.add(topLeftBox);
        topBox.add(colorList);
        //Put the top in the middle area
        jFrame.add(topBox,BorderLayout.CENTER);

        //Assemble bottom
        JPanel bottomPanel = new JPanel();
        bottomPanel.add(jTextField);
        bottomPanel.add(ok);
        jFrame.add(bottomPanel, BorderLayout.SOUTH);

        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Set the function of closing the window and exiting the program
        //Set the optimal size through the pack() method
        jFrame.pack();
        //Set the position and size of the Frame
        jFrame.setBounds(400,200,500,300);
        //Set Frame visible
        jFrame.setVisible(true);
    }

    //Define a method to change the interface style
    private void changeStyle(String command) throws UnsupportedLookAndFeelException, 
            ClassNotFoundException, InstantiationException, IllegalAccessException {
        switch (command) {
            case "Metal style":
                UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
                break;
            case "Nimbus style":
                UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
                break;
            case "Windows style":
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                break;
            case "Windows Classic style":
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel");
                break;
            case "Motif style":
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
                break;
        }
        //Refresh component appearance
        SwingUtilities.updateComponentTreeUI(jFrame.getContentPane()); //Refresh all contents of the top-level container
        SwingUtilities.updateComponentTreeUI(jMenuBar);
        SwingUtilities.updateComponentTreeUI(jPopupMenu);
    }

    public static void main(String[] args) throws UnsupportedLookAndFeelException, 
            ClassNotFoundException, InstantiationException, IllegalAccessException {
        new PLAFDemo().init();
    }
}

2.3. Set the frame for the component

Keywords: Java Back-end

Added by Fazer on Tue, 18 Jan 2022 22:14:04 +0200