最近在做swing程序中遇到使用消息提示框的,JOptionPane類其中封裝了很多的方法。
很方便的,於是就簡單的整理了一下。
1.1 showMessageDialog
顯示一個帶有OK 按鈕的模態對話框。
下面是幾個使用showMessageDialog 的例子:
import javax.swing.JOptionPane; //導包 public class showMessageDialogDemo { public static void main(String[] args) { JOptionPane.showMessageDialog(null, "友情提示"); } }
效果如下:
import java.awt.Component;
import javax.swing.JOptionPane;
public class showMessageDialogDemo {
private static Component jPanel;
public static void main(String[] args) {
JOptionPane.showMessageDialog(jPanel, "提示消息", "標題",JOptionPane.WARNING_MESSAGE);
}
}
效果如下:
1.2 showOptionDialog
這個函數可以改變顯示在按鈕上的文字。你還可以執行更多的個性化操作。
常規的消息框:
int n = JOptionPane.showConfirmDialog(null, "你高興嗎?", "標題",JOptionPane.YES_NO_OPTION);//i=0/1 System.out.println("n:" + n); //高興 - 0 , 不高興 - 1
效果如下:
個性話消息框:
Object[] options ={ "好啊!", "去一邊!" }; int m = JOptionPane.showOptionDialog(null, "我可以約你嗎?", "標題",JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); System.out.println("m:" + m); //好啊! -- 0 , 去一邊! -- 1
效果如下:
1.3 showInoutDialog
該方法返回一個Object 類型。這個Object 類型一般是一個String 類型,反應了用戶的輸入。
下拉列表形式的例子:
Object[] obj2 ={ "足球", "籃球", "乒乓球","網球" }; String s = (String) JOptionPane.showInputDialog(null,"請選擇你的愛好:\n", "愛好", JOptionPane.PLAIN_MESSAGE, new ImageIcon("icon.png"), obj2, "網球"); System.out.println("s:"+s);
文本框形式的例子:
private static Icon icon;
String s = (String) JOptionPane.showInputDialog(null,"請輸入你的愛好:\n","title",JOptionPane.PLAIN_MESSAGE,icon,null,"在這輸入"); System.out.println("s:"+s);
對應的小圖標可參照下圖:
下面是本文檔所有的參考代碼:
package will01; import java.awt.Component; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JOptionPane; public class showMessageDialogDemo { private static Component jPanel; private static Icon icon; public static void main(String[] args) { //JOptionPane.showMessageDialog(null, "友情提示"); //JOptionPane.showMessageDialog(jPanel, "提示消息", "標題",JOptionPane.WARNING_MESSAGE); //JOptionPane.showMessageDialog(null, "提示消息.", "標題",JOptionPane.ERROR_MESSAGE); //JOptionPane.showMessageDialog(null, "提示消息.", "標題",JOptionPane.PLAIN_MESSAGE); //int n = JOptionPane.showConfirmDialog(null, "你高興嗎?", "標題",JOptionPane.YES_NO_OPTION);//i=0/1 //System.out.println("n:" + n); //高興 - 0 , 不高興 - 1 //Object[] options ={ "好啊!", "去一邊!" }; //int m = JOptionPane.showOptionDialog(null, "我可以約你嗎?", "標題",JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); //System.out.println("m:" + m); //好啊! -- 0 , 去一邊! -- 1 //Object[] obj2 ={ "足球", "籃球", "乒乓球","網球" }; //String s = (String) JOptionPane.showInputDialog(null,"請選擇你的愛好:\n", "愛好", JOptionPane.PLAIN_MESSAGE, new ImageIcon("icon.png"), obj2, "網球"); //System.out.println("s:"+s); String s = (String) JOptionPane.showInputDialog(null,"請輸入你的愛好:\n","title",JOptionPane.PLAIN_MESSAGE,icon,null,"在這輸入"); System.out.println("s:"+s); } }
參考文檔: https://www.cnblogs.com/guohaoyu110/p/6440333.html