日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關咨詢
選擇下列產品馬上在線溝通
服務時間:8:30-17:00
你可能遇到了下面的問題
關閉右側工具欄

新聞中心

這里有您想知道的互聯網營銷解決方案
JavaSwing編程:基本組件

今天還是繼續(xù)我們的JAVA的GUI,前幾天講了AWT,這個太重了。Swing開發(fā)圖形界面比AWT更加優(yōu)秀,切實輕量級的,100%的JAVA實現,唯一的缺點就是比AWT略慢。

先講下Swing和AWT組件的相似處,以下圖顯示相同的組件

Swing多出來的組件

組件比較多,那些和AWT相同的組件用起來差不多,我就不多講了,就貼段全面的代碼讓大家把玩下,eg

 
 
 
  1. public class SwingComponent  
  2. {  
  3.     JFrame f = new JFrame("測試");  
  4.     //定義一個按鈕,并為之指定圖標  
  5.     Icon okIcon = new ImageIcon("ico/ok.png");  
  6.     JButton ok = new JButton("確認" , okIcon);  
  7.     //定義一個單選按鈕,初始處于選中狀態(tài)  
  8.     JRadioButton male = new JRadioButton("男" , true);  
  9.     //定義一個單按鈕,初始處于沒有選中狀態(tài)  
  10.     JRadioButton female = new JRadioButton("女" , false);  
  11.     //定義一個ButtonGroup,用于將上面兩個JRadioButton組合在一起  
  12.     ButtonGroup bg = new ButtonGroup();  
  13.     //定義一個復選框,初始處于沒有選中狀態(tài)。  
  14.     JCheckBox married = new JCheckBox("是否已婚?" , false);  
  15.     String[] colors = new String[]{"紅色" , "綠色"  , "藍色"};  
  16.     //定義一個下拉選擇框  
  17.     JComboBox colorChooser = new JComboBox(colors);  
  18.     //定義一個列表選擇框  
  19.     JList colorList = new JList(colors);  
  20.     //定義一個8行、20列的多行文本域  
  21.     JTextArea ta = new JTextArea(8, 20);  
  22.     //定義一個40列的單行文本域  
  23.     JTextField name = new JTextField(40);  
  24.     JMenuBar mb = new JMenuBar();  
  25.     JMenu file = new JMenu("文件");  
  26.     JMenu edit = new JMenu("編輯");  
  27.     //創(chuàng)建“新建”菜單項,并為之指定圖標  
  28.     Icon newIcon = new ImageIcon("ico/new.png");  
  29.     JMenuItem newItem = new JMenuItem("新建" , newIcon);  
  30.     //創(chuàng)建“保存”菜單項,并為之指定圖標  
  31.     Icon saveIcon = new ImageIcon("ico/save.png");  
  32.     JMenuItem saveItem = new JMenuItem("保存" , saveIcon);  
  33.     //創(chuàng)建“退出”菜單項,并為之指定圖標  
  34.     Icon exitIcon = new ImageIcon("ico/exit.png");  
  35.     JMenuItem exitItem = new JMenuItem("退出" , exitIcon);      
  36.     JCheckBoxMenuItem autoWrap = new JCheckBoxMenuItem("自動換行");  
  37.     //創(chuàng)建“復制”菜單項,并為之指定圖標  
  38.     JMenuItem copyItem = new JMenuItem("復制" , new ImageIcon("ico/copy.png"));  
  39.     //創(chuàng)建“粘貼”菜單項,并為之指定圖標  
  40.     JMenuItem pasteItem = new JMenuItem("粘貼" , new ImageIcon("ico/paste.png"));  
  41.     JMenu format = new JMenu("格式");  
  42.     JMenuItem commentItem = new JMenuItem("注釋");  
  43.     JMenuItem cancelItem = new JMenuItem("取消注釋");  
  44.       
  45.     //定義一個右鍵菜單用于設置程序風格  
  46.     JPopupMenu pop = new JPopupMenu();  
  47.     //用于組合三個風格菜單項的ButtonGroup  
  48.     ButtonGroup flavorGroup = new ButtonGroup();  
  49.     //創(chuàng)建三個單選框按鈕,用于設定程序的外觀風格  
  50.     JRadioButtonMenuItem metalItem = new JRadioButtonMenuItem("Metal風格" , true);  
  51.     JRadioButtonMenuItem windowsItem = new JRadioButtonMenuItem("Windows風格");  
  52.     JRadioButtonMenuItem motifItem = new JRadioButtonMenuItem("Motif風格");  
  53.  
  54.     public void init()  
  55.     {  
  56.         //創(chuàng)建一個裝載了文本框、按鈕的JPanel  
  57.         JPanel bottom = new JPanel();  
  58.         bottom.add(name);  
  59.         bottom.add(ok);  
  60.         f.add(bottom , BorderLayout.SOUTH);  
  61.         //創(chuàng)建一個裝載了下拉選擇框、三個JCheckBox的JPanel  
  62.         JPanel checkPanel = new JPanel();  
  63.         checkPanel.add(colorChooser);  
  64.         bg.add(male);  
  65.         bg.add(female);  
  66.         checkPanel.add(male);  
  67.         checkPanel.add(female);  
  68.         checkPanel.add(married);  
  69.         //創(chuàng)建一個垂直排列組件的Box,盛裝多行文本域JPanel  
  70.         Box topLeft = Box.createVerticalBox();  
  71.         //使用JScrollPane作為普通組件的JViewPort  
  72.         JScrollPane taJsp = new JScrollPane(ta);  
  73.         topLeft.add(taJsp);  
  74.         topLeft.add(checkPanel);  
  75.         //創(chuàng)建一個垂直排列組件的Box,盛裝topLeft、colorList  
  76.         Box top = Box.createHorizontalBox();  
  77.         top.add(topLeft);  
  78.         top.add(colorList);  
  79.         //將top Box容器添加到窗口的中間  
  80.         f.add(top);   
  81.         //-----------下面開始組合菜單、并為菜單添加事件監(jiān)聽器----------  
  82.         //為newItem設置快捷鍵,設置快捷鍵時要使用大寫字母  
  83.         newItem.setAccelerator(KeyStroke.getKeyStroke('N' , InputEvent.CTRL_MASK));   
  84.         newItem.addActionListener(new ActionListener()  
  85.         {  
  86.             public void actionPerformed(ActionEvent e)  
  87.             {  
  88.                 ta.append("用戶單擊了“新建”菜單/n");  
  89.             }  
  90.         });  
  91.         //為file菜單添加菜單項  
  92.         file.add(newItem);  
  93.         file.add(saveItem);  
  94.         file.add(exitItem);  
  95.         //為edit菜單添加菜單項  
  96.         edit.add(autoWrap);  
  97.         //使用addSeparator方法來添加菜單分隔線  
  98.         edit.addSeparator();  
  99.         edit.add(copyItem);  
  100.         edit.add(pasteItem);  
  101.         commentItem.setToolTipText("將程序代碼注釋起來!");  
  102.         //為format菜單添加菜單項  
  103.         format.add(commentItem);  
  104.         format.add(cancelItem);  
  105.         //使用添加new JMenuItem("-")的方式不能添加菜單分隔符  
  106.         edit.add(new JMenuItem("-"));  
  107.         //將format菜單組合到edit菜單中,從而形成二級菜單  
  108.         edit.add(format);  
  109.         //將file、edit菜單添加到mb菜單條中  
  110.         mb.add(file);  
  111.         mb.add(edit);  
  112.         //為f窗口設置菜單條  
  113.         f.setJMenuBar(mb);  
  114.         //-----------下面開始組合右鍵菜單、并安裝右鍵菜單----------  
  115.         flavorGroup.add(metalItem);  
  116.         flavorGroup.add(windowsItem);  
  117.         flavorGroup.add(motifItem);  
  118.         pop.add(metalItem);  
  119.         pop.add(windowsItem);  
  120.         pop.add(motifItem);  
  121.         //為三個菜單創(chuàng)建事件監(jiān)聽器  
  122.         ActionListener flavorListener = new ActionListener()  
  123.         {  
  124.             public void actionPerformed(ActionEvent e)  
  125.             {  
  126.                 try 
  127.                 {  
  128.                     if (e.getActionCommand().equals("Metal風格"))  
  129.                     {  
  130.                         changeFlavor(1);  
  131.                     }  
  132.                     else if (e.getActionCommand().equals("Windows風格"))  
  133.                     {  
  134.                         changeFlavor(2);  
  135.                     }  
  136.                     else if (e.getActionCommand().equals("Motif風格"))  
  137.                     {  
  138.                         changeFlavor(3);  
  139.                     }  
  140.                 }  
  141.                 catch (Exception ee)  
  142.                 {  
  143.                     ee.printStackTrace();  
  144.                 }  
  145.             }  
  146.         };  
  147.         //為三個菜單添加事件監(jiān)聽器  
  148.         metalItem.addActionListener(flavorListener);  
  149.         windowsItem.addActionListener(flavorListener);  
  150.         motifItem.addActionListener(flavorListener);  
  151.         //調用該方法即可設置右鍵菜單,無需使用事件機制  
  152.         ta.setComponentPopupMenu(pop);   
  153.         //設置關閉窗口時,退出程序  
  154.         f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  155.         f.pack();  
  156.         f.setVisible(true);  
  157.     }  
  158.  
  159.     //定義一個方法,用于改變界面風格  
  160.     private void changeFlavor(int flavor)throws Exception  
  161.     {  
  162.         switch (flavor)  
  163.         {  
  164.             //設置Metal風格  
  165.             case 1:  
  166.                 UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");  
  167.                 break;  
  168.             //設置Windows風格  
  169.             case 2:  
  170.                 UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");  
  171.                 break;  
  172.             //設置Motif風格  
  173.             case 3:  
  174.                 UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");  
  175.                 break;            
  176.         }  
  177.         //更新f窗口內頂級容器以及內部所有組件的UI  
  178.         SwingUtilities.updateComponentTreeUI(f.getContentPane());  
  179.         //更新mb菜單條以及內部所有組件的UI  
  180.         SwingUtilities.updateComponentTreeUI(mb);  
  181.         //更新pop右鍵菜單以及內部所有組件的UI  
  182.         SwingUtilities.updateComponentTreeUI(pop);  
  183.  
  184.     }  
  185.     public static void main(String[] args)   
  186.     {  
  187.         //設置Swing窗口使用Java風格  
  188.         JFrame.setDefaultLookAndFeelDecorated(true);   
  189.         new SwingComponent().init();  
  190.     }  
  191. }  

