Title: Chapter 12- GUI
1Chapter 12- GUIs, Java, and Swing.
2Overview
- What are GUIs
- How Java does GUIs- Swing
- Buttons
- Containers
- Text I/O and Swing
- Review
3GUIs and theory.
4What is a GUI?
- GUI- Graphical User Interface.
- Pronounced Gooey.
- Before 1983, everything was command line
interfaces and text menus. - Now have a pointing device, and
clickable/moveable objects on the screen.
5What our GUIs have
- Windows, menus, and buttons
- Uses the Event Driven programming model. A fairly
large shift from command line programming(what we
have been doing so far).
6Event Driven programming
- The program sets up the GUI and waits to see what
the user does. - Any user action fires an event.
- This event is caught and handled by the
appropriate listener (event handler).
7Event model example.
- Imagine the work of a worker who only does what
their boss tells them to. - The worker just sits around until the boss comes
up and tells them to Write a report A (an event
is fired) The worker creates the report and is
finished(the event is handled). The worker then
begins waiting for the next request(continues
listening).
8Paradigm shift
- You dont determine the order of how the program
is executed. The order of the events(which are
fired when the user does something in a
particular order) determines the order.
9An example.
- In our previous grocery program, we asked the
user first how many oranges they want, then eggs,
then apples, watermelons, and bagels. - In a graphical version of a shopping cart, the
user can choose these items in any order, or not
choose an item at all.
10GUIs, Java, and Swing
11Swing-How Java does GUIs
- Ever since Java 1.2 (Java 2), the Graphical User
Interfaces for Java have been created using
Swing. Before Java 1.2, awt was used (it is still
included and still gives us functionality we need
sometimes). - Swing is faster and has more options.
12Beginning tips for GUI programming.
- Save your work often! If your GUI crashes in a
way such that your computer becomes unresponsive
you may need to restart your computer and lose
unsaved work. - Copy someone elses base work and modify it (This
does not mean to cheat).
13A (good) first window class
Always extend from JFrame
import javax.swing. public class FirstWindow
extends JFrame public static final int
WIDTH300 public static final int
HEIGHT200 public FirstWindow()
setSize(WIDTH,HEIGHT) JLabel myLabel new
JLabel(Howdy.) getContentPane().add(myLabel)
WindowDestroyer listener new
WindowDestroyer() addWindowListener(listener)
Sets the size of the frame
Adds the text Howdy to the frame.
Makes the window close when you click on the X
(event driven listener)
14Using the first window class
import javax.swing. public class
FirstWindowDemo public static void
main(String args) FirstWindow window1
new FirstWindow() window1.setVisible(true) Fi
rstWindow window2 new FirstWindow() window2.se
tVisible(true)
Makes one of our windows(frames)
Allows us to see the frame that has been made.
15Import statements
- Usually want to import the following three
libraries - javax.swing.
- java.awt.
- java.awt.event.
16JFrame
- Used to create a window that we can put stuff
into like buttons, text labels, text boxes,
drop-down lists, menus, etc. - For every method in the constructor that didnt
have an object to the left, the code was using
this implicitly, so those are methods of JFrame.
17SetSize(int width, int height)
- Sets the size of the window in pixels. Makes it
width x height. The larger the number, the bigger
it is on the screen. Be careful that you dont
set it to something larger than the resolution on
your screen.
18JLabel
- new Jlabel(String) creates a new JLabel and sets
the text of the label to the string passed in. - Once you have created it, you need to make sure
that you add it to a container for it to be seen.
19getContentPane()
- Returns a Container object that represents the
area that you can put things into in a JFrame. - This is where you add things that you want to
show up on the JFrame. - Dont add things directly to the JFrame, it wont
work. Always add to the content pane.
20Window listeners and destroyers.
- Always need to create a window destroyer and add
it to the JFrame. Else you wont be able to close
the window. - Use addWindowListener(WindowDestroyer object) to
add the listener to the window(listens for the
close-window event, basically).
21WindowDestroyer code
public class WindowDestroyer extends
WindowAdapter public void windowClosing(WindowE
vent e) System.exit(0)
Just copy this code directly. Dont worry about
trying to ever create it from scratch. It is
provided on the Savitch CD.
22To see your creation.
- Create an object of that GUI type
- FirstWindow w new FirstWindow()
- Must set it to be visible
- w.setVisible(true)
23Other methods of JFrame
- setBackground(Color c)
- setForeground(Color c)
- Where c is a color like
Color.black Color.darkGray Color.gray Color.white
Color.red Color.green Color.blue
24Extra Colors
- We can create any color that we want in the
standard RGB color space with each component
having values 0-255 (or 0.0 1.0).
int red105, green45, blue205 Color aColor
new Color(red, green, blue) setBackground(aColor)
// or like on the previous slide setForeground(C
olor.black)
25New Layouts.
- When we add things to containers, Java tries to
figure out what it thinks is the best possible
layout for the items. - We can override Javas default way of placing
things on the screen by changing our layout
manager.
26Default Layout Manager- BorderLayout.
- The default layout manager that Java uses is
BorderLayout. - See page 785 to see what the BorderLayout manager
tries to do. - The BorderLayout manager will try to fill up the
whole section with the object that you
add(buttons look huge).
27Adding content to specific positions in
BorderLayout.
- When you give your add command, put in a second
argument to say where you want it to go(else it
goes in BorderLayout.CENTER).
Container contentPane getContentPane() contentP
ane.add(aLabel, BorderLayout.NORTH) contentPane.a
dd(bLabel, BorderLayout.EAST) contentPane.add(cLa
bel, South) contentPane.add(dLabel)//adds to
center. contentPane.add(eLabel, Center)
28Setting your layout manager
- Use the setLayout method of the container to set
your manager
Container contentPane getContentPane() content
Pane.setLayout(new BorderLayout()) or contentPane
.setLayout(new FlowLayout()) or contentPane.setLa
yout(new GridLayout(4,3))
29FlowLayout()
- Simplest manager.
- Elements are added one after the other from left
to right, and they are evenly spaced. - Laid out in the order you add them to the
container.
contentPane.add(aLabel) //no second
argument. //nothing else to //specify.
30GridLayout()
- Constructed differently.
- new GridLayout(int rows, int cols) creates a
evenly spaced grid of the specified number of
rows and columns. - Adds content to a single cell left to right, top
to bottom, one cell at a time. - Cant skip cells
contentPane.add(aLabel) //no second argument.
31Many more layout managers.
- You are not limited to only these three layout
managers. There are many more and you can create
your own. Some other examples are - GridBagLayout
- CardLayout
- BoxLayout.
- See the documentation for more.
32Basic Swing Review
- What class do we use to create a window in Swing?
- What class do we use to create some visible text
in Swing? - What classes do we use to manage how content is
added to a window in Swing?
33Basic Swing Review
- Can you add content directly to a JFrame?
- Where should you add content to add something to
a window? - How do you make your window visible?
- How do you set your background color in a window?
34Basic Swing Review
- What is the default layout manager for Swing?
- What are the names of the regions in the default
layout manager for swing? - How would you add a label called helloLabel to
the top part of the window?
35Buttons
36Interactive windows
- Now know how to create windows and output
information(through labels). - Now need to know how to take in information.
- The most basic way of taking in information with
GUIs is with a button. - Buttons are how we signify selections, that we
are done, etc.
37JButton
- We can use JButtons to create your basic push
button. - We need to be able to tell when a user presses a
button, so we need add a listener to the button. - We also need to make sure that we add these
buttons to some container so that we can see them.
38JButton Example
public class ButtonDemo extends
JFrame implements ActionListener public
ButtonDemo() Container contentPane
getContentPane() Jbutton aButton new
JButton(Howdy) Create button with label
Howdy on it. aButton.addActionListener(this) T
here will be a method actionPerformed in
this class contentPane.add(aButton,
South) Add the button to the content pane at
the bottom. ...
39Dealing with the button click
public void actionPerformed(ActionEvent e)
if(e.getActionCommand().equals(Howdy))
if the Howdy button getContentPane.setBackgrou
nd(Color.black) do something
40ActionListeners
- To allow a class to listen to button events need
to add the following to the class declaration - implements ActionListener
- ActionListener is an interface.
- This tells the computer that you will define a
method in the class called actionPerformed that
returns nothing and accepts an ActionEvent. - In actionPerformed, you will say how you deal
with the events.
41Creating the button.
- new JButton(String) creates a button that has the
string as its label.
42Registering the listener.
- Once you create the button, you need to say just
who will be listening to your button. We do this
by registering our listener.
aButton.addActionListener(this) //usually do
this bButton.addActionListener(anActionListener)
//if your listener is defined //in another
class, use this way //after creating
anActionListener.
43Putting the button somewhere.
- Once we have created the button and registered
it, we need to put it somewhere. Use the add
method for some container.
Container contentPane getContentPane() contentP
ane.add(aButton, West) contentPane.add(bButton)
44Catching the event.
- If your class is implementing ActionListener, you
need to define an actionPerformed method
public void actionPerformed(ActionEvent
e) //do something.
45ActionEvents
- When you get an ActionEvent object, you can check
the actionCommand of the object to see where it
came from - e.getActionCommand() //returns a string
- The ActionCommand is usually the text of the
button, unless someone has called
setActionCommand(String) on the button object.
46Shortcut keys
- To set a shortcut key for a button use
setMnemonic(char). - To do it for a JTextField or other JLabeled
component, you can first use setLabelFor(Component
) and then use setDisplayedMnemonic(char).
47Button Review
- What class do we use to make buttons?
- If we want to catch the button push events what
interface do we need to implement? - How do we register the listener of our buttons?
- How do we tell what button an event came from?
48Containers
49Container classes
- Containers are classes that can hold objects like
buttons, text fields, labels, etc. - The content pane on a JFrame is one type of
container. - We can have more than one container in a window.
In fact, we can even put containers inside of
containers.
50JPanel, a new type of Container
- A commonly used Container is the JPanel.
- This allows us to group things together and
create subsections of a frame. - We can use a different kind of layout manager for
each different container that we have.
51Using JPanels
- First use new JPanels to create a panel.
- Once you have created the panel, you can then add
things directly to the panel(no need to use
content panes with JPanels). - When you are done adding stuff to the panel, add
the panel to the JFrame.
52A note concerning JPanels, JFrames, and Layout
Managers.
- It is often a good idea to use a BorderLayout on
the Frame and other layout managers (like
FlowLayout) for your JPanel. - This will cause your panel to take up the whole
section of the BorderLayout while keeping your
pieces reasonably spaced and sized inside of your
panel.
53Review for Containers
- Name a class of type Container?
- Can we add things directly to JPanel?
- Can we add things directly to JFrame?
- How many Layout Managers can we have in a single
container? - Can we have different layout managers for
different containers?
54Text I/O (for GUIs)
55Text I/O
- Now we get to learn how to take more input into
our GUIs this time by allowing the user to type
information into our program. - The text boxes and fields we will be using also
allow us to output more information to the user.
56JTextField
- JTextFields are just a single line input field.
- We create them with a constructor that takes a
single integer, which specifies the width of
input field. - Then add the JTextField to some container.
JPanel aPanel new JPanel() JTextField text
new JTextField(20) aPanel.add(text)
57Getting and setting the text
- If we want to see the string that a user typed
into a JTextField, we can use the getText()
command to retrieve the string. - If we want to set the text, use setText(String).
String someStuff text.getString() text.setStrin
g(Wake up!)
58JTextArea
- A JTextArea is just like a JTextField, except
that it can contain multiple lines. - The main difference comes when we construct the
JTextArea, we provide a number of lines as well
as line width.
JTextArea area new JTextArea(5,20) //creates
5 lines each 20 characters //wide.
59Methods of JTextArea.
- The exact same as JTextField. getText() and
setText(String). - If we want to allow a user to enter multiple
lines, we will want to turn on line wrapping.
setLineWrap(true).
60Other methods of JTextField and JTextArea
- We can make any kind of JTextArea or JTextField
read-only (uneditable) by setting its editable
property. - We can also set the background colors of the text
areas by using setBackground(Color).
61Reading numbers
- Just like File I/O, reading things besides
strings is more difficult. - Again we will want to use parsing and tokenizing.
- A good idea before parsing numbers is to trim off
whitespace. - Again, you will need to be prepared to catch a
NumberFormatException.
62Reading numbers example
String response aTextField.getText() //if it
is an integer. int someInt Integer.parseInt(r
esponse.trim()) //if it is a double. double
someDouble Double.parseDouble(response.trim())
63Review for Text I/O
- What is the difference between a JTextArea and a
JTextField? - How many arguments do we give when we call the
JTextField constructor? What do the arguments do? - How many arguments do we give when we call the
JTextArea constructor? What do the arguments do?
64Review for Text I/O
- How do we get the text that is inside of a
JTextArea? - How do we set the text inside of a JTextArea?
- How do we allow line wrapping in JTextArea?
- How do we make a JTextField read-only?
65Review for Text I/O
- How do we get a number from a text box?
- What kind of exception should we be prepared to
catch when getting numbers from text boxes?
66Review
67Review
- What does GUI stand for?
- How is Event Driven programming different than
what we have been doing up till now? - What libraries do we usually import for GUI work?
68Review
- What class do we inherit from to be able to make
windows? - Can we add objects directly to this class that
makes windows? - How do we get a container to add our objects to
the window?
69Review
- What kind of event listener do we need to add to
be able to close our window? - How do we make a window visible?
- What does a Layout Manager do?
- What are three Layout Managers we have discussed
so far? What does each do?
70Review
- What class do we use to make simple text for
merely displaying? - What class do we use to make buttons?
- What interface do we have to implement if we want
to listen to the actions of the buttons? - How do we tell what button was pushed when an
event is triggered?
71Review
- What are two containers that we have talked about
so far? - Why would you want to use a JPanel?
- Can you add objects directly to the JPanel?
72Review
- What are two classes for taking in Text in a GUI?
- How do you call the constructor for each class?
- How do you get the text that is being displayed
in either of these classes?