Вы находитесь на странице: 1из 44

Java Foundation Classes (JFC) The JFC isnt just a single component; its actually made up of the following

five different APIs: Abstract Windowing Toolkit (AWT) The original Java GUI component set. The Abstract Windowing Toolkit (AWT) provides basic facilities for creating graphical user interfaces (GUIs), and also for drawing graphics. AWT has been a core part of Java since Java 1.0. The GUI features of AWT are layered on top of the native GUI system of the underlying platform. In other words, when you create a graphical push button with AWT, AWT creates a Windows push button, or a Macintosh push button, or whatever, depending on the platform on which the application is running. Java 2D A set of classes for 2D graphics and imaging. Accessibility Designed to provide user interface assistance for people with disabilities. Includes screen magnifiers and audible text readers. Drag-and-Drop(DnD) DnD allows the user to click and hold a GUI object, move it to another window or frame. The DnD API allows users to implement droppable elements that transfer information between Java applications and between Java and native applications. Swing Swing is an advanced GUI toolkit written in pure Java. It is built upon the AWT but provides many new GUI components. Swing offers a pluggable look-and-feel architecture that allows an application to be configured either to display a platform-independent Java look-and-feel or to mimic the look-and-feel of the native operating system. Heavyweight and Lightweight Components: AWT components are called Heavyweight components. When instantiating any of the AWT component classes, e.g. a java.awt.Button, the system actually asks the native environment to create the component. The native code that provides this look-and-feel is called a peer; each platform has its own set of peers. A Java button appears and acts as a Windows button when run under Windows, as a Macintosh button when run under Macintosh, and as a Unix button when run under Unix. There are problems because not all native controls respond similarly to the same events. This can result in a Java program exhibiting different behavior under different Java AWT environments. To overcome this problem, we must use components written entirely in Java. That is, components that do not have a native peer. These are called lightweight components. Swing provides a set of pure Java lightweight components, ensuring better cross-platform compatibility. A lightweight component is one that subclasses java.awt.Component (or java.awt.Container) directly implementing the look-and-feel of the component in Java rather than delegating the look-and-feel to a native peer. Lightweight components can be more efficient at utilizing system resource, they can be transparent, and they do not have to be rectangular (all of which are limitations when working with components that have a peer). A Visual Index of the Swing Components: Top-Level Containers The components at the top of any Swing containment hierarchy.

Applet Frame Dialog General-Purpose Containers Intermediate containers that can be used under many different circumstances.

Panel

Scroll pane

Tabbed pane

Split pane

Tool bar Special-Purpose Containers Intermediate containers that play specific roles in the UI.

Internal frame Layered pane

Root pane Basic Controls Atomic components that exist primarily to get input from the user; they generally also show simple state.

List Buttons Combo box

Slider

Menu

Spinner

Text field or Formatted text field

Uneditable Information Displays Atomic components that exist solely to give the user information.

Progress bar

Tool tip Label Interactive Displays of Highly Formatted Information Atomic components that display highly formatted information that (if you choose) can be modified by the user.

Color chooser

File chooser

Table Text Tree

Swing's Component Hierarchy

The Swing components have similar names as the AWT components but begin with J.

Class JFrame java.lang.Object | +--java.awt.Component | +--java.awt.Container | +--java.awt.Window | +--java.awt.Frame | +--javax.swing.JFrame An extended version of java.awt.Frame that adds support for the JFC/Swing component architecture. Like all other JFC/Swing top-level containers, a JFrame contains a JRootPane as its only child. The content pane provided by the root pane should, as a rule, contain all the non-menu components displayed by the JFrame. This is different from the AWT Frame case. For example, to add a child to an AWT frame you'd write:

frame.add(child); However using JFrame you need to add the child to the JFrame's content pane instead: frame.getContentPane().add(child); The same is true for setting layout managers, removing components, listing children, and so on. All these methods should normally be sent to the content pane instead of the JFrame itself. The content pane will always be non-null. Attempting to set it to null will cause the JFrame to throw an exception. The default content pane will have a BorderLayout manager set on it. Unlike a Frame, a JFrame has some notion of how to respond when the user attempts to close the window. The default behavior is to simply hide the JFrame when the user closes the window. To change the default behavior, you invoke the method setDefaultCloseOperation(int). To make the JFrame behave the same as a Frame instance, use setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE).

Constructor Summary JFrame() Constructs a new frame that is initially invisible. JFrame(String title) Creates a new, initially invisible Frame with the specified title. The Root Pane java.lang.Object |

+--java.awt.Component | +--java.awt.Container | +--javax.swing.JComponent | +--javax.swing.JRootPane Swing provides three generally useful top-level container classes: JFrame, JDialog, and JApplet. Each top-level container has a content pane that contains the components. We can optionally add a menu bar to a top-level container. The menu bar is by convention positioned within the top-level container, but outside the content pane. Each top-level container relies on an intermediate container called the root pane that is represented by the class JRootPane. The root pane manages the content pane and the menu bar, along with a couple of other containers. We generally don't need to know about root panes to use Swing components. However, if we ever need to intercept mouse clicks or paint over multiple components, we should get acquainted with root panes. Here's a glimpse at the components that a root pane provides to a frame (and to every other toplevel container):

As the preceding figure shows, a root pane has four parts: The glass pane Hidden, by default. If you make the glass pane visible, then it's like a sheet of glass over all the other parts of the root pane. It's completely transparent unless we implement the glass pane's paintComponent() method so that it does something, and it intercepts input events for the root pane. The layered pane Serves to position its contents, which consist of the content pane and the optional menu bar. Can also hold other components in a specified Z order. The content pane The container of the root pane's visible components, excluding the menu bar. The optional menu bar The home for the root pane's container's menus. If the container has a menu bar, we generally use the container's setJMenuBar() method to put the menu bar in the appropriate place. To add components to the JRootPane (other than the optional menu bar), we add the object to the contentPane of the JRootPane, like this: rootPane.getContentPane().add(child);

The same principle holds true for setting layout managers, removing components, listing children, etc. All these methods are invoked on the contentPane instead of on the JRootPane. The Glass Pane GlassPane is the topmost component of all the components in the JRootPane and fills the entire viewable area of the JRootPane. It is like a glass sheet over all the components in the JRootPane. It is by default made invisible. But once it is made visible, it can be used for drawing above all the components and intercept mouse events over multiple components in the JRootPane. Here's a picture of an application that demonstrates glass pane features. It contains a check box that lets us set whether the glass pane is "visible" whether it can get events and paint itself onscreen. When the glass pane is visible, it blocks all input events from reaching the components in the content pane. It also paints a red dot in the place where it last detected a mouse-pressed event.

We can make a glass pane visible by invoking the method setVisible(true) on a glass pane object. A reference to a glass pane object is obtained by invoking the method getGlassPane() on a container.

The Layered Pane java.lang.Object | +--java.awt.Component | +--java.awt.Container | +--javax.swing.JComponent | +--javax.swing.JLayeredPane JLayeredPane adds depth to a JFC/Swing container, allowing components to overlap each other when needed. A layered pane is a Swing container that provides a third dimension for positioning components: depth, also known as Z order. Every Swing container that has a root pane such as JFrame, JApplet, JDialog, or JInternalFrame automatically has a layered pane. Swing provides two layered pane classes. The first, JLayeredPane, is the class that root panes use. The second, JDesktopPane, is a JLayeredPane subclass that's specialized for the task of holding internal frames. JLayeredPane divides the depth-range into several different layers.

Putting a component into one of those layers makes it easy to ensure that components overlap properly, without having to worry about specifying numbers for specific depths:

DEFAULT_LAYER The standard layer, where most components go. This is the bottommost layer. The depth is specified by the object new Integer(0) PALETTE_LAYER The palette layer sits over the default layer. Useful for floating toolbars and palettes, so they can be positioned above other components. The depth is specified by the object new Integer(100) MODAL_LAYER The layer used for modal dialogs. They will appear on top of any toolbars, palettes, or standard components in the container. The depth is specified by the object new Integer(200) POPUP_LAYER The popup layer displays above dialogs. That way, the popup windows associated with combo boxes, tooltips, and other help text will appear above the component, palette, or dialog that generated them. The depth is specified by the object new Integer(300) DRAG_LAYER When dragging a component, reassigning it to the drag layer ensures that it is positioned over every other component in the container. When finished dragging, it can be reassigned to its normal layer. The depth is specified by the object new Integer(400) In addition to these layers, there is a special layer called the frame-content layer to position the content pane and the optional menubar of the root pane. This layer is specified by the static constant FRAME_CONTENT _LAYER, which has the value new Integer(-30000) The JLayeredPane methods moveToFront(Component), moveToBack(Component) and setPosition can be used to reposition a component within its layer. The setLayer method can also be used to change the component's current layer. The Content Pane The content pane actually sits on one of the layers of the layered pane specified by the layered pane constant FRAME_CONTENT_LAYER. The following is the code used to add a component to a content pane with a specific layout: Container contentPane = swingContainer.getContentPane(); contentPane.setLayout(new SomeLayout());

contentPane.add(new SomeComponent()); By default, the content pane is set to the BorderLayout Manager.

Class JLabel java.lang.Object | +--java.awt.Component | +--java.awt.Container | +--javax.swing.JComponent | +--javax.swing.JLabel A JLabel object can display either text, an image, or both. We can specify where in the label's display area the label's contents are aligned by setting alignment. By default, labels are vertically centered in their display area. We can use the setIconTextGap method to specify how many pixels should appear between the text and the image. The default is 4 pixels.