下面Swing的特殊組件,我將以舉例的形式,這樣最能主觀理解,大家一定要動手試試

首先是JToolBar

 
 
 
  1. public class TestJToolBar  
  2. {  
  3.     JFrame jf = new JFrame("測試工具條");  
  4.     JTextArea jta = new JTextArea(6, 35);  
  5.     JToolBar jtb = new JToolBar();  
  6.     JMenuBar jmb = new JMenuBar();  
  7.     JMenu edit = new JMenu("編輯");  
  8.     Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();  
  9.     //創(chuàng)建"粘貼"Action,該Action用于創(chuàng)建菜單項、工具按鈕和普通按鈕  
  10.     Action pasteAction = new AbstractAction("粘貼", new ImageIcon("ico/paste.png"))  
  11.     {  
  12.         public void actionPerformed(ActionEvent e)  
  13.         {  
  14.             //如果剪貼板中包含stringFlavor內容  
  15.             if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor))  
  16.             {  
  17.                 try 
  18.                 {  
  19.                     //取出剪貼板中stringFlavor內容  
  20.                     String content = (String)clipboard.getData(DataFlavor.stringFlavor);  
  21.                     //將選中內容替換成剪貼板中的內容  
  22.                     jta.replaceRange(content , jta.getSelectionStart() , jta.getSelectionEnd());  
  23.                 }  
  24.                 catch (Exception ee)  
  25.                 {  
  26.                     ee.printStackTrace();  
  27.                 }  
  28.             }  
  29.         }  
  30.     };  
  31.     //創(chuàng)建"復制"Action  
  32.     Action copyAction = new AbstractAction("復制", new ImageIcon("ico/copy.png"))  
  33.     {  
  34.         public void actionPerformed(ActionEvent e)  
  35.         {  
  36.             StringSelection contents = new StringSelection(jta.getSelectedText());  
  37.             //將StringSelection對象放入剪貼板  
  38.             clipboard.setContents(contents, null);  
  39.             //如果剪貼板中包含stringFlavor內容  
  40.             if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor))  
  41.             {  
  42.                 //將pasteAction激活  
  43.                 pasteAction.setEnabled(true);  
  44.             }  
  45.         }  
  46.     };  
  47.     public void init()  
  48.     {  
  49.         //pasteAction默認處于不激活狀態(tài)  
  50.         pasteAction.setEnabled(false);  
  51.         jf.add(new JScrollPane(jta));  
  52.         //以Action創(chuàng)建按鈕,并將該按鈕添加到Panel中  
  53.         JButton copyBn = new JButton(copyAction);  
  54.         JButton pasteBn = new JButton(pasteAction);  
  55.         JPanel jp = new JPanel();  
  56.         jp.add(copyBn);  
  57.         jp.add(pasteBn);  
  58.         jf.add(jp , BorderLayout.SOUTH);  
  59.         //向工具條中添加Action對象,該對象將會轉換成工具按鈕  
  60.         jtb.add(copyAction);  
  61.         jtb.addSeparator();  
  62.         jtb.add(pasteAction);  
  63.         //向菜單中添加Action對象,該對象將會轉換成菜單項  
  64.         edit.add(copyAction);  
  65.         edit.add(pasteAction);  
  66.         //將edit菜單添加到菜單條中  
  67.         jmb.add(edit);  
  68.         jf.setJMenuBar(jmb);  
  69.         //設置工具條和工具按鈕之間的距離  
  70.         jtb.setMargin(new Insets(20 ,10 , 5 , 30));  
  71.         //向窗口中添加工具條  
  72.         jf.add(jtb , BorderLayout.NORTH);  
  73.         jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  74.         jf.pack();  
  75.         jf.setVisible(true);  
  76.     }  
  77.     public static void main(String[] args)   
  78.     {  
  79.         new TestJToolBar().init();  
  80.     }  

