This document provides an overview of Java GUI libraries and Swing programming. It discusses key Swing components like JButton, JTextField, JLabel and how to add them to containers using layout managers. It also covers more advanced topics like JTable, JTree, event handling and creating custom Swing components. The document is a useful reference for learning how to build graphical user interfaces in Java using the Swing toolkit.
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);
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)
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( )
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).
Volumes of data are better maintained in a tabular format than as a list
Delete all rows in table:
while (model.getRowCount()&gt;0){model.remove(0);}
Or:
DefaultTableModel dm = (DefaultTableModel)table.getModel();dm.getDataVector().removeAllElements();
Có thể dùng cách đơn giản hơn là: add(Object)
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
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
setRootVisible: áp dụng cho trường hợp cây chưa có nút gốc
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
if (selectedNode == null) return;