0% found this document useful (0 votes)
43 views40 pages

Chapter 1 Swing

The document discusses Swing components and layout managers in Java for building graphical user interfaces. It introduces common Swing components like JFrame, JPanel, JButton and different layout managers including FlowLayout, BorderLayout and GridLayout and how to use them to design GUI applications.

Uploaded by

mehari kiros
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views40 pages

Chapter 1 Swing

The document discusses Swing components and layout managers in Java for building graphical user interfaces. It introduces common Swing components like JFrame, JPanel, JButton and different layout managers including FlowLayout, BorderLayout and GridLayout and how to use them to design GUI applications.

Uploaded by

mehari kiros
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 40

Chapter One

Java GUIs using 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.

 Constructing Swing interfaces


 Using the Swing Event Model.

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

 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)
5
 JComponent - superclass to most Swing components
Contd.

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

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

 Swing provides 6 Layout manager classes: FlowLayout,


GridLayout, BorderLayout,GridBagLayout,BoxLayout and
12 CardLayout
FlowLayout
 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
import java.awt.*;
import javax.swing.*;
public class Main extends JFrame{
public static void main (String args[])
{ Output
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
 A border layout divides the container into five regions (top,
bottom ,left,right and center); each region may contain only one
component
North

West Center East

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.

The first and second are rows and columns.


Syntax
<nameofcontainer>.setLayout(new GridLayout(int rows, int cols, int hgap,
int vgap));
17 Example: panel.setLayout(new GridLayout(2.3));
//GridLayout
import java.awt.*;
import javax.swing.*;
public class Main extends JFrame{
public static void main (String args[]) Output
{
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
 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

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


21 JButton(String text) : Creates a button with text.
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.
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

See source code


Data held in array
List box shows array
List box inside scroll pane
myList.getModel().getElementAt(..
Two JListBoxes

See source code


We want to add items to list
So use a Vector not an array to hold data
Check methods to delete items and copy to other listbox
JCheckBox
 When JCheckBox changes
ItemEvent generated
 Handled by an ItemListener, which must define
itemStateChanged
Register handlers with with addItemListener

private class CheckBoxHandler implements ItemListener {


public void itemStateChanged( ItemEvent e )
 Class ItemEvent
getStateChange
 Returns ItemEvent.SELECTED or
ItemEvent.DESELECTED
1 // Fig. 12.12: CheckBoxTest.java

2 // Creating Checkbox buttons.

3 import java.awt.*;

4 import java.awt.event.*;

5 import javax.swing.*;

7 public class CheckBoxTest extends JFrame {

8 private JTextField t;

9 private JCheckBox bold, italic;

10

11 public CheckBoxTest()

12 {

13 super( "JCheckBox Test" );

14

15 Container c = getContentPane();

16 c.setLayout(new FlowLayout());

17

18 1. import
t = new JTextField( "Watch the font style change", 20 );

19 t.setFont( new Font( "TimesRoman", Font.PLAIN, 14 ) );

20 c.add( t );

21

22

23
// create checkbox objects

bold = new JCheckBox( "Bold" );


1.1 Declarations
Create JCheckBoxes
24 c.add( bold );

25

26 italic = new JCheckBox( "Italic" );

27 c.add( italic ); 1.2 Initialize JCheckBoxes


28

29 CheckBoxHandler handler = new CheckBoxHandler();

30 bold.addItemListener( handler );
31 italic.addItemListener( handler );

32

33 addWindowListener(

34 new WindowAdapter() {

35 public void windowClosing( WindowEvent e )

36 {

37 System.exit( 0 );

38 }

39 }

40 );

41

42 setSize( 275, 100 );

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

51 private class CheckBoxHandler implements ItemListenergetStateChange


{ returns
52 private int valBold = Font.PLAIN;

53 private int valItalic = Font.PLAIN; ItemEvent.SELECTED or


54 ItemEvent.DESELECTED
55 public void itemStateChanged( ItemEvent e )

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

2 // Creating radio buttons using ButtonGroup and JRadioButton.

3 import java.awt.*;

4 import java.awt.event.*;

5 import javax.swing.*;

7 public class RadioButtonTest extends JFrame {

8 private JTextField t;

9 private Font plainFont, boldFont,

10 italicFont, boldItalicFont;

11 private JRadioButton plain, bold, italic, boldItalic;

12 private ButtonGroup radioGroup;

13

14 public RadioButtonTest()

15 {

16 super( "RadioButton Test" );

17

18 Container c = getContentPane(); 1. import


19 c.setLayout( new FlowLayout() );

20 Initialize radio buttons. Only


21 t = new JTextField( "Watch the font style change", 25 );
one is initially selected.
22

23
c.add( t );
1.1 Declarations
24 // Create radio buttons

25 plain = new JRadioButton( "Plain", true );

26 c.add( plain );

27 bold = new JRadioButton( "Bold", false); 1.2 Initialization


28 c.add( bold );

29 italic = new JRadioButton( "Italic", false );

30 c.add( italic );
31 boldItalic = new JRadioButton( "Bold/Italic", false );

32 c.add( boldItalic );

33

34 // register events

35 RadioButtonHandler handler = new RadioButtonHandler();

36 plain.addItemListener( handler ); Create a ButtonGroup. Only


37 bold.addItemListener( handler );
one radio button in the group may
38 italic.addItemListener( handler );
be selected at a time.
39 boldItalic.addItemListener( handler );

40

41 // create logical relationship between JRadioButtons

42 radioGroup = new ButtonGroup();


43 radioGroup.add( plain );
Method add adds radio
44 radioGroup.add( bold ); buttons to the ButtonGroup
45 radioGroup.add( italic );

46 radioGroup.add( boldItalic );

47

48 plainFont = new Font( "TimesRoman", Font.PLAIN, 14 );

49 boldFont = new Font( "TimesRoman", Font.BOLD, 14 );

50 italicFont = new Font( "TimesRoman", Font.ITALIC, 14 );

51 boldItalicFont =

52 new Font( "TimesRoman", Font.BOLD + Font.ITALIC, 14 );

53 t.setFont( plainFont );
54

55 setSize( 300, 100 );

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

31 colorList = new JList( colorNames );


32 colorList.setVisibleRowCount( 5 );

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

38 // add a JScrollPane containing the JList


Make the JList a single-
39 // to the content pane
selection list.
40 c.add( new JScrollPane( colorList ) );
41

42 // set up event handler


Create a new JScrollPane
43 colorList.addListSelectionListener(
object, initialize it with a JList,
44 new ListSelectionListener() {

45 public void valueChanged( ListSelectionEvent e )


and attach it to the content pane.
46 {

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

57 public static void main( String args[] )

58 {

59 ListTest app = new ListTest();


1 // Fig. 12.20: MouseDetails.java
2 // Demonstrating mouse clicks and
3 // distinguishing between mouse buttons.
4 import javax.swing.*;
Another example, illustrating
5 import java.awt.*;
mouse events in AWT and Swing
6 import java.awt.event.*;
7
8 public class MouseDetails extends JFrame {
9 private String s = "";
10 private int xPos, yPos;
11
Add a listener for a
12 public MouseDetails()
mouse click.
13 {
14 super( "Mouse clicks and buttons" );
15
16 addMouseListener( new MouseClickHandler() );
17
18 setSize( 350, 150 );
19 show();
20 }
21
22 public void paint( Graphics g )
23 {
24 g.drawString( "Clicked @ [" + xPos + ", " + yPos + "]",
25 xPos, yPos );
26 }
27
Colors
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;

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.*;

public class Calc extends JFrame{


private JPanel entryPanel;
private JPanel answerPanel;
public Calc() {
Container cp = getContentPane();
setDefaultCloseOperation(EXIT_ON_CLOSE);
cp.setBackground(Color.white);
setTitle("My Funky Calculator");
setSize(1000,700);
entryPanel = new JPanel();
entryPanel.setBackground(Color.orange);
answerPanel = new JPanel();
38 answerPanel.setBackground(Color.yellow);
// . . .
Exercise 2: answer continued
cp.add(entryPanel);
cp.add(answerPanel);
}
public static void main (String[] args){
Calc trial = new Calc();
trial.setVisible(true);
}
}

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

 Swing containers have default layout managers but you


can always change them

40  Swing is HUGE! You must explore it further.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy