slide1 l.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Swing PowerPoint Presentation
Download Presentation
Swing

Loading in 2 Seconds...

play fullscreen
1 / 25

Swing - PowerPoint PPT Presentation


  • 146 Views
  • Uploaded on

Swing. Creating an Applet with a Graphical User Interface. There are three steps that a programmer must complete to create an applet with a graphical user interface:. Step 1. Declare and define the components that will be placed on the applet.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Swing' - fiachra


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
slide2

Creating an Applet with a Graphical User Interface

There are three steps that a programmer must complete to create an applet with a graphical user interface:

Step 1. Declare and define the components that will be placed on the applet.

Step 2. Choose a Layout Manager and use this manager to direct the placement of the components on the applet.

Step 3. Add appropriate event listeners to the components you have placed in the applet, and provide the appropriate (actionPerformed) instructions for each event listener

In this lecture we focus on Step 1 – declaring and defining components.

slide3

Swing

Differences between Swing and AWT

Naming Conventions

All Swing components begin with a capital J -- JPanel, JButton, JScrollBar, JApplet, etc..

Most Swing Components are “Lightweight”

  • Use Java code rather than native code to draw in the underlying window.
  • The Exceptions are JFrame, JApplet, JWindow, andJDialog

Use Content Pane for adding Components to “Heavyweight” Containers

To add Components to a JApplet (in method init( )) use

Container cp = new getContentPane( );

