chapter 3 swing - i 3.1 introduction 3.4 jcomponent class · the swing api contains 100% pure java...

16
Chapter 3 Swing - I 3.1 Introduction 3.2 Features of Swing 3.3 Swing API component 3.4 JComponent Class 3.5 Windows, Dialog Boxes and Panels 3.1 Introduction The AWT API described in previous chapter, this chapter provides a user interface frame work with which you can continue to develop GUIs. When the java platform was introduced in 1995, the AWT was the only API for creating GUIs. The set of components provided by the AWT is adequate for simple task, but it has some limitations. For example- creating a new type of component by directly subclassing Component is difficult because you must also create a peer object. Swing/JFC is short for Java Foundation Classes, which encompass a group of features for building graphical user interfaces (GUIs) and adding rich graphics functionality and interactivity to Java applications. The swing API contains 100% pure java versions of the AWT components, plus many additional components that are also 100% pure java, because swing does not contain or depend on native code. Swing is the package or set of classes that provide more powerful and flexible component than that of ‘AWT’. It supplies several exiting addition including tabbed panes, trees and tables. Even familiar component like buttons have more capabilities in swing i.e buttons may have both image and text associated with it. You can identify Swing components because their names start with J. The AWT button class, for example, is named Button, while the Swing button class is named JButton. Additionally, the AWT components are in the java.awt package, while the Swing components are in the javax.swing package. 3.2 Features of Swing Swing Components Are Lightweight

Upload: buithu

Post on 15-Jul-2019

228 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 3 Swing - I 3.1 Introduction 3.4 JComponent Class · The swing API contains 100% pure java versions of the AWT components, plus many additional components that are also 100%

Chapter 3

Swing - I

3.1 Introduction

3.2 Features of Swing

3.3 Swing API component

3.4 JComponent Class

3.5 Windows, Dialog Boxes and Panels

3.1 Introduction

The AWT API described in previous chapter, this chapter provides a user interface frame work with

which you can continue to develop GUIs. When the java platform was introduced in 1995, the AWT was

the only API for creating GUIs. The set of components provided by the AWT is adequate for simple task,

but it has some limitations. For example- creating a new type of component by directly subclassing

Component is difficult because you must also create a peer object.

Swing/JFC is short for Java Foundation Classes, which encompass a group of features for building

graphical user interfaces (GUIs) and adding rich graphics functionality and interactivity to Java

applications.

The swing API contains 100% pure java versions of the AWT components, plus many additional

components that are also 100% pure java, because swing does not contain or depend on native code.

Swing is the package or set of classes that provide more powerful and flexible component than that of

‘AWT’.

It supplies several exiting addition including tabbed panes, trees and tables.

Even familiar component like buttons have more capabilities in swing i.e buttons may have both image

and text associated with it.

You can identify Swing components because their names start with J. The AWT button class, for

example, is named Button, while the Swing button class is named JButton. Additionally, the AWT components are in the java.awt package, while the Swing components are in the javax.swing package.

3.2 Features of Swing

Swing Components Are Lightweight

Page 2: Chapter 3 Swing - I 3.1 Introduction 3.4 JComponent Class · The swing API contains 100% pure java versions of the AWT components, plus many additional components that are also 100%

This means that they are written entirely in Java and do not map directly to platform-specific peers. Because lightweight components are rendered using graphics primitives, they can be transparent which enables non rectangular shapes. Thus, lightweight components are more efficient and more flexible. Because lightweight components do not translate into native peers, the look and feel of each component is determined by Swing, not by the underlying operating system. This means that each component will work in a consistent manner across all platforms.

Swing Supports a Pluggable Look and Feel

Each Swing component is rendered by Java code rather than by native peers, the look and feel of a component is under the control of Swing. It is possible to “plug in” a new look and feel for any given component without creating any side effects in the code that uses that component.

The MVC Architecture

This is Essential feature of Swing that is using MVC we can change internal representation of table, trees and list.

New Components

