Swing 简明教程

SWING - Quick Guide

SWING - Overview

Swing API 是可扩展 GUI 组件集,可帮助开发者轻而易举地创建基于 Java 的前端/GUI 应用程序。它建立在 AWT API 之上,可替代 AWT API,因为它几乎每个控件都对应到 AWT 控件。Swing 组件遵循模型-视图-控制器架构以满足以下准则。

Swing API is a set of extensible GUI Components to ease the developer’s life to create JAVA based Front End/GUI Applications. It is build on top of AWT API and acts as a replacement of AWT API, since it has almost every control corresponding to AWT controls. Swing component follows a Model-View-Controller architecture to fulfill the following criterias.

  1. A single API is to be sufficient to support multiple look and feel.

  2. API is to be model driven so that the highest level API is not required to have data.

  3. API is to use the Java Bean model so that Builder Tools and IDE can provide better services to the developers for use.

MVC Architecture

Swing API 架构大致遵循 MVC 架构,具体方式如下。

Swing API architecture follows loosely based MVC architecture in the following manner.

  1. Model represents component’s data.

  2. View represents visual representation of the component’s data.

  3. Controller takes the input from the user on the view and reflects the changes in Component’s data.

  4. Swing component has Model as a seperate element, while the View and Controller part are clubbed in the User Interface elements. Because of which, Swing has a pluggable look-and-feel architecture.

Swing Features

  1. Light Weight − Swing components are independent of native Operating System’s API as Swing API controls are rendered mostly using pure JAVA code instead of underlying operating system calls.

  2. Rich Controls − Swing provides a rich set of advanced controls like Tree, TabbedPane, slider, colorpicker, and table controls.

  3. Highly Customizable − Swing controls can be customized in a very easy way as visual apperance is independent of internal representation.

  4. Pluggable look-and-feel − SWING based GUI Application look and feel can be changed at run-time, based on available values.

SWING - Environment Setup

本部分将指导您如何在计算机上下载和设置 Java。请使用以下步骤设置环境。

This section guides you on how to download and set up Java on your machine. Please use the following steps to set up the environment.

Java SE 可从链接 Download Java 中免费获取。因此,您可以根据操作系统下载版本。

Java SE is freely available from the link Download Java. Hence, you can download a version based on your operating system.

按照说明下载 Java 并运行 .exe 在计算机上安装 Java。在计算机上安装 Java 后,您需要设置环境变量以指向正确的安装目录。

Follow the instructions to download Java and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set the environment variables to point to the correct installation directories.

Setting Up the Path for Windows 2000/XP

假设您已在 c:\Program Files\java\jdk 目录中安装了 Java−

Assuming you have installed Java in c:\Program Files\java\jdk directory −

Step 1 − 右键单击“我的电脑”并选择“属性”。

Step 1 − Right-click on 'My Computer' and select 'Properties'.

Step 2 − 单击“高级”选项卡下的“环境变量”按钮。

Step 2 − Click the 'Environment variables' button under the 'Advanced' tab.

Step 3 − 更改“Path”变量,以便它还包含 Java 可执行文件的路径。例如,如果路径当前设置为 'C:\WINDOWS\SYSTEM32' ,请将路径更改为 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'

Step 3 − Alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.

Setting Up the Path for Windows 95/98/ME

假设您已在 c:\Program Files\java\jdk 目录中安装了 Java−

Assuming you have installed Java in c:\Program Files\java\jdk directory −

Step 1 − 编辑 'C:\autoexec.bat' 文件并在末尾添加以下行: 'SET PATH=%PATH%;C:\Program Files\java\jdk\bin'

Step 1 − Edit the 'C:\autoexec.bat' file and add the following line at the end: 'SET PATH=%PATH%;C:\Program Files\java\jdk\bin'.

Setting Up the Path for Linux, UNIX, Solaris, FreeBSD

环境变量 PATH 应设置为指向 Java 二进制文件已安装的位置。如果您在执行此操作时遇到问题,请参阅 Shell 文档。

Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your Shell documentation if you have trouble doing this.

