Week 13—11/29/11) Understanding components

slimwhimperΛογισμικό & κατασκευή λογ/κού

3 Νοε 2013 (πριν από 3 χρόνια και 5 μήνες)

55 εμφανίσεις

Chapter 13

Understanding
Swing Components

ISQS 6337


Jim Burns


Using the JFrame Class


There are lots of other UI components,
such as buttons, check boxes, and menus
that are included in the JFrame Class


In this chapter you will learn how to add
these UI components to applets and
applications


Such Swing components as JButton,
JLabel are easy to use

To use these JFrame UI Components…


You insert the import statement

import javax.swing.*;

at the beginning of your Java program files




About Swing components


Most Swing components are said to be
lightweight

because they do not rely upon
methods that are part of the operating
system


An exception is the JFrame component
because it does require interaction with the
local operating system, so it is a
heavyweight

component

More about Swing components…


You usually place them in containers


A container is a type of component that
holds other components so you can treat a
group of them as a single entity


You usually create a JFrame so that you
can place other objects within it for display.

JFrame Inheritance Hierarchy


Java.lang.Object


Java.awt.Component


Java.awt.Container


Java.awt.Window


Java.awt.Frame



javax.swing.JFrame

JFrame Constructors


JFrame()

constructs a new frame that
initially is invisible and has no title


JFrame(String title)

creates a new, initially
invisible
JFrame

with the specified title


JFrame(GraphicsConfiguration gc)

creates
a
JFrame

in the specified
GraphicsConfiguration

of a screen device
with a blank title


JFrame(String title, GraphicsConfiguration
gc)

creates a
JFrame

with the specified title
and the specified
GraphicsConfiguration

of
a screen

Constructing a
JFrame


You do this just as you would any other other
object instantiated from a conventional class


JFrame firstFrame = new JFrame(“Hello”);


JFrame secondFrame = new JFrame();


After you create a
JFrame

object, you can use the
now
-
familiar object
-
dot
-
method format you have
used with other objects to call methods that
maniuplate a
JFrame
’s features


Methods in the JFrame class


void setTitle(String)


void setSize(int, int)


void setSize(Dimension)


string getTitle()


void setResizable(boolean)


boolean isResizable()


void setvisible(boolean)


void setBounds(int, int, int, int)


Examples of method usage…

firstFrame.setSize(200, 100);

firstFrame.setTitle(“My frame”);


The JFrame1 application

import javax.swing.*;

public class JFrame1

{


public static void main(String[] args)


{


JFrame aFrame = new JFrame("First frame");


aFrame.setSize(200,100);


aFrame.setVisible(true);


}

}

The code in the slide above…


Creates a small empy JFrame


This window has all the behaviros of any
conventionial window

can change the
frame’s size by dragging its border, can
reposition the frame by dragging the title
bar, can Minimize, Maximize or Restore,
and Close with buttons in the title bar of the
frame’s upper
-
right corner and a menu
under the icon in the upper
-
left corner

The JFrame2 class

import javax.swing.*;

import java.awt.*;

public class JFrame2

{


public static void main(String[] args)


{


final int FRAME_WIDTH = 200;


final int FRAME_HEIGHT = 100;


JFrame aFrame = new JFrame("Second frame");


aFrame.setSize(FRAME_WIDTH, FRAME_HEIGHT);


aFrame.setVisible(true);


aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


JLabel label = new JLabel("Hello");


Container con = aFrame.getContentPane();


con.setLayout(new FlowLayout());


con.add(label);


}

}

Customizing a JFrame’s Appearance


Items like an icon in the upper
-
left title bar
and the minimize, maximize and close
buttons are known as
window decorations


Window decorations

are supplied by the
operating system


However, you can request that Java’s
look
and feel

provide the decorations

A JFrame’s Look and Feel


Optionally, you can set a JFrame’s look
and feel using the


setDefaultLookandFeelDecorated()

method


Use of this is shown in the next program

import javax.swing.*;

import java.awt.*;

public class JFrame3

{


public static void main(String[] args)


{


final int FRAME_WIDTH = 200;


final int FRAME_HEIGHT = 100;


JFrame.setDefaultLookAndFeelDecorated(true);


JFrame aFrame = new JFrame("Third frame");


aFrame.setSize(FRAME_WIDTH, FRAME_HEIGHT);


aFrame.setVisible(true);


aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


JLabel label = new JLabel("Hello");


Container con = aFrame.getContentPane();


con.setLayout(new FlowLayout());


con.add(label);


}

}

