Hmwk 19 Introduction to Graphical User Interfaces (GUI ) Tutorial

mammetlizardlickSoftware and s/w Development

Nov 3, 2013 (3 years and 7 months ago)

200 views

Hmwk 19 Introduction to Graphical User Interfaces (GUI )

Tutorial



Due: Beginning of class on Tuesday 7 April



Concepts



Graphical User Interfaces (GUIs)



Using the Java API



JOptionPane



JFrame



JLabel



GUI events



WindowListeners



Overview

This lab provides

a review of JOptionPanes and introduces you to the world of Graphical
User Interfaces (GUIs).



Description


This tutorial is a follow
-
instructions
-
and
-
answer
-
questions style exercise. You will have
to make extensive use of the Java API found at
http://java.sun.com/javase/6/docs/api/
.


Many of the answers can only be found by looking at this documentation.



Part 1

Basic graphical interface mechanisms are built into Java using the
AWT

package. This
p
ackage gives you basic functionality, but you still need to build much of the
functionality by hand. Built on top of
AWT

is
Swing
.
Swing

is a collection of commonly
used interface items built out of basic
AWT

tools.

The most fundamental Swing object is th
e
JOptionPane
.

This class brings up basic
dialog boxes, etc. Within
JOptionPane

is a static method
showMessageDialog()
.
Examine, compile and run the following bit of code:




import javax.swing.*;



public class GuiTest {


public static void main (String[] args) {


JOptionPane.showMessageDialog(null,"Input something,

and I'll " +


"repeat it","Intro",

JOptionPane.INFORMATION_MESSAGE);


System.e
xit(0);


}

}

Questions:

1.

Where does the dialog box appear on the screen?
It appears in the center of the
screen.
<found by running the program>

2.

What does the null in the first argument mean?
This parameter is the parent
frame component in which the dialo
g box will be placed. If it is null, then the
default Frame is used.
<found under the parentComponent of the Parameters
section>

3.

Name something with which we can replace
JOptionPane.INFORMATION_MESSAGE
.


If we do this, what is the difference?
We
could repl
ace
.INFORMATION_MESSAGE

with
ERROR_MESSAGE
,
WARNING_MESSAGE
,
QUESTION_MESSAGE

or
PLAIN_MESSAGE
.
<found under the
messageType of the Parameters section>
The
NFORMATION_MESSAGE
displays a
circular icon with an "I" in it.


If it is replaced by
ERROR_MESSAGE
,
then the icon
becomes a red hexagon with an "X" in it.


If it is replaced by
WARNING_MESSAGE
,
then the icon becomes a yellow triangle with an "!" in it. If it is replaced by
QUESTION_MESSAGE
, then the icon becomes a green square with an "?" in it. If it is

replaced by
PLAIN_MESSAGE
, then no icon is displayed.
<found by running the
program>

4.

What does
System.exit(0) do
? Hint: In the top left pane, click on
All
Classes

and then click on
System
in the bottom left pane.
It terminates the
currently running JVM an
d closes the dialog box once the user clicks on the "OK"
button.



Part 2

Another static method in
JOptionPane

is
showConfirmDialog()
. Examine, compile and
run the following bit of code:



import javax.swing.*;



public class GuiTest {



public static v
oid main (String[] args) {



JOptionPane.showMessageDialog(null,"Input something, and I'll repeat it",


"Intro",JOptionPane.INFORMATION_MESSAGE);



boolean notDone=true;



while (notDone) {





int i = JOptionPane.show
ConfirmDialog(null,"Are you done?", "",


JOptionPane.YES_NO_OPTION);





if (i==0) notDone = false;



}



System.exit(0);



}

}

Questions:

1.

How is the dialog box displayed by
showConfirmDialog()

different from
showMess
ageDialog
?

Instead of an "OK" button it has a "Yes" button and a
"No" button.

2.

What does
showConfirmDialog()

return for each of the user actions?
It returns
an integer based on what option was selected.


Yes returns 0 and No returns 1.
<You can get this by

examining the program’s while loop and printing the value
of i>

3.

What were some other choices for the fourth argument?


Hint: There are
actually three choices so look at all of the
showConfirmDialog()

examples.
The
other choices are
YES_NO_CANCEL_OPTION

an
d
OK_CANCEL_OPTION
.


There is also
the default option obtained by not including the last two parameters.