例如,如果您使用 bash 作为 shell,则您会在结尾 '.bashrc: export PATH=/path/to/java:$PATH' 添加以下行。

Example, if you use bash as your shell, then you would add the following line to the end '.bashrc: export PATH=/path/to/java:$PATH'.

为了编写 Java 程序,您需要文本编辑器。市场上还有功能更强大的 IDE。但是目前,您可以考虑以下选项之一−

To write your Java programs, you will need a text editor. There are even more sophisticated IDE available in the market. But for now, you can consider one of the following −

  1. Notepad − On Windows machine, you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad.

  2. Netbeans − Netbeans is a Java IDE that is open source and free, which can be downloaded from https://www.netbeans.org/index.html.

  3. Eclipse − Eclipse is also a Java IDE developed by the Eclipse open source community and can be downloaded from https://www.eclipse.org/.

SWING - Controls

每个用户界面都考虑以下三个主要方面:

Every user interface considers the following three main aspects −

  1. UI Elements − These are the core visual elements the user eventually sees and interacts with. GWT provides a huge list of widely used and common elements varying from basic to complex, which we will cover in this tutorial.

  2. Layouts − They define how UI elements should be organized on the screen and provide a final look and feel to the GUI (Graphical User Interface). This part will be covered in the Layout chapter.

  3. Behavior − These are the events which occur when the user interacts with UI elements. This part will be covered in the Event Handling chapter.

swing class hierarchy

每个 SWING 控件都从以下组件类层次继承属性。

Every SWING controls inherits properties from the following Component class hiearchy.

S.No.

Class & Description

1

ComponentA Component is the abstract base class for the non menu user-interface controls of SWING. Component represents an object with graphical representation

2

ContainerA Container is a component that can contain other SWING components

3

JComponentA JComponent is a base class for all SWING UI components. In order to use a SWING component that inherits from JComponent, the component must be in a containment hierarchy whose root is a top-level SWING container

SWING UI Elements

以下是使用 SWING 设计 GUI 时常用的控件列表。

Following is the list of commonly used controls while designing GUI using SWING.

S.No.

Class & Description

1

JLabelA JLabel object is a component for placing text in a container.

2

JButtonThis class creates a labeled button.

3

JColorChooserA JColorChooser provides a pane of controls designed to allow a user to manipulate and select a color.

4

JCheck BoxA JCheckBox is a graphical component that can be in either an on (true) or off (false) state.

5

JRadioButtonThe JRadioButton class is a graphical component that can be in either an on (true) or off (false) state. in a group.

6

JListA JList component presents the user with a scrolling list of text items.

7

JComboBoxA JComboBox component presents the user with a to show up menu of choices.

8

JTextFieldA JTextField object is a text component that allows for the editing of a single line of text.

9

JPasswordFieldA JPasswordField object is a text component specialized for password entry.

10

JTextAreaA JTextArea object is a text component that allows editing of a multiple lines of text.

11

ImageIconA ImageIcon control is an implementation of the Icon interface that paints Icons from Images

12

JScrollbarA Scrollbar control represents a scroll bar component in order to enable the user to select from range of values.

13

JOptionPaneJOptionPane provides set of standard dialog boxes that prompt users for a value or informs them of something.

14

JFileChooserA JFileChooser control represents a dialog window from which the user can select a file.

15

JProgressBarAs the task progresses towards completion, the progress bar displays the task’s percentage of completion.

16

JSliderA JSlider lets the user graphically select a value by sliding a knob within a bounded interval.

17

JSpinnerA JSpinner is a single line input field that lets the user select a number or an object value from an ordered sequence.

SWING - Event Handling

在本章中,你将了解事件、其类型,以及如何处理事件。本文末尾提供了示例,以帮助你更好地理解。

In this chapter, you will learn about Events, its types, and also learn how to handle an event. Example is provided at the end of the chapter for better understanding.

What is an Event?