Java’s Look and Feel


With the exception of the pink line, this
program is identical to the previous one


It generates a JFrame that looks as shown
below


This window avoids possible law suits
involving copyright infringement of the look
and feel of another firm



Extending the JFrame Class


You can instantiate a JFrame object in any
method you choose, including
main()

and
Init()

methods


Alternatively, you can create your own
class that descends from a JFrame class


The advantage of creating a child class of a
JFrame class is that you set the JFrame’s
properties within your object’s constructor
method; then, when you create your
JFrame child object, it is automatically
endowed with the features, such as size,
that you have specified

Using a child class of the JFrame
class…


Enables you to set properties such as the
size of the JFrame, whether the JFrame is
visible, and its look and feel


You do this all in the constructor of the child
class

The JMyFrame class

import javax.swing.*;

public class JMyFrame extends JFrame

{


final int WIDTH = 400;


final int HEIGHT = 120;


public JMyFrame()


{


super("This is my frame");


setSize(WIDTH, HEIGHT);


setVisible(true);


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


}

}

Look at the JMyFrame class above


The first statement in the constructor is the
super(“This is my frame”);


This statement calls the parent class’
constructor and sets the title in the title bar
to show
This is my frame


The CreateTwoJMyFrameObjects App

public class CreateTwoJMyFrameObjects

{


public static void main(String[] args)


{


JMyFrame myFrame = new JMyFrame();


JMyFrame mySecondFrame = new
JMyFrame();


}

}

The above code…


Creates two JMyFrame windows, both
identical, as each has the same set of
attributes



Using the JPanel Class


The simplest Swing container is the JPanel


It is a plain, borderless surface that can
hold lightweight UI components


import javax.swing.*;

import java.awt.*;

public class JFrameWithPanels extends JFrame

{


final int SIZE = 150;


JButton button1 = new JButton("One");


JButton button2 = new JButton("Two");


JButton button3 = new JButton("Three");


public JFrameWithPanels()


{


super("JFrame with Panels");


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


JPanel pane = new JPanel();


JPanel pane2 = new JPanel();


Container con = getContentPane();


con.setLayout(new FlowLayout());


con.add(pane);


con.add(pane2);


pane.add(button1);


pane.setBackground(Color.BLUE);


pane2.add(button2);


pane2.add(button3);


pane2.setBackground(Color.BLUE);


setSize(SIZE, SIZE);


setVisible(true);


}

}

JPanel Inheritance Hierarchy


Java.lang.Object


Java.awt.Component


Java.awt.Container


Java.swing.JComponent


Java.awt.JPanel

Create JFrame with Panels


public class CreateJFrameWithPanels


{



public static void main(String[] args)



{



JFrameWithPanels panel = new
JFrameWithPanels();



}


}

Understanding Swing Event Listeners


Classes that respond to user
-
initiated
events, such as button clicks, must
implement an interface that deals with, or
handles, the events.


These interfaces are called
event listeners
.


You first used these in chapter 9 when you
used the ActionListener interface with
JButton objects.


A class can implement as many listeners
as it needs.

User
-
initiated events


An event occurs every time a user clicks a
mouse or types a character


Listed below are some event listeners

Listener

Type of Events

Example

ActionListener

Action events

Button clicks

AdjustmentListener

Adjustment event

Scroll bar moves

ChangeListener

Change events

Slider is repositioned

FocusListener

Keyboard focus events

Text field gains or loses focus

ItemListener

Item events

Check box changes status

KeyListener

Keyboard events

Text is entered

MouseListener

Mouse events

Mouse clicks

MouseMotionListener

Mouse movement events

Mouse rolls

WindowListener

Window events

Window closes

Event Listeners


Any object can be notified of an event as
long as it implements the appropriate
interface and is registered as an event
listener on the appropriate event source



Components


Associated Listener
-
Registering
Methods

JButton, JCheckBox, JComboBox,
JTextField, and JRadioButton

addActionListener()

JScrollBar

addAdjustmentListener()

All Swing components

addFocusListener(),
addKeyListener(),
addMouseListener(),
addMouseMotionListener()

