SlideShare a Scribd company logo
Java GUI Libraries
Swing Programming
Swing Components
• Swing is a collection of libraries that contains
primitive widgets or controls used for designing
Graphical User Interfaces (GUIs).
• Commonly used classes in javax.swing package:
– JButton, JTextBox, JTextArea, JPanel, JFrame, JMenu,
JSlider, JLabel, JIcon, …
– There are many, many such classes to do anything
imaginable with GUIs
– Here we only study the basic architecture and do simple
examples
Swing components, cont.
• Each component is a Java class with a fairly extensive
inheritency hierarchy:
Object
Component
Container
JComponent
JPanel
Window
Frame
JFrame
Using Swing Components
• Very simple, just create object from
appropriate class – examples:
– JButton button = new JButton();
– JTextField text = new JTextField();
– JTextArea text = new JTextArea();
– JLabel lab = new JLabel();
Adding components
• Once a component is created, it can be added to a
container by calling the container’s add method:
Container cp = getContentPane();
cp.add(new JButton(“cancel”));
cp.add(new JButton(“go”));
How these are laid out is determined by the layout
manager.
This is required
Laying out components
• Use layout managers – basically tells form how to
align components when they’re added.
• Each Container has a layout manager associated
with it.
• A JPanel is a Container –Set the desired layout
manager for each JPanel, then add components
directly to panels.
Layout Managers
• Java comes with 7 or 8. Most common and
easiest to use are
– FlowLayout
– BorderLayout
– GridLayout
Setting layout managers
• Very easy to associate a layout manager with a
component. Simply call the setLayout method on
the Container:
JPanel p1 = new JPanel();
p1.setLayout(new FlowLayout(FlowLayout.LEFT));
JPanel p2 = new JPanel();
p2.setLayout(new BorderLayout());
As Components are added to the container, the layout
manager determines their size and positioning.
Simplest GUI
import javax.swing.JFrame;
class SimpleGUI extends JFrame{
SimpleGUI(){
setSize(400,400); //set frames size in pixels
setDefaultCloseOperation(EXIT_ON_CLOSE);
show();
}
public static void main(String[] args){
SimpleGUI gui = new SimpleGUI();
System.out.println(“main thread coninues”);
}
}
Another Simple GUI
import javax.swing.*;
class SimpleGUI extends JFrame{
SimpleGUI(){
setSize(400,400); //set frames size in pixels
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton but1 = new JButton(“Click me”);
Container cp = getContentPane();//must do this
cp.add(but1);
show();
}
public static void main(String[] args){
SimpleGUI gui = new SimpleGUI();
System.out.println(“main thread coninues”);
}}
Add Layout Manager
import javax.swing.*; import java.awt.*;
class SimpleGUI extends JFrame{
SimpleGUI(){
setSize(400,400); //set frames size in pixels
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton but1 = new JButton(“Click me”);
Container cp = getContentPane();//must do this
cp.setLayout(new FlowLayout(FlowLayout.CENTER);
cp.add(but1);
show();
}
public static void main(String[] args){
SimpleGUI gui = new SimpleGUI();
System.out.println(“main thread coninues”);
}}
Add call to event handler
import javax.swing.*; import java.awt.*;
class SimpleGUI extends JFrame{
SimpleGUI(){
setSize(400,400); //set frames size in pixels
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton but1 = new JButton(“Click me”);
Container cp = getContentPane();//must do this
cp.setLayout(new FlowLayout(FlowLayout.CENTER);
but1.addActionListener(new MyActionListener());
cp.add(but1);
show();
}
public static void main(String[] args){
SimpleGUI gui = new SimpleGUI();
System.out.println(“main thread coninues”);
}}
Event Handler Code
class MyActionListener implements ActionListener{
public void actionPerformed(ActionEvent ae){
JOptionPane.showMessageDialog(“I got clicked”, null);
}
}
JFrame
•JFrame is the top-level container that is
commonly used for Swing applications.
–setSize(275, 100);
–setVisible(true);
–void setDefaultCloseOperation(int what);
–JFrame.EXIT_ON_CLOSE.
–JFrame.DISPOSE_ON_CLOSE
–JFrame.HIDE_ON_CLOSE
–JFrame.DO_NOTHING_ON_CLOSE
JLabel and ImageIcon
•Constructor
–JLabel(Icon icon)
–JLabel(String str)
–JLabel(String str, Icon icon, int align)
•Methods
–Icon getIcon( )
–String getText( )
–void setIcon(Icon icon)
–void setText(String str)
–ImageIcon ii = new ImageIcon("france.gif");
–// Create a label.
–JLabel jl = new JLabel("France", ii, JLabel.CENTER);
JTextField
•Constructors
–JTextField(int cols)
–JTextField(String str, int cols)
–JTextField(String str)
–jtf = new JTextField(15);
The Swing Buttons
•Swing defines four types of buttons: JButton,
JToggleButton, JCheckBox, and JRadioButton.
•All are subclasses of the AbstractButton class,
which extends JComponent. Thus, all buttons
share a set of common traits.
–void setDisabledIcon(Icon di)
–void setPressedIcon(Icon pi)
–void setSelectedIcon(Icon si)
–void setRolloverIcon(Icon ri)
–String getText( )
–void setText(String str)
JButton
•Constructors
–JButton(Icon icon)
–JButton(String str)
–JButton(String str, Icon icon)
•Methods
–String getActionCommand( )
–void setActionCommand( )
JToggleButton
•Auseful variation on the push button is called a
toggle button. A toggle button looks just like a
push button, but it acts differently because it
has two states: pushed and released.
–JToggleButton(String str)
•Methods
–Object getItem( )
–boolean isSelected( )
Check Boxes
•The JCheckBox class provides the functionality
of a check box. Its immediate superclass is
JToggleButton, which provides support for two-
state buttons
JCheckBox(String str)
Radio Buttons
•JRadioButton(String str)
•JRadioButton b1 = new JRadioButton("A");
•JRadioButton b2 = new JRadioButton(“B");
•JRadioButton b3 = new JRadioButton(“C");
•ButtonGroup bg = new ButtonGroup();
•bg.add(b1);
•bg.add(b2);
•bg.add(b3);
JTabbedPane
•The general procedure to use a tabbed pane is
outlined here:
1.Create an instance of JTabbedPane.
2.Add each tab by calling addTab( ).
3.Add the tabbed pane to the content pane.
1.JTabbedPane jtp = new JTabbedPane();
2.jtp.addTab("Cities", new CitiesPanel());
3.jtp.addTab("Colors", new ColorsPanel());
4.jtp.addTab("Flavors", new FlavorsPanel());
•class ColorsPanel extends
JPanel {
•public ColorsPanel() {
•JCheckBox cb1 = new
JCheckBox("Red");
•add(cb1);
•JCheckBox cb2 = new
JCheckBox("Green");
•add(cb2);
•JCheckBox cb3 = new
JCheckBox("Blue");
•add(cb3);
•}
•}
•class FlavorsPanel extends
JPanel {
•public FlavorsPanel() {
class CitiesPanel extends JPanel
public CitiesPanel() {
JButton b1 = new JButton("New
York");
add(b1);
JButton b2 = new
JButton("London");
add(b2);
JButton b3 = new JButton("Hong
Kong");
add(b3);
JButton b4 = new
JButton("Tokyo");
add(b4);
}
}
JScrollPane
•JScrollPane is a lightweight container that automatically
handles the scrolling of another component. The component
being scrolled can either be an individual component, such as a
table, or a group of components contained within another
lightweight container, such as a JPanel. In either case, if the
object being scrolled is larger than the viewable area, horizontal
and/or vertical scroll bars are automatically provided, and the
component can be scrolled through the pane. Because
JScrollPane automates scrolling, it usually eliminates the need to
manage individual scroll bars.
•Here are the steps to follow to use a scroll
pane:
–Create the component to be scrolled.
–Create an instance of JScrollPane, passing to it the
object to scroll.
–Add the scroll pane to the content pane
JPanel jp = new JPanel();
jp.setLayout(new GridLayout(20, 20));
int b = 0;
for(int i = 0; i < 20; i++) {
for(int j = 0; j < 20; j++) {
jp.add(new JButton("Button " + b));
++b;
}
}
// Create the scroll pane.
JScrollPane jsp = new JScrollPane(jp);
// Add the scroll pane to the content pane.
// Because the default border layout is used,
// the scroll pane will be added to the center.
add(jsp, BorderLayout.CENTER);
JList
•In Swing, the basic list class is called JList. It
supports the selection of one or more items
from a list.
•JList(Object[ ] items)
•ListSelectionModel:
–SINGLE_SELECTION
–SINGLE_INTERVAL_SELECTION
–MULTIPLE_INTERVAL_SELECTION
•int getSelectedIndex( )
•String Cities[] = { "New York", "Chicago",
"Houston“,"Denver", "Los Angeles", "Seattle“,
"London", "Paris", "New Delhi“,"Hong Kong",
"Tokyo", "Sydney" };
•JList jlst = new JList(Cities);
•jlst.setSelectionMode(ListSelectionModel.SING
LE_SELECTION);
JComboBox
•Swing provides a combo box (a combination of
a text field and a drop-down list) through the
JComboBox class.
–JComboBox(Object[ ] items)
•Methods
–void addItem(Object obj)
–Object getSelectedItem( )
•String flags[] = { "France", "Germany", "Italy",
"Japan" };
•JComboBox jcb = new JComboBox(flags);
JTable
• A table displays a two-dimensional grid of
objects
31
31
Constructors - Methods of JTable
• JTable(Object[][] entries, Object[] columnNames)
– constructs a table with a default table model
• JTable(TableModel model)
– displays the elements in the specified, non-null table
model
• int getSelectedRow()
– returns the index of the first selected row, -1 if no row
is selected
• Object getValueAt(int row, int column)
• void setValueAt(Object value, int row, int
column)
– gets or sets the value at the given row and column
• int getRowCount()
– returns the number of row in the table 32
32
JTable with Fixed Set of Choices
• Build JTable:
– Supply the column names:
String[] columnNames = { "Ma mon", "Ten mon", "So tin chi"};
– Create data in two-dimensional array of Object:
Object[][] cells = {{"001", "Lap trinh Windows", new Integer(5)},
{"002", "Do hoa may tinh", new Integer(4)}, {"003", "Phan tich
thiet ke", new Integer(5)}, …};
– Construct a table from the cell and column name arrays:
JTable table = new JTable(cells, columnNames);
– Finally, add scroll bars in the usual way, by wrapping the
table in a JScrollPane:
JScrollPane pane = new JScrollPane(table);
3333
Example: JTableDemo.java
34
34
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class JTableDemo extends JFrame {
public JTableDemo() {
String[] colnames = {“SNO",“Name”,”deptno"};
Object[ ][ ] cells = {
{"001", “Rahul", new Integer(5)},
{"002", “Mukesh", new Integer(4)},
{"003", “Akshay", new Integer(5)}
};
JTable table = new JTable(cells, colnames);
add(new JScrollPane(table));
setSize(200,200);
setVisible(true);
}
public static void main(String args[]) {
new JTableDemo();
}
}
JTable with Changeable Choices
• Build JTable:
– Create a columns name array, create a
DefaultTableModel, pass to constructor
String[] cols= {“Sno", “Name", “deptno"};
DefaultTableModel model=new DefaultTableModel(cols,0);
JTable table = new JTable(model);
JScrollPane pane = new JScrollPane(table);
• Add/remove elements
– Use the model, not the JTable directly
36
36
Methods in DefaultTableModel
• void addRow(Object[] rowData)
– add a row of data to the end of the table model
• void insertRow(int row,
Object[] rowData)
– adds a row of data at index row
• void removeRow(int row)
– removes the given row from the model
37
37
Event of JTable
• We use MouseEvent to process event of
choosing rows on JTable
– implement MouseListener (in java.awt.event)
– method ?
– register ?
38
38
public void mouseClicked (MouseEvent e) {}
public void mousePressed (MouseEvent e) {}
public void mouseReleased (MouseEvent e) {}
public void mouseEntered (MouseEvent e) {}
public void mouseExited (MouseEvent e) {}
JTable with Custom Data ModelJTable with Custom Data Model
• Build custom JTable
– Create a class has Vector field, this class extends
AbstractTableModel
• public int getColumnCount()
• public int getRowCount()
• public void setValueAt(Object value, int row, int col)
• public Object getValueAt(int row, int col)
• public String getColumnName(int col)
• public Class getColumnClass(int c)
– Pass model to JTable constructor
• Add/remove items: use the model
39
39
JTree
• JTree is used to display hierarchical data
• A JTree is composed of TreeNode
– Root node
– Parent node
– Child node
– Leaf node
40
40
Contructors of JTree
• JTree (TreeNode root)
– construct a tree with a default tree model that displays
the root
• JTree (TreeModel model)
– constructs a tree from a tree model
• TreeNode is an interface. How do you obtain it?
– Using the DefaultMutableTreeNode class (in
package javax.swing.tree)
– Constructing your own treenode by creating a class that
implements the TreeNode interface
41
41
Methods of JTree
• void setEditable(boolean b)
• void setRootVisible(boolean b)
• void makeVisible(TreePath path)
• void scrollPathToVisible(TreePath path)
• Object getLastSelectedPathComponent()
42
42
Event of JTree
• When the user selects tree nodes, a tree
produces a TreeSelectionEvent
– implement TreeSelectionListener
(javax.swing.event)
– method
• public void
valueChanged(TreeSelectionEvent event)
 That method is called whenever the user selects or
deselects tree nodes
– register
JTree with Fixed Set of Nodes
• Build JTree
– Create a root node and child nodes:
DefaultMutableTreeNode root=new DefaultMutableTreeNode("World");
DefaultMutableTreeNode country,country1;
country = new DefaultMutableTreeNode("USA");
root.add(country);
country1 = new DefaultMutableTreeNode("Germany");
root.add(country);
– Pass root node in JTree’s constructor:
JTree tree = new JTree(root);
– Add JTree to scrollpane:
JScrollPane scrollTree = new JScrollPane(tree);
JTreeSimpleDemo.java
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
public class TreeSimpleDemo extends JFrame {
JTree tree;
public TreeSimpleDemo() {
setTitle("Simple Tree demo");
// set up tree model data
DefaultMutableTreeNode root = new DefaultMutableTreeNode("World");
DefaultMutableTreeNode country = new DefaultMutableTreeNode("USA");
root.add(country);
DefaultMutableTreeNode state = new DefaultMutableTreeNode("California");
country.add(state);
DefaultMutableTreeNode city = new DefaultMutableTreeNode("San Jose");
state.add(city);
city = new DefaultMutableTreeNode("Cupertino");
state.add(city);
state = new DefaultMutableTreeNode("Michigan");
country.add(state);
JTreeSimpleDemo.java (cont.)
city = new DefaultMutableTreeNode("Ann Arbor");
state.add(city);
country = new DefaultMutableTreeNode("Germany");
root.add(country);
state = new DefaultMutableTreeNode("Schleswig-Holstein");
country.add(state);
// construct tree and put it in a scroll pane
tree = new JTree(root);
JScrollPane scrollTree = new JScrollPane(tree);
add(scrollTree);
setSize(300, 200);
setVisible(true);
}
public static void main(String[] args) {
new TreeSimpleDemo();
}
}
46
46
Event handling
What are events?
• All components can listen for one or more events.
• Typical examples are:
– Mouse movements
– Mouse clicks
– Hitting any key
– Hitting return key
– etc.
• Telling the GUI what to do when a particular
event occurs is the role of the event handler.
ActionEvent
• In Java, most components have a special
event called an ActionEvent.
• This is loosely speaking the most common
or canonical event for that component.
• A good example is a click for a button.
• To have any component listen for
ActionEvents, you must register the
component with an ActionListener. e.g.
– button.addActionListener(new MyAL());
Delegation, cont.
• This is referred to as the Delegation Model.
• When you register an ActionListener with a
component, you must pass it the class which
will handle the event – that is, do the work
when the event is triggered.
• For an ActionEvent, this class must
implement the ActionListener interface.
• This is simple a way of guarantee that the
actionPerformed method is defined.
actionPerformed
• The actionPerformed method has the following
signature:
void actionPerformed(ActionEvent)
• The object of type ActionEvent passed to the
event handler is used to query information about
the event.
• Some common methods are:
– getSource()
• object reference to component generating event
– getActionCommand()
• some text associated with event (text on button, etc).
actionPerformed, cont.
• These methods are particularly useful when
using one eventhandler for multiple
components.
Swing basics
Swing basics
Swing basics
Swing basics
Swing basics
Swing basics

More Related Content

What's hot

Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1
PRN USM
 
Exercises of java tutoring -version1
Exercises of java tutoring -version1Exercises of java tutoring -version1
Exercises of java tutoring -version1
Uday Sharma
 

What's hot (20)

25 awt
25 awt25 awt
25 awt
 
Gui
GuiGui
Gui
 
Jdbc
JdbcJdbc
Jdbc
 
The Ring programming language version 1.3 book - Part 83 of 88
The Ring programming language version 1.3 book - Part 83 of 88The Ring programming language version 1.3 book - Part 83 of 88
The Ring programming language version 1.3 book - Part 83 of 88
 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
 
Dr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWTDr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWT
 
Complete java swing
Complete java swingComplete java swing
Complete java swing
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
Swing and Graphical User Interface in Java
Swing and Graphical User Interface in JavaSwing and Graphical User Interface in Java
Swing and Graphical User Interface in Java
 
Java Swing JFC
Java Swing JFCJava Swing JFC
Java Swing JFC
 
Swing
SwingSwing
Swing
 
Java awt tutorial javatpoint
Java awt tutorial   javatpointJava awt tutorial   javatpoint
Java awt tutorial javatpoint
 
GUI components in Java
GUI components in JavaGUI components in Java
GUI components in Java
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1
 
Java swing
Java swingJava swing
Java swing
 
Graphical User Components Part 1
Graphical User Components Part 1Graphical User Components Part 1
Graphical User Components Part 1
 
java- Abstract Window toolkit
java- Abstract Window toolkitjava- Abstract Window toolkit
java- Abstract Window toolkit
 
Matlab GUI
Matlab GUIMatlab GUI
Matlab GUI
 
Awt
AwtAwt
Awt
 
Exercises of java tutoring -version1
Exercises of java tutoring -version1Exercises of java tutoring -version1
Exercises of java tutoring -version1
 

Similar to Swing basics

Chapter 5 GUI for introduction of java and gui .ppt
Chapter 5 GUI  for  introduction of java and gui .pptChapter 5 GUI  for  introduction of java and gui .ppt
Chapter 5 GUI for introduction of java and gui .ppt
HabibMuhammed2
 
12advanced Swing
12advanced Swing12advanced Swing
12advanced Swing
Adil Jafri
 
Getting started with GUI programming in Java_1
Getting started with GUI programming in Java_1Getting started with GUI programming in Java_1
Getting started with GUI programming in Java_1
Muhammad Shebl Farag
 
13 advanced-swing
13 advanced-swing13 advanced-swing
13 advanced-swing
Nataraj Dg
 
Getting started with GUI programming in Java_2
Getting started with GUI programming in Java_2Getting started with GUI programming in Java_2
Getting started with GUI programming in Java_2
Muhammad Shebl Farag
 

Similar to Swing basics (20)

Chapter 5 GUI for introduction of java and gui .ppt
Chapter 5 GUI  for  introduction of java and gui .pptChapter 5 GUI  for  introduction of java and gui .ppt
Chapter 5 GUI for introduction of java and gui .ppt
 
11basic Swing
11basic Swing11basic Swing
11basic Swing
 
Basic swing
Basic swingBasic swing
Basic swing
 
Advanced java programming
Advanced java programmingAdvanced java programming
Advanced java programming
 
13457272.ppt
13457272.ppt13457272.ppt
13457272.ppt
 
Swings
SwingsSwings
Swings
 
12advanced Swing
12advanced Swing12advanced Swing
12advanced Swing
 
ch20.pptx
ch20.pptxch20.pptx
ch20.pptx
 
Unit-2 swing and mvc architecture
Unit-2 swing and mvc architectureUnit-2 swing and mvc architecture
Unit-2 swing and mvc architecture
 
CORE JAVA-2
CORE JAVA-2CORE JAVA-2
CORE JAVA-2
 
Quiz app(j tabbed pane,jdialog,container,actionevent,jradiobutton,buttongroup...
Quiz app(j tabbed pane,jdialog,container,actionevent,jradiobutton,buttongroup...Quiz app(j tabbed pane,jdialog,container,actionevent,jradiobutton,buttongroup...
Quiz app(j tabbed pane,jdialog,container,actionevent,jradiobutton,buttongroup...
 
Getting started with GUI programming in Java_1
Getting started with GUI programming in Java_1Getting started with GUI programming in Java_1
Getting started with GUI programming in Java_1
 
13 advanced-swing
13 advanced-swing13 advanced-swing
13 advanced-swing
 
GWT Widgets
GWT WidgetsGWT Widgets
GWT Widgets
 
DSJ_Unit III.pdf
DSJ_Unit III.pdfDSJ_Unit III.pdf
DSJ_Unit III.pdf
 
Java swing
Java swingJava swing
Java swing
 
Awt components
Awt componentsAwt components
Awt components
 
Module 4
Module 4Module 4
Module 4
 
swings.pptx
swings.pptxswings.pptx
swings.pptx
 
Getting started with GUI programming in Java_2
Getting started with GUI programming in Java_2Getting started with GUI programming in Java_2
Getting started with GUI programming in Java_2
 

Recently uploaded

Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
plant breeding methods in asexually or clonally propagated crops
plant breeding methods in asexually or clonally propagated cropsplant breeding methods in asexually or clonally propagated crops
plant breeding methods in asexually or clonally propagated crops
parmarsneha2
 

Recently uploaded (20)

50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
 
Salient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptxSalient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptx
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
NLC-2024-Orientation-for-RO-SDO (1).pptx
NLC-2024-Orientation-for-RO-SDO (1).pptxNLC-2024-Orientation-for-RO-SDO (1).pptx
NLC-2024-Orientation-for-RO-SDO (1).pptx
 
Benefits and Challenges of Using Open Educational Resources
Benefits and Challenges of Using Open Educational ResourcesBenefits and Challenges of Using Open Educational Resources
Benefits and Challenges of Using Open Educational Resources
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptxJose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
 
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.pptBasic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
 
B.ed spl. HI pdusu exam paper-2023-24.pdf
B.ed spl. HI pdusu exam paper-2023-24.pdfB.ed spl. HI pdusu exam paper-2023-24.pdf
B.ed spl. HI pdusu exam paper-2023-24.pdf
 
plant breeding methods in asexually or clonally propagated crops
plant breeding methods in asexually or clonally propagated cropsplant breeding methods in asexually or clonally propagated crops
plant breeding methods in asexually or clonally propagated crops
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Basic Civil Engineering Notes of Chapter-6, Topic- Ecosystem, Biodiversity G...
Basic Civil Engineering Notes of Chapter-6,  Topic- Ecosystem, Biodiversity G...Basic Civil Engineering Notes of Chapter-6,  Topic- Ecosystem, Biodiversity G...
Basic Civil Engineering Notes of Chapter-6, Topic- Ecosystem, Biodiversity G...
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdfDanh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 

Swing basics

  • 2. Swing Components • Swing is a collection of libraries that contains primitive widgets or controls used for designing Graphical User Interfaces (GUIs). • Commonly used classes in javax.swing package: – JButton, JTextBox, JTextArea, JPanel, JFrame, JMenu, JSlider, JLabel, JIcon, … – There are many, many such classes to do anything imaginable with GUIs – Here we only study the basic architecture and do simple examples
  • 3. Swing components, cont. • Each component is a Java class with a fairly extensive inheritency hierarchy: Object Component Container JComponent JPanel Window Frame JFrame
  • 4. Using Swing Components • Very simple, just create object from appropriate class – examples: – JButton button = new JButton(); – JTextField text = new JTextField(); – JTextArea text = new JTextArea(); – JLabel lab = new JLabel();
  • 5. Adding components • Once a component is created, it can be added to a container by calling the container’s add method: Container cp = getContentPane(); cp.add(new JButton(“cancel”)); cp.add(new JButton(“go”)); How these are laid out is determined by the layout manager. This is required
  • 6. Laying out components • Use layout managers – basically tells form how to align components when they’re added. • Each Container has a layout manager associated with it. • A JPanel is a Container –Set the desired layout manager for each JPanel, then add components directly to panels.
  • 7. Layout Managers • Java comes with 7 or 8. Most common and easiest to use are – FlowLayout – BorderLayout – GridLayout
  • 8. Setting layout managers • Very easy to associate a layout manager with a component. Simply call the setLayout method on the Container: JPanel p1 = new JPanel(); p1.setLayout(new FlowLayout(FlowLayout.LEFT)); JPanel p2 = new JPanel(); p2.setLayout(new BorderLayout()); As Components are added to the container, the layout manager determines their size and positioning.
  • 9. Simplest GUI import javax.swing.JFrame; class SimpleGUI extends JFrame{ SimpleGUI(){ setSize(400,400); //set frames size in pixels setDefaultCloseOperation(EXIT_ON_CLOSE); show(); } public static void main(String[] args){ SimpleGUI gui = new SimpleGUI(); System.out.println(“main thread coninues”); } }
  • 10. Another Simple GUI import javax.swing.*; class SimpleGUI extends JFrame{ SimpleGUI(){ setSize(400,400); //set frames size in pixels setDefaultCloseOperation(EXIT_ON_CLOSE); JButton but1 = new JButton(“Click me”); Container cp = getContentPane();//must do this cp.add(but1); show(); } public static void main(String[] args){ SimpleGUI gui = new SimpleGUI(); System.out.println(“main thread coninues”); }}
  • 11. Add Layout Manager import javax.swing.*; import java.awt.*; class SimpleGUI extends JFrame{ SimpleGUI(){ setSize(400,400); //set frames size in pixels setDefaultCloseOperation(EXIT_ON_CLOSE); JButton but1 = new JButton(“Click me”); Container cp = getContentPane();//must do this cp.setLayout(new FlowLayout(FlowLayout.CENTER); cp.add(but1); show(); } public static void main(String[] args){ SimpleGUI gui = new SimpleGUI(); System.out.println(“main thread coninues”); }}
  • 12. Add call to event handler import javax.swing.*; import java.awt.*; class SimpleGUI extends JFrame{ SimpleGUI(){ setSize(400,400); //set frames size in pixels setDefaultCloseOperation(EXIT_ON_CLOSE); JButton but1 = new JButton(“Click me”); Container cp = getContentPane();//must do this cp.setLayout(new FlowLayout(FlowLayout.CENTER); but1.addActionListener(new MyActionListener()); cp.add(but1); show(); } public static void main(String[] args){ SimpleGUI gui = new SimpleGUI(); System.out.println(“main thread coninues”); }}
  • 13. Event Handler Code class MyActionListener implements ActionListener{ public void actionPerformed(ActionEvent ae){ JOptionPane.showMessageDialog(“I got clicked”, null); } }
  • 14. JFrame •JFrame is the top-level container that is commonly used for Swing applications. –setSize(275, 100); –setVisible(true); –void setDefaultCloseOperation(int what); –JFrame.EXIT_ON_CLOSE. –JFrame.DISPOSE_ON_CLOSE –JFrame.HIDE_ON_CLOSE –JFrame.DO_NOTHING_ON_CLOSE
  • 15. JLabel and ImageIcon •Constructor –JLabel(Icon icon) –JLabel(String str) –JLabel(String str, Icon icon, int align) •Methods –Icon getIcon( ) –String getText( ) –void setIcon(Icon icon) –void setText(String str) –ImageIcon ii = new ImageIcon("france.gif"); –// Create a label. –JLabel jl = new JLabel("France", ii, JLabel.CENTER);
  • 16. JTextField •Constructors –JTextField(int cols) –JTextField(String str, int cols) –JTextField(String str) –jtf = new JTextField(15);
  • 17. The Swing Buttons •Swing defines four types of buttons: JButton, JToggleButton, JCheckBox, and JRadioButton. •All are subclasses of the AbstractButton class, which extends JComponent. Thus, all buttons share a set of common traits. –void setDisabledIcon(Icon di) –void setPressedIcon(Icon pi) –void setSelectedIcon(Icon si) –void setRolloverIcon(Icon ri) –String getText( ) –void setText(String str)
  • 18. JButton •Constructors –JButton(Icon icon) –JButton(String str) –JButton(String str, Icon icon) •Methods –String getActionCommand( ) –void setActionCommand( )
  • 19. JToggleButton •Auseful variation on the push button is called a toggle button. A toggle button looks just like a push button, but it acts differently because it has two states: pushed and released. –JToggleButton(String str) •Methods –Object getItem( ) –boolean isSelected( )
  • 20. Check Boxes •The JCheckBox class provides the functionality of a check box. Its immediate superclass is JToggleButton, which provides support for two- state buttons JCheckBox(String str)
  • 21. Radio Buttons •JRadioButton(String str) •JRadioButton b1 = new JRadioButton("A"); •JRadioButton b2 = new JRadioButton(“B"); •JRadioButton b3 = new JRadioButton(“C"); •ButtonGroup bg = new ButtonGroup(); •bg.add(b1); •bg.add(b2); •bg.add(b3);
  • 22. JTabbedPane •The general procedure to use a tabbed pane is outlined here: 1.Create an instance of JTabbedPane. 2.Add each tab by calling addTab( ). 3.Add the tabbed pane to the content pane. 1.JTabbedPane jtp = new JTabbedPane(); 2.jtp.addTab("Cities", new CitiesPanel()); 3.jtp.addTab("Colors", new ColorsPanel()); 4.jtp.addTab("Flavors", new FlavorsPanel());
  • 23. •class ColorsPanel extends JPanel { •public ColorsPanel() { •JCheckBox cb1 = new JCheckBox("Red"); •add(cb1); •JCheckBox cb2 = new JCheckBox("Green"); •add(cb2); •JCheckBox cb3 = new JCheckBox("Blue"); •add(cb3); •} •} •class FlavorsPanel extends JPanel { •public FlavorsPanel() { class CitiesPanel extends JPanel public CitiesPanel() { JButton b1 = new JButton("New York"); add(b1); JButton b2 = new JButton("London"); add(b2); JButton b3 = new JButton("Hong Kong"); add(b3); JButton b4 = new JButton("Tokyo"); add(b4); } }
  • 24. JScrollPane •JScrollPane is a lightweight container that automatically handles the scrolling of another component. The component being scrolled can either be an individual component, such as a table, or a group of components contained within another lightweight container, such as a JPanel. In either case, if the object being scrolled is larger than the viewable area, horizontal and/or vertical scroll bars are automatically provided, and the component can be scrolled through the pane. Because JScrollPane automates scrolling, it usually eliminates the need to manage individual scroll bars.
  • 25. •Here are the steps to follow to use a scroll pane: –Create the component to be scrolled. –Create an instance of JScrollPane, passing to it the object to scroll. –Add the scroll pane to the content pane
  • 26. JPanel jp = new JPanel(); jp.setLayout(new GridLayout(20, 20)); int b = 0; for(int i = 0; i < 20; i++) { for(int j = 0; j < 20; j++) { jp.add(new JButton("Button " + b)); ++b; } } // Create the scroll pane. JScrollPane jsp = new JScrollPane(jp); // Add the scroll pane to the content pane. // Because the default border layout is used, // the scroll pane will be added to the center. add(jsp, BorderLayout.CENTER);
  • 27. JList •In Swing, the basic list class is called JList. It supports the selection of one or more items from a list. •JList(Object[ ] items) •ListSelectionModel: –SINGLE_SELECTION –SINGLE_INTERVAL_SELECTION –MULTIPLE_INTERVAL_SELECTION •int getSelectedIndex( )
  • 28. •String Cities[] = { "New York", "Chicago", "Houston“,"Denver", "Los Angeles", "Seattle“, "London", "Paris", "New Delhi“,"Hong Kong", "Tokyo", "Sydney" }; •JList jlst = new JList(Cities); •jlst.setSelectionMode(ListSelectionModel.SING LE_SELECTION);
  • 29. JComboBox •Swing provides a combo box (a combination of a text field and a drop-down list) through the JComboBox class. –JComboBox(Object[ ] items) •Methods –void addItem(Object obj) –Object getSelectedItem( )
  • 30. •String flags[] = { "France", "Germany", "Italy", "Japan" }; •JComboBox jcb = new JComboBox(flags);
  • 31. JTable • A table displays a two-dimensional grid of objects 31 31
  • 32. Constructors - Methods of JTable • JTable(Object[][] entries, Object[] columnNames) – constructs a table with a default table model • JTable(TableModel model) – displays the elements in the specified, non-null table model • int getSelectedRow() – returns the index of the first selected row, -1 if no row is selected • Object getValueAt(int row, int column) • void setValueAt(Object value, int row, int column) – gets or sets the value at the given row and column • int getRowCount() – returns the number of row in the table 32 32
  • 33. JTable with Fixed Set of Choices • Build JTable: – Supply the column names: String[] columnNames = { "Ma mon", "Ten mon", "So tin chi"}; – Create data in two-dimensional array of Object: Object[][] cells = {{"001", "Lap trinh Windows", new Integer(5)}, {"002", "Do hoa may tinh", new Integer(4)}, {"003", "Phan tich thiet ke", new Integer(5)}, …}; – Construct a table from the cell and column name arrays: JTable table = new JTable(cells, columnNames); – Finally, add scroll bars in the usual way, by wrapping the table in a JScrollPane: JScrollPane pane = new JScrollPane(table); 3333
  • 34. Example: JTableDemo.java 34 34 import javax.swing.*; import java.awt.*; import java.awt.event.*; class JTableDemo extends JFrame { public JTableDemo() { String[] colnames = {“SNO",“Name”,”deptno"}; Object[ ][ ] cells = { {"001", “Rahul", new Integer(5)}, {"002", “Mukesh", new Integer(4)}, {"003", “Akshay", new Integer(5)} }; JTable table = new JTable(cells, colnames); add(new JScrollPane(table)); setSize(200,200); setVisible(true); } public static void main(String args[]) { new JTableDemo(); } }
  • 35. JTable with Changeable Choices • Build JTable: – Create a columns name array, create a DefaultTableModel, pass to constructor String[] cols= {“Sno", “Name", “deptno"}; DefaultTableModel model=new DefaultTableModel(cols,0); JTable table = new JTable(model); JScrollPane pane = new JScrollPane(table); • Add/remove elements – Use the model, not the JTable directly 36 36
  • 36. Methods in DefaultTableModel • void addRow(Object[] rowData) – add a row of data to the end of the table model • void insertRow(int row, Object[] rowData) – adds a row of data at index row • void removeRow(int row) – removes the given row from the model 37 37
  • 37. Event of JTable • We use MouseEvent to process event of choosing rows on JTable – implement MouseListener (in java.awt.event) – method ? – register ? 38 38 public void mouseClicked (MouseEvent e) {} public void mousePressed (MouseEvent e) {} public void mouseReleased (MouseEvent e) {} public void mouseEntered (MouseEvent e) {} public void mouseExited (MouseEvent e) {}
  • 38. JTable with Custom Data ModelJTable with Custom Data Model • Build custom JTable – Create a class has Vector field, this class extends AbstractTableModel • public int getColumnCount() • public int getRowCount() • public void setValueAt(Object value, int row, int col) • public Object getValueAt(int row, int col) • public String getColumnName(int col) • public Class getColumnClass(int c) – Pass model to JTable constructor • Add/remove items: use the model 39 39
  • 39. JTree • JTree is used to display hierarchical data • A JTree is composed of TreeNode – Root node – Parent node – Child node – Leaf node 40 40
  • 40. Contructors of JTree • JTree (TreeNode root) – construct a tree with a default tree model that displays the root • JTree (TreeModel model) – constructs a tree from a tree model • TreeNode is an interface. How do you obtain it? – Using the DefaultMutableTreeNode class (in package javax.swing.tree) – Constructing your own treenode by creating a class that implements the TreeNode interface 41 41
  • 41. Methods of JTree • void setEditable(boolean b) • void setRootVisible(boolean b) • void makeVisible(TreePath path) • void scrollPathToVisible(TreePath path) • Object getLastSelectedPathComponent() 42 42
  • 42. Event of JTree • When the user selects tree nodes, a tree produces a TreeSelectionEvent – implement TreeSelectionListener (javax.swing.event) – method • public void valueChanged(TreeSelectionEvent event)  That method is called whenever the user selects or deselects tree nodes – register
  • 43. JTree with Fixed Set of Nodes • Build JTree – Create a root node and child nodes: DefaultMutableTreeNode root=new DefaultMutableTreeNode("World"); DefaultMutableTreeNode country,country1; country = new DefaultMutableTreeNode("USA"); root.add(country); country1 = new DefaultMutableTreeNode("Germany"); root.add(country); – Pass root node in JTree’s constructor: JTree tree = new JTree(root); – Add JTree to scrollpane: JScrollPane scrollTree = new JScrollPane(tree);
  • 44. JTreeSimpleDemo.java import java.awt.*; import javax.swing.*; import javax.swing.tree.*; public class TreeSimpleDemo extends JFrame { JTree tree; public TreeSimpleDemo() { setTitle("Simple Tree demo"); // set up tree model data DefaultMutableTreeNode root = new DefaultMutableTreeNode("World"); DefaultMutableTreeNode country = new DefaultMutableTreeNode("USA"); root.add(country); DefaultMutableTreeNode state = new DefaultMutableTreeNode("California"); country.add(state); DefaultMutableTreeNode city = new DefaultMutableTreeNode("San Jose"); state.add(city); city = new DefaultMutableTreeNode("Cupertino"); state.add(city); state = new DefaultMutableTreeNode("Michigan"); country.add(state);
  • 45. JTreeSimpleDemo.java (cont.) city = new DefaultMutableTreeNode("Ann Arbor"); state.add(city); country = new DefaultMutableTreeNode("Germany"); root.add(country); state = new DefaultMutableTreeNode("Schleswig-Holstein"); country.add(state); // construct tree and put it in a scroll pane tree = new JTree(root); JScrollPane scrollTree = new JScrollPane(tree); add(scrollTree); setSize(300, 200); setVisible(true); } public static void main(String[] args) { new TreeSimpleDemo(); } } 46 46
  • 47. What are events? • All components can listen for one or more events. • Typical examples are: – Mouse movements – Mouse clicks – Hitting any key – Hitting return key – etc. • Telling the GUI what to do when a particular event occurs is the role of the event handler.
  • 48. ActionEvent • In Java, most components have a special event called an ActionEvent. • This is loosely speaking the most common or canonical event for that component. • A good example is a click for a button. • To have any component listen for ActionEvents, you must register the component with an ActionListener. e.g. – button.addActionListener(new MyAL());
  • 49. Delegation, cont. • This is referred to as the Delegation Model. • When you register an ActionListener with a component, you must pass it the class which will handle the event – that is, do the work when the event is triggered. • For an ActionEvent, this class must implement the ActionListener interface. • This is simple a way of guarantee that the actionPerformed method is defined.
  • 50. actionPerformed • The actionPerformed method has the following signature: void actionPerformed(ActionEvent) • The object of type ActionEvent passed to the event handler is used to query information about the event. • Some common methods are: – getSource() • object reference to component generating event – getActionCommand() • some text associated with event (text on button, etc).
  • 51. actionPerformed, cont. • These methods are particularly useful when using one eventhandler for multiple components.

Editor's Notes

  1. Volumes of data are better maintained in a tabular format than as a list
  2. Delete all rows in table: while (model.getRowCount()&amp;gt;0){model.remove(0);} Or: DefaultTableModel dm = (DefaultTableModel)table.getModel();dm.getDataVector().removeAllElements();
  3. Có thể dùng cách đơn giản hơn là: add(Object)
  4. By default, the tree displays the root node. A node having child nodes is called a branch node else it is called as a. A specific node in a tree can be identified either by a TreePath, an object that encapsulates a node and all of its ancestors
  5. Có khoảng 7 hàm khởi tạo JTree You populate the default tree model with objects of any class that implements the interface. We can use the concrete node class, namely, DefaultMutableTreeNode. This class implements the MutableTreeNode interface, a subinterface of TreeNode
  6. setRootVisible: áp dụng cho trường hợp cây chưa có nút gốc
  7. DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); if (selectedNode == null) return;