0% found this document useful (0 votes)
74 views49 pages

Lecture 9 GUI Basic JLabel, Jbutton, JFrame

Graphical user interfaces provide visual components for user interaction. The Abstract Window Toolkit (AWT) is Java's initial GUI library, while Swing provides more powerful and portable components. Common GUI elements include containers like frames and panels that hold other components, as well as atomic components like buttons, labels, and text fields for user input.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views49 pages

Lecture 9 GUI Basic JLabel, Jbutton, JFrame

Graphical user interfaces provide visual components for user interaction. The Abstract Window Toolkit (AWT) is Java's initial GUI library, while Swing provides more powerful and portable components. Common GUI elements include containers like frames and panels that hold other components, as well as atomic components like buttons, labels, and text fields for user input.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Graphical User Interfaces

Compiled By: Umm-e-Laila & Aneeta Siddiqui

Lecture # 9

1
Course Books

◼ Text Book:
◼ Herbert Schildt, Java: The Complete Reference, McGraw-Hill
Education, Eleventh Edition
◼ Craig Larman, Applying UML & patterns, 2 edition

◼ Reference Books:
◼ Cay S. Horstmann, Big Java: Early Objects, Wiley, 7th Edition
◼ Herbert Schildt, Java: A Beginner's Guide, McGraw-Hill Education,
Eighth Edition

2
Course Instructors

◼ Umm-e-Laila [email protected]
Assistant Professor, CED
Room Number: BS-04
Tel: 111-994-994, Ext. 536

◼ Aneeta Siddiqui [email protected]


Assistant Professor, CED
Room Number: BS-03
Tel: 111-994-994,
Course Website

◼ http://sites.google.com/site/ulaila206

4
Introduction
◼ Up till now you have written programs that
communicate with the end user through a
text-based interface
❑ Using System.out for output
❑ Using Keyboard for input.

◼ Java provides two sets of facilities for


developing GUIs:
❑ The Abstract Window Toolkit (AWT): package
java.awt
❑ Swing: package javax.swing
Abstract Window Toolkit (AWT)
◼ The Abstract Window Toolkit is a portable GUI library.
◼ Sun's initial effort to create a set of cross-platform GUI
classes. (JDK 1.0 - 1.1)
❑ Maps general Java code to each operating
system's real GUI system
◼ AWT provides the connection between your application
and the native GUI.
◼ AWT provides a high-level abstraction since it hides you
from the underlying details of the GUI your program will be
running on.
◼ AWT components depend on native code counterparts
(called peers) to handle their functionality. Thus, these
components are often called heavyweight components.
Swing
◼ Swing implements GUI components that build on AWT
technology.
◼ Swing is implemented entirely in Java.
◼ A newer GUI library written from the ground up that allows
much more powerful graphics and GUI construction. (JDK
1.2+)
❑ Paints GUI controls itself pixel-by-pixel rather than handing off to OS.
❑ Benefits: Features; compatibility; OO design.
◼ Swing components do not depend on peers to handle their
functionality. Thus, these components are often called
lightweight components.
◼ Problem
◼ Both exist in Java now; easy to get them
mixed up; still have to use both in various places.
Peers and Platform Independence
◼ The first AWT (Java 1.0) was rolled out in an
incredible 6 weeks using peers
◼ Thus an AWT menu on the Solaris platform,
for example, actually creates a Motif menu
object as its peer
◼ UI components that have peers are called
heavyweight because
❑ they are rendered in their own
(opaque) windows and thus are
expensive to use,
❑ they must be rectangular and

cannot have transparent backgrounds, and


❑ they are not amenable to being subclassed
Using Peers

Native
Java Java Window
Program AWT System
Peers

A Java program creates and displays an AWT component,


which creates and displays a native component, or peer.
Swing: Pros and Cons
 Pros
 Portability: Pure Java implementation.
 Features: Not limited by native components.
 Look and Feel: Pluggable look and feel. Components
automatically have the look and feel of the OS their running
on.
 Cons
 Performance: Swing components handle their own
painting (instead of using APIs like DirectX on Windows).
 Look and Feel: May look slightly different than native
components.
AWT: Pros and Cons

 Pros
 Speed: native components speed performance.

 Look and feel: AWT components more closely reflect


the look and feel of the OS they run on.
 Cons
 Portability: use of native peers creates platform
specific limitations.
 Features: AWT supports only the lowest common