对象的上述状态变化称为 Event ,即事件描述了源状态的变化。事件是用户与图形用户界面组件交互的结果而生成的。例如,单击按钮、移动鼠标、通过键盘输入字符、从列表中选择项目以及滚动页面都是导致事件发生的活动。

Change in the state of an object is known as Event, i.e., event describes the change in the state of the source. Events are generated as a result of user interaction with the graphical user interface components. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from the list, and scrolling the page are the activities that causes an event to occur.

Types of Event

事件可以大致分为两类 −

The events can be broadly classified into two categories −

  1. Foreground Events − These events require direct interaction of the user. They are generated as consequences of a person interacting with the graphical components in the Graphical User Interface. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page, etc.

  2. Background Events − These events require the interaction of the end user. Operating system interrupts, hardware or software failure, timer expiration, and operation completion are some examples of background events.

What is Event Handling?

事件处理是控制事件并决定如果发生事件应发生什么的机制。此机制具有一个代码,称为事件处理程序,该代码在事件发生时执行。

Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism has a code which is known as an event handler, that is executed when an event occurs.

Java 使用委派事件模型来处理事件。此模型定义了生成和处理事件的标准机制。

Java uses the Delegation Event Model to handle the events. This model defines the standard mechanism to generate and handle the events.

委托事件模型具有以下关键参与者。

The Delegation Event Model has the following key participants.

  1. Source − The source is an object on which the event occurs. Source is responsible for providing information of the occurred event to it’s handler. Java provide us with classes for the source object.

  2. Listener − It is also known as event handler. The listener is responsible for generating a response to an event. From the point of view of Java implementation, the listener is also an object. The listener waits till it receives an event. Once the event is received, the listener processes the event and then returns.

此方法的优点是,用户界面逻辑与生成事件的逻辑完全分离。用户界面元素能够将事件处理委托给单独的一段代码。

The benefit of this approach is that the user interface logic is completely separated from the logic that generates the event. The user interface element is able to delegate the processing of an event to a separate piece of code.

在此模型中,侦听器需要向源对象注册,以便侦听器可以接收事件通知。这是一​​种处理事件的有效方法,因为只有希望接收事件的侦听器才会收到事件通知。

In this model, the listener needs to be registered with the source object so that the listener can receive the event notification. This is an efficient way of handling the event because the event notifications are sent only to those listeners who want to receive them.

Steps Involved in Event Handling

Step 1 −用户单击按钮,生成事件。

Step 1 − The user clicks the button and the event is generated.

Step 2 −自动创建有关事件类的对象,并将有关源和事件的信息填充到同一对象中。

Step 2 − The object of concerned event class is created automatically and information about the source and the event get populated within the same object.

Step 3 −事件对象转到已注册侦听器类的,方法。

Step 3 − Event object is forwarded to the method of the registered listener class.

Step 4 −该方法得到执行并返回。

Step 4 − The method is gets executed and returns.

Points to Remember About the Listener

  1. In order to design a listener class, you have to develop some listener interfaces. These Listener interfaces forecast some public abstract callback methods, which must be implemented by the listener class.

  2. If you do not implement any of the predefined interfaces, then your class cannot act as a listener class for a source object.

Callback Methods

这些方法由 API 供应商提供并且由应用程序程序员定义,由应用程序开发人员调用。此处,回调方法表示事件方法。响应事件,java jre 将激发回调方法。所有此类回调方法都包含在侦听器接口中。

These are the methods that are provided by API provider and are defined by the application programmer and invoked by the application developer. Here the callback methods represent an event method. In response to an event, java jre will fire callback method. All such callback methods are provided in listener interfaces.

如果某个组件希望有侦听器来侦听其事件,则源必须向侦听器注册自身。

If a component wants some listener to listen ot its events, the source must register itself to the listener.

Event Handling Example

使用您选择的任意编辑器,使用以下命令创建 Java 程序,例如 D:/ > SWING > com > tutorialspoint > gui >

Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >

SwingControlDemo.java

package com.tutorialspoint.gui;

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

