AWT overview

AWT: Short for Abstract Window ToolKit, Abstract Window Component ToolKit is the earliest Java language ToolKit for writing GUI applications. It provides a set of interfaces for interacting with native graphical interfaces. There is a one-to-one correspondence between the graphical methods in the AWT and those provided by the operating system. Therefore, when using AWT to create a graphical interface, you are actually taking advantage of the graphical library provided by the operating system. AWT components are not fully cross-platform. Because AWT relies on native methods to implement its functionality, AWT components are often referred to as heavyweight components. AWT provides a series of components for implementing graphical interfaces, such as Windows, buttons, text boxes, dialog boxes, and so on. Java classes are provided in the JDK for each component in the java.awt package, which contains all the classes and interfaces for creating user interfaces and drawing graphical images.

Component classes

The Component class and its subclasses are used to describe GUI elements that graphically display on the screen and interact with the user. Component can be divided into basic Component classes and container classes according to the different roles of Component. The base Component classes are graphical elements such as buttons and text boxes, while the Container classes are objects instantiated through Component’s subclass Container.

The Container class

Component is a subclass of Component, a container Component, a special Component that can contain components and other containers. Container Is divided into two types: Window and Panel. Container objects can be added to other Component objects or Container objects using Add (Component comp). You can also remove a specified Component from the current container Component by using the remove(Component comp) method.

The Window class

Window class A container that exists independently of other containers and can be displayed as an application Window, its objects representing free-moored top-level Windows. The top container is a container that can provide graphic drawing, which is the basis of graphic programming. All graphic things are included in the top container.

(1) Frame class

A subclass of Window, which stands for framework, is a top-level container for designing applications that resemble Windows in Windows systems.

Frame construction methods:

Frame() : Constructs a new instance of Frame that is not initially visible. Frame(String s) : Constructs a new, initially invisible Frame object with the specified title S. Other common methods for Frame: setBounds(int x,int y,int width,int height) : Sets the position and size of the form, where x and y are the upper-left coordinates, and width and height are the width and height,in pixels. SetSize (int width,int height) : setLocation(int x, int y) : SetBackground (Color C) : setBackground(Color c) : setVisible(Boolean B) : setTitle(String name) : setVisible(String name) : Setrestage (Boolean b) : indicates whether the stage is being resized. Frame class application:

public class Test1 { public static void main(String[] args) { Frame f=new Frame("My First Test"); F.s etLocation (300300); F.s etSize (170100); f.setBackground(Color.yellow); f.setResizable(false); f.setVisible(true); }}Copy the code

(2) the Dialog class

A subclass of Window, dialog box, is to display information to the user and obtain the data required for the operation of the program Window, can play the role of interaction with the user. Unlike normal Windows, dialogs depend on other Windows and will disappear when the window on which they depend disappears or is minimized. When the window is restored, the dialog box is automatically restored.

The Panel class

A Panel, which cannot exist as a separate window for the application, must be added to another Container to be displayed. Therefore, a Panel is an intermediate Container. An intermediate container is a container component that can contain components and components of other containers, but must itself be contained in other containers (such as top-level containers). A typical Panel is an Applet, which is used to design Java applets that can be embedded in web pages. Panel() : using the default FlowLayout class layout manager to initialize a Panel(layoutmanlayout) : using the specified layout manager to initialize a Panel class usually with methods: setBounds(int x, int y, int width, Int height setSize(int width,int height) setLocation(int x,int y) setBackground(Color C) setLayout(LayoutManager MGR) etc Panel class:

public class Test1 { public static void main(String[] args) { Frame f=new Frame("Java Frame with Panel"); Panel p=new Panel(null); f.setLayout(null); F.s etBounds (300300500500); F.setbackground (new Color(0,0,102)); P. etBounds (50,50,400,400); // Coordinates relative to outer Frame p.setBackground(new Color(204,204,255)); f.add(p); // Add panel to Frame f.visible (true); }}Copy the code

Other common subclasses of the Component class

Non-container components: Cannot contain components and components of other containers

  • Button: Label Button. When the Button is pressed, the application performs an action
  • Label: A component that places text in a container
  • CheckBox: CheckBox, a graphical component that can be in the “on” (True) or “off” (false) state
  • Choice: Pop-up selection menu. The current selection appears as the title of the menu
  • List: Provides the user with a scrollable List of text items
  • ScrollBar: represents a ScrollBar
  • TextComponent: Is a superclass for all components that allow editing text, with common subclasses TextArea (multi-line text) and TextField (but line text)
  • Canvas: Represents a blank rectangular area on the screen that an application can draw or capture user input events from

Swing

SUN launched Swing in 1997, which is a new graphical interface system built on the basis of AWT. It contains all the functions that AWT can provide, and has greatly expanded the functions of AWT with pure Java code. It is an enhanced component of AWT components. Because Swing does not use native methods to implement graphical functionality, Swing behaves consistently across operating platforms and is capable of providing other functionality not supported by native windowing systems. Swing components are often referred to as lightweight components.

AWT is based on local methods, so it is relatively fast. Swing is a Java program based on AWT that runs slower than AWT. Swing is more commonly used in standard Java applications based on PCS or workstations to improve application performance by sacrificing speed, while in embedded applications, relatively efficient AWT is used to ensure speed by sacrificing performance. The Javax. Swing package: Provides a set of “lightweight” (all Java language) components that try to work the same on all platforms. Java and Javax are both Java API packages, Java is the core package, Javax x stands for extension, indicating that Javax is the Java class library extension package. To use Swing containers and components, import the Javax. Swing package in the following format: import javax.swing. To make better use of Swing, we often import two other packages in the following format:

	import java.awt.*;
	import java.awt.event.*;
Copy the code

Swing component class names are basically the same as their AWT component names. Most of them are preceded by a “J”, but there are some exceptions, such as Swing JComboBox components that correspond to AWT Choice components (drop-down box).

Containers in Swing

(1) Top-level container class

JFrame: Class for frame Windows. JDialog: Class for dialog boxes. JApplet: A class for Java applets that use Swing components. JWindow: it has no title bar, window management button.

(2) Intermediate container class

JPanel: Used to group together small lightweight components such as JButton, JLabel, and other non-container components or JPanel components. JScrollPane: A scroll window, similar to a JPanel, with scroll bars. JTabbedPane: Displays one component at a time. JToolBar: Arranges groups of components (usually buttons) in rows or columns.

The vast majority of Swing components derive from the JCompomnent class, which is the base class for all Swing components except the top-level container. The JComponent class has only one no-argument constructor: Format: public JComponent() function: calls the Container constructor and does no initialization beyond that.

Use of Swing components

Unlike AWT components, a Swing component cannot be added directly to the top-level container; it must be added to a Content Pane associated with the Swing top-level container. The content panel is a lightweight component that is a normal container contained in the top-level container.

You can add a component to a JFrame by:

1) Use the getContentPane() method to obtain the Content pane of JFrame and add components to it in the following format:

frame.getContentPane().add(childComponent);
Copy the code

2) If the user’s custom class is a subclass of JFrame class, you can create a JPanel object and then add components to the panel in the following format:

   JPanel contentPane=new JPanel();
   contentPane.add(childComponent);
Copy the code

3) Create an intermediate container, add components to the container, and use the setContentPane() method to set the container to the Content pane of the JFrame in the following format:

Jpanel contentPane=new Jpanel(); ... // Add other components to the Jpanel; frame.setContentPane(contentPane); // set the contentPane object to be the frame's contentPaneCopy the code

Basic steps of GUI program development using JFrame container:

1) The JFrame window created is invisible. To make it visible, use the show() method or setVisible(Boolean b) method, where the parameter b in setVisible =true. 2) Use the setSize method to set the window size. 3) To add a component to a JFrame, you must obtain the ContentPane and then use the Add () method to add the component to the ContentPane, unlike the AWT package where frames add components directly using the Add () method. Programs written using Swing components:

import javax.swing.*; public class First { public static void main(String[] args) { JFrame frame=new JFrame(); // Create a label with text JLabel label=new JLabel("Swing component "); // Once you have the content pane, add the label to the frame frame.getContentPane().add(label); / / call the following method can by clicking on the "close" button to close this frame frame. The setDefaultCloseOperation (JFrame. EXIT_ON_CLOSE); Frame. The setSize (200200); // Set the width and height of the frame frame.setvisible (true); // Make frame visible}}Copy the code

Layout manager

In the Java language, objects that provide a layout manager class can manage the layout of Components in a Container without having to directly set the location and size of components. Each Container has a layout manager object. When the Container needs to locate or determine the size of a component, it calls its layout manager. The setLayout() method of the Container is used to change the layout manager object.

Common LayoutManager provided by AWT: implements the LayoutManager interface

  • FlowLayout
  • BorderLayout
  • GridLayout
  • GridBagLayout
  • CardLayout

FlowLayout layout

FlowLayout: Java.awt. FlowLayout is a direct subclass of Java.lang. Object. It is the default layout manager of the Panel class and is the simplest layout manager. The FlowLayout manager arranges the components in the container from left to right in the order they were added to the container. When one row is full (reaching the boundary of the container), it moves to the next row and continues the arrangement from left to right. Do not change the size of the component, according to the original size of the component display, you can set different component spacing, line spacing and its way. FlowLayout Components in the Layout manager can be aligned left, center (the default), or right.

Constructor of FlowLayout:

FlowLayout() : Used to create a FlowLayout that is centered and spaced horizontally and vertically by 5 pixels. FlowLayout(int align) Is used to create an object of the FlowLayout class, aligned with the given align value. Horizontal and vertical intervals of each component are 5 pixels. Align can be flowlayout. LEFT, flowlayout. RIGHT, or flowlayout. CENTER. FlowLayout(int align, int hGap, int vGap) is used to create an object of the FlowLayout class that specifies both alignment and spacing between components. The function and value of parameter align are the same as above; The hgap parameter specifies the horizontal interval between components. The vgap parameter specifies the vertical interval between components. The interval is in pixels. FlowLayout example:

import java.awt.*; import javax.swing.*; Public class myFlowLayoutExample{public static void main(String args[]){JFrame JFrame =new JFrame(" an example of a scrolling list "); Container cp=jframe.getContentPane(); cp.setLayout(new FlowLayout()); JButton jbt1=new JButton(" soccer "); JButton jbt2=new JButton(" basketball "); JButton jbt3=new JButton(" volleyball "); JButton jbt4=new JButton(" badminton "); JButton jbt5=new JButton(" table tennis "); cp.add(jbt1); cp.add(jbt2); cp.add(jbt3); cp.add(jbt4); cp.add(jbt5); Jframe. SetSize (150200); jframe.setVisible(true); }}Copy the code

BorderLayout layout

The BorderLayout manager is the default layout manager for the Frame class. It divides the container into five areas: North, South, East, West, and Center. Only one component can be placed in each area. If a component is not added to the Center area, the component is added to the Center area by default.

BorderLayout constructor

Public BorderLayout() : Creates an object of the BorderLayout class with zero horizontal and vertical spacing between the components. Public BorderLayout(int hGap, int vGap) : Creates an object of the BorderLayout class with horizontal spacing hGAP and vertical spacing vgap between the components.

BorderLayout, for instance:

import javax.swing.*; import javax.swing.*; Public class BorderLayoutEx {public static void main(String[] args) {JFrame jf=new JFrame("BorderLayout sample program "); Jf. SetBounds (100100300200); jf.setVisible(true); / / jf. SetLayout (new BorderLayout (5, 10)); JButton bSouth=new JButton(" south "); // create a button object JButton bNorth=new JButton(" north "); JButton bEast=new JButton(" east "); JButton bWest=new JButton(" west "); JButton bCenter=new JButton("中"); jf.add(bNorth,BorderLayout.NORTH); jf.add(bSouth,BorderLayout.SOUTH); jf.add(bEast,BorderLayout.EAST); jf.add(bWest,BorderLayout.WEST); jf.add(bCenter,BorderLayout.CENTER); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}Copy the code

GridLayout layout

Grid Layout manager: Use vertical and horizontal lines to divide the container into n rows and m columns of equal size, placing one component in each grid. Components added to the container are placed first in the grid in row 1, column 1 (upper left), then left to right in the grid in row 1, and then left to right in the next row when the rows are full. Components placed in the GridLayout Manager automatically occupy the entire area of the grid.

The GridLayout class has three constructors:

GridLayout() : Creates a GridLayout as the default (1 row, 1 column). GridLayout(int Rows,int COLs) : Creates a GridLayout with rows and COLS columns. GridLayout(int Rows,int COLs,int hGap,int vGap) : Creates a GridLayout with the specified number of rows, number of columns COLs, horizontal interval HGAP, and vertical interval vgap.

GridLayout example:

import javax.swing.*; import java.awt.*; Public class GridLayoutEx {public static void main(String[] args) {JFrame jf=new JFrame("GridLayout sample program "); Jf. SetBounds (100100300200); jf.setVisible(true); JButton b1=new JButton(" C171"); JButton b2=new JButton(" C172"); JButton b3=new JButton(" C173"); JButton b4=new JButton(" C174"); JButton b5=new JButton(" C175"); JButton b6=new JButton(" C176"); JButton b7=new JButton(" S181"); JButton b8=new JButton(" S182"); Jf. SetLayout (new GridLayout (3,3,10,10)); jf.add(b1); jf.add(b2); jf.add(b3); // Add button jf.add(b4); jf.add(b5); jf.add(b6); jf.add(b7); jf.add(b8); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}Copy the code

Grid Package Layout Manager: GridBagLayout is the most flexible and complex layout manager. Similar to the GridLayout layout manager, except that it allows components to vary in size in a grid, allows a component to span one or more grids, and aligns components vertically and horizontally without requiring components to be the same size. It solves almost any interface layout problem.

Steps to use the GridBagLayout layout Manager:

① Create a GridBagLayout manager and make the container adopt the layout manager.

	GridBagLayout layout=new GridBagLayout();
	container.setLayout(layout);
Copy the code

② Create a GridBagContraints object (layout constraints, is the core class that controls the layout of each component in GridBagLayout), and set the related properties of the object.

attribute role
Gridx and gridy Sets the horizontal and vertical indexes (that is, the row and column) of the grid on which the upper-left corner of the component is located. If set the gridx and gridy values of GridBagConstraints. The RELATIVE (default), said that the current component follow closely behind on a component
Gridwidth and gridheight Sets the component to span several grids horizontally and vertically, with the logical value of 1 for both properties. If the two attribute’s value is set to GridBagConstraints. The REMAINER said the current component on the adults or the column for the last component. If the two attribute’s value is set to GridBagConstraints. RELATVE, said that the current component on the adults or column for the penultimate components
fill Set whether and how to change the size of the component if the display area of the component is larger than the required size. This property accepts the following values: NONE: The default does not change the size of the component. HORIZONTAL: Makes the component long enough horizontally to fill the display area, but not at the same height; VERTICAL: Make the component as high as possible vertically to fill the display area, but the length remains the same. BOTH: Makes the component large enough to fill the entire display area
Weightx and weighty Sets the proportion (also known as weight) of excess horizontal and vertical white space occupied by components in the container. Suppose the container has three components whose weightx is 1, 2, and 3. When the container width is increased by 60 pixels, the three containers gain 10, 20, and 30 pixels respectively. The default value for both of these attributes is 0, which means no excess space is occupied

③ Call the setConstraints() method of the GridBagLayout object to establish the association between the GridBagConstraints object and the controlled component.

	layout.setConstraints(component, constraints);
Copy the code

④ Add components to the container.

	container.add(component);
Copy the code

The GridBagConstraints object can be reused by simply changing its properties. To add multiple components to the container, repeat steps ②③④.

GridBagLayout example:

import java.awt.*; Class Layout extends Frame {private void addComponent(String name, GridBagLayout, GridBagConstraints c) { Button bt = new Button(name); // Set the layout of the GridBagConstraints object and the button's association.setConstraints (bt, c); this.add(bt); } public Layout(String title) {GridBagLayout = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); this.setLayout(layout); c.fill = GridBagConstraints.BOTH; // Set the component to eighteightx = 1; // Set the lateral weights to 1 c weighty = 1; // Set the vertical weight to 1 this.addComponent("btn1", layout, c); this.addComponent("btn2", layout, c); this.addComponent("btn3", layout, c); c.gridwidth = GridBagConstraints.REMAINDER; This.addcomponent ("btn4", layout, c); c.weightx = 0; // Set transverse weights to 0 c.weighty = 0; AddComponent ("btn5", layout, c); c.gridwidth = 1; // Set the component across a grid (default) this.addComponent("btn6", layout, c); c.gridwidth = GridBagConstraints.REMAINDER; This.addcomponent ("btn7", layout, c); c.gridheight = 2; // Set the component vertically across two grids c.ridwidth = 1; // Set the component horizontally across a grid c.eighteightx = 2; // Set the lateral weights to 2 c weighty = 2; // Set the vertical weight to 2 this.addComponent("btn8", layout, c); c.gridwidth = GridBagConstraints.REMAINDER; c.gridheight = 1; this.addComponent("btn9", layout, c); this.addComponent("btn10", layout, c); this.setTitle(title); this.pack(); this.setVisible(true); }}Copy the code

CardLayout layout

CardLayout manager: CardLayout treats each component as a card, stacking the components like playing cards. Only one card can be seen at a time, and the container acts as a stack of cards. When the container is first displayed, the first component added to the CardLayout object is visible, and this displayed component takes up all of the container space.

CardLayout class constructor:

Public CardLayout() : Creates a CardLayout() class object using the default (interval 0). Public CardLayout(int hGap, int vGap) : Creates a CardLayout() class object using the horizontal interval specified by hgap and the vertical interval specified by vgap.

CardLayout class common methods:

Public void first(Container parent) : Displays the first card of the parent Container. Public void last(Container parent) : Displays the last card of the parent Container. Public void next(Container parent) : Displays the next card of the parent Container. Public void previous(Container parent) : Displays the previous card of the parent Container. Public void show(Container parent, String name) : Displays the component named name in the parent Container. If the component does not exist, no operation is performed

CardLayout example:

import java.awt.*; import javax.swing.*; Public class TestCard {public static void main(String[] args) {JFrame jf=new JFrame("CardLayout sample program "); //Container cp=jf.getContentPane(); JPanel cp=new JPanel(); jf.setContentPane(cp); CardLayout card = new CardLayout (20, 20); jf.setLayout(card); JButton bt1=new JButton(" soccer "); JButton bt2=new JButton(" basketball "); JButton bt3=new JButton(" volleyball "); JButton bt4=new JButton(" table tennis "); JButton bt5=new JButton(" badminton "); cp.add(bt1); cp.add(bt2); cp.add(bt3); cp.add(bt4); cp.add(bt5); card.next(cp); Jf. SetSize (200200); jf.setVisible(true); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}Copy the code

Custom layout

With the layout manager, the layout manager is responsible for the size and location of individual components. You cannot set component size and location properties in this case, and the setLocation(), setSize(), and setBounds() methods provided using the Java language are overridden by the layout manager. A custom layout does not use a layout manager. The format is setLayout(NULL); Because you are not using a layout manager, you can use the setBounds() method to specify the location and size of the component. Custom layouts are widely used because programmers can pay attention to the placement of components regardless of layout.

Use AWT components and Swing components for the basic steps of programming

  • Import corresponding packages
  • Setting the top-level container
  • Set up the layout manager
  • Add components to the container
  • Event handling of components

The event processing

Java uses the delegate event model to handle events. The delegate event model is characterized by delegating the handling of events to independent objects rather than components themselves. The delegate event model contains three important concepts: events, event sources, and event listeners.

The event

An operation performed by a user on an interface (usually performed using various input devices such as a mouse or keyboard), such as dragging the mouse, pressing the Enter key, entering a character through the keyboard, selecting a menu item, selecting an option in the list, or obtaining the focus, are all events. When an event occurs, the event is represented by an event object. Event objects have corresponding event classes. Different event classes describe different types of user actions. Event classes are included in java.awt. Event and javax.Swing.Event.

The name of the instructions
ActionEvent Handle buttons, double – click list items, click menu items
AdjustmentEvent Scroll bar position changed
ComponentEvent Resize components to move, hide, or show components
ContainerEvent Add and remove components from a container
FocusEvent Component loses or gains focus
MouseEvent Drag, move, click, press, release
ItemEvent Select or deselect list boxes, check boxes, and other options
KeyEvent Press or release a key
InputEvent Handles events for check box and list item clicks, control selection, and optional menu item selection
TextEvent Handles changes to a text area or the value of a text area
WindowEvent Handles window activation, active window loss, minimize, open, close, or exit events

The event source

The component that produces the event is called the event source. For example, when a mouse is placed over a button, the button is the event source and an ActionEvent event is generated.

The listener

Listener: an object that listens for events occurring on an event source (receives event objects) and processes events accordingly. Event listener class: A class that checks if an event occurs and then activates the event listener to handle it, must implement the event listener interface or inherit the event listener adapter class. Event listener interface: Each listener comes with an interface that defines one or more methods that must be implemented to handle events. Implementing these methods is a series of actions that are performed when an event is listened for. The adapter class is a special class that already implements an interface and adds an empty statement body to all the methods in the interface. So instead of using listeners, adapters can be used to rewrite the methods that the program needs to execute and the methods that do not need to be executed, simplifying the writing of programs. The event listener interface and the event listener adapter classes are also included in the java.awt. Event and Javax.Swing.Event packages. Each event class has a “unique” interface for event handling methods.

Register event listeners

In order to be able to have event listeners check for certain events on a component (event source) and process them accordingly, event listeners must be registered on the event source. This is done using the event source component as follows. AddXxxListener (event listener object) where Xxx corresponds to the corresponding event class.

A. addXXXListener(B) : When A XXX event occurs, object B is notified and calls the corresponding method to process the event. Node.addactionlistener (handler h); Method one: A custom listener class implements the event listening interface

ActionListener{public void actionPerformed(ActionEvent e) {...... }}Copy the code

Method two: implement the event listening interface with anonymous inner classes

Button.addactionlistener (new ActionListener(){public void actionPerformed(ActionEvent e) {...... }});Copy the code

Method three: Customize the class to implement the corresponding adapter class

button. addMouseListener(new MAdapter()); Class MAdapter extends MouseAdapter{@override public void mouseClicked(MouseEvent e) {}Copy the code

General steps for processing component events in Java

  1. Create a new component (such as JButton).
  2. Add this component to the appropriate panel, such as a JPanel.
  3. Register listeners to listen for events generated by the event source (such as in response to a user clicking a button via ActionListener).
  4. Define methods to handle the event (such as in actionPerformed in ActionListener).

Common components

Various components can be added to a window through the container’s add() method. Common components: buttons, labels, text boxes, text areas, check boxes, radio buttons, lists, menus, dialog boxes, and so on

button

Buttons (Button, JButton) are common components that allow ICONS, strings, or both, the most common action being clicking on a Button.

(1) Construction method

(2) Common methods

  • public void addActionListener(ActionListener a)
  • Public void setMnemonic(int mnemonic) : Specifies a hot key. Pressing Alt and specifying a hot key simultaneously means pressing the button
  • Public void setEnabled(Boolean B) : Enable (or disable) button.
  • Public Boolean isSelected() : Returns the status of the button. Returns true if the toggle button is selected, false otherwise.
  • Public String getText() : Returns the text of the button.
  • Public setText(String Text) : Sets the text of the button.
  • Public Boolean isDefaultButton() : gets the value of the defaultButton property, if true means the button is the current defaultButton.

(3) Common events

ActionEvent Event An ActionEvent occurs when a button is clicked or the Space key is pressed when the button is in focus. The ActionLister interface is used to listen for this event, and the ActionLister interface method actionPerformed() must be implemented.

The label

Labels (Label, JLabel) are common components that can display text, images, or both. The tag is typically used to display a prompt and does not respond to input events. As a result, it can’t get keyboard focus.

(1) Construction method

(2) Common methods

  • Public Icon getIcon() : Returns the Icon displayed on the label.
  • Public void setIcon(Icon Icon) : defines the Icon to be displayed for the label. If the value of the parameter icon is null, nothing is displayed.
  • Public String getText() : Returns the String displayed by the label.
  • Public void setText(String Text) : Defines the single line of text to display for the label. If the value of the text argument is null or an empty string (” “), nothing is displayed.
  • Public void setHorizontalAlignment(int alignment) Sets the alignment along the X axis. The parameter is usually one of the LEFT, CENTER, or RIGHT constants.

The text box

TextField (TextField, JTextField) components allow you to edit or enter a single line of text.

(1) Construction method

(2) Common methods

  • Public String getText() : Gets the text of the text box
  • Public void setText(String text) : Sets the text of the text box to text
  • Public void addActionListener(ActionListener L) : Registers an ActionEvent listener for a text box
  • Public void removeActionListener(ActionListener L) : Removes the ActionEvent listener for the text box
  • Public void setColumns(int columns) : Sets the number of columns in this TextField and verifies the layout.
  • Public void setFont(Font f) : Sets the current Font.
  • Public void setHorizontalAlignment(int alignment) Sets the horizontal alignment of the text. The value of the alignment can be one of the following: Jtextfield-left, jTextField-center, jTextField-right, jTextfield-leading, jTextfield-trailing.

(3) Common events

An ActionEvent event

When characters are entered in the text box and carriage Return is pressed, the ActionEvent event occurs and the actionPerformed() method of the overridden ActionListener interface is executed.

FocusEvent event

Most components can listen for FocusEvent. After a FocusEvent occurs, the focusGained() method is executed, and the focusLost() method is executed if the component loses focus.

JPanel

JPanel components in Java are container components. You can put buttons, text boxes, and other non-container components in a JPanel, and you can even put several more JPanel components in a JPanel. Swing uses JPanel to define panels, which must be contained in another container, such as JFrame.

(1) Construction method

  • JPanel() : Creates a JPanel with FlowLayout as the default
  • JPanel(LayoutManager Layout) : Creates a JPanel for the specified layout

(2) Common methods

  • Void add(Component comp) : Adds Component comp
  • Void add(Component comp, int index) : Adds the Component comp to the specified position index
  • Int getComponentCount() : Gets the number of all components in a Jpanel
  • Component getComponent(int index) : Gets the Component corresponding to the specified index
  • Component getComponent(int x, int y) : Gets the Component at position
    ,y>
  • Void Remove (Component comp) : Removes Component comp
  • Void removeAll() : removes all components
  • Void setLayout(LayoutManager Layout) : Sets the layout to layout
  • LayoutManager getLayout() : Gets the current layout
  • Void setBorder(Border Border) : Sets the Border to Border

(3) Border interface

Public Interface Border This interface describes an object that can render borders around the edges of Swing components. Public Class BorderFactory extends Object Provides a factory class for the standard Border Object. Wherever possible, this factory class will provide a reference to the shared Border instance. The methods in this class are static.

The radio button

Radio buttons allow the user to select a single option from a set of components. Swing’s JRadioButton class is used to create checkboxes.

(1) Construction method

(2) Combine radio buttons into groups

Checkboxes can be added to containers like buttons. To group singletons, create an instance of java.Swing.ButtonGroup and add the singletons to the instance using the Add method, as follows: java.Swing.ButtonGroup

ButtonGroup btg = new ButtonGroup(); JRadioButton jrb1=new JRadioButton(" male "); Jrb2 =new JRadioButton(" 女 "); btg.add(jrb1); btg.add(jrb2);Copy the code

The ButtonGroup class is an invisible component that does not need to be added to the container to display, but logically represents a group of radio buttons.

(3) Common methods of ButtonGroup class

  • Public ButtonGroup() : Constructs a single box group.
  • Public void Add (AbstractButton B) : Adds an option box to the ButtonGroup component.
  • Public int getButtoncount() : getButtoncount;
  • Public void remove(AbstractButton B) : remove option B.

(4) JRadioButton class common methods

  • Public Boolean isSelected() : Returns the status of the button. Returns true if the toggle button is selected, false otherwise.
  • Public String getText() : Returns the text of the button.
  • Public void setText(String text) : Sets the text of the button.

(5) JRadioButton events

An ActionEvent event

Monitor Settings: addActionListener(ActionListener) Interface method: actionPerformed(ActionEvent E)

ItemEvent event

Monitor Settings: addItemListener(ItemListener) Interface method: itemStateChanged(ItemEvent E)

public void itemStateChanged(ItemEvent e) { // if(e.getSource() instanceof JRadioButton) if(jrb1.isSelected()) //Process  the selection for jrb1 if(jrb2.isSelected()) //Process the selection for jrb2 }Copy the code

Check box

A checkbox is a component that users can turn on and off options, like a light switch. Swing’s JCheckBox class is used to create checkboxes.

(1) Construction method

(2) JCheckBox class common methods

  • Public Boolean isSelected() : Returns the status of the button. Returns true if the toggle button is selected, false otherwise.
  • Public String getText() : Returns the text of the button.
  • Public void setText(String text) : Sets the text of the button.

(3) JCheckBox event

An ActionEvent event

Monitor Settings: addActionListener(ActionListener) Interface method: actionPerformed(ActionEvent E)

ItemEvent event

Monitor Settings: addItemListener(ItemListener) Interface method: itemStateChanged(ItemEvent E)

public void itemStateChanged(ItemEvent e)
{
	if(e.getSource() instanceof JCheckBox)
		if(jchk1.isSelected())
			//Process the selection for jchk1;
		if(jchk2.isSelected())
			//Process the selection for jchk2;
}
Copy the code

Combo box

The JComboBox component, called a combo box or the following list box, folds all options together, with the first option added displayed by default. When the user clicks on the combo box, a drop-down list of options appears, from which the user can select an item and display it. JComboBox combobox components come in editable and uneditable forms.

  • Uneditable combo box: You can only select from an existing list of options.
  • Editable combo box: You can either select from existing options or enter new content yourself, but it is only displayed as the current item and is not added to the combo box’s list of options.

(1) Construction method

String items[]={" left aligned ", "right aligned", "aligned at both ends", "Centered", "scattered aligned"}; JComboBox jcb=new JcomboBox(items);Copy the code

(2) Common methods

  • Void addItem(Object item) : Adds an option to the selection box
  • Void addItemListener(ItemListener) : Registers listeners with the selection box
  • Object getItemAt(int index) : Gets the option specified in the selection box
  • Int getItemCount() : Gets the number of options in the selection box
  • Object getSelectedItem() : Gets the Object representation (usually a string representation) of the selected option in the selection box.
  • Void removeItem(Object anObject) : Removes an item from the item list.
  • Void removeAllItems() : Removes all items from the item list.
  • Void removeItemAt(int anIndex) : Removes the item at anIndex.
  • Void setEditable(Boolean b) : Sets the editable properties of the selection box
  • Void setEnabled(Boolean b) : Sets whether the selection box is available
  • Public Boolean isEditable() : returns true if the combo box isEditable. Otherwise, the value is false.

(3) JComboBox event

JComboBox can raise ActionEvent and ItemEvent events, among other events. When a new option is selected, JComboBox produces two ItemEvent events, one to cancel the previous option and one to select the current option. JComboBox generates an ActionEvent event after the ItemEvent event is generated. To respond to the ItemEvent event, implement the processing method itemStateChanged(ItemEvent E) to handle the selection.

Text area

The text area component (JTextArea) is similar to the text box component, except that the text area component displays multi-line text and has the function of scrolling when the content is out of the display range, while the text box component displays single-line text.

(1) Construction method

(2) Common methods

  • Public void insert(String STR,int pos) : Inserts the specified text into the specified position.
  • Public void appEnd (String STR) : appends the given text to the end of the document.
  • Public void replaceRange(String STR,int start,int end) : Replaces text from the indicated start position to the end position with the given new text.
  • Public void Copy () : transfers the currently selected range in the associated text model to the system clipboard, retaining the contents in the text model. The current selection remains as it is. Nothing is done with the NULL selection.
  • Public void paste() : transfers the contents of the system clipboard to the associated text model. If there is a selection in the associated view, replace it with the contents of the clipboard. If nothing is selected, the clipboard is inserted in front of the current insertion position in the associated view. If the clipboard is empty, no action is performed.
  • Public void cut() : transfers the currently selected range in the associated text model to the system clipboard and removes the content from the model. Resets the current selection. Nothing is done with the NULL selection.
  • Public void selectAll() : Selects all text in the text area. Nothing is done on null or empty documents.
  • Public void setLineWrap(Boolean wrap) : Sets the line break policy for the text area. Public void setWrapStyleWord(Boolean word) : Sets the newline mode (if the text area is to be newline).

(3) Common events

ActionEvent Event: Similar to the ActionEvent event of a text box. DocumentEvent event: This event occurs when a user edits text in a text area. Three methods of the DocumentListener interface are implemented in the following format:

  • Void changedUpdate(DocumentEvent E) : Gives notice that a property or set of properties has changed.
  • Void insertUpdate(DocumentEvent E) : Gives notification that an insert has been performed on the document.
  • Void removeUpdate(DocumentEvent E) : Gives notice that part of the document has been removed.

The password

The JPasswordField extends JTextField component is similar to the text field component except that a password field does not display input information. Instead, it displays the set echo character, which is ‘*’ by default.

(1) Construction method

(2) Common methods

  • Public char[] getPassword() : Returns the text contained in this password box object.
  • Public char getEchoChar() : Returns the character to be used in the echo. The default is ‘*’.
  • Public void setEchoChar(char C) : Sets the characters in the output of the password box object.

(3) Events of the password box

Similar to the ActionEvent event for a text box

The list of

Lists are used to select from multiple list items, numbered from 0. AWT’s List class and Swing’s Jlist class are used for lists. Note: List does not support multiple selection by default, whereas Jlist does. The JList must be in the JScrollPane, otherwise scrolling is not supported.

(1) Construction method

(2) Common methods

  • Public Object getSelectedValue() : Returns the selected value when only a single item of the list is selected.
  • Public int getSelectedIndex() : Returns the selected index if only a single item of the list is selected.
  • Public setModal(ListModel Model) : Sets the model that represents the content of the list or the “value” of the list, notifies the property change listener, and then clears the list selection.

(3) the ListModel

  • Public Interface ListModel: This interface defines method components (such as JList) that are used to get the value of each cell in the list and the length of the list. Logically, the model is a vector with indexes ranging from 0 to ListDatamodel.getSize () -1. Any changes to the content and length of the data model must be reported to all ListDataListener.
  • The add(int Index,Object Element) method in the DefaultListModel class inserts the specified element at the specified position in this list.

(4) Jlist events

ListSelectionEvent and ListDataEvent events

  • When the user selects a list item in the list box, the ListSelectionEvent event occurs, and the valueChanged() method is executed after the ListSelectionListener listens for this event.
  • The listener ListDataListener listens for the ListDataEvent event and executes the contentsChanged(), intervalAdded(), or intervalRemoved() methods, depending on the event type.

JScrollPane

  • When setting up an interface that displays a larger portion of the content in a smaller container form, use the JScrollPane. A JScrollPane is a scrollbar panel used to create a scroll window. It is also a container, but can only hold one component and cannot use a layout manager. If you need to place multiple components in the JScrollPane pane, you need to place multiple components on the JPanel panel, and then add the JPanel panel as an integral component to the JScrollPane pane.
  • The JScrollPane class is often used in conjunction with the JList, JLabel, and JTextArea classes.
  • JScrollPane manages viewports, optional vertical and horizontal scroll bars, and optional row and column headers viewports.
  • JViewport provides a window or “viewport” for the data source.
  • A JScrollPane can have a column header and a row header. Both of these are JViewport objects and can be specified by setRowHeaderView and setColumnHeaderView. The column header viewport automatically scrolls left and right to track the left and right scrolling of the main viewport. (But it doesn’t scroll vertically.) Row headers scroll similarly.
  • At the intersection of two scroll bars, the intersection of row and column headings, or the intersection of the scroll bar and one of the headings, the two components stop close to the corner, leaving a rectangular space that is empty by default. These Spaces could exist at all four corners. An angular component is visible only if there is empty space in the corner in which it exists.

The menu

Menus are a very important and common component of guIs. The drop-down menu is usually located at the top of the window, including the menu bar (JMenuBar), the menu (JMenu) and the menu item (JMuneItem), and the menu item can also contain several menu items. Pop-up menu (JpopupMenu) is also called the right menu or shortcut menu. Click the right mouse button to display the pop-up menu.

(1) Menu bar

The menu bar component is the container that holds the menu. The menu bar does not respond to events. Constructor: public JMenuBar()

  • Public JMenu Add (JMenu C) : Appends the menu to the end of the menu bar.
  • Public JMenu getMenu(int index) : returns the menu at the index position in the menu bar. The first position is 0 in ascending order.
  • Public Boolean isSelected() : Return “true” if the menu bar has been selected, “false” otherwise.

(2) Menu

The menu contains several menu items and dividers. When you click a menu, the menu expands.

Construction method:

Common methods:

  • Public JMenuItem add(Action A) : Creates a new menu item that connects to the specified Action object and appends it to the end of the menu.
  • Public Component Add (Component C) : Appends a Component to the end of this menu.
  • Public Component add(Component C,int index) : Adds the specified Component to the given position in the container.
  • Public JMenuItem add(JMenuItem menuItem) : appends a menuItem to the end of the menu.
  • Public JMenuItem add(String s) : Creates a new menu item with the specified text and appends it to the end of the menu.
  • Public void addSeparator() : Appends the new separator to the end of the menu.

Common events:

  • MenuEvent Event notification that the menu that is the source of the event has been sent, selected, or cancelled.
  • When the MenuListener listens for a MenuEvent, the menuSelected() method is called if a menu is selected. To deselect a menu, call the menuDeselected() method. If the menu is cancelled, the menuCanceled() method is called.

(3) Menu items

A menu item is an implementation of an item in a menu. When selected with the mouse or keyboard, an action event is triggered. A menu item can be a command or another menu (submenu).

Construction method:

Common methods:

  • Public void setEnabled(Boolean b) : Enable or disable a menu item.
  • Protected String paramString() : Returns the String representation of this JMenuItem.

(4) Steps to create a menu:

Create MenuBar: MenuBar mnuBar=new MenuBar(); 2. Create menu and add to menu bar: JMenu mnuFile=new JMenu(” file “); mnuBar.add(mnuFile); MnuNew =new JMenuItem(” New “); mnuFile.add(mnuNew); 4. Add menu bar to container: setJMenuBar(mnuNotepad); 5. Add event listeners and implement corresponding listener interface methods: MenuListener, ActionListener

dialog

The dialog box is one of the most widely used components. It can’t be used as the main window of an application. There are no minimize and maximize buttons, and you can’t set menu bars. There are two types of dialog boxes: modal and unmodal. Modal dialogs block user operations on other Windows, such as JOptionPane, when displayed. Non-modal dialogs display without blocking user operations on other Windows, such as JDialog.

(1) JOptionPane class

JOptionPane is a simple and commonly used modal dialog box class that provides four commonly used dialog box styles. Dialogs can be created either through the constructor method or through its static method showXxxDialog.

  • ShowMesageDialog () : Displays some messages to the user and gets “OK” and “undo” responses.
  • ShowConfirmDialog () : Ask a question asking for confirmation and get a yes/no/ Cancel response.
  • ShowInputDialog () : Prompts the user for input through a text box, list, or other means, and gets an “OK” and “undo” response.
  • ShowOptionDialog () : Optional dialog box

These methods return an integer indicating which button the user clicked. Valid values for the returned value are YES_OPTION, NO_OPTION, CANCEL_OPTION, OK_OPTION, and CLOSED_OPTION.

import java.awt.*; import javax.swing.*; The class JOptionPaneEx {public static void main (String [] args) {String s = JOptionPane. ShowInputDialog (" please input your name: "); JOptionPane. ShowMessageDialog (null, "hello," + s); }}Copy the code

(2) JDialog class

The JDialog class can be used to design custom dialog boxes when the four common dialog box modes provided by the JOptionPane class are insufficient. Constructor: See the API documentation

  • Public JDialog() : Creates a non-modal dialog
  • JDialog(Dialog Owner,String Title,Boolean Modal) : Creates a Dialog box with a specified title, mode, and specified owner Dialog.
  • JDialog(Frame Owner,String Title,Boolean Modal) : Creates a dialog box with a specified title, owner Frame, and mode.

JFileChooser

JFileChooser provides a simple mechanism for users to select files.

Construction method:

Common methods:

  • Void setSelectedFile(File File) : Sets the selected File
  • ShowDialog (Component parent, String approveButtonText) : Pops up a custom file selector dialog box with a custom Approve button
  • ShowOpenDialog (Component parent) : Displays an “Open File” file selector dialog box
  • ShowSaveDialog (Compont Parent) : Displays a “Save File” File selector dialog box
JFileChooser jfc=new JFileChooser(); if(jfc.showSaveDialog(null)! = JFileChooser.APPROVE_OPTION) return; File file= jfc.getSelectedFile();Copy the code

Common event

Mouse events

Mouse events are classified into two categories. One is mouseEvents that occur on the left and right mouse buttons. Another type of event is an event that happens on a mouse wheel, called a MouseWheelEvent. Different MouseEvent events are handled through the MouseListener listener interface and MouseMotionListener listener interface. The MouseWheelEvent event is handled through the MouseWheelListener listener interface.

MouseEvent event

MouseEvent includes the following two types of events: MouseEvent class

  • Press the mouse button
  • Release the mouse button
  • Click the mouse button (press and release)
  • The mouse cursor goes into the uncovered part of the component geometry
  • The mouse cursor moves away from the uncovered part of the component geometry

Mouse movement event class

  • Move the mouse
  • Drag the mouse

A common method for MouseEvent

  • Public int getButton() Specifies the mouse button
  • Public int getClickCount() Number of mouse clicks
  • Public int getX() Specifies the x-coordinate of the mouse relative to the source component
  • Public int getY() Specifies the Y coordinate of the mouse relative to the source component

The MouseListener listener interface handles mouseEvents. The MouseListener listener interface is used to receive mouse events on the component, including mouse events such as press, release, click, enter, or leave. When the MouseListener listener interface listens for a MouseEvent event to occur, it executes the following methods based on the event type:

  • void mouseClicked(MouseEvent e)
  • mouseEntered(MouseEvent e)
  • void mouseExited(MouseEvent e)
  • void mousePressed(MouseEvent e)
  • void mouseReleased(MouseEvent e)

The MouseMotionListener listener interface handles MouseEvent events. The MouseMotionListener listener interface is used to receive mouse movement events on components, including moving and dragging the mouse. When the MouseMotionListener listener interface listens for a MouseEvent event to occur, it executes the following methods based on the event type:

  • Void mouseDragged(MouseEvent E) : Called after pressing and dragging the mouse button on a component.
  • Void mouseMoved(MouseEvent E) : Called when the mouse cursor is moved over the component but no key is pressed.

MouseWheelEvent event

The MouseWheelEvent event indicates that the mouse wheel is rolled in the component.

MouseWheelEvent is a common method for events

  • Public int getWheelRotation() : Returns the number of times the “click” of the mouse wheel.

When the MouseWheelListener listener interface listens for a MouseWheelEvent event to occur, execute the following methods: Void mouseWheelMoved(MouseWheelEvent e) Called when the mouse wheel is rotated.

Keyboard events

KeyEvent is an event that occurs when a key is pressed, released, or typed.

KeyEvent common method

  • public char getKeyChar()
  • public void setKeyCode(int keyCode)
  • public int getModifiers()
  • public static String getKeyModifiersText(int modifiers)

The KeyListener handles KeyEvent events: When the KeyListener listener listens for a KeyEvent event to occur, it executes the following methods based on the event type:

  • void keyTyped(KeyEvent e)
  • void keyPressed(KeyEvent e)
  • void keyReleased(KeyEvent e)

Form the event

Most GUI applications require the Window form object as the outermost container and form object is the basis of all GUI applications where other components are placed directly or indirectly on the form. Actions performed on a form, such as opening, closing, activating, deactivating, etc., are WindowEvent events. The JDK provides a class called WindowEvent to represent these events. The WindowListener listener handles WindowEvent events: When the WindowListener listener listens for a WindowEvent event to occur, it executes the following methods based on the behavior that occurred:

  • WindowOpened () : Executes this method when a window opens.
  • WindowClosing () : This method is performed when you try to close the window by clicking the close button in the upper right corner of the window.
  • WindowIconified () : Click the Minimize icon of a window. This method is performed when the window is minimized.
  • WindowDeiconified () : Click the Restore button of the window. This method is performed when the window is restored.
  • WindowActivated () : Executes this method when the window becomes the current window before a series of Windows; This method is executed when you open a window, restore a window, or click a window to the foreground.
  • WindowDeactivated () : Executes this method when a window is removed from the foreground, such as icon, close, or another window is activated.
  • WindowClosed () : This method is executed after the window is closed, such as after clicking the close button or after the Dispose () method of the window is executed.

Closing a window in JFrame

Public void setDefaultCloseOperation(int operation) The default value of HIDE_ON_CLOSE is one of the following constants:

  • DO_NOTHING_ON_CLOSE: no operation is performed.
  • HIDE_ON_CLOSE: hides the current window.
  • DISPOSE_ON_CLOSE: Hides the current window and frees the resources it occupies.
  • EXIT_ON_CLOSE: Use the System exit method to exit the application where the window resides.