There are various new components provided by swing which are as follows Image Button Tabbed Panes Sliders Toolbars Color Chooser Text Areas List Trees tables 3.3 Swing API component

Here the following APIs interfaces and classes are available: The following interfaces and it's descriptions to be used by the Java swing.

Interface Descriptions

Action

This interface performed the action with

the ActionListener where the multiple controls are

Page 3: Chapter 3 Swing - I 3.1 Introduction 3.4 JComponent Class · The swing API contains 100% pure java versions of the AWT components, plus many additional components that are also 100%

used for same purposes.

ButtonModel

It defines the state model for the buttons like:

radio buttons, check boxes etc.

ComboBoxEditor In this interface, the editor component used to JComboBoxcomponents.

BoundedRangeModel

This interface defines the data model of components like: sliders and progressBars.

ComboBoxEditor

In this interface, the editor component used to JComboBoxcomponents.

DesktopManager

This interface has JDesktopPane object.

The JInternalFrameimplements in the

JDesktopPane with the help of DesktopManager.

Icon

This interface used to graphical representation of

the components. It has fixed size picture.

ListModel

This interface used for JList components method.

It gets the value of each cell of list.

Renderer

It defines the requirements of an object for

displaying the values.

RootPaneContainer

This interface uses the RootPane properties and it

has the components like: JFrame, JInternalFrame

and JWindow etc.

Scrollable

This interface provides the scrolling to show the

large amount of data with the help of JScrollPane.

WindowConstants

This interface has two methods

setDefaultCloseOperation and

getDefaultCloseOperation and provides the

window close opration.

The following classes and it's descriptions to be used by the Java swing.

Classes Descriptions

JApplet This class extends the Applet and implements

the Accessible and RootPaneContainer.

JButton This class extends the AbstractButton and you can

create the new button.

Page 4: Chapter 3 Swing - I 3.1 Introduction 3.4 JComponent Class · The swing API contains 100% pure java versions of the AWT components, plus many additional components that are also 100%

JCheckBox This class extends the JToggleButton and

implements the check box in which buttons are

selected or deselected.

JCheckBoxMenuItem It extends the JMenuItem and determines the

items which is selected or deselected.

JColorChooser It extends the JComponent and implementing the

Accessable. Here, you choose and manipulate the

colors.

JComboBox This class extends the JComboBox. It provides the

drop-down list where user select only one item or

value at a time. But combo box is a combination of

multiple text or buttons etc.

JComponent In java swing, All components are used the

JComponent except the top-level containers like:

JFrame, JDialog etc.

JDesktopPane This class extends the JLayeredPane and when you

create the object of JInternalFrame to be

maintained in the JDesktopPane. The

JDesktopPane has DesktopManager.

JDialog It extends the Dialog. This class used to create the

dialog window and when you want to create the

custom dialog window with the help

of JOptionPane method.

JEditorPane This class extends the JTextComponent. It edits the

component by the EditorKit.

JFileChooser This class provides the facility to choosing the file.

JFrame It extends the Frame and supports the swing

components architecture.

JInternalFrame This class extends from the JComponent and

provides the facility to dragging, closing, resizing

and menu bar of the internal frame. The

JInternalFrame added into the JDesktopPane.

JLabel This class used to show the small text and image.

JLayeredPane It has JFC/Swing container that can be used to

overlap the components to each other.

JList This class used to create a list where you select the

one or more than objects.

JMenu This class used to create a new menu where you

add the JMenuItems. When you select the item

then shows the popup menu items in the

JMenuBar.

JMenuBar It used to create a new menu bar where the

JMenu objects are added.

JMenuItem This class used to create new menu items in the

mebus.

JOptionPane It used to create some different types of dialog box

Page 5: Chapter 3 Swing - I 3.1 Introduction 3.4 JComponent Class · The swing API contains 100% pure java versions of the AWT components, plus many additional components that are also 100%

like: message dialog box, error dialog box etc.

JPanel It extends the JComponent and used to create a

new panel.

