LẬP TRÌNH JAVA NÂNG CAO Chương 01: Lập trình giao diện Lê Tân Bộ môn: Lập trình máy tính
LP TRNH JAVA NNG CAO
Chng 01: Lp trnh giao din
L TnB mn: Lp trnh my tnh
Ni dung chng 01F S phn cp lp GUIF JFramesF Layout Managers F Drawing on JPanels: Lines, Rectangles,
Ovals, Arcs, PolygonsF Event-Driven Programming: Event Source,
Listener, Listener InterfaceF Nt nhn v menuF JCheckbBox v JRadioButton F Cc lp vn bn v JScrollBar
Cc thnh phn GUIF Cc i tng GUI: button, label, text field, check box, radio button, combo box,
F Mi loi i tng c xc nh trong 1 lp: JButton, JLabel, JTextField, JCheckBox, JRadioButton, JComboBox,
F Mi lp thnh phn GUI c mt s constructor to cc i tng thnh phn GUI.
Swing vs. AWTF AWT: Abstract Windows Toolkit:
Java 1
c gn vi platform xc nh
Thch hp vi vic pht trin cc ng dng GUI n gin.
F Swing components: Java 2
Khng gn vi platform c nh
Mnh, a nng, linh hot
S phn cp lp GUI (Swing)
Dimension
Font
FontMetrics
Component
Graphics
Object Color
Container
Panel Applet
Frame
Dialog
Window
JComponent
JApplet
JFrame
JDialog
Swing Components in the javax.swing package
Lightweight
Heavyweight
Classes in the java.awt package
1
LayoutManager
*
JComponent
Cc lp GUI: nhm containerF c dng cha cc thnh phn khc.
F Cc lp container (Swing): Container JFrame JDialog JApplet JPanel
Cc lp GUI: nhm componentF Gm cc subclass ca lp JComponent.F Cc lp GUI component (Swing):
JButton JLabel JTextField JTextArea JComboBox JList JRadioButton JMenu
Cc lp GUI: nhm helperF c cc component v container dng v v t cc i tng.
F Cc lp helper (Swing): Graphics Color Font FontMetrics Dimension LayoutManager
AWT (Optional)AWTEvent
Font
FontMetrics
Component
Graphics
Object Color
Canvas
Button
TextComponent
Label
List
CheckBoxGroup
CheckBox
Choice
Container Panel Applet
Frame
Dialog FileDialog
Window
TextField
TextArea
MenuComponent MenuItem
MenuBar
Menu
Scrollbar
LayoutManager
Cc thnh phn giao din ngi s dng
Frame Pull-down Menus
User InterfaceComponents (UI)
Panel
Panel
Panel
UI
Panel
UI
Panel
UI
Applet
Panel
User InterfaceComponents
Panel
User InterfaceComponents
Panel
User InterfaceComponents
Panel
User InterfaceComponents
panel
Pull-down Menus
FramesF Frame l mt ca s khng cha trong ca s khc.
F Frame l nn tng cha cc thnh phn GUI khc trong cc ng dng Java GUI.
F Trong cc chng trnh Swing GUI, s dng lp JFrame to cc ca s.
To Frameimport javax.swing.*;public class MyFrame { public static void main(String[] args) { JFrame frame = new JFrame("Test Frame"); frame.setSize(400, 300); frame.setVisible(true); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); }
}Ch : Chy chng trnh cn JDK 1.3 hoc cao hn
Cn gia Frame
Mc nh, frame c hin th gc trn
bn tri ca mn hnh. hin th frame mt v tr xc nh, s
dng phng thc setLocation(x, y) trong lp JFrame. Phng thc ny t gc tri trn ca frame
ti v tr c ta (x, y).
Cn gia Frame (tip)
screenHeight
screenWidth
getHeight()
getWidth()
(x, y)
Frame
Screen
(0, 0)
a cc thnh phn vo trong Frame
// Dua nut bam vao trong frame frame.getContentPane().add( new JButton("OK"));
LU Content pane l mt lp con ca Container. Cu lnh slide trc tng ng vi 2 cu lnh sau:Container container = frame.getContentPane();container.add(new JButton("OK"));
Content pane c sinh ra khi mt i tng JFrame c to. i tng JFrame s dng content pane cha cc thnh phn trong frame.
Layout ManagersF Cc layout manager ca Java cung cp c ch t ng nh x cc thnh phn GUI ca bn trn tt c cc h thng ca s.
F Cc thnh phn GUI c t trong cc container. Mi container c mt layout manager sp xp cc thnh phn .
Thit lp Layout ManagerLayoutManager layMan = new XLayout();
container.setLayout(layMan);
F XLayout: FlowLayout GridLayout BorderLayout
V d 9.1: FlowLayout ManagerCc thnh phn c sp xp trong container t tri sang phi, t trn xung di theo th t chng c a vo.
FlowLayout ConstructorsF public FlowLayout(int align, int hGap, int vGap)Xy dng mt FlowLayout mi c cch sp hng (alignment), khong trng ngang (horizontal gap), khong trng dc (vertical gap) xc nh. Cc khong trng gia cc thnh phn c tnh bng pixel.
F public FlowLayout(int alignment)Xy dng mt FlowLayout mi c alignment xc nh, khong trng ngang v dc u c mc nh bng 5 pixel.
F public FlowLayout()Xy dng mt FlowLayout mi c cch sp hng mc nh cn gia v khong trng ngang v dc mc nh bng 5 pixel.
V d 9.2: GridLayout ManagerGridLayout manager sp xp cc thnh phn trong mt li (ma trn) vi s hng v s ct c xc nh bi constructor. Cc thnh phn c t trong li t tri sang phi, t trn xung di.
GridLayout ConstructorsF public GridLayout(int rows,int columns)Xy dng mt GridLayout mi c s hng v s ct xc nh.
F public GridLayout(int rows, int columns, int hGap, int vGap)Xy dng mt GridLayout mi c s hng v s ct xc nh, v khong trng ngang v dc gia cc thnh phn c xc nh.
V d 9.3: BorderLayout Manager
FBorderLayout manager chia container thnh 5 khu vc: East, South, West, North, v Center.
V d 9.3 (tip)FCc thnh phn c a vo
BorderLayout bng phng thc add:add(Component, constraint)Fconstraint: BorderLayout.EAST, BorderLayout.SOUTH, BorderLayout.WEST, BorderLayout.NORTH, BorderLayout.CENTER.
S dng Panel lm ContainerF Cc panel ng vai tr nh cc container nh nhm cc thnh phn GUI.
F Bn nn t cc thnh phn GUI trong cc panel v t cc panel trong mt frame, hoc cng c th t panel trong panel. JPanel p = new JPanel();p.add(new JButton("OK");frame.getContentPanel().add(p);
V d 9.4: PanelChng trnh to mt giao din cho l vi sng, s dng cc panel t chc cc thnh phn.
A button
A textfield
12
buttons
frame
p2
p1
V trn PanelF JPanel cn c th c s dng v ha, vn bn v cho php tng tc vi ngi s dng.
F v trn panel: To mt lp subclass ca JPanel Chng phng thc paintComponent. Sau c th hin th cc chui k t, v cc khi hnh hc v
hin th nh trn panel.
V trn Panel (tip)public class DrawMessage extends JPanel { /** Main method */ public static void main(String[] args) { JFrame frame = new JFrame("DrawMessage"); frame.getContentPane().add(new DrawMessage());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200); frame.setVisible(true); }
/** Paint the message */ public void paintComponent(Graphics g) { super.paintComponent(g); g.drawString("Welcome to Java!", 40, 40); }}
V trn Panel (tip)
LU F Lp Graphics l mt lp tru tng hin th hnh v v nh trn mn hnh trn cc platform khc nhau. F Lp Graphics gi gn cc chi tit platform v cho php bn v cc th theo cch ging nhau khng lin quan n cc platform c th. F Li gi super.paintComponent(g) l cn thit m bo rng vng hin th c xa sch trc khi hin th mt bn v.
LU
v cc hnh, thng thng bn to mt lp con ca JPanel v chng phng thc paintComponent "ni" cho h thng phi v nh th no. Thc t bn c th v cc th trn bt k thnh phn GUI no.
Lp ColorF Bn c th thit lp mu cho cc thnh phn GUI bng cch s dung lp java.awt.Color. Cc mu c to t 3 mu c bn l red, green, blue; mi mu c biu din bi mt gi tr byte (0-255) miu t cng . y c gi l h mu RGB (RGB model).
Color c = new Color(r, g, b);r, g, b xc nh mt mu c to bi cc thnh phn tng ng red, green, blue. V d:
Color c = new Color(228, 100, 255);
Thit lp muF Bn c th s dng cc phng thc sau thit lp mu background v foreground ca cc thnh phn:
setBackground(Color c) setForeground(Color c)
V d:JButton jbtOK = new JButton();jbtOK.setBackground(Color.yellow); jbtOK.setForeground(new Color(255,0,0));
Lp FontFont myFont = Font(name, style, size);
V d:Font font1 = new Font("SansSerif", Font.BOLD, 16);Font font2 = new Font("Serif",
Font.BOLD+Font.ITALIC, 12);
Tm tt c tn Font kh dngimport java.awt.GraphicsEnvironment;
public class testAllFonts { public static void main(String[] args) {GraphicsEnvironment e =
GraphicsEnvironment.getLocalGraphicsEnvironment();String[] fontnames = e.getAvailableFontFamilyNames();for (int i = 0; i < fontnames.length; i++)System.out.println(fontnames[i]);}
}
Thit lp Fontpublic void paint(Graphics g) { Font myFont = new Font("Times", Font.BOLD, 18); g.setFont(myFont); g.drawString("Welcome to Java", 20, 40);
//set a new font g.setFont(new Font("Courier",Font.BOLD+Font.ITALIC,16)); g.drawString("Welcome to Java", 20, 70);}
Lp FontMetricsF Bn c th hin th mt chui k t ti v tr bt k trong panel bng cch s dng lp FontMetrics.
F nhn i tng FontMetrics cho mt font xc nh, s dng phng thc getFontMetrics:public void paint(Graphics g) { g.getFontMetrics(Font f); // hoc g.getFontMetrics();}
Cc phng thc ly thuc tnh chui ca lp FontMetrics
F public int getAscent()F public int getDescent()F public int getLeading()F public int getHeight()F public int stringWidth(String str)
V d 9.5: S dng FontMetricsF Mc tiu: Hin th Welcome to Java cn gia trong frame.
Welcome to Java stringWidth
stringAscent getHeight()
getWidth()
messagePanel
V d 9.5 (tip)
MessagePanel -xCoordinate: int -yCoordinate: int -centered: boolean -message: String +getMessage(): String +getXCoordinate(): int +getYCoordinate(): int +isCentered(): boolean +setMessage(message: String): void +setXCoordinate(x: int): void +setYCoordinate(y: int): void +setCentered(centered: boolean): void +paintComponent(g: Graphics): void +getPerferredSize(): Dimension +getMinimumSize(): Dimension
1 TestFontMetrics
JPanel -char token +getToken +setToken +paintComponet +mouseClicked
JFrame -char token +getToken +setToken +paintComponet +mouseClicked
1
V cc hnh hnh hc trn Panel
F V ng thngF V hnh ch nhtF V hnh bu dcF V cung trnF V a gic
V ng thng
drawLine(x1, y1, x2, y2);
V hnh ch nhtF drawRect(x, y, w, h);F fillRect(x, y, w, h);
V hnh ch nht gc trnF drawRoundRect(x, y, w, h, aw, ah);F fillRoundRect(x, y, w, h, aw, ah);
V hnh bu dcF drawOval(x, y, w, h);F fillOval(x, y, w, h);
V cung trnF drawArc(x, y, w, h, angle1, angle2);F fillArc(x, y, w, h, angle1, angle2);
V a gicint[] x = {40, 70, 60, 45, 20};int[] y = {20, 40, 80, 45, 60};g.drawPolygon(x, y, x.length);g.fillPolygon(x, y, x.length);
V d 9.6: V chic ng hF Mc tiu: S dng cc phng thc v v lng gic v mt chic ng h hin th gi, pht, giy hin ti trong mt frame.
V d 9.6 (tip)xEnd = xCenter + handLength sin()yEnd = yCenter - handLength cos()V 1 pht c 60 giy, gc ca
kim giy l:
second (2pi/60)
V d 9.6 (tip)xEnd = xCenter + handLength sin()yEnd = yCenter - handLength cos()V tr ca kim pht c xc nh
bi pht v giy theo cng thc minute + second/60. V d, nu thi gian l 3 pht 30 giy. Tng s pht l 3.5. V 1 gi c 60 pht, gc ca kim pht l: (minute + second/60) (2pi/60)
V d 9.6 (tip)xEnd = xCenter + handLength sin()yEnd = yCenter - handLength cos()V hnh trn c chia thnh 12
gi, gc ca kim gi l:(hour + minute/60 + second/(60 60))) (2pi/12)
Lp trnh hng s kin
F Lp trnh hng th tc (Procedural programming) chng trnh c thc hin theo th t th tc.
F Trong lp trnh hng s kin (event-driven programming), m lnh c thc hin vo lc kch hot s kin.
S kin
F Mt s kin (event) c th c nh ngha l mt loi tn hiu bo cho chng trnh c iu g xy ra..
F S kin c sinh ra bi cc hnh ng ca ngi s dng (v d: di chut, kch phm chut, n phm) hoc bi HH (vd: timer).
Cc lp s kin
Cc lp s kin trn nm trong gi java.awt.eventring ListSelectionEvent trong gi javax.swing.event
Selected User ActionsSource Event Type
User Action Object Generated
Clicked on a button JButton ActionEventChanged text JTextComponent TextEventDouble-clicked on a list item JList ActionEventSelected or deselected an item JList ItemEvent with a single click
Selected or deselected an item JComboBox ItemEvent
M hnh y quyn
Selected Event Handlers Event Class Listener Interface Listener Methods (Handlers)ActionEvent ActionListener actionPerformed(ActionEvent)ItemEvent ItemListener itemStateChanged(ItemEvent)WindowEvent WindowListener windowClosing(WindowEvent)
windowOpened(WindowEvent)windowIconified(WindowEvent)windowDeiconified(WindowEvent)windowClosed(WindowEvent)windowActivated(WindowEvent)windowDeactivated(WindowEvent)
ContainerEvent ContainerListener componentAdded(ContainerEvent)componentRemoved(ContainerEvent)
V d 9.7:X l s kin hnh ng n gin
F Mc tiu: Hin th 2 nt bm OK v Cancel trong ca s. Khi kch chut vo mt nt, mt message c hin th ch ra nt no c kch.
import java.util.*;import java.awt.*;import java.awt.event.*;import javax.swing.*;class Gui { private static JFrame fr = null; private static JButton btn = null; private static JButton btn1 = null; private static JTextField txt = null; private static Label reg; public static void main(String args[]) { Label hi = new Label("Hi"); Label nhap = new Label("Nhap:"); txt = new JTextField(); reg = new Label(""); JPanel pane = new JPanel(new GridLayout(3,2)); pane.add(hi);pane.add(reg);pane.add(nhap);pane.add(txt); btn=new JButton("OK"); btn.setActionCommand("btn"); btn.setMnemonic(KeyEvent.VK_O); //Su dung phim tat Alt+C btn.addActionListener(new ButtonListener()); // nut btn dang ky xu ly su kien btn1 = new JButton("Cancel"); // Tao nut Cancel btn1.setActionCommand("btn1"); btn1.setMnemonic(KeyEvent.VK_C); //Su dung phim tat Alt+C btn1.addActionListener(new ButtonListener()); // nut btn1 dang ky xu ly su kien pane.add(btn); pane.add(btn1); fr = new JFrame("Thu nghiem"); fr.setContentPane(pane); fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); fr.setSize(200,100); fr.setLocation(200, 200); fr.setVisible(true); }
// Xu ly su kien khi nguoi dung bam chuot vao nut static class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { String whichButton = e.getActionCommand( ); // Get name
if (whichButton.equals("btn")){ reg.setText(txt.getText()); txt.setText(""); } else{ fr.dispose();//Dong khung System.exit(0);//Ket thuc chuong trinh } } }}
V d 9.8: X l s kin ca sF Mc tiu: Minh ha vic x l s kin ca s. Bt
k lp con no ca lp Window c th to ra cc s kin ca s sau: m, ang ng, ng, c kch hot, mt kch hot, c thu nh thnh biu tng, phng to tr li ca s. Chng trnh ny to mt frame, lng nghe cc s kin ca s, v hin th thng bo ch ra s kin ang xut hin.
import javax.swing.*;class Gui1 {public static void main(String args[ ]) { JFrame myWindow = new JFrame(); myWindow.setSize(400,300); JLabel myLabel = new JLabel(Hello my world!); myWindow.getContentPane().add(myLabel); WindowDestroyer myListener = new WindowDestroyer(); myWindow.addWindowListener(myListener); myWindow.setVisible(true); }}import java.awt.*; import java.awt.event.*;public class WindowDestroyer extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); }}
JButtonF Button l mt thnh phn gy ra mt s kin hnh ng khi c kch chut. F Cc constructor ca JButton:JButton()JButton(String text)JButton(String text, Icon icon)JButton(Icon icon)
Cc thuc tnh JButtonF textF iconF mnemonicF horizontalAlignmentF verticalAlignmentF horizontalTextPositionF verticalTextPosition
Using Buttons
p ng cc s kin JButtonJButton bt = new JButton(OK);bt.setActionCommand(Left);bt.addActionListener(new Nghenut());static class Nghenut implements ActionListener{public void actionPerformed(ActionEvent e) { // Get the button label String actionCommand = e.getActionCommand(); // Make sure the event source is Left button if (e.getSource() instanceof JButton) // Make sure it is the right button if ("Left".equals(actionCommand)) System.out.println ("Button pressed!");}
JCheckBoxF Check box l mt thnh phn cho php ngi dng bt hay tt mt la chn, ging nh 1 cng tc n.F Cc constructor:JCheckBox()JCheckBox(String text)JCheckBox(String text, boolean selected)JCheckBox(Icon icon)JCheckBox(String text, Icon icon)JCheckBox(String text,Icon icon,boolean selected)
Cc thuc tnh JCheckBoxF JCheckBox c tt c cc thuc tnh trong JButton. Ngoi ta, JCheckBox c thuc tnh:selectedF Using Check Box:JCheckBox cb = new JCheckBox(Chon);if (cb.isSelected()) { . . . }
JRadioButtonF Cc Radio button l s bin i ca cc check box. Chng thng c s dng trong mt nhm khi m ch c 1 button c chn ti mt thi im.F Cc constructor:
JRadioButton()JRadioButton(String text)JRadioButton(String text, boolean selected)JRadioButton(Icon icon)JRadioButton(String text, Icon icon)JRadioButton(String text, Icon icon, boolean selected)
Cc thuc tnh JRadioButtonJRadioButton c tt c cc thuc tnh trong JButton. Ngoi ra, JRadioButton c thuc tnh:selected
Gp nhm cc Radio ButtonButtonGroup btg = new ButtonGroup();btg.add(jrb1);btg.add(jrb2);
Using Radio Buttons:JRadioButton rb1 = new JRadioButton(Chon);JRadioButton rb2 = new JRadioButton(Khong chon);
btg.add(rb1); btg.add(rb2);if (rb1.isSelected()) { . . . }
JLabelF Label dng hin th mt chui vn bn thng thng
nhm m t thm thng tin cho cc i tng khc.F Cc constructor ca JLabel:
JLabel()JLabel(String text)JLabel(String text,int hAlignment)JLabel(Icon icon)JLabel(Icon icon, int hAlignment)JLabel(String text,Icon icon,int hAlignment)
Cc thuc tnh JLabelF textF iconF horizontalAlignmentF verticalAlignment
Using Labels
JTextFieldF Text field l nhp d liu dng vn bn trn 1 dng.F Cc constructor ca JTextField:JTextField()JTextField(int columns)
To mt text field trng c s ct xc nh.JTextField(String text)
To mt text field vi vn bn c sn.JTextField(String text, int columns)
To mt text field vi vn bn c sn v s ct xc nh.
Cc thuc tnh JTextFieldF textF horizontalAlignmentF editableF columns
Cc phng thc JTextFieldF getText()Tr v chui k t trong text field.
F setText(String text)t chui k t trong text field.
F setEditable(boolean editable)Cho php hoc v hiu ha son tho trong text field. Mc nh, editable l true.
F setColumns(int)Thit lp s ct trong text field. Chiu di ca text field c th thay i.
JTextAreaF TextArea l khung cho php ngi s dng nhp vo nhiu dng vn bn.F Cc constructor ca JTextArea:JTextArea()JTextArea(String s)JTextArea(int rows, int columns)JTextArea(String s, int rows, int columns)
Cc thuc tnh JTextAreaF textF editableF columnsF lineWrapF wrapStyleWordF rowsF lineCountF tabSize
S dng Text AreaChng trnh hin th 1 nh v 1 title trong 1 label, hin th vn bn trong text area.
DescriptionPanel
-jlblImage-jlblTitle-jtaTextDescription
+setImageIcon+setTitle+setTextDescription+getMinimumSize
11 TextAreaDemo
JPanel
-char token
+getToken+setToken+paintComponet+mouseClicked
JFrame
-char token
+getToken+setToken+paintComponet+mouseClicked
JComboBoxF Combo box l danh sch n gin cc mc chn. C bn n thc hin chc nng ging nh 1 list, nhng ch c th ly 1 gi tr.F Cc constructor:JComboBox()
to 1 combo box rngJComboBox(Object[] stringItems)
to 1 combo box cha cc phn t trong dy
Cc phng thc JComboBoxjcbo.addItem(Object item)thm 1 mc chn vo JComboBox jcbo
jcbo.getItem()jcbo.getItemAt(int index)ly 1 mc chn t JComboBox jcbo
jcbo.removeItemAt(int index)loi 1 mc chn khi JComboBox jcbo
Using Combo Box:
S dng itemStateChanged HandlerKhi mt la chn c check hoc uncheck, itemStateChanged() cho ItemEvent v actionPerformed() handler cho ActionEvent s c gi.
public void itemStateChanged(ItemEvent e){ // Make sure the source is a combo box if (e.getSource() instanceof JComboBox) String s = (String)e.getItem();}
JListF List l mt thnh phn c bn thc hin chc nng ging combo box, nhng n cho php ngi s dng chn mt hoc nhiu gi tr.F Cc constructor:JList()
to 1 list rng.
JList(Object[] stringItems)to 1 list cha cc phn t trong dy.
Cc thuc tnh JListF selectedIndexF selectedIndicesF selectedValueF selectedValuesF selectionModeF visibleRowCountUsing Lists:
JScrollBarF ScrollBar l mt iu khin cho php ngi s dng chn t mt di cc gi tr.F Cc constructor:JScrollBar()JScrollBar(int orientation)JScrollBar(int orientation, int value,
int extent, int min, int max)
Cc thuc tnh JScrollBarF orientation: 1 - dc, 0 - ngangF maximum, minimumF visibleAmount (extent): rng ca phn con chyF value: gi tr hin thi ca scroll barF blockIncrement: gi tr c cng thm khi kch hot vng tng.F unitIncrement: gi tr c cng thm khi kch hot u tng.
Cc phng thc JScrollBarF setBlockIncrement(int increment)F setMaximum(int maximum)F setMinimumF setOrientation(int orientation)F setUnitIncrement(int increment)F setValue(int value)F setVisibleAmount (extent): F getBlockIncrement()F ...
BordersF Bn c th thit lp mt border trn bt k i tng no ca lp JComponent, nhng thng hu ch khi thit lp mt titled border trn JPanel nhm mt tp cc thnh phn giao din ngi s dng c lin quan.F Using border:
Cc phng thc tnh to BordersF createTitledBorder(String title)F createLoweredBevelBorder()F createRaisedBevelBorder()F createLineBorder(Color color)F createLineBorder(Color color, int thickness)F createEtchedBorder()F createEtchedBorder(Color highlight,
Color shadow, boolean selected)F createEmptyBorder()F createMatteBorder(int top, int left,
int bottom, int right, Icon tileIcon)F createCompoundBorder(Border outsideBorder,
Border insideBorder)
DialogsF C th s dng lp JOptionPane to 4 loi dialog chun:
Message Dialog hin th mt message v i ngi s dng kch nt OK ng hp thoi.
Confirmation Dialog hin th cu hi v ngh ngi s dng tr li, vd: OK hay Cancel
Input Dialog hin th cu hi v nhn d liu vo t 1 text field, combo box hoc list.
Option Dialog hin th cu hi v nhn cu tr li t mt tp cc la chn.
To cc Message DialogS dng phng thc tnh trong lp JOptionPane
showMessageDialog(Component parentComponent, Object message)
showMessageDialog(Component parentComponent, Object message,String title, int messageType)
showMessageDialog(Component parentComponent, Object message, String title, int messageType, Icon icon)
To cc Confirmation DialogS dng phng thc tnh trong lp JOptionPane
showConfirmDialog(Component parentComponent, Object message)
showConfirmDialog(Component parentComponent, Object message, String title, int optionType)
showConfirmDialog(Component parentComponent, Object message, String title, int optionType,
[[int messageType], Icon icon])
To cc Option DialogS dng phng thc tnh trong lp JOptionPane
showOptionDialog(Component parentComponent, Object message, String title, int optionType, int messageType, Icon icon, Object[] options, Object initialValue)
S dng cc dialog:
MenusF Java cung cp mt s lp - JMenuBar, JMenu, JMenuItem, JCheckBoxMenuItem, v JRadioButtonMenuItem - thc thi menu trong mt frame.
F Mt JFrame hoc JApplet c th cha mt menu bar trn c gn cc pull-down menu. Cc menu cha cc menu item ngi dng la chn (hoc bt/tt). Menu bar c th c xem nh mt cu trc h tr cc menu.
Menu Demo
Lp JMenuBarMenu bar cha cc menu; menu bar ch c th c
thm vo 1 frame. on code sau to v thm mt
JMenuBar vo 1 frame:
JFrame f = new JFrame();f.setSize(300, 200);f.setVisible(true);JMenuBar mb = new JMenuBar(); f.setJMenuBar(mb);
Lp MenuBn gn cc menu vo mt JMenuBar. on code sau to 2 menu File v Help, v thm chng vo JMenuBar mb:
JMenu fileMenu = new JMenu("File", false);JMenu helpMenu = new JMenu("Help", true);mb.add(fileMenu);mb.add(helpMenu);
Lp JMenuItemon code sau thm cc mc chn (menu item) v cc
separator trong menu fileMenu:
fileMenu.add(new JMenuItem("New"));fileMenu.add(new JMenuItem("Open"));fileMenu.addSeparator();fileMenu.add(new JMenuItem("Print"));fileMenu.addSeparator();fileMenu.add(new JMenuItem("Exit"));
SubmenusBn c th thm cc submenus vo cc menu item. on code sau thm cc submenu Unix, NT, v Win95 vo trong mc chn Software.
JMenu softwareHelpSubMenu = new JMenu("Software");JMenu hardwareHelpSubMenu = new JMenu("Hardware");helpMenu.add(softwareHelpSubMenu);helpMenu.add(hardwareHelpSubMenu);softwareHelpSubMenu.add(new JMenuItem("Unix"));softwareHelpSubMenu.add(new JMenuItem("NT"));softwareHelpSubMenu.add(new JMenuItem("Win95"));
Submenu Demo
S dng Menu
To mt giao din thc hin cc php ton s hc gia 2 s Number1 v Number2. Giao din cha cc nhn v text field cho Number 1, Number 2, v Result (s dng nh i vi JButton).
Bc 1: To 1 subclass ca lp JFrame (c gi l 1 SubFrame) xc nh ca s mi lm vic g. V d, tt c cc chng trnh ng dng GUI m rng JFrame v l cc subclass ca JFrame.
To thm Window - bc 1
To thm Window - bc 2Bc 2: To 1 instance ca SubFrame trong ng dng hoc trong applet.
V d:SubFrame subFrame = new SubFrame("SubFrame Title");
To thm Window - bc 3
Bc 3: To 1 JButton kch hot subFrame.add(new JButton("Activate SubFrame"));
To thm Window - bc 4Bc 4: chng phng thc actionPerformed() nh sau:
public actionPerformed(ActionEvent e){ String actionCommand = e.getActionCommand(); if (e.target instanceof Button) { if ("Activate
SubFrame".equals(actionCommand)) { subFrame.setVisible(true); } }}
V d: To nhiu WindowV d to 1 main window c 1 text area trong scroll pane, 1 button "Show Histogram". Khi ngi s dng kch vo button, 1 ca s mi xut hin hin th biu cho biu din tn s xut hin ca cc k t trong text area.
JScrollPaneScroll pane l mt thnh phn t ng h tr cun ca s m khng cn lp trnh.
Using Scroll Pane: add mt TextArea vo trong mt Scroll pane
Cu trc Scroll PaneColumn headerCorner
Component
Row header
JViewport
Scrollable Component
Horizontal scroll bars
Vertical scroll bars
CornerComponent
CornerComponent
CornerComponent
JTabbedPaneTabbed pane cung cp mt tp cc tab loi tr ln nhau truy nhp nhiu thnh phn.
Using Tabbed Pane:
LP TRNH JAVA NNG CAONi dung chng 01Cc thnh phn GUISwing vs. AWTS phn cp lp GUI (Swing)JComponentCc lp GUI: nhm containerCc lp GUI: nhm componentCc lp GUI: nhm helperAWT (Optional)Cc thnh phn giao din ngi s dngFramesTo FrameCn gia FrameCn gia Frame (tip)a cc thnh phn vo trong FrameLU Layout ManagersThit lp Layout ManagerV d 9.1: FlowLayout ManagerFlowLayout ConstructorsV d 9.2: GridLayout ManagerGridLayout ConstructorsV d 9.3: BorderLayout ManagerV d 9.3 (tip)S dng Panel lm ContainerV d 9.4: PanelV trn PanelV trn Panel (tip)Slide 30Slide 31Slide 32Lp ColorThit lp muLp FontTm tt c tn Font kh dngThit lp FontLp FontMetricsCc phng thc ly thuc tnh chui ca lp FontMetricsV d 9.5: S dng FontMetricsSlide 41V d 9.5 (tip)V cc hnh hnh hc trn PanelV ng thngV hnh ch nhtV hnh ch nht gc trnV hnh bu dcV cung trnV a gicV d 9.6: V chic ng hV d 9.6 (tip)Slide 52Slide 53Lp trnh hng s kinS kinCc lp s kinSelected User ActionsM hnh y quynSelected Event HandlersV d 9.7: X l s kin hnh ng n ginSlide 61Slide 62V d 9.8: X l s kin ca sSlide 64JButtonCc thuc tnh JButtonp ng cc s kin JButtonJCheckBoxCc thuc tnh JCheckBoxJRadioButtonCc thuc tnh JRadioButtonGp nhm cc Radio ButtonJLabelCc thuc tnh JLabelJTextFieldSlide 76Cc phng thc JTextFieldJTextAreaCc thuc tnh JTextAreaS dng Text AreaJComboBoxCc phng thc JComboBoxS dng itemStateChanged HandlerJListCc thuc tnh JListJScrollBarCc thuc tnh JScrollBarCc phng thc JScrollBarBordersCc phng thc tnh to BordersDialogsTo cc Message DialogTo cc Confirmation DialogTo cc Option DialogMenusMenu DemoLp JMenuBarLp MenuLp JMenuItemSubmenusSubmenu DemoS dng MenuSlide 103To thm Window - bc 2To thm Window - bc 3To thm Window - bc 4V d: To nhiu WindowJScrollPaneCu trc Scroll PaneJTabbedPane