OOP II Chapter Two JUI-Swing Part I

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 69

Java GUIs using Swing

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.

 Constructing Swing interfaces


 Using the Swing Event Model. (@Part II)

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

 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. JButton is a component the user
clicks to trigger a specific action.
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. JCheckBox is not a member of a checkbox group. A checkbox
can be selected and deselected, and it also displays its current
state.
8
10. JMenubar can contain several JMenu’s. Each of the JMenu’s
//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.
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() );

 Swing provides 6 Layout manager classes: FlowLayout,


12
GridLayout, BorderLayout,GridBagLayout,BoxLayout
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());
13 Example: panel.setLayout(new FlowLayout());
//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());
15
<nameofcontainer>.add(<nameofcomponent>,BorderLayout.REGIO
//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,
17 int hgap, int vgap));
//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
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.setLayout( new GridLayout(5, 2) );

JLabel lengthL, widthL, areaL, perimeterL;


lengthL = new JLabel("Enter the length: ",
SwingConstants.RIGHT);
widthL = new JLabel("Enter the width: ", SwingConstants.RIGHT);
areaL = new JLabel("The area is: ", SwingConstants.RIGHT);
perimeterL = new JLabel("Perimeter: ", SwingConstants.RIGHT);

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:

JTextField lengthTF, widthTF, areaTF, perimeterTF;


lengthTF = new JTextField(10);
widthTF = new JTextField(10);
areaTF = new JTextField(10);
areaTF.setEditable(false); //this TF is to display output
perimeterTF = new JTextField(10);
perimeterTF.setEditable(false); //this TF is to display output

• The ’10’ in the constructor initializes the text field to a maximum of 10


characters.
• The next step is to add these text-field components to our content pane.
JTextField lengthTF, widthTF, areaTF, perimeterTF;
lengthTF = new JTextField(10);
widthTF = new JTextField(10);
areaTF = new JTextField(10);
perimeterTF = new JTextField(10);

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

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


26 JButton(String text) : Creates a button with text.
class JButton
• Here is the code that generates the buttons, followed by the code
to add all the various components to the content pane. Note the
order in which the components are added. Recall that when
adding components to a GridLayout, the components are added
from left to right, row by row.
JButton calculateB, exitB;
calculateB = new JButton("Calculate");
exitB = new JButton("Exit");

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!

What is Now??? Events (will be


addressed on Chapter Two-Part II, lecture slide)
Handling Button’s Click event, just for highlight

 Implement an ActionListener and Assign it to


the button
class CopyListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
//Handle the event here
}
}

//Create the listener and assign it to the button


CopyListener listener = new CopyListener();
button.addActionListener(listener);

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

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.*;
6
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
1.1 Declarations
// create checkbox objects
bold = new JCheckBox( "Bold" );
Create JCheckBoxes
24 c.add( bold );
25
26
27 1.2 Initialize JCheckBoxes
italic = new JCheckBox( "Italic" );
c.add( italic );
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 }
Because CheckBoxHandler implements
45
46 public static void main( String
ItemListener, it must define method
args[] )
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.*;
6
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 styleone is initially
change", selected.
25 );
22
23
c.add( t );
1.1 Declarations
24 // Create radio buttons
25 plain = new JRadioButton( "Plain", true );
26
27
c.add( plain );
1.2 Initialization
bold = new JRadioButton( "Bold", false);
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 );
Initialize JList with array of
33
Strings, and show 5 items at
34 // do not allow multiple selections
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() { and attach it to the content pane.
45 public void valueChanged( ListSelectionEvent e )
46 {
47 c.setBackground(
48 colors[ colorList.getSelectedIndex() ] );
49 }
50 } Change the color according to the item
51 );
selected (use getSelectedIndex).
52
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;

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

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();
50
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);
}
}

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

 Swing containers have default layout managers but you


can always change them

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


End of Chapter Two Part One

Next slides (54-69) bellow are for you


(Students as an Additional reading)

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

Could add Icon for JLabel


ImageIcon icon=new ImageIcon("watch2.png");
lbl.setIcon(icon);

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

If you don’t allow input data, please call


setEditable method and take false value
txtTen.setEditable(false);

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

JTextArea are=new JTextArea(5, 15);


 5 rows, 15 columns
We should use JScrollPane to create
Scroll for JTextArea when user input
data over limit row or column
58
3. Common Control
 ButtonGroup & JRadioButton
Make single choice
Must add JRadioButton into the ButtonGroup

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");

ButtonGroup group=new ButtonGroup();


group.add(rad1);group.add(rad2);
group.add(rad3);group.add(rad4);
pnGroup.add(rad1);pnGroup.add(rad2);
pnGroup.add(rad3);pnGroup.add(rad4);
add(pnGroup);

60
 ButtonGroup & JRadioButton
Create Border with title:
Border bor=BorderFactory.createLineBorder(Color.RED);
TitledBorder titlebor=new TitledBorder
(bor, "Chọn nè:");
pnGroup.setBorder(titlebor);

Define a buttongroup to add all radio:


ButtonGroup group=new ButtonGroup();
group.add(rad1);
And add all Radio into the pnGroup:
pnGroup.add(rad1);
Add pnGroupd into the Window:
add(pnGroup);
61
3. Common Control
 JCheckBox Make multi choice
JPanel pnCheck=new JPanel();
pnCheck.setLayout(new GridLayout(2, 2));
Border bor2=BorderFactory
.createEtchedBorder(Color.BLUE, Color.RED);
TitledBorder titlebor2=
new TitledBorder(bor2, "Môn học yêu thích:");
pnCheck.setBorder(titlebor2);
JCheckBox chk1=new JCheckBox("Java");
JCheckBox chk2=new JCheckBox("F Sharp");
JCheckBox chk3=new JCheckBox("C Sharp");
JCheckBox chk4=new JCheckBox("Ruby");
pnCheck.add(chk1);pnCheck.add(chk2);
pnCheck.add(chk3);pnCheck.add(chk4);
add(pnCheck);
62
3. Common Control
 JCheckBox Make multi choice
Set grid layout 2 rows and 2 column
pnCheck.setLayout(new GridLayout(2, 2));
Create JCheckBox:
JCheckBox chk1=new JCheckBox("Java");
Add chk1 into the pnCheck:
if(chk1.isSelected())
pnCheck.add(chk1); {
Add pnCheck into the Window: //do something
}
add(pnCheck);
Create border with 2 color: Blue, Red:
BorderFactory.createEtchedBorder(Color.BLUE, Color.RED);

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

We get Person from selected:


Person p=(Person)cbo2.getSelectedItem();

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

You might also like