Java learning ----------- Java Swing GUI Graphical interface development

1, Introduction to Java Swing

Java Swing is a set of toolkits provided by Java for graphical interface application development. It is a part of java basic classes. Swing contains various components for building graphical interface (GUI), such as window, label, button, text box, etc. these elements (components) constituting the graphical interface are included under javax.swing. * package. The class name usually starts with J, such as JFrame, JButton, etc. Component is the most basic part of Java Swing development, and it is also a part of our focus to learn.

2, Java Swing components

What is a component? Components are various elements that make up the graphical interface, such as buttons, windows, text boxes, etc. In Java Swing, if we divide components according to classes, the structure level is as follows.

If divided by function, it can be divided into top-level container, intermediate container and basic components.

The top container includes

JFrameWindow (most Swing GUI programs use JFrame as the top-level container)
JDialogdialog box

Intermediate containers include

JTabbedPaneTab panel

Special intermediate container

JMenuBarmenu bar
JPopMenuPop-up Menu

Basic components include

JCheckBoxcheck box
JRadioButtonradio button
JTextFieldText box
JComboBoxDrop down list box
JOptionPaneWarning box
JTextAreaText area

1. Usage of top container

Top level containers commonly include JFrame and JDialog, both of which belong to forms. As a top-level container, windows are the carrier of basic components, which we can often use in Java Swing development. Next, let's look at how we use these two containers in our code.

Using JFrame forms

