You are on page 1of 29

I,Tng quan v Swing.

Nu bn tng vo trang ch ca Java (http://oracle.com/java), bn s


nhn thy Swing c m t nh l mt tp cc thnh phn ha c to ra
nhng cm quan (Look&Feel) c th hin vo thi im runtime.
Tht s, th Swing cn nhiu hn nh th. Swing l b cng c GUI th h k tip
m Sun Microsystems to ra cho php mi trng pht trin enterprise trong
Java.Bng mi trng pht trin enterprise, chng ta hiu rng, cc lp trnh vin
c th s dng Swing to ra cc ng dng Java c kh nng m rng vi mt
dy nhiu thnh phn mnh m. Thm vo , bn c th k tha hoc chnh sa
nhng thnh phn ny iu khin vic hin th v cc hnh x ca chng.
Swing khng phi l mt t vit tt. l tn thay th cho mt tp hp la
chn ca n cho cc designer khi d n c thc hin vo 1996. Swing tht s l
mt phn ca gia nh rng ln cc sn phm ca Java c bit n nh Java
Foundation Classes s(JFC) bao gm nhiu c im ca Internet Foundation
Classes ca Netscape cng nh b nh hng thit k ca Taligent v Lighthouse
Design ca IBM. Swing c pht trin tht s k t thi im bn beta ca JDK
1.1, khong ma xun 1997. Swing API bn beta a ra khong na cui 1997 v
c chnh thc pht hnh vo thng 3 nm 1998. Khi c pht hnh, cc th
vin ca Swing 1.0 cha khong 250 lp v 80 giao tip. S pht trin c tip
tc khi theo thi gian, bn Swing 1.4 cha 85 giao tip public v 451 lp
public.Mc d Swing l c pht trin n l t li ca Java Development Kit, n
yu cu phi c ti thiu JDK 1.1.5 chy. Swing c xy dng da trn nhng
m hnh event c gii thiu trong serie JDK 1.1. Bn khng th s dng Swing
vi JDK 1.0.2, thm vo bn phi c Java 1.1 cho php trnh duyt h tr Swing
Applet. Java 2 SDK 1.4 c pht hnh bao gm nhiu lp Swing c cp nht
v h tr mt vi c im mi. Swing c tch hp y trong c trong b
cng c ca cc nh pht trin v runtime environment ca tt c cc bn pht hnh
1 | Page

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.

Hnh 1:Giao din swing n gin

II,Cc thnh phn giao tip c bn ca swing.


1,Cc container .
1.1.Jframe.
JFrame l mt Top-level Container thng c s dng to cc giao din
ng dng ngi dng.N thng c dng cha cc thnh phn giao din khc
( Button, Label, ).
1.2.JPanel.
JPanel l mt container (thng cha) n dng cha cc i tng tng t
nh JFrame tuy nhin n khng phi l 1 JFrame.
2,Cc Components.
2 | Page

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.

Hnh 2:Demo Combobox

Khai bo ComboBox nh sau:

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

Hnh 3:Demo Jslider

Khai bo JSlider nh sau:


public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider)e.getSource();
if (!source.getValueIsAdjusting()) {
int fps = (int)source.getValue();
if (fps == 0) {
if (!frozen) stopAnimation();
} else {
delay = 1000 / fps;
timer.setDelay(delay);
timer.setInitialDelay(delay * 10);
if (frozen) startAnimation();
}
}
}

Hm khi to (contructor) ca Jslider:


JSlider()
JSlider(int min, int max)
JSlider(int orientation)
JSlider(BoundedRangeModel)

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.

Hnh 4:Demo Jlist

Demo khai bo Jlist


list = new JList(data); //data has type Object[]
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
list.setVisibleRowCount(-1);
...
JScrollPane listScroller = new JScrollPane(list);
listScroller.setPreferredSize(new Dimension(250, 80));

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

Hnh 5:Demo Jtable

Theo mc nh, tt c cc ct trong mt bng bt u vi chiu rng bng


nhau, v cc ct t ng in vo ton b chiu rng ca bng. Khi bng tr nn
rng hn hoc hp hn (c th xy ra khi ngi dng thay i kch thc ca s
cha bng), tt c cc rng ct thay i thch hp. Khi ngi dng thay i kch
thc mt ct bng cch ko bin phi ca mnh, sau mt trong hai ct khc
phi thay i kch thc, hoc kch thc ca bng phi thay i. Theo mc nh,
kch thc ca bng vn gi nguyn, v tt c cc ct bn phi ca im ko thay
i kch thc ph hp khng gian thm vo hoc g b t ct bn tri ca im
ko. ty chnh rng ct ban u, bn c th gi setPreferredWidth trn mi
ct ca bng ca bn. iu ny t ra c chiu rng a thch ca cc ct v chiu
rng tng i gn ng ca h. V d, thm on m sau vo SimpleTableDemo
lm cho ct th ba ca n ln hn cc ct khc:
TableColumn column = null;
for (int i = 0; i < 5; i++) {
column = table.getColumnModel().getColumn(i);
if (i == 2) {
column.setPreferredWidth(100); //third column is bigger
} else {
column.setPreferredWidth(50);
}
}

