OOP II Chapter Two JUI-Swing Part I
OOP II Chapter Two JUI-Swing Part I
OOP II Chapter Two JUI-Swing Part I
Chapter Two
Part I
1
Objective
Introducing the different techniques necessary to
build graphical user interfaces (GUIs) for your
applications.
Learning Swing basic concepts:
components
Containers
colors
layout.
2
Introduction
So far, our user interfaces have only been textual,
meaning the user sees text and writes text at the
command prompt.
But it is also possible to make our interfaces graphical,
so we can use our programs through windows, click on
buttons, etc, using Java GUIs.
A graphical user interface presents a user-friendly
mechanisms for interacting with an application.
There are actually two sets of GUI components in Java:
AWT(Abstract Window Toolkit)
3 Swing
Swing Vs AWT
AWT is Java’s original set of classes for building GUIs
which:
The AWT components are 'heavyweight', rely on local platform's
windowing system for look and feel.
Not truly portable: looks different and lays out inconsistently on
different Oss Due to OS’s underlying display management
system
Swing is designed to solve AWT’s problems
Most Swing components are 'lightweight', in the sense that they
are coded in Java and do not correspond to OS things.
Swing components allow programmer to specify look and feel
Can change depending on platform
4
Can be same across all platforms
nts
neo
mp
Co
ing
Sw
When building a GUI you must create your components, create the
containers that will hold the components and then add the
components to the containers.
Top level containers Jframe, Jdialog, Jwindow do not inherit from
6
Jcomponent.
Swing Components
1. JFrame is Swing’s version of Frame and is descended directly
from that class. The components added to the frame are referred
to as its contents; these are managed by the contentPane.
2. JPanel is Swing’s version of the AWT class Panel and uses the
same default layout, FlowLayout.
JPanel is descended directly from Jcomponent.
public Main() {
super("Wel-Come to Java GUI");
setSize(300, 100);
getContentPane().add(myLabel);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main (String args[]) {
Main m = new Main();
}
}
Output
9
JFrame
JFrame is the application window that encompasses your GUI
objects with border, title and buttons.
It is special; it draws the window and interacts with the operating
system
When a JFrame is created, an inner container called the
contentPane is automatically created.
We don't draw graphics directly on JFrame; we draw on the
contentPane
Creating a JFrame Window
1. Construct an object of the JFrame class.
2. Set the size of the Jframe.
3. Set the title of the Jframe to appear in the title bar (title bar will be
blank if no title is set).
4. Set the default close operation. When the user clicks the close
button, the program stops running.
10
5. Make the Jframe visible.
title bar
minimize
maximize
close
contentPane
(A) Anatomy of a
JFrame
(B)Frames, Panes and
Panels
11
Layout Manager
Layout management is the process of determining the size
and location of a container's components.
Java containers do not handle their own layout. They
delegate that task to their layout manager, an instance of
another class.
If you do not like a container's default layout manager,
you can change it.
Container content = getContentPane();
content.setLayout( new FlowLayout() );
14
}
BorderLayout Zones
A border layout divides the container into five regions (top,
bottom ,left,right and center); each region may contain only one
component North
South
16
}}
GridLayout
is a layout manager that lays out a container’s components in a
rectangular grid.
The container is divided into equal-sized rectangles, and one
component is placed in each rectangle.
Items are added (by default) into top-down left-right order.
GridLayout(int rows, int cols, int hgap, int vgap); is also a
GridLayout constructo which creates a grid layout with the
specified number of rows and columns.
The third and fourth arguments are gaps between cells.
By default they are zero.
18
Another Example:
public static void main(String[] args)
{
JFrame frame = new JFrame("Rectangle Calculator");
frame.setSize(400, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.add(lengthL);
frame.add(widthL);
frame.add(areaL);
frame.add(perimeterL);
} //end main()
JLabels
Labels
Provide text instructions or information on a GUI.
Displays a single linw read-only text, an image or both text and
image.
Programs rarely change a label's contents
Constructors:
1. JLabel() : Creates a JLabel instance with no image and with an
empty string for the title.
2. JLabel(Icon image) :Creates a JLabel instance with the specified
image.
3. JLabel(String text) : Creates a JLabel instance with the
specified text.
Methods
21 myLabel.setToolTipText( "Text" )
JTextField
JTextField allows editing/displaying of a single line of text
with new editing features.
When the user types data into them and presses the Enter key,
an ActionPerformed event is produced.
JTextField is an input area where the user can type in
characters.
If you want to let the user enter multiple lines of text, you can
use JTextArea, which enables the user to enter multiple lines
of text.
JTextField Constructor
i. JTextField() Constructs a new TextField.
22 ii. JTextField(String text) Constructs a new TextField
So we might add the following:
frame.add(lengthL);
frame.add(lengthTF);
frame.add(widthL);
frame.add(widthTF);
frame.add(areaL);
frame.add(areaTF);
frame.add(perimeterL);
frame.add(perimeterTF);
Note the order in which the compnents have been added to the layout
JButton
The Java class that allows you to define a button
frame.add(lengthL);
frame.add(lengthTF);
frame.add(widthL);
frame.add(widthTF);
frame.add(areaL);
frame.add(areaTF);
frame.add(perimeterL);
frame.add(perimeterTF);
frame.add(calculateB);
frame.add(exitB);
Recap
• What we’ve done:
– We created a Window/Frame (by instantiating the JFrame
class)
– We set up a layout manager (in this case, a GridLayout)
for our frame by invoking the setLayout() from the
Container class
– We created several components for our GUI such as
labels, text fields, buttons
– We added the various components to our container
• The summary of our code is on the note part of this slide. Feel free to
copy it into your compiler so that you can actually see it! Then compile
and execute the program.
So we have a pretty picture….
Big Deal – it’s not like it does anything!
31
//Swing sample Program
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JUIExample1 extends JFrame {
private JTextArea text;
public JUIExample1 () {
super("Wel-Come to Java GUI");
setSize(300, 100);
getContentPane().setLayout(new BorderLayout());
text= new JTextArea (30,40);
getContentPane().add(text, BorderLayout.CENTER);
JButton button= new JButton ("Change to Capital");
getContentPane().add(button,BorderLayout.SOUTH);
32
class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
text.setText(text.getText().toUpperCase());
}
}
ButtonListener listener = new ButtonListener();
button.addActionListener(listener);
setVisible(true);
}
public static void main (String args[]) {
JUIExample1 m = new JUIExample1 ();
}
}
33
JComboBox
JComboBox is like a drop down box, you can click a drop-
down arrow and select an option from a list.
It generates ItemEvent. For example, when the component
has focus, pressing a key that corresponds to the first character
in some entry’s name selects that entry.
A vertical scrollbar is used for longer lists.
JComboBox Constructor
JComboBox() Creates a JComboBox with a default data model.
JComboBox(Object[] items) Creates a JComboBox that
contains the elements in the specified array.
JComboBox(Vector items) Creates a JComboBox that contains
the elements in the specified Vector.
34
RadioButton group border
..
JPanel groupPanel = new JPanel();
groupPanel.setBounds(10,10,100,60);
groupPanel.setBorder(BorderFactory.createLineBorder(Color.
black));
frame.getContentPane().add(groupPanel);
groupPanel.add(new JRadioButton("Black"));
groupPanel.add(new JRadioButton(“White"));
..
ListBox
48
Exercise 2: JPanels with color
Set the background of the contentPane to white using
<nameofobject>.setBackground(<color>);
Create two JPanels in the constructor of Calc
Set the background color of one to orange; set the
background color of the other to yellow
Add the two JPanels to the contentPane using
<nameofobject>.add(<objecttobeadded>)
add the orange JPanel first; NOTE: the order in which
you add your objects determine the way your program
looks
49
Exercise 2: Answer
package swinglab;
import java.awt.*;
import javax.swing.*;
51
Summary
When creating GUI, a JFrame is used; it interacts with
the native system
A contentPane is automatically created when a JFrame is
created. It has 5 zones where you can add a component
(default layout is BorderLayout)
JPanel is the workhorse of most complicated
interfaces. It is
a good all purpose container
the standard drawing surface
53
Common Control
JButton
It is very important, attach event to do
something that you want.
JButton btn=new JButton("Watch");
btn.setIcon(new ImageIcon("mywatch.png"));
btn.setMnemonic('W'); Alt+W to call btn command
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//do something here coding here
}
});
Add event for this button:
54
3. Common Control
JLabel
Display Text, not editable
JLabel lbl=new JLabel("Đồng hồ nè:");
lbl.setForeground(Color.RED);
55
3. Common Control
JTextField Display data, Input data
getContentPane().setLayout(new FlowLayout());
JLabel lblTen=new JLabel("Nhập tên:");
JTextField txtTen=new JTextField(15);
add(lblTen);add(txtTen);
56
3. Common Control
JTextField
To set Text in code behind for JTextField:
txtTen.setText("Hello Tèo");
To get Text from JTextField:
String s=txtTen.getText();
We could convert data:
int n=Integer.parseInt(s);
double d=Double.parseDouble(s);
float f=Float.parseFloat(s);
To set focus:txtTen.requestFocus();
57
3. Common Control
JTextAreaInput data multi line
JLabel lblDes=new JLabel("Mô tả:");
JTextArea are=new JTextArea(5, 15);
JScrollPane sc=new JScrollPane(are);
add(lblDes);add(sc);
if(rad1.isSelected())
{
}
59
ButtonGroup & JRadioButton
JPanel pnGroup=new JPanel();
pnGroup.setLayout(new BoxLayout(pnGroup, BoxLayout.Y_AXIS));
Border bor=BorderFactory.createLineBorder(Color.RED);
TitledBorder titlebor=new TitledBorder(bor, "Chọn nè:");
pnGroup.setBorder(titlebor);
JRadioButton rad1=new JRadioButton("Rất hài lòng");
JRadioButton rad2=new JRadioButton("Hài lòng");
JRadioButton rad3=new JRadioButton("Tạm chấp nhận");
JRadioButton rad4=new JRadioButton("Không chấp nhận");
60
ButtonGroup & JRadioButton
Create Border with title:
Border bor=BorderFactory.createLineBorder(Color.RED);
TitledBorder titlebor=new TitledBorder
(bor, "Chọn nè:");
pnGroup.setBorder(titlebor);
63
3. Common Control
JComboBox
JComboBox cbo=new JComboBox();
cbo.addItem("Xuất sắc");
cbo.addItem("Giỏi");
cbo.addItem("Khá");
cbo.addItem("Trung bình");
add(cbo);
String arr[]={"Xuất
sắc" ,"Giỏi" ,"Khá","Trung bình"};
JComboBox cbo=new JComboBox(arr);
add(cbo);
64
3. Common Control
JComboBox
int n=cbo.getSelectedIndex();
n is position that we selected
Object o=cbo.getSelectedItem();
We could cast object to valid
another type
cbo.setSelectedIndex(-1);
To clear selection
65
3. Common Control
JComboBox How to add Array Person
to JComboBox?
class Person
{
private String Id;
private String Name;
public Person(String id,String name){
Id=id;
Name=name;
}
public String toString() {
return Name;
}
}
66
3. Common Control
JComboBox How to add Array Person
to JComboBox?
Person []list={
new Person("1", "Trần Thành Công"),
new Person("2", "Nguyễn Đại Thắng"),
new Person("3", "Hoàng Thành Đạt")};
JComboBox cbo2=new JComboBox(list);
add(cbo2);
67
3. Common Control
JList
Person []list={
new Person("1", "Đỗ Công Thành"),
new Person("2", "Nguyễn Văn Hùng"),
new Person("3", "Trần Duy Thanh"),
new Person("4", "Đoàn Ái Nương"),
…
new Person("10", "Đào Cẩm Hằng")
};
JList jl=new JList(list);
jl.setSelectionBackground(Color.RED);
jl.setSelectionForeground(Color.WHITE);
JScrollPane scjl=new JScrollPane(jl,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
add(scjl);
68
3. Common Control
JList ListSelectionModel
ListSelectionModel.SINGLE_SELECTION;
ListSelectionModel.SINGLE_INTERVAL_SELECTION;
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION;
jl.setSelectionMode(ListSelectionMo
del.MULTIPLE_INTERVAL_SELECTION)
int n=jl.getSelectedIndex();
int m[]=jl.getSelectedIndices();
Object o=jl.getSelectedValue();
Object arr[]=jl.getSelectedValues();
69