JPassworkField It provides the single line text editing. Here, don't

available the original characters but view type

indication characters are available.

JPopupMenu This class used to create a popup menu. It provides

small window where the various types of choices

are available.

JProgressBar It shows the integer types values in percent within

a bounded range to determine the working

process.

JRadioButton It implements the radio button and shows the

state of an item selected or deselected.

JRadioButtonMenuItem It extends the JMenuItem and implements the

radio button menu item

JRootPane This class provides the component behind the

scenes by JFrame, JWindow, JDialog etc. for

providing the task-orientation and functionality.

JScrollBar This class used to create a scroll bar. It provides

the view content area where you show the

content to scroll this.

JScrollPane It provides the scrollable view components.

JSeparator This class use the separator among the

components.

JSlider This class provides a control to represent a

numeric value by dragging the slider.

JSplitPane This class used to divides the two components

graphically like: top and button, left and right.

JTabbedPane This class provides the tab component through

which you can switch from one component to

another component regarding to the specific tab

button by clicking on that.

JTable It provides the user interface component and

represents the two dimensional data.

JTextArea It provides the multi line plain text area.

JTextField It provides the facility to editing the text in a single

line.

JTextPane This class provides the component like JTexArea

for multiple lines text with more capabalities.

JToolBar

It provides set of command buttons icons that

performs the different actions or controls.

JToolTip It shows the tool tips related to it's components.

JTree It shows the data in a hierarchical way.

JViewPort

It gives you about the underlying information.

Page 6: Chapter 3 Swing - I 3.1 Introduction 3.4 JComponent Class · The swing API contains 100% pure java versions of the AWT components, plus many additional components that are also 100%

Swing Component

Swing Hierarchy

3.4 JComponent Class

java.lang.Object

java.awt.Component

java.awt.Container

javax.swing.JComponent

Class : javax.swing.JComponent

Object

Component

Container

Panel

Applet

JApplet

Window

Frmae JFrame

Dialog JDialog

JComponent

JTextComponent

JTextArea

JEditorPane

JTextField JLable

JList

JMenuBar

JPopMenu

JPane

JRootPane

JLayeredPane

JPanel

JScrollBar

AbstractButton

JToggleButton

JCheckBox

JRadioButton

JButton

JMenuItem

JMenu

JCheckBoxMenuItem

JRadioButtonMenuItem

Page 7: Chapter 3 Swing - I 3.1 Introduction 3.4 JComponent Class · The swing API contains 100% pure java versions of the AWT components, plus many additional components that are also 100%

Perpose: The base class for all Swing components except top-level containers. To use a component that inherits from JComponent, you must place the component in a containment hierarchy whose root is a top-level Swing container.

The JComponent class provides:

The base class for both standard and custom components that use the Swing architecture.

A "pluggable look and feel" (L&F) that can be specified by the programmer or (optionally) selected by the user at runtime.

Support for tool tips -- short descriptions that pop up when the cursor lingers over a component. Support for accessibility. JComponent contains all of the methods in the Accessible interface,

but it doesn't actually implement the interface. That is the responsibility of the individual classes that extend JComponent.

Support for component-specific properties.

Constructor:

public JComopent()

Default JComponent constructor.

Methods:

void addXXXListener(XXXListener object)

Registers a listeners for a specific type of event with the component. The XXX in the

method name varies depending upon the type of the listeners.

public void repaint(long tm,

int x,

int y,

int width,

int height)

Adds the specified region to the dirty region list if the component is showing. The component will be repainted after all of the currently pending events have been dispatched.

tm(milliseconds)

public void setBackground(Color bg)

Sets the background color of this component.

public void setEnabled(boolean enabled)

Sets whether or not this component is enabled. A component that is enabled may respond to user input, while a component that is not enabled cannot respond to user input.

public void setFont(Font font)

Sets the font for this component.

Page 8: Chapter 3 Swing - I 3.1 Introduction 3.4 JComponent Class · The swing API contains 100% pure java versions of the AWT components, plus many additional components that are also 100%