denominator—e.g. no tool tips or icons.
AWT Packages
java.awt Basic component functionality
java.awt.accessibility Assistive technologies
java.awt.color Colors and color spaces
java.awt.datatransfer Clipboard and data transfer support
java.awt.dnd Drag and drop
java.awt.event Event classes and listeners
java.awt.font 2D API font package
java.awt.geom 2D API geometry package
java.awt.im Input methods
java.awt.image Fundamental image manipulation classes
java.awt.peer Peer interfaces for component peers
java.awt.print 2D API support for printing
GUI terminology
◼ A container is a type of component that has the purpose of containing other components.

◼ window: A first-class citizen of the graphical desktop.


❑ Also called a top-level container.
❑ examples: frame, dialog box, applet
❑ Top-level containers cannot be added to other containers.
 There are three top-level Swing containers
 JFrame: window that has decorations, such as a border, a title, and buttons for iconifying and closing
the window
 JDialog: a window that's dependent on another window
 JApplet: applet's display area within a browser window

◼ container: A logical grouping for storing components.


❑ examples: panel
 Also called a Intermediate containers: used to group components so that they can be handled as a
single component (e.g JPanel, JTabbedPane).
GUI terminology
◼ component: A GUI widget that resides in a
window.
❑ Atomic components (basic controls): cannot contain
other components (e.g JButton, JTextField).
❑ Also called controls in many other languages.
❑ examples: button, text box, label
◼ Often called widgets:
❑ Label – used to put a label next to another component
❑ Button – used to make the program “do something”
❑ Checkbox component – used for yes/no, true/false response from
user
❑ Choice component – drop-down list
❑ TextField – used to type single line of text
Components
Swing inheritance hierarchy
◼ Component (AWT) import java.awt.*;
❑ Window import javax.swing.*;
◼ Frame
• JFrame (Swing)
• JDialog

❑ Container
◼ JComponent (Swing)
• JButton JColorChooser JFileChooser
• JComboBox JLabel JList
• JMenuBar JOptionPane JPanel
• JPopupMenu JProgressBar JScrollbar
• JScrollPane JSlider JSpinner
• JSplitPane JTabbedPane JTable
• JToolbar JTree JTextArea
• JTextField ...
Description of Classes
◼ Object: All classes ultimately derive from Object, thus this
class is at the top of the tree.
◼ Component: represents an object that has a visual
representation that can be shown on-screen and that can
interact with users. This class defines some basic methods
that are available to all Swing classes.
◼ Container: builds on the basic visual capabilities of the
Component class by adding the ability to hold other
containers.
◼ Window: a specialized type of container object that has a
border, a title bar, buttons that minimize, maximize, and
close the window, and that can be repositioned and
possibly even resized by the user.
Description of Classes (Cont’d)
◼ Frame: a type of Window that serves as the basis for Java
GUI applications. Frame is an AWT class that has been
improved upon by the JFrame class.
◼ JFrame: the Swing version of the older Frame class. Most
of the Swing applications include at least one JFrame
object.
◼ JComponent: is the basis for all other Swing components
except for frames.
◼ JPanel: used to organize and control the layout of other
components such as labels, buttons, text fields, etc. In
most Swing applications, one or more panels are added to
a frame. Then, when the frame is displayed, the
components that were added to its panels are made
visible.
JFrame
a graphical window to hold other components
A JFrame is a container. Containers have these methods and
constructors:
◼ public JFrame()
public JFrame(String title)
Creates a frame with an optional title.
◼ Call setVisible(true) to make a frame appear on the
screen after creating it.
◼ public void add(Component comp)
Places the given component or container inside the frame.
◼ public void add(Component comp, Object info)
Adds a component to the container, possibly giving extra
information about where to place it.
◼ public void remove(Component comp)
More JFrame
◼ public void setDefaultCloseOperation(int op)
Makes the frame perform the given action when it closes.
❑ Common value passed: JFrame.EXIT_ON_CLOSE
❑ If not set, the program will never exit even if the frame is closed.
◼ public void setSize(int width, int height)
Gives the frame a fixed size in pixels.
◼ public void pack()
Resizes the frame to fit the components inside it snugly.
◼ public void setLayout(LayoutManager mgr)
Uses the given layout manager to position components.
◼ public void validate()
Refreshes the layout (if it changes after the container is onscreen).
◼ void setLocation (int x, int y)
Sets the x and y position of the frame on-screen. The top-left corner of the screen is
0, 0.
JLabel
◼ Labels
❑ Provide text instructions on a GUI

❑ Read-only text
❑ Programs rarely change a label's contents