Constructor Summary JLabel() Creates a JLabel instance with no image and with an empty string for the title. JLabel(Icon image) Creates a JLabel instance with the specified image. JLabel(Icon image, int horizontalAlignment) Creates a JLabel instance with the specified image and horizontal alignment. JLabel(String text) Creates a JLabel instance with the specified text. JLabel(String text, Icon icon, int horizontalAlignment) Creates a JLabel instance with the specified text, image, and horizontal alignment. JLabel(String text, int horizontalAlignment) Creates a JLabel instance with the specified text and horizontal alignment. import java.awt.*; import javax.swing.*; /* <applet code="JLabelDemo" width=250 height=150> </applet> */ public class JLabelDemo extends JApplet { public void init() { // Get content pane Container contentPane = getContentPane(); // Create an icon ImageIcon ii = new ImageIcon("BGLEFTUP.GIF");

// Create a label JLabel jl = new JLabel("France", ii, JLabel.CENTER); // Add label to the content pane contentPane.add(jl); } } Class JTextField java.lang.Object | +--java.awt.Component | +--java.awt.Container | +--javax.swing.JComponent | +--javax.swing.text.JTextComponent | +--javax.swing.JTextField JTextField allows the editing of a single line of text. A text field is a basic text control that lets the user enter a small amount of text. When the user indicates that text entry is complete (usually by pressing Enter), the text field fires an action event. To provide password-like services a separate class JPasswordField extends JTextField is used

Constructor Summary JTextField() Constructs a new TextField. JTextField(int columns) Constructs a new empty TextField with the specified number of columns. JTextField(String text) Constructs a new TextField initialized with the specified text. JTextField(String text, int columns) Constructs a new TextField initialized with the specified text and columns. import java.awt.*; import javax.swing.*; /* <applet code="JTextFieldDemo" width=300 height=50> </applet> */ public class JTextFieldDemo extends JApplet { JTextField jtf; public void init() {

// Get content pane Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); // Add text field to content pane jtf = new JTextField(15); contentPane.add(jtf); } } // MnemonicLabels.java import javax.swing.*; import java.awt.*; public class MnemonicLabels { public static void main(String[] args) { JTextField firstField = new JTextField(10); JTextField middleField = new JTextField(10); JTextField lastField = new JTextField(10); // Create labels and mnemonics JLabel firstLabel = new JLabel("First Name", JLabel.RIGHT); firstLabel.setDisplayedMnemonic('F'); firstLabel.setLabelFor(firstField); JLabel lastLabel = new JLabel("Last Name", JLabel.RIGHT); lastLabel.setDisplayedMnemonic('L'); lastLabel.setLabelFor(lastField); // Layout and Display JPanel p = new JPanel(); p.setLayout(new GridLayout(2, 2, 5, 5)); p.add(firstLabel); p.add(firstField); p.add(lastLabel); p.add(lastField); JFrame f = new JFrame("MnemonicLabels"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setContentPane(p); f.setSize(200,200); f.setVisible(true); } } Class JButton java.lang.Object | +--java.awt.Component | +--java.awt.Container |

+--javax.swing.JComponent | +--javax.swing.AbstractButton | +--javax.swing.JButton Constructor Summary JButton() Creates a button with no set text or icon. JButton(Icon icon) Creates a button with an icon. JButton(String text) Creates a button with text. JButton(String text, Icon icon) Creates a button with initial text and an icon. import java.awt.event.*; import javax.swing.*; /* <applet code="JButtonDemoApplet" width=250 height=300> </applet> */ public class JButtonDemoApplet extends JApplet implements ActionListener { JTextField jtf; public void init() { // Get content pane Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); // Add buttons to content pane ImageIcon previous = new ImageIcon("previous.GIF"); JButton jb = new JButton(previous); jb.setActionCommand("Previous Button Clicked"); jb.addActionListener(this); contentPane.add(jb); ImageIcon next = new ImageIcon("next.GIF"); jb = new JButton(next); jb.setActionCommand("Next Button Clicked"); jb.addActionListener(this); contentPane.add(jb); // Add text field to content pane jtf = new JTextField(15); contentPane.add(jtf); } public void actionPerformed(ActionEvent ae) { jtf.setText(ae.getActionCommand());

} } Class JToggleButton java.lang.Object | +--java.awt.Component | +--java.awt.Container | +--javax.swing.JComponent | +--javax.swing.AbstractButton | +--javax.swing.JToggleButton An implementation of a two-state button. When a toggle button is pushed-in, its view remains in the pushed-in condition until it is pressed again to pop-out. The JRadioButton and JCheckBox classes are subclasses of this class. Constructor Summary JToggleButton() Creates an initially unselected toggle button without setting the text or image. JToggleButton(Icon icon) Creates an initially unselected toggle button with the specified image but no text. JToggleButton(Icon icon, boolean selected) Creates a toggle button with the specified image and selection state, but no text. JToggleButton(String text) Creates an unselected toggle button with the specified text. JToggleButton(String text, boolean selected) Creates a toggle button with the specified text and selection state. JToggleButton(String text, Icon icon) Creates a toggle button that has the specified text and image, and that is initially unselected. JToggleButton(String text, Icon icon, boolean selected) Creates a toggle button with the specified text, image, and selection state. // JToggleButtonEvents.java // The event demonstration program for JToggleButton. import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; public class JToggleButtonEvents { public static void main(String[] args) { JToggleButton jtb = new JToggleButton("Press Me"); jtb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) {

System.out.println("ActionEvent!"); } }); JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container c = f.getContentPane(); c.setLayout(new FlowLayout()); c.add(jtb); f.setSize(200,100); f.setVisible(true); } } Class JCheckBox java.lang.Object | +--java.awt.Component | +--java.awt.Container | +--javax.swing.JComponent | +--javax.swing.AbstractButton | +--javax.swing.JToggleButton | +--javax.swing.JCheckBox An implementation of a check box -- an item that can be selected or deselected, and which displays its state to the user. By convention, any number of check boxes in a group can be selected. Constructor Summary JCheckBox() Creates an initially unselected check box button with no text, no icon. JCheckBox(Icon icon) Creates an initially unselected check box with an icon. JCheckBox(Icon icon, boolean selected) Creates a check box with an icon and specifies whether or not it is initially selected. JCheckBox(String text) Creates an initially unselected check box with text. JCheckBox(String text, boolean selected) Creates a check box with text and specifies whether or not it is initially selected. JCheckBox(String text, Icon icon) Creates an initially unselected check box with the specified text and icon. JCheckBox(String text, Icon icon, boolean selected) Creates a check box with text and icon, and specifies whether or not it is initially selected. import java.awt.*; import java.awt.event.*; import javax.swing.*;

