Swing Word document - kbucaria.com

paltryboarpigSoftware and s/w Development

Nov 3, 2013 (4 years and 8 months ago)






The following lesson will answer the following questions.

1.What is an object of the class JFrame?

2.What are some of the built
in methods of JFrame?

3.What is the content pane? Is it necessary for the programmer to

4.What does it mean in event driven programming that the programmer
does not determine the order in which things happen?

5.Why is it necessary to have the class WindowDestroyer?

6.When is setVisible( ) needed?

7.What are the steps to add a
label to a frame?

FirstSwingDemo.java demonstrates the Jlabel, JFrame components of a
Swing program.

1 import javax.swing.*;

2 import java.awt.*;

3 public class FirstSwingDemo

4 {


public static final int WIDTH = 500;


public static final

int HEIGHT = 400;

7 public static void main (String [] args)




JFrame myWindow = new JFrame();


myWindow. setSize( WIDTH,HEIGHT);



JLabel myLabel = new JLabel( "Please don't eat the


Container contentPane = myWi
ndow.getContentPane ();




WindowDestroyer listener = new WindowDestroyer();


myWindow.addWindowListener( listener);//listener is the

//to be notified when the event


myWindow. setVisible ( true);



18 }

// the following is needed for the above program










windowClosing (WindowEvent e)






After compiling and running FirstSwingDemo.java add a second label
called secondLabel to the program, stating " I don't like to eat daisies"

Compile and run.

The original label is overwritten? In order to have two labels, it is
ecessary to set a layout for the content pane.


is a simple component capable of displaying text or an icon,
and does not have a border. No actions are associated with a JLabel, as
there are with buttons. A JLabel is just a label.

What is necessa
ry to import for programs with Swing?

line 1 of the code above states that the program uses the Swing library
and this is to be imported for each program using Swing.

line 2 states that the program uses the abstract window toolkit awt.


On line 9,

myWindow is an object of the class JFrame. A JFrame in
Swing is a window. It is a simple window with a border, a place for a
title and the close
window button.

Setting the size of a JFrame?

On line 10, setSize is a method of the class JFrame, and sets t
he size of
the window to the declared constants.

What is a content pane?

In addition to a border, title, and a close
window button, every JFrame
has a content pane. This is the "inside" of the JFrame. Components are
added directly to the content pane, not

the JFrame.

On line 12, Container contentPane = myWindow.getContentPane ( )
accesses the content pane and has the variablecontentPane refer to it.

On line 13, the contentPane.add( myLabel ) method will add myLabel to
the content pane. getContentPane( )
and add( ) are methods of Container



line 16 calls the method setVisible. If false were the parameter, the
FirstSwingDemo would never have its JFrame displayed.

Closing a window?

The JFrame has the close
window button installed. Unless w
e associate
the actual closing of the window with the close
window button, we will
not be able to close the window. Closing the window is an excellent
example of event
driven programming. It is an event waiting to happen.
When the user mouse
clicks the 'x'

of the close
window button, the
window is expected to close.

addWindowListener( ) is a method from the JFrame class. It is necessary
to create a listener object of WindowDestroyer and then add this listener
to myWindow. WindowDestroyer is not a built
class. It is inherited
from WindowAdapter. An object, like listener that receives events from
an object is called a listener. Associating the listener with the object it is
listening to is called registering the listener.

line 14 creates the object listen
er and

line 15 registers the listener with myWindow.

The method windowClosing( ) of the class WindowAdapter(see below)
already connects the mouse
click on the close
window button to close the
window, but we wish also to terminate the program. That is why

override windowClosing( ) and add System.exit( 0 ) to the method
windowClosing( ).

The import statement import java.awt.event.*; is needed because that is
where WindowAdapter and WindowEvent are

defined. The System.exit( 0 ) statement will return us t
o the operating


The class for WindowDestroyer is as follows and must be added to all
Swing projects

import java.awt.*;

import java.awt.event.*; // for java.awt.event.WindowAdapter and

// jav

public class WindowDestroyer extends WindowAdapter


public void windowClosing( WindowEvent e )


System.exit( 0 );



Driven Programming?

The programs in this lab are all examples of event driven p
An event in a gui (graphical user interface) is an object that represents
some actions such as clicking a mouse, dragging the mouse, pressing a
key, clicking the close
window button or any other action that is expected
to elicit a response. Whe
n an object generates an event, that is called
firing the event. You the programmer have defined listener objects for the
events. That is, you tell the object from which events may emerge which
other objects it is no notify with specific kinds of occurrenc
es. These
other objects awaiting notification are "listeners." A listener object has
methods that specify what will happen with particular notifications.
These are coded by overriding inherited stubs. These methods that handle
events are called event handl
ers. You the programmer create objects that

fire events, and listener objects that react to the events, but you do not
determine the order in which things happen. The events determine the
order. The event
driven programming that we will be doing makes
nsive use of inheritance.

Methods in the class JFrame are:

JFrame( ),

JFrame( String title ),

addWindowListener( WindowListener e ),

setSize( int width, int height ),

setVisible( boolean b ),


show( ) will bring that particular window to the front when the
re are
several Frames on the screen,

setTitle( String title ),

setForeground( Color c ), Color is covered later

setBackground( Color c ),

setLocation( int x, int y )

Container getContentPane( ) returns the content pane object of the
JFrame and its return
ed type is Container.



Topic II

Windows and The Color class


The following lesson will answer the following questions.

1.Why are you permitted to have two methods or constructors with the
same name?

2.Where is Color clas
s found and how is it used.


import java.awt.*; // needed for the Color class

public class SecondWindowDemo


public static void main ( String [ ] args)


SecondWindow window1 = new SecondWindow( );


// SecondWindow window2 = new SecondWindow(Color.pink);

// window2.setVisible ( true);




import javax.swing.*;

import java.awt.*; // needed for the Color and Container class

public class SecondWindow extends JFrame


public static final int WIDTH = 550;

public static final int HEIGHT = 400;


public SecondWindow()




Container contentPane = getContentPane ();

el label = new JLabel ( "Now available in color.");


setTitle("Second Window");

contentPane.setBackground (Color.blue);

addWindowListener(new WindowDestroyer());


blic SecondWindow(Color customColor)




Container contentPane = getContentPane ();

JLabel label = new JLabel ( "Now available in color.");


setTitle("Second Window");

contentPane.setBackground (customColor);

addWindowListener(new WindowDestroyer());





Create a project and attach the files SecondWi

There are two constructors for SecondWindow, one the default, the other
accepts a color parameter.

Why are there two classes?

With having created two classes, we are able to declare many objects
of the Se
condWindow class. The class SecondWindow extends JFrame,
and therefore inherits all the methods of class JFrame. This is the normal
way to define a window interface.

In class SecondWindow, on lines 9 and 20, super( ) calls the
constructor for the par
ent class JFrame. Sometimes this is

necessary and is responsible for the behind the scenes initializations for
the objects of type JFrame. This is not necessary when no information


needs to be passed to the super class's constructor (i.e. when the no
ent constructor is the constructor of choice.) It is necessary where
there is a need to pass one or more arguments. The call to super( ) must
be the first statement in the derived class's constructor.

