新聞中心
這里有您想知道的互聯網營銷解決方案
JavaSwing編程:基本組件
今天還是繼續(xù)我們的JAVA的GUI,前幾天講了AWT,這個太重了。Swing開發(fā)圖形界面比AWT更加優(yōu)秀,切實輕量級的,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);
- //定義一個單選按鈕,初始處于選中狀態(tài)
- JRadioButton male = new JRadioButton("男" , true);
- //定義一個單按鈕,初始處于沒有選中狀態(tài)
- JRadioButton female = new JRadioButton("女" , false);
- //定義一個ButtonGroup,用于將上面兩個JRadioButton組合在一起
- ButtonGroup bg = new ButtonGroup();
- //定義一個復選框,初始處于沒有選中狀態(tài)。
- 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("編輯");
- //創(chuàng)建“新建”菜單項,并為之指定圖標
- Icon newIcon = new ImageIcon("ico/new.png");
- JMenuItem newItem = new JMenuItem("新建" , newIcon);
- //創(chuàng)建“保存”菜單項,并為之指定圖標
- Icon saveIcon = new ImageIcon("ico/save.png");
- JMenuItem saveItem = new JMenuItem("保存" , saveIcon);
- //創(chuàng)建“退出”菜單項,并為之指定圖標
- Icon exitIcon = new ImageIcon("ico/exit.png");
- JMenuItem exitItem = new JMenuItem("退出" , exitIcon);
- JCheckBoxMenuItem autoWrap = new JCheckBoxMenuItem("自動換行");
- //創(chuàng)建“復制”菜單項,并為之指定圖標
- JMenuItem copyItem = new JMenuItem("復制" , new ImageIcon("ico/copy.png"));
- //創(chuàng)建“粘貼”菜單項,并為之指定圖標
- 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();
- //創(chuàng)建三個單選框按鈕,用于設定程序的外觀風格
- JRadioButtonMenuItem metalItem = new JRadioButtonMenuItem("Metal風格" , true);
- JRadioButtonMenuItem windowsItem = new JRadioButtonMenuItem("Windows風格");
- JRadioButtonMenuItem motifItem = new JRadioButtonMenuItem("Motif風格");
- public void init()
- {
- //創(chuàng)建一個裝載了文本框、按鈕的JPanel
- JPanel bottom = new JPanel();
- bottom.add(name);
- bottom.add(ok);
- f.add(bottom , BorderLayout.SOUTH);
- //創(chuàng)建一個裝載了下拉選擇框、三個JCheckBox的JPanel
- JPanel checkPanel = new JPanel();
- checkPanel.add(colorChooser);
- bg.add(male);
- bg.add(female);
- checkPanel.add(male);
- checkPanel.add(female);
- checkPanel.add(married);
- //創(chuàng)建一個垂直排列組件的Box,盛裝多行文本域JPanel
- Box topLeft = Box.createVerticalBox();
- //使用JScrollPane作為普通組件的JViewPort
- JScrollPane taJsp = new JScrollPane(ta);
- topLeft.add(taJsp);
- topLeft.add(checkPanel);
- //創(chuàng)建一個垂直排列組件的Box,盛裝topLeft、colorList
- Box top = Box.createHorizontalBox();
- top.add(topLeft);
- top.add(colorList);
- //將top Box容器添加到窗口的中間
- f.add(top);
- //-----------下面開始組合菜單、并為菜單添加事件監(jiān)聽器----------
- //為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);
- //為三個菜單創(chuàng)建事件監(jiān)聽器
- 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();
- }
- }
- };
- //為三個菜單添加事件監(jiān)聽器
- 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();
- //創(chuàng)建"粘貼"Action,該Action用于創(chuàng)建菜單項、工具按鈕和普通按鈕
- 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();
- }
- }
- }
- };
- //創(chuàng)建"復制"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默認處于不激活狀態(tài)
- pasteAction.setEnabled(false);
- jf.add(new JScrollPane(jta));
- //以Action創(chuàng)建按鈕,并將該按鈕添加到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();
- }
- }
繼續(xù)講Swing的特殊組件,JColorChooser和JFileChooser這兩個東西在awt中都是利用系統(tǒng)的控件,這樣導致不同操作系統(tǒng)有不同的界面,用Swing就避免了這些問題。下面就先看JColorChooser的例子,eg(一個簡單畫圖程序)
- public class HandDraw
- {
- //畫圖區(qū)的寬度
- private final int AREA_WIDTH = 500;
- //畫圖區(qū)的高度
- 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);
- //下面代碼則可以彈出一個非模式的顏色選擇對話框,
- //并可以分別為“確定”按鈕、“取消”按鈕指定事件監(jiān)聽器
- 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));
- //監(jiān)聽鼠標移動動作
- 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();
- }
- });
- //監(jiān)聽鼠標事件
- 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();
- }
- //讓畫圖區(qū)域繼承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();
- //以當前路徑創(chuàng)建文件選擇器
- JFileChooser chooser = new JFileChooser(".");
- JLabel accessory = new JLabel();
- ExtensionFileFilter filter = new ExtensionFileFilter();
- public void init()
- {
- //-------------------下面開始初始化JFileChooser的相關屬性-----------------
- // 創(chuàng)建一個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的被選文件已經發(fā)生了改變
- 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());
- &nb
名稱欄目:JavaSwing編程:基本組件
網頁路徑:http://www.dlmjj.cn/article/djgocij.html


咨詢
建站咨詢
