Lecture 9 GUI Basic JLabel, Jbutton, JFrame
Lecture 9 GUI Basic JLabel, Jbutton, JFrame
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
◼ 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.
Native
Java Java Window
Program AWT System
Peers
Pros
Speed: native components speed performance.
❑ 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
◼ 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
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.*;
}
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
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