to mt bng mu trong Swing ta lm nh sau.


8 | 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);
}
}

Lp s kin ca Jtable l TablemoderListener chng ta hy theo di demo sau


y
import javax.swing.event.*;
import javax.swing.table.TableModel;
public class SimpleTableDemo ... implements TableModelListener {
...
public SimpleTableDemo() {
...
table.getModel().addTableModelListener(this);
...
}
public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
int column = e.getColumn();
TableModel model = (TableModel)e.getSource();
String columnName = model.getColumnName(column);

9 | Page

Object data = model.getValueAt(row, column);


...// Do something with the data...
}
...
}

Chng ta c th to mt bng trong kt hp gia Jtable vi combobox hay


vi cc thnh phn khc c trnh by phn trc.Hy cng nhau xem xt cc v
d sau:
Ex1:
TableColumn sportColumn = table.getColumnModel().getColumn(2);
...
JComboBox comboBox = new JComboBox();
comboBox.addItem("Snowboarding");
comboBox.addItem("Rowing");
comboBox.addItem("Chasing toddlers");
comboBox.addItem("Speed reading");
comboBox.addItem("Teaching high school");
comboBox.addItem("None");
sportColumn.setCellEditor(new DefaultCellEditor(comboBox));

Ex2:public

class ColorEditor extends AbstractCellEditor


implements TableCellEditor,
ActionListener {

Color currentColor;
JButton button;
JColorChooser colorChooser;
JDialog dialog;

10 | P a g e

protected static final String EDIT = "edit";


public ColorEditor() {
button = new JButton();
button.setActionCommand(EDIT);
button.addActionListener(this);
button.setBorderPainted(false);
//Set up the dialog that the button brings up.
colorChooser = new JColorChooser();
dialog = JColorChooser.createDialog(button,
"Pick a Color",
true, //modal
colorChooser,
this, //OK button handler
null); //no CANCEL button handler
}
public void actionPerformed(ActionEvent e) {
if (EDIT.equals(e.getActionCommand())) {
//The user has clicked the cell, so
//bring up the dialog.
button.setBackground(currentColor);
colorChooser.setColor(currentColor);
dialog.setVisible(true);
fireEditingStopped(); //Make the renderer reappear.
} else { //User pressed dialog's "OK" button.
currentColor = colorChooser.getColor();
}
}

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:

Hnh 6:M hnh Tree

JTree hin th d liu theo chiu dc. Mi hng hin th bi cc cy cha


chnh xc mt mc d liu, c gi l mt nt(Node). Mi cy c mt nt gc m
t tt c cc nt i xung. Theo mc nh, cy hin th cc nt gc, nhng bn
12 | P a g e

c th ch nh nt khc. Mt nt c th hoc c con hay khng.Chng ta cng


nhau xem qua on demo v Tree sau:
private JTree tree;
...
public TreeDemo() {
...
DefaultMutableTreeNode top =
new DefaultMutableTreeNode("The Java Series");
createNodes(top);
tree = new JTree(top);
...
JScrollPane treeView = new JScrollPane(tree);
...
}

Code ny to mt mt nt gc cho cy.Sau n to ra cc nt cn li ca


cy,cc nt gc c xc nh bng tham s,cui cng n t cy trong mt ca
s,chng ta c th click x ra cc th mc t cy.Cy c biu din trong cc
h iu hnh c th khc nhau v ha nhng bn cht n khng c g thay i.

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

Nu DefaultTreeModel khng ph hp vi nhu cu ca bn, bn s cn phi


vit mt m hnh d liu ty chnh. M hnh d liu ca bn phi thc hin giao
din TreeModel. TreeModel quy nh c th phng php c c mt nt c
th ca cy, nhn c s lng con chu ca mt nt c th, xc nh mt nt l
mt chic l, thng bo cho cc m hnh ca mt s thay i trong cy, v thm v
loi b cc m hnh gi hoc c trong cy. Tht th v, giao din TreeModel chp
nhn bt k loi i tng nh l mt nt cy. N khng i hi rng cc nt c
biu din bi cc i tng DefaultMutableTreeNode, hoc thm ch l cc nt
thc hin giao din TreeNode. V d, nu bn c mt cu trc d liu phn cp t
trc, bn khng cn phi lp li n hay buc n vo khun TreeNode. Bn ch cn
thc hin m hnh cy ca bn n s dng cc thng tin trong cu trc d liu
hin c.

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

Container c chia lm 5 vng theo cc hng:ng,ty,nam,bc,trung tm.

Hnh 8:BorderLayout

3.GridbagLayout.
Cc Component c thm vo da theo ta m chng ta truyn vo.

Hnh 9:GridbagLayout

IV,X l s kin trong Swing.


S kin l s tng tc ca ngi dng v phn mm phi c s phn hi
li,s tng tc c th l mt c click chut,nhn phm,chn trong danh sch.Khi
bt s kin phi ch ra y l s kin no v ca ci g.
Mt s x l s kin n gin.
16 | P a g e

Ex1:s kin ca cc nut bm


public class MultiListener ... implements ActionListener {
...
//where initialization occurs:
button1.addActionListener(this);
button2.addActionListener(this);
button2.addActionListener(new Eavesdropper(bottomTextArea));
}
public void actionPerformed(ActionEvent e) {
topTextArea.append(e.getActionCommand() + newline);
}
}
class Eavesdropper implements ActionListener {
...
public void actionPerformed(ActionEvent e) {
myTextArea.append(e.getActionCommand() + newline);
}
}