繼續(xù)講Swing的特殊組件,JColorChooser和JFileChooser這兩個東西在awt中都是利用系統(tǒng)的控件,這樣導致不同操作系統(tǒng)有不同的界面,用Swing就避免了這些問題。下面就先看JColorChooser的例子,eg(一個簡單畫圖程序)

 
 
 
  1. public class HandDraw  
  2. {  
  3.     //畫圖區(qū)的寬度   
  4.     private final int AREA_WIDTH = 500;  
  5.     //畫圖區(qū)的高度  
  6.     private final int AREA_HEIGHT = 400;  
  7.     //下面的preX、preY保存了上一次鼠標拖動事件的鼠標座標  
  8.     private int preX = -1;  
  9.     private int preY = -1;  
  10.     //定義一個右鍵菜單用于設置畫筆顏色  
  11.     JPopupMenu pop = new JPopupMenu();  
  12.     JMenuItem chooseColor = new JMenuItem("選擇顏色");  
  13.     //定義一個BufferedImage對象  
  14.     BufferedImage image = new BufferedImage(AREA_WIDTH , AREA_HEIGHT ,   
  15.         BufferedImage.TYPE_INT_RGB);  
  16.     //獲取image對象的Graphics  
  17.     Graphics g = image.getGraphics();  
  18.     private JFrame f = new JFrame("簡單手繪程序");  
  19.     private DrawCanvas drawArea = new DrawCanvas();  
  20.     //用于保存需要繪制什么圖形的字符串屬性  
  21.     private String shape = "";  
  22.     //用于保存畫筆顏色  
  23.     private Color foreColor = new Color(255, 0 ,0);  
  24.     public void init()  
  25.     {  
  26.         chooseColor.addActionListener(new ActionListener()  
  27.         {  
  28.             public void actionPerformed(ActionEvent ae)  
  29.             {  
  30.                 //下面代碼直接彈出一個模式的顏色選擇器對話框,并返回用戶選擇的顏色  
  31.                 //foreColor = JColorChooser.showDialog(f , "選擇畫筆顏色" , foreColor);  
  32.                 //下面代碼則可以彈出一個非模式的顏色選擇對話框,  
  33.                 //并可以分別為“確定”按鈕、“取消”按鈕指定事件監(jiān)聽器  
  34.                 final JColorChooser colorPane = new JColorChooser(foreColor);  
  35.                 JDialog jd = JColorChooser.createDialog(f ,"選擇畫筆顏色",false,   
  36.                     colorPane, new ActionListener()  
  37.                     {  
  38.                         public void actionPerformed(ActionEvent ae)  
  39.                         {  
  40.                             foreColor = colorPane.getColor();  
  41.                         }  
  42.                     }, null);  
  43.                 jd.setVisible(true);  
  44.             }  
  45.         });  
  46.         //將菜單項組合成右鍵菜單  
  47.         pop.add(chooseColor);  
  48.         //將右鍵菜單添加到drawArea對象中  
  49.         drawArea.setComponentPopupMenu(pop);  
  50.         //將image對象的背景色填充成白色  
  51.         g.fillRect(0 , 0 ,AREA_WIDTH , AREA_HEIGHT);  
  52.         drawArea.setPreferredSize(new Dimension(AREA_WIDTH , AREA_HEIGHT));  
  53.         //監(jiān)聽鼠標移動動作  
  54.         drawArea.addMouseMotionListener(new MouseMotionAdapter()  
  55.         {  
  56.             //實現按下鼠標鍵并拖動的事件處理器  
  57.             public void mouseDragged(MouseEvent e)  
  58.             {  
  59.                 //如果preX和preY大于0  
  60.                 if (preX > 0 && preY > 0)  
  61.                 {  
  62.                     //設置當前顏色  
  63.                     g.setColor(foreColor);  
  64.                     //繪制從上一次鼠標拖動事件點到本次鼠標拖動事件點的線段  
  65.                     g.drawLine(preX , preY , e.getX() , e.getY());  
  66.                 }  
  67.                 //將當前鼠標事件點的X、Y座標保存起來  
  68.                 preX = e.getX();  
  69.                 preY = e.getY();  
  70.                 //重繪drawArea對象  
  71.                 drawArea.repaint();  
  72.             }  
  73.         });  
  74.         //監(jiān)聽鼠標事件  
  75.         drawArea.addMouseListener(new MouseAdapter()  
  76.         {  
  77.             //實現鼠標松開的事件處理器  
  78.             public void mouseReleased(MouseEvent e)  
  79.             {  
  80.                 //松開鼠標鍵時,把上一次鼠標拖動事件的X、Y座標設為-1。  
  81.                 preX = -1;  
  82.                 preY = -1;  
  83.             }  
  84.         });  
  85.         f.add(drawArea);  
  86.         f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  87.         f.pack();  
  88.         f.setVisible(true);  
  89.     }  
  90.     public static void main(String[] args)   
  91.     {  
  92.         new HandDraw().init();  
  93.     }  
  94.     //讓畫圖區(qū)域繼承JPanel類  
  95.     class DrawCanvas extends JPanel  
  96.     {  
  97.         //重寫JPanel的paint方法,實現繪畫  
  98.         public void paint(Graphics g)  
  99.         {  
  100.             //將image繪制到該組件上  
  101.             g.drawImage(image , 0 , 0 , null);  
  102.         }  
  103.     }  
  104. }  

