Upload
jason-ruiz
View
227
Download
0
Embed Size (px)
Citation preview
7/27/2019 Chapter 3 - GUI and Multimedia
1/271
7/27/2019 Chapter 3 - GUI and Multimedia
2/271
Topics of this chapter
0 Evolution of the Java GUI
0 Swing Vs. AWT
0 Swing0 Buttons, events, and other swing
0 Basics ,containers and layout managers
0 Menus and buttons, text fields and text areas
0 Window listeners, icons and scroll bars0 Color and font ,Loading
0 Playing Audio Clips , Playing Video
Chap-3 Adv Prog 2
7/27/2019 Chapter 3 - GUI and Multimedia
3/271
Evolution of Java GUI
0 Java 1.0 AWT built in 30 days, and it shows Java 1.1 AWT
significantly improved, but GUI not finished yet
0 Java 2 Swing: very different, vastly improved
Chap-3 Adv Prog 3
7/27/2019 Chapter 3 - GUI and Multimedia
4/271
JDK 1.0 (circa 1996)0 JDK 1.0 went a long way to implementing platform-
independent GUI library
0 Bruce Eckel: it "produced a GUI that looks equally mediocreon all systems."
0 Just 4 fonts
0 Couldnt access GUI of native OS
0 Didnt separate model and UI code cleanly
Chap-3 Adv Prog 4
7/27/2019 Chapter 3 - GUI and Multimedia
5/271
JDK 1.1 (circa 1998)0 JDK 1.1 makes AWT more robust and extensible
0 Delegation-based event model separates userinterface from problem domain
0 Other enhancements: button tool tips, cut/paste tothe clipboard, popup menus, printing, etc.
0 Adds supports for JavaBeans
Chap-3 Adv Prog 5
7/27/2019 Chapter 3 - GUI and Multimedia
6/271
JDK 1.2 (Swing)0 JDK 1.2 adds Java Foundation Classes
0 Swing is the GUI library for JDK 1.2
0 Much richer class library plus better integration with look
and feel of GUI of OS
Chap-3 Adv Prog 6
7/27/2019 Chapter 3 - GUI and Multimedia
7/271
Java Foundation Class
0 JFC(Java Foundation Class) has two parts:
0 Abstract Window Toolkit (AWT)
0 Original user interface toolkit
0 Refers to the set of classes provided by Java that enables the
creation of a graphical user interface and provide amechanism to handle user input through the mouse andkeyboard.
0 Swing
0 Introduced in Java 1.2
0 Swing is the codename of the project that developed thefirst JFC components (JFC 1.1) which is initially released as anextension to JDK 1.1.
Chap-3 Adv Prog 7
7/27/2019 Chapter 3 - GUI and Multimedia
8/271
Swing Vs. AWT0 AWT is Javas original set of classes for building GUIs
0 Uses peer components of the OS; heavyweightcomponents
0 Not truly portable: looks different and lays out inconsistently ondifferent OSs
0 Due to OSs underlying display management system
0 Swing is designed to solve AWTs problems
0 99% java; lightweightcomponents
0 Drawing of components is done in java
0 Uses AWTs components like Window, frame, dialog
0 Lays out consistently on all OSs
0 Uses AWT event handling
0 Swing provides several advanced components such as tabbed panel,scroll panes, trees, tables and lists.
0 Unlike AWT components, Swing components are not implemented byplatform-specific code. Instead they are written entirely in Java andtherefore are platform-independent. The term "lightweight" is used todescribe such an element.
Chap-3 Adv Prog 8
7/27/2019 Chapter 3 - GUI and Multimedia
9/271
Swing Vs. AWT0 Swing provides replacements for most of the AWT components, althoght
many AWT non-component classes remain in use. Upward compatibility
is assured in almost all cases; an AWT continues to work in Java.0 Mixing both Swing andAWT components in the same interface can
produce errors, so one has to make a decision about which to use. Despitethe advantages of Swing, there actually are arguments for using AWT.
0 Swing advantages
Swing is faster. Swing is more complete.
Swing is being actively improved.
0 AWT advantages
AWT is supported on older, as well as newer, browsers so Applets written in
AWT will run on more browsers. The Java Micro-Edition, which is used for phones, TV settop boxes, PDAs, etc,
uses AWT, not Swing.
Chap-3 Adv Prog 9
7/27/2019 Chapter 3 - GUI and Multimedia
10/271
Peer classes at run-timeclass TestPeer {TestPeer() {Frame myFrame = new Frame("my Frame"); //create window FrameButton myButton = new Button("my Button"); //create myButton
myFrame.add("Center",myButton); //putAttach (add) myButton in myFramemyFrame.setVisible(true); //button appears in window on screen by
// setting myFrame and myButton visible,// by creating platform-specific peer objects.
//setVisible() creates peer objects for myFrame & myButtonComponentPeer buttonPeer = myButton.getPeer(); //now works}
}
0 TestPeer first constructs a frame, then adds a button on the frame0 setVisible method creates peer objects on platform
0 Last line now accesses myButtons peer object0 Peer classes are usually hidden from developers.0 In fact, in newer versions of JDK, getPeer() method is "deprecated"0 Peer classes strongly discouraged for code maintenance purposes
Chap-3 Adv Prog 10
7/27/2019 Chapter 3 - GUI and Multimedia
11/271
WHAT IS SWING? Swingis Java's GUI(graphical user interface) library
So far, our user interfaces have only been textual,meaning the user sees text and writes text at thecommand prompt.
Swing is created to provide a more sophisticated set ofGUI components than the Abstract Windows Toolkit
(AWT) Today we will learn to make our interfacesgraphical, so
we can use our programs through windows, click onbuttons, etc.
You MUST import the following packages to use swing:import java.awt.*;
import javax.swing.*;
Chap-3 Adv Prog 11
7/27/2019 Chapter 3 - GUI and Multimedia
12/271
WHAT IS SWING?0 Swing Java consists of
Pluggable Look and feel manse each picture shows the
same program but with a different look and feel
Accessibility API - Screen readers, Braille displays, ... Java 2D
Drag and Drop - Between Java applications and native
applications
Chap-3 Adv Prog 12
7/27/2019 Chapter 3 - GUI and Multimedia
13/271
WHAT IS SWING?0 Swing is a Java package, javax.swing, provided in J2SDK (Java
2 Software Development Kit). It provides many
enhancements to the existing graphics package, AWT
(Abstract Windows Toolkit) package, java.awt.
0 javax.swing and java.awt together offer a complete API
(Application Programming Interface) for Java applications tooperate graphical devices and create GUI (Graphical User
Interfaces).
0 The Swing components are implemented entirely in the Java
programming language.
Chap-3 Adv Prog 13
7/27/2019 Chapter 3 - GUI and Multimedia
14/271
WHAT IS SWING?The Swing package in JDK 1.6 and recent versions containsfollowing sub packages:
0 javax.swing - Provides a set of "lightweight" (written in Java with no nativecode) components that, to the maximum degree possible, work the same onall platforms.
0 javax.swing.border - Provides classes and interfaces for drawing specializedborders around a Swing component.
0 javax.swing.colorchooser - Contains classes and interfaces used by the
JColorChooser component.0 javax.swing.event - Provides support for events fired by Swing components.
0 javax.swing.filechooser - Contains classes and interfaces used by theJFileChooser component.
0 javax.swing.plaf - Provides one interface and many abstract classes that Swinguses to provide its pluggable look and feel capabilities.
0 javax.swing.plaf.basic - Provides user interface objects built according to theBasic look and feel.
0 javax.swing.plaf.metal - Provides user interface objects built according to theJava look and feel (once codenamed Metal), which is the default look and feel.
0 javax.swing.plaf.multi - Provides user interface objects that combine two ormore look and feels. Chap-3 Adv Prog 14
7/27/2019 Chapter 3 - GUI and Multimedia
15/271
WHAT IS SWING?0 javax.swing.plaf.synth - Provides user interface objects for a skinnable
look and feel in which all painting is delegated.
0 javax.swing.table - Provides classes and interfaces for dealing withJTable.
0 javax.swing.text - Provides classes and interfaces that deal witheditable and non-editable text components.
0 javax.swing.text.html - Provides the class HTMLEditorKit andsupporting classes for creating HTML text editors.
0 javax.swing.text.html.parser - Provides the default HTML parser, alongwith support classes.
0 javax.swing.text.rtf - Provides a class (RTFEditorKit) for creating Rich
Text Format text editors.0 javax.swing.tree - Provides classes and interfaces for dealing with
JTree.
0 javax.swing.undo - Allows developers to provide support forundo/redo in applications such as text editors.
Chap-3 Adv Prog 15
7/27/2019 Chapter 3 - GUI and Multimedia
16/271
What are Components?
0 A componentis an object having a graphical representation
that can be displayed on the screen. like checkboxes, menus,
windows, buttons, text fields, applets, and more.
0A containeris a special component that can hold other
components.0 Example of containers in typical GUIapplications include:
panels, windows, applets, frames
Functionality of most GUI components derive from the
Componentand Containerclasses.
Chap-3 Adv Prog 16
7/27/2019 Chapter 3 - GUI and Multimedia
17/271
Components
Chap-3 Adv Prog 17
7/27/2019 Chapter 3 - GUI and Multimedia
18/271
Swing Containment Hierarchy
0 Top-level container:
0 place for other Swing components to paint themselves
0 e.g., JFrame, JDialog, Japplet
Chap-3 Adv Prog 18
7/27/2019 Chapter 3 - GUI and Multimedia
19/271
Swing Containment Hierarchy
0 Intermediate container:
0 simplify positioning of atomic components
0 e.g., JPanel, JSplitPane, JTabbedPane
Chap-3 Adv Prog 19
7/27/2019 Chapter 3 - GUI and Multimedia
20/271
Swing Containment Hierarchy
0 Atomic components:
0 self-sufficient components that present information to
and get input from the user
0 e.g., JButton, JLabel, JComboBox, JTextField, JTable
Chap-3 Adv Prog 20
7/27/2019 Chapter 3 - GUI and Multimedia
21/271
Implementing a Swing GUI
0 Import javax.swing.*, java.io.*, java.awt.*
0 Make a specific class to do GUI functions
0 Specify all the GUI functions/components in the classsconstructor (or methods / classes called by the
constructor)
0 Run the GUI by instantiating the class in the classs main
method
Chap-3 Adv Prog 21
M Fi t S i P
7/27/2019 Chapter 3 - GUI and Multimedia
22/271
import javax.swing.*;
public class HelloWorldSwing {
public static void main(String[] args) {
// lets create a frame object and give some title
JFrameframe = new JFrame("HelloWorldSwing");
// lets have a label
JLabellabel = new JLabel("Hello World");
//lets add the label to the frame we have created above
frame.getContentPane().add(label);
//this is the operation to do when the window is closed.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//pack() causes a window to be sized to fit the preferred
//size and layouts of its sub-components
frame.pack();
// lets make the frame to be visible
frame.setVisible(true);
}
} Chap-3 Adv Prog 22
My First Swing Program
7/27/2019 Chapter 3 - GUI and Multimedia
23/271
Example 2
import javax.swing.*;
public class HelloWorldFrame extends JFrame{
public HelloWorldFrame() {
super(HelloWorldSwing);
final JLabellabel = new JLabel("Hello World");
getContentPane().add(label);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);}
public static void main(String[] args) {
HelloWorldFrame frame = new HelloWorldFrame();
}
}
In this example
a custom frame
is created
7/27/2019 Chapter 3 - GUI and Multimedia
24/271
Components0 Components(also known as "widgets") are the basic user
interface elements the user interacts with: labels, buttons, textfields, ...
0 Components are placed in a container(eg, JPanel). The visual
arrangement of the components depends on the container's
layout. When the user does something to a component, the
component's listeneris sent an event.
Chap-3 Adv Prog 24
7/27/2019 Chapter 3 - GUI and Multimedia
25/271
Components0 The most important componentsto learn for simple programs are:
0 Input Components
Buttons( JButton, Radio Buttons, JCheckBox)Text (JTextField, JTextArea)
Menus(JMenuBar, JMenu, JMenuItem)
Sliders(JSlider)
JComboBox (uneditable)(JComboBox)
0 Information Display ComponentsJLabel
Progress bars (JProgressBar)
Tool tips (using JComponent's setToolTipText(s) method)
0 Choosers
File chooser(JFileChooser)
Color chooser (JColorChooser)0 More complex displays
Tables (JTable)
Trees (JTree)
Formatted TextChap-3 Adv Prog 25
Top level Container: javax swing JFrame
http://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/05Intro_to_components/01buttons.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/20buttons/10jbutton.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/50radio_buttons/25radiobuttons.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/60check_boxes/30checkbox.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/30textfield/11textfield.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/40textarea/20textarea.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/menus/menus.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/70sliders/10slider.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/80combo_box/35combo1.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/10labels/10label.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/containers/20dialogs/30filechooser.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/containers/20dialogs/30filechooser.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/10labels/10label.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/80combo_box/35combo1.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/80combo_box/35combo1.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/80combo_box/35combo1.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/80combo_box/35combo1.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/80combo_box/35combo1.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/70sliders/10slider.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/menus/menus.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/40textarea/20textarea.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/30textfield/11textfield.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/60check_boxes/30checkbox.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/50radio_buttons/25radiobuttons.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/20buttons/10jbutton.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/05Intro_to_components/01buttons.html7/27/2019 Chapter 3 - GUI and Multimedia
26/271
Top-level Container: javax.swing.JFrameJFrame - window, typically subclassed
w =new JFrame(); Constructor
w =new JFrame(t); Constructor. Sets titlebar to t.
w.setTitle(t); Sets titlebar text to t
w.setDefaultCloseOperation(opt); JFrame.EXIT_ON_CLOSE terminates program when
close box clicked.
w.setVisible(true/false); Make visible (and start GUI thread) or hide.
w.pack(); Calculates layout on all inner containers and sets
size of JFrame.w.setContentPane(cont); Sets the content pane - common to pass a JPanel
here.
cont =w.getContentPane(); Returns the window's content pane.
w.setJMenuBar(mb); Adds a JMenuBar.
w.setResizable(false); Prevent user from resizing window.
w.setLocation(x, y); Positions window's top left corner at screen
coordinates (x, y).
w.setSize(w, h); Sets window size, but use layouts and pack()
instead.
w.show(); Deprecated. Use w.setVisible(true).
w.hide(); Deprecated. Use w.setVisible(false).
26
7/27/2019 Chapter 3 - GUI and Multimedia
27/271
Anatomy of a JFrame
Chap-3 Adv Prog 27
title bar
minimize
maximize
close
ThecontentPane holds your
content; created automatically
when a JFrame is created
7/27/2019 Chapter 3 - GUI and Multimedia
28/271
JFrame0 JFrameis the application window class
0 It draws the window and interacts with the operating system0 When a JFrameis created, an inner container called the
contentPaneis automatically created
0 We don't draw graphics directly on JFrame; we draw on the
contentPane0 Frames are the basis of any Java GUI
0 Frame is the actual window that encompasses your GUI objects;a GUI can have multiple frames
0 The J prefix is at the beginning of any Swing componentsname (to distinguish them from AWT components)
0 JFrame is a wrapper around AWTs Frame
Chap-3 Adv Prog 28
7/27/2019 Chapter 3 - GUI and Multimedia
29/271
JFrame0 The javax.swing.JFrameclass is used to create a "window". This
window has a few characteristics of its own (title bar, etc), butmost of the controls are placed in one of two subareas: content
paneor menu bar.
0 You can create a frame like this:
JFrame w = new JFrame("your title");// but it's better to use subclassing as below.
0 Subclass JFrame, build in constructor. Another better way is
to define a class, eg MyWindowthat extends JFrame, put the
code which builds the GUI in the class's constructor, and createan instance of the window from the main program. See example
below.
Chap-3 Adv Prog 29
7/27/2019 Chapter 3 - GUI and Multimedia
30/271
Jframe(cont)0 Content pane - Two styles - Get it or Set it
There are two common ways to use a JFrame's content pane. Bothare commonly used. In both cases, the easiest style is to assign
the working version of the content pane to
0 Get the predefined content pane and change it.Every
JFrame comes with a default content pane. It doesn't haveanything on it, although it does have a default layout, probably
not the one you want to use though! ThegetContentPane()
method returns a Container object, which interestingly is
actually a Jpanel.
0 Create a JPanel and make it the content pane.This requires
a call tosetContentPane(...).
Chap-3 Adv Prog 30
7/27/2019 Chapter 3 - GUI and Multimedia
31/271
Jframe(cont)
Using the content pane.
c= w.getContentPane(); Returns window's content pane. Use either get or set,
but not both.
w.setContentPane(c); Sets window's content pane to c(or subclass JPanel).
Handling the window's close box.
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); This adds a window listenerthat simply executes
System.exit(). It's the short,
appropriate, solution for
most small programs.
w.addWindowListener(listen); Use this to call your own
window closing listener.
Executing the layout.
w.pack(); Finalize layout after everything is added to window and content
pane. Don't use validate() with layout managers.
31
Jf ( t)
7/27/2019 Chapter 3 - GUI and Multimedia
32/271
Jframe(cont)Displaying the window.
w.setVisible(true); Makes the window visible, and starts the Event Dispatch
Thread (EDT) which manages the GUI. This is usually calledby the main program after calling the constructor. show()
should no longer be used.
Miscellaneous.
w.setTitle(title); xxx
w.setResizable(false); Set to false if you don't want the user to resize yourwindow.
w.setJMenuBar(mbar); This is how to add a menubar to the window.
w.setLocationRelativeTo(null); Centers the window. If you even bother with position,
this is the most common choice.
Less common positioning and sizing.
w.setSize(w, h); Sets window to pixel width (w) and height (h). The only reasons
to use this are to fill the screen or restore a window size from a
previous run.
w.setLocation(x, y); Sets the upper left corner of the window to this screen pixel
coordinate.32
Jf ( t)
7/27/2019 Chapter 3 - GUI and Multimedia
33/271
Jframe(cont)0 There is typically be a very short main method something
like this.
public static void main(String[] args {JFrame windo = new MyExample();windo.setVisible(true);
}
0 And a class which defines the window.public class MyExample extends JFrame {
//..Declare components, something to hold the model..
public MyExample() { // constructor builds GUI
//... Build the content pane.
Container content = this.getContentPane();content.add(...) // Add components to the content . .
. this.setTitle("My new window");this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.pack(); // does layout of components.
}//end constructor }
Chap-3 Adv Prog 33
Jframe(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
34/271
Jframe(cont)
Window Size and Position
0 First pack your window to do the layout : The optimum size of
a window depends on the size and layout of the components.
After adding all the components to a window (JFrame), call
pack()to perform the layout.
0 Centering a Window : The following code positions a window
(JFrame)fin the centerof the screen. Use this when you create awindow, after calling pack() has been called, as follows.
setLocationRelativeTo(null);
// Implicit "this" if inside JFrame constructor.
f.setLocationRelativeTo(null);
// Explicit JFrame if outside JFrame constructor.
Chap-3 Adv Prog 34
Jframe(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
35/271
Jframe(cont)
Window Size and Position
0 You can use the older, more explicit, way of centering a
windowDimension screenSize =Toolkit.getDefaultToolkit().getScreenSize();
Dimension windowSize = window.getSize();
int windowX =Math.max(0,(screenSize.width-windowSize.width )/2);
int windowY =Math.max(0,(screenSize.height-windowSize.height)/2);
f.setLocation(windowX, windowY); // Don't use "f." inside
constructor.
0 The Math.max call makes sure the window origin is not negative.
Chap-3 Adv Prog 35
Jframe(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
36/271
Jframe(cont)
Window Size and Position
0 Expanding a window to fit the screen
The first example leaves a 40 pixel border around the window. The
second example passes the Dimension object directly to setSize().
You don't need the explicit "f." if this code is in the constructor.Dimension screenSize =
Toolkit.getDefaultToolkit().getScreenSize();f.setSize(screenSize.width - 40, screenSize.height - 40);
f.validate(); // Make sure layout is ok
0 Completely full screen.f.setSize(Toolkit.getDefaultToolkit().getScreenSize());
f.validate(); // Make sure layout is ok
Chap-3 Adv Prog 36
Jframe(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
37/271
Jframe(cont)
Window Size and Position
0 Fixed Window Size using setSize() and validate() -
Probably a mistake
0 You canset the size of a window, but it's almost always a
mistake unless you're simply expanding the window to fill the
screen. The default window size should depend on the size and
layout of the components as determined by pack(). If you must
create a fixed size window (JFrame), callsetSize(width, height)
orsetSize(dimension), then call validate() to finalize the
component layout before making the window visible.
Chap-3 Adv Prog 37
Jframe(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
38/271
Jframe(cont)
Content Panes
0 Before Java 2 each top-level container had only one layer. Java 2
top-level containers (JFrame, JApplet, ...) have several layers
(panes): root, content, layered, andglass. Programs normally
reference only the content pane. There are two programming
idioms for using the content pane: (1) using the preassignedpane (recommended), or (2) building your own pane.
0 Naming convention
0 It is common to name the content pane contentor contentPane.
Chap-3 Adv Prog 38
Jframe(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
39/271
Jframe(cont)
Content Panes0 Idiom 1: Use the existing content pane
0 Each container has a pre constructed content pane of classContainer. You can get this pane and add the components to it.
For example,
class MyWindow extends JFrame {
. . .MyWindow() {
// constructor
Container content = getContentPane();
// Use the default content pane.
content.add(...);content.add(...);
. . .
}
Chap-3 Adv Prog 39
Jframe(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
40/271
Jframe(cont)
Content Panes0 All JFrames already have a content pane, so there's no need to
create a new one, just get the existing pane. And if you'rewondering about the Container type, it's a superclass of JPanel.In fact, if you look at the actualtype of the object that'scurrently returned bygetContentPane(), it really is a JPanel,although you can't count on this in the future, of course.
0 Sometimes programmers don't bother to copy the content panereference into a new variable, resulting in code like this. Sincethere are typically a large number of references to the contentpane, this seems awkward.
class MyWindow extends JFrame {
. . .MyWindow() {
// constructor
getContentPane().add(...);
getContentPane().add(...);
. . . Chap-3 Adv Prog40
Jframe(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
41/271
Jframe(cont)
Content Panes0 Idiom 2: Create your own content pane
It's common to create a new panel for the content pane and tellthe window to use this new panel for it's content pane. For
example,class MyWindow extends JFrame {
. . .
MyWindow() {
// constructor
JPanel content = new JPanel();
// Create a new content pane.
content.add(...);
content.add(...);
. . .
setContentPane(content);
}
} Chap-3 Adv Prog41
Wh d l
7/27/2019 Chapter 3 - GUI and Multimedia
42/271
Where to declare components0 Components are typically declared in one of several places:
0 Field variables : Some components should be declared as fieldvariables (instance variables, member variables). This is theappropriate place to declare components which must be referenced afterthe interface is constructed. Typically these are text fields or text areas,check boxes, etc. Those components whose values must be gotten or set.
0 Local variables : Local variables should be used for components whichare never referenced after the interface is constructed. Typically these
are panels for holding components, buttons (whose interaction is thrutheir listeners), ... Local variables disappear when the method they arein returns, but the component will continue to exist if it has been addedto the interface.
0 Anonymous : Anonymous creation is typical with labels, which can becreated and added in one step and never assigned to a variable. Of
course, if the appearance (font, alignment, ...) must be changed, thenthey should be put in a local variable. Some programs use labels foroutput (not a good idea), and in this case they should be field variables.Example content.add(new JLabel("Look at this"));
Chap-3 Adv Prog 42
J T t
http://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/index.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/index.html7/27/2019 Chapter 3 - GUI and Multimedia
43/271
Java: Text
Component Lines Style Use
JLabel
1 plain, HTML
"page", and/or
an icon
plain or
HTML
For displaying afixedline of text. Can be
HTML
JTextField 1 plain
For entering or displaying one line of plain
text.
JFormattedTextField 1 plain
Added in SDK 1.4, JFormattedTextField is a
subclass of JTextField for which the type of
entry may be specified. For example, a field
can be constructed to only accept integer
values.
JPasswordField 1 plain
For entering one line of plain text that
displays a symbol instead of the characters, ie,
for entering passwords. Subclass of JTextField.
JTextArea many plain
For entering or displaying multiple lines of
plain text. Put it into a JScrollPane to add
scrolling.
If you work with text, you need to know about the following user interface
text components.
JLabel
http://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/index.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/10labels/10label.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/30textfield/11textfield.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/40textarea/20textarea.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/40textarea/20textarea.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/30textfield/11textfield.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/10labels/10label.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/index.html7/27/2019 Chapter 3 - GUI and Multimedia
44/271
JLabel0 Labels display fixed text or imageson a GUI as information to
the user, for example, as a label in front of a a JTextField, etc. You
can have text (including HTML), an image, or both on a JLabel. AJLabel has a transparent background, so it will always match the
container it is in.
0 JLabel Constructors
Assume the following declarations.String text;
Icon image;
int alignment; // JLabel.LEFT, JLabel.Center, or JLabel.RIGHT.
JLabelyourLabel= new JLabel(text);JLabelyourLabel= new JLabel(text, alignment);
JLabelyourLabel= new JLabel(image);
JLabelyourLabel= new JLabel(image, alignment);
JLabelyourLabel= new JLabel(text, image, alignment); 44
Jl b l( t)
7/27/2019 Chapter 3 - GUI and Multimedia
45/271
Jlabel(cont)
0 Java Idiom
Because there is usually no need to refer to a JLabel after it has
been added to a container, it is common to combine creation and
adding the JLabel in one statement.
For example.
...
p.add(new JLabel("Enter your ID:", JLabel.RIGHT));
is the same as
JLabel idLabel = new JLabel("Enter ID:", JLabel.RIGHT);
. . .p.add(idLabel);
45
Jlabel(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
46/271
Jlabel(cont)HTML in JLabels
0 You may put HTML text in a JLabel. In this case the text shouldbegin with and end with .
0 JLabel font and color
The most user-friendly interfaces are usually obtained by using the
default appearance (font, color, background), but there are caseswhere you want to change these.
0Appearance: setting the font
The font of a JLabel can be changed like this.
JLabel title = new JLabel(Enter Name :", JLabel.CENTER);
title.setFont(new Font("Serif", Font.BOLD, 48));
46
Jlabel(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
47/271
Jlabel(cont)HTML in JLabels
0Appearance: setting the text color
Use the setForeground method to set the text color.JLabel title = new JLabel(Name :", JLabel.CENTER);title.setForeground(Color.white);
0Appearance: setting the background color
Because a JLabel's background is transparent, there is no effectfrom using the setBackground method. To make a new background,
you need to create a JPanel with the appropriate color and put the
label on that. For exampleJLabel title = new JLabel(Enter your name");title.setForeground(Color.white);
JPanel titlePanel = new JPanel();titlePanel.setBackground(Color.blue);
titlePanel.add(title);
// adds to center of panel's default BorderLayout.47
Jlabel(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
48/271
Jlabel(cont)JLabel for output
0 Why using JLabel for output is usually bad
It's possible to change the text of a JLabel, although this is not generally agood idea after the user interface is already displayed. For outputJTextField is often a better choice. The use of JLabel for output ismentioned because some textbooks display output this way. Here aresome reasons notto use it.
0 Can't copy to clipboard. The user can not copy text from a JLabel, but
can from a JTextField.0 Can't set background. Changing the background of individual
components probably isn't a good idea, so this restriction on JLabels isnot serious. You can change the background of a JTextField, for better orworse.
0 Text length. This is where there are some serious issues. You canalways see the entire text in a JTextField, altho you might have to scrollit it's long. There are several possibilities with a JLabel. You may eithernot see all of the long text in a JLabel, or putting long text into a JLabelmay cause the layout to be recomputed, resulting in a truly weird userexperience.
48
Jl b l( )
7/27/2019 Chapter 3 - GUI and Multimedia
49/271
Jlabel(cont)
0 Changing the text of a JLabel
Most JLabels are never changed, except for internationalization, and
that is done before the user interface is shown. To change the text,
use
yourLabel.setText(String newText);
49
JTextField
7/27/2019 Chapter 3 - GUI and Multimedia
50/271
JTextField0 javax.swing.JTextField has two uses.
Input. The user can enter one line of text (a String)
Output. To display one line of text.
0 If you need a component that displays or allows entry of
more than one line, use a JTextArea.
0 Overview of methods
Chap-3 Adv Prog 50
JTextFieldJTextField(width)
setText(text)
String getText()
addActionListener(listener)
setEditable(true/false)
setFont(font)
setHorizontalAlignment(align)
requestFocus(align)
JTextField(cont)
http://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/40textarea/20textarea.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/40textarea/20textarea.html7/27/2019 Chapter 3 - GUI and Multimedia
51/271
JTextField(cont)To use a JTextField for Input
1. Declarea JTextField as an instance variable. Reason: If it's an
instance variable, it can be seen in all methods in the class.2. Assign an initial value to this variable by calling the JTextField
constructor. Specify the approximate field width in the constructor.Example:JTextFieldyourInpuField= new JTextField(16);
3. Addthe text field to a container.
content.add(yourInputField);
or to add it to a JPanel p
p.add(yourInputField);
4. Inputis done by calling thegetText().1. Get the string in the text field by callingyourTextField.getText() method
whenever you need it. This is probably the most common way.
String x = yourInputField.getText();2. Attach an action listener to the text field. It is called whenever the user
types Enter in that field. The listener can then get the text and process it.
Chap-3 Adv Prog 51
JTextField(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
52/271
JTextField(cont)To use a JTextField for Output
0 Using a JTextField for output is almost the same as for input, but . . .
1. Set the text field withyourTextField.setText(someString)
2. If it's only for output, call .setEditable(false) so the user can'tchange the field.
0 Here is the sequence.
1. Declare and initialize a JTextFieldas a field variable (instancevariable). Example:
JTextField myOutput = new JTextField(16);
You can also set the initial value in the field
JTextField myOutput = new JTextField("someInitialValue", 20);
2. Add the text field to a container. For example, to add it to JPanel p.p.add(myOutput);
3. Setting the value of the text field. Whenever you want put a stringvalue in the text field, call myOutput.setText("Some text").
myOutput.setText("some text");Chap-3 Adv Prog
52
JTextField(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
53/271
JTextField(cont)0 Constructors
JTextField tf= new JTextField(int columns);
The number of columns is approximate because the width of text
depends on the font and width of individual characters.
JTextField tf= new JTextField(String initial);This puts the initialString in the JTextField. The size of the JTextField
is set from this String.
JTextField tf= new JTextField(String initial, int columns);This creates a JTextField columnswide with value initial.
Chap-3 Adv Prog53
JTextField(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
54/271
JTextField(cont)Common methods
0 Here are some of the most common methods use with text fields: Assum
these declarationsJTextField tf;
ActionListener listener;
String s,
text;
Fontf;//--- When used for input.
s= tf.getText(); // gets the text from the JTextFieldtf.addActionListener(listener);// Optional listener intialization.
//--- When used for output.
tf.setText(text);// Sets text in the JTextField.tf.setEditable(false); // Initialization to disallow user changes.
//--- To change the appearance.
tf.setHorizontalAlignment(align);//See below for possible values.
tf.setFont(f); // sets the font for the textChap-3 Adv Prog
54
JTextField(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
55/271
JTextField(cont)Appearance of a JTextField - font, alignment
0yourField.setFont(Font f);sets the font for the text. Often numbers ar
aligned to the right (eg, in the display of a calculator), and text is aligned to theleft.
0yourField.setHorizontalAlignment(align); sets the alignment ofthe text in the field, where alignis one of these values: JTextField.LEFT(the default), JTextField.CENTER, or JTextField.RIGHT.
0 Example
JTextField userID; // declare a field . . .
userID = new JTextField(8); // create field approx 8 columns wide. p.add(userID);// add it to a JPanel
userID.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
... // THIS CODE IS EXECUTED WHEN RETURN IS TYPED
}
}
);Chap-3 Adv Prog
55
JTextField(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
56/271
JTextField(cont)Use JPasswordField for passwords
0 Use a JPasswordField component for a field where the characters
the person enters are replaced by some other character.JPasswordField is a subclass of JTextField.
Use JFormattedTextField to restrict input format
0 The JPasswordField subclass of JTextField can be used to restrictthe input to particular values.
Focus
0 To select a JTextField so that user typing occurs in that field, you
must give the JTextFieldfocus. For example, the nameField
JTextField can be given focus with:
nameField.requestFocus();Chap-3 Adv Prog
56
JTextArea
7/27/2019 Chapter 3 - GUI and Multimedia
57/271
JTextArea0 A javax.swing.JTextArea is a multi-linetext component to display
text or allow the user to enter text.
0 Using a JTextArea for output -- Setting the text0 Assume: JTextArea ta;
int i, w, pos, start, end, line;
String s; boolean b;
Font f;
Reader reader;
Writer writer;
Chap-3 Adv Prog 57
Result Method DescriptionConstructors
ta= new JTextArea(rows, cols); Creates text area. colsis approx char
width.
ta= new JTextArea(s, rows, cols); As above, but also containing initial
string s.
JTextArea(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
58/271
JTextArea(cont)
Chap-3 Adv Prog 58
Result Method Description
Setting text
ta.setText(s); Replaces all text with s.
ta.append(s); Appends sto the end.
ta.insert(s, pos); Inserts sat positionpos.
ta.replaceRange(s, start, end); Replace startto endwith s.
Getting text
s= ta.getText(); Returns all text. Use methods below to get
individual lines.
i= ta.getLineCount(); Returns number of lines in the text area.
i= ta.getLineStartOffset(line); Returns character index of beginning of lineline. May throw
javax.swing.text.BadLocationException.
i= ta.getLineEndOffset(line); Returns character index of end of line line.
May throw
javax.swing.text.BadLocationException.
JTextArea(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
59/271
JTextArea(cont)
Chap-3 Adv Prog 59
Result Method Description
Changing the appearance/function
ta.setBorder(brdr); Text is tight against edge. See example belowto add space.
ta.setLineWrap(b); Lines wrapped if true. Default false.
ta.setWrapStyleWord(b); If wrapping on (see above), wraps at words
(true) or chars (false). Default false.
ta.setTabSize(w); Number of max width chars in a tab.ta.setFont(f); Displays using Fontf.
ta.setEditable(b); Set false to disable user editing.
ta.setCaretPosition(i); Set caret position. If content is scrolled,
setCaretPosition(0) will move to top.
Reading and writing to/from a JTextArea
ta.read(reader, null); Reads text from readerinto text area. May
throw IOException.
ta.write(writer); Writes text from text area to writer. May
throw IOException.
JTextArea(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
60/271
JTextArea(cont)Scrolling
0 JTextArea doesn't support scrolling itself but you can easily addthe JTextArea to a JScrollPane. JScrollPane creates scrollbars as
needed. For example,
//... Create scrolling text area.resultTA = new JTextArea("This is a test", 10, 80);JScrollPane scrollingResult = newJScrollPane(resultTA);
content.add(scrollingResult);
Chap-3 Adv Prog 60
JTextArea(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
61/271
JTextArea(cont)Scrollbar policy
0 There are threepoliciesthat you can specify for the scrollbars. Below is how you
set if for the horizontal scrollbar, but change "horizontal" to "vertical" as needed.0 ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED - Default value.
0 ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
0 ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS
0 It's Unncessaryto have horizontal scrolling when wrapping is turned on.Wrapping takes precedence over horizontal scrolling.
Positioning the scrolling view to the top - moving the caret
0 If more lines are added than can be displayed and the scrollbars appear, theposition that shows can be controlled with setCaretPosition(pos) , whereposis acharacter position between 0 and the length of the text. To move to the top, useposition 0.
Chap-3 Adv Prog 61
Result Method Description
scrollPane.setHorizontalScrollBarPolicy(policy); Wherepolicyis described above.
scrollPane.setVerticalScrollBarPolicy(policy); Wherepolicyis described above.
JTextArea(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
62/271
JTextArea(cont)Space between text and edge improves appearance
0 JTextArea leaves no space between the edge andtext that it holds.This can be fixed by adding an empty border to it.
outArea.setBorder(BorderFactory.createEmptyBorder(4,4,4,4));
0 Example: Common JTextArea+JScrollPane usage
Setting up a text area can be slightly tedious. Here is an example.
JTextArea outputTA = new JTextArea(12, 40);
. . .
outputTA.setLineWrap(true);
outputTA.setWrapStyleWord(true);outputTA.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
JScrollPane scroller = new JScrollPane(outputTA);scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
. . .
content.add(scroller, ...);
Chap-3 Adv Prog 62
7/27/2019 Chapter 3 - GUI and Multimedia
63/271
JTextArea(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
64/271
JTextArea(cont)public class TextAreaDemoB extends JFrame {
JTextArea _resultArea = new JTextArea(6, 20);
public TextAreaDemoB() {
//... Set textarea's initial text, scrolling, and border. _resultArea.setText("Entermore text to see scrollbars");
JScrollPane scrollingArea = new JScrollPane(_resultArea);
//... Get the content pane, set layout, add to center
JPanel content = new JPanel();
content.setLayout(new BorderLayout());content.add(scrollingArea, BorderLayout.CENTER);
//... Set window characteristics.
this.setContentPane(content);
this.setTitle("TextAreaDemo B");this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack(); }//=============================================================public main public static void main(String[] args) {
JFrame win = new TextAreaDemoB();
win.setVisible(true);
}
}
Chap-3 Adv Prog 64
Java: Buttons
http://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/index.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/index.html7/27/2019 Chapter 3 - GUI and Multimedia
65/271
Java: Buttons
Components Description
JButton This is a standard button which can have text,
icon, or both.
Listener: addActionListener(...)
JCheckBox The box next to the text can be toggled on or off.
JRadioButton, ButtonGroup Radio buttons are a group of buttons that can have
at most one button toggled on. When you click one
button, that button is toggled on, and all others
are set to off.
JMenuItem Menu items are a kind of button.
JToggleButton Changes between two states: on and off. Stays
on/off until the next click.
Chap-3 Adv Prog 65
There are many kinds of buttons, all derived from theAbstractButtonclass.
JButton
http://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/index.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/20buttons/10jbutton.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/components/20buttons/10jbutton.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/index.html7/27/2019 Chapter 3 - GUI and Multimedia
66/271
JButton0 There are a few steps in using a button: declaring it, creating it,
adding it to a container (the content pane or a JPanel), and adding alistener that has code to execute when the user clicks on the button.
Images can be used on buttons, including automatic rollover effects.0 Constructors
0 Assume these declarations.
String text;
Icon image;
JButton btn = new JButton(text);JButton btn = new JButton(text, image);JButton btn = new JButton(image); Common methods0 Assume these declarations:
JButton btn;
ActionListener listener;boolean b;
//--- Buttons always have action listeners.btn.addActionListener(listener);btn.setEnabled(b);
Chap-3 Adv Prog 66
Jbutton(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
67/271
Jbutton(cont)0 Events : When a button is clicked, the actionPerformed()method is called
for all of the button's listeners. It is passed an ActionEvent, which isgenerally ignored, but can be used to identify which component generated
the event if several share the same listener. The example below shows thecreation of a button, attaching a listener, and adding the button to acontainer.
0 Example
0 Typically a button is assigned to a local variable (not an instance variable)and an anonymous action listener is added to it. The listener often calls
another method to do everything because separating the code to build theuser interface and do the "semantics" makes a program clearer and easierto modify.
JButton mybtn = new JButton("Do Something");mybtn.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
doMyAction(); // code to execute when button is pressed}
}); . . .
content.add(mybtn); // add the button to a JPanel (eg, content).67
Jbutton(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
68/271
Jbutton(cont)JButton Appearance
0 Dynamically changing a button
0 You can change the text or icon (image) that appears on a
button with:
btn.setText("someText");
btn.setIcon(anIcon);0 WARNING: If you change the sizeof the button by one of these
changes, this may have consequences in the layout of the
components. This may require a call to validate() or
revalidate() which then computes a new layout based on the
change in the button size. This is not a quick operation.
Replacing an icon with another of the same size should notcause any problems.
68
Jbutton(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
69/271
Jbutton(cont)Buttons with Icons
0 You can create buttons that show text, icons (images), or both.
Different images can be associated with different button states
and user interactions with the button (disabled, rollover, ...). The
two supported image formats are GIF and JPEG, although
support for more image types is being worked on.
0 To create a button with an iconJButton next = new JButton(new ImageIcon("right.gif"));
or
JButton next = new JButton("Next", rightArrow);
69
Jbutton(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
70/271
Buttons with IconsMethods to change the icon on a JButton
0 It is common to show different icons when the button is disabled, the
mouse is over it (rollover), etc. Java recognizes seven (7) differentstates for a button, and you can set a different image for each state.
0 Java computes two button images automatically: the disabledimage iscomputed from the normal image, and the selected, disabledimage iscomputed from the selectedimage if one is supplied.
0 Rollover image changes are not automatic -- first you must callb.setRolloverEnabled(true) ;.
JButton b = new JButton(Icon x); // Create button with normal iconb.setIcon(Icon x);
b.setDisabledIcon(Icon x);
b.setPressedIcon(Icon x);b.setSelectedIcon(Icon x);
b.setDisabledSelectedIcon(Icon x);
b.setRolloverEnabled(boolean b); // turn on before rollovers workb.setRolloverIcon(Icon x);
b.setRolloverSelectedIcon(Icon x);
70
JComboBox (uneditable)
7/27/2019 Chapter 3 - GUI and Multimedia
71/271
JComboBox (uneditable)Making Choices
0 There are several ways to select one of many fixed choices: radio
buttons, a menu, a list, or a (uneditable) combo box. A combo box(JComboBox) is a popup menu and is often the best component to usebecause it uses less space than radio buttons or a list, and it shows aspart of a "form" so the user realizes it's there, unlike a menu.
You can also use an editable combo box, and in this case the user caneither choose from the pop-up menu or type in a value.
Constructor
0 An easy way to build a combo box is to initialize an array (or Vector,but not yet the new Collections types) of strings and pass it to theconstructor. Objects other than strings can be used, but this is themost common. The list also be built by successive calls to the addmethod.
String[] dias = {"lunes", "martes", "miercoles"};
JComboBox dayChoice = new JComboBox(dias);
Chap-3 Adv Prog
71
JComboBox (uneditable)
7/27/2019 Chapter 3 - GUI and Multimedia
72/271
JComboBox (uneditable)Common methods0 In these prototypes, assume the following. int index;
String item;String obj; // obj can be any object type, but is commonly
String JComboBox cb = new JComboBox(. . .);
Chap-3 Adv Prog
72
Result Call Description
cb.addActionListener(...); Add listener -- same as for button.
Modifying a JComboBox
cb.setSelectedIndex(index); Set default, visible, choice.
cb.setSelectedItem(obj); Set default, visible, choice.
cb.add(item); Add additional item to the list
cb.insert(item, index); Add additional item after index.
cb.remove(item); Remove item from the list
cb.remove(index); Remove item as position index
Testing a JComboBox
index = cb.getSelectedIndex(); Return index of selected item.
obj = cb.getSelectedItem(); Return selected item.
JComboBox (uneditable)
7/27/2019 Chapter 3 - GUI and Multimedia
73/271
JComboBox (uneditable)Events
0 A JComboBox generates both ActionEvents (like buttons, text fields, etc), orItemEvents. Because it is easier to work with ActionEvents, we'll ignore the
ItemEvents. When the user chooses an item from a combo box, an ActionEvent isgenerated, and the listener's actionPerformed method is called. Use eithergetSelectedIndex to get the integer index of the item that was selected, orgetSelectedItem to get the value (eg, a String) that was selected.
0 Example
0 This example creates a JComboBox, and adds a listener to it. The getSelectedItemmethod returns an Objecttype, so it's necessary to downcast it back to a
String.String[] fnt = {"Serif", "SansSerif", "Monospaced"};JComboBox fontChoice = new JComboBox(fnt);fontChoice.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {JComboBox combo = (JComboBox)e.getSource();currentFont = (String)combo.getSelectedItem();}
});
Chap-3 Adv Prog
73
JCheckBox
7/27/2019 Chapter 3 - GUI and Multimedia
74/271
JCheckBox
0 A javax.swing.JCheckBox shows a small box that is either
markedor unmarked. When you click on it, it changes from
checked to unchecked or vice versa automatically. You don't
have to do any programming for the checkbox to change.
0 There are two ways to use a checkbox:
1. Active.Use addActionListeneror addItemListener() so that a
method will be called whenever the checkbox is changed.
2. Passive.Use isSelected()to test if a checkbox is checked.
Chap-3 Adv Prog 74
JCheckBox(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
75/271
JCheckBox(cont)0 Common constructors and methods
0 Assume
JCheckBox cb; // A checkbox.
String text; // Label on text box.
boolean state; // True/false state of checkbox.
Chap-3 Adv Prog 75
Constructorscb=new JCheckBox(text); Creates check box, initially unchecked.
cb=new JCheckBox(text, state); Creates check box, checked or not depending on state.
Methods
state=cb.isSelected(); Returns true if the check box is checked.
cb.setSelected(state); Checks (true) or unchecks check box.
cb.addActionListener(action-
listener);
Adds an action listener to the radio button. The
action listener will be called if button is selected.
cb.addItemListener(item-
listener);
Add an item listener to a radio button. The item
listener will be called if the button is selected or
deselected.
JCheckBox
7/27/2019 Chapter 3 - GUI and Multimedia
76/271
JCheckBox0 Example using an ActionListener
0 An ActionListener should probably be preferred to an ItemListener, and this needsto have a little more explanation.
0 Example with anonymous inner class ItemListener0 This example creates a checkbox (ignoreCase) that is already checked, and adds it
to the JPanel (content). It sets the boolean variable (ignore) whenever the box stateis changed by the user.
boolean ignore = true; // true if should ignore case . . .
JCheckBox ignoreCase = new JCheckBox("Ignore Case", true);ignoreCase.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {// Set "ignore" whenever box is checked or unchecked.ignore = (e.getStateChange() == ItemEvent.SELECTED);
}}
);content.add(ignoreCase);
76
JCheckBox
7/27/2019 Chapter 3 - GUI and Multimedia
77/271
JCheckBox0 Example checking state
0 This example is similar to the above, but gets the state of the
checkbox when the value is needed.JCheckBox ignoreCase;
. . . //... inside window constructor
JCheckBox ignoreCase = new JCheckBox("Ignore Case", true);content.add(ignoreCase);
. . .
//... Inside processing method, eg in button listener.
if (ignoreCase.isSelected()) {
. . .
77
Radio Buttons(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
78/271
Radio Buttons(cont)0 Radio buttons (javax.swing.JRadioButton) are used in groups
(java.awt.ButtonGroup) where at most one can be selected. The
example below produced this image. A radio button group startswith all buttons deselected, but after one is selected the only way
to have them appear all off is to have an invisible button that is
selected by the program.
Chap-3 Adv Prog 78
Radio Buttons(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
79/271
Radio Buttons(cont)0 Source code for above example
0 This example creates a group of three radio buttons, puts them in agrid layout on a panel, and puts a titled, etched border around them.
JRadioButton yesButton = new JRadioButton("Yes" , true);JRadioButton noButton = new JRadioButton("No" , false);JRadioButton maybeButton = new JRadioButton("Maybe",false);
ButtonGroup bgroup = new ButtonGroup();bgroup.add(yesButton);bgroup.add(noButton);bgroup.add(maybeButton);
JPanel radioPanel = new JPanel();
radioPanel.setLayout(new GridLayout(3, 1));radioPanel.add(yesButton);radioPanel.add(noButton);radioPanel.add(maybeButton);radioPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Married?"));
Radio Buttons(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
80/271
Radio Buttons(cont)
Testing the status of radio buttons
0 There are several ways to find out about radio button states:
During execution, test the radio button with isSelected().
In the setup phase, add an action listener with
addActionListener(...). ActionListeners are called when a radio
button is selected. In the setup phase, add an item listener with addItemListener.
ItemListeners are called both when the radio button is selected and
(automatically) deselected.
Chap-3 Adv Prog 80
Radio Buttons(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
81/271
Radio Buttons(cont)
0 JRadioButton methods
boolean b;
JRadioButton rb= new JRadioButton("Sample", false);
0 Common JRadioButton methods
Chap-3 Adv Prog 81
b=rb.isSelected(); Returns true if that button isselected.
rb.setSelected(b); Sets selected status of a radio button to
b(true/false).
rb.addActionListener(an-action-listener); Adds an action listener to the radio
button. The action listener will be
called if button is selected.
rb.addItemListener(an-item-listener); Add an item listener to a radio button.
The item listener will be called if the
button is selected or deselected.
Radio Buttons(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
82/271
Radio Buttons(cont)0 ButtonGroup methods
0 The most common method used for a button group is add(), but
it's also possible to get or set the selected button. Assume:
JRadioButton rb= new JRadioButton("Sample", false);ButtonGroup bgroup= new ButtonGroup();
0 Common ButtonGroup methods
Chap-3 Adv Prog 82
bgroup.add(rb); Adds a button to a radio button
group.
rb=bgroup.getSelectedJRadioButton(); Returns the radio button which is
currently selected.bgroup.setSelectedJRadioButton(rb); Sets the status of a particular radio
button (unsetting others).
bgroup.add(rb); Adds a button to a radio button group.
Sliders
7/27/2019 Chapter 3 - GUI and Multimedia
83/271
Sliders0 A slider (JSlider class) lets the user easily select from a range of
integer values. Use sliders for integer input whenever you can.
They are easier for the user than text fields, and there is no
possibility of illegal input values, so your programming is
simpler.Constructors
0 The usual constructor is JSlider s = new JSlider(orientation, min,
max, initial);orientation: JSlider.HORIZONTAL orJSlider.VERTICAL
min: The minimum value.
max: The maximum value.
initial: The initial value.
0 Example:JSlider sl = new JSlider(JSlider.HORIZONTAL, 0, 20, 10);
Chap-3 Adv Prog 83
Sliders(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
84/271
Sliders(cont)Tick Marks
0 You can add both majorand minor tick marks. You must call
setPaintTicks(true) to make the tick marks appear.
0 Here is an example that sets major tick marks every 10 values
and minor tick marks every 1 value:
sl.setMajorTickSpacing(10); // sets numbers for biggest tick
marks
sl.setMinorTickSpacing(1); // smaller tick marks
sl.setPaintTicks(true); // display the ticksLabels
0 To display the values next to the major tick marks:sl.setPaintLabels(true);
Chap-3 Adv Prog 84
Sliders(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
85/271
( )Listeners and getting the slider value
0 We will see how to do something when the slider is changed in
the next lessons.
Advanced Appearance
0 In addition to tick marks, you can specify text or icon labels atany values that you specify usingsetLabelTable(...). You can
also specify which end of the slider should have the high or low
values usingsetInverted(true/false).
Chap-3 Adv Prog 85
Menus
7/27/2019 Chapter 3 - GUI and Multimedia
86/271
Types of menus
0 A menu is a way to arrange buttons. There are several types.
0 Traditional dropdown menusare positioned across the top of a
window in a menu bar, and display below the menu name.
0 Popup menusappear when the user clicks, egwith the right
mouse button, on a component that can handle a popup request.
Menus and Menu Items are Buttons!
0 It is easy to see how menu items are buttons that appear when a
menu appears. But the menu names in the menu bar are also
buttons. When you press on these "buttons", they create a
popup menu that you see as a dropdown menu.
Chap-3 Adv Prog 86
Menus(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
87/271
Dropdown menus: JMenuBar, JMenu, and JMenuItem
0 A menu barcan be added to the top of a top-level container, eg,
JFrame, JApplet, or JDialog. Note that a menu bar can not beadded to JPanel.
0 Dropdown menus have three parts:
1. JMenuBaris positioned across the top of a container (egaJFrame, JPanel, or JApplet). It's placed above the content pane,
so does not use the container's layout. Add menusto themenubar.
2. JMenuhas a name and contains a number of menu itemswhich are displayed is a vertical list of menu items.
3. JMenuItems and Separatorsare added to each menu. Menuitems are usually text "buttons", but can also have icons,checkboxes, radio buttons, or be hierarchical submenus.
Chap-3 Adv Prog 87
7/27/2019 Chapter 3 - GUI and Multimedia
88/271
7/27/2019 Chapter 3 - GUI and Multimedia
89/271
Menus(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
90/271
0 Menu item mnemonicsare used to select a menu item when its
menu is already open. Typically the character corresponds to
the first, or a significant, letter in the menu item name. That
letter in the menu item will be underlined.
openItem.setMnemonic('O');
0Acceleratorkey combinations are used to directly invoke a
menu item without opening the menu, for example the common
CTRL-C (Copy) execute the copy menu action. Accelerator key
options are displayed to the right of the menu item name.
Adding accelerator key requires using KeyStrokecodes. There
are several ways to get these codes, but the model below showsone of the easiest.
openItem.setAccelerator(KeyStroke.getKeyStroke("control O"));
Chap-3 Adv Prog 90
Menus(cont)Jframe frame = new Jframe();
7/27/2019 Chapter 3 - GUI and Multimedia
91/271
( )frame.setTitle(Menu Sample");
frame.setBounds(100, 100, 500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//menu items, then munu and finaly menubar
//menu itemes
JMenuItem mi1 = new JMenuItem("item 1...");
mi1.setMnemonic('I');
mi1.setAccelerator(KeyStroke.getKeyStroke("control I"));
JMenuItem mi2 = new JMenuItem("item 2");
mi2.setMnemonic('T');
mi2.setAccelerator(KeyStroke.getKeyStroke("alt T"));
JMenuItem mi3 = new JMenuItem("item 3");mi3.setAccelerator(KeyStroke.getKeyStroke("control 3"));
JMenuItem mi4 = new JMenuItem("item 4");
mi4.setAccelerator(KeyStroke.getKeyStroke("alt 4"));
91
Menus(cont)//
7/27/2019 Chapter 3 - GUI and Multimedia
92/271
//menu
JMenu m1 = new JMenu("Menu 1");
m1.add(mi1);
m1.add(mi2);
JMenu m2 = new JMenu("Menu 2");
m2.add(mi3);
m2.add(mi4);
//menubarJMenuBar mbar = new JMenuBar();
mbar.add(m1);
mbar.add(m2);
frame.setJMenuBar(mbar);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
92
Dialogs
7/27/2019 Chapter 3 - GUI and Multimedia
93/271
0 There are several ways to build dialog boxes:
0 JOptionPane - Simple DialogsThis is a very easy way (onestatement) to build simple dialogs. Usually this, JFileChooser,
and maybe JColorChooser are the only dialog classes that you
need.
0 JFileChooserThis will create and control a standard file
chooser dialog.
javax.swing.JColorChooser You can call one static method
(Color.showDialog(. . .)) to display a dialog that lets the user choose
a color, or you can add listeners to make a more complicated dialog
interaction, or you can use this class to create a color chooser pane. javax.swing.Jdialog This can be used for building dialogs that are
too complicated for JOptionPane.
Chap-3 Adv Prog 93
Dialogs(cont)
http://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/containers/20dialogs/10joptionpane.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/containers/20dialogs/30filechooser.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/containers/20dialogs/30filechooser.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/containers/20dialogs/10joptionpane.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/containers/20dialogs/10joptionpane.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/containers/20dialogs/10joptionpane.htmlhttp://d/Acadamy%20case/Advanced%20Programming/ADVANCED%20PROGRAMMING/notes-java-2007-04-25/notes-java/GUI/containers/20dialogs/10joptionpane.html7/27/2019 Chapter 3 - GUI and Multimedia
94/271
Dialogs are attached to window (frame)
0 Every dialog is attached to a window (frame). When the windowin iconified, the dialog will automatically disappear, and it will
automatically reappear when the window is deiconified. When
the window is destroyed, the dialog will disappear.
Dialogs are usually modal
0 When a dialog in active, input to other parts of the graphical
user interface will be blocked. This kind of dialog is called a
modal dialog. If you want a dialog which is modeless(allows
interaction with other windows), you must use the JDialog class.
Chap-3 Adv Prog 94
JOptionPane0 H t f l t ti th d f
7/27/2019 Chapter 3 - GUI and Multimedia
95/271
0 Here are two useful static methods from
javax.swing.JOptionPane that allow you to easily create dialog
boxes for input and output. The Java API documentation has
manymore JOptionPane options, but these are sufficient for
many uses. In the code below userInputand textare Strings.
Use null for the componentparameter if you don't have a
window
0 The dialog box will be centered over the component given in thefirst parameter. Typically you would give the window over
which it should be centered. If your program doesn't have a
window, you may simply write null, in which case the dialog box
will be centered on the screen. 95
Value Method call
userInput = JOptionPane.showInputDialog(component, text);
JOptionPane.showMessageDialog(component, text);
7/27/2019 Chapter 3 - GUI and Multimedia
96/271
JOptionPane(cont)
JOptionPane.showMessageDialog(null, "Hello guys!");
Chap-3 Adv Prog 96
JOptionPane(eg 1)0 This program produces the dialog boxes below
7/27/2019 Chapter 3 - GUI and Multimedia
97/271
0 This program produces the dialog boxes below.
import javax.swing.JOptionPane;
public class JOptionPaneTest1 {
public static void main(String[] args) {
String ans;
ans = JOptionPane.showInputDialog(null, "Speed in miles/ hour?");
double mph = Double.parseDouble(ans);
double kph = 1.621 * mph;
JOptionPane.showMessageDialog(null, "KPH = " + kph);
System.exit(0);
}
}
97
JOptionPane(eg 1)
7/27/2019 Chapter 3 - GUI and Multimedia
98/271
98
This line displays a String, an input text field
(JTextField), and OK and CANCEL buttons. If the user
presses the OK button, the string in the text field is
returned. If the user didn't type anything, the string"" is returned. If the user presses the CANCEL button,
null is returned. Because this call returns a String, it's
necessary in the next line to convert it into a double
to do the arithmetic calculation.
This line displays a String and an OK button. In this
call the String formed by concatenating a String
literal with a number. When a String is concatenated
with anything, that other operand is converted to aString by Java, then the two are put together into a
new String.
7/27/2019 Chapter 3 - GUI and Multimedia
99/271
7/27/2019 Chapter 3 - GUI and Multimedia
100/271
JDi l ( t)
7/27/2019 Chapter 3 - GUI and Multimedia
101/271
JDialog (cont)Example
Icon
description
Java look
and feel
Windows
look and
feel
question
information
warning
error
Chap-3 Adv Prog 101
JFileChooser0 Use javax swing JFileChooser to create a file chooser for
7/27/2019 Chapter 3 - GUI and Multimedia
102/271
0 Use javax.swing.JFileChooserto create a file chooser for
selecting a file or directory to open or save.
To display a file chooser0 Use one of three methods to display the dialog after it has been
created.
r =fc.showOpenDialog(owner); // button labeled "Open"
r =fc.showSaveDialog(owner); // button labeled "Save"r =fc.showDialog(owner, title);
0 The ownerparameter is the component (eg, JFrame, JPanel, ...)
over which the dialog should be centered. You can use null for
the owner, which will put the dialog in the center of the screen.The titleparameter is a string that is used as the dialog's title
and accept button text.
102
JFileChooser(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
103/271
J ( )Checking the return value
0 The user may either select a file or directory, or click CANCEL orclose the file chooser window. If the user selected a file or
directory, the value returned will be
JFileChooser.APPROVE_OPTION. Always check this value.
0 For example,JFileChooser fc = new JFileChooser();
int retval = fc.showOpenDialog(null);
if (retval == JFileChooser.APPROVE_OPTION) {
. . .// The user did select a file.;
103
7/27/2019 Chapter 3 - GUI and Multimedia
104/271
7/27/2019 Chapter 3 - GUI and Multimedia
105/271
JFileChooser(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
106/271
( )Filtering files
0 You can specify the kinds of files that should be shown (eg, with a specific
extension, ...), by supplying a JFileFilter.myChooser.setFileFilter(FileFilter filter);
Eg to select only picture files
JFileChooser myChooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(".txt and
.java files", "txt", "java");
myChooser.setFileFilter(filter);
7/27/2019 Chapter 3 - GUI and Multimedia
107/271
JFileChooser(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
108/271
Specify a start directory in the constructor
0 The file chooser will start the file dialog at some default directory, forexample, "C:\My Documents". To start the dialog at a different directory
(called the current directory), specify the directory path as a String or File
value in the JFileChooser constructor.
JFileChooser m_fileChooser= new JFileChooser("C:\home");
The current directory is ".".
0 Portability warning: If you put system specific file paths in your code, the
program will not be portable to other systems. Note that the above call is
therefore not portable.
JTabbedPane
7/27/2019 Chapter 3 - GUI and Multimedia
109/271
0 Description.
The JTabbedPane container allows many panels to occupy the same area of the
interface, and the user may select which to show by clicking on a tab. A tab mayalso be selected by the program.
0 Constructor
JTabbedPane tp = new JTabbedPane(); // Defaults to tabs along the top edge.
JTabbedPane tp = new JTabbedPane(edge);
Where edgespecifies which edge the tabs are onJTabbedPane.TOP (default)
JTabbedPane.RIGHT
JTabbedPane.BOTTOM
JTabbedPane.LEFT
JTabbedPane (cont)
7/27/2019 Chapter 3 - GUI and Multimedia
110/271
Adding tabs to the JTabbedPane
0 Add tabs to a tabbed pane by calling addTab and passing it a String title and a
component (eg a JPanel) to display in that tab. For example,JTabbedPane display = new JTabbedPane();
display.addTab("Diagram View", diagramPanel);
display.addTab("SQL View" , sqlPanel);
display.addTab("Instructions", instructionPanel);
Selecting the tab to display
0 A tab can be selected by the program using setSelectedIndex().
display.setSelectedIndex(1); // Display SQL View tab
Listening for a tab change0 When the user selects a tab, a ChangeEventis fired. Add a ChangeListenerto
receive notification of the tab change.
______.addChangeListener(ChangeListener cl);
JTabbedPane (cont)
7/27/2019 Chapter 3 - GUI and Multimedia
111/271
JFrame f = new JFrame();
f.setTitle("Tab demo");
f.setSize(500,100);JPanel p = new JPanel();
p.setLayout(new FlowLayout());
JPanel diagramPanel = new JPanel();
JPanel sqlPanel = new JPanel();
JPanel instructionPanel = new JPanel();
JTabbedPane display = new JTabbedPane();
display.addTab("Diagram View", diagramPanel);
display.addTab("SQL View" , sqlPanel);
display.addTab("Instructions", instructionPanel);
display.setSelectedIndex(1);
f.add(display);
f.setVisible(true);
Anatomy of an Application
7/27/2019 Chapter 3 - GUI and Multimedia
112/271
Anatomy of an Application
GUI
Chap-3 Adv Prog 112
JPanel
JButton
JFrame
JLabel
GUI Internal structure
JFrame
JPanel
JButton JLabel
containers
7/27/2019 Chapter 3 - GUI and Multimedia
113/271
Using a GUI Component 2
1. Create it
2. Configure it
3. Add children (if container)
4. Add to parent (if not JFrame)
5. Listen to it
Chap-3 Adv Prog 113
order
important
ld f b
7/27/2019 Chapter 3 - GUI and Multimedia
114/271
Build from bottom up
0 Create:
0 Frame
0 Panel
0 Components0 Listeners
0 Add: (bottom up)
0 listeners into components
0 components into panel0 panel into frame
Chap-3 Adv Prog 114
JPanel
JButton
Listener
JFrame
JLabel
What Is Layout?
7/27/2019 Chapter 3 - GUI and Multimedia
115/271
0 A layout is a set of rules that defines how graphical components
should be positioned in a container.
0 Layouts tell Java where to put componentsin containers
(JPanel, content pane, etc). Every panel (and other container)
has a default layout, but it's better to set the layout explicitly for
clarity.
0 Create a new layout object (using one of its constructors) and
use the container's setLayout method to set the layout. Each
layout has its own way to resize components to fit the layout,
and you must become familiar with these.
115
What Is Layout?(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
116/271
0 There two ways to position a component is a container:
1. Using apredefined layout and allowing the layout to decide
where to position the component. This is a soft way of
positioning a component. If the container changes its size, the
component's position will be adjusted. But you may not able
to get precisely where you want to component to be.
2. Specifying the position of the component using thecontainer's coordinates. This is a hard way of positioning a
component. You can get precisely where you want the
component to be. But if the container changes its size, the
component's position will not be adjusted.
Chap-3 Adv Prog 116
What Is Layout?(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
117/271
AWT offers a number of predefined layouts for you to use:
0 java.awt.BorderLayout- Divides the container into five
regions: east, south, west, north, and center and assigns onecomponent for each region.
0 java.awt.FlowLayout- Takes unlimited number of componentsand let them flow naturally horizontally first, then vertically.
0 java.awt.BoxLayout - Takes unlimited number of componentsand let them flow horizontally or vertically in one direction.
0 java.awt.GridLayout - Divides the container into rows andcolumns and assigns one component for each cell.
0 java.awt.GridBagLayout- Divides the container into rows and
columns and assigns one component for each cell with cell sizesnot equal.
Chap-3 Adv Prog 117
BorderLayout
7/27/2019 Chapter 3 - GUI and Multimedia
118/271
0 It is a very simple layout that:
0 Divides the container into five regions: east, south, west, north,and center.
0 Takes maximum 5 components only, one per region.
0 Resizes each component to match the size of its region.
0 Acts as the default layout in a container.0 Resizes each region when the container is resized.
Chap-3 Adv Prog 118
North
South
West EastCenter
BorderLayout(cont)
7/27/2019 Chapter 3 - GUI and Multimedia
119/271
0 Expand to fill region. Components start at their preferred size, but are
expanded as needed to fill the region they are in.
0 Use subpanel for more than one component in a region. You can add atmost one component to each region of a BorderLayout. To put more than
one component in a section, put them in a JPanel (with its own layout), then
add that panel to the border layout.
0 Where extra space goes? The size of a region is adjusted depending on
what is in it. If there is nothing in an region, its size will be reduced to zero.Components in the North and South cells are stretched horizontally, and
those in East and West are stretched vertically to fill all the space. The center
is stretched vertically and horizontally as needed, so it is a good place to put
graphics or text areas that you want to expand.
0 Specifying the region. When you add components to a container whichuses BorderLayout, specify the target region as the second parameter as, for
example, BorderLayout.NORTH.
0 Not all regions are required If nothing has been added to a region, the
neighboring regions expand to fill that space.Chap-3 Adv Prog
119
BorderLayout(cont)Constructors
7/27/2019 Chapter 3 - GUI and Multimedia
120/271
Constructors
0 If you don't need any space between regions, use the default
constructor. You can also specify the number of pixels betweenregions.
p.setLayout(new BorderLayout()); // Default is no gaps
p.setLayout(new BorderLayout(hgap, vgap);
Where hgapand vgapare the distances in pixels between the
regions.
Chap-3 Adv Prog120
BorderLayout(cont)public static void main(String[] a) {
7/27/2019 Chapter 3 - GUI and Multimedia
121/271
public static void main(String[] a) {
JFrame myFrame = new JFrame("FlowLayout Test");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container myPane = myFrame.getContentPane();
myPane.setLayout(new BorderLayout());
myPane.add(new JButton("North"), BorderLayout.NORTH);
myPane.add(new JButton("South"), BorderLayout.SOUTH);
myPane.add(new JButton("East"), BorderLayout.EAST);myPane.add(new JButton("West"), BorderLayout.WEST);
myPane.add(new JButton(new ImageIcon("java.gif")),
BorderLayout.CENTER);
myFrame.pack();
myFrame.setVisible(true);}
Chap-3 Adv Prog 121
FlowLayoutFlowLayout is a very simple layout that:
7/27/2019 Chapter 3 - GUI and Multimedia
122/271
FlowLayout is a very simple layout that:
0 Takes unlimited number of components.
0 Uses the default size of each component.0 Positions each component next to each other in a row. If there is not enough
room in the current row, the component will be positioned at the beginning
of the next row.
0 Re-arranges the flow when the container is resized.
0 Lets see how flowlayout and othe layouts re-arranges the flow when thecontainer is resized. We wanted the window to look like this:
- Details ----------- ------------------
| Name: Text |
| System: Radio button || Language: Check box |
| Year: Dropdown |
-------------------------- ---------
OK Cancel
Chap-3 Adv Prog 122
FlowLayout(cont)Constructors
7/27/2019 Chapter 3 - GUI and Multimedia
123/271
Constructors
0 Typically the constructor is called in the call to the container's setLayout
method (see example code). The parameterless FlowLayout() constructor is
probably most common, but there are some good places to use the
alignment.
new FlowLayout() // default is centered with 5 pixel gaps
new FlowLayout(int align)
new FlowLayout(int align, int hgap, int vgap)Alignment
0 alignis one of FlowLayout.LEFT, FlowLayout.CENTER (the default), or
FlowLayout.RIGHT. You might want to use the RIGHT aligment when
building a dialog that puts the OK and