Chapter 8. GUI Programming - HNT
Chapter 8. GUI Programming - HNT
Objective
❑Understanding the using of Swing control
❑Using events of controls component
❑Using the basis layout to design GUI
Object Oriented Programming Course VKU
Part 1
• Introduction to Swing, JFrame, Jpanel
Object Oriented Programming Course VKU
Content
• Creating GUI
• Control Components
Object Oriented Programming Course VKU
GUI Package
• Gói Abstract Window Toolkit
import java.awt.*;
• Gói Event and Listener import java.awt.event.*;
• Gói Java Swing
import javax.swing.*;
Object Oriented Programming Course VKU
Example
public class MyWindow extends JFrame{
public MyWindow(){
super("Demo Windows");
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
MyWindow ui=new MyWindow();
ui.setSize(400, 300);
ui.setLocationRelativeTo(null);
ui.setVisible(true);
}
}
Object Oriented Programming Course VKU
Example
super("Demo Windows");
Use to set title for this window
setDefaultCloseOperation(EXIT_ON_CLOSE);
Allow click ‘x’ Top right corner to close the window
ui.setSize(400, 300);
set Width =400 and Height =300
ui.setLocationRelativeTo(null);
Display window on desktop center screen
ui.setVisible(true);
Show the window
7
Object Oriented Programming Course VKU
JPanel
• Group components
• JPanel contains control components and other panels
8
Object Oriented Programming Course VKU
9
Object Oriented Programming Course VKU
Layout in Swing
• Flowlayout
• Boxlayout
• Borderlayout
• CardLayout
10
Object Oriented Programming Course VKU
FlowLayout
• Flowlayout
11
Object Oriented Programming Course VKU
Example
JPanel pnFlow=new JPanel();
pnFlow.setLayout(new FlowLayout());
pnFlow.setBackground(Color.PINK);
JButton btn1=new JButton("FlowLayout");
JButton btn2=new JButton("Add các control");
JButton btn3=new JButton("Trên 1 dòng");
JButton btn4=new JButton("Hết chỗ chứa");
JButton btn5=new JButton("Thì xuống dòng");
pnFlow.add(btn1);pnFlow.add(btn2);
pnFlow.add(btn3);pnFlow.add(btn4);
pnFlow.add(btn5);
Container con=getContentPane();
con.add(pnFlow);
12
Object Oriented Programming Course VKU
FlowLayout
• pnFlow.setLayout(new FlowLayout());
• Setup FlowLayout for pnFlow
• pnFlow.add(btn1);
• Add new button into the pnFlow
• Container con=getContentPane();
• get the Window container
• con.add(pnFlow);
• add pnFlow panel into the window container
13
Object Oriented Programming Course VKU
BoxLayout
• BoxLayout cho phép add các control theo dòng hoặc cột, tại mỗi
vị trí add nó chỉ chấp nhận 1 control, do đó muốn xuất hiện
nhiều control tại một vị trí thì bạn nên add vị trí đó là 1 JPanel
rồi sau đó add các control khác vào JPanel này.
• BoxLayout.X_AXIS cho phép add các control theo hướng từ
trái qua phải.
• BoxLayout.Y_AXIS cho phép add các control theo hướng từ
trên xuống dưới.
• BoxLayout sẽ không tự động xuống dòng khi hết chỗ chứa,
tức là các control sẽ bị che khuất nếu như thiếu không gian
chứa nó.
14
Object Oriented Programming Course VKU
BoxLayout
BoxLayout.X_AXIS BoxLayout.Y_AXIS
15
Object Oriented Programming Course VKU
BoxLayout
JPanel pnBox=new JPanel();
pnBox.setLayout(new BoxLayout(pnBox, BoxLayout.X_AXIS));
JButton btn1=new JButton("BoxLayout");
btn1.setForeground(Color.RED);
Font font=new Font("Arial",Font.BOLD | Font.ITALIC,25);
btn1.setFont(font);pnBox.add(btn1);
JButton btn2=new JButton("X_AXIS");
btn2.setForeground(Color.BLUE);
btn2.setFont(font);pnBox.add(btn2);
JButton btn3=new JButton("Y_AXIS");
btn3.setForeground(Color.ORANGE);
btn3.setFont(font);pnBox.add(btn3);
Container con=getContentPane();
con.add(pnBox);
16
Object Oriented Programming Course VKU
BoxLayout
pnBox.setLayout(new BoxLayout(pnBox, BoxLayout.X_AXIS));
Setup BoxLayout for pnBox with X_AXIS
btn1.setForeground(Color.RED);
Setup TextColor for button btn1
btn1.setFont(font);
setup font for button btn1
17
Object Oriented Programming Course VKU
BorderLayout
• BorderLayout locates controls in 5 zones: North, South, West, East,
Center
• Nếu như không có 4 vùng : North, West, South, East. Thì vùng
Center sẽ tràn đầy cửa sổ, thông thường khi đưa các control JTable,
JTree, ListView, JScrollpane… ta thường đưa vào vùng Center để
nó có thể tự co giãn theo kích thước cửa sổ giúp giao diện đẹp hơn.
18
Object Oriented Programming Course VKU
BorderLayout
JPanel pnBorder=new JPanel();
pnBorder.setLayout(new BorderLayout());
JPanel pnNorth=new JPanel();
pnNorth.setBackground(Color.RED);
pnBorder.add(pnNorth,BorderLayout.NORTH);
JPanel pnSouth=new JPanel();
pnSouth.setBackground(Color.RED);
pnBorder.add(pnSouth,BorderLayout.SOUTH);
JPanel pnWest=new JPanel();
pnWest.setBackground(Color.BLUE);
pnBorder.add(pnWest,BorderLayout.WEST);
JPanel pnEast=new JPanel();
pnEast.setBackground(Color.BLUE);
pnBorder.add(pnEast,BorderLayout.EAST);
JPanel pnCenter=new JPanel();
pnCenter.setBackground(Color.YELLOW);
pnBorder.add(pnCenter,BorderLayout.CENTER);
getContentPane().add(pnBorder);
19
Object Oriented Programming Course VKU
BorderLayout
pnBorder.setLayout(new BorderLayout());
Setup BorderLayout for pnBorder
pnBorder.add(pnNorth,BorderLayout.NORTH);
Add pnNorth into the NORTH side
pnBorder.add(pnSouth,BorderLayout.SOUTH);
Add pnSouth into the SOUTH side
pnBorder.add(pnWest,BorderLayout.WEST);
Add pnWest into the WEST side
pnBorder.add(pnEast,BorderLayout.EAST);
Add pnEast into the EAST side
pnBorder.add(pnCenter,BorderLayout.CENTER);
Add pnCenter into the CENTER side
20
Object Oriented Programming Course VKU
CardLayout
• CardLayout cho phép chia sẻ vị trí hiển thị của các control, tức
là ứng với cùng 1 vị trí hiển thị đó thì ta có thể cho các control
khác hiển thị tại những thời điểm khác nhau, mặc định control
được add đầu tiên sẽ hiển thị.
21
Object Oriented Programming Course VKU
CardLayout
final JPanel pnCenter=new JPanel();
pnCenter.setLayout(new CardLayout());
final JPanel pnCard1=new JPanel();
pnCard1.setBackground(Color.LIGHT_GRAY);
final JPanel pnCard2=new JPanel();
pnCard2.setBackground(Color.PINK);
pnCenter.add(pnCard1,"mycard1");
pnCenter.add(pnCard2,"mycard2");
btnShowCard1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
CardLayout cl=(CardLayout)pnCenter.getLayout();
cl.show(pnCenter, "mycard1");
}});
22
Object Oriented Programming Course VKU
pnCenter.setLayout(new CardLayout());
Setup CardLayout for pnCenter
pnCenter.add(pnCard1,"mycard1");
Add pnCard1 into pnCenter with mycard1 name
CardLayout cl=(CardLayout)pnCenter.getLayout();
get CardLayout from pnCenter
cl.show(pnCenter, "mycard1");
Show component with mycard1 name, that we
define from above
23
Object Oriented Programming Course VKU
Part 3
✓ JLabel
✓ JTextField
✓ Jbutton
✓ ActionListener
Object Oriented Programming Course VKU
JLabel
• Display Text, not editable
JLabel lbl=new JLabel("Đồng hồ nè:");
lbl.setForeground(Color.RED);
25
Object Oriented Programming Course VKU
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);
26
Object Oriented Programming Course VKU
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();
27
Object Oriented Programming Course VKU
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:
28
Object Oriented Programming Course VKU
Event in component
• Event processing in component
✓ Inline anonymous listener
✓ Listener in variable
✓ Listener class
29
Object Oriented Programming Course VKU
30
Object Oriented Programming Course VKU
31
Object Oriented Programming Course VKU
Listener in variable
• Hold a reference to the Listener in a variable
➔ could share event
ActionListener btnClick=new ActionListener()
{
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "Click!");
}
};
btn1.addActionListener(btnClick);
btn2.addActionListener(btnClick);
• As the same for mouse events
32
Object Oriented Programming Course VKU
Listener class
private class MyClick implements ActionListener
{
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
btn1.addActionListener(new MyClick());
Could use class event anywhere
33
Object Oriented Programming Course VKU
Part 4
35
Object Oriented Programming Course VKU
36
Object Oriented Programming Course VKU
JTextArea, JScrollPane
JLabel lblDes=new JLabel("Mô tả:");
JTextArea are=new JTextArea(5, 15);
JScrollPane sc=new JScrollPane(are);
add(lblDes);add(sc);
37
Object Oriented Programming Course VKU
JTextArea, JScrollPane
• JScrollPane sc=new JScrollPane(are,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
38
Object Oriented Programming Course VKU
JTextArea, JScrollPane
• ImageIcon img=new ImageIcon("baby.jpg");
• JLabel lblImg=new JLabel(img);
• JScrollPane scimg=new JScrollPane(lblImg,
• JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
• JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
• scimg.setPreferredSize(new Dimension(600, 500));
• add(scimg);
39
Object Oriented Programming Course VKU
JCheckBox
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);
40
Object Oriented Programming Course VKU
JCheckBox
• 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); {
//do something
• Add pnCheck into the Window: }
• add(pnCheck);
• Create border with 2 color: Blue, Red:
• BorderFactory.createEtchedBorder(Color.BLUE,
Color.RED);
41
Object Oriented Programming Course VKU
JRadioButton- ButtonGroup
• Make single choice
• Must add JRadioButton into the ButtonGroup
if(rad1.isSelected())
{
}
•
42
Object Oriented Programming Course VKU
JRadioButton- ButtonGroup
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");
JRadioButton- ButtonGroup
Create Border with title:
Border bor=BorderFactory.createLineBorder(Color.RED);
TitledBorder titlebor=new TitledBorder
(bor, "Chọn nè:");
pnGroup.setBorder(titlebor);
44
Object Oriented Programming Course VKU
Part 5
JCombobox, JList
Object Oriented Programming Course VKU
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);
46
Object Oriented Programming Course VKU
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
47
Object Oriented Programming Course VKU
JCombobox
class Person
{
private String Id;
private String Name;
public Person(String id,String name){
Id=id;
Name=name;
}
public String toString() {
return Name;
}
}
48
Object Oriented Programming Course VKU
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);
49
Object Oriented Programming Course VKU
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);
50
Object Oriented Programming Course VKU
JList
• ListSelectionModel
• ListSelectionModel.SINGLE_SELECTION;
• ListSelectionModel.SINGLE_INTERVAL_SELECTION;
• ListSelectionModel.MULTIPLE_INTERVAL_SELECTION;
• jl.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVA
L_SELECTION)
• int n=jl.getSelectedIndex();
• int m[]=jl.getSelectedIndices();
• Object o=jl.getSelectedValue();
• Object arr[]=jl.getSelectedValues();
51
Object Oriented Programming Course VKU
Advance component
52
Object Oriented Programming Course VKU
Split Panes
53
Object Oriented Programming Course VKU
Split Panes
JSplitPane splitPane = new
JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
listScrollPane, pictureScrollPane);
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(150);
54
Object Oriented Programming Course VKU
JTable
55
Object Oriented Programming Course VKU
JTable
DefaultTableModel dm=new DefaultTableModel();
dm.addColumn("Mã");
dm.addColumn("Tên");
dm.addColumn("Tuổi");
56
Object Oriented Programming Course VKU
JTable
• How to handle event : Mouse, Key from JTable?
tbl.addMouseListener(new MouseListener() {
public void mouseReleased(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {
int row=tbl.getSelectedRow();
int col=tbl.getSelectedColumn();
String s=(String)tbl.getValueAt(row, col);
JOptionPane.showMessageDialog(null, s);
}});
57
Object Oriented Programming Course VKU
JTable
• How to handle event : Mouse, Key from JTable?
tbl.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent arg0) {}
public void keyReleased(KeyEvent arg0) {
int row=tbl.getSelectedRow();
int col=tbl.getSelectedColumn();
String s=(String)tbl.getValueAt(row, col);
JOptionPane.showMessageDialog(null, s);
}
public void keyPressed(KeyEvent arg0) {}
});
58
Object Oriented Programming Course VKU
JTable
• Clear all data from JTable
dm.setRowCount(0);
Get total row from JTable
dm.getRowCount();
• 2 Ways to add new Row:
dm.addRow(
new String[]{"ID_002","Võ Tòng","32"});
Vector<String>vec=new Vector<String>();
vec.add("ID_003");
vec.add("Lâm Sung");
vec.add("30");
dm.addRow(vec);
59
Object Oriented Programming Course VKU
JTree
• A control that displays a set of hierarchical data as an outline.
DefaultMutableTreeNode root=
new DefaultMutableTreeNode("ĐH Công Nghiệp");
final JTree tree=new JTree(root);
DefaultMutableTreeNode cnttNode=new
DefaultMutableTreeNode("Công Nghệ TT");
root.add(cnttNode);
DefaultMutableTreeNode dhth1Node=new
DefaultMutableTreeNode("Lớp ĐHTH1");
cnttNode.add(dhth1Node);
60
Object Oriented Programming Course VKU
JTree
• Handle event
tree.addMouseListener(new MouseListener() {
public void mouseReleased(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {
Object o=tree.getLastSelectedPathComponent();
DefaultMutableTreeNode
node=(DefaultMutableTreeNode)o;
JOptionPane.showMessageDialog(null, node);
}
});
61
Object Oriented Programming Course VKU
JMenuBar
JMenuBar menubar=new JMenuBar();
setJMenuBar(menubar);
JMenu mnuFile=new JMenu("File");
JMenu mnuEdit=new JMenu("Edit");
menubar.add(mnuFile);
menubar.add(mnuEdit);
JMenuItem mnuFileNew=new JMenuItem("New");
JMenuItem mnuFileOpen=new JMenuItem("Open");
JMenuItem mnuFileExit=new JMenuItem("Exit");
mnuFile.add(mnuFileNew);
mnuFile.add(mnuFileOpen);
mnuFile.addSeparator();
mnuFile.add(mnuFileExit);
62
Object Oriented Programming Course VKU
JMenuBar
• Handle event as the same JButton
mnuFileExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
63
Object Oriented Programming Course VKU
JToolBar
JToolBar toolBar=new JToolBar("MyBar");
JButton btn1=new JButton("New");
JCheckBox chk1=new JCheckBox("Checkme");
toolBar.add(btn1);
toolBar.add(chk1);
JButton btn2=new JButton("Exit");
toolBar.add(btn2);
add(toolBar,BorderLayout.NORTH);
• Handle event as the same JButton
64
Object Oriented Programming Course VKU
JTabbedPane
• JTabbedPane có giao diện đẹp mắt và thân thiện với người sử
dụng, dùng để chia màn hình sử dụng:
65
Object Oriented Programming Course VKU
JTabbedPane
JTabbedPane myTabled=new JTabbedPane();
JPanel pnTab1=new JPanel();
pnTab1.setBackground(Color.BLUE);
pnTab1.add(new JButton("Tabbed 1"));
JPanel pnTab2=new JPanel();
pnTab2.setBackground(Color.ORANGE);
pnTab2.add(new JButton("Tabbed 2"));
myTabled.add(pnTab1,"Tab1");
myTabled.add(pnTab2,"Tab2");
Container con=getContentPane();
con.add(myTabled);
66
Object Oriented Programming Course VKU
JOptionPane
JOptionPane.showMessageDialog(null,"Hello Tèo");
int ret=JOptionPane.showConfirmDialog(null,"Thoát
hả?","Thoát",JOptionPane.YES_NO_OPTION);
if(ret==JOptionPane.YES_OPTION)
{
}
String s=JOptionPane.showInputDialog("Nhập :");
67
Object Oriented Programming Course VKU
JFileChooser
JFileChooser chooser=new JFileChooser();
if(chooser.showOpenDialog(null)==
JFileChooser.APPROVE_OPTION)
{
}
if(chooser.showSaveDialog(null)==JFileChooser.APPROVE
_OPTION)
{
chooser.getSelectedFile().getAbsolutePath());
}
68
Object Oriented Programming Course VKU
JFileChooser
chooser.setFileFilter(new FileFilter() {
@Override
public String getDescription() {
return ".exe";
}
@Override
public boolean accept(File f) {
return f.getAbsolutePath().endsWith(".exe");
}
});
69
Object Oriented Programming Course VKU
JFileChooser
chooser.setFileFilter(new FileFilter() {
@Override
public String getDescription() {
return "docx,txt,xls";
}
@Override
public boolean accept(File f) {
return
f.getAbsolutePath().endsWith(".txt")||f.getAbsolutePath().endsWith(".docx")
||f.getAbsolutePath().endsWith(".xlsx");
}
});
70