public void setForeground(Color fg)

Sets the foreground color of this component.

public void setToolTipText(String text)

Registers the text to display in a tool tip. The text displays when the cursor lingers over the component.

public void setVisible(boolean aFlag)

Makes the component visible or invisible.

3.5 Windows, Dialog Boxes and Panels

3.5.1 JDesktopPane

Class: javax.swing.JDesktopPane

Purpose: A container used to create a multiple-document interface or a virtual desktop. You create JInternalFrame objects and add them to the JDesktopPane. JDesktopPane extends JLayeredPane to manage the potentially overlapping internal frames. It also maintains a reference to an instance of DesktopManager that is set by the UI class for the current Look and Feel (L&F). Costructor:

public JDesktopPane()

Creates a new JDesktopPane.

3.5.2 JInternalFrame

Class: javax.swing.JInternalFrame

Purpose: A lightweight object that provides many of the features of a native frame, including dragging, closing, becoming an icon, resizing, title display, and support for a menu bar. Generally, you add JInternalFrames to a JDesktopPane. The UI delegates the look-and-feel-specific actions to the DesktopManager object maintained by the JDesktopPane. Constructor:

public JInternalFrame()

Creates a non-resizable, non-closable, non-maximizable, non-iconifiableJInternalFrame with no title.

Page 9: Chapter 3 Swing - I 3.1 Introduction 3.4 JComponent Class · The swing API contains 100% pure java versions of the AWT components, plus many additional components that are also 100%

public JInternalFrame(String title)

Creates a non-resizable, non-closable, non-maximizable, non-iconifiableJInternalFrame with the specified title.

public JInternalFrame(String title, boolean resizable)

Creates a non-closable, non-maximizable, non-iconifiable JInternalFrame with the specified title and with resizability specified.

public JInternalFrame(String title, boolean resizable, boolean

closable )

Creates a non-maximizable, non-iconifiableJInternalFrame with the specified title and with resizability and closability specified.

public JInternalFrame(String title, boolean resizable, boolean

closable,boolean maximizable)

Creates a non-iconifiableJInternalFrame with the specified title and with resizability, closability, and maximizability specified.

public JInternalFrame(String title, boolean resizable, boolean

closable,boolean maximizable, boolean iconifiable)

Creates a JInternalFrame with the specified title and with resizability, closability, maximizability, and iconifiability specified.

The default is false in all cases. 3.5.3 JLayeredPane Class: javax.swing.JLayeredPane

Purpose: 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. 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. Constructor:

public JLayeredPane()

Create a new JLayeredPane 3.5.4 JRootPane Class: javax.swing.JRootPane

Page 10: Chapter 3 Swing - I 3.1 Introduction 3.4 JComponent Class · The swing API contains 100% pure java versions of the AWT components, plus many additional components that are also 100%

Purpose: A lightweight container used behind the scenes by JFrame, JDialog, JWindow, JApplet, and JInternalFrame. A JRootpane is made up of a glassPane, an optional menuBar, and a contentPane. The JLayeredPane manages the menuBar and the contentPane.

The layeredPane is the parent of all children in the JRootPane. It is an instance of JLayeredPane, which provides the ability to add components at several layers. This capability is very useful when working with menu popups, dialog boxes, and dragging -- situations in which you need to place a component on top of all other components in the pane.

The glassPane sits on top of all other components in the JRootPane. That provides a convenient place to draw above all other components, and makes it possible to intercept mouse events, which is useful both for dragging and for drawing. Developers can use setVisible on the glassPane to control when theglassPane displays over the other children. By default the glassPane is not visible.

The contentPane is adjusted in location and size to fill the remaining area.

Constructor: public JRootPane()

Create a JRootPane, setting up its glassPane, LayeredPane, and contentPane.

3.5.5 JOptionPane Class: javax.swing.JOptionPane

Purpose: JOptionPane makes it easy to pop up a standard dialog box that prompts users for a value or informs them of something.