cp.add(new JButton(“Start”);

slide4

Part of the AWT Class Hierarchy

Object

Component

Button

Checkbox

Choice

List

Label

Canvas

TextComponent

Container

Scrollbar

TextArea

TextField

Panel

Window

ScrollPane

Applet

Dialog

Frame

slide5

Container

Panel

Window

ScrollPane

Applet

Heavyweight Swing components

Dialog

Frame

The “Swing Set”

All Swing classes are derived from the AWT abstract class Container

AWT classes

Swing classes

JComponent JApplet JDialog JFrame JWindow

slide6

Object

Class Object is the root of the class hierarchy. Every class has Object as

a superclass. All objects implement the methods of this class.

Component

The Component class is the abstract superclass of many of the

AWT classes. It represents something that has a position, a size,

can be painted on the screen, and can receive input events.

Some Methods Defined in Class Component:

setForeground(Color) set the component’s foreground color

setBackground(Color) set the component’s background color

setFont(Font) set the component’s font

paint(Graphics) repaint the component

repaint( ) schedule the component for repainting

addxxxListener(xxxListener) add an xxx listener for the component

(where xxx is Component, Focus, Key,

Mouse, or MouseMotion)

An xxxListener is an object that waits for an event to occur, then executes certain

actions in response to the event.

slide7

JLabel JPanel JTextComponent JComboBox JScrollBar AbstractButton JList JScrollPane others

JMenuItem JButton JToggleButton

JTextField JTextArea JEditorPane

Heavyweight Swing components

JCheckBox JRadioButton

Swing Components

Swing classes

JComponent JApplet JDialog JFrame JWindow

slide8

An Applet Displaying the Components to be Discussed:

ComponentIntro1

The Essence of the Structure of the Code of the Nine Applets

to be Displayed Next:

import java.awt.*;

import javax.swing.*;

public class Xxx extends JApplet {

<declarations of Components> //in a few cases other stuff

public void init() {

<Component registration> //using method add(...) and

} //in a few cases other stuff

}

For Component JPanel, an “inner” subclass of class JPanel has been employed that

implements method paint(Graphics).

slide9

Container

The Container class is the abstract superclass representing all

components that can hold other components. JComponent is derived from this class,

Some Methods Defined in Class Container (and JComponent):

setLayout(LayoutManager) associate a particular layout with the container

add(Component) add a component to the container

The following components are placed within Container objects:

JLabel

Labels

A Label object consists of non-editable text.

In addition, input events can be associated with the following components:

JButton

Buttons

This class creates a labeled button.

JCheckBox

(ButtonGroup)

A check box has an "on" (true) and "off" (false) state. Clicking on the

check box toggles its state between "on" and "off ".

A group of radio buttons or check boxes in which only 1 can be in its "on" state at any time.

CheckBoxes

slide10

JComboBox

A combo box presents the user with a pop-up menu of choices. The current choice is displayed as the title of the menu.

ChoiceLists

TextComponent

A text component is the superclass of any component that

allows the editing of some text.

JTextArea

A text area is a multi-line area for displaying text. It can be set to

allow editing or to be read-only.

TextAreas

JTextField

A text field presents the user with a single editable line of text.

TextFields

JList

A list presents the user with a scrolling list of text items that can be set

up either so that the user can pick only 1 item or pick multiple items.

ScrollingLists

JScrollBar

A scroll bar provides a convenient means of allowing a user to select

from a range of values.

ScrollBars

JPanel

A JPanel component represents a blank rectangular area of the screen

onto which can appear a drawing.

Panels

slide11

The Form of the HTML File Used in the Previous 9 Applets:

<HTML>

<HEAD>

<TITLE>Xxx</TITLE>

</HEAD>

<BODY>

<H2>Component: Yyy</H2>

<applet code=“Xxx.class" width=www height=hhh>

</applet>

<P>

<A HREF=“Xxx.java"> Java Source </A>

</BODY>

</HTML>

where Xxx is the public class name, Yyy is the component name,

and www & hhh represent the applet size.

slide12

More Information about Swing Components

Adding JComponents to a JApplet

Step 1. Import classes (as needed) from packages java.awt.* (for Container) and javax.swing.* (for JApplet and the needed JComponents).

Step 2. Write the header for a class that extends JApplet.

Step 3. Declare and define any JComponents that you will add to your applet.

Step 4. In method init( ), call method getContentPane( ) to serve as a Container object for holding swing components in a JApplet.

Step 5. Select a Layout manager and with method setLayout( ), install this choice as the Layout manager for the ContentPane. Optionally you may also set the background color for the ContentPane. (default is lightGray)

Step 6. Add all the declared JComponents to the ContentPane.

To provide functionality to these components you will have to add event listeners, but this will be deferred until a bit later.

slide13

Step 1. Import classes from packages java.awt and javax.swing

Step 2. Programmer’s class extends JApplet

Step 3. Declare and define JComponents

Step 4. Use getContentPane( ) to provide a container for components

Step 5. Provide a Layout manager for the ContentPane, and optionally a background color (default is lightGray)

Step 6. Add components to the ContentPane

Swing Components

Example – Create an Applet with a JLabel and a JTextField

import java.awt.*;

import javax.swing.*;

publicclass LabelDemo extends JApplet {

private JLabel nameLabel = new JLabel(“name”);

private JTextField theName = new JTextField(25);

public void init( ) {

Container cp = getContentPane( );

cp.setLayout(new FlowLayout( ));

cp.setBackground(Color.cyan);

cp.add(nameLabel);

cp.add(theName);

}

}

Layout managers will be discussed in the next lecture. FlowLayout is the simplest to use, but provides the least programmer control over placement of components.

LabelDemo

slide14

Creates a JLabel object with center alignment an no text

Creates a JLabel with default center alignment

Inherited from JComponent

Swing Components

Common methods in JLabel

Constructors

JLabel( );

JLabel(String textTo Appear);

JLabel(String textToAppear, int alignment);

Alignment is either JLabel.LEFT, JLabel.CENTER, or JLabel.RIGHT

Other JLabel methods include

String getText( );

void setText(String textToAppear);

setOpaque(boolean);

setBackground(Color c); setForeground(Color c);

setFont(Font f);

Hides container window color

slide15

Text field with default width determined by system

Blank text field with specified number of columns

Width of text field = length of string

Sets both width and contents of text field

Blank text area with default length and width

Blank text area with r rows and c columns

Text area of default size containing the string

Text area of set size with initial string

Swing Components

Common TextComponent methods

Constructors

JTextField( );

JTextField(int cols);

JTextField(String textToEnter);

JTextField(String, int);

JTextField objects are used to enter or display text on a single line. JTextArea objects are used to enter or display more than one line of text. The constructors for a JTextArea are similar to those for the JTextField.

JTextArea( );

JTextArea(int r, int c);

JTextArea(String textToEnter);

JTextArea(String, int, int);

slide16

Declarations creating a JTextArea and a JScrollPane

The JScrollPane object is added to the ContentPane

Swing Components

Other JTextComponent methods include:

void setText(String textToEnter);

String getText( );

A JTextArea is often enclosed in a JScrollPane. Using the constructor for a JScrollPane that takes only the component to be shown in this window, the scroll bars will be invisible until they are needed.

The statements needed to place a JTextArea in a JScrollPane are as follows:

private JTextArea theText = new JTextArea(3, 10);

private JScrollPane sp = new JScrollPane(theText);

//in method init( )

Container cp = getContentPane( );

cp.add(sp);

The JScrollPane is created holding the JTextArea object

slide17

Without this statement, the background of the label will not be set to white, but will remain lightGray, the default color of the ContentPane

Swing Components

JLabels can have their own Font and foreground and background color.

Suppose we want to add a JLabel object named textLabel to a ContentPane cp, and we want the font to be bold, sansSerif, and 20 point, and we want the label to appear blue on a white background. We would use the following statements in method init( ):

textLabel.setFont(new Font(“sansSerif”, Font.BOLD, 20) );

textLabel.setOpaque(true);

textLabel.setForeground(Color.blue);

textLabel.setBackground(Color.white);

cp.add(textLabel);

This applet illustrates the points stated on the last few slides about JLabel and JTextComponent objects. Notice what happens when we comment out the setOpaque(true) statement for the addressField. Enter text in the text fields and text areas and see what happens when you exceed the space provided.

Component Demol

slide18

Add to end of menu

Menu items may be String (text) or icons

Allows the user to input text if “true”

Swing Components

JComboBox

A JComboBox describes a menu with several choices, one of which can be selected. When the user is not accessing the JComboBox object, only the currently selected choice (and a down arrow) appears in the menu. The class JComboBox is similar to class Choice in AWT.

Methods in JComboBox include:

void addItem(Object alternative);

void insertItemAt(Object alternative, int loc);

void removeItem(Object alternative);

void removeItemAt(int loc);

Object getSelectedItem( );

int getSelectedIndex( );

Object getItemAt(int loc);

int getItemCount( );

void setEditable(boolean);

slide19

Create a menu with the above menu items

Create an empty menu ….

…and add items individually

Swing Components

Constructing a Menu

A menu can be displayed in a JComboBox or a JList. Both of these classes have a constructor that creates its menu from an array of menu items. The JComboBox class also has a constructor that creates an empty menu.

String [ ] menuItems = {“open”, “close”, “save”, “delete”, “quit”}

JComboBox jcb1 = new JComboBox(menuitems);

JComboBox jcb2 = new JComboBox( );

jcb2.addItem(“open”);

jcb2.addItem(“close”);

etc.

The JList class only has the first type of constructor.

JList myJList = new JList(menuItems);

slide20

Wrap the JList inside a JScrollPane object

Add the JScrollPane object to the ContentPane

Swing Components

A JList menu may contain more items than those that are visible at any one time. The programmer should set the number of rows that are visible to the desired value, then wrap the JList object inside of a JScrollPane.

JList myList = new JList (menuItems);

JScrollPane jsp = new JScrollPane(myList);

//in method init( )

myList.setVisibleRowCount(3);

cp.add(jsp);

A JComboBox provides for only a single selection. A JList allows multiple selections. There are three selection modes the programmer can choose from:

myList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

myList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);