import javax.swing.*;
public class JFrameDemo {
    public static void CreateJFrame() {
        JFrame jf = new JFrame("hh");//JFrame is a class in Java, and the created window is actually the actual object of this class.
        jf.setVisible(true); //Set form visibility
        jf.setSize(500, 300); //Set the size of the form. The front is wide and the back is high
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//Set the closing method of the form to Exit_ON_CLOSE ---- exit the application. The default window is closed
    public static void main(String[] args) {
        JFrameDemo.CreateJFrame(); //Call the CreateJFrame method in this class

Use inherited writing of JFrame

import javax.swing.*;

public class JFrameDemo extends JFrame {
    public  void create() {
        this.setSize(500, 350);

    public static void main(String[] args) {
        JFrameDemo jd = new JFrameDemo();

public class JFrameDemo extends JFrame {
      public JFrameDemo {
         setSize(300, 400);
      public static void main(String[] args) {
         JFrameDemo jf = new JFrameDemo();
}//It would be better to write the relevant settings to the constructor

The effect is shown in the figure

The setDefaultCloseOperation() method is used to set the window closing method, which is often passed in
WindowConstants.EXIT_ON_CLOSE exit the application. The default window closes
WindowConstants.DO_NOTHING_ON_CLOSE closes the form without doing anything
WindowConstants.DISPOSE_ON_CLOSE any registered listener object will automatically hide and release the form
WindowConstants.HIDE_ON_CLOSE indicates that the default window for hidden windows is closed

Common methods of JFrame:

void get/setTitle(): obtain/Set the title of the container.
void get/setState(): obtain/Set the minimization, maximization and other states of the container.
void is/setVisible(): obtain/Sets the visual state of the container, in other words, whether it is displayed on the screen.
void get/setLocation(): obtain/Set where the container should appear on the screen.
void get/setsize(): obtain/Set the size of the container.
void add(): Add components to the container.

Using JDialog forms

If it is simply used, its calling method is roughly the same as that of JFrame form. JDialog is often used to pop up one form from another.

import javax.swing.*;
public class JDialogDemo {
       public static void main(String[] args) {
         JFrame jf = new JFrame("outter");
         jf.setSize(800, 600);
         JDialog jd = new JDialog();
         jd.setSize(200, 150);

The methods in JDialog are roughly the same as those in JFrame

Construction method:
JDialog(Frame owner, String title)

void add(Component comp)
void setSize(int width, int height)
void setVisible(boolean b)
void setTitle(String title)

2. Usage of intermediate components

The JPanel component definition panel is actually a container component used to accommodate various other lightweight components.

Common methods:

void add(Component):Add components.
void add(Component,int):Adds a component to the location specified by the index.
void add(Component,Object):Add components according to the specified layout constraints.
void add(Component,Object,int):Add components to the specified location according to the specified layout manager restrictions.
void remove(Component):Remove components.
void remove(int):Remove the component at the specified location.
void removeAll():Remove all components.
void paintComponent(Graphics):Draw components.
void repaint():Redraw.
void setPreferredSize(Dimension):Set the component size.


import javax.swing.*;
public class Demo {
     public static void main(String[] args) {
       JFrame jf = new JFrame("window");
       jf.setSize(250, 250);
       JPanel panel = new JPenel();
       JButton btn = new JButton("Button");
       panel.add(btn); //Add button to the chopping board
       jf.setContentPane(panel);//Set the panel container into the window

JTabbedPane tab panel. Use to create multiple tabbed panes. These panes can place other components, and you can switch panes by clicking the appropriate tab.
Common methods:

Construction method:
   JTabbedPane(int tabPlacement)
void add(Component comp)
void addTab(String title, Component component)//Add tabs / components to TabbedPane objects
void setSize(int width, int height)
void setVisible(boolean b)


import javax.swing.*;
public class Demo {
    public static void main(String[] args) {
        JFrame jf = new JFrame("window");
        jf.setSize(250, 250);
        JTabbedPane tp = new JTabbedPane(JTabbedPane.TOP);
        JPanel panel1 = new JPanel();
        JPanel panel2 = new JPanel();
        tp.addTab("Option 1", panel1);
        tp.addTab("Option 2", panel2);;

JMenu/JMenuBar/JMenuItem ---- menu component. JMenu is a first level menu, which is used to add menus on the menu bar. JMenuItem is a secondary menu, which is used to add menu items on the menu, and JMenuBar is a menu

Common methods of JMenuBar:

void get/setAccelerator(): obtain/Sets the key used as a shortcut Ctrl+Key.
void get/setText(): obtain/Sets the text of the menu.
void get/setIcon(): obtain/Set the picture used by the menu
int getMenu(int index)
int getMenuCount();

JMenu common methods:

    JMenu(String s)
Component add(Component c)
void addSeparator()

JMenuItem common methods

Construction method:
    JMenuItem(String s)
void setEnabled(boolean b)
void setMnemonic(int mnemonic)


import javax.swing.*;
public class Demo {
    public static void main(String[] args) {
        JFrame jf = new JFrame("window");
        jf.setSize(250, 250);

        JMenu jm = new JMenu("File");
        JMenuBar jmb = new JMenuBar();

        JMenuItem jmi1 = new JMenuItem("Open");
        JMenuItem jmi2 = new JMenuItem("Close");
        JMenuItem jmi3 = new JMenuItem("Save");

        JMenu jm1 = new JMenu("new");
        JMenuItem jmi4 = new JMenuItem("Directory");
        JMenuItem jmi5 = new JMenuItem("File");


        jmb.add(jm);//Add content to menu bar

        jf.setJMenuBar(jmb);//add cannot be added to the menu bar

3. Usage of basic components

From the above examples, we can see that the use of components is generally to instantiate the object of the class where the component itself is located, and then add the component to the form by calling the add() method of the form.

Let's take a look at some basic components and their functions:

JButton: button
JLabel: Label
JCheckBox: check box
JRadioButton: radio button
Jtextfile: text box
JList: List
JComboBox: drop down list box
JTextArea: text area

How to use in a form:

import javax.swing.*;
public class Demo extends JFrame {
    private JButton jbtn;
    private JLabel jlab;
    private JComboBox jcom;
    private JTextArea jt;
    private JList jli;
    private JCheckBox jck;
    private JPanel jp;
    private JTextField jtxt;
    private JRadioButton jradio1;
    private JRadioButton jradio2;
    private ButtonGroup buttonGroup;
    public Demo() {
        setSize(500, 500);

        jtxt = new JTextField("I am:");

        jp = new JPanel();

        jbtn = new JButton("Button");

        jlab = new JLabel("I am hhh ");

        jt = new JTextArea(5, 20);

        jck = new JCheckBox();

        jradio1 = new JRadioButton("1");
        jradio2 = new JRadioButton("2");
        buttonGroup = new ButtonGroup();

        String[] cities = {"Beijing", "Qingdao", "Shanghai"};
        jli = new JList(cities);
        jcom = new JComboBox(cities);


    public static void main(String[] args) {
        Demo d = new Demo();

Unfinished to be continued

Tags: Java Back-end

Posted on Mon, 01 Nov 2021 04:40:31 -0400 by fowlerlfc