❑ Class JLabel (subclass of JComponent)

◼ You can specify the font, size, whether the text is bold, italic, or underlined, what
color the text is displayed as, and so on
Constructor Description

JLabel() Creates a JLabel instance with no image and


with an empty string for the title.
JLabel(String s) Creates a JLabel instance with the specified
text.
JLabel(Icon i) Creates a JLabel instance with the specified
image.
JLabel(String s, Icon i, int horizontalAlignment) Creates a JLabel instance with the specified
text, image, and horizontal alignment.
◼ Methods
❑ myLabel.setToolTipText( "Text" )
◼ Displays "Text" in a tool tip when mouse over label
❑ myLabel.setText( "Text" )
❑ myLabel.getText()

 A label can also display an image, or it can display both an image


and some text.
 Icon
 Object that implements interface Icon
 One class is ImageIcon (.gif and .jpeg images)
 Icon bug = new ImageIcon( "bug1.gif" );
 Assumed same directory as program
 Display an icon with JLabel’s setIcon method
 label3.setIcon( bug );
 myLabel.setIcon( myIcon );

 myLabel.getIcon //returns current Icon


JButton
a clickable region for causing actions to occur
Constructor Description

JButton() It creates a button with no text and icon.


JButton(String s) It creates a button with the specified text.
JButton(Icon i) It creates a button with the specified icon
object.

◼ public String getText()


Returns the text showing on the button.
◼ public void setText(String text)
Sets button's text to be the given string.
◼ void setEnabled (boolean value)
◼ Enables or disables the button. The default setting is true (enabled).
◼ void setToolTipText (String text)
Sets the tooltip text that's displayed if the user lets the mouse rest over the button.
Main Steps in GUI Programming
To make any graphic program work we must be able to create
windows and add content to them.

To make this happen we must:

1. Import the awt or swing packages.


