Java How to Program学习笔记_章节小结——第十二章_GUI组件——第一部分(GUI Components: Part 1)

这章的内容挺多的。

Summary

Section 12.1 Introduction

• A graphical user interface (GUI) presents a user-friendly mechanism for interacting with an application. A GUI gives an application a distinctive look-and-feel.

• Providing different applications with consistent, intuitive user-interface components gives users a sense of familarity with a new application, so that they can learn it more quickly.

• GUIs are built from GUI components —sometimes called controls or widgets.

Section 12.2 Java’s Nimbus Look-and-Feel

• As of Java SE 6 update 10, Java comes bundled with a new, elegant, cross-platform look-and-feel known as Nimbus.

• To set Nimbus as the default for all Java applications, create a swing.properties text file in the lib folder of your JDK and JRE installation folders. Place the following line of code in the file:

swing.defaultlaf=com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel

• To select Nimbus on an application-by-application basis, place the following command-line argument after the java command and before the application’s name when you run the application:

-Dswing.defaultlaf=com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel

Section 12.3 Simple GUI-Based Input/Output with JOptionPane

• Most applications use windows or dialog boxes to interact with the user.

• Class JOptionPane of package javax.swing provides prebuilt dialog boxes for both input and output. JOptionPane static method showInputDialog displays an input dialog.

• A prompt typically uses sentence-style capitalization—capitalizing only the first letter of the first word in the text unless the word is a proper noun.

• An input dialog can input only input Strings. This is typical of most GUI components.

JOptionPane static method showMessageDialog displays a message dialog.

Section 12.4 Overview of Swing Components

• Most Swing GUI components are located in package javax.swing.

• Together, the appearance and the way in which the user interacts with the application are known as that application’s look-and-feel. Swing GUI components allow you to specify a uniform look-and-feel for your application across all platforms or to use each platform’s custom look-and-feel.

• Lightweight Swing components are not tied to actual GUI components supported by the underlying platform on which an application executes.

• Several Swing components are heavyweight components that require direct interaction with the local windowing system , which may restrict their appearance and functionality.

• Class Component of package java.awt declares many of the attributes and behaviors common to the GUI components in packages java.awt and javax.swing.

• Class Container of package java.awt is a subclass of Component. Components are attached to Containers so the Components can be organized and displayed on the screen.

• Class JComponent of package javax.swing is a subclass of Container. JComponent is the superclass of all lightweight Swing components and declares their common attributes and behaviors.

• Some common JComponent features include a pluggable look-and-feel, shortcut keys called mnemonics, tool tips , support for assistive technologies and support for user-interface localization.

Section 12.5 Displaying Text and Images in a Window

• Class JFrame provides the basic attributes and behaviors of a window.

• A JLabel displays read-only text, an image, or both text and an image. Text in a JLabel normally uses sentence-style capitalization.

• Each GUI component must be attached to a container, such as a window created with a JFrame.

• Many IDEs provide GUI design tools in which you can specify the exact size and location of a component by using the mouse; then the IDE will generate the GUI code for you.

JComponent method setToolTipText specifies the tool tip that’s displayed when the user positions the mouse cursor over a lightweight component.

Container method add attaches a GUI component to a Container.

• Class ImageIcon supports several image formats, including GIF, PNG and JPEG.

• Method getClass of class Object retrieves a reference to the Class object that represents the the class declaration for the object on which the method is called.

Class method getResource returns the location of its argument as a URL. The method getResource uses the Class object’s class loader to determine the location of the resource.

• The horizontal and vertical alignments of a JLabel can be set with methods setHorizontalAlignment and setVerticalAlignment, respectively.

JLabel methods setText and getText set and get the text displayed on a label.

JLabel methods setIcon and getIcon set and get the Icon on a label.

JLabel methods setHorizontalTextPosition and setVerticalTextPosition specify the text position in the label.

JFrame method setDefaultCloseOperation with constant JFrame.EXIT_ON_CLOSE as the argument indicates that the program should terminate when the window is closed by the user.

Component method setSize specifies the width and height of a component.

Component method setVisible with the argument true displays a JFrame on the screen.

Section 12.6 Text Fields and an Introduction to Event Handling with Nested Classes

• GUIs are event driven—when the user interacts with a GUI component, events drive the program to perform tasks.

• An event handler performs a task in response to an event.

• Class JTextField extends JTextComponent of package javax.swing.text, which provides common text-based component features. Class JPasswordField extends JTextField and adds several methods that are specific to processing passwords.

• A JPasswordField shows that characters are being typed as the user enters them, but hides the actual characters with echo characters.