Cc s kin v listener tng ng:

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

actionPerformed. Mi khi ngi dng nhn nt,hnh ng ny s c bt bi


ActionListener.V d:
import java.awt.*;
import java.awt.event.*;
public class AL extends Frame implements WindowListener,ActionListener {
TextField text = new TextField(20);
Button b;
private int numClicks = 0;
public static void main(String[] args) {
AL myWindow = new AL("My first window");
myWindow.setSize(350,100);
myWindow.setVisible(true);
}
public AL(String title) {
super(title);
setLayout(new FlowLayout());
addWindowListener(this);
b = new Button("Click me");
add(b);
add(text);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
numClicks++;
text.setText("Button Clicked " + numClicks + " times");
}
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
public
public
public
public
public
public

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

y l s kin khi chut hay phm cn tp trung vo mt im no lc ny


s my tnh s gi n phng thc FocusListener tp trung cho mt giao din
duy nht.V d khi bn cn ng k ti khon con tr chut lun nhy ng k
u tin,ng khng?Sau y l Demo ca FocusListener:
public class FocusEventDemo ... implements FocusListener ... {
public FocusEventDemo() {
...
JTextField textField = new JTextField("A TextField");
textField.addFocusListener(this);
...
JLabel label = new JLabel("A Label");
label.addFocusListener(this);
...
JComboBox comboBox = new JComboBox(vector);
comboBox.addFocusListener(this);
...
JButton button = new JButton("A Button");
button.addFocusListener(this);
...
JList list = new JList(listVector);
list.setSelectedIndex(1); //It's easier to see the focus change
//if an item is selected.
list.addFocusListener(this);
JScrollPane listScrollPane = new JScrollPane(list);
...
//Set up the area that reports focus-gained and focus-lost events.
display = new JTextArea();
display.setEditable(false);
//The method setRequestFocusEnabled prevents a
//component from being clickable, but it can still
//get the focus through the keyboard - this ensures
//user accessibility.
display.setRequestFocusEnabled(false);
display.addFocusListener(this);
JScrollPane displayScrollPane = new JScrollPane(display);
...
}
...
public void focusGained(FocusEvent e) {
displayMessage("Focus gained", e);
}
public void focusLost(FocusEvent e) {
displayMessage("Focus lost", 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

display = new JTextArea();


display.setEditable(false);
JScrollPane scrollPane = new JScrollPane(display);
scrollPane.setPreferredSize(new Dimension(500, 450));
getContentPane().add(scrollPane, BorderLayout.CENTER);
addWindowListener(this);
addWindowFocusListener(this);
addWindowStateListener(this);
checkWM();
}
public WindowEventDemo(String name) {
super(name);
}
//Some window managers don't support all window states.
public void checkWM() {
Toolkit tk = frame.getToolkit();
if (!(tk.isFrameStateSupported(Frame.ICONIFIED))) {
displayMessage(
"Your window manager doesn't support ICONIFIED.");
} else displayMessage(
"Your window manager supports ICONIFIED.");
if (!(tk.isFrameStateSupported(Frame.MAXIMIZED_VERT))) {
displayMessage(
"Your window manager doesn't support MAXIMIZED_VERT.");
} else displayMessage(
"Your window manager supports MAXIMIZED_VERT.");
if (!(tk.isFrameStateSupported(Frame.MAXIMIZED_HORIZ))) {
displayMessage(
"Your window manager doesn't support MAXIMIZED_HORIZ.");
} else displayMessage(
"Your window manager supports MAXIMIZED_HORIZ.");
if (!(tk.isFrameStateSupported(Frame.MAXIMIZED_BOTH))) {
displayMessage(
"Your window manager doesn't support MAXIMIZED_BOTH.");
} else {
displayMessage(
"Your window manager supports MAXIMIZED_BOTH.");
}
}
public void windowClosing(WindowEvent e) {
displayMessage("WindowListener method called: windowClosing.");
//A pause so user can see the message before
//the window actually closes.

21 | P a g e

ActionListener task = new ActionListener() {


boolean alreadyDisposed = false;
public void actionPerformed(ActionEvent e) {
if (frame.isDisplayable()) {
alreadyDisposed = true;
frame.dispose();
}
}
};
Timer timer = new Timer(500, task); //fire every half second
timer.setInitialDelay(2000);
//first delay 2 seconds
timer.setRepeats(false);
timer.start();
}
public void windowClosed(WindowEvent e) {
//This will only be seen on standard output.
displayMessage("WindowListener method called: windowClosed.");
}
public void windowOpened(WindowEvent e) {
displayMessage("WindowListener method called: windowOpened.");
}
public void windowIconified(WindowEvent e) {
displayMessage("WindowListener method called: windowIconified.");
}
public void windowDeiconified(WindowEvent e) {
displayMessage("WindowListener method called: windowDeiconified.");
}
public void windowActivated(WindowEvent e) {
displayMessage("WindowListener method called: windowActivated.");
}
public void windowDeactivated(WindowEvent e) {
displayMessage("WindowListener method called: windowDeactivated.");
}
public void windowGainedFocus(WindowEvent e) {
displayMessage("WindowFocusListener method called: windowGainedFocus.");
}
public void windowLostFocus(WindowEvent e) {
displayMessage("WindowFocusListener method called: windowLostFocus.");
}
public void windowStateChanged(WindowEvent 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

S kin ny cho thy khi ngi dng g vo bn phm. C th, s kin ny


c bn bi cc thnh phn vi trng tm l bn phm khi ngi dng nhn phm
bn phm.S pht sinh ra hm Keylistener ca my tnh bt s kin ny.V d:
public class KeyEventDemo ... implements KeyListener ... {
...//where initialization occurs:
typingArea = new JTextField(20);
typingArea.addKeyListener(this);
//Uncomment this if you wish to turn off focus
//traversal. The focus subsystem consumes
//focus traversal keys, such as Tab and Shift Tab.
//If you uncomment the following line of code, this
//disables focus traversal and the Tab events
//become available to the key event listener.
//typingArea.setFocusTraversalKeysEnabled(false);
...
/** Handle the key typed event from the text field. */
public void keyTyped(KeyEvent e) {
displayInfo(e, "KEY TYPED: ");
}
/** Handle the key-pressed event from the text field. */
public void keyPressed(KeyEvent e) {
displayInfo(e, "KEY PRESSED: ");
}
/** Handle the key-released event from the text field. */
public void keyReleased(KeyEvent e) {
displayInfo(e, "KEY RELEASED: ");
}
...
private void displayInfo(KeyEvent e, String keyStatus){
//You should only rely on the key char if the event
//is a key typed event.
int id = e.getID();
String keyString;
if (id == KeyEvent.KEY_TYPED) {
char c = e.getKeyChar();
keyString = "key character = '" + c + "'";
} else {
int keyCode = e.getKeyCode();
keyString = "key code = " + keyCode
+ " ("
+ KeyEvent.getKeyText(keyCode)
+ ")";
}

25 | P a g e

int modifiersEx = e.getModifiersEx();


String modString = "extended modifiers = " + modifiersEx;
String tmpString = KeyEvent.getModifiersExText(modifiersEx);
if (tmpString.length() > 0) {
modString += " (" + tmpString + ")";
} else {
modString += " (no extended modifiers)";
}
String actionString = "action key? ";
if (e.isActionKey()) {
actionString += "YES";
} else {
actionString += "NO";
}
String locationString = "key location: ";
int location = e.getKeyLocation();
if (location == KeyEvent.KEY_LOCATION_STANDARD) {
locationString += "standard";
} else if (location == KeyEvent.KEY_LOCATION_LEFT) {
locationString += "left";
} else if (location == KeyEvent.KEY_LOCATION_RIGHT) {
locationString += "right";
} else if (location == KeyEvent.KEY_LOCATION_NUMPAD) {
locationString += "numpad";
} else { // (location == KeyEvent.KEY_LOCATION_UNKNOWN)
locationString += "unknown";
}
...//Display information about the KeyEvent...
}
}

Qua cc Demo phn trc chng ta bit gn nh ht cc s kin ca java


swing,vy by gi chng ta hy n vi mt v d c th v sinh ng ca x l s
kin trong java.Swing.
Demo Gii phng trnh bc hai:
Class1:
public class PTB2Engine {
private int a;
private int b;

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

x2 = " + ((-this.b + Math.sqrt(delta)) / (2 * this.a));

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

You might also like