++ ++ 11-1:使用JDialog組件: JDialog的類層次結構圖: java.lang.Object --java.awt.Component --java.awt.Container --java.awt.Window --java.awt.JDialog --javax.swing.JDialog 如果你為公司設計一套“物品工具借用系統”,在這個系統中,借用物品的員工必須詳細填員工編號、借用物品、借用器具、借 用日期、預計歸還日期時間、借用原因等等,若沒有詳細填這此數據,就無法取得準許借用物品的證明文件。因此在設計這套系統 的過程中,你必須查看用戶是否已經填妥相關數據,若員工忘記了填寫某些重要字段,系統應該給予警示,提醒用戶哪些字段必須 填寫。這個情況也常發生在網絡問卷或網絡會員注冊系統,用戶必須填寫相關數據,例如用戶若沒有填寫E-Mail郵件地址,則系統 會提示你應當填寫郵件地址,否則系統將不處理用戶填寫的信息。 為應付這種情況,java提供了JDialog與JOptionPane供我們使用,事實上,JOptionPane是陽春版的JDialog,當你在使用 JOptionPane時,系統會自動產生JDialog組件,并將JOptionPane的內容放入JDialog的ContentPane中,而這些均由系統在背后自動 運行,并不需要由我們介入。使用JOptionPane的好處是此組件已經默認了許多交互方式,你只用設置想要的顯示模式,JOptionPane 就能輕易的顯示出來,可說相當方便,若這些模式還是無法滿足你的需求,你就可以使用JDialog來自行設計你的對話框。 我們先來看如何構造JDialog,JOptionPane將在后半段介紹: JDialog構造函數: JDialog():建立一個non-modal的對話框,沒有title也不屬于任何事件窗口組件。 JDialog(Dialog owner):建立一個屬于Dialog組件的對話框,為non-modal形式,也沒有title. JDialog(Dialog owner,Boolean modal):建立一個屬于Dialog組件的對話框,可決定modal形式,但沒有title. JDialog(Dialog owner,String title):建立一個屬于Dialog組件的對話框,為non-modal形式,對話框上有title. JDialog(Dialog owner,String title,Boolean modal):建立一個屬于Dialog組件的對話框,可決定modal形式,且對話框上有 title. JDialog(Frame owner):建立一個屬于Frame組件的對話框,為non-modal形式,也沒有title. JDialog(Frame owner,Boolean modal):建立一個屬于Frame組件的對話框,可決定modal形式,但沒有title. JDialog(Frame owner,String title):建立一個屬于Frame組件的對話框,為non-modal形式,對話框上有title. JDialog(Frame owner,String title,Boolean modal):建立一個屬于Frame組件的對話框,可決定modal形式,且對話框上有title. 上面所說的modal是一種對話框操作模式,當modal為true時,代表用戶必須結束對話框才能回到原來所屬的窗口。當modal為 false時,代表對話框與所屬窗口可以互相切換,彼此之間在操作上沒有順序性。 一般而言對話框都會依附在某個窗口上,例如JFrame或JDialog,原因在于對話框通常是一個程序運行的過程中與用戶互動的中 間過程,在使用JDialog上跟JFrame非常相似,由上面的JDialog層次結構圖中你可以發現,JDialog是繼承AWT的Dialog類而來,因 此JDialog為一個Heavyweight組件。要加入組件到JDialog上與JFrame是一樣的,你必須先取得JDialog的ContentPane,然后再把組 件加到此ContentPane中,JDialog默認的版面管理器是BorderLayout. 11-1-1:在JFrame上建立JDialog: 我們來看一個JDialog的例子,在這個例子中,用戶在主窗口按下"借用物品"的按鈕時,會跳出一個讓用戶填寫窗體的JDialog 窗口,用戶必須結束此JDialog窗口后才能返回主窗口. import javax.swing.*; import javax.swing.border.*; import java.awt.*; import java.awt.event.*; import java.util.*; import com.incors.plaf.alloy.*; import com.incors.plaf.alloy.themes.glass.*; public class DialogDemo implements ActionListener{ JFrame f=null; public void actionPerformed(ActionEvent e){ String cmd=e.getActionCommand(); if (cmd.equals("借用物品")){ new LendingSystem(f); }else if (cmd.equals("離開系統")){ System.exit(0); } } public DialogDemo(){ f=new JFrame("JDialog Example"); Container contentPane=f.getContentPane(); JPanel buttonPanel=new JPanel(); JButton b=new JButton("借用物品"); b.addActionListener(this); buttonPanel.add(b); b=new JButton("離開系統"); b.addActionListener(this); buttonPanel.add(b); buttonPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.blue,2), "借用物品系統",TitledBorder.CENTER,TitledBorder.TOP)); contentPane.add(buttonPanel,BorderLayout.CENTER); f.pack(); f.setVisible(true); f.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } }); } public static void main(String[] args){ SwingUtil.setLookAndFeel(); new DialogDemo(); } } class LendingSystem implements ActionListener{ JTextField staffField,objectField,borrowDateField,returnDateField,reasonField; JDialog dialog; public void actionPerformed(ActionEvent e){ String cmd=e.getActionCommand(); if (cmd.equals("確定")){ }else if (cmd.equals("取消")){ dialog.dispose(); } } LendingSystem(JFrame f){ dialog = new JDialog(f,"借用物品",true); GridBagConstraints c; int gridx,gridy,gridwidth, gridheight,anchor,fill,ipadx,ipady; double weightx,weighty; Insets inset; GridBagLayout gridbag = new GridBagLayout(); Container dialogPane = dialog.getContentPane(); dialogPane.setLayout(gridbag); JLabel label = new JLabel("員工編號 : "); gridx=0; //第0列 gridy=0; //第0行 gridwidth = 1; //占一單位寬度 gridheight = 1; //占一單位高度 weightx = 0; //窗口增大時組件寬度增大比率0 weighty = 0; //窗口增大時組件高度增大比率0 anchor = GridBagConstraints.CENTER; //容器大于組件size時將組件置于容器中央 fill = GridBagConstraints.BOTH; //窗口拉大時會填滿水平與垂直空間 inset = new Insets(0,0,0,0); //組件間間距 ipadx = 0; //組件內水平寬度 ipady = 0; //組件內垂直高度 c = new GridBagConstraints(gridx,gridy,gridwidth,gridheight, weightx,weighty,anchor,fill,inset,ipadx,ipady); gridbag.setConstraints(label,c); dialogPane.add(label); label = new JLabel("借用器具 : "); gridx=3; gridy=0; c = new GridBagConstraints(gridx,gridy,gridwidth,gridheight, weightx,weighty,anchor,fill,inset,ipadx,ipady); gridbag.setConstraints(label,c); dialogPane.add(label); label = new JLabel("借用日期: "); gridx=0; gridy=1; c = new GridBagConstraints(gridx,gridy,gridwidth,gridheight, weightx,weighty,anchor,fill,inset,ipadx,ipady); gridbag.setConstraints(label,c); dialogPane.add(label); label = new JLabel("歸還日期: "); gridx=3; gridy=1; c = new GridBagConstraints(gridx,gridy,gridwidth,gridheight, weightx,weighty,anchor,fill,inset,ipadx,ipady); gridbag.setConstraints(label,c); dialogPane.add(label); label = new JLabel("借用原因 : "); gridx=0; gridy=2; c = new GridBagConstraints(gridx,gridy,gridwidth,gridheight, weightx,weighty,anchor,fill,inset,ipadx,ipady); gridbag.setConstraints(label,c); dialogPane.add(label); staffField = new JTextField(); gridx=1; gridy=0; gridwidth = 2; gridheight = 1; weightx = 1; weighty = 0; c = new GridBagConstraints(gridx,gridy,gridwidth,gridheight, weightx,weighty,anchor,fill,inset,ipadx,ipady); gridbag.setConstraints(staffField,c); dialogPane.add(staffField); objectField = new JTextField(); gridx=4; gridy=0; c = new GridBagConstraints(gridx,gridy,gridwidth,gridheight, weightx,weighty,anchor,fill,inset,ipadx,ipady); gridbag.setConstraints(objectField,c); dialogPane.add(objectField); borrowDateField = new JTextField(); gridx=1; gridy=1; c = new GridBagConstraints(gridx,gridy,gridwidth,gridheight, weightx,weighty,anchor,fill,inset,ipadx,ipady); gridbag.setConstraints(borrowDateField,c); dialogPane.add(borrowDateField); returnDateField = new JTextField(); gridx=4; gridy=1; c = new GridBagConstraints(gridx,gridy,gridwidth,gridheight, weightx,weighty,anchor,fill,inset,ipadx,ipady); gridbag.setConstraints(returnDateField,c); dialogPane.add(returnDateField); reasonField = new JTextField(); gridx=1; gridy=2; gridwidth = 5; c = new GridBagConstraints(gridx,gridy,gridwidth,gridheight, weightx,weighty,anchor,fill,inset,ipadx,ipady); gridbag.setConstraints(reasonField,c); dialogPane.add(reasonField); JPanel panel = new JPanel(); panel.setLayout(new GridLayout(1,2)); JButton b = new JButton("確定"); panel.add(b); b = new JButton("取消"); b.addActionListener(this); panel.add(b); gridx=0; gridy=3; gridwidth = 6; weightx = 1; weighty = 1; c = new GridBagConstraints(gridx,gridy,gridwidth,gridheight, weightx,weighty,anchor,fill,inset,ipadx,ipady); gridbag.setConstraints(panel,c); dialogPane.add(panel); dialog.setBounds(200,150,400,130); dialog.show(); } } class SwingUtil{ public static final void setLookAndFeel() { try{ Font font = new Font("JFrame", Font.PLAIN, 12); Enumeration keys = UIManager.getLookAndFeelDefaults().keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); if (UIManager.get(key) instanceof Font) { UIManager.put(key, font); } } AlloyLookAndFeel.setProperty("alloy.isLookAndFeelFrameDecoration", "true"); AlloyTheme theme = new GlassTheme(); LookAndFeel alloyLnF = new AlloyLookAndFeel(theme); UIManager.setLookAndFeel(alloyLnF); }catch(UnsupportedLookAndFeelException ex){ ex.printStackTrace(); } /* try{ Font font = new Font("JFrame", Font.PLAIN, 12); Enumeration keys = UIManager.getLookAndFeelDefaults().keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); if (UIManager.get(key) instanceof Font) { UIManager.put(key, font); } } UIManager.setLookAndFeel("com.stefankrause.xplookandfeel.XPLookAndFeel"); }catch(Exception e){ e.printStackTrace(); }*/ } } 11-2:使用JOptionPane類的靜態方法: JOptionPane的類層次結構圖: java.lang.Object --java.awt.Component --java.awt.Container --javax.swing.JComponent --javax.swing.JOptionPane 以JDialog來制作對話框,你必須實作對話框中的每一個組件,但有時候我們的對話框只是要顯示一段文字,或是一些簡單的 選擇(是或否),這時候可以利用JOptionPane類,它可以讓你很簡單的做出這樣的效果,不僅大大的減少了程序代碼的編寫,也 讓整個程序看起來清爽許多! JOptionPane的構造函數: JOptionPane():建立一個顯示測試信息的JOptionPane組件。 JOptionPane(Object message):建立一個顯示特定信息的JOptionPane組件。 JOptionPane(Object message,int messageType):建立一個顯示特定信息的JOptionPane組件,并設置信息類型。 JOptionPane(Object message,int messageType,int optionType):建立一個顯示特定信息的JOptionPane組件,并設置信息與選項. JOptionPane(Object message,int messageType,int optionType,Icon icon):建立一個顯示特定信息的JOptionPane組件,并設置 信息與選項,且可顯示出圖案. JOptionPane(Object message,int messageType,int optionType,Icon icon,Object[] options):建立一個顯示特定信息的 JOptionPane組件,并設置信息與選項,且可顯示出圖案.選項值是一個Object Array,可 用作更改按鈕上的文字. JOptionPane(Object message,int messageType,int optionType,Icon icon,Object[] options,Object initialValue):建立一個 顯示特定信息的JOptionPane組件,并設置信息與選項類型,且可以顯示出圖案.選項值是 一個Object Array,可用作更改按鈕上的文字,并設置默認按鈕. 使用JOptionPane對象所得到的對話框是modal為true形式,也就是說我們必須先關閉對話框窗口才能回到產生對話框的母窗口上 . 要利用JOptionPane類來輸出對話框,通常我們不會new一個JOptionPane對象出來,而是使用JOptionPane所提供的一些靜態方法, 不用產生JOptionPane對象就可以直接使用,這些方法方法都是以showXxxxxDialog的形式出現,若你的對話框是出現在 InternaleFrame上,你可以用showInternalXxxxxDialog的各種方法產生對話框.以下我們整理出JOptionPane提供輸出對話框的所有 靜態方法: Message Dialog ---------------------------------------------------------------------------------------------------------- 方法: |void showMessageDialog(Component parentComponent,Object message) |void showMessageDialog(Component parentComponent,Object message,String title,int messageType) |void showMessageDialog(Component parentComponent,Object message,String title,int messageType,Icon | icon) |void showInternalMessageDialog(Component parentComponent,Object message) |void showInternalMessageDialog(Component parentComponent,Object message,String title,int messageType) |void showInternalMessageDialog(Component parentComponent,Object message,String title,int messageType | ,Icon icon) ------------------------------------------------------------------------------------------------------------ 說明: |顯示信息對話框,對話框中只含有一個按鈕,通常是"確定"按鈕,例如安裝完某個軟件時通常會跳出一個對話框告知你 |安裝已經成功.這類的方法有5種參數: |parentComponent:是指產生對話框的組件為何,通常是指Frame或Dialog組件. | message:是指要顯示的組件,通常是String或Label類型 | title:對話框標題列上顯示的文字. | messageType:指定信息類型,共有5種類型,分別是ERROR_MESSAGE,INFORMATION_MESSAGE,WARING_MESSAGE, | QUESTION_MESSAGE,PLAIN_MESSAGE(不顯示圖標).指定類型后對話框就會出現相對應的圖標. | icon:若你不喜歡java給的圖標,你可以自己自定圖標. ------------------------------------------------------------------------------------------------------------ Confirm Dialog ------------------------------------------------------------------------------------------------------------ 方法: |int showConfirmDialog(Component parentComponent,Object message) |int showConfirmDialog(Component parentComponent,Object message,String title,int optionType) |int showConfirmDialog(Component parentComponent,Object message,String title,int optionType, | int messageType) |int showConfirmDialog(Component parentComponent,Object message,String title,int optionType, | int messageType,Icon icon) |int showInternalConfirmDialog(Component parentComponent,Object message) |int showInternalConfirmDialog(Component parentComponent,Object message,String title,int optionType) |int showInternalConfirmDialog(Component parentComponent,Object message,String title,int optionType | ,int messageType) |int showInternalConfirmDialog(Component parentComponent,Object message,String title,int optionType | ,int messageType,Icon icon) ----------------------------------------------------------------------------------------------------------- 說明: |顯示確認對話框,這類的對話框通常會問用戶一個問題,然后用戶回答是或不是,例如當我們修改了某個文件的內容 |卻沒存盤就要離開時,系統大部份都會跳出確認對話框.詢問我們是否要存儲修改過的內容.確認對話框方法有6種 |參數: |parentComponent:是指產生對話框的組件為何,通常是指Frame或Dialog組件. | message:是指要顯示的組件,通常是String或Label類型 | title:對話框標題列上顯示的文字. | optionType:確定按鈕的類型,有5種類型,分別是DEFAULT_OPTION,YES_NO_OPTION,YES_NO_CANCEL,與 | OK_CANCEL_OPTION. | messageType:指定信息類型,共有5種類型,分別是ERROR_MESSAGE,INFORMATION_MESSAGE,WARING_MESSAGE, | QUESTION_MESSAGE,PLAIN_MESSAGE(不顯示圖標).指定類型后對話框就會出現相對應的圖標. | icon:若你不喜歡java給的圖標,你可以自己自定圖標. | 返回值為一整數值,依用戶按下什么鈕而定,YES_OPTION=0,NO_OPTION=1,CANCEL_OPTION=2,OK_OPTION=0 |,CLOSED_OPTION=-1(當用戶都不選直接關掉對話框時) ---------------------------------------------------------------------------------------------------------- Input Dialog ----------------------------------------------------------------------------------------------------------- 方法: |String showInputDialog(Object message) |String showInputDialog(Component parentComponent,Object message) |String showInputDialog(Component parentComponent,Object message,String title,int messageType) |Object showInputDailog(Component parentComponent,Object message,String title,int messageType,Icon icon | ,Object[] selectionValues,Object initialSelectionValue) |String showInternalInputDialog(Object message) |String showInternalInputDialog(Component parentComponent,Object message) |String showInternalInputDialog(Component parentComponent,Object message,String title,int messageType) |Object showInternalInputDialog(Component parentComponent,Object message,String title,int messageType, | Icon icon,Object[] selectionValues,Object initialSelectionValue) ----------------------------------------------------------------------------------------------------------- 說明: |顯示輸入對話框,這類的對話框可以讓用戶輸入相關的信息,當用戶按下確定鈕后,系統會得到用戶所輸入的信息.輸入 |對話框不僅可以讓用戶輸入文字,也可以提供Combo Box組件讓用戶選擇相關信息,避免用戶輸入錯誤.輸入對話框方法 |有6種參數: |parentComponent:是指產生對話框的組件為何,通常是指Frame或Dialog組件. | message:是指要顯示的組件,通常是String或Label類型 | title:對話框標題列上顯示的文字. | messageType:指定信息類型,共有5種類型,分別是ERROR_MESSAGE,INFORMATION_MESSAGE,WARING_MESSAGE, | QUESTION_MESSAGE,PLAIN_MESSAGE(不顯示圖標).指定類型后對話框就會出現相對應的圖標. | icon:若你不喜歡java給的圖標,你可以自己自定圖標. |selectionValues:給用戶選擇的可能值.Object Array中的數據會以ComboBox方式顯示出來. |initialSelectionValue:對話框初始化時所顯示的值. | 當用戶按下確定按鈕時會返回用戶輸入的信息,若按下取消按鈕則返回null. ------------------------------------------------------------------------------------------------------------- Option Dialog ------------------------------------------------------------------------------------------------------------- 方法: |int showOptionDialog(Component parentComponent,Object message,String title,int optionType,int | messageType,Icon icon,Object[] options,Object initalValue) |int showInternalOptionDialog(Component parentComponent,Object message,String title,int optionType, | int messageType,Icon icon,Object[] options,Object initialValue) ------------------------------------------------------------------------------------------------------------- 說明: |顯示選擇對話框,這類的對話框可以讓用戶自定義對話類型,最大的好處是可以改變按鈕上的文字.選擇對話框方法有 |6種參數: |parentComponent:是指產生對話框的組件為何,通常是指Frame或Dialog組件. | message:是指要顯示的組件,通常是String或Label類型 | title:對話框標題列上顯示的文字. | optionType:確定按鈕的類型,有5種類型,分別是DEFAULT_OPTION,YES_NO_OPTION,YES_NO_CANCEL,與 | OK_CANCEL_OPTION. | messageType:指定信息類型,共有5種類型,分別是ERROR_MESSAGE,INFORMATION_MESSAGE,WARING_MESSAGE, | QUESTION_MESSAGE,PLAIN_MESSAGE(不顯示圖標).指定類型后對話框就會出現相對應的圖標. | icon:若你不喜歡java給的圖標,你可以自己自定圖標. | options:給用戶選擇的按鈕顯示文字. | initalValue:對話框初始化時按鈕默認值. | 返回值為一整數值,依用戶按下什么鈕而定,YES_OPTION=0,NO_OPTION=1,CANCEL_OPTION=2,OK_OPTION=0 |,CLOSED_OPTION=-1(當用戶都不選直接關掉對話框時) ------------------------------------------------------------------------------------------------------------ 上面表格看起來好像很多方法似的,但實際上只區分成四大類,你只需要選擇要用哪類的對話框,再決定使用那類中的哪個方法即 可.我們慢慢來為你介紹這四個種類的對話框. 11-2-1:輸出Message Dialog Message Dialog是在對話框上顯示出一段信息,目的在告知用戶一些相關信息,因此Message Dialog只會有一個確定按鈕,讓用戶 看完信息后就可以關閉這個對話框.下面這個例子我們使用Message對話框,我們來看看不同的MessageType會有什么樣的圖案產生. MessageDialog.java import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.*; import com.incors.plaf.alloy.*; import com.incors.plaf.alloy.themes.glass.*; public class MessageDialog implements ActionListener{ JFrame f=null; public MessageDialog(){ f=new JFrame("optionPane"); Container contentPane=f.getContentPane(); contentPane.setLayout(new GridLayout(2,3)); JButton b=new JButton("Show Error Icon"); b.addActionListener(this); contentPane.add(b); b=new JButton("Show Information Icon"); b.addActionListener(this); contentPane.add(b); b=new JButton("Show Waring Icon"); b.addActionListener(this); contentPane.add(b); b=new JButton("Show Question Icon"); b.addActionListener(this); contentPane.add(b); b=new JButton("Show Plain Icon"); b.addActionListener(this); contentPane.add(b); b=new JButton("Show User Define Icon"); b.addActionListener(this); contentPane.add(b); f.pack(); f.setVisible(true); f.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } }); } public static void main(String[] args){ SwingUtil.setLookAndFeel(); new MessageDialog(); } public void actionPerformed(ActionEvent e){ String cmd=e.getActionCommand(); String title="Message Dialog"; String message=""; int type=JOptionPane.PLAIN_MESSAGE; if (cmd.equals("Show Error Icon")){ type=JOptionPane.ERROR_MESSAGE; message="Error Message"; }else if (cmd.equals("Show Information Icon")){ type=JOptionPane.INFORMATION_MESSAGE; message="information Message"; }else if (cmd.equals("Show Waring Icon")){ type=JOptionPane.WARNING_MESSAGE; message="Waring Message"; }else if (cmd.equals("Show Question Icon")){ type=JOptionPane.QUESTION_MESSAGE; message="Question Message"; }else if (cmd.equals("Show Plain Icon")){ type=JOptionPane.PLAIN_MESSAGE; message="Plain Message"; }else if (cmd.equals("Show User Define Icon")){ type=JOptionPane.PLAIN_MESSAGE; JOptionPane.showMessageDialog(f,message,title,type,new ImageIcon("..\\icons\\glass.jpg")); return ; } JOptionPane.showMessageDialog(f,message,title,type); } } class SwingUtil{ public static final void setLookAndFeel() { try{ Font font = new Font("JFrame", Font.PLAIN, 12); Enumeration keys = UIManager.getLookAndFeelDefaults().keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); if (UIManager.get(key) instanceof Font) { UIManager.put(key, font); } } AlloyLookAndFeel.setProperty("alloy.isLookAndFeelFrameDecoration", "true"); AlloyTheme theme = new GlassTheme(); LookAndFeel alloyLnF = new AlloyLookAndFeel(theme); JFrame.setDefaultLookAndFeelDecorated(true); UIManager.setLookAndFeel(alloyLnF); }catch(UnsupportedLookAndFeelException ex){ ex.printStackTrace(); } } } 11-2-2:輸出Confirm Dialog: 看過了信息對話框,接著我們來看確認對話框到底怎樣.Confirm Dialog目的在讓用戶對某個問題選擇"Yes"或"No",可算是一種 相當簡單的是非選擇對話框.下面這個范例中,用戶可選擇不同按鈕類型的確認對話框,為方便說明,在此我們將Message Type都默認 為JOptionPane.INFORMATION_MESSAGE. ConfirmDialog.java import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.*; import com.incors.plaf.alloy.*; import com.incors.plaf.alloy.themes.glass.*; public class ConfirmDialog implements ActionListener { JFrame f = null; JLabel label = null; public ConfirmDialog() { f = new JFrame("OptionPane Demo"); Container contentPane = f.getContentPane(); JPanel panel = new JPanel(); panel.setLayout(new GridLayout(2,2)); JButton b = new JButton("Show DEFAULT_OPTION"); b.addActionListener(this); panel.add(b); b = new JButton("Show YES_NO_OPTION"); b.addActionListener(this); panel.add(b); b = new JButton("Show YES_NO_CANCEL_OPTION"); b.addActionListener(this); panel.add(b); b = new JButton("Show OK_CANCEL_OPTION"); b.addActionListener(this); panel.add(b); label = new JLabel(" ",JLabel.CENTER); contentPane.add(label,BorderLayout.NORTH); contentPane.add(panel,BorderLayout.CENTER); f.pack(); f.setVisible(true); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } public static void main(String[] args) { SwingUtil.setLookAndFeel(); new ConfirmDialog(); } public void actionPerformed(ActionEvent e) { //處理用戶按鈕事件,默認的messageType是JoptionPane.INFORMATION_MESSAGE. String cmd = e.getActionCommand(); String title = "Confirm Dialog"; String message =""; int messageType = JOptionPane.INFORMATION_MESSAGE; int optionType = JOptionPane.YES_NO_OPTION; if(cmd.equals("Show DEFAULT_OPTION")) { optionType = JOptionPane.DEFAULT_OPTION; message = "Show DEFAULT_OPTION Buttons"; } else if(cmd.equals("Show YES_NO_OPTION")) { optionType = JOptionPane.YES_NO_OPTION; message = "Show YES_NO_OPTION Buttons"; } else if(cmd.equals("Show YES_NO_CANCEL_OPTION")) { optionType = JOptionPane.YES_NO_CANCEL_OPTION; message = "Show YES_NO_CANCEL_OPTION Buttons"; } else if(cmd.equals("Show OK_CANCEL_OPTION")) { optionType = JOptionPane.OK_CANCEL_OPTION; message = "Show OK_CANCEL_OPTION Buttons"; } int result = JOptionPane.showConfirmDialog(f, message, title, optionType, messageType); if (result == JOptionPane.YES_OPTION) label.setText("您選擇:Yes or OK"); if (result == JOptionPane.NO_OPTION) label.setText("您選擇:No"); if (result == JOptionPane.CANCEL_OPTION) label.setText("您選擇:Cancel"); if (result == JOptionPane.CLOSED_OPTION) label.setText("您沒做任何選擇,并關閉了對話框"); } } class SwingUtil{ public static final void setLookAndFeel() { try{ Font font = new Font("JFrame", Font.PLAIN, 12); Enumeration keys = UIManager.getLookAndFeelDefaults().keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); if (UIManager.get(key) instanceof Font) { UIManager.put(key, font); } } AlloyLookAndFeel.setProperty("alloy.isLookAndFeelFrameDecoration", "true"); AlloyTheme theme = new GlassTheme(); LookAndFeel alloyLnF = new AlloyLookAndFeel(theme); UIManager.setLookAndFeel(alloyLnF); }catch(UnsupportedLookAndFeelException ex){ ex.printStackTrace(); } } } 11-2-3:輸出Input Dialog: Input Dialog可以讓用戶輸入相關信息,當用戶按下確定鈕后,系統會得到用戶所輸入的信息.輸入對話框不僅可以讓用戶自輸入 文字,也可以顯示出ComboBox組件讓用戶選擇相關信息,避免用戶輸入錯誤,當用戶輸入完畢按下確定按鈕時會返回用戶輸入的信息, 若按下取消則返回null值.下面為InputDialog的范例. InputDialog.java import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.*; import com.incors.plaf.alloy.*; import com.incors.plaf.alloy.themes.glass.*; public class InputDialog implements ActionListener { JFrame f = null; JLabel label = null; public InputDialog() { f = new JFrame("OptionPane Demo"); Container contentPane = f.getContentPane(); JPanel panel = new JPanel(); panel.setLayout(new GridLayout(1,2)); JButton b = new JButton("Show Text Input"); b.addActionListener(this); panel.add(b); b = new JButton("Show ComboBox Input"); b.addActionListener(this); panel.add(b); label = new JLabel(" ",JLabel.CENTER); contentPane.add(label,BorderLayout.NORTH); contentPane.add(panel,BorderLayout.CENTER); f.pack(); f.setVisible(true); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } public static void main(String[] args) { SwingUtil.setLookAndFeel(); new InputDialog(); } public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); String title = "Input Dialog"; String message ="您最熟悉哪一種程序語言?"; int messageType = JOptionPane.QUESTION_MESSAGE; String[] values = {"JAVA","PHP","ASP","C++","VB"}; String result =""; if(cmd.equals("Show Text Input")) { result = JOptionPane.showInputDialog(f, message, title, messageType); } else if(cmd.equals("Show ComboBox Input")) { result = (String)JOptionPane.showInputDialog(f, message, title, messageType,null,values,values[0]); } if (result == null) label.setText("您取消了對話框"); else{ label.setText("您輸入:"+result); } } } class SwingUtil{ public static final void setLookAndFeel() { try{ Font font = new Font("JFrame", Font.PLAIN, 12); Enumeration keys = UIManager.getLookAndFeelDefaults().keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); if (UIManager.get(key) instanceof Font) { UIManager.put(key, font); } } AlloyLookAndFeel.setProperty("alloy.isLookAndFeelFrameDecoration", "true"); AlloyTheme theme = new GlassTheme(); LookAndFeel alloyLnF = new AlloyLookAndFeel(theme); UIManager.setLookAndFeel(alloyLnF); }catch(UnsupportedLookAndFeelException ex){ ex.printStackTrace(); } } } 11-2-3:輸出Option Dialog: Option Dialog可以讓用戶自定義對話框類型,比較具有彈性,最大的好處是可以改變按鈕上的文字.我們來看下面的例子: OptionDialog.java import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.*; import com.incors.plaf.alloy.*; import com.incors.plaf.alloy.themes.glass.*; public class OptionDialog implements ActionListener { JFrame f = null; JLabel label = null; public OptionDialog() { f = new JFrame("OptionPane Demo"); Container contentPane = f.getContentPane(); JButton b = new JButton("Show Option Dialog"); b.addActionListener(this); label = new JLabel(" ",JLabel.CENTER); contentPane.add(label,BorderLayout.NORTH); contentPane.add(b,BorderLayout.CENTER); f.pack(); f.setVisible(true); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } public static void main(String[] args) { SwingUtil.setLookAndFeel(); new OptionDialog(); } public void actionPerformed(ActionEvent e) { String title = "Option Dialog"; String message ="您喜歡吃漢堡嗎?"; int messageType = JOptionPane.QUESTION_MESSAGE; //由于我們的optionType設置成JOptionPane.YES_NO_CANCEL_OPTION,因此對話框中會有三個按鈕.我們在options //的String Arrray中設置這三個按鈕的名稱,并以options[1]按鈕為默認值,若將options參數設為null,系統會原來 //的按鈕名稱來顯示. int optionType = JOptionPane.YES_NO_CANCEL_OPTION; String[] options = {"喜歡","不喜歡","取消"}; int result = JOptionPane.showOptionDialog(f, message, title, optionType, messageType,null,options,options[1]); if (result == JOptionPane.YES_OPTION) label.setText("您選擇:喜歡"); if (result == JOptionPane.NO_OPTION) label.setText("您選擇:不喜歡"); if (result == JOptionPane.CANCEL_OPTION) label.setText("您選擇:取消"); if (result == JOptionPane.CLOSED_OPTION) label.setText("您沒做任何選擇,并關閉了對話框"); } } class SwingUtil{ public static final void setLookAndFeel() { try{ Font font = new Font("JFrame", Font.PLAIN, 12); Enumeration keys = UIManager.getLookAndFeelDefaults().keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); if (UIManager.get(key) instanceof Font) { UIManager.put(key, font); } } AlloyLookAndFeel.setProperty("alloy.isLookAndFeelFrameDecoration", "true"); AlloyTheme theme = new GlassTheme(); LookAndFeel alloyLnF = new AlloyLookAndFeel(theme); UIManager.setLookAndFeel(alloyLnF); }catch(UnsupportedLookAndFeelException ex){ ex.printStackTrace(); } } } 11-2-5:輸出Internal Dialog: 我們之前曾經說過,JOptionPane也可以顯示出Internal Dialog對話框,使用方法跟上面的范例一模一樣,只是在方法名稱上多 了Internal這個字眼,例如showInternalMessageDialog()等等,我們來看下面的范例: import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.*; import com.incors.plaf.alloy.*; import com.incors.plaf.alloy.themes.glass.*; public class InternalDialog implements ActionListener { JInternalFrame internalFrame = null; JLabel label = null; public InternalDialog() { JFrame f = new JFrame("OptionPane Demo"); Container contentPane = f.getContentPane(); JDesktopPane desktopPane = new JDesktopPane(); internalFrame = new JInternalFrame( "Internal Frame", true, true, true, true); internalFrame.setLocation( 20,20); internalFrame.setSize(200,200); internalFrame.setVisible(true); Container icontentPane = internalFrame.getContentPane(); JButton b = new JButton("Show Internal Dialog"); b.addActionListener(this); icontentPane.add(b,BorderLayout.CENTER); label = new JLabel(" ",JLabel.CENTER); icontentPane.add(label,BorderLayout.NORTH); desktopPane.add(internalFrame); contentPane.add(desktopPane,BorderLayout.CENTER); f.setSize(350, 350); f.setVisible(true); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } public static void main(String[] args) { SwingUtil.setLookAndFeel(); new InternalDialog(); } public void actionPerformed(ActionEvent e) { String title = "Option Dialog"; String message ="您喜歡吃漢堡嗎?"; int messageType = JOptionPane.QUESTION_MESSAGE; int optionType = JOptionPane.YES_NO_CANCEL_OPTION; String[] options = {"喜歡","不喜歡","取消"}; int result = JOptionPane.showInternalOptionDialog(internalFrame, message, title, optionType, messageType,null,options,options[1]); if (result == JOptionPane.YES_OPTION) label.setText("您選擇:喜歡"); if (result == JOptionPane.NO_OPTION) label.setText("您選擇:不喜歡"); if (result == JOptionPane.CANCEL_OPTION) label.setText("您選擇:取消"); if (result == JOptionPane.CLOSED_OPTION) label.setText("您沒做任何選擇,并關閉了對話框"); } } class SwingUtil{ public static final void setLookAndFeel() { try{ Font font = new Font("JFrame", Font.PLAIN, 12); Enumeration keys = UIManager.getLookAndFeelDefaults().keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); if (UIManager.get(key) instanceof Font) { UIManager.put(key, font); } } AlloyLookAndFeel.setProperty("alloy.isLookAndFeelFrameDecoration", "true"); AlloyTheme theme = new GlassTheme(); LookAndFeel alloyLnF = new AlloyLookAndFeel(theme); UIManager.setLookAndFeel(alloyLnF); }catch(UnsupportedLookAndFeelException ex){ ex.printStackTrace(); } } } 讀者在使用Internal Dialog時要特別注意,一般我們利用JOptionPane所產生的對話框均是modal為true狀態,可是當你使用 Internal Dialog時對話框會變成modal為false狀態.因此你可以不用關閉之前的對話框,就可以再按一次按鈕,再產生一個Internal Dialog.你再運行上一例操作后就知道了. 若你想將JInternalFrame內的Internal Dialog model設為true,你可以有下面兩種解決方法: 1.你可以建立JOptionPane對象,而非直接去調用JOptionPane的static方法來輸出對話框.然后利用JOptionPane的createDialog()方 法,取得JDialog對象,再利用Dialog(JDialog繼承Dialog)所提供的setModal()方法將modal設為true. 2.直接使用JDialog. 11-3:使用JOptionPane組件建立對話框: 我們在11-2節中已經介紹了JOptionPane的構造函數,雖然大部份的情況下我們只需要使用JOptionPane的靜態方法來產生對話框 ,但如果你想直接使用JOptionPane對象來產生對話框,當然也可以.下面我們就舉一個以JOptionPane對象產生對話框的范例: import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.*; import com.incors.plaf.alloy.*; import com.incors.plaf.alloy.themes.glass.*; public class OptionPaneDemo implements ActionListener { JFrame f = null; JLabel label = null; public OptionPaneDemo() { f = new JFrame("OptionPane Demo"); Container contentPane = f.getContentPane(); JButton b = new JButton("Show Text Input"); b.addActionListener(this); label = new JLabel(" ",JLabel.CENTER); contentPane.add(label,BorderLayout.NORTH); contentPane.add(b,BorderLayout.CENTER); f.pack(); f.setVisible(true); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } public static void main(String[] args) { SwingUtil.setLookAndFeel(); new OptionPaneDemo(); } public void actionPerformed(ActionEvent e) { String title = "Input Dialog"; JLabel message =new JLabel("您最喜歡吃什么食物?",JLabel.CENTER); int messageType = JOptionPane.QUESTION_MESSAGE; int optionType = JOptionPane.OK_CANCEL_OPTION; String result =""; //利用message,messageType,optionType來建立JOptionPane對象 JOptionPane optionPane = new JOptionPane(message,messageType,optionType); //利用JOptionPane的setWandtsInput()方法,使對話框有一個輸入字段讓用戶輸入信息 optionPane.setWantsInput(true); //利用JOptionPane的setInitialSelectionValue()方法,使得輸入字段上的初始值為"請輸入"; optionPane.setInitialSelectionValue("請輸入!"); //利用JOptionPane的setInputValue()方法,使得當用戶按下"Cancel"鍵或關閉對話框時,result的默認字符串為 //"你沒有輸入"; optionPane.setInputValue("您沒有輸入!"); JDialog dialog = optionPane.createDialog(f, title); dialog.show(); //JOptionPane的getInputValue()方法可以取得用戶輸入的信息. result = (String)optionPane.getInputValue(); label.setText("您輸入:"+result); } } class SwingUtil{ public static final void setLookAndFeel() { try{ Font font = new Font("JFrame", Font.PLAIN, 12); Enumeration keys = UIManager.getLookAndFeelDefaults().keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); if (UIManager.get(key) instanceof Font) { UIManager.put(key, font); } } AlloyLookAndFeel.setProperty("alloy.isLookAndFeelFrameDecoration", "true"); AlloyTheme theme = new GlassTheme(); LookAndFeel alloyLnF = new AlloyLookAndFeel(theme); UIManager.setLookAndFeel(alloyLnF); }catch(UnsupportedLookAndFeelException ex){ ex.printStackTrace(); } } } |