myList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

default

If one of the multiple selection modes is chosen, the user selects several choices by using Shift and Control keys in combination with mouse clicks.

slide21

Swing Components

JButton

A JButton has a label and/or an icon. The programmer can set the Font and background and foreground color of the button in a manner similar to that which was done for the JLabel.

JButton saveButton = new JButton(“Save”);

//in method init( )

saveButton.setFont(new Font(“sansSerif”, Font.BOLD+Font.ITALIC, 16));

saveButton.setOpaque(true);

saveButton.setBackground(Color.cyan);

saveButton.setForeground(Color.white);

slide22

Add buttons to the ButtonGroup

Add buttons to the ContentPane

Democrat

Independent

Republican

Swing Components

ButtonGroup

Objects of class JRadioButton or JCheckBox can be grouped together into a ButtonGroup. If ungrouped, each object these classes can be toggled “on” or “off” separately. If part of a ButtonGroup, when one object from either of these classes is asserted, the previously asserted object is toggled “off”.

private JRadioButton b1 = new JRadioButton(“Democrat”,false);

private JRadioButton b2 = new JRadioButton(“Independent”,true);

private JRadioButton b3 = new JRadioButton(“Republican”, false);

private ButtonGroup voters = new ButtonGroup( );

//in method init( ) after getting a ContentPane cp

voters.add(b1); voters.add(b2); voters.add(b3);

cp.add(b1); cp.add(b2); cp.add(b3);

Labels and initial settings

Select option

slide23

JScrollBar.HORIZONTAL or JScrollBar.VERTICAL

Choosing 0 sets indicator to the default size

Swing Components

JScrollBar

The constructor for a JScrollBar has the following parameters

  • Orientation
  • Initial value
  • Size of the indicator
  • Minimum value
  • Maximum value

JScrollBar scrollbar = new JScrollBar(JScrollBar.HORIZONTAL, 10, 0, 1, 20);

slide24

Swing Components

JPanel

A JPanel is a component capable of holding other components. It is used as:

  • A surface for drawing text or shapes
  • A container for grouping components

A JPanel may have its own Layout Manager (different from the Layout Manager used for the ContentPane in which it resides).

A JPanel object is transparent. It will show the color of the container in which it resides.

JPanel objects will be used extensively to group components for placement purposes when we discuss Layout Managers in the next lecture

slide25

Review

To review the swing components discussed in this lecture, we again refer to the applet below. Refer to the applet code to observe the effect of each statement. Be sure you understand how the picture of the components on the applet corresponds to the code.

Display of common swing components