下面舉個JFileChooser,這些東西組件不是很常用,大家可以收藏著,到用的時候翻出來看,eg

 
 
 
  1. public class ImageViewer  
  2. {  
  3.     final int PREVIEW_SIZE = 100;  
  4.     JFrame jf = new JFrame("簡單圖片查看器");  
  5.     JMenuBar menuBar = new JMenuBar();  
  6.     //該label用于顯示圖片  
  7.     JLabel label = new JLabel();  
  8.     //以當前路徑創(chuàng)建文件選擇器  
  9.     JFileChooser chooser = new JFileChooser(".");  
  10.     JLabel accessory = new JLabel();  
  11.     ExtensionFileFilter filter = new ExtensionFileFilter();  
  12.     public void init()  
  13.     {  
  14.         //-------------------下面開始初始化JFileChooser的相關屬性-----------------  
  15.         // 創(chuàng)建一個FileFilter  
  16.         filter.addExtension("jpg");  
  17.         filter.addExtension("jpeg");  
  18.         filter.addExtension("gif");  
  19.         filter.addExtension("png");  
  20.         filter.setDescription("圖片文件(*.jpg,*.jpeg,*.gif,*.png)");  
  21.         chooser.addChoosableFileFilter(filter);  
  22.         //禁止“文件類型”下拉列表中顯示“所有文件”選項。  
  23.         chooser.setAcceptAllFileFilterUsed(false);   
  24.         //為文件選擇器指定自定義的FileView對象  
  25.         chooser.setFileView(new FileIconView(filter));  
  26.         //為文件選擇器指定一個預覽圖片的附件組件  
  27.         chooser.setAccessory(accessory);  
  28.         //設置預覽圖片組件的大小和邊框  
  29.         accessory.setPreferredSize(new Dimension(PREVIEW_SIZE, PREVIEW_SIZE));  
  30.         accessory.setBorder(BorderFactory.createEtchedBorder());  
  31.         //用于檢測被選擇文件的改變事件  
  32.         chooser.addPropertyChangeListener(new PropertyChangeListener()  
  33.         {  
  34.             public void propertyChange(PropertyChangeEvent event)   
  35.             {  
  36.                 //JFileChooser的被選文件已經發(fā)生了改變  
  37.                 if (event.getPropertyName() == JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)  
  38.                 {  
  39.                     //獲取用戶選擇的新文件   
  40.                     File f = (File) event.getNewValue();  
  41.                     if (f == null)  
  42.                     {   
  43.                         accessory.setIcon(null);   
  44.                         return;   
  45.                     }  
  46.                     //將所文件讀入ImageIcon對象中  
  47.                     ImageIcon icon = new ImageIcon(f.getPath());  
  48.       &nb
    名稱欄目:JavaSwing編程:基本組件
    網頁路徑:http://www.dlmjj.cn/article/djgocij.html