JButton, JCheckbox, JComboBox, &
JRadioButton

addItemListener()

All JWindow and JFrame components

Add WindowListener()

JSlider and JCheckbox

addChangeListener()

The format for a listener statement
is…

theSourceOfTheEvent.addListenerMethod
(theClassThatShouldRespond);



Note that you name the class that should respond
to the event as the only argument within ()


The class of the object that responds to an event
must contain a method that accepts the event
object created by the user’s action

In other words,…


When you register a component (such as a
JFrame) to be a listener for events
generated by another component (such as
a JCheckBox), you must write a method
that reacts to any generated event.


You cannot choose just any name for the
reacting methods

specific methods react
to specific events types, as listed below

Listener

Method

ActionListener

actionPerformed(ActionEvent)

AdjustmentListener

adjustmentValueChanged(adjustm
entEvent)

FocusListener

focusGained(FocusEvent) and
focusLost(FocusEvent)

ItemListener

itemStateChanged(ItemEvent)

Remember these three points….


When you declare a class that handles an
event, you create the class to either
implement a listener interface or extend a
class that implements a listener interface..


Example…

Public class MYFrame extends JFrame
implements ItemListener

And remember to ….


Register an instance of the event handler
class as a listener for one or more
components. For example,…

myCheckBox.addItemListener(this);

And…


Write a method that accepts the generated
event and reacts to it. For example:

Public void itemStateChanged(ItemEvent
event)

{

// code that executes when ever the event occurs

}

Notes….


If you fail to include an
actionPerformed()

method in a program that implements
ActionListener
, the program does not
compile


Still more notes…


If more than one component generates an
event, you usually want to figure out which
component generated the specific event, so
you decide which action to take



You can use the
getSource()

method to
determine the component that sent the event


The following
actionPerformed()

method
gets the source of the event and then
compares it to a
JButton

named
oneButton
,
which takes one action if the
JButton

is the
source of the event and a different action if
some other component is the source of the
event

The method described above follows

Public void actionPerformed(ActionEvent event)

{

Object source = event.getSource();

If(Source == oneButton)


// take some action

Else


// take some other action

}






Using the JCheckBox Class


A JCheckBox consists of a label postioned
beside a square


You click the square to display or remove a
check mark


This turns an option on or off


The code for an application that uses four
JCheckBoxes is shown below

import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

public class CheckBoxDemonstration extends JFrame implements
ItemListener

{


FlowLayout flow = new FlowLayout();


JLabel label = new JLabel("What would you like to drink?");


JCheckBox coffee = new JCheckBox("Coffee", false);


JCheckBox cola = new JCheckBox("Cola", false);


JCheckBox milk = new JCheckBox("Milk", false);


JCheckBox water = new JCheckBox("Water", false);


String output, insChosen;


JPanel panel = new JPanel();


Container con;


public CheckBoxDemonstration()


{


super("CheckBox Demonstration");


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


con = getContentPane();


con.add(panel);


panel.setLayout(flow);


label.setFont(new Font("Arial", Font.ITALIC, 22));


coffee.addItemListener(this);



cola.addItemListener(this);


milk.addItemListener(this);


water.addItemListener(this);


panel.add(label);


panel.add(coffee);


panel.add(cola);


panel.add(milk);


panel.add(water);


}


public static void main(String[] arguments)


{


final int FRAME_WIDTH = 350;


final int FRAME_HEIGHT = 120;

CheckBoxDemonstration frame =


new CheckBoxDemonstration();


frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);


frame.setVisible(true);


}


public void itemStateChanged(ItemEvent check)


{


// Actions based on choice go here


}

}


In the code above, the JLabel and
JCheckBox objects are added to a JPanel
and the JPanel is added to the Container
that serves as the content pane

Constructors for CheckBoxes

JCheckBox box 1 = new JCheckBox();


//No label, unchecked

JCheckBox box 1 = new JCheckBox(“Check here”);


//label, unchecked

JCheckBox box 1 = new JCheckBox(“Check here”,
false);


//label, unchecked

JCheckBox box 1 = new JCheckBox(“Check here”,
true);


//label, checked



Using the ButtonGroup Class


You use this when you want options to be
mutually exclusive


When you create aButtonGroup, you can
group several components, such as
JCheckBoxes are automatically turned off
when the user selects any one check box

