LẬP TRÌNH ĐỒ HỌA VỚI AWT
Trang 1L p p trình h h a a v i i AWT
CAO Duc Thong – Thanglong University
thongcd@thanglong.edu.vn
Trang 22
Trang 3Trình qu n lý trình bày (Layout Manager)
a (Graphics), phông ch (Font), ki n (Event)
Trang 44
Th vi nAWT T
Image Insets Polygon Rectangle Toolkit MenuComponent
XXXLayout CheckboxGroup Component
MenuBar MenuItem
Menu Checkbox MenuItem
Trang 5Applet Checkbox
Choice Container Label List Scrollbar TextComponent
Panel Window ScrollPane
TextArea TextField
Frame Dialog
FileDialog
Trang 6Ví Component: button, checkbox, scrollbar…
t ph ng th c n a Component
getBounds(): tr ph m vi a Component (Rectangle)
getFont(): tr font hi n i a Component
getForeGround(): tr màu a Component
getHeight(): tr chi u cao a Component (pixel, ki u int)
Trang 7getSize(): tr kích th c a Component (Dimenstion)
getWidth(): tr chi u ng a Component (int)
getX(), getY(): tr a hi n i
isEnable(): boolean
paint(Graphics): ch u trách nhi m hi n th component
setVisible(boolean): hi n th component
Trang 9Frame a là Component a là Container
o Frame Frame() Frame(String title)
Ví
Trang 10UseLessFrame frame = new UseLessFrame();
} }
Trang 13t ngu n sinh ra ki n có th có nhi u p nghe
Trang 14class EventTest extends Frame implements ActionListener {
Label lab = new Label("Enter a number");
TextField tf1 = new TextField(5);
TextField tf2 = new TextField(5);
Button btnResult = new Button("Double is");
Button ext = new Button("exit");
public EventTest(String title) {
Trang 15public static void main(String args[]) {
EventTest t = new EventTest("Event handling");
t.setSize(300, 200);
t.setVisible(true);
} }
Trang 17java.awt.AWTEvent
AdjustmentEvent ComponentEvent ItemEvent
FocusEvent InputEvent ContainerEvent
KeyEvent MouseEvent
TextEvent WindowEvent
Trang 19v ContainerListenere
n FocusListenert
L
i ItemListeners
e
n MouseListenere
r MouseMotionListener
TextListener WindowListener
Trang 20addActionListener(A ctionListener)
addItemListener(Ite mListener)
Trang 22b.addActionListener(new ButtonHandler());
f.add(b, BorderLayout.CENTER);
f.pack();
f.setVisible(true);
Trang 23X lý ý cács ki n n
Trang 24
public static void main(String[] args){
TestButton test = new TestButton();
test.init();
} }
class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e) {
System.out.println("Button's command is: "+
e.getActionCommand());
} }
Trang 25Button's command is: ButtonPressed
Button's command is: ButtonPressed
Button's command is: ButtonPressed
Trang 2625
Trang 27public void windowClosed(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}
public void windowOpened(WindowEvent e){}
}
Trang 29public class GUIFrame extends Frame {
public GUIFrame(String title){
}
Trang 30setLocation((d.width - getWidth())/2, (d.height
-getHeight())/2);
} super.setVisible(visible);
}
public static void main(String[] args){
GUIFrame frame = new GUIFrame("GUI Frame");
frame.setSize(400,300);
frame.setVisible(true);
} }
Trang 32tr Label.LEFT, Label.RIGHT, Label.CENTER
Trang 33Label l1 = new Label("Label");
Label l2 = new Label("I am a label");
l2.setFont(new Font("Timesroman", Font.BOLD, 18));
Label l3 = new Label();
Trang 34public static void main(String[] args) {
LabelTest lt = new LabelTest();
}
}
Trang 35getSelectedText() getSelectionStart() getSelectionEnd() getText(), setText() select(int, int)
setCaretPosition(int) setEditable(boolean) setSelectionStart(int)
Trang 36TextField(int columns) TextField(String s)
TextField(String s, int columns) addActionListener(ActionListener) echoCharIsSet()
setEchoChar(char)
setText()
setColumn(int)
Trang 37isEditable(): xác nh xem có ch Editable không
Trang 38TextField tf1 = new TextField();
TextField tf2 = new TextField(25);
tf2.setText("Type stuff here");
tf2.setFont(new Font("Timesroman",Font.BOLD,18)); TextField tf3 = new TextField("I am disabled",15);
Trang 39Cácthànhph nAWT T
Trang 40
TextField tf7 = new TextField("Caret here >< ");
TextField tf8 = new TextField("username",8);
TextField tf9 = new TextField("password",8);
tf9.setEchoChar('*');
ComponentTestFrame frame = new
ComponentTestFrame("TextField Test");
frame.add(tf1); frame.add(tf2); frame.add(tf3);
frame.add(tf4); frame.add(tf5); frame.add(tf6);
frame.add(tf7); frame.add(tf8); frame.add(tf9);
frame.setVisible(true);
tf7.setCaretPosition(14);
} public static void main(String[] args) {
TextFieldTest test = new TextFieldTest();
} }
Trang 42TextArea(int rows, int columns) TextArea(String text)
TextArea(String text, int rows, int columns)
Trang 43get/set row/column setEditable/isEditable append(String)
insert(String s, int i): chèn chu i vào t trí replaceRange(String, int, int): thay th n n m gi a tríint và int cho tr c
Trang 44TextArea ta1 = new TextArea(10,20);
TextArea ta2 = new TextArea("Text Area\n with
TextArea ta4 = new TextArea("This textarea is not enable",
4,25,TextArea.SCROLLBARS_NONE);
Trang 45public static void main(String[] args) {
TextAreaTest test = new TextAreaTest();
} }
Trang 47Button(String text) addActionListener(ActionListener) String getLabel()
setLabel(String) removeActionListener(ActionListener)
Trang 48Button b1 = new Button("Button");
Button b2 = new Button();
b2.setLabel("Press me!");
b2.setFont(new Font("Timesroman", Font.BOLD, 16));
Button b3 = new Button("Can't press me");
Trang 49public static void main(String[] args) {
ButtonTest lt = new ButtonTest();
}
}
Trang 50Có th ch n nhi u option a Checkbox RadioButton ng gi ng nh Checkbox nh ng ch cho phép ch n
o RadioButton)
t ph ng th c Checkbox()
Checkbox(String) Checkbox(String, boolean)
Trang 51set/getLabel() set/getState() removeItemListener(ItemListener)
Trang 52Checkbox cb1 = new Checkbox("Java",false);
Checkbox cb2 = new Checkbox("C++",false);
cb2.setEnabled(false);
Checkbox cb3 = new Checkbox("HTML",true);
Checkbox cb4 = new Checkbox();
Trang 53public static void main(String[] args) {
CheckboxTest test = new CheckboxTest();
} }
Trang 54CheckboxGroup group = new CheckboxGroup();
Checkbox cb1 = new Checkbox("Java",false,group);
Checkbox cb2 = new Checkbox("C++",false,group);
cb2.setEnabled(false);
Checkbox cb3 = new Checkbox("HTML",true,group);
Checkbox cb4 = new Checkbox("",true,group);
Trang 55CheckboxGroupTest test = new CheckboxGroupTest();
} }
Trang 56add(String) addItem(String) addItemListener(ItemListener) getItem(int)
getItemCount() getSelectedIndex() insert(String, int)
Trang 57select(int) select(String)
Trang 59ChoiceTest test = new ChoiceTest();
} }
Trang 62public class CanvasTest extends Canvas {
public void paint(Graphics g){
setFont(new Font("Arial", Font.BOLD + Font.ITALIC, 16));
g.drawString("Canvas", 15, 25);
}
Trang 63public static void main(String[] args) {
CanvasTest c1 = new CanvasTest();
Trang 65o Menu Menu fileMenu = new Menu(“File”);
n Menu vào MenuBar menuBar.add(fileMenu);
o MenuItem MenuItem fileOpen = new MenuItem(“Open”);
Trang 67isEnabled() setEnabled()
Trang 68MenuItem fileOpen = new MenuItem("Open");
fileOpen.setShortcut(new MenuShortcut(KeyEvent.VK_O));
MenuItem fileSave = new MenuItem("Save");
fileSave.setShortcut(new MenuShortcut(KeyEvent.VK_S));
fileSave.setEnabled(false);
MenuItem fileSaveAs = new MenuItem("Save As");
Trang 69fileSaveAs.setEnabled(false);
MenuItem fileExit = new MenuItem("Exit");
fileExit.setShortcut(new MenuShortcut(KeyEvent.VK_X));
MenuItem editCut = new MenuItem("Cut");
editCut.setShortcut(new MenuShortcut(KeyEvent.VK_X));
MenuItem editCopy = new MenuItem("Copy");
editCopy.setShortcut(new MenuShortcut(KeyEvent.VK_C));
MenuItem editPaste = new MenuItem("Paste");
editPaste.setShortcut(new MenuShortcut(KeyEvent.VK_P));
Menu file = new Menu("File");
Trang 70public static void main(String[] args) {
MenuTest test = new MenuTest();
}
Trang 71Cácthànhph nAWT T
Trang 73
MenuItem paste = new MenuItem("Paste");
Trang 74MenuItem delete = new MenuItem("Delete");
PopupMenu popupMenu = new PopupMenu("Clipboard");
PopupMenuTest test = new PopupMenuTest();
} }
Trang 76Dùng Panel nhóm các thành ph n GUI i i nhau
import java.awt.*;
public class PanelTest {
public PanelTest() {
super();
Label lb1 = new Label("URL: ");
TextField tf1 = new TextField("",20);
Button b1 = new Button("Go");
Panel p1 = new Panel();
p1.setBackground(Color.CYAN);
p1.add(lb1); p1.add(tf1); p1.add(b1);
CheckboxGroup group = new CheckboxGroup();
Trang 77Cácthànhph nAWT T
Panel
Checkbox cb1 = new Checkbox("Java",group,true);
Checkbox cb2 = new Checkbox("C++",group,false);
Checkbox cb3 = new Checkbox("HTML",group,false); Checkbox cb4 = new Checkbox("ADA",group,false); Panel p2 = new Panel();
p2.setBackground(Color.BLUE);
p2.add(cb1); p2.add(cb2); p2.add(cb3); p2.add(cb4);
ComponentTestFrame frame = new
ComponentTestFrame("PanelTest");
frame.add(p1); frame.add(p2);
frame.setVisible(true);
} public static void main(String[] args) {
PanelTest test = new PanelTest();
} }
Trang 78Cácthànhph nAWT T
74
Trang 80t Dialog có th là modal ho c non-modal Modal dialog
Non-modal dialog
Trang 81Dialog(Frame) Dialog(Frame, String)
Trang 82Dialog d1 = new Dialog(frame,"Modal Dialog Test",true);
d1.add(new Label("Modal Dialog Test"));
Trang 83public void windowClosing(WindowEvent arg0) {
((Dialog)arg0.getSource()).setVisible(false);
} public void windowClosed(WindowEvent arg0) { }
Trang 84public static void main(String[] args) {
DialogTest test = new DialogTest();
} }
Trang 8682
Qu nlý ý trình h bày y
Layout manager: qu n lý cách trình bày a các GUI
components trong t Container
Trang 87Các hàm kh i o
FlowLayout() FlowLayout(int alignment)Alignment có th là FlowLayout.CENTER, LEFT, RIGHT FlowLayout(int, int, int)
Trang 88public class FlowLayoutTest extends Frame implements WindowListener {
public FlowLayoutTest(String title){
dispose();
System.exit(0);
}
Trang 89public void windowActivated(WindowEvent e){}
public void windowClosed(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}
public void windowOpened(WindowEvent e){}
public static void main(String[] args) { FlowLayoutTest ft = new FlowLayoutTest("FlowLayout Test");
} }
Trang 91Là layout c nh cho Frame, Window, Dialog
Các thành ph n c p p trên 5 khu c khác nhau
• NORTH – t nh a container.
• EAST – t phía bên ph i a container.x`
• SOUTH – t phía i a container
• WEST – t phía bên trái a container.
• CENTER – t gi a a container.
thêm t thành ph n vào vùng ‘North’
Button b1=new Button(“North Button”); // khai báo thành ph n
setLayout(new BorderLayout()); // thi t p layout
add(b1,BorderLayout.NORTH); // thêm thành ph n vào layout
Kh i o: BorderLayout(), BorderLayout(int, int)
Trang 94Các hàm kh i o:
GridLayout(int), GridLayout(int, int), GridLayout(int, int, int,int)
Trang 95public class GridLayoutTest extends Frame implements WindowListener {
public GridLayoutTest(String title){
Trang 96public void windowActivated(WindowEvent e){}
public void windowClosed(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}
public void windowOpened(WindowEvent e){}
public static void main(String[] args) {
GridLayoutTest ft = new GridLayoutTest(“GridLayout Test");
} }
Trang 9995
WindowEvent
Cài t giao ti p WindowListener
Xem ví Frame
X lý ý cács ki n n
Trang 101c phát sinh i Button, MenuItem, TextField, List
p nghe cài t giao ti p ActionListener hay cài t ph ng th c actionPerformed(ActionEvent)
t bi n & ph ng th c a ActionEvent int ALT_MASK: phím ALT có c nh n ? int CTRL_MASK: phím CTRL có c nh n ? int SHIFT_MASK: phím SHIFT có c nh n ? int getModifiers(): có th tr ALT_MASK, CTRL_MASK…
String getActionCommand(): tr command n i i ActionEvent
Trang 102class ActionListenerTest extends GUIFrame implements ActionListener {
Panel controlPanel, whoDoneItPanel, commandPanel;
Label whoDoneItLabel, commandLabel;
TextField whoDoneItTextField, commandTextField, textField;
Trang 103whoDoneItPanel.setBackground(Color.pink);
whoDoneItLabel = new Label("Who done it",
whoDoneItTextField = new TextField("A TextField"); //whoDoneItTextField.addActionListener(this);
whoDoneItTextField.setEditable(false);
whoDoneItPanel.add(whoDoneItLabel);
whoDoneItPanel.add(whoDoneItTextField);
add(whoDoneItPanel,BorderLayout.NORTH);
Trang 104X lý ý cács ki n n
99
Trang 105X lý ý cács ki n n
ActionEvent
//create controlPanel controlPanel = new Panel();
controlPanel.add(new Label("A TextField", Label.RIGHT)); textField = new TextField(15);
controlPanel.add(new Label("A List",Label.RIGHT));
list = new List(5,false);
list.add("Breakfast");
list.add("Lunch");
list.add("Diner");
Trang 107commandLabel = new Label("Action Command");
Trang 109} public static void main(String[] args){
ActionListenerTest test = new ActionListenerTest();
} }
Trang 111p nghe ItemEvent n cài t giao ti p ItemListener
Ph ng th c n cài t: itemStateChanged(ItemEvent)
Ph ng th c a ItemEvent
int getStateChange(): có th nh n ItemEvent.SELECTED ho cItemEvent.DESELECTED
Object getItem(): item ã thay i tr ng thái (Checkbox,
Trang 112c o ra i TextComponent (TextField, TextArea)
p nghe cài t giao ti p TextListener
Ph ng th c n cài t textValueChanged(TextEvent)
i (thêm, xóa text)
Trang 115super("Mouse Event Test");
canvas = new Canvas();
Trang 116new MouseTest();
} public void mouseClicked(MouseEvent e){
String text = "Event: Clicked Button ";
switch(e.getModifiers()){
case InputEvent.BUTTON1_MASK:
text += 1;
Trang 118event.setText(text);
} public void mouseEntered(MouseEvent e){
event.setText("Event: Entered");
} public void mouseExited(MouseEvent e){
event.setText("Event: Exited");
}
Trang 119X lý ý cács ki n n
110
Trang 120event.setText("Event: Released");
} public void mouseMoved(MouseEvent e){
location.setText("Location: (" + e.getX()+"," + e.getY()+")");
} public void mouseDragged(MouseEvent e){
Point p = e.getPoint();
event.setText("Event: Dragged");
location.setText("Location: (" + p.getX()+"," + p.getY()+")");
}
Trang 122void keyTyped(KeyEvent)
Trang 123Image image =
Toolkit.getDefaultToolkit().getImage("image.jpg");
Trang 125public static void main(String[] args) {
ImageTest image = new ImageTest();
GUIFrame frame = new GUIFrame("ImageTest");
frame.add(image);
frame.pack();
frame.setVisible(true);
} }
Trang 127CÂU U H I I
Trang 128th c 200, 200 màu Khi a chu t vào Canvas
ch ng trình hi n dòng ch “In canvas”, khi a chu t ra
ngoài hi n dòng ch “Not in canvas”
Vi t ch ng trình cho phép ng tròn i t trí
t mà ng i dùng nh n chu t trên màn hình
Vi t t ch ng trình i menu “Draw” có 3 menu item:
line, circle, square: khi ng i dùng kích vào ng menu
item, 50 line ho c circle ho c square c ra
Trang 130trí a qu bóng thay i theo Yêu u o t p
Ball riêng bi t (M ng bài toán cho tr ng p ng i
Trang 131121
ki n và i ng gây ra ki n
Tham m kh o o