/* <applet code="JCheckBoxDemo" width=400 height=50> </applet> */ public class JCheckBoxDemo extends JApplet implements ItemListener { JTextField jtf; public void init() { // Get content pane Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); // Create icons ImageIcon normal = new ImageIcon("yellow.gif"); ImageIcon rollover = new ImageIcon("blue.gif"); ImageIcon selected = new ImageIcon("click.gif"); // Add check boxes to the content pane JCheckBox cb = new JCheckBox("C", normal); cb.setRolloverIcon(rollover); cb.setSelectedIcon(selected); cb.addItemListener(this); contentPane.add(cb); cb = new JCheckBox("Java", normal); cb.setRolloverIcon(rollover); cb.setSelectedIcon(selected); cb.addItemListener(this); contentPane.add(cb); // Add text field to the content pane jtf = new JTextField(15); contentPane.add(jtf); } public void itemStateChanged(ItemEvent ie) { JCheckBox cb = (JCheckBox)ie.getItem(); jtf.setText(cb.getText()); } } Class JRadioButton java.lang.Object | +--java.awt.Component | +--java.awt.Container | +--javax.swing.JComponent | +--javax.swing.AbstractButton |

+--javax.swing.JToggleButton | +--javax.swing.JRadioButton An implementation of a radio button -- an item that can be selected or deselected, and which displays its state to the user. Used with a ButtonGroup object to create a group of buttons in which only one button at a time can be selected. (Create a ButtonGroup object and use its add method to include the JRadioButton objects in the group.)

Constructor Summary JRadioButton() Creates an initially unselected radio button with no set text. JRadioButton(Icon icon) Creates an initially unselected radio button with the specified image but no text. JRadioButton(Icon icon, boolean selected) Creates a radio button with the specified image and selection state, but no text. JRadioButton(String text) Creates an unselected radio button with the specified text. JRadioButton(String text, boolean selected) Creates a radio button with the specified text and selection state. JRadioButton(String text, Icon icon) Creates a radio button that has the specified text and image, and that is initially unselected. JRadioButton(String text, Icon icon, boolean selected) Creates a radio button that has the specified text, image, and selection state. import java.awt.*; import java.awt.event.*; import javax.swing.*; /* <applet code="JRadioButtonDemo" width=300 height=50> </applet> */ public class JRadioButtonDemo extends JApplet implements ActionListener { JTextField tf; public void init() { // Get content pane Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); // Add radio buttons to content pane JRadioButton b1 = new JRadioButton("A"); b1.addActionListener(this); contentPane.add(b1); JRadioButton b2 = new JRadioButton("B"); b2.addActionListener(this);

contentPane.add(b2); // Define a button group ButtonGroup bg = new ButtonGroup(); bg.add(b1); bg.add(b2); // Create a text field and add it // to the content pane tf = new JTextField(5); contentPane.add(tf); } public void actionPerformed(ActionEvent ae) { tf.setText(ae.getActionCommand()); } } Class JComboBox java.lang.Object | +--java.awt.Component | +--java.awt.Container | +--javax.swing.JComponent | +--javax.swing.JComboBox A component that combines a button or editable field and a drop-down list. The user can select a value from the drop-down list, which appears at the user's request. If we make the combo box editable, then the combo box includes an editable field into which the user can type a value.

Constructor Summary JComboBox() Creates a JComboBox with a default data model. JComboBox(Object[] items) Creates a JComboBox that contains the elements in the specified array. JComboBox(Vector items) Creates a JComboBox that contains the elements in the specified Vector. import java.awt.*; import java.awt.event.*; import javax.swing.*; /* <applet code="JComboBoxDemo" width=300 height=100> </applet> */ public class JComboBoxDemo extends JApplet implements ItemListener {

JLabel jl; ImageIcon india, germany, italy, japan; public void init() { // Get content pane Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); // Create a combo box and add it // to the panel JComboBox jc = new JComboBox(); jc.addItem("India"); jc.addItem("Germany"); jc.addItemListener(this); contentPane.add(jc); // Create label jl = new JLabel(new ImageIcon("india.gif")); contentPane.add(jl); } public void itemStateChanged(ItemEvent ie) { String s = (String)ie.getItem(); jl.setIcon(new ImageIcon(s + ".gif")); } } Pluggable Look-and-Feel One of the unique features of Swing is its pluggable look-and-feel (PLAF) architecture, which allows a Swing application to change its entire appearance without restarting it. The most common use of this feature is to give applications a choice between the native platform look-and-feel and a new platform-independent Java look-and-feel (also known as the Metal look-andfeel). Swing is distributed with three look-and-feels: Metal and two look-and-feels that mimic the appearance and behavior of the Windows and Motif (Unix/X) component toolkits. A look-and-feel that mimics the Macintosh platform is available as a separate download. While the Metal and Motif look-and-feels can be freely used, the Windows look-and-feel is restricted for use only on Windows platform--for copyright reasons, it does not run on any other operating system. When a Swing application starts up, it reads the system property swing.defaultlaf to determine the classname of the default look-and-feel. In most Java installations, this property is set to the default Java look-and-feel, implemented by the class javax.swing.plaf.metal.MetalLookAndFeel.

To explicitly set the look-and-feel of a Swing Application, simply call the static setLookAndFeel() method of the UIManager class and specify the classname of the desired look-and-feel implementation.

To

make

existing

components

reflect

the

new

look

and

feel,

invoke

the

updateComponentTreeUI method of SwingUtilities class once per top-level container. Example: Open the file Pluggable_Look_And_Feel.java Output when Metal button is clicked

Output when Motif button is clicked

Output when Windows button is clicked

Class JScrollBar java.lang.Object | +--java.awt.Component | +--java.awt.Container | +--javax.swing.JComponent | +--javax.swing.JScrollBar

Constructor Summary The most commonly used constructor is: JScrollBar(int orientation, int value, int extent, int min, int max) Creates a scrollbar with the specified orientation, value, extent, minimum, and maximum. orientation: specifies whether the scrollbar is horizontal or vertical. value: it is the initial value of the scrollbar extent: it is the visible extent or amount of the display area. minimum and maximum are the respective minimum and maximum values of the scrollbar. When a scrollbar is adjusted, it fires adjustment events that are objects of the event class A class that implements the interface AdjustmentListener receives these events. The event listener class is registered with the source scrollbar by invoking the method The method addAdjustmentListener() takes the listener object as its argument value.

AdjustmentEvent.

addAdjustmentListener() on the scrollbar object.

The listener class must implement the method adjustmentValueChanged() from the The code to be executed when the scrollbar is being adjusted is enclosed in this method. The method getValue() retrieves the current value in the adjustment event. Example: Open the file ScrollBarExample.java

interface, which takes the AdjustmentEvent object as its argument value.

Output:

Class JViewport java.lang.Object | +--java.awt.Component | +--java.awt.Container | +--javax.swing.JComponent | +--javax.swing.JViewport The JViewport provides a window, or "viewport" onto a data source -- for example, a text file or "porthole" through which we see the underlying information. That data source is the "scrollable client" (aka data model) displayed by the JViewport view. When we scroll, what moves is the viewport. It is like peering through a camera's viewfinder. Moving the viewfinder upwards brings new things into view at the top of the picture and loses things that were at the bottom. Class JScrollPane

java.lang.Object | +--java.awt.Component | +--java.awt.Container | +--javax.swing.JComponent | +--javax.swing.JScrollPane A scroll pane is used to display a child component with a built-in scrolling facility. The scrolling of a child component, when its size is larger than the available view port, is

performed in horizontal and vertical directions by using the scrollbars associated with the scroll pane. A JScrollPane manages a viewport, optional vertical and horizontal scroll bars, and optional A JScrollPane basically consists of JScrollBars, a JViewport, and the wiring between them, as row and column heading viewports. shown in the diagram at right.

In addition to the scroll bars and viewport, a JScrollPane can have a column header and a row header. Each of these is a JViewport object that you specify with setRowHeaderView, and setColumnHeaderView. The column header viewport automatically scrolls left and right, tracking the left-right scrolling of the main viewport.The row header acts in a similar fashion. By default, the corners are empty. You can put a component into a corner using setCorner() The size of corner components is entirely determined by the size of the headers and scroll bars that surround them.

Example: Open the file ScrollPaneDemo.java

Output:

Class JList java.lang.Object | +--java.awt.Component | +--java.awt.Container | +--javax.swing.JComponent | +--javax.swing.JList

A component that allows the user to select one or more objects from a list.

Constructor Summary JList() Constructs a JList with an empty model. JList(Object[] listData) Constructs a JList that displays the elements in the specified array. JList(Vector listData)

Constructs a JList that displays the elements in the specified Vector.

A separate model, ListModel, represents the contents of the list. It's easy to display an array or vector of objects, using a JList constructor that builds a ListModel instance for you: // Create a JList that displays the strings in data[] String[] data = {"one", "two", "three", "four"}; JList dataList = new JList(data);

The constructor with Vector argument can perform various operations, such as appending more items to the list, by using the functionality provided by java.util.Vector class. For example: Vector months = new Vector(); JList list = new JList(months); ... months.addElement(January); ... Months.addElement(December);

JList doesn't support scrolling directly. To create a scrolling list you make the JList the viewport view of a JScrollPane. For example: JScrollPane scrollPane = new JScrollPane(dataList); // Or in two steps: JScrollPane scrollPane = new JScrollPane(); scrollPane.getViewport().setView(dataList);

Example: Open the file ScrollList.java

Output:

Class Timer java.lang.Object | +--javax.swing.Timer

Constructor Summary Timer(int delay, ActionListener listener) Creates a Timer that will notify its listeners every delay milliseconds. Fires one or more action events after a specified delay. For example, an animation object can use a Timer as the trigger for drawing its frames. Setting up a timer involves creating a Timer object, registering one or more action listeners on it, and starting the timer using the start method. Each Timer has an action listener and a delay (the time between action events). When delay milliseconds have passed, the Timer fires an action event to its listeners. By default, this cycle repeats until the stop method is called. If you want the timer to fire only once, invoke setRepeats(false) on the timer. Example: Open the file ClockTest.java

Output:

Class JProgressBar java.lang.Object |

+--java.awt.Component | +--java.awt.Container | +--javax.swing.JComponent | +--javax.swing.JProgressBar A component that, by default, displays an integer value within a bounded interval. A progress bar typically communicates the progress of some work by displaying its percentage of completion and possibly a textual display of this percentage.

Constructor Summary JProgressBar() Creates a horizontal progress bar that displays a border but no progress string. JProgressBar(int orient) Creates a progress bar with the specified orientation, which can be either JProgressBar.VERTICAL or JProgressBar.HORIZONTAL. JProgressBar(int min, int max) Creates a horizontal progress bar with the specified minimum and maximum. JProgressBar(int orient, int min, int max) Creates a progress bar using the specified orientation, minimum, and maximum. Method void setValue(int) int getValue() double getPercentComplete() void setMinimum(int) int getMinimum() void setMaximum(int) int getMaximum() void setOrientation(int) int getOrientation() void setStringPainted(boolean) boolean isStringPainted() void setString(String) Set or get whether the progress bar displays a percent string. Set or get the percent string. Purpose Set or get the current value of the progress bar. The value is constrained by the minimum and maximum values. Get the percent complete for the progress bar. Set or get the minimum value of the progress bar. Set or get the maximum value of the progress bar. Set or get whether the progress bar is vertical or horizontal. Acceptable values are JProgressBar.VERTICAL or JProgressBar.HORIZONTAL.

String getString()

Example: Open the file Progress.java

Output:

Class JTabbedPane java.lang.Object | +--java.awt.Component | +--java.awt.Container | +--javax.swing.JComponent | +--javax.swing.JTabbedPane

With the JTabbedPane class, you can have several components (usually panels) share the same space. The user chooses which component to view by selecting the tab corresponding to the desired component. Tabs/components are added to a TabbedPane object by using the addTab and insertTab methods. A tab is represented by an index corresponding to the position it was added in, where the first tab has an index equal to 0 and the last tab has an index equal to the tab count minus 1.

Constructor Summary JTabbedPane() Creates an empty TabbedPane with a default tab placement of JTabbedPane.TOP JTabbedPane(int tabPlacement) Creates an empty TabbedPane with the specified tab placement of either: JTabbedPane.TOP, JTabbedPane.BOTTOM, JTabbedPane.LEFT, or JTabbedPane.RIGHT Method addTab(String, Icon, Component, String) addTab(String, Icon, Component) addTab(String, Component) Purpose Add a new tab to the tabbed pane. The first argument specifies the text on the tab. The optional icon argument specifies the tab's icon. The component argument specifies the component that the tabbed pane should show when the tab is selected. The fourth argument, if present, specifies the tool

insertTab(String, Icon, Component, String, int) remove(Component) removeTabAt(int) removeAll() int indexOfComponent(Component) int indexOfTab(String) int indexOfTab(Icon) void setSelectedIndex(int) void setSelectedComponent(Component) int getSelectedIndex() Component getSelectedComponent() void setComponentAt(int, Component) Component getComponentAt(int) void setToolTipTextAt(int, String) String getToolTipTextAt(int)

tip text for the tab. Insert a tab at the specified index, where the first tab is at index 0. The arguments are the same as for addTab. Remove the tab corresponding to the specified component or index. Remove all tabs. Return the index of the tab that has the specified component, title, or icon. Select the tab that has the specified component or index. Selecting a tab has the effect of displaying its associated component. Return the index or component for the selected tab. Set or get which component is associated with the tab at the specified index. The first tab is at index 0. Set or get the text displayed on tool tips for the specified tab.

Example: Open the file SimpleTab.java Output:

Menus A menu usually appears either in a menu bar or as a popup menu. A menu bar contains one or more menus. A popup menu is a menu that is invisible until the user makes a platform-specific mouse action, such as pressing the right mouse button, over a popup-enabled component. The popup menu then appears under the cursor.

The Menu Component Hierarchy Here is a picture of the inheritance hierarchy for the menu-related classes:

Menu items (including menus) are simply buttons. To bring up a popup menu (JPopupMenu), we must register a mouse listener on each component that the popup menu should be associated with. Mnemonics offer a way to use the keyboard to navigate the menu hierarchy, increasing the accessibility of programs. A mnemonic is a key that makes an already visible menu item be chosen by pressing the Underlined letter with Alt key. Creating and Setting Up Menu Bars

Constructor or Method JMenuBar() JMenu add(JMenu) void setJMenuBar(JMenuBar) JMenuBar getJMenuBar() (in JApplet, JDialog, JFrame, JInternalFrame, JRootPane)

Purpose Creates a menu bar. Appends the specified menu to the end of the menu bar. Sets or gets the menu bar of an applet, dialog, frame, internal frame, or root pane. Creating and Populating Menus

Constructor or Method JMenu() JMenu(String) JMenuItem add(JMenuItem) JMenuItem add(String) void addSeparator() JMenuItem insert(JMenuItem, int) void insert(String, int) void insertSeparator(int) void remove(JMenuItem) void remove(int)

Purpose Creates a menu. The string specifies the text to display for the menu. Adds a menu item to the current end of the menu. If the argument is a string, then the menu automatically creates a JMenuItem object that displays the specified text. Adds a separator to the current end of the menu. Inserts a menu item or separator into the menu at the specified position. The first menu item is at position 0, the second at position 1, and so on. The JMenuItem and String arguments are treated the same as in the corresponding add methods. Removes the specified item(s) from the menu. If the argument is an integer, then it specifies the position of the menu item to be removed.

void removeAll() Creating, Populating, and Controlling Popup Menus Constructor or Method JPopupMenu() JPopupMenu(String) void show(Component, int, int) Purpose Creates a popup menu. The optional string argument specifies the title that a look and feel might display as part of the popup window. Display the popup menu at the specified x,y position (specified in that order by the integer arguments) in the coordinate system of the specified component. Implementing Menu Items Purpose Creates an ordinary menu item. The icon argument, if present, specifies the icon that the menu item should display. Similarly, the string argument specifies the text that the menu item should display. The integer argument specifies the keyboard mnemonic to use.

Constructor or Method JMenuItem() JMenuItem(String) JMenuItem(Icon) JMenuItem(String, Icon) JMenuItem(String, int) JCheckBoxMenuItem() JCheckBoxMenuItem(String) JCheckBoxMenuItem(Icon) JCheckBoxMenuItem(String, Icon) JCheckBoxMenuItem(String, boolean) JCheckBoxMenuItem(String, Icon, boolean) JRadioButtonMenuItem() JRadioButtonMenuItem(String) JRadioButtonMenuItem(Icon) JRadioButtonMenuItem(String, Icon) JRadioButtonMenuItem(String, boolean) JRadioButtonMenuItem(Icon, boolean) JRadioButtonMenuItem(String, Icon, boolean) void setEnabled(boolean) void setMnemonic(int)

Creates a menu item that looks and acts like a check box. The string argument, if any, specifies the text that the menu item should display. If you specify true for the boolean argument, then the menu item is initially selected (checked). Otherwise, the menu item is initially unselected. Creates a menu item that looks and acts like a radio button. The string argument, if any, specifies the text that the menu item should display. If you specify true for the boolean argument, then the menu item is initially selected. Otherwise, the menu item is initially unselected. If the argument is true, enable the menu item. Otherwise, disable the menu item. Set the mnemonic that enables keyboard navigation to the menu or menu item. Use one of the VK constants defined in the KeyEvent class.

Examples: Open the files MenuExample.java, PopupMenuDemo.java Output:

Class JToolBar java.lang.Object | +--java.awt.Component | +--java.awt.Container | +--javax.swing.JComponent | +--javax.swing.JToolBar A JToolBar is a container that groups several components usually buttons with icons into a row or column. Often, tool bars provide easy access to functionality that is also in menus. By default, the user can drag the tool bar to a different edge of its container or out into a window of its own. For the drag-out behavior to work correctly, the tool bar must be in a container that uses BorderLayout. Purpose Create a tool bar. The optional int parameter lets you specify the orientation; the default is HORIZONTAL. The optional String parameter, allows you to specify the title displayed for the tool bar's window. Add a component to the tool bar. Component add(Component) void addSeparator() void setFloatable(boolean) boolean isFloatable() void setRollover(boolean) boolean isRollover() Add a separator to the end of the tool bar. The floatable property is true by default, to indicate that the user can drag the tool bar out into a separate window. To turn off tool bar dragging, use toolBar.setFloatable(false). The rollover property is false by default. Set it to true to request that every button in the tool bar have no borders until the user passes the cursor over the button.

Method or Constructor JToolBar() JToolBar(int) JToolBar(String) JToolBar(String, int)

Example: Open the file ToolBarDemo.java Output:

Class JSplitPane java.lang.Object | +--java.awt.Component | +--java.awt.Container | +--javax.swing.JComponent | +--javax.swing.JSplitPane A JSplitPane displays two components, either side by side or one on top of the other. By dragging the divider that appears between the components, the user can specify how much of the split pane's total area goes to each component. We can divide screen space among three or more components by putting split panes inside of split panes. Instead of adding the components of interest directly to a split pane, we often put each component into a scroll pane. We then put the scroll panes into the split pane. This allows the user to view any part of a component of interest, without requiring the component to take up a lot of screen space. Method or Constructor Purpose JSplitPane() Create a split pane. JSplitPane(int) When present, the int parameter indicates the split pane's orientation, either HORIZONTAL_SPLIT (the JSplitPane(int, boolean) default) or VERTICAL_SPLIT. The boolean parameter, when present, sets whether the JSplitPane(int, Component, components continually repaint as the user drags the Component) split pane. If left unspecified, this option (called continuous JSplitPane(int, boolean, layout) is turned off. Component, Component) void setOrientation(int) Set or get the split pane's orientation. Use either HORIZONTAL_SPLIT or int getOrientation() VERTICAL_SPLIT defined in JSplitPane. If left unspecified, the split pane will be horizontally

void add(Component)

split. Add the component to the split pane. You can add only two components to a split pane. The first component added is the top/left component. The second component added is the bottom/right component. Any attempt to add more components results in an exception.

Example: Open the file SplitPaneExample.java

Class JLayeredPane java.lang.Object | +--java.awt.Component | +--java.awt.Container | +--javax.swing.JComponent | +--javax.swing.JLayeredPane


JLayeredPane adds depth to a JFC/Swing container, allowing components to overlap each other when needed. An Integer object specifies each component's depth in the container, where higher-numbered components sit "on top" of other components.

For convenience, JLayeredPane divides the depth-range into several different layers.

Putting a component into one of those layers makes it easy to ensure that components overlap properly, without having to worry about specifying numbers for specific depths.

Every Swing container that has a root pane such as JFrame, JApplet, JDialog, or JInternalFrame automatically has a layered pane. Swing provides two layered pane classes. The first, JLayeredPane, is the class that root panes use. The second, JDesktopPane, is a JLayeredPane subclass that's specialized for the task of holding internal frames. Method or Constructor JLayeredPane() JLayeredPane getLayeredPane() (in JApplet, JDialog, JFrame, and JInternalFrame) Method void add(Component) void add(Component, Object) void add(Component, Object, int) void setLayer(Component, int) Purpose Create a layered pane. Get the automatic layered pane in an applet, dialog, frame, or internal frame. Layering Components Purpose Add the specified component to the layered pane. The second argument, when present, is an Integer that indicates the layer. The third argument, when present, indicates the component's position within its layer. Change the component's layer.

void setLayer(Component, int, int) int getLayer(Component)

The second argument indicates the layer. The third argument, when present, indicates the component's position within its layer. Get the layer for the specified component.

Get the number of components in the specified layer. int getComponentCountInLayer(int) The value returned by this method can be useful for computing position values. Component[] Get an array of all the components in the specified layer. getComponentsInLayer(int) Setting Components' Intra-Layer Positions Method Purpose void setPosition(Component, int) Set or get the position for the specified component within its layer. int getPosition(Component) void moveToFront(Component) Move the specified component to the front or back of its layer. void moveToBack(Component)

Class JInternalFrame java.lang.Object | +--java.awt.Component | +--java.awt.Container | +--javax.swing.JComponent | +--javax.swing.JInternalFrame JInternalFrame provides many of the features of a native frame, including dragging, closing, becoming an icon, resizing, title display, and support for a menu bar. We add JInternalFrames to a JDesktopPane. The JInternalFrame content pane is where we add child components. Creating the Internal Frame Purpose Create a JInternalFrame instance. The first argument specifies the title (if any) to be displayed by the internal frame. The rest of the arguments specify whether the internal frame should contain decorations allowing the user to resize, close, maximize, and iconify the internal frame (specified in that order). The default value for each boolean argument is false, which means that the operation is not allowed.

Constructor or Method JInternalFrame() JInternalFrame(String) JInternalFrame(String, boolean) JInternalFrame(String, boolean, boolean) JInternalFrame(String, boolean, boolean, boolean)

JInternalFrame(String, boolean, boolean, boolean, boolean) Method void setContentPane(Container) Container getContentPane() void setJMenuBar(JMenuBar) JMenuBar getJMenuBar() Specifying the Internal Frame's Visibility, Size, and Location Method Purpose Make the internal frame visible (if true) or invisible (if false). void setVisible(boolean) You should invoke setVisible(true) on each JInternalFrame before adding it to its container. (Inherited from Component). Size the internal frame so that its components are at their void pack() preferred sizes. void setBounds(Rectangle) Explicitly set the size and location of the internal frame. (Inherited from Component). void setBounds(int, int, int, int) Performing Window Operations on the Internal Frame Method Purpose Set or get what the internal frame does when the void setDefaultCloseOperation(int) user attempts to "close" the internal frame. The default value is DISPOSE_ON_CLOSE. Other int getDefaultCloseOperation() possible values are DO_NOTHING_ON_CLOSE and HIDE_ON_CLOSE void moveToFront() If the internal frame's parent is a layered pane such as a desktop pane, moves the internal frame to the void moveToBack() front or back (respectively) of its layer. Set or get whether the internal frame is currently closed. void setClosed(boolean) The argument to setClosed must be true. When boolean isClosed() reopening a closed internal frame, you make it visible and add it to a container (usually the desktop pane you originally added it to). void setIcon(boolean) Iconify or deiconify the internal frame, or determine boolean isIcon() whether it's currently iconified. void setMaximum(boolean) Maximize or restore the internal frame, or determine boolean isMaximum() whether it's maximized. void setSelected(boolean) Set or get whether the internal frame is the currently boolean isSelected() "selected" (activated) internal frame. Controlling Window Decorations and Capabilities Adding Components to the Internal Frame Purpose Set or get the internal frame's content pane, which generally contains all of the internal frame's GUI, with the exception of the menu bar and window decorations.

Set or get the internal frame's menu bar.

Method void setClosable(boolean) boolean isClosable() void setIconifiable(boolean) boolean isIconifiable() void setMaximizable(boolean) boolean isMaximizable() void setResizable(boolean) boolean isResizable() void setTitle(String) String getTitle()

Purpose Set or get whether the user can close the internal frame. Set or get whether the internal frame can be iconified. Set or get whether the user can maximize this internal frame. Set or get whether the internal frame can be resized. Set or get the window title.

Using the JDesktopPane API Constructor or Method Purpose JDesktopPane() Creates a new instance of JDesktopPane. JInternalFrame[] getAllFrames() Returns all JInternalFrame objects that the desktop contains. Example using JLayeredPane and JInternalFrame: Open the file JLayeredPaneSample.java Output:

Class JWindow java.lang.Object | +--java.awt.Component | +--java.awt.Container | +--java.awt.Window | +--javax.swing.JWindow A JWindow is a container that can be displayed anywhere on the user's desktop. It does not have the title bar, window-management buttons like JFrame. The JWindow component contains a JRootPane as it's only child. The contentPane should be the parent of any children of the JWindow. Using JWindow we add a child component like this: window.getContentPane().add(child);

The same is true of setting LayoutManagers, removing components, listing children, etc. All these methods should normally be sent to the contentPane instead of the JWindow itself. The default contentPane will have a BorderLayout manager set on it.

Example: Open the file WindowExample.java

Class JDialog java.lang.Object | +--java.awt.Component | +--java.awt.Container | +--java.awt.Window | +--java.awt.Dialog | +--javax.swing.JDialog Dialog boxes are windows that pop up over a parent window and are used to display feedback messages, confirm actions, receive inputs, display tools and so on. Every dialog is dependent on a frame. When that frame is destroyed, so are its dependent dialogs. When the frame is iconified, its dependent dialogs disappear from the screen. When the frame is deiconified, its dependent dialogs return to the screen. A dialog can be modal. When a modal dialog is visible, it blocks user input to all other windows in the program. The JDialogs that JOptionPane creates are modal. To create a non-modal dialog, we use the JDialog class directly. Frequently Used JDialog Constructors and Methods Method or Constructor Purpose Creates a JDialog instance. Jdialog(Frame, boolean) The Frame argument, if any, is the frame (usually a JFrame object) that the dialog depends on. JDialog(Frame, String) Make the boolean argument true to specify a modal dialog, false or absent to specify a non-modal dialog. JDialog(Frame, String, boolean) You can also specify the title of the dialog, using a string argument.

Class JOptionPane java.lang.Object | +--java.awt.Component | +--java.awt.Container | +--javax.swing.JComponent | +--javax.swing.JOptionPane

JOptionPane Features Using JOptionPane, we can create and customize several different kinds of dialogs.

JOptionPane provides support for laying out standard dialogs, providing icons, specifying the dialog's title and text, and customizing the button text. JOptionPane's icon support lets us easily specify which icon the dialog displays. We can use a custom icon, no icon at all or any one of four standard JOptionPane icons (question, information, warning, and error). Each look and feel has its own versions of the four standard icons. The following figure shows the icons used in the Java look and feel. Icons provided by JOptionPane (Java look and feel shown) question information warning error

Almost all uses of the JOptionPane class are one-line calls to one of the static showTypeDialog methods shown below:

showConfirmDialog Asks a confirming question, like yes/no/cancel. showInputDialog Prompt for some input. showMessageDialog Tell the user about something that has happened. All dialogs are modal. The arguments to all of the showTypeDialog methods and JOptionPane constructors are standardized, though the number of arguments for each method and constructor varies. The following list describes each argument. Component parentComponent o The first argument to each showTypeDialog method is always the parent component, which must be a frame, a component inside a frame, or null. o If we specify a frame, then the dialog will appear over the center of the frame, and depend on that frame. o If we specify a component inside a frame, then the dialog will appear over the center of that component, and depend on that component's frame. o If we specify null, then the look and feel picks an appropriate position for the dialog generally the center of the screen. o The JOptionPane constructors do not include this argument. Object message o This required argument specifies what the dialog should display in its main area. o Generally, we specify a string, which results the dialog displaying a label with the specified text. o We can split the message over several lines by putting newline (\n) characters inside the message string. For example: "Complete the sentence:\n \"My Name is...\"" String title o The title of the dialog. int optionType o Specifies the set of buttons that appear at the bottom of the dialog. o Choose from one of the following standard sets: DEFAULT_OPTION, YES_NO_OPTION, YES_NO_CANCEL_OPTION, OK_CANCEL_OPTION. int messageType o This argument determines the icon displayed in the dialog.

o Choose from one of the following values: PLAIN_MESSAGE (no icon), ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE. Icon icon o The icon to display in the dialog. Object[] options o Generally used to specify the string displayed by each button at the bottom of the dialog. o Can also be used to specify icons to be displayed by the buttons or non-button components to be added to the button row. Object initialValue o Specifies the default value to be selected.

Examples: Open the files MessageDialog.java, Sample_Input_Dialog.java Output:

SpringLayout

A SpringLayout lays out the children of its associated container according to a set of constraints. Each constraint controls the vertical or horizontal distance between two component edges. The edges can belong to any child of the container, or to the container itself. For example, the allowable width of a component can be expressed using a constraint that controls the distance between the west (left) and east (right) edges of the component. The allowable y coordinates for a component can be expressed by constraining the distance between the north (top) edge of the component and the north edge of its container. The constructor SpringLayout( ) constructs a new SpringLayout. We can use the putConstraint method to establish a spring linking the edges of two components within the same container. public void putConstraint(String e1, Component c1, int pad, String e2, Component c2) Links edge e1 of component c1 to edge e2 of component c2, with a fixed distance (pad) between the edges. Open the files SpringDemo1.java, SpringDemo2.java

Output:

BoxLayout

The Swing packages include a general-purpose layout manager named BoxLayout. BoxLayout allows multiple components to be laid out either vertically or horizontally. The components will not wrap so, for example, a vertical arrangement of components will stay vertically arranged when the frame is resized. Constructor: BoxLayout(Container target, int axis) o Creates a layout manager that will lay out components along the given axis. The BoxLayout manager is constructed with an axis parameter that specifies the type of layout that will be done. The choices are: X_AXIS - Components are laid out horizontally from left to right. Y_AXIS - Components are laid out vertically from top to bottom.

For all directions, components are arranged in the same order as they were added to the container. Example: Open the file BoxLayoutDemo.java

Output:

Вам также может понравиться