You are on page 1of 35

ASTU

CSE 2202 Object Oriented Programming


(OOP)

Java GUIs using Swing


2018

Computer Science & Engineering Program


The School of EE & Computing
Adama Science & Technology University

1
Objective ASTU

• Introducing the different techniques necessary


to build graphical user interfaces (GUIs) for
your applications.
• Learning Swing basic concepts:
– components
– Containers
– colors
– layout.
• Constructing Swing interfaces
• Using the Swing Event Model.

2
Introduction ASTU

 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)
 Swing

3
ASTU
AWT Vs. Swing

4
ASTU

 Component defines methods used in its subclasses


 (for example, paint and repaint)
 Container - collection of related components
 When using JFrame, add components to content pane
(a Container)
 JComponent - superclass to most Swing components 5
Contd. ASTU

• 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 Jcomponent.
6
Swing Components ASTU

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.

3. FlowLayout when used arranges swing components from left


to right until there’s no more space available. Then it begins a
new row below it and moves from left to right again.
4. 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.

7
ASTU
Contd.
5. JLabel descended from JComponent, is used to create text
labels.
6. JButton The abstract class AbstractButton extends class
JComponent and provides a foundation for a family of button
classes, including Jbutton.
7. JTextField allows editing of a single line of text with new text
editing features.
8. JTextArea allows editing of multiple lines of text.
9. JButton is a component the user clicks to trigger a specific
action.
10. JCheckBox is not a member of a checkbox group. A
checkbox can be selected and deselected, and it also displays
its current state.
11. JMenubar can contain several JMenu’s. Each of the JMenu’s
can contain a series of JMenuItem ’s that you can select. 8
Swing sample Program ASTU

//Swing sample Program


import java.awt.*;
import javax.swing.*;
public class Main extends JFrame {
JLabel myLabel = new JLabel("Hello, World!");

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 ASTU

 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.
5. Make the Jframe visible.

10
ASTU

title bar
minimize
maximize
close

contentPane

(A) Anatomy of a JFra


me
(B)Frames, Panes and
Panels
11
Layout Manager ASTU

 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() );

 Swing provides 6 Layout manager classes:


FlowLayout, GridLayout,
BorderLayout,GridBagLayout,BoxLayout and
CardLayout
12
FlowLayout ASTU

 FlowLayout, the simplest of the managers, simply


adds components left to right until it can fit no
more within its container's width.
 It then starts a second line of components, fills that,
starts a third, etc.
 Each component gets as much space as it needs
and no more.
 FlowLayout is the default layout manager for Jpanel
Syntax
<nameofcontainer>.setLayout(new FlowLayout());
Example: panel.setLayout(new FlowLayout());
panel.add(button);

13
FlowLayout Example ASTU

import java.awt.*;
import javax.swing.*; Output
public class Main extends JFrame{
public static void main (String args[])
{
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("FlowLayout");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new FlowLayout());
JButton b1 = new JButton("Hello");
frame.getContentPane().add(b1);
JButton b2 = new JButton("Two");
frame.getContentPane().add(b2);
JTextField t1 = new JTextField("Text here");
frame.getContentPane().add(t1);
frame.pack();
frame.setVisible(true);
}
}

14
BorderLayout Zones ASTU

 A border layout divides the container into five regions (top,


bottom ,left,right and center); each region may contain only
one component
 Components are added to one of these parts, only one
component per part.
 BorderLayout is the default LayoutManager for the
contentpane of a Jframe
Syntax
<nameofcontainer>.setLayout(new BorderLayout());
<nameofcontainer>.add(<nameofcomponent>,BorderLayout.RE
GION);
where REGION is either NORTH, SOUTH, WEST, CENTER OR EAST
North

West Center East

South 15
BorderLayout Example ASTU

//BorderLayout
import java.awt.*;
import javax.swing.*;
public class DemoBorderLayout extends JFrame{ Output
public static void main (String args[]){
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Border");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton b1 = new JButton("At the top");
frame.getContentPane().add(b1,BorderLayout.NORTH );
JButton b2 = new JButton("Bottom");
frame.getContentPane().add(b2,BorderLayout.SOUTH);
JTextField t1 = new JTextField("Left");
frame.getContentPane().add(t1,BorderLayout.WEST);
JTextField t2 = new JTextField("Right");
frame.getContentPane().add(t2,BorderLayout.EAST);
JButton b3 = new JButton("Centre");
frame.getContentPane().add(b3,BorderLayout.CENTER );
frame.setSize(200, 120);
frame.setVisible(true);
}}

16
GridLayout ASTU

 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.
