Bài giảng Lập trình Java 3 - Bài 2: Các thành phần GUI cơ bản
JComponent
JComponent là lớp cơ sở abstract của tất cả các Swing
components (có tên bắt đầu chữ J - ngoại trừ topcontainer)
Kế thừa từ Component và Container
Đóng gói hầu hết các đặc điểm và thao tác cơ bản của 1
thành phần GUI
Lớp JComponent
• Cảm quan khả kiến (Pluggable)
• Phím tắt (tính dễ nhớ)
• Khả năng xử lý sự kiện chungJComponent
Bao gồm:
JButton, JList, JLabel, JTextField,JTextArea
JComboBox, JRadioButton,
JCheckBox extend functionality existing in AWT
Components.
JProgressBar, JSlider, JTable, JToolBar, JTree provide new
components.
JInternalFrame, JScrollPane,
JSplitPane, JTabbedPane provide new ways to combine
components.
Bạn đang xem 20 trang mẫu của tài liệu "Bài giảng Lập trình Java 3 - Bài 2: Các thành phần GUI cơ bản", để tải tài liệu gốc về máy hãy click vào nút Download ở trên
Tóm tắt nội dung tài liệu: Bài giảng Lập trình Java 3 - Bài 2: Các thành phần GUI cơ bản
Bài 2:
Các thành phần GUI cơ bản
SOF203 - Lập trình Java 3
Bài 2 : Các thành phần GUI cơ bản
Mục tiêu bài học
Phương thức chung của các component trong SWING
Một số Swing component (JTextfield, JLabel,JButton,
JCheckBox, JRadioButton,JTextArea, JPasswordField)
Modal và Non – Modal Dialog
Custom Dialog
JComponent
JComponent là lớp cơ sở abstract của tất cả các Swing
components (có tên bắt đầu chữ J - ngoại trừ top-
container)
Kế thừa từ Component và Container
Đóng gói hầu hết các đặc điểm và thao tác cơ bản của 1
thành phần GUI
Lớp JComponent
• Cảm quan khả kiến (Pluggable)
• Phím tắt (tính dễ nhớ)
• Khả năng xử lý sự kiện chung
JComponent
Bao gồm:
JButton, JList, JLabel, JTextField,JTextArea
JComboBox, JRadioButton,
JCheckBox extend functionality existing in AWT
Components.
JProgressBar, JSlider, JTable, JToolBar, JTree provide new
components.
JInternalFrame, JScrollPane,
JSplitPane, JTabbedPane provide new ways to combine
components.
JComponent
Property Data type get is set
Default value (if applicable)
Background Color
colorModel ColorModel
component' Component
componentCount int
Components Component[]
Cursor Cursor Cursor.DEFAULT CURSOR
Enabled boolean true
Font Font
Foreground Color
insets Insets Insets(0,0, 0, 0)
layout LayoutManager BorderLayout( )
locale Locale
location Point
locationOnScreen Point
name String ""
parent Container null
size Dimension
showing boolean true
valid boolean
visible boolean true
'indexed
JTextField
Để hiển thị dữ liệu, nhập dữ liệu
Khởi tạo
JTextField(): text field trống
JTextField(int): A text field with the specified width
JTextField(String): A text field with text
JTextField(String, int): A text field with the specified text and
width
JTextField(int cols): khởi tạo JtextField với số cột quy định.
JTextField(String text, int cols): khởi tạo JTextField với
dòng text và số cột quy định.
JTextField
Ví dụ:
JTextField textField = new JTextField(20);
Và sau đó setText():
textField.setText("Hello!");
JTextField
Methods:
-void setText(String t) set Text in code behind for
JTextField
-String getText()
• String s = txtHoten.getText();
• void setEditable(boolean b): chỉnh sửa nội dung
• setColumns()
• strim(): bỏ đi khoảng trắng đầu và cuối chuỗi
• setFont
• textField.setFont(new Font("Arial", Font.BOLD,12));
• requestFocus();
Events:
• –caretUpdate
AWT
Giới thiệu chung
Thư viện API cung cấp các đối tượng GUI
Tạo liên kết giao diện giữa ứng dụng Java và OS
Chiếm nhiều tài nguyên hệ thống(Heavy-weight component)
Package java.awt
Gồm nhiều phần tử (class) để tạo GUI.
Có các lớp quản lý việc bố trí các phần tử.
Có (event-oriented application) mô hình ứng dụng hướng sự kiện.
Có các công cụ xử lý đồ họa và hình ảnh.
Các lớp sử dụng các tác vụ với clipboard (vùng nhớ đệm) như cut,
paste.
(Abstract Windows Toolkit)
JLabel
JLabel thường được dùng để hiển thị text hoặc hình ảnh để
tạo các chỉ dẫn, hướng dẫn trên giao diện người dùng.
Khai báo:
Label() : An empty label
JLabel(String) : A label with the specified text
JLabel(String, int) : A label with the specified text and
alignment LEFT, CENTER, and RIGHT.
JLabel(String, Icon, int) : A label with the specified text, icon,
and Alignment
JLabel
Methods:
• void setFont (Font f)
• void setText(String S) quy định chuỗi văn bản.
• String getText()
• void setIcon(Icon) quy định Icon
• getLength(): đưa ra chiều dài của chuỗi text.
Events:
mouseClicked
JLabel
Example:
• JLabel lbl=new JLabel("Họ và tên:");
• JLabel lbl=new JLabel("Ngày sinh:");
Sử dụng HTML để tạo ra các JLabel nhiều dòng, nhiều
định dạng
JButton
là một đối tượng mà cho phép chúng ta khi click chuột
vào sẽ thực hiện một việc gì đó
Khai báo
• JButton() Creates a button with no set text or icon.
• JButton(Action a) Creates a button where properties
are taken from the Action supplied.
• JButton(Icon icon) Creates a button with an icon.
• JButton(String text) Creates a button with text.
• JButton(String text, Icon icon) Creates a button with
initial text and an icon.
JButton
Methods:
• setText (String text)
• getText ()
• setForeground (Color fg)
• setFocusCycleRoot (boolean b)
Events
• actionPerformed
• mousePressed
JButton
Các cách tạo và bắt sự kiện JButton
JButton bt=new JButton("Watch");
bt.setIcon(new ImageIcon("mywatch.png"));
bt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
//do something here
}
});
JButton
Ví dụ
JCheckBox
là đối tượng cho phép chúng ta chọn nhiều thuộc tính.
Ví dụ như khi điền thông tin một người xem có tiền, có nhà, có xe hơi
không chẳng hạn. Người đó có thể có cả 3 hoặc không có một cái nào cả
Khai báo
• JCheckBox() Creates an initially unselected check box button with no
text, no icon.
• JCheckBox(Action a) Creates a check box where properties are taken
from the Action supplied.
• JCheckBox(Icon icon) Creates an initially unselected check box with an
icon.
• JCheckBox(Icon icon, boolean selected) Creates a check box with an icon
and specifies whether or not it is initially selected.
• JCheckBox(String text) Creates an initially unselected check box with text.
• JCheckBox(String text, boolean selected)
• JCheckBox(String text, Icon icon)
• JCheckBox(String text, Icon icon, boolean selected)
JCheckBox
Methods:
• –setSelected (boolean b)
• –isSelected ()
• –setText (String text)
• –getText ()
Events:
–actionPerformed
JCheckBox
Ví dụ:
panelCheck=new JPanel();
panelCheck.setLayout(new GridLayout(2, 2));
JCheckBox chk1=new JCheckBox("C/C++");
JCheckBox chk2=new JCheckBox("C#");
JCheckBox chk3=new JCheckBox("PHP");
JCheckBox chk4=new JCheckBox("Java");
panelCheck.add(chk1);
panelCheck.add(chk2);
panelCheck.add(chk3);
panelCheck.add(chk4);
JCheckBox
JRadioButton
là một đối tượng cho phép chúng ta chọn lựa các thuộc tính giốn như
JCheckBox. Tuy nhiên chúng ta hay sử dụng JRadioButton khi mà muốn
người dùng chỉ chọn được một trong các thuộc tính.
Ví dụ chọn giới tính thì người dùng chỉ được chọn là Nam hoặc Nữ.
Khai báo
• JRadioButton() Creates an initially unselected radio button with no set
text.
• JRadioButton(Action a) Creates a radiobutton where properties are
taken from the Action supplied.
• JRadioButton(Icon icon) Creates an initially unselected radio button
with the specified image but no text.
• JRadioButton(Icon icon, boolean selected) Creates a radio button with
the specified image and selection state, but no text.
• JRadioButton(String text) Creates an unselected radio button with the
specified text.
• JRadioButton(String text, boolean selected)
• JRadioButton(String text, Icon icon) Creates a radio button that has
the specified text and image, and that is initially unselected.
• JRadioButton(String text, Icon icon, boolean selected)
Must add JRadioButton into the ButtonGroup
JRadioButton
Methods:
• setSelected (boolean b)
• isSelected ()
• setText (String text)
• getText ()
Events:
• actionPerformed
JRadioButton
Ví dụ:
JPanel panelGroup=new JPanel();
panelGroup.setBorder(new TitledBorder("Ý kiến của bạn:"));
JRadioButton rad1=new JRadioButton("Lập trình Java rất dễ");
JRadioButton rad2=new JRadioButton("Design GUI Java rất dễ");
JRadioButton rad3=new JRadioButton("Viết web trên Java rất dễ");
JRadioButton rad4=new JRadioButton("Tất cả đều khó");
ButtonGroup group=new ButtonGroup();
group.add(rad1);
group.add(rad2);
group.add(rad3);
group.add(rad4);
panelGroup.add(rad1);
panelGroup.add(rad2);
panelGroup.add(rad3);
panelGroup.add(rad4);
add(panelGroup);
JRadioButton
JTextArea
là một thành phần cho phép hiển thị nhiều dòng văn bản
đồng thời người dùng có thể chỉnh sửa văn bản
Khai báo
JTextArea(): Create a default text area.
JTextArea(int rows, int columns): Create a text area with
the specified number of rows and columns.
JTextArea(String text)
JTextArea(String text, int rows, int columns)
JTextArea(Document doc): Create a text area that uses
the specified Document.
JTextArea(Document doc, String text, int rows, int
columns)
JTextArea
Methods
setWrapStyleWord(true);
setLineWrap(true);
setText("");
setFont(font);
setForeground(Color.BLUE);
void append(String str)
Append the given text to the end of the document.
void insert(String str, int pos)
Insert the specified text at the given position . To insert
text at the beginning of the document, use a position of
0.
JTextArea
void replaceRange(String str, int start, int end)
Replace a section of the document
public int getLineStartOffset(int line) throws BadLocationException
Return the character offset (from the beginning) that marks the
beginning of the specified line number.
public int getLineEndOffset(int line) throws BadLocationException
Return the character offset (from the beginning) that marks the end
of the specified line number. This is actually the offset of the first
character of the next line.
public int getLineOfOffset(int offset) throws BadLocationException
Return the line number that contains the given character offset
(from the beginning of the document).
- Kết hợp với thanh cuộn:
textArea = new JTextArea(8, 40);
JScrollPane scrollPane = new JScrollPane(textArea);
JTextArea
Ví dụ
JPanel contentPane = new JPanel();
JLabel lblNewLabel = new JLabel("Nhập dữ liệu:");
contentPane.add(lblNewLabel);
JTextArea textArea = new JTextArea(3,15);
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
JScrollPane scrollPane = new JScrollPane(textArea);
contentPane.add(scrollPane);
JTextArea class MyJTextArea extends JFrame {
private JPanel contentPane;
public MyJTextArea() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 257, 128);
contentPane = new JPanel();
JTextArea
Ví dụ
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JLabel lblNewLabel = new JLabel("Nhập dữ liệu:");
contentPane.add(lblNewLabel);
JScrollPane scrollPane = new JScrollPane();
JTextArea textArea = new JTextArea(3,15);
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
scrollPane.setViewportView(textArea);
contentPane.add(scrollPane);
}
JTextArea
JPasswordField
là đối tượng cho phép chúng ta nhập vào một dòng text giống
như JTextField nhưng được ẩn bởi các dấu sao (*) hoặc chấm tròn
để tạo nên mật khẩu (password)
JPasswordField class, a subclass of JTextField.
JPasswordField constructor methods take the same arguments as
those of its parent class.
Khởi tạo
• JPasswordField(): Khởi tạo JPasswordField không có text và độ
rộng là 0 cột
• JPasswordField(int columns): Khởi tạo JPasswordField không có
text và độ rộng là columns cột
• JPasswordField(String text): Khởi tạo JPasswordField vớit text ban
đầu
• JPasswordField(String text, int columns): Khởi tạo JPasswordField
vớit text ban đầu và rộng columns cột
JPasswordField
Methods
JPasswordField(String text, int columns)
char[] getPassword(): returns the text contained in this
password field JPasswordField setEchoChar(char):
replacing each input character with the specified
character
JPasswordField pass = new JPasswordField(20);
pass.setEchoChar('#');
JDialog
Hộp thoại thường là cửa sổ phụ trình bày danh sách tùy chọn hoặc hiển thị thông
điệp
Hộp thoại thường cung cấp nút xác nhận thay đổi hoặc trường nhập vào thành
phần, hủy bỏ thay đổi...
Có 3 dạng hộp thoại:
Hộp thoại thông điệp
Hộp thoại xác nhận
Hộp thoại tập tin (JFileChooser)
JDialog có 2 trạng thái
• Modal: Khi Jdialog thực hiện xong mới được phép thao tác lên form cha .
• Modeless: Sau khi hiển thị dialog, người dùng có thể thao tác lên form cha
JDialog thường được sử dụng với trạng thái Modal
Khởi tạo
public JDialog()
public JDialog(Dialog owner, String title, boolean modal, GraphicsConfiguration gc)
public JDialog(Frame owner, String title, boolean modal, GraphicsConfiguration gc)
JDialog
Ví dụ:
JOptionPane.showMessageDialog(this,”Chào quí vị”);
JDialog
Ví dụ 2:
int choice=JOptionPane.showConfirmDialog(this,”Bạn có
người yêu chưa?”);
If(JOptionPane.YES_OPTION==choice) {
//do something
}
else if(JOptionPane.NO_OPTION=choice){
//do something
}
else{
}
JDialog
Ví dụ 3
String input =JOptionPane.showInputDialog(this,”Vui lòng
nhập họ và tên của bạn”);
JDialog
Property Data type get is set Default value
acce3SibleContext°
AccessibleCont
ext
JDialog.AccessibleJDialog(
)
contentPane0 Container From rootPane
defaultCloseOperation int HIDE_ON_CLOSE
defaultLookAndFeelDecorateds' 1-4 boolean Depends on L&.F, often false
glassPane® Component From rootPane
JMenuBar° JMenuSar null
layeredPane0 JLayeredPane From rootPane
layout0 LayoutManager BorderLayout
modal* boolean false
parent* Container
SwingUtilities.get-
SharedOwnerFrame( )
rootPane JRootPane JRootPane
title* String n n
Methods
Dialog tùy biến
public class LoginJDialog extends javax.swing.Jdialog{
}
LogginJDialog dialog=new LoginJDialog()
dialog.setDefaultCloseOperation(Jdialog.DIPOSE_ON_CLOS
E);
dialog.setTitle(“Đăng nhâp”);
dialog.setAlwaysOnTop(true);
dialog.setIconImage(new
ImageIcon(getClass().getResource(“/icons/Login.png”)).getI
mage()
Dialog tùy biến
XIN CẢM ƠN!
SOF203 - Lập trình Java 3
Bài 2 : Các thành phần GUI cơ bản
File đính kèm:
bai_giang_lap_trinh_java_3_bai_2_cac_thanh_phan_gui_co_ban.pdf