public class SwingControlDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingControlDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingControlDemo swingControlDemo = new SwingControlDemo();
      swingControlDemo.showEventDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);
      statusLabel.setSize(350,100);

      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }
      });
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);
   }
   private void showEventDemo(){
      headerLabel.setText("Control in action: Button");

      JButton okButton = new JButton("OK");
      JButton submitButton = new JButton("Submit");
      JButton cancelButton = new JButton("Cancel");

      okButton.setActionCommand("OK");
      submitButton.setActionCommand("Submit");
      cancelButton.setActionCommand("Cancel");

      okButton.addActionListener(new ButtonClickListener());
      submitButton.addActionListener(new ButtonClickListener());
      cancelButton.addActionListener(new ButtonClickListener());

      controlPanel.add(okButton);
      controlPanel.add(submitButton);
      controlPanel.add(cancelButton);

      mainFrame.setVisible(true);
   }
   private class ButtonClickListener implements ActionListener{
      public void actionPerformed(ActionEvent e) {
         String command = e.getActionCommand();

         if( command.equals( "OK" ))  {
            statusLabel.setText("Ok Button clicked.");
         } else if( command.equals( "Submit" ) )  {
            statusLabel.setText("Submit Button clicked.");
         } else {
            statusLabel.setText("Cancel Button clicked.");
         }
      }
   }
}

使用命令提示符编译程序。转到 D:/ > SWING 然后键入以下命令。

Compile the program using the command prompt. Go to D:/ > SWING and type the following command.

D:\AWT>javac com\tutorialspoint\gui\SwingControlDemo.java

如果没有发生任何错误,则表示编译成功。使用以下命令运行程序。

If no error occurs, it means the compilation is successful. Run the program using the following command.

D:\AWT>java com.tutorialspoint.gui.SwingControlDemo

验证以下输出。

Verify the following output.

swing button

SWING - Event Classes

事件类表示事件。Java 提供各种事件类,但仅讨论最常用的事件类。

Event classes represent the event. Java provides various Event classes, however, only those which are more frequently used will be discussed.

EventObject Class

它是所有事件状态对象派生的根类。所有事件均使用对对象的引用 source 构造,该对象在逻辑上被认为是事件最初发生的上的对象。此类在 java.util 包中定义。

It is the root class from which all event state objects shall be derived. All Events are constructed with a reference to the object, the source, that is logically deemed to be the object upon which the Event in question initially occurred upon. This class is defined in java.util package.

Class Declaration

以下是对 java.util.EventObject 类的声明 −

Following is the declaration for java.util.EventObject class −

public class EventObject
   extends Object
      implements Serializable

Field

以下是对 java.util.EventObject 类的字段 −

Following are the fields for java.util.EventObject class −

protected Object source − 事件最初发生的对象。

protected Object source − The object on which the Event initially occurred.

Class Constructors

Sr.No.

Constructor & Description

1

EventObject(Object source) Constructs a prototypical Event.

Class Methods

Sr.No.

Method & Description

1

Object getSource() The object on which the Event initially occurred.

2

String toString() Returns a String representation of this EventObject.

Methods Inherited

此类从以下类继承方法 −

This class inherits methods from the following class −

  1. java.lang.Object

SWING Event Classes

以下是常用事件类的列表。

Following is the list of commonly used Event classes.

Sr.No.

Class & Description

1

AWTEventIt is the root event class for all SWING events. This class and its subclasses supercede the original java.awt.Event class.

2

ActionEventThe ActionEvent is generated when the button is clicked or the item of a list is double-clicked.

3

InputEventThe InputEvent class is the root event class for all component-level input events.

4

KeyEventOn entering the character the Key event is generated.

5

MouseEventThis event indicates a mouse action occurred in a component.

6

WindowEventThe object of this class represents the change in the state of a window.

7

AdjustmentEventThe object of this class represents the adjustment event emitted by Adjustable objects.

8

ComponentEventThe object of this class represents the change in the state of a window.

9