2. Set up a top-level container.
3. Fill the container with GUI components.
4. Install listeners for GUI Components. // will be discussed
later on
5. Display the container.
Example: A Simple Framed Window
Step 1 and 2
import java.awt.*;
import javax.swing.*;
public class SwingTest {
public static void main(String[] args) {
JFrame frame = new JFrame(“Hello World Swing
Example");
frame.setSize(new Dimension(300,200));
frame.setLocation(100,100);
frame.setVisible(true);
}
}
Notes on the Example
• setSize and setLocation require java.awt.*; the rest require
javax.swing.*
• The JFrame constructor argument is used as a title
• The Dimension constructor takes an integer width and height, respectively
• The setLocation method takes a pair of integer coordinates (x,y) where
(0,0) is the upper left corner of the display
• The visibility of a JFrame is set to false by default
Example: Hello World with Label

Step 3
import javax.swing.*;
public class HelloWorldSwing {
public static void main(String[] args) {
JFrame frame = new JFrame("HelloWorldSwing");
final JLabel label = new JLabel("Hello World");
frame.getContentPane().add(label);
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
Containment Hierarchy
 In the Hello World example, there was a content
pane.
 Every top-level container indirectly contains an
intermediate container known as a content pane.
 As a rule, the content pane contains, directly or
indirectly, all of the visible components in the
window's GUI.
 To add a component to a container, you use one of
the various forms of the add method. JFrame
 Containment Hierarchy of the Hello World Example

content pane

JLabel
Example: Adding a button
import javax.swing.*;
public class FirstGUI
{
public static void main(String[] args)
{
JFrame f = new JFrame( );
JButton button = new JButton("Press me!"); // create a button
f.getContentPane().add(button); // add the button to the frame
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack( );
f.setVisible(true);
}
}
Organizing the code in a better way
 As we start adding more components, the main
method will become too large and messy.
 A better way:
 Create a class that extends JFrame
 Put all components into the class (as data members)
 Do the rest in the constructor
import javax.swing.*;
public class SimpleFrame extends JFrame {
private JButton button = new JButton("Press me!");
public SimpleFrame( ) {
getContentPane( ).add(button);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
}
Adding Color
The java.awt.Color class has the following static
fields (data members):

❑ Color.black ❑ Color.magenta
❑ Color.blue ❑ Color.orange
❑ Color.cyan ❑ Color.pink
❑ Color.darkGray ❑ Color.red
❑ Color.gray ❑ Color.white
❑ Color.green ❑ Color.yellow
❑ Color.lightGra
y
Changing Background Color

import java.awt.*;
import javax.swing.*;

public class SwingTest {

public static void main(String[] args) {


JFrame frame = new JFrame("Test Frame");
frame.setSize(new Dimension(300,200));
frame.setLocation(100,100);
Container contentPane = frame.getContentPane();
contentPane.setBackground(Color.red);
frame.setVisible(true);
}

}
Font
◼Font f = new Font("Times New Roman",Font.BOLD,18);
◼ //set the font by passing the font object
◼ button2.setFont(f);
◼ Font font2 = new Font("Serif", Font.BOLD+ Font.ITALIC, 12);
GUI example with font and color
import java.awt.*; // Where is the other button?
import javax.swing.*;
public class GuiExample1 {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(300, 100));
frame.setTitle("A frame");
JButton button1 = new JButton();
button1.setText("I'm a button.");
button1.setBackground(Color.BLUE);
frame.add(button1);
JButton button2 = new JButton();
button2.setText("Click me!");
button2.setBackground(Color.RED);
Font f = new Font("Times New Roman",Font.BOLD,18);
//set the font by passing the font object
button2.setFont(f);
frame.add(button2);
frame.setVisible(true);
} }
Notes on the Code

◼ Since the frame is a top-level Swing window,


components must be added to its content pane
◼ When components are added to a container, how
they are placed is dependent upon the container's
layout manager
◼ The default layout manager for a JFrame is a
BorderLayout manager (described later)
◼ When adding to a container whose layout manager is
BorderLayout, the second parameter should be a
location defined in the BorderLayout class
Sizing and positioning
How does the programmer specify where each component appears, how big
each component should be, and what the component should do if the
window is resized / moved / maximized / etc.?

◼ Absolute positioning (C++, C#, others):


Programmer specifies exact pixel coordinates of every component.
❑ "Put this button at (x=15, y=75) and make it 70x31 px in size."

◼ Layout managers (Java):


Objects that decide where to position each component based on some
general rules or criteria.
❑ "Put these four buttons into a 2x2 grid and put these text boxes in a horizontal
flow in the south part of the frame."
Layout Management

◼ A layout manager determines the location and


size of components placed into a container
◼ Different layout managers use different
algorithms for determining size and location:
❑ BorderLayout: places at compass locations and
center
❑ FlowLayout: places components in rows, left to right
❑ GridLayout: places in rectangular grid
❑ BoxLayout: places in a single row or column
Containers and layout
◼ Place components in a container; add the
container to a frame.
❑ container: An object that stores components and
governs their positions, sizes, and resizing behavior.
Preferred sizes
◼ Swing component objects each have a certain size they would
"like" to be: Just large enough to fit their contents (text, icons,
etc.).
❑ This is called the preferred size of the component.

❑ Some types of layout managers (e.g. FlowLayout) choose to size the


components inside them to the preferred size.
❑ Others (e.g. BorderLayout, GridLayout) disregard the preferred size
and use some other scheme to size the components.

Buttons at preferred size: Not preferred size:


FlowLayout
public FlowLayout()
◼ treats container as a left-to-right, top-to-bottom "paragraph".
❑ Components are given preferred size, horizontally and vertically.
❑ Components are positioned in the order added.
❑ If too long, components wrap around to the next line.
❑ The components are centered in each row by default.
❑ The programmer can specify the size of both the vertical and horizontal
gaps between the components.
❑ FlowLayout is the default layout for JPanels.

myFrame.setLayout(new FlowLayout());
myFrame.add(new JButton("Button 1"));
FlowLayout Example
public class FlowLayoutTest extends JFrame {
JButton b1=new JButton("Red"),
b2=new JButton("Green"),b3=new
JButton("Blue"),
b4=new
JButton("Yellow"),b5=newJButton("Pink");
public FlowLayoutTest() {
setTitle("FlowLayout Test");
Container pane = getContentPane();
pane.setLayout(new FlowLayout());
setBounds(0,0,400,100);
pane.add(b1); pane.add(b2); pane.add(b3);
pane.add(b4); pane.add(b5);
}
public static void main(String args[]) {
JFrame f = new FlowLayoutTest();
f.setVisible(true);
}
}
BorderLayout
public BorderLayout()
◼ Divides container into five regions:
❑ NORTH and SOUTH regions expand to fill region horizontally,
and use the component's preferred size vertically.
❑ WEST and EAST regions expand to fill region vertically,
and use the component's preferred size horizontally.
❑ CENTER uses all space not occupied by others.
◼ The programmer specifies the area in which a component
should appear.
myFrame.setLayout(new BorderLayout());
myFrame.add(new JButton("Button 1"), BorderLayout.NORTH);
❑ This is the default layout for a JFrame.
❑ The relative dimensions of the areas are governed by the size of the
components added to them.
Border-Layout
Example

public class BorderLayoutTest extends JFrame {


JButton b1=new JButton("Red"),
b2=new JButton("Green"),b3=new JButton("Blue"),
b4=new JButton("Yellow"),b5=new JButton("Pink");
public BorderLayoutTest() {
setTitle("BorderLayout Test");
Container pane = getContentPane();
pane.setLayout(new BorderLayout());note extra paramet
setBounds(0,0,400,150);
pane.add(b1,"North"); pane.add(b2,"South");
pane.add(b3,"East");
pane.add(b4,"West"); pane.add(b5,"Center");
}
public static void main(String args[]) {
JFrame f = new BorderLayoutTest();
f.setVisible(true);
}
}
GridLayout
 Components are placed in a grid with a user-specified
number of columns and rows.
 Each component occupies exactly one grid cell.
 Grid cells are filled left to right and top to bottom.
 All cells in the grid are the same size.
 Specifying zero for either rows or columns means any
number of items can be placed in that row or column.
GridLayout Example
public class GridLayoutTest extends JFrame {
JButton b1=new JButton("Red"),
b2=new JButton("Green"),b3=new JButton("Blue"),
b4=new JButton("Yellow"),b5=new JButton("Pink");
public GridLayoutTest() {
setTitle("GridLayout Test");
Container pane = getContentPane();
pane.setLayout(new GridLayout(2,3));
setBounds(0,0,300,100);
pane.add(b1); pane.add(b2); pane.add(b3);
pane.add(b4); pane.add(b5);
}
public static void main(String args[]) {
JFrame f = new GridLayoutTest();
f.setVisible(true);
}
}
Default Layout Managers

◼ The default layout manager for content panes


is BorderLayout. Recall that the following
Swing components have content panes:
❑ JWindow
❑ JFrame
❑ JDialog
❑ JApplet
❑ JInternalFrame
◼ The other Swing container is the JPanel,
whose default layout manager is
FlowLayout.
Example No1
import java.awt.*; import javax.swing.*; // Setting and getting text from Label
public class LabelFrame extends JFrame{ label2.setText("this is the way");
//Declare Button class variable String s1 = label2.getText();
JButton button; System.out.println(s1);
JLabel label1; //Label Alignment
JLabel label2; label2.setAlignmentX(JLabel.CENTER);
JLabel label3; label2.setAlignmentY(JLabel.LEFT);
//constructor of the class //Extract out the Alignment .output will
LabelFrame(String s) { bean integer value 0 forleft ,1 for center and 2
//call to the Frame constructor, to set the name for right alignment
of the window float al=label2.getAlignmentX();
super(s); System.out.println ("Alignment of label 2=
//set the back ground color of the Frame "+al);
//black,blue,red,cyan,darkGray,gray check the //Add the button on to the frame container
color class from API to make it a component
this.getContentPane().setBackground(Color.pink add(button);
); //add label onto the frame
//set the size of the window, change it and run add(label1);
again add(label2);
setSize(400,400); add(label3);
//set the location of the Frame on the screen //Set the layout of the component place on
setLocation(400,50); container
//Create Button setLayout(new FlowLayout());
button=new JButton("Click me"); //set Title of frame
//Create Label this.setTitle("My labeFrame");
label1=new JLabel("hello"); setVisible(true);}}
label2=new JLabel("hello2",JLabel.CENTER);
label3=new JLabel("hello3",JLabel.RIGHT);
Example temperature convertor
import javax.swing.*;
import java.awt.*;

class ConvertTemp extends JFrame {


JLabel directions;
JTextField fahrenheit;;
JLabel celsius;
ConvertTemp(String s){
super(s);
setSize(230,200);
setLayout(new FlowLayout());
directions=new JLabel("Enter the Temperature in Fahrenheit:");
add(directions);
fahrenheit=new JTextField(10);
add(fahrenheit);
celsius=new JLabel(" ");
celsius.setFont(new Font("TimesRoman 12 point bold",20,20));
add(celsius);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true); }
class ExampleConvertTemp{
public static void main (String[] args) {
ConvertTemp obj1 = new ConvertTemp("Tempoerature Convertion");}
}
Home exercise

◼ Create the board for Tic Tac Toe using


Jbuttons and Gird Layout

You might also like