On line 16, the nameless object for WindowDestroyer ()
. Nameless
objects like these are termed "anonymous" objects.

addWindowListener( new WindowDestroyer( ) );

is equivalent to the following

WindowDestroyer listener = new WindowDestroyer( );

addWindowListener( li
stener );

There is no need to name the object, since we will not be referring to
it again.

Where should the setVisible command be written, now that there
are have two classes?

The setVisible( ) command is usually written in the main( ), a
nd not in
the constructor. Look for it in SecondWindowDemo.

How many colors are available?

Color is the name of the class and the following are constants:
Color.black, Color.blue, Color.cyan, Color.darkGray, Color.gray,
Color.green, Color.light
Gray, Color.magenta, Color.orange, Color.pink,
Color.red, Color.white, Color,yellow. Alternatively, you can create colors
with your own RGB intensities. Each of the color constants is an object.
You can get your own color with: new Color ( red, green, blue

) where
red, green, and blue are integers within the range of 0..255.

What is needed to use Color in a Swing program?

java.awt.*; must be imported to use the Color class

Presently, the first constructor is executed and a blue window

Remove the comment lines from lines 8 and 9, compile and run. What
happened to the blue window? The pink window is on top of the blue
window. Drag the second one away from the first.



Swing Layouts



The f
ollowing lesson will show the demonstrate the different layouts of
the Jframe class.