ContainerEventThe object of this class represents the change in the state of a window.

10

MouseMotionEventThe object of this class represents the change in the state of a window.

11

PaintEventThe object of this class represents the change in the state of a window.

SWING - Event Listeners

事件侦听器表示负责处理事件的接口。Java 提供各种事件侦听器类,但我们只讨论使用最频繁的那些类。每个事件侦听器方法的一个方法只有一个参数,该参数是一个对象,它是 EventObject 类的子类。例如,鼠标事件侦听器方法接受 MouseEvent 的实例,其中 MouseEvent 派生自 EventObject。

Event listeners represent the interfaces responsible to handle events. Java provides various Event listener classes, however, only those which are more frequently used will be discussed. Every method of an event listener method has a single argument as an object which is the subclass of EventObject class. For example, mouse event listener methods will accept instance of MouseEvent, where MouseEvent derives from EventObject.

EventListner Interface

它是一个标记接口,每个侦听器接口都必须扩展它。此类在 java.util 中定义。

It is a marker interface which every listener interface has to extend. This class is defined in java.util package.

Class Declaration

以下是 java.util.EventListener 接口的声明 −

Following is the declaration for java.util.EventListener interface −

public interface EventListener

SWING Event Listener Interfaces

以下是常用事件侦听器的列表。

Following is the list of commonly used event listeners.

Sr.No.

Class & Description

1

ActionListenerThis interface is used for receiving the action events.

2

ComponentListenerThis interface is used for receiving the component events.

3

ItemListenerThis interface is used for receiving the item events.

4

KeyListenerThis interface is used for receiving the key events.

5

MouseListenerThis interface is used for receiving the mouse events.

6

WindowListenerThis interface is used for receiving the window events.

7

AdjustmentListenerThis interface is used for receiving the adjustment events.

8

ContainerListenerThis interface is used for receiving the container events.

9

MouseMotionListenerThis interface is used for receiving the mouse motion events.

10

FocusListenerThis interface is used for receiving the focus events.

SWING - Event Adapters

适配器是接收各种事件的抽象类。这些类中的方法为空。这些类作为创建侦听器对象的一种方便方式而存在。

Adapters are abstract classes for receiving various events. The methods in these classes are empty. These classes exist as convenience for creating listener objects.

SWING Adapters

以下列出了 SWING 中用于侦听 GUI 事件的常见适配器列表。

Following is the list of commonly used adapters while listening GUI events in SWING.

Sr.No.

Adapter & Description

1

FocusAdapterAn abstract adapter class for receiving focus events.

2

KeyAdapterAn abstract adapter class for receiving key events.

3

MouseAdapterAn abstract adapter class for receiving mouse events.

4

MouseMotionAdapterAn abstract adapter class for receiving mouse motion events.

5

WindowAdapterAn abstract adapter class for receiving window events.

SWING - Layouts

布局是指容器内组件的排列。从另一个角度来说,也可以说布局是在容器内将组件放置在特定位置。放置控件的任务由布局管理器自动完成。

Layout refers to the arrangement of components within the container. In another way, it could be said that layout is placing the components at a particular position within the container. The task of laying out the controls is done automatically by the Layout Manager.

Layout Manager

布局管理器自动定位容器内的所有组件。即使您不使用布局管理器,组件仍然会由默认布局管理器定位。动手放置控件是可能的,但是由于以下两个原因,这变得非常困难。

The layout manager automatically positions all the components within the container. Even if you do not use the layout manager, the components are still positioned by the default layout manager. It is possible to lay out the controls by hand, however, it becomes very difficult because of the following two reasons.

  1. It is very tedious to handle a large number of controls within the container.

  2. Usually, the width and height information of a component is not given when we need to arrange them.

Java 提供了各种布局管理器来定位控件。诸如大小、形状和排列之类的属性在不同的布局管理器之间各不相同。当 applet 或应用程序窗口的大小改变时,组件的大小、形状和排列也会相应地改变,即布局管理器适应 applet 查看器或应用程序窗口的尺寸。