While the JOptionPane class may appear complex because of the large number of methods, almost

all uses of this class are one-line calls to one of the static showXxxDialog 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.

showOptionDialog The Grand Unification of the above three.

Constructor:

public JOptionPane(Object message)

Creates a instance of JOptionPane to display a message using the plain-message message type and the default options delivered by the UI.

Parameters:

message - the Object to display

Page 11: Chapter 3 Swing - I 3.1 Introduction 3.4 JComponent Class · The swing API contains 100% pure java versions of the AWT components, plus many additional components that are also 100%

public JOptionPane(Object message,

int messageType)

Creates an instance of JOptionPane to display a message with the specified message type and the default options,

Parameters:

messageType - the type of message to be displayed: ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE, or PLAIN_MESSAGE

public JOptionPane(Object message,

int messageType,

int optionType)

Creates an instance of JOptionPane to display a message with the specified message type and options.

Parameters:

optionType - the options to display in the pane: DEFAULT_OPTION, YES_NO_OPTION, YES_NO_CANCEL_OPTION OK_CANCEL_OPTION

public JOptionPane(Object message,

int messageType,

int optionType,

Icon icon)

Creates an instance of JOptionPane to display a message with the specified message type, options, and icon.

Parameters:

icon - the Icon image to display

public JOptionPane(Object message,

int messageType,

int optionType,

Icon icon,

Object[] options)

Creates an instance of JOptionPane to display a message with the specified message type, icon, and options. None of the options is initially selected.

objects should contain either instances of Components, (which are added directly) or Strings (which are wrapped in a JButton). If you provide Components, you must ensure that when the Component is clicked it messages setValue in the created JOptionPane.

Parameters:

options - the choices the user can select

public JOptionPane(Object message,

int messageType,

int optionType,

Icon icon,

Page 12: Chapter 3 Swing - I 3.1 Introduction 3.4 JComponent Class · The swing API contains 100% pure java versions of the AWT components, plus many additional components that are also 100%

Object[] options,

Object initialValue)

Creates an instance of JOptionPane to display a message with the specified message type, icon, and options, with the initially-selected option specified.

Parameters:

initialValue - the choice that is initially selected

3.5.6 JSplitPane

Class: javax.swing.JSplitPane

Purpose:

JSplitPane is used to divide two (and only two) Components. The two Components are graphically divided based on the look and feel implementation, and the two Components can then be interactively resized by the user.

The two Components in a split pane can be aligned left to right using JSplitPane.HORIZONTAL_SPLIT, or top to bottom

usingJSplitPane.VERTICAL_SPLIT. The preferred way to change the size of the Components is to invoke setDividerLocation where location is either the new x or y position, depending on

the orientation of the JSplitPane.

Constructor:

public JSplitPane()

Creates a new JSplitPane configured to arrange the child components side-by-side horizontally with no continuous layout, using two buttons for the components.

public JSplitPane(int newOrientation)

Creates a new JSplitPane configured with the specified orientation and no continuous layout.

Parameters:

newOrientation -JSplitPane.HORIZONTAL_SPLIT or JSplitPane.VERTICAL_SPLIT

public JSplitPane(int newOrientation,

boolean newContinuousLayout)

Creates a new JSplitPane with the specified orientation and redrawing style.

Parameters:

newContinuousLayout - a boolean, true for the components to redraw continuously as the divider changes position, false to wait until the divider position stops changing to redraw

Page 13: Chapter 3 Swing - I 3.1 Introduction 3.4 JComponent Class · The swing API contains 100% pure java versions of the AWT components, plus many additional components that are also 100%

public JSplitPane(int newOrientation,

boolean newContinuousLayout,

Component newLeftComponent,

Component newRightComponent)

Creates a new JSplitPane with the specified orientation and redrawing style, and with the specified components.

Parameters:

newLeftComponent - the Component that will appear on the left of a horizontally-split pane, or at the top of a vertically-split pane

newRightComponent - the Component that will appear on the right of a horizontally-split pane, or at the bottom of a vertically-split pane

public JSplitPane(int newOrientation,

Component newLeftComponent,

Component newRightComponent)

Creates a new JSplitPane with the specified orientation and with the specified components that do not do continuous redrawing.

Parameters:

newOrientation - JSplitPane.HORIZONTAL_SPLIT or JSplitPane.VERTICAL_SPLIT

newLeftComponent - the Component that will appear on the left of a horizontally-split pane, or at the top of a vertically-split pane

newRightComponent - the Component that will appear on the right of a horizontally-split pane, or at the bottom of a vertically-split pane

3.5.7 JTabbedPane

Class: javax.swing.JTabbedPane

Purpose:

A component that lets the user switch between a group of components by clicking on a tab with a given title and/or icon.

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:

public JTabbedPane()

Creates an empty TabbedPane. The default tab placement is TOP.

Page 14: Chapter 3 Swing - I 3.1 Introduction 3.4 JComponent Class · The swing API contains 100% pure java versions of the AWT components, plus many additional components that are also 100%

public JTabbedPane(int tabPlacement)

Creates an empty TabbedPane with the specified tab placement of either: TOP, BOTTOM, LEFT, or RIGHT.

Parameters:

tabPlacement - the placement for the tabs relative to the content

3.5.8 JViewPort

Class: javax.swing.JViewport

Purpose:

The "viewport" or "porthole" through which you see the underlying information. When you 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.

By default, JViewport is opaque. To change this, use the setOpaque method.

Constructor:

public JViewport()

Creates a JViewport.

3.5.9 JPanel

Class: javax.swing.JPanel

Purpose:

JPanel is a generic lightweight container.

Constructor:

public JPanel()

Create a new JPanel with a double buffer and a flow layout

public JPanel(boolean isDoubleBuffered)

Create a new JPanel with FlowLayout and the specified buffering strategy.

If isDoubleBuffered is true, the JPanel will use a double buffer.

Page 15: Chapter 3 Swing - I 3.1 Introduction 3.4 JComponent Class · The swing API contains 100% pure java versions of the AWT components, plus many additional components that are also 100%

Parameters:

layout - the LayoutManager to use

isDoubleBuffered - a boolean, true for double-buffering, which uses additional memory space to achieve fast, flicker-free updates

public JPanel(LayoutManager layout)

Create a new buffered JPanel with the specified layout manager

Parameters:

layout - the LayoutManager to use

public JPanel(LayoutManager layout,

boolean isDoubleBuffered)

Creates a new JPanel with the specified layout manager and buffering strategy.

Parameters:

layout - the LayoutManager to use

isDoubleBuffered - a boolean, true for double-buffering, which uses additional memory space to achieve fast, flicker-free updates

Program:

import java.awt.*;

import javax.swing.*;

public class Example1

{

JPanel p1,p2,p3,p4;

JLabel l1,l2,l3,l4;

JTabbedPane tab;

public JTabbedPaneDemo()

{

JFrame f = new JFrame("JTabbedPane");

f.setVisible(true);

f.setSize(300,300);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

l1 = new JLabel("First Tab");

l2 = new JLabel("Second Tab");

l3 = new JLabel("Third Tab");

l4 = new JLabel("Forth Tab");

p1 =new JPanel();

p2 =new JPanel();

Page 16: Chapter 3 Swing - I 3.1 Introduction 3.4 JComponent Class · The swing API contains 100% pure java versions of the AWT components, plus many additional components that are also 100%

p3 =new JPanel();

p4 =new JPanel();

p1.add(l1);

p2.add(l2);

p3.add(l3);

p4.add(l4);

tab = new JTabbedPane();

tab.addTab("Panel 1", p1);

tab.addTab("Panel 2", p2);

tab.addTab("Panel 3", p3);

tab.addTab("Panel 4", p4);

f.add(tab);

}

public static void main(String args[])

{

new JTabbedPaneDemo();

}

}