今天還是繼續我們的JAVA的GUI,前幾天講了AWT,這個太重了。Swing開發圖形界面比AWT更加優秀,切實輕量級的,100%的Java實現,唯一的缺點就是比AWT略慢。
先講下Swing和AWT組件的相似處,以下圖顯示相同的組件
Swing多出來的組件
組件比較多,那些和AWT相同的組件用起來差不多,我就不多講了,就貼段全面的代碼讓大家把玩下,eg
- public class SwingComponent
- {
- JFrame f = new JFrame("測試");
- //定義一個按鈕,並為之指定圖標
- Icon okIcon = new ImageIcon("ico/ok.png");
- JButton ok = new JButton("確認" , okIcon);
- //定義一個單選按鈕,初始處於選中狀態
- JRadioButton male = new JRadioButton("男" , true);
- //定義一個單按鈕,初始處於沒有選中狀態
- JRadioButton female = new JRadioButton("女" , false);
- //定義一個ButtonGroup,用於將上面兩個JRadioButton組合在一起
- ButtonGroup bg = new ButtonGroup();
- //定義一個復選框,初始處於沒有選中狀態。
- JCheckBox marrIEd = new JCheckBox("是否已婚?" , false);
- String[] colors = new String[]{"紅色" , "綠色" , "藍色"};
- //定義一個下拉選擇框
- JComboBox colorChooser = new JComboBox(colors);
- //定義一個列表選擇框
- JList colorList = new JList(colors);
- //定義一個8行、20列的多行文本域
- JTextArea ta = new JTextArea(8, 20);
- //定義一個40列的單行文本域
- JTextFIEld name = new JTextFIEld(40);
- JMenuBar mb = new JMenuBar();
- JMenu file = new JMenu("文件");
- JMenu edit = new JMenu("編輯");
- //創建“新建”菜單項,並為之指定圖標
- Icon newIcon = new ImageIcon("ico/new.png");
- JMenuItem newItem = new JMenuItem("新建" , newIcon);
- //創建“保存”菜單項,並為之指定圖標
- Icon saveIcon = new ImageIcon("ico/save.png");
- JMenuItem saveItem = new JMenuItem("保存" , saveIcon);
- //創建“退出”菜單項,並為之指定圖標
- Icon exitIcon = new ImageIcon("ico/exit.png");
- JMenuItem exitItem = new JMenuItem("退出" , exitIcon);
- JCheckBoxMenuItem autoWrap = new JCheckBoxMenuItem("自動換行");
- //創建“復制”菜單項,並為之指定圖標
- JMenuItem copyItem = new JMenuItem("復制" , new ImageIcon("ico/copy.png"));
- //創建“粘貼”菜單項,並為之指定圖標
- JMenuItem pasteItem = new JMenuItem("粘貼" , new ImageIcon("ico/paste.png"));
- JMenu format = new JMenu("格式");
- JMenuItem commentItem = new JMenuItem("注釋");
- JMenuItem cancelItem = new JMenuItem("取消注釋");
- //定義一個右鍵菜單用於設置程序風格
- JPopupMenu pop = new JPopupMenu();
- //用於組合三個風格菜單項的ButtonGroup
- ButtonGroup flavorGroup = new ButtonGroup();
- //創建三個單選框按鈕,用於設定程序的外觀風格
- JRadioButtonMenuItem metalItem = new JRadioButtonMenuItem("Metal風格" , true);
- JRadioButtonMenuItem WindowsItem = new JRadioButtonMenuItem("Windows風格");
- JRadioButtonMenuItem motifItem = new JRadioButtonMenuItem("Motif風格");
- public void init()
- {
- //創建一個裝載了文本框、按鈕的JPanel
- JPanel bottom = new JPanel();
- bottom.add(name);
- bottom.add(ok);
- f.add(bottom , BorderLayout.SOUTH);
- //創建一個裝載了下拉選擇框、三個JCheckBox的JPanel
- JPanel checkPanel = new JPanel();
- checkPanel.add(colorChooser);
- bg.add(male);
- bg.add(female);
- checkPanel.add(male);
- checkPanel.add(female);
- checkPanel.add(marrIEd);
- //創建一個垂直排列組件的Box,盛裝多行文本域JPanel
- Box topLeft = Box.createVerticalBox();
- //使用JScrollPane作為普通組件的JVIEwPort
- JScrollPane taJSP = new JScrollPane(ta);
- topLeft.add(taJSP);
- topLeft.add(checkPanel);
- //創建一個垂直排列組件的Box,盛裝topLeft、colorList
- Box top = Box.createHorizontalBox();
- top.add(topLeft);
- top.add(colorList);
- //將top Box容器添加到窗口的中間
- f.add(top);
- //-----------下面開始組合菜單、並為菜單添加事件監聽器----------
- //為newItem設置快捷鍵,設置快捷鍵時要使用大寫字母
- newItem.setAccelerator(KeyStroke.getKeyStroke('N' , InputEvent.CTRL_MASK));
- newItem.addActionListener(new ActionListener()
- {
- public void actionPerformed(ActionEvent e)
- {
- ta.append("用戶單擊了“新建”菜單/n");
- }
- });
- //為file菜單添加菜單項
- file.add(newItem);
- file.add(saveItem);
- file.add(exitItem);
- //為edit菜單添加菜單項
- edit.add(autoWrap);
- //使用addSeparator方法來添加菜單分隔線
- edit.addSeparator();
- edit.add(copyItem);
- edit.add(pasteItem);
- commentItem.setToolTipText("將程序代碼注釋起來!");
- //為format菜單添加菜單項
- format.add(commentItem);
- format.add(cancelItem);
- //使用添加new JMenuItem("-")的方式不能添加菜單分隔符
- edit.add(new JMenuItem("-"));
- //將format菜單組合到edit菜單中,從而形成二級菜單
- edit.add(format);
- //將file、edit菜單添加到mb菜單條中
- mb.add(file);
- mb.add(edit);
- //為f窗口設置菜單條
- f.setJMenuBar(mb);
- //-----------下面開始組合右鍵菜單、並安裝右鍵菜單----------
- flavorGroup.add(metalItem);
- flavorGroup.add(WindowsItem);
- flavorGroup.add(motifItem);
- pop.add(metalItem);
- pop.add(WindowsItem);
- pop.add(motifItem);
- //為三個菜單創建事件監聽器
- ActionListener flavorListener = new ActionListener()
- {
- public void actionPerformed(ActionEvent e)
- {
- try
- {
- if (e.getActionCommand().equals("Metal風格"))
- {
- changeFlavor(1);
- }
- else if (e.getActionCommand().equals("Windows風格"))
- {
- changeFlavor(2);
- }
- else if (e.getActionCommand().equals("Motif風格"))
- {
- changeFlavor(3);
- }
- }
- catch (Exception ee)
- {
- ee.printStackTrace();
- }
- }
- };
- //為三個菜單添加事件監聽器
- metalItem.addActionListener(flavorListener);
- WindowsItem.addActionListener(flavorListener);
- motifItem.addActionListener(flavorListener);
- //調用該方法即可設置右鍵菜單,無需使用事件機制
- ta.setComponentPopupMenu(pop);
- //設置關閉窗口時,退出程序
- f.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
- f.pack();
- f.setVisible(true);
- }
- //定義一個方法,用於改變界面風格
- private void changeFlavor(int flavor)throws Exception
- {
- switch (flavor)
- {
- //設置Metal風格
- case 1:
- UIManager.setLookAndFeel("Javax.swing.plaf.metal.MetalLookAndFeel");
- break;
- //設置Windows風格
- case 2:
- UIManager.setLookAndFeel("com.sun.Java.swing.plaf.windows.WindowsLookAndFeel");
- break;
- //設置Motif風格
- case 3:
- UIManager.setLookAndFeel("com.sun.Java.swing.plaf.motif.MotifLookAndFeel");
- break;
- }
- //更新f窗口內頂級容器以及內部所有組件的UI
- SwingUtilitIEs.updateComponentTreeUI(f.getContentPane());
- //更新mb菜單條以及內部所有組件的UI
- SwingUtilitIEs.updateComponentTreeUI(mb);
- //更新pop右鍵菜單以及內部所有組件的UI
- SwingUtilitIEs.updateComponentTreeUI(pop);
- }
- public static void main(String[] args)
- {
- //設置Swing窗口使用Java風格
- JFrame.setDefaultLookAndFeelDecorated(true);
- new SwingComponent().init();
- }
- }
下面Swing的特殊組件,我將以舉例的形式,這樣最能主觀理解,大家一定要動手試試
首先是JToolBar
- public class TestJToolBar
- {
- JFrame jf = new JFrame("測試工具條");
- JTextArea jta = new JTextArea(6, 35);
- JToolBar jtb = new JToolBar();
- JMenuBar jmb = new JMenuBar();
- JMenu edit = new JMenu("編輯");
- Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
- //創建"粘貼"Action,該Action用於創建菜單項、工具按鈕和普通按鈕
- Action pasteAction = new AbstractAction("粘貼", new ImageIcon("ico/paste.png"))
- {
- public void actionPerformed(ActionEvent e)
- {
- //如果剪貼板中包含stringFlavor內容
- if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor))
- {
- try
- {
- //取出剪貼板中stringFlavor內容
- String content = (String)clipboard.getData(DataFlavor.stringFlavor);
- //將選中內容替換成剪貼板中的內容
- jta.replaceRange(content , jta.getSelectionStart() , jta.getSelectionEnd());
- }
- catch (Exception ee)
- {
- ee.printStackTrace();
- }
- }
- }
- };
- //創建"復制"Action
- Action copyAction = new AbstractAction("復制", new ImageIcon("ico/copy.png"))
- {
- public void actionPerformed(ActionEvent e)
- {
- StringSelection contents = new StringSelection(jta.getSelectedText());
- //將StringSelection對象放入剪貼板
- clipboard.setContents(contents, null);
- //如果剪貼板中包含stringFlavor內容
- if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor))
- {
- //將pasteAction激活
- pasteAction.setEnabled(true);
- }
- }
- };
- public void init()
- {
- //pasteAction默認處於不激活狀態
- pasteAction.setEnabled(false);
- jf.add(new JScrollPane(jta));
- //以Action創建按鈕,並將該按鈕添加到Panel中
- JButton copyBn = new JButton(copyAction);
- JButton pasteBn = new JButton(pasteAction);
- JPanel jp = new JPanel();
- jp.add(copyBn);
- jp.add(pasteBn);
- jf.add(jp , BorderLayout.SOUTH);
- //向工具條中添加Action對象,該對象將會轉換成工具按鈕
- jtb.add(copyAction);
- jtb.addSeparator();
- jtb.add(pasteAction);
- //向菜單中添加Action對象,該對象將會轉換成菜單項
- edit.add(copyAction);
- edit.add(pasteAction);
- //將edit菜單添加到菜單條中
- jmb.add(edit);
- jf.setJMenuBar(jmb);
- //設置工具條和工具按鈕之間的距離
- jtb.setMargin(new Insets(20 ,10 , 5 , 30));
- //向窗口中添加工具條
- jf.add(jtb , BorderLayout.NORTH);
- jf.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
- jf.pack();
- jf.setVisible(true);
- }
- public static void main(String[] args)
- {
- new TestJToolBar().init();
- }
- }
繼續講Swing的特殊組件,JColorChooser和JFileChooser這兩個東西在awt中都是利用系統的控件,這樣導致不同操作系統有不同的界面,用Swing就避免了這些問題。下面就先看JColorChooser的例子,eg(一個簡單畫圖程序)
- public class HandDraw
- {
- //畫圖區的寬度
- private final int AREA_WIDTH = 500;
- //畫圖區的高度
- private final int AREA_HEIGHT = 400;
- //下面的preX、preY保存了上一次鼠標拖動事件的鼠標座標
- private int preX = -1;
- private int preY = -1;
- //定義一個右鍵菜單用於設置畫筆顏色
- JPopupMenu pop = new JPopupMenu();
- JMenuItem chooseColor = new JMenuItem("選擇顏色");
- //定義一個BufferedImage對象
- BufferedImage image = new BufferedImage(AREA_WIDTH , AREA_HEIGHT ,
- BufferedImage.TYPE_INT_RGB);
- //獲取image對象的Graphics
- Graphics g = image.getGraphics();
- private JFrame f = new JFrame("簡單手繪程序");
- private DrawCanvas drawArea = new DrawCanvas();
- //用於保存需要繪制什麼圖形的字符串屬性
- private String shape = "";
- //用於保存畫筆顏色
- private Color foreColor = new Color(255, 0 ,0);
- public void init()
- {
- chooseColor.addActionListener(new ActionListener()
- {
- public void actionPerformed(ActionEvent ae)
- {
- //下面代碼直接彈出一個模式的顏色選擇器對話框,並返回用戶選擇的顏色
- //foreColor = JColorChooser.showDialog(f , "選擇畫筆顏色" , foreColor);
- //下面代碼則可以彈出一個非模式的顏色選擇對話框,
- //並可以分別為“確定”按鈕、“取消”按鈕指定事件監聽器
- final JColorChooser colorPane = new JColorChooser(foreColor);
- JDialog jd = JColorChooser.createDialog(f ,"選擇畫筆顏色",false,
- colorPane, new ActionListener()
- {
- public void actionPerformed(ActionEvent ae)
- {
- foreColor = colorPane.getColor();
- }
- }, null);
- jd.setVisible(true);
- }
- });
- //將菜單項組合成右鍵菜單
- pop.add(chooseColor);
- //將右鍵菜單添加到drawArea對象中
- drawArea.setComponentPopupMenu(pop);
- //將image對象的背景色填充成白色
- g.fillRect(0 , 0 ,AREA_WIDTH , AREA_HEIGHT);
- drawArea.setPreferredSize(new Dimension(AREA_WIDTH , AREA_HEIGHT));
- //監聽鼠標移動動作
- drawArea.addMouseMotionListener(new MouseMotionAdapter()
- {
- //實現按下鼠標鍵並拖動的事件處理器
- public void mouseDragged(MouseEvent e)
- {
- //如果preX和preY大於0
- if (preX > 0 && preY > 0)
- {
- //設置當前顏色
- g.setColor(foreColor);
- //繪制從上一次鼠標拖動事件點到本次鼠標拖動事件點的線段
- g.drawLine(preX , preY , e.getX() , e.getY());
- }
- //將當前鼠標事件點的X、Y座標保存起來
- preX = e.getX();
- preY = e.getY();
- //重繪drawArea對象
- drawArea.repaint();
- }
- });
- //監聽鼠標事件
- drawArea.addMouseListener(new MouseAdapter()
- {
- //實現鼠標松開的事件處理器
- public void mouseReleased(MouseEvent e)
- {
- //松開鼠標鍵時,把上一次鼠標拖動事件的X、Y座標設為-1。
- preX = -1;
- preY = -1;
- }
- });
- f.add(drawArea);
- f.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
- f.pack();
- f.setVisible(true);
- }
- public static void main(String[] args)
- {
- new HandDraw().init();
- }
- //讓畫圖區域繼承JPanel類
- class DrawCanvas extends JPanel
- {
- //重寫JPanel的paint方法,實現繪畫
- public void paint(Graphics g)
- {
- //將image繪制到該組件上
- g.drawImage(image , 0 , 0 , null);
- }
- }
- }
下面舉個JFileChooser,這些東西組件不是很常用,大家可以收藏著,到用的時候翻出來看,eg
- public class ImageVIEwer
- {
- final int PREVIEW_SIZE = 100;
- JFrame jf = new JFrame("簡單圖片查看器");
- JMenuBar menuBar = new JMenuBar();
- //該label用於顯示圖片
- JLabel label = new JLabel();
- //以當前路徑創建文件選擇器
- JFileChooser chooser = new JFileChooser(".");
- JLabel Accessory = new JLabel();
- ExtensionFileFilter filter = new ExtensionFileFilter();
- public void init()
- {
- //-------------------下面開始初始化JFileChooser的相關屬性-----------------
- // 創建一個FileFilter
- filter.addExtension("jpg");
- filter.addExtension("jpeg");
- filter.addExtension("gif");
- filter.addExtension("png");
- filter.setDescription("圖片文件(*.jpg,*.jpeg,*.gif,*.png)");
- chooser.addChoosableFileFilter(filter);
- //禁止“文件類型”下拉列表中顯示“所有文件”選項。
- chooser.setAcceptAllFileFilterUsed(false);
- //為文件選擇器指定自定義的FileVIEw對象
- chooser.setFileVIEw(new FileIconVIEw(filter));
- //為文件選擇器指定一個預覽圖片的附件組件
- chooser.setAccessory(Accessory);
- //設置預覽圖片組件的大小和邊框
- Accessory.setPreferredSize(new Dimension(PREVIEW_SIZE, PREVIEW_SIZE));
- Accessory.setBorder(BorderFactory.createEtchedBorder());
- //用於檢測被選擇文件的改變事件
- chooser.addPropertyChangeListener(new PropertyChangeListener()
- {
- public void propertyChange(PropertyChangeEvent event)
- {
- //JFileChooser的被選文件已經發生了改變
- if (event.getPropertyName() == JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)
- {
- //獲取用戶選擇的新文件
- File f = (File) event.getNewValue();
- if (f == null)
- {
- Accessory.setIcon(null);
- return;
- }
- //將所文件讀入ImageIcon對象中
- ImageIcon icon = new ImageIcon(f.getPath());
- //如果圖像太大,則縮小它
- if(icon.getIconWidth() > PREVIEW_SIZE)
- {
- icon = new ImageIcon(icon.getImage()
- .getScaledInstance(PREVIEW_SIZE, -1, Image.SCALE_DEFAULT));
- }
- //改變Accessory Label的圖標
- Accessory.setIcon(icon);
- }
- }
- });
- //----------下面代碼開始為該窗口安裝菜單------------
- JMenu menu = new JMenu("文件");
- menuBar.add(menu);
- JMenuItem openItem = new JMenuItem("打開");
- menu.add(openItem);
- //單擊openItem菜單項顯示“打開文件”的對話框
- openItem.addActionListener(new ActionListener()
- {
- public void actionPerformed(ActionEvent event)
- {
- //設置文件對話框的當前路徑
- //chooser.setCurrentDirectory(new File("."));
- //顯示文件對話框
- int result = chooser.showDialog(jf , "打開圖片文件");
- //如果用戶選擇了APPROVE(贊同)按鈕,即打開,保存及其等效按鈕
- if(result == JFileChooser.APPROVE_OPTION)
- {
- String name = chooser.getSelectedFile().getPath();
- //顯示指定圖片
- label.setIcon(new ImageIcon(name));
- }
- }
- });
- JMenuItem exitItem = new JMenuItem("退出");
- menu.add(exitItem);
- exitItem.addActionListener(new ActionListener()
- {
- public void actionPerformed(ActionEvent event)
- {
- System.exit(0);
- }
- });
- jf.setJMenuBar(menuBar);
- //添加用於顯示圖片的JLabel組件。
- jf.add(new JScrollPane(label));
- jf.setSize(500, 400);
- jf.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
- jf.setVisible(true);
- }
- public static void main(String[] args)
- {
- new ImageVIEwer().init();
- }
- }
- //創建FileFilter的子類,用以實現文件過濾功能
- class ExtensionFileFilter extends FileFilter
- {
- private String description = "";
- private ArrayList<String> extensions = new ArrayList<String>();
- //自定義方法,用於添加文件擴展名
- public void addExtension(String extension)
- {
- if (!extension.startsWith("."))
- {
- extension = "." + extension;
- extensions.add(extension.toLowerCase());
- }
- }
- //用於設置該文件過濾器的描述文本
- public void setDescription(String aDescription)
- {
- description = aDescription;
- }
- //繼承FileFilter類必須實現的抽象方法,返回該文件過濾器的描述文本
- public String getDescription()
- {
- return description;
- }
- //繼承FileFilter類必須實現的抽象方法,判斷該文件過濾器是否接受該文件
- public boolean accept(File f)
- {
- //如果該文件是路徑,接受該文件
- if (f.isDirectory()) return true;
- //將文件名轉為小寫(全部轉為小寫後比較,用於忽略文件名大小寫)
- String name = f.getName().toLowerCase();
- //遍歷所有可接受的擴展名,如果擴展名相同,該文件就可接受。
- for (String extension : extensions)
- {
- if (name.endsWith(extension))
- {
- return true;
- }
- }
- return false;
- }
- }
- //自定義一個FileVIEw類,用於為指定類型的指定圖標
- class FileIconVIEw extends FileVIEw
- {
- private FileFilter filter;
- public FileIconVIEw(FileFilter filter)
- {
- this.filter = filter;
- }
- //如果文件不是目錄,並且不是
- public Icon getIcon(File f)
- {
- if (!f.isDirectory() && filter.accept(f))
- {
- return new ImageIcon("ico/pict.png");
- }
- else if (f.isDirectory())
- {
- //獲取所有根路徑
- File[] fList = File.listRoots();
- for (File tmp : fList)
- {
- //如果該路徑是根路徑
- if (tmp.equals(f))
- {
- return new ImageIcon("ico/dsk.png");
- }
- }
- return new ImageIcon("ico/folder.png");
- }
- //使用默認圖標
- else
- {
- return null;
- }
- }
- }
注意:以上圖片我都沒給,自己隨便弄幾張看看效果
JOptionPane是一種特殊的JFrame,他的出現是為了方便我們創建一些簡單的對話框,你也可以用JFrame搞一個,但很繁瑣,但如果你用UI的拖拽工具那就沒什麼了。eg(各種對話框)
- public class TestJOptionPane
- {
- JFrame jf = new JFrame("測試JOptionPane");
- //分別定義6個面板用於定義對話框的幾種選項
- private ButtonPanel messagePanel;
- private ButtonPanel messageTypePanel;
- private ButtonPanel msgPanel;
- private ButtonPanel confirmPanel;
- private ButtonPanel optionsPanel;
- private ButtonPanel inputPanel;
- private String messageString = "消息區內容";
- private Icon messageIcon = new ImageIcon("ico/heart.png");
- private Object messageObject = new Date();
- private Component messageComponent = new JButton("組件消息");
- private JButton msgBn = new JButton("消息對話框");
- private JButton confrimBn = new JButton("確認對話框");
- private JButton inputBn = new JButton("輸入對話框");
- private JButton optionBn = new JButton("選項對話框");
- public void init()
- {
- JPanel top = new JPanel();
- top.setBorder(new TitledBorder(new EtchedBorder(), "對話框的通用選項" ,
- TitledBorder.CENTER ,TitledBorder.TOP ));
- top.setLayout(new GridLayout(1 , 2));
- //消息類型Panel,該Panel中的選項決定對話框的圖標
- messageTypePanel = new ButtonPanel("選擇消息的類型",
- new String[]{"ERROR_MESSAGE", "INFORMATION_MESSAGE", "WARNING_MESSAGE",
- "QUESTION_MESSAGE", "PLAIN_MESSAGE" });
- //消息內容類型的Panel,該Panel中的選項決定對話框的消息區的內容
- messagePanel = new ButtonPanel("選擇消息內容的類型",
- new String[]{"字符串消息", "圖標消息", "組件消息", "普通對象消息" , "Object[]消息"});
- top.add(messageTypePanel);
- top.add(messagePanel);
- JPanel bottom = new JPanel();
- bottom.setBorder(new TitledBorder(new EtchedBorder(), "彈出不同的對話框" ,
- TitledBorder.CENTER ,TitledBorder.TOP));
- bottom.setLayout(new GridLayout(1 , 4));
- //創建用於彈出消息對話框的Panel
- msgPanel = new ButtonPanel("消息對話框", null);
- msgBn.addActionListener(new ShowAction());
- msgPanel.add(msgBn);
- //創建用於彈出確認對話框的Panel
- confirmPanel = new ButtonPanel("確認對話框",
- new String[]{"DEFAULT_OPTION", "YES_NO_OPTION", "YES_NO_CANCEL_OPTION",
- "OK_CANCEL_OPTION"});
- confrimBn.addActionListener(new ShowAction());
- confirmPanel.add(confrimBn);
- //創建用於彈出輸入對話框的Panel
- inputPanel = new ButtonPanel("輸入對話框",
- new String[]{"單行文本框","下拉列表選擇框"});
- inputBn.addActionListener(new ShowAction());
- inputPanel.add(inputBn);
- //創建用於彈出選項對話框的Panel
- optionsPanel = new ButtonPanel("選項對話框",
- new String[]{"字符串選項", "圖標選項", "對象選項"});
- optionBn.addActionListener(new ShowAction());
- optionsPanel.add(optionBn);
- bottom.add(msgPanel);
- bottom.add(confirmPanel);
- bottom.add(inputPanel);
- bottom.add(optionsPanel);
- Box box = new Box(BoxLayout.Y_AXIS);
- box.add(top);
- box.add(bottom);
- jf.add(box);
- jf.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
- jf.pack();
- jf.setVisible(true);
- }
- //根據用戶選擇返回選項類型
- private int getOptionType()
- {
- if (confirmPanel.getSelection().equals("DEFAULT_OPTION"))
- return JOptionPane.DEFAULT_OPTION;
- else if (confirmPanel.getSelection().equals("YES_NO_OPTION"))
- return JOptionPane.YES_NO_OPTION;
- else if (confirmPanel.getSelection().equals("YES_NO_CANCEL_OPTION"))
- return JOptionPane.YES_NO_CANCEL_OPTION;
- else
- return JOptionPane.OK_CANCEL_OPTION;
- }
- //根據用戶選擇返回消息
- private Object getMessage()
- {
- if (messagePanel.getSelection().equals("字符串消息"))
- return messageString;
- else if (messagePanel.getSelection().equals("圖標消息"))
- return messageIcon;
- else if (messagePanel.getSelection().equals("組件消息"))
- return messageComponent;
- else if(messagePanel.getSelection().equals("普通對象消息"))
- return messageObject;
- else
- return new Object[]{messageString , messageIcon ,
- messageObject , messageComponent};
- }
- //根據用戶選擇返回消息類型(決定圖標區的圖標)
- private int getDialogType()
- {
- if (messageTypePanel.getSelection().equals("ERROR_MESSAGE"))
- return JOptionPane.ERROR_MESSAGE;
- else if (messageTypePanel.getSelection().equals("INFORMATION_MESSAGE"))
- return JOptionPane.INFORMATION_MESSAGE;
- else if (messageTypePanel.getSelection().equals("WARNING_MESSAGE"))
- return JOptionPane.WARNING_MESSAGE;
- else if(messageTypePanel.getSelection().equals("QUESTION_MESSAGE"))
- return JOptionPane.QUESTION_MESSAGE;
- else
- return JOptionPane.PLAIN_MESSAGE;
- }
- private Object[] getOptions()
- {
- if (optionsPanel.getSelection().equals("字符串選項"))
- return new String[]{"a" , "b" , "c" , "d"};
- else if (optionsPanel.getSelection().equals("圖標選項"))
- return new Icon[]{new ImageIcon("ico/1.gif") , new ImageIcon("ico/2.gif"),
- new ImageIcon("ico/3.gif"),new ImageIcon("ico/4.gif")};
- else
- return new Object[]{new Date() ,new Date() , new Date()};
- }
- //為各按鈕定義事件監聽器
- private class ShowAction implements ActionListener
- {
- public void actionPerformed(ActionEvent event)
- {
- if (event.getActionCommand().equals("確認對話框"))
- {
- JOptionPane.showConfirmDialog(jf , getMessage(),"確認對話框",
- getOptionType(), getDialogType());
- }
- else if (event.getActionCommand().equals("輸入對話框"))
- {
- if (inputPanel.getSelection().equals("單行文本框"))
- {
- JOptionPane.showInputDialog(jf, getMessage(), "輸入對話框", getDialogType());
- }
- else
- {
- JOptionPane.showInputDialog(jf, getMessage(), "輸入對話框", getDialogType(),
- null, new String[] {"輕量級J2EE企業應用實戰", "Struts2權威指南"},
- "Struts2權威指南");
- }
- }
- else if (event.getActionCommand().equals("消息對話框"))
- {
- JOptionPane.showMessageDialog(jf,getMessage(),"消息對話框",getDialogType());
- }
- else if (event.getActionCommand().equals("選項對話框"))
- {
- JOptionPane.showOptionDialog(jf , getMessage() , "選項對話框", getOptionType(),
- getDialogType(), null, getOptions(), "a");
- }
- }
- }
- public static void main(String[] args)
- {
- new TestJOptionPane().init();
- }
- }
- //定義一個JPanel類擴展類,該類的對象包含多個縱向排列的JRadioButton控件
- //且Panel擴展類可以指定一個字符串作為TitledBorder
- class ButtonPanel extends JPanel
- {
- private ButtonGroup group;
- public ButtonPanel(String title, String[] options)
- {
- setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), title));
- setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
- group = new ButtonGroup();
- for (int i = 0; options!= null && i < options.length; i++)
- {
- JRadioButton b = new JRadioButton(options[i]);
- b.setActionCommand(options[i]);
- add(b);
- group.add(b);
- b.setSelected(i == 0);
- }
- }
- //定義一個方法,用於返回用戶選擇的選項
- public String getSelection()
- {
- return group.getSelection().getActionCommand();
- }
- }
看似簡單,用起來花樣還是挺多的。