做桌面應用時,各種提示、確認、輸入對話框幾乎無所不在。Java Swing 的 JOptionPane 把這些常見對話框都標準化了,非常好用。本文透過一個完整範例,示範錯誤提示、確認、警告、輸入、選擇等各類對話框的實現方式。
以下程式建立一個工具列,上面擺放六個按鈕,點擊各按鈕便會彈出對應類型的對話框:
package test001;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JToolBar;
public class TestJOptionPane implements ActionListener{
private JFrame jf = new JFrame("標准對話框測試");
public static void main(String[] args) {
new TestJOptionPane().createUI();
}
public void createUI(){
JToolBar jtb = new JToolBar();
String[] s = {"錯誤", "退出確認1", "退出確認2", "警告", "輸入", "選擇"};
int size = s.length;
JButton[] button = new JButton[size];
for(int i = 0; i < size; i++){
button[i] = new JButton(s[i]);
button[i].addActionListener(this);
jtb.add(button[i]);
}
jf.add(jtb, "North");
jf.setSize(350, 150);
jf.setLocation(400, 200);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
String s = e.getActionCommand();
if(s.equals("錯誤")){
JOptionPane.showMessageDialog(null, "要顯示的錯誤信息---",
"錯誤提示",JOptionPane.ERROR_MESSAGE);
}
else if(s.equals("退出確認1")){
int result = JOptionPane.showConfirmDialog(null,
"推出前是否保存程序?");
if(result == JOptionPane.YES_OPTION){
System.out.println("保存程序---");
System.exit(0);
}
else if(result == JOptionPane.NO_OPTION){
System.exit(0);
}
}
else if(s.equals("退出確認2")){
int result = JOptionPane.showConfirmDialog(null, "退出前是否保存程序?");
if(result == JOptionPane.YES_OPTION){
System.out.println("保存程序---");
System.exit(0);
}
else if(result == JOptionPane.NO_OPTION){
System.exit(0);
}
}
else if(s.equals("警告")){
Object[] options = {"繼續", "撤銷"};
int result = JOptionPane.showOptionDialog(null,
"本操作可能導致數據丟失","Warning", JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE, null, options, options[0]);
if(result == 0){
System.out.println("繼續操作---");
}
}
else if(s.equals("輸入")){
String name = JOptionPane.showInputDialog("請輸入您的姓名:");
if(name != null){
System.out.println("姓名:" + name);
}
}
else if(s.equals("選擇")){
Object[] possibleValues = {"體育", "政治", "經濟", "文化"};
Object selectedValue = JOptionPane.showInputDialog(null,
"Choose one","Input", JOptionPane.INFORMATION_MESSAGE, null,
possibleValues, possibleValues[0]);
String choose = (String)selectedValue;
if(choose != null){
System.out.println("你選擇的是:"+ choose);
}
}
}
}
以下幾張圖分別展示了各類對話框的運行效果:






從程式碼可以歸納出幾個常用方法:showMessageDialog 用於純訊息提示;showConfirmDialog 回傳 YES_OPTION / NO_OPTION 等常數,適合做「是否」確認;showOptionDialog 可自訂按鈕選項,靈活度最高;showInputDialog 則同時支援文字輸入與下拉式選擇。把這幾個方法摸熟,Swing 桌面應用裡的大小互動對話框就都能應付自如了。