This will
automatically bring up the
YES_NO_CANCEL_OPTION
.



Part 3

The method
showInputDialog()

brings up a window for entering text. It returns a
St
ring
.



import javax.swing.*;



public class GuiTest {



public static void main (String[] args) {



JOptionPane.showMessageDialog(null,"Input something,

"


+

"
and I'll repeat it", "Intro",JOptionPane.INFORMATION_MESSAGE);



boolea
n notDone=true;



while (notDone) {





String s = JOptionPane.showInputDialog("Enter Something");





JOptionPane.showMessageDialog(null,s,"Repeat",JOptionPane.PLAIN_MESSAGE);





int i = JOptionPane.showConfirmDialog(null,"A
re you done?", "",


JOptionPane.YES_NO_OPTION);





if (i==0) notDone = false;



}



System.exit(0);



}

}

Questions:

1.

What does
showInputDialog()

return if the user h
its cancel?


Hint: Try
printing out s.


It retur
ns a null.

There! You've built your first GUI. Congratulations.



Part 4

JOptionPane

is a nice way to throw together a few dialog boxes and get a GUI, but it
doesn't give us the flexibility we really want. But with power and flexibility come
complexity.

The basic class we start with is a JFrame. A JFrame is a top level window with a title and
a border.



import javax.swing.*;



public class GuiTest {



public static void main (String[] args) {



JFrame j = new JFrame("Title");



j.setSize(2
75,170);



j.setVisible(true);



}

}

Questions:The

1.

Thoroughly describe what the code displays and indicate where it is displayed?


It displays a JFrame window with the Java icon and Title in the header.


It also
displays icons that allow the windo
w to be minimized, maximized and closed.


It
is positioned in the upper left corner of the screen.

2.

What happens if you comment out the
j.setVisisble(true);

line of code?


JFrame is not displayed.

3.

Does the program end when you close the window?
No




In eclip
se you can check for running
processes

in the
Debug

resource.


The
Debug

tab should be in the upper right corner of the eclipse window.





From the Unix command line, you can check for working processes with the
ps

command.


You can terminate the process wi
th
kill xxxx

where
xxxx

is the
process number.

4.

What happens if you put
System.exit(0);

at the end
? The JFrame appears
momentarily and then disappears because the program terminated
.

Now we have a problem.


The process does not terminate when we close the
window, but
adding
System.exit(0)

doesn’t do what we want.


Not to worry, we’ll fix it in Part 8.





Part 5

All GUIs are made up of collections of components called
Containers
. For instance, a
container can hold a scrollbar and a button, and a text window
. Of course, containers can
also contain other containers. Every JFrame has a base container called the
ContentPane

which should "contain all the non
-
menu components displayed by the JFrame". The
method
getContentPane()

returns the JFrame's ContentPane. Yo
u can add to a
ContentPane with the
add()

method.

One kind of thing you can add to a Container is a
JLabel
.



import javax.swing.*;



public class GuiTest {



public static void main (String[] args) {



JFrame j = new JFrame("Title");



j.s
etSize(275,170);



JLabel lab1 = new JLabel(" Text Label");



j.getContentPane().add(lab1);


//comment



j.setVisible(true);



}

}

Questions:

1.

What does the line with the comment do? If you are not sure, remove the line
and see what happ
ens.


Hint: Look in the Container class.JFrame class.
This
statement adds the
JLabel

object, i.e.,
lab1
, to the
contentPane

of the
JFrame
.


The JLabel is left justified.

2.

We could have broken that line into 2 parts:

Container c =j.getContentPane();

and
c.a
dd(lab1);
, but it wouldn't
compile. What import would we have to add to get it to compile? Hint: Look in
the Container class.


We would have to import java.awt.*;

Part 6

Labels can also have pictures. Download this image:
(
mislink3.gif
) to your
eclipse directory (same place you put data files) and then try:





import javax.swing.*;



public class GuiTest {



public static void main (String[] args) {



JFrame j = new JFram
e("Title");



j.setSize(275,170);



JLabel lab1 = new JLabel(" Text Label");



j.getContentPane().add(lab1);




Icon i = new ImageIcon("mislink3.gif");



JLabel lab2
= new JLabel("Text and Graphics
Label",


i,S
wingConstants.LEFT);



j.getContentPane().add(lab2);



j.setVisible(true);



}

}

Questions:

1.

What happened to the first label?
It disappeared.

2.

What does SwingConstants.LEFT do? Hint: Look at the JLabel class. I
t set the
horizontal alignment of

the label to left justified.

3.

Try changing LEFT to RIGHT.


What happened?
The icon and text were right
justified.

4.

Did the lab1 JLabel appear?
No

5.

What other SwingConstant can be used besides LEFT?


LEFT
,
CENTER
,
RIGHT
,
LEADING

or
TRAILING
.



Part 7

To fix t
he problem of the disappearing lab1 JLabel in the above program, we need to tell
the
Container

how to arrange the items in it. We do this with a layout. Here we'll try a
FlowLayout

by importing
java.awt.*
, modifying the
.add()

and
getContentPane
() and addi
ng
c.setLayout
(new FlowLayout());

.





import javax.swing.*;

import java.awt.*;



public class GuiTest {



public static void main (String[] args) {



JFrame j = new JFrame("Title");



j.setSize(275,170);



JLabel lab1 = new JLabel(" T
ext Label");



Container c = j.getContentPane();



c.setLayout(new FlowLayout());



c.add(lab1);



Icon i = new ImageIcon("mislink3.gif");



JLabel lab2 = new JLabel("Text and graphics Label",


i,SwingConstants.LEF
T);



lab2.setToolTipText("This is a fancy label"); //comment



c.add(lab2);



j.setVisible(true);



}

}

Questions:

1.

What does FlowLayout do?
A flow layout arranges components in a directional
flow, much like lines of text in a paragraph
.

2.

What other layouts are there?
BorderLayout
,
BoxLayout
,
CardLayout
,
FlowLayout
,
GridBagLayout
,
GridLayout
, and
SpringLayout


<You have to do
some searching to find them listed all together.


A google search for “java gui
layouts” will lead you to this page on the java.sun.com web site
http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html
.


It has a good
description with visual examples of each type of layout.

3.

What does the line with the comment do? Hint: Place your cursor over one

of
the words in the lab2 label.

The text “This is a fancy label” will eventually pop
up.



Part 8

We never solved the problem of ending the program when the window closes. To do this,
we need to understand the idea of "events". In a GUI there are these th
ings called events.
Events are things a user does, like pressing a button or closing a window. When events
occur, a particular method is automatically called to handle that event. What we need to
do is write these methods that get called when the event occ
urs.

A JFrame has a method
addWindowListener()

that allows us to specify what method we
want to call for what event.
addWindowListener()

expects its argument to be of type
WindowListener
, which is an interface
described here
. If you look at the definition of the
interface, you see seven different methods for different kinds of events on windows.
Sometimes we want to specify all seven methods, so we'll just implement
the interface
ourselves, but right now, we just want to implement a method for one event:
windowClosed()
. To make this easier, there is an abstract class
WindowAdapter

that
implements
WindowListener

with empty methods. If we extend
WindowAdapter

and
overri
de one of the methods, then that will cause that method to be called when that event
occurs. Note that we need to add the
import java.awt.event.*;

line.



import javax.swing.*;

import java.awt.*;

import java.awt.event.*;



public class GuiTest {



public

static void main (String[] args) {



JFrame j = new JFrame("Title");



j.setSize(275,170);



JLabel lab1 = new JLabel(" Text Label");



Container c = j.getContentPane();



c.setLayout(new FlowLayout());



c.add(lab1);




Icon i = new ImageIcon("mislink3.gif");



JLabel lab2 = new JLabel("Text and graphics Label",


i,SwingConstants.LEFT);



lab2.setToolTipText("This is a fancy label");



c.add(lab2);



j.setVisible(true);



j.
addWindowListener(new MyWindowAdapter());



}

}



class MyWindowAdapter extends WindowAdapter {



public void windowClosing (WindowEvent e) {



System.out.println("Window closed...Exiting program!");



System.exit(0);



}

}

Questions:

1.

Wha
t happens when we click the close button in the upper right corner of the
JFrame window?

The JFrame disappeared and the process terminated.

2.

Why did I have to import java.awt.event.* if I already imported java.awt.*?
Because event is a subdirectory of awt
and you don’t get the contents of the
subdirectories with *.



Deliverables/due date

Your answers to the questions are due at the beginning of class on
Tuesday
,
7

April.


There is nothing else you need to turn in.