Java provides various layout managers to position the controls. Properties like size, shape, and arrangement varies from one layout manager to the other. When the size of the applet or the application window changes, the size, shape, and arrangement of the components also changes in response, i.e. the layout managers adapt to the dimensions of the appletviewer or the application window.

布局管理器与容器对象相关联。每个布局管理器都是实现 LayoutManager 接口的类的对象。

The layout manager is associated with every Container object. Each layout manager is an object of the class that implements the LayoutManager interface.

以下是定义布局管理器功能的接口。

Following are the interfaces defining the functionalities of Layout Managers.

Sr.No.

Interface & Description

1

LayoutManagerThe LayoutManager interface declares those methods which need to be implemented by the class, whose object will act as a layout manager.

2

LayoutManager2The LayoutManager2 is the sub-interface of the LayoutManager. This interface is for those classes that know how to layout containers based on layout constraint object.

AWT Layout Manager Classes

以下是使用 AWT 设计 GUI 时常用的控件列表。

Following is the list of commonly used controls while designing GUI using AWT.

Sr.No.

LayoutManager & Description

1

BorderLayoutThe borderlayout arranges the components to fit in the five regions: east, west, north, south, and center.

2

CardLayoutThe CardLayout object treats each component in the container as a card. Only one card is visible at a time.

3

FlowLayoutThe FlowLayout is the default layout. It layout the components in a directional flow.

4

GridLayoutThe GridLayout manages the components in the form of a rectangular grid.

5

GridBagLayoutThis is the most flexible layout manager class. The object of GridBagLayout aligns the component vertically, horizontally, or along their baseline without requiring the components of the same size.

6

GroupLayoutThe GroupLayout hierarchically groups the components in order to position them in a Container.

7

SpringLayoutA SpringLayout positions the children of its associated container according to a set of constraints.

SWING - Menu Classes

众所周知,每个顶级窗口都与它关联有一个菜单栏。此菜单栏由最终用户使用的各种菜单选项组成。此外,每个选项都包含一个称为下拉菜单的列表。菜单和 MenuItem 控件是 MenuComponent 类的子类。

As we know that every top-level window has a menu bar associated with it. This menu bar consists of various menu choices available to the end user. Further, each choice contains a list of options, which is called drop-down menus. Menu and MenuItem controls are subclass of MenuComponent class.

Menu Hierarchy

swing menuhiearchy

Menu Controls

Sr.No.

Class & Description

1

JMenuBarThe JMenuBar object is associated with the top-level window.

2

JMenuItemThe items in the menu must belong to the JMenuItem or any of its subclass.

3

JMenuThe JMenu object is a pull-down menu component which is displayed from the menu bar.

4

JCheckboxMenuItemJCheckboxMenuItem is the subclass of JMenuItem.

5

JRadioButtonMenuItemJRadioButtonMenuItem is the subclass of JMenuItem.

6

JPopupMenuJPopupMenu can be dynamically popped up at a specified position within a component.

SWING - Containers

容器是 SWING GUI 组件的组成部分。容器提供了放置组件的空间。AWT 中的 Container 本身就是一个组件,它提供了将组件添加到自身的特性。以下是需要考虑的部分注意事项。

Containers are an integral part of SWING GUI components. A container provides a space where a component can be located. A Container in AWT is a component itself and it provides the capability to add a component to itself. Following are certain noticable points to be considered.

  1. Sub classes of Container are called as Container. For example, JPanel, JFrame and JWindow.

  2. Container can add only a Component to itself.

  3. A default layout is present in each container which can be overridden using setLayout method.

SWING Containers

以下是使用 SWING 设计 GUI 时常用容器的列表。

Following is the list of commonly used containers while designed GUI using SWING.

Sr.No.

Container & Description

1

PanelJPanel is the simplest container. It provides space in which any other component can be placed, including other panels.

2

FrameA JFrame is a top-level window with a title and a border.

3

WindowA JWindow object is a top-level window with no borders and no menubar.