Inheritance hierarchy for ButtonGroup


Java.lang.Object


Java.swing.ButtonGroup

To create a ButtonGroup and then add
a JCheckBox, you perform these steps:


Create a ButtonGroup:

ButtonGroup aGroup = new ButtonGroup();


Create a JCheckBox:

JCheckBox aBox = new JCheckBox();


Add aBox to aGroup:

aGroup.add(aBox);



Clearly, you have to add all of the individual
check boxes to the ButtonGroup with the
add()

method


It doesn’t make any difference which you
create first

Using the JComboBox Class


A JComboBox is a component that
combines two features

a display area
showing an option and a dropdown list box
containing additional options.

You can build a JComboBox …


By using a constructor with no arguments
and then adding items to the list with the
addItem() method

JComboBox majorChoice = new JComboBox();

majorChoice.addItem(“English”);

majorChoice.addItem(“Math”);

majorChoice.addItem(“Sociology”);



Creating JScrollPanes


Allows a pane to be scrolled when it is too
small to hold all of the content


Provides scroll bars along the side or
bottom of a pane, or both, so that the user
can scroll initially invisible parts of the pane
into view

Inheritance hierarchy of the
JScrollPane class


Java.lang.Object


Java.awt.Component


Java.awt.Container


Javax.swing.JComponent


Javax.swing.JScrollPane

There are four JScrollPane
constructors


JScrollPane()

creates an empty JScrollPane with
scroll bars when needed


JScrollPane(Component)

creates a JScrollPane
that displays the contents of the specified
component


JScrollPane(Component, int, int)

creates a
JScrollPane that displays the contents of the
specified component


JScrollPane(int, int)

creates a JScrollPane with
both vertical and horizontal scroll bar
specifications

import javax.swing.*;

import java.awt.*;

public class JScrollDemo extends JFrame

{


JPanel panel = new JPanel();


JScrollPane scroll = new JScrollPane(panel,


ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,


ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);


JLabel label = new JLabel("Event Handlers Incorporated");


Font bigFont = new Font("Arial", Font.PLAIN, 20);


Container con;


public JScrollDemo()


{


super("JScrollDemo");


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


con = getContentPane();


label.setFont(bigFont);


con.add(scroll);


panel.add(label);


}


public static void main(String[] args)


{


final int WIDTH = 180;


final int HEIGHT = 100;


JScrollDemo aFrame = new JScrollDemo();


aFrame.setSize(WIDTH, HEIGHT);


aFrame.setVisible(true);


}

}

Understanding When to Use
getContentPane()


When you use JAVA 5 or later, you are
allowed to add
Components

directly to
JFrames

and
JApplets

without explicitly
calling getContentPane()


You can also use the remove() and
setLayout() methods without an explicit call
to getContentPane()

import java.awt.*;

import javax.swing.*;

public class JFrameWithContentCall extends JFrame

{


final int SIZE = 180;


Container con = getContentPane();


JButton button = new JButton("Press Me");


public JFrameWithContentCall()


{


super("Frame");


setSize(SIZE, SIZE);


setVisible(true);


con
.setLayout(new FlowLayout());


con
.add(button);


}

}



JFrameWithContentCall Class

import java.awt.*;

import javax.swing.*;

public class JFrameWith
out
ContentCall extends JFrame

{


final int SIZE = 180;


JButton button = new JButton("Press Me");


public JFrameWith
out
ContentCall()


{


super("Frame");


setSize(SIZE, SIZE);


setVisible(true);


setLayout(new FlowLayout());


add(button);


}

}


JFrameWithoutContentCall class

The main class..calling the above

Public class TestFramesWithAndWithout

{


Public static void main(String[] args)


{


JFrameWithContentCall f1 = new

JFrameWithContentCall();


JFrameWithoutContentCall f2 = new

JFrameWithoutContentCall();


}

}


It is convenient that when you call add(button)
from within the JFrameWithoutContentCall class,
you do not have to create the container object con


In the newer versions of Java, in effect, you are
calling this.getContentPane().add(button), but you
are allowed to write the statement more simply.


The same is true for any calls to the setLayout()
and remove() methods

However…


When you want to do something other than
add(), setLayout(), or remove(),
the

JFrameWithoutContentCall

CLASS does
not work

it will compile and execute but it
will not do the thing you request, like
change the color of the background