Professional Documents
Culture Documents
Java 2 (SDK 1.2 v nhng phin bn cao hn) cha c Java Plug-in.Cho n nay
d java rt lu t khi java ra i n vn l ng ng ph bin ca gii lp trnh.
2.1.Jlaybel.
2.2.JButton.
2.3.JCheckBox .
2.4.JTextField.
2.5.JTextArea.
3,Cc thnh phn khc.
3.1.JCombobox.
JCombobox ging nh mt drop down box bn c th click vo mi tn
drop down v chn mt la chn t mt danh sch. N sinh ra ItemEvent.Thanh
cun dc thng c dng cho mt danh sch di.
3 | Page
Hm khi to Combobox
JComboBox()
JComboBox(ComboBoxModel)
JComboBox(Object[])
JComboBox(Vector)
3.2.JSlider.
Mt thnh phn JSlider c thit k cho php ngi dng d dng nhp
mt gi tr s gii hn bi mt gi tr ti thiu v ti a..Thanh trt ca slider c
th ty bin nm ngang hoc nm dc. V chng ta s thy cc gi tr c biu
din trn mt thanh trt nh sau
4 | Page
5 | Page
3.3JRadioButton.
Nt radio l nhm cc nt, trong , theo quy c, ch c mt nt ti mt thi
im c th c la chn.Di y l m t RadioButtonDemo.java to ra cc nt
radio trong v d trc v phn ng vi nhp chut.
JRadioButton birdButton = new JRadioButton(birdString);
birdButton.setMnemonic(KeyEvent.VK_B);
birdButton.setActionCommand(birdString);
birdButton.setSelected(true);
JRadioButton catButton = new JRadioButton(catString);
catButton.setMnemonic(KeyEvent.VK_C);
catButton.setActionCommand(catString);
JRadioButton dogButton = new JRadioButton(dogString);
dogButton.setMnemonic(KeyEvent.VK_D);
dogButton.setActionCommand(dogString);
JRadioButton rabbitButton = new JRadioButton(rabbitString);
rabbitButton.setMnemonic(KeyEvent.VK_R);
rabbitButton.setActionCommand(rabbitString);
JRadioButton pigButton = new JRadioButton(pigString);
pigButton.setMnemonic(KeyEvent.VK_P);
pigButton.setActionCommand(pigString);
//Group the radio buttons.
ButtonGroup group = new ButtonGroup();
group.add(birdButton);
group.add(catButton);
group.add(dogButton);
group.add(rabbitButton);
group.add(pigButton);
//Register a listener for the radio buttons.
birdButton.addActionListener(this);
catButton.addActionListener(this);
dogButton.addActionListener(this);
rabbitButton.addActionListener(this);
pigButton.addActionListener(this);
...
public void actionPerformed(ActionEvent e) {
picture.setIcon(new ImageIcon("images/"
+ e.getActionCommand()
+ ".gif"));
}
6 | Page
3.4.Jlist.
Mt JList hin cho ngi dng vi mt nhm sn phm, hin th trong mt
hoc nhiu ct, la chn. Danh sch c th c nhiu mt hng, do chng
thng c t trong tm di chuyn. Ngoi danh sch, cc thnh phn Swing sau
y gii thiu nhiu mt hng c th la chn cho ngi s dng: hp t hp, trnh
n, bng biu, v nhm cc hp kim tra hoc nt radio. hin th d liu phn
cp, s dng mt Tree.
3.5 JTable.
Vi lp JTable bn c th hin th bng d liu, ty chn cho php ngi dng
chnh sa d liu. JTable khng cha d liu hoc b nh cache; n ch n gin l
mt cch biu din d liu ca bn.
7 | Page
new AbstractTableModel() {
public String getColumnName(int col) {
return columnNames[col].toString();
}
public int getRowCount() { return rowData.length; }
public int getColumnCount() { return columnNames.length; }
public Object getValueAt(int row, int col) {
return rowData[row][col];
}
public boolean isCellEditable(int row, int col)
{ return true; }
public void setValueAt(Object value, int row, int col) {
rowData[row][col] = value;
fireTableCellUpdated(row, col);
}
}
9 | Page
Ex2:public
Color currentColor;
JButton button;
JColorChooser colorChooser;
JDialog dialog;
10 | P a g e
11 | P a g e
3.6 JTree.
Vi lp JTree, bn c th hin th d liu phn cp. Mt i tng JTree
khng thc s cha d liu ca bn; n ch n gin l biu din ca d liu.
Ging nh bt k thnh phn Swing , cy c d liu bng cch truy vn m hnh
d liu ca n. y l mt hnh nh ca mt cy:
Khi to mt cy th mc nh sau:
rootNode = new DefaultMutableTreeNode("Root Node");
treeModel = new DefaultTreeModel(rootNode);
treeModel.addTreeModelListener(new MyTreeModelListener());
tree = new JTree(treeModel);
tree.setEditable(true);
tree.getSelectionModel().setSelectionMode
(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.setShowsRootHandles(true);
13 | P a g e
III,Layout Manager
Layout l nhng phng thc sp xp cc component trong cc container.
thit lp layout cho container chng ta lm nh sau:
import java.awt.*;
class Fltest extends Frame
{
Button b1=new Button("Center Aligned Button 1");
Button b2=new Button("Center Aligned Button 2");
Button b3=new Button("Center Aligned Button 3");
public Fltest(String title)
{
super(title);
setLayout(new FlowLayout(FlowLayout.CENTER));
14 | P a g e
add(b1);
add(b2);
add(b3);
}
public static void main(String args[])
{
Fltest t=new Fltest("Flow Layout");
t.setSize(300,200);
t.show();
}
}
1.FlowLayout.
Cc component hin th t tri sang phi,t trn xung di bn trong
container theo ng th t c add ca chng.Khi ht mt dng s xung dng
mi tip theo.
Hnh 7:FlowLayout
2.BorderLayout.
15 | P a g e
Hnh 8:BorderLayout
3.GridbagLayout.
Cc Component c thm vo da theo ta m chng ta truyn vo.
Hnh 9:GridbagLayout
1ActionEvent- ActionListener
ActionListener c l l d nht - x l s kin thc hin - v ph bin nht.
My tnh thc hin mt hnh ng lng nghe xc nh nhng g nn c thc
hin khi ngi dng thc hin mt hot ng nht nh. By gi, khi ngi dng
nhp vo nt b, nt b n sinh ra mt s kin m hnh ng gi phng thc
17 | P a g e
void
void
void
void
void
void
windowOpened(WindowEvent e) {}
windowActivated(WindowEvent e) {}
windowIconified(WindowEvent e) {}
windowDeiconified(WindowEvent e) {}
windowDeactivated(WindowEvent e) {}
windowClosed(WindowEvent e) {}
2.ForcusEvent FocusListener
18 | P a g e
19 | P a g e
}
void displayMessage(String prefix, FocusEvent e) {
display.append(prefix
+ (e.isTemporary() ? " (temporary):" : ":")
+ e.getComponent().getClass().getName()
+ "; Opposite component: "
+ (e.getOppositeComponent() != null ?
e.getOppositeComponent().getClass().getName() : "null")
+ newline);
}
...
}
3.ItemEvent ItemListener
Nhn chung y l s kin lien quan n cc mc c chn nh
checkbox,Checkmenu Item,comboboxsau y l demo v itemEvent
ItemListener
//where initialization occurs
checkbox.addItemListener(this);
...
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
label.setVisible(true);
...
} else {
label.setVisible(false);
}
}
4.WindowEvent WindowListener
y l cc loi s kin lien quan n ca s(Hp thoi).y l demo v
WindowEvent WindowListener
public class WindowEventDemo extends JFrame implements WindowListener,
WindowFocusListener,
WindowStateListener {
...
static WindowEventDemo frame = new WindowEventDemo("WindowEventDemo");
JTextArea display;
...
private void addComponentsToPane() {
20 | P a g e
21 | P a g e
22 | P a g e
displayStateMessage(
"WindowStateListener method called: windowStateChanged.", e);
}
void displayMessage(String msg) {
display.append(msg + newline);
System.out.println(msg);
}
void displayStateMessage(String prefix, WindowEvent e) {
int state = e.getNewState();
int oldState = e.getOldState();
String msg = prefix
+ newline + space
+ "New state: "
+ convertStateToString(state)
+ newline + space
+ "Old state: "
+ convertStateToString(oldState);
displayMessage(msg);
}
String convertStateToString(int state) {
if (state == Frame.NORMAL) {
return "NORMAL";
}
String strState = " ";
if ((state & Frame.ICONIFIED) != 0) {
strState += "ICONIFIED";
}
//MAXIMIZED_BOTH is a concatenation of two bits, so
//we need to test for an exact match.
if ((state & Frame.MAXIMIZED_BOTH) == Frame.MAXIMIZED_BOTH) {
strState += "MAXIMIZED_BOTH";
} else {
if ((state & Frame.MAXIMIZED_VERT) != 0) {
strState += "MAXIMIZED_VERT";
}
if ((state & Frame.MAXIMIZED_HORIZ) != 0) {
strState += "MAXIMIZED_HORIZ";
}
if (" ".equals(strState)){
strState = "UNKNOWN";
}
}
return strState.trim();
}
}
23 | P a g e
5.MouseEvent MouseListener
S kin chut thng bo khi ngi dng s dng chut (hoc thit b u vo
tng t) tng tc vi mt thnh phn. S kin chut xy ra khi con tr i vo
hoc thot ra khi khu vc trn mn hnh v khi ngi dng nhn phm mt trong
cc nt chut.Demo ca MouseEvent:
public class MouseEventDemo ... implements MouseListener {
//where initialization occurs:
//Register for mouse events on blankArea and the panel.
blankArea.addMouseListener(this);
addMouseListener(this);
...
public void mousePressed(MouseEvent e) {
saySomething("Mouse pressed; # of clicks: "
+ e.getClickCount(), e);
}
public void mouseReleased(MouseEvent e) {
saySomething("Mouse released; # of clicks: "
+ e.getClickCount(), e);
}
public void mouseEntered(MouseEvent e) {
saySomething("Mouse entered", e);
}
public void mouseExited(MouseEvent e) {
saySomething("Mouse exited", e);
}
public void mouseClicked(MouseEvent e) {
saySomething("Mouse clicked (# of clicks: "
+ e.getClickCount() + ")", e);
}
void saySomething(String eventDescription, MouseEvent e) {
textArea.append(eventDescription + " detected on "
+ e.getComponent().getClass().getName()
+ "." + newline);
}
}
6.KeyEvent KeyListener
24 | P a g e
25 | P a g e
26 | P a g e
private int c;
public PTB2Engine(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
public String compute() {
String kq = "";
if (this.a == 0) {
if (this.b == 0) {
if (this.c == 0) {
kq = "vo so nghien";
} else {
kq = "vo nghiem";
}
} else {
kq = "Pt co 1 no x1=" + (-this.c / this.b);
}
} else {
double delta = this.b * this.b - 4 * this.a * this.c;
if (delta < 0) {
kq = "V nghim";
} else if (delta == 0) {
kq = "No kp x1=x2=" + (-this.b / (2 * this.a));
} else {
kq = "x1 = " + ((-this.b - Math.sqrt(delta)) / (2 * this.a));
kq += "
}
}
return kq;
}
}
Class2:
27 | P a g e
btnThoat.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int ret = JOptionPane.showConfirmDialog(null, "Mun thot?", "Thot",
JOptionPane.YES_NO_OPTION);
if (ret == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
});
btnXoa.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
txtb.setText("");
txtc.setText("");
txtkq.setText("");
txta.requestFocus();
}
});
btnGiai.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String sa = txta.getText();
int a = 0, b = 0, c = 0;
try {
a = Integer.parseInt(sa);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Nhp sai nh dng!");
txta.selectAll();
txta.requestFocus();
return;
}
String sb = txtb.getText();
try {
b = Integer.parseInt(sb);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Nhp sai nh dng!")
28 | P a g e
txtb.selectAll();
txtb.requestFocus();
return;
Kt qu nh sau:
29 | P a g e