The first and second are rows and columns.
Syntax
<nameofcontainer>.setLayout(new GridLayout(int rows, int cols,
int hgap, int vgap));
Example: panel.setLayout(new GridLayout(2.3));
17
GridLayout Example ASTU

//GridLayout
import java.awt.*;
import javax.swing.*; Output
public class Main extends JFrame{
public static void main (String args[])
{
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("GridLayout");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new GridLayout(4,3,5,5));
for (int i=0; i<10; i++)
frame.getContentPane().add(new JButton(""+i));
frame.pack();
frame.setVisible(true);
}
}
18
JLabels ASTU
 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
– myLabel.setToolTipText( "Text" )
• Displays "Text" in a tool tip when mouse over label
– myLabel.setText( "Text" )
– myLabel.getText()

19
JTextField ASTU

 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.
ii. JTextField(String text) Constructs a new TextField
initialized with the specified text.
20
JButton ASTU

 The Java class that allows you to define a button


 Multiple constructors allow you to initialize a button
with a predefined label and/or a predefined icon
 Although the button’s “action” can be defined in the
constructor, defining a button’s action can take many
lines of code and should be done separately.
JButton Constructor
– JButton() : Creates a button with no set text or icon.
– JButton(Action a) : Creates a button where properties
are taken from the Action supplied.
– JButton(String text) : Creates a button with text.
21
Java JPanel Example ASTU

import java.awt.*;
import javax.swing.*;
class PanelExample {
PanelExample()
{
JFrame f= new JFrame("Panel Example");
JPanel panel=new JPanel();
panel.setBounds(40,80,200,200); //x,y,w,h
panel.setBackground(Color.gray);
JButton b1=new JButton("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
JButton b2=new JButton("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PanelExample();
}
}

22
JComboBox ASTU

 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.

23
ComboBoxExample ASTU

import javax.swing.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args) {
new ComboBoxExample();
}
}

24
ASTU
RadioButtonExample
import javax.swing.*;
public class RadioButtonExample {
JFrame f;
RadioButtonExample(){
f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);bg.add(r2);
f.add(r1);f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new RadioButtonExample();
}
}
25
ListExample ASTU

import javax.swing.*;
public class ListExample
{
ListExample(){
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("Item1");
l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4");
JList<String> list = new JList<>(l1);
list.setBounds(100,100, 75,75);
f.add(list);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample();
}}
26
CheckBoxExample ASTU

import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50); //x,y,width &height
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}}

27
JRadioButton ASTU

• Radio buttons
– Have two states: selected and deselected
– Normally appear as a group
• Only one radio button in group selected at time
• Selecting one button forces the other buttons off
– Mutually exclusive options
– ButtonGroup - maintains logical relationship
between radio buttons
• Class JRadioButton
– Constructor
• JRadioButton( "Label", selected )
• If selected true, JRadioButton initially selected

28
RadioButtonExample ASTU

import javax.swing.*;
public class RadioButtonExample {
JFrame f;
RadioButtonExample(){
f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
r1.setBounds(75,50,100,30); //x,y,width &height
r2.setBounds(75,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);bg.add(r2);
f.add(r1);f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new RadioButtonExample();
}

29
}
TableExample ASTU

import javax.swing.*;
public class TableExample {
JFrame f;
TableExample(){
f=new JFrame();
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args) {
new TableExample();
}
}
30
MenuExample ASTU

import javax.swing.*;
class MenuExample
{ JMenu menu, submenu;
JMenuItem i1, i2, i3, i4, i5;
MenuExample(){
JFrame f= new JFrame("Menu and MenuItem Example");
JMenuBar mb=new JMenuBar();
menu=new JMenu("Menu");
submenu=new JMenu("Sub Menu");
i1=new JMenuItem("Item 1");
i2=new JMenuItem("Item 2");
i3=new JMenuItem("Item 3");
i4=new JMenuItem("Item 4");
i5=new JMenuItem("Item 5");
menu.add(i1); menu.add(i2); menu.add(i3);
submenu.add(i4); submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setJMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true); }
public static void main(String args[])
{ new MenuExample();
}}

31
Colors ASTU

• There are 13 predefined colors


• You can access them using Color.x
where x is
– orange, pink, cyan, magenta, yellow, black,
blue, white, gray, lightGray, darkGray, red, green
• You can define your own colors
Color ugly = new Color(30,90,120);
//RGB(red-green-blue); values between 0-255;

32
Exercise 2: JPanels with color ASTU

• 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 33
ASTU
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

• Swing containers have default layout managers


but you can always change them
• Swing is HUGE! You must explore it further.
34
ASTU

Thank you !!

35

You might also like