• A component receives the focus when the user clicks the component.

JTextComponent method setEditable can be used to make a text field uneditable.

• To respond to an event for a particular GUI component, you must create a class that represents the event handler and implements an appropriate event-listener interface, then register an object of the event-handling class as the event handler.

Non-static nested classes are called inner classes and are frequently used for event handling.

• An object of a non-static inner class must be created by an object of the top-level class that contains the inner class.

• An inner-class object can directly access the instance variables and methods of its top-level class.

• A nested class that’s static does not require an object of its top-level class and does not implicitly have a reference to an object of the top-level class.

Pressing Enter in a JTextField or JPasswordField generates an ActionEvent that can be handled by an ActionListener of package java.awt.event.

JTextField method addActionListener registers an event handler for a text field’s ActionEvent.

• The GUI component with which the user interacts is the event source.

• An ActionEvent object contains information about the event that just occurred, such as the event source and the text in the text field.

ActionEvent method getSource returns a reference to the event source. ActionEvent method getActionCommand returns the text the user typed in a text field or the label on a JButton.

JPasswordField method getPassword returns the password the user typed.

Section 12.7 Common GUI Event Types and Listener Interfaces

• Each event-object type typically has a corresponding event-listener interface that specifies one or more event-handling methods, which must be declared in the class that implements the interface.

Section 12.8 How Event Handling Works

• When an event occurs, the GUI component with which the user interacted notifies its registered listeners by calling each listener’s appropriate event-handling method.

• Every GUI component supports several event types. When an event occurs, the event is dispatched only to the event listeners of the appropriate type.

Section 12.9 JButton

• A button is a component the user clicks to trigger an action. All the button types are subclasses of AbstractButton. Button labels typically use book-title capitalization.

• Command buttons are created with class JButton.

• A JButton can display an Icon. A JButton can also have a rollover Icon —an Icon that’s displayed when the user positions the mouse over the button.

• Method setRolloverIcon of class AbstractButton specifies the image displayed on a button when the user positions the mouse over it.

Section 12.10 Buttons That Maintain State

• There are three Swing state button typesJToggleButton , JCheckBox and JRadioButton.

• Classes JCheckBox and JRadioButton are subclasses of JToggleButton.

Component method setFont sets the component’s font to a new Font object of package java.awt.

• Clicking a JCheckBox causes an ItemEvent that can be handled by an ItemListener which defines method itemStateChanged. Method addItemListener registers the listener for the ItemEvent of a JCheckBox or JRadioButton object.

JCheckBox method isSelected determines whether a JCheckBox is selected.

JRadioButtons have two states—selected and not selected. Radio buttons normally appear as a group in which only one button can be selected at a time.

JRadioButtons are used to represent mutually exclusive options.

• The logical relationship between JRadioButtons is maintained by a ButtonGroup object.

ButtonGroup method add associates each JRadioButton with a ButtonGroup. If more than one selected JRadioButton object is added to a group, the selected one that was added first will be selected when the GUI is displayed.

JRadioButtons generate ItemEvents when they’re clicked.

Section 12.11 JComboBox; Using an Anonymous Inner Class for Event Handling

• A JComboBox provides a list of items from which the user can make a single selection. JComboBoxes generate ItemEvents.

• Each item in a JComboBox has an index. The first item added to a JComboBox appears as the currently selected item when the JComboBox is displayed.

JComboBox method setMaximumRowCount sets the maximum number of elements that are displayed when the user clicks the JComboBox.

• An anonymous inner class is a class without a name and typically appears inside a method declaration. One object of the anonymous inner class must be created when the class is declared.

JComboBox method getSelectedIndex returns the index of the selected item.

Section 12.12 JList

• A JList displays a series of items from which the user may select one or more items. Class JList supports single-selection lists and multiple-selection lists.

• When the user clicks an item in a JList, a ListSelectionEvent occurs. JList method addListSelectionListener registers a ListSelectionListener for a JList’s selection events. A ListSelectionListener of package javax.swing.event must implement method valueChanged.

JList method setVisibleRowCount specifies the number of visible items in the list.

JList method setSelectionMode specifies a list’s selection mode.

• A JList can be attached to a JScrollPane to provide a scrollbar for the JList.

JFrame method getContentPane returns a reference to the JFrame’s content pane where GUI components are displayed.

JList method getSelectedIndex returns the selected item’s index.

Section 12.13 Multiple-Selection Lists

• A multiple-selection list enables the user to select many items from a JList.

JList method setFixedCellWidth sets a JList’s width. Method setFixedCellHeight sets the height of each item in a JList.

