Chapter 1 Swing
Chapter 1 Swing
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)
• Swing
3
Swing Vs AWT
AWT is Java’s original set of classes for building GUIs which:
• The AWT components are 'heavyweight', depend 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
Can be same across all platforms
Uses some of AWT components like Window, frame, dialog
Uses AWT event handling
4
nts
ne
po
om
C
i ng
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.
5. Make the Jframe visible.
10
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() );
South
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.REGION);
where REGION is either NORTH, SOUTH, WEST, CENTER OR EAST
15
//BorderLayout
import java.awt.*;
import javax.swing.*;
public class DemoBorderLayout extends JFrame{
public static void main (String args[]){
JFrame.setDefaultLookAndFeelDecorated(true);
Output
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
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
JLabels
Labels
Provide text instructions or information on a GUI.
Displays a single line 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
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
The Java class that allows you to define a button
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.
22
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(app.choice1);
groupPanel.add(app.choice2);
..
ListBox
3 import java.awt.*;
4 import java.awt.event.*;
5 import javax.swing.*;
8 private JTextField t;
10
11 public CheckBoxTest()
12 {
14
15 Container c = getContentPane();
16 c.setLayout(new FlowLayout());
17
18 1. import
t = new JTextField( "Watch the font style change", 20 );
20 c.add( t );
21
22
23
// create checkbox objects
25
30 bold.addItemListener( handler );
31 italic.addItemListener( handler );
32
33 addWindowListener(
34 new WindowAdapter() {
36 {
37 System.exit( 0 );
38 }
39 }
40 );
41
43 show();
44 }
45
Because CheckBoxHandler implements
46 public static void main( String args[] ) ItemListener, it must define method
47 { itemStateChanged
48 new CheckBoxTest();
49 }
50
56 {
57 if ( e.getSource() == bold )
58 if ( e.getStateChange() == ItemEvent.SELECTED )
59 valBold = Font.BOLD;
60 else
61 valBold = Font.PLAIN;
JRadioButton
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
1 // Fig. 12.12: RadioButtonTest.java
3 import java.awt.*;
4 import java.awt.event.*;
5 import javax.swing.*;
8 private JTextField t;
10 italicFont, boldItalicFont;
13
14 public RadioButtonTest()
15 {
17
23
c.add( t );
1.1 Declarations
24 // Create radio buttons
26 c.add( plain );
30 c.add( italic );
31 boldItalic = new JRadioButton( "Bold/Italic", false );
32 c.add( boldItalic );
33
34 // register events
40
46 radioGroup.add( boldItalic );
47
51 boldItalicFont =
53 t.setFont( plainFont );
54
56 show();
57 }
58
JList
List
Displays series of items
may select one or more items
Class JList
Constructor JList( arrayOfNames )
Takes array of Objects (Strings) to display in list
setVisibleRowCount( n )
Displays n items at a time
Does not provide automatic scrolling
30 // create a list with the items in the colorNames array
33
Initialize JList with array of
34 // do not allow multiple selections
Strings, and show 5 items at
35 colorList.setSelectionMode( a time.
36 ListSelectionModel.SINGLE_SELECTION );
37
47 c.setBackground(
48 colors[ colorList.getSelectedIndex() ] );
49 }
50 }
Change the color according to the item
51 );
52
selected (use getSelectedIndex).
53 setSize( 350, 150 );
54 show();
55 }
56
58 {
36
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
37
Exercise 2: Answer
package swinglab;
import java.awt.*;
import javax.swing.*;
39
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