1 import javax.swing.*;

2 import java.awt.*;


*Simple demonstration of using
a layout manager to arrange labels.


3 public class BorderLayoutDemo extends JFrame

4 {

5 public static final int WIDTH = 300;

6 public static final int HEIGHT = 200;

7 p
ublic static void main(String[] args)

8 {

9 BorderLayoutDemo gui = new BorderLayoutDemo();

10 gui.setVisible(true);

11 }

12 public BorderLayoutDemo()

13 {

14 setSize(WIDTH, HEIGHT);

15 addWindowListener(new WindowDe

16 setTitle("Layout Demonstration");

17 Container content = getContentPane();

18 content.setLayout(new BorderLayout());

19 JLabel label1 = new JLabel("Please don't eat the daisies.");

20 content.add(label1
, BorderLayout.NORTH);

21 JLabel label2 = new JLabel("I don't like to eat daisies.");

22 content.add(label2, BorderLayout.CENTER);

23 JLabel label3 = new JLabel("A host of golden daffodils! ( or



content.add(label3, BorderLayout.SOUTH);

25 }

26 }


Make a project called BorderLayoutDemo.java. Make the project and

How are all the components arranged on the JFrame? A layout
manager is created to arrange compone
nts on the JFrame. Three different
layout managers are:



which has 5 regions: NORTH,

WEST,CENTER,EAST and SOUTH. The BorderLayout is the default
layout manager for JFrame, likewise for JPanel and JApplet. The
CENTER section is much larger th
an the others.


adds the components one after another from left to
right. No second parameter is needed in the add statement.
FlowLayout is the default for Applet.

3. The

arranges components in rows and columns. The
for this layout needs the number of rows and columns for the
grid. e.g. aContainer.setLayout( new GridLayout( 2, 2 ) ); Components
will be added to the next grid automatically.


Change the code so that the FlowLayout is displayed on line 18. Remove
the sec
ond parameters from the add statements on lines 22, 23 and 24.
Compile and run.

On line 18, change the code so that you test GridLayout, with a size of
2,2. Compile and run. You may need to extend the output window by
dragging the right side to the right
to see the entire text.

Three other layouts are BoxLayout, CardLayout, and GridBagLayout.



Topic IV



The following lesson will answer the following questions.

1.Does Java allow for multiple inheritance?

2.What is an


3.When you implement ActionListener, is it necessary to have the
method actionPerformed( )? What if you don't want any action
performed, do you still need the method?

4.When you implement WindowListener, how many methods must you

5.What does it mean to add the "action listener"?

6.How does actionPerformed( ) get activated. There is no code calling


1 import javax.swing.*;

2 import java.awt.event.*;

3 import java.awt.*;

4 public class ButtonDemo ext
ends JFrame implements ActionListener

5 {

6 public static final int WIDTH = 300;

7 public static final int HEIGHT = 200;

8 public static void main(String[] args)

9 {

10 ButtonDemo buttonGui = new ButtonDemo();

11 buttonGui.

12 }

13 public ButtonDemo()

14 {

15 setSize(WIDTH, HEIGHT);


16 addWindowListener(new WindowDestroyer());

17 setTitle("Button Demonstration");

18 Container contentPane = getContentPane ();

9 contentPane.setBackground(Color.blue);

20 contentPane.setLayout(new FlowLayout());

21 JButton stopButton = new JButton("Red");

22 stopButton.addActionListener(this);

23 contentPane.add(stopButton);

24 JButton g
oButton = new JButton("Green");

25 goButton.addActionListener(this);

26 contentPane.add(goButton);

27 }

28 public void actionPerformed(ActionEvent e)

29 {


Container contentPane = getContentPane ();

31 if (

32 {

33 contentPane.setBackground(Color.red);

34 }

35 else if (e.getActionCommand().equals("Green"))

36 {

37 contentPane.setBackground(Color.green);

38 }

39 else

40 System.out.println ( "Error in button interface." );


42 }



Create a project for ButtonDemo.java

Compile and run the project. Click on the red and green buttons
alternatively and watch what


How do we associate an action (like the changing of color) with the
clicking on of a button?


ButtonDemo inherits the class JFrame but also implements

This interface ActionListener is as close to multiple inheritance as Java
ts. ActionListener is not a class, but is a property that you can give to
any class, to give it an additional identity as a type. Objects of any class
that implements the ActionListener interface can be referenced by a
variable of type ActionListener.

A button fires event objects of type ActionEvent, which are handled
by listeners known as ActionListeners. To make a

class into an ActionListener, you must

1. Add the phrase implements ActionListener at the end of the class
line (as on line 4)

2. Define a method named actionPerformed( ). (as on line 28)

You may be discouraged from using other classes as interfaces
because all the methods must be specified for the interface.
ActionListener only has one method, while WindowListener has s

On lines 15
19 in the constructor are the usual calls to methods of the
class JFrame

On line 20 a layout for the placement of the buttons is set.

The unnamed object is created in the parameter of setLayout( ).

On line 25 the class Button
Demo is itself the listener class for the buttons
inside of ButtonDemo. That is why on line 25 the parameter that is sent
by addActionListener is "this". Line 25 adds the goButton to the

How does

) work?

O lines 28
42, as you click on either the Red or Green button an
ActionEvent is sent to the action listener of that button. More
specifically, the button calls the actionPerformed( ) method in the
registered listener passing to it the ActionEvent. When the formal
rameter of actionPerformed( ) is always an ActionEvent. The code for


actionPerformed( ) decides what action to take. getActionCommand( )
returns the string label on the button, that was determined in the
instantiation statement (lines 21 and 24).

Please note that we named the stopButton "Red", the "Red" became
the default action command which was retrieved in getActionCommand(
). If you wanted a different name for the action associated with the
stopButton, you may use the method setActionCommand.


Jbutton stopButton = new Jbutton( "Red" );

stopButton.setActionCommand ( "Stop");

Therefore, a button may have a name that is different from its action

Student Task: Create another button that says Caution and have the frame

painted yellow when the caution button is pressed.





The following lesson will answer the following questions.

1.How come line 21 doesn't set the whole JFrame to blue when the first
JFrame appears?

2.Why i
sn't the entire JFrame changing to either red or green? Answer
this question referring to the code.

3.On what line of code is the buttonPanel created?

4.What is the layout of the buttonPanel?

5.Where is the buttonPanel placed? What line of code does tha

6.How many buttons are placed in the buttonPanel?

7.On line 37 a new JPanel is created. What is the name of that JPanel?

8.On what line of code is an object created for JTextArea, and what is it

9.Which line of code stores the action that a
button is clicked?

10.Explain the difference between the Save Memo 1 button and the Get
Memo 1 button.

Create a project for PanelDemoTwo.java Compile and run. If you click
on a button again, the color switches back and forth between the original

and the chosen color.


1 import javax.swing.*;

2 import java.awt.*;

3 import java.awt.event.*;

4 /*Simple demonstration of placing several panels within the content pane. */

5 public class PanelDemoTwo extends JFrame implements ActionListener

6 {

7 public static final int WIDTH = 300;

8 public static final int HEIGHT = 200;

9 private JPanel firstPanel,secondPanel;

10 public static void main(String[] args)

11 {

12 PanelDemoTwo guiWithPanel = new PanelDemoTwo();



14 }

15 public PanelDemoTwo()

16 {

17 setSize(WIDTH, HEIGHT);

18 addWindowListener(new WindowDestroyer());

19 setTitle("Panel Demonstration");

20 Container contentPane = getCon
tentPane ();

21 contentPane.setBackground(Color.blue);

22 contentPane.setLayout (new GridLayout () );

23 firstPanel = new JPanel ();

24 firstPanel.setBackground (Color.white);

25 secondP
anel = new JPanel ();

26 secondPanel.setBackground ( Color.gray);

27 JButton stopButton = new JButton("Red");

28 stopButton.setBackground(Color.red);

29 stopButton.addActionListener(this);

30 firstPanel.add(stopBu

31 JButton goButton = new JButton("Green");

32 goButton.setBackground(Color.green);

33 goButton.addActionListener(this);

34 secondPanel.add(goButton);

35 contentPane.add(firstPanel);

36 contentPa

37 }

38 public void actionPerformed(ActionEvent e)

39 {

40 if (e.getActionCommand().equals("Red"))

41 {


if (firstPanel.getBackground() .equals (Color.white ))

43 firstPanel.setBack

44 else


firstPanel.setBackground (Color.white );

46 }

47 else if (e.getActionCommand().equals("Green"))

48 {


if ( secondPanel.getBackground ().equals (Color.gray) )



51 else


secondPanel.setBackground ( Color.gray);

53 }

54 else

55 System.out.println ( "Error in button interface.");

56 }

57 }


How many panels can be added to a JFrame?

What is different about this program from the previous button demo?
Two panels are created and a button is placed in each panel. The class
JPanel is a container class that does little more than group objects. A

JPanel object is an area of the screen into which you put other objects,
such as buttons and labels. It is true that you can place buttons on the
screen without having a panel in each of the five locations of the
BorderLayout. But suppose that you wanted
to place two buttons in the
SOUTH position. What you can do is to create a JPanel for the SOUTH
position after placing the two buttons in there. You may have multiple
JPanels in a frame. In fact, multiple JPanels may be added to a JPanel,
and each one may

have its own explicitly specified layout manager. This
program creates two JPanels

firstPanel on line 23 and secondPanel on
line 25.

On lines 17
19 the methods are referring to the JFrame line 18 as before
adds the unnamed object of class WindowDestroy
er as a window listener.

Lines 20
22 deal with the contentPane, setting its color and layout.


Lines 23
36 deal with creating two Panels, and adding a button to each

Notice the difference in adding to a JFrame versus adding to a JPanel.
With a JFra
me, you first get the contentPane with getContentPane( ) as
on lines 20 and 21 before you setBackground( ) color or add to it as on
lines 35 and 36. To add to a JPanel, you may just use the method add( )
as on line 30; there is no need to worry about a co

Add a third panel to the content pane with a caution button that will turn
that panel yellow, when the button is pressed. Notice that the panels are
declared on line 9.

You can add one JPanel to another JPanel using add( ). With a hierarchy
f panels, you can create any sort of arrangement inside of a GUI.




In the previous programs, the program created and printed the text. How
can we get text from the keyboard?

JTextArea is a built
in class that provides for key
board input.

Create a project for MemoSaver.java Compile and run the project.

1 import javax.swing.*;

2 import java.awt.*;

3 import java.awt.event.*;

4 public class MemoSaver extends JFrame implements ActionListener

5 { public static final int W
IDTH = 600;

6 public static final int HEIGHT = 300;

7 public static final int LINES = 10;

8 public static final int CHAR_PER_LINE = 40;

9 private JTextArea theText;

10 private String memo1 = "No Memo 1.";

11 private String me
mo2 = "No Memo 2.";

12 public MemoSaver()

13 { setSize(WIDTH, HEIGHT);

14 addWindowListener(new WindowDestroyer());

15 setTitle("Memo Saver");

16 Container contentPane = getContentPane();

17 contentPane.setLayout(new

18 JPanel buttonPanel = new JPanel();

19 buttonPanel.setBackground(Color.white);

20 buttonPanel.setLayout(new FlowLayout());

21 JButton memo1Button = new JButton("Save Memo 1");

22 memo1Button.addActionL

23 buttonPanel.add(memo1Button);

24 JButton memo2Button = new JButton("Save Memo 2");

25 memo2Button.addActionListener(this);

26 buttonPanel.add(memo2Button);

27 JButton clearButton = new JButton("Clear")

28 clearButton.addActionListener(this);

29 buttonPanel.add(clearButton);

30 JButton get1Button = new JButton("Get Memo 1");

31 get1Button.addActionListener(this);

32 buttonPanel.add(get1Button);

33 JButton get2
Button = new JButton("Get Memo 2");

34 get2Button.addActionListener(this);

35 buttonPanel.add(get2Button);

36 contentPane.add(buttonPanel, BorderLayout.SOUTH);

37 JPanel textPanel = new JPanel();

38 textPanel.setBackgro

39 theText = new JTextArea(LINES, CHAR_PER_LINE);

40 theText.setBackground(Color.white);


41 textPanel.add(theText);

42 contentPane.add(textPanel, BorderLayout.CENTER);

43 }

44 public void actionPerformed(A
ctionEvent e)

45 { String actionCommand = e.getActionCommand();

46 if (actionCommand.equals("Save Memo 1"))

47 memo1 = theText.getText();

48 else if (actionCommand.equals("Save Memo 2"))

49 memo2 = theText.getText(

50 else if (actionCommand.equals("Clear"))

51 theText.setText("");

52 else if (actionCommand.equals("Get Memo 1"))

53 theText.setText(memo1);

54 else if (actionCommand.equals("Get Memo 2"))

55 theTex

56 else

57 theText.setText("Error in memo interface");

58 }

59 public static void main(String[] args)

60 { MemoSaver guiMemo = new MemoSaver();

61 guiMemo.setVisible(true);

62 }



You may expand the output screen width
wise by dragging on the right
hand edge of the window and expanding the window to the right.

You may type anywhere in the white textbox. After you type a message,
click on Save Memo 1 or Save Memo 2. Then c
lick on Clear. To retrieve
the message, click on the appropriate Get Memo 1 or Get Memo 2.

Experiment by placing the message anywhere in the textbox.

It is interesting how the buttons are all placed in one panel before being
added to the contentPane.

dd a button called CONCATENATE to the button panel so that the
message from Memo1 is concatenated to Memo2. You must change the
code in actionPerformed( ) to test if the concatenate button is pressed,
and perform the concatenation.

The parameters (LINES
, CHAR_PER_LINE) in the instantiation
statement on line 39 state that the JTextArea is 10 lines long and 40
characters wide. The text area has its own scroll bars, and you are
permitted to type past the width of the box, but a very long line cannot be
n at once.

Methods associated with JTextArea are setBackground( ), getText( ) and
setText( ). getText( ) retrieves the text in the JTextArea, while setText( )
stores the text in the JTextArea.

There are three private instance variables on lines 9
11. The
se may be
accessed by any method in the class.

Notice on line 45 in method actionPerformed( ), a local String variable
actionCommand is used to store the e.getActionCommand( ). This is
done so that e.getActionCommand does not have to be repeated four



JPanel, JLabel, JtextFields


The following lesson will answer the following questions.

1.Which line of code creates the first object of class JPanel? What is the
JPanel's name?

2.Which line of code creates the JLabel?

3.How does the JLabel gets its wording?

4.On what lines are the JTextFields and JLabels added to the JPanel?

5.On what line of code is the JPanel added to the content pane?

6.What is the second panel in this program?

7.Why does this second panel need

an action listener, but not the first ?

8.Was there a certain layout for adding the panels to the content pane?

There is a class called JTextField. It is different from JTextArea in that
JTextField can only store one line of text, but the number of char
on the line can be sent to the constructor. JTextFields are discussed in
Section VII.

If you wish for the characters on a line to wrap around and continue on
the next line, use this line of code:

theText.setLineWrap( true );

If you don't wa
nt the user to be able to change the text in a JTextArea,
use this code:

theText.setEditable( false ); (The default in both cases is true.)


Label and TextField Demo

1 import javax.swing.*;

2 import java.awt.*;

3 import java.awt.event.*;


public class LabelDemo extends JFrame implements ActionListener

5 {

6 public static final int WIDTH = 300;

7 public static final int HEIGHT = 200;

8 private JTextField name;

9 public LabelDemo()

10 {

11 setTitle("Name Test

12 setSize(WIDTH, HEIGHT);

13 addWindowListener(new WindowDestroyer());

14 Container content = getContentPane();

15 content.setLayout(new GridLayout(2, 1));

16 JPanel namePanel = new JPanel();

17 namePanel.s
etLayout(new FlowLayout());

18 namePanel.setBackground(Color.lightGray);

19 name = new JTextField(20);

20 namePanel.add(name);

21 JLabel nameLabel = new JLabel("Enter your name ");

22 namePanel.add(nameLabel);



24 JPanel buttonPanel = new JPanel();

25 buttonPanel.setLayout(new FlowLayout());

26 JButton b = new JButton("Test");

27 b.addActionListener(this);

28 buttonPanel.add(b);

29 b = new JButto

30 b.addActionListener(this);

31 buttonPanel.add(b);

32 content.add(buttonPanel);

33 }

34 public void actionPerformed(ActionEvent e)

35 {

36 if (e.getActionCommand().equals("Test"))

37 name.setTe
xt("A very good name!");

38 else if (e.getActionCommand().equals("Clear"))

39 name.setText("");

40 else

41 name.setText("Error in window interface.");

42 }

43 public static void main(String[] args)

44 {


LabelDemo w = new LabelDemo();


46 w.setVisible(true);

47 }

48 }

Make a project for LabelDemo.java Compile and run.


Sometimes you want to label text field, especially if there are two text
fields for two different inputs.
Access LabelDemo.java, and run the
program. After typing in your name, press test and clear. Notice that the
program doesn't do too much!!! The process is to create an object of class
JLabel, create a JTextField, add the JLabel and JTextField to the same
JPanel and then add the JPanel to the contentPane, which is just called
content in this program. By adding the JLabel and JTextField to the same
panel, and declaring its layout, the programmer can control the placement
of JLabel with respect to the JTextFi

Add a JTextField called university on line 8. It is necessary to declare the
references for the JTextFields as private instance variables so that all
methods, especially actionPerformed( ) will have access to them. Add it
to the namePanel.

Add a JL
abel called universityLabel which states "Enter your university
here". Add it to the namePanel.

After line 37, add a line of code which will set the text for university to
say " A very good university!" when the e.getActionCommand( ) equals


line 39, add a line of code which will set the text for university to a
String of length 0 (i.e. "") when e.getActionCommand( ) equals "Clear".




Make a project for Adder.java

1 import javax.swing

2 import java.awt.*;

3 import java.awt.event.*;

4 public class Adder extends JFrame implements ActionListener

5 {

6 public static final int WIDTH = 400;

7 public static final int HEIGHT = 200;

8 private JTextField inputOutputField;

private double sum = 0;

10 public static void main(String[] args)

11 {

12 Adder guiAdder = new Adder();

13 guiAdder.setVisible(true);

14 }

15 public Adder()

16 {

17 setTitle("Adding Machine");

18 addWindowListener
(new WindowDestroyer());

19 setSize(WIDTH, HEIGHT);

20 Container contentPane = getContentPane();

21 contentPane.setLayout(new BorderLayout());

22 JPanel buttonPanel = new JPanel();

23 buttonPanel.setBackground(Color.gray)

24 buttonPanel.setLayout(new FlowLayout());

25 JButton addButton = new JButton("Add");

26 addButton.addActionListener(this);

27 buttonPanel.add(addButton);

28 JButton resetButton = new JButton("Reset");

29 re

30 buttonPanel.add(resetButton);

31 contentPane.add(buttonPanel, BorderLayout.SOUTH);

32 JPanel textPanel = new JPanel();

33 textPanel.setBackground(Color.yellow);

34 textPanel.setLayo
ut(new GridLayout());

35 inputOutputField = new JTextField();

36 inputOutputField.setBackground(Color.white);

37 textPanel.add(inputOutputField);

38 JLabel enterLabel = new JLabel ( "Click, and enter numbers to the
left" );



40 contentPane.add(textPanel, BorderLayout.CENTER);

41 }

42 public void actionPerformed(ActionEvent e)

43 {

44 if (e.getActionCommand().equals("Add"))

45 {

46 sum = sum +


47 inputOutputField.setText(Double.toString(sum));

48 }

49 else if (e.getActionCommand().equals("Reset"))

50 {


51 sum = 0;

52 inputOutputField.setText(

53 }

54 else

55 inputOutputField.setText("Error in adder code.");

56 }

57 private static double stringToDouble(String stringObject)

58 {

59 return Double.parseDouble(stringObject.trim());

60 }

61 }

Compile and run the program a few times. Click in the white textfield,
place a number in the textField, then click on Add In or Reset.

This program could be
by having two text fields; one for input
to store the last number in
putted and one for output to store the sum.

Save the program as AdderTwo.java

You will need to change a few lines of code

a. change it to public class AdderTwo on line 4

b. AdderTwo guiAdder = new AdderTwo( ); on line 12

c. public AdderTwo( ) // on
line 15 in the constructor



We need to have two textFields instead of one, so that one is used for
input and the other for output to store and display the sum.

Change the present inputOutputField to just inputField on line 8, as well
as inside of the

constructor on lines 35, 36, and 37. Change the
accumulating statement inside of actionPerformed( ) on line 46 to
getText( ) from the inputField only.

Create a new JTextField for outputField, declare it after line 8. After line
37, inside of the construc
tor, instantiate the outputField. (Similar to the
creation of inputField.) Set its background color to lightGray and add it
to the textPanel. In actionPerformed( ), change the three setText( )
commands on lines 47, 52, and 55 to outputField, not inputOutpu

Save, compile, and run AdderTwo.

The code is below to AdderTwo.

mport javax.swing.*;

import java.awt.*;

import java.awt.event.*;


*GUI for totaling a series of numbers.


public class AdderTwo extends JFrame implements ActionListener


public static final int WIDTH = 400;

public static final int HEIGHT = 200;

//private JTextField inputOutputField;

private JTextField inputField;

private JTextFie
ld outputField;

private double sum = 0;

public static void main(String[] args)


AdderTwo guiAdder = new AdderTwo();



public AdderTwo()


setTitle("Adding Machine");


indowListener(new WindowDestroyer());


Container contentPane = getContentPane();

contentPane.setLayout(new BorderLayout());

JPanel buttonPanel = new JPanel();


buttonPanel.setLayout(new FlowLayout());

JButton addButton = new JButton("Add");



JButton resetButton = new JButton("Reset");



contentPane.add(buttonPanel, BorderLayout.SOUTH);

JPanel textPanel = new JPanel();


textPanel.setLayout(new GridLayout

inputField = new JTextField();



outputField=new JTextField();



JLabel enterLabel = new JLabel ( "Click, and enter numbers to the left" );


contentPane.add(textPanel, BorderLayout.CENTER);


public void actionPerformed(ActionEvent e)


if (e.getActionCommand().equals("Add"))


sum = sum +




else if (e.getActionCommand().equals("Reset


sum = 0;




outputField.setText("Error in adder code.");



private static double stringToDouble(String stringObject)


return Double




Programming Assignments With Swing

Write Swing programs that would produce each of the above


Programming Assignments With Swing

Write a swing progr
am that will convert Fahrenheit to Celcius and
vice versa. The conversion will depend on which button is clicked.




Mary C. Courtney

Pace University Computer Science
Department. Some of her JAVA AB course materials were
adapted with permi
ssion for this curriculum.


Horstman, Cay, Computing Concepts with Java 2 Essentials:
John Wiley & Sons, 2000.


Litvin, Maria& Gary, Java Methods

An Introduction to
Oriented Programming: Skylight Publishing, 2001


Neumaier, Diane, ed. Reframing
s: New American Feminist



Temple University Press. Philadelphia. 1995.