• Normally, an external event generated by another GUI component (such as a JButton) specifies when the multiple selections in a JList should be processed.

JList method setListData sets the items displayed in a JList. JList method getSelectedValues returns an array of Objects representing the selected items in a JList.

Section 12.14 Mouse Event Handling

• The MouseListener and MouseMotionListener event-listener interfaces are used to handle mouse events. Mouse events can be trapped for any GUI component that extends Component.

• Interface MouseInputListener of package javax.swing.event extends interfaces

MouseListener and MouseMotionListener to create a single interface containing all their methods.

• Each mouse event-handling method receives a MouseEvent object that contains information about the event, including the x- and y-coordinates where the event occurred. Coordinates are measured from the upper-left corner of the GUI component on which the event occurred.

• The methods and constants of class InputEvent enable an application to determine which mouse button the user clicked.

• Interface MouseWheelListener enables applications to respond to mouse-wheel events.

Section 12.15 Adapter Classes

• An adapter class implements an interface and provides default implementations of its methods. When you extend an adapter class, you can override just the method(s) you need.

MouseEvent method getClickCount returns the number of consecutive mouse-button clicks. Methods isMetaDown and isAltDown determine which button was clicked.

Section 12.16 JPanel Subclass for Drawing with the Mouse

JComponents method paintComponent is called when a lightweight Swing component is displayed. Override this method to specify how to draw shapes using Java’s graphics capabilities.

• When overriding paintComponent, call the superclass version as the first statement in the body.

• Subclasses of JComponent support transparency. When a component is opaque , paint-

Component clears its background before the component is displayed.

• The transparency of a Swing lightweight component can be set with method setOpaque.

• Class Point package java.awt represents an x-y coordinate.

• Class Graphics is used to draw.

MouseEvent method getPoint obtains the Point where a mouse event occurred.

• Method repaint, inherited indirectly from class Component, indicates that a component should be refreshed on the screen as soon as possible.

• Method paintComponent receives a Graphics parameter and is called automatically whenever a lightweight component needs to be displayed on the screen.

Graphics method fillOval draws a solid oval. The first two arguments are the upper-left x-y coordinate of the bounding box, and the last two are the bounding box’s width and height.

Section 12.17 Key Event Handling

• Interface KeyListener is used to handle key events that are generated when keys on the keyboard are pressed and released. Method addKeyListener of class Component registers a KeyListener.

KeyEvent method getKeyCode gets the virtual key code of the pressed key. Class KeyEvent contains virtual key-code constants that represent every key on the keyboard.

KeyEvent method getKeyText returns a string containing the name of the pressed key.

KeyEvent method getKeyChar gets the Unicode value of the character typed.

KeyEvent method isActionKey determines whether the key in an event was an action key.

InputEvent method getModifiers determines whether any modifier keys (such as Shift, Alt and Ctrl) were pressed when the key event occurred.

KeyEvent method getKeyModifiersText returns a string containing the pressed modifier keys.

Section 12.18 Introduction to Layout Managers

• Layout managers arrange GUI components in a container for presentation purposes.

• All layout managers implement the interface LayoutManager of package java.awt.

Container method setLayout specifies the layout of a container.

FlowLayout places components left to right in the order in which they’re added to the container. When the container’s edge is reached, components continue to display on the next line. FlowLayout allows GUI components to be left aligned, centered (the default) and right aligned.

FlowLayout method setAlignment changes the alignment for a FlowLayout.

BorderLayout the default for a JFrame) arranges components into five regions: NORTH, SOUTH, EAST, WEST and CENTER. NORTH corresponds to the top of the container.

• A BorderLayout limits a Container to containing at most five components—one in each region.

GridLayout divides a container into a grid of rows and columns.

Container method validate recomputes a container’s layout based on the current layout manager for the Container and the current set of displayed GUI components.

Section 12.19 Using Panels to Manage More Complex Layouts

• Complex GUIs often consist of multiple panels with different layouts. Every JPanel may have components, including other panels, attached to it with Container method add.

Section 12.20 JTextArea

• A JTextArea —a subclass of JTextComponent—may contain multiple lines of text.

• Class Box is a subclass of Container that uses a BoxLayout layout manager to arrange the GUI components either horizontally or vertically.

Box static method createHorizontalBox creates a Box that arranges components from left to right in the order that they’re attached.

• Method getSelectedText returns the selected text from a JTextArea.

• You can set the horizontal and vertical scrollbar policies of a JScrollPane when it’s constructed.

JScrollPane methods setHorizontalScrollBarPolicy and setVerticalScrollBarPolicy can be used to change the scrollbar policies at any time.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值