第一部分:理論知識學習部分java
第11章 事件處理編程
11.1 事件處理基礎安全
a)事件源(event source):可以產生事件的對象均可 以成爲事件源,如文本框、按鈕等。一個事件源是一個 可以註冊監聽器並向監聽器發送事件對象的對象。網絡
b) 事件監聽器(event listener):事件監聽器對象接 收事件源發送的通告(事件對象),並對發生的事件做 出響應。一個監聽器對象就是一個實現了專門監聽器接 口的類實例,該類必須實現接口中的方法,這些方法當 事件發生時,被自動執行。框架
c) 事件對象(event object):Java將事件的相關信息 封裝在一個事件對象中,全部的事件對象都最終派生於 java.util.EventObject類。不一樣的事件源能夠產生不 同類別的事件。dom
11.2 動做工具
a) 激活一個命令能夠有多種方式,如用戶能夠經過 菜單、擊鍵或工具欄上的按鈕選擇特定的功能。 學習
b) 在AWT事件模型中,不管是經過哪一種方式下達命 令(如:點擊按鈕、菜單選項、按下鍵盤),其 操做動做都是同樣的。測試
11.3 鼠標事件this
a)鼠標事件 – MouseEvent
b)鼠標監聽器接口 – MouseListener – MouseMotionListener
c) 鼠標監聽器適配器 – MouseAdapter – MouseMotionAdapter
11.4 AWT事件繼承層次
a) 全部的事件都是由java.util包中的EventObject 類擴展而來。
b) AWTEevent 是全部AWT 事件類的父類, 也是 EventObject的直接子類。
c) 有些Swing組件生成其餘類型的事件對象,通常直 接 擴 展 於 EventObject, 而不是AWTEvent,位於 javax.swing.event.*。
d) 事件對象封裝了事件源與監聽器彼此通訊的事件 信息。在必要的時候,能夠對傳遞給監聽器對象的 事件對象進行分析。
第二部分:實驗部分——圖形界面事件處理技術
實驗時間 2018-11-22
1、實驗目的與要求
(1) 掌握事件處理的基本原理,理解其用途;
(2) 掌握AWT事件模型的工做機制;
(3) 掌握事件處理的基本編程模型;
(4) 瞭解GUI界面組件觀感設置方法;
(5) 掌握WindowAdapter類、AbstractAction類的用法;
(6) 掌握GUI程序中鼠標事件處理技術。
2、實驗內容和步驟
實驗1: 導入第11章示例程序,測試程序並進行代碼註釋。
測試程序1:
1.在elipse IDE中調試運行教材443頁-444頁程序11-1,結合程序運行結果理解程序;
2.在事件處理相關代碼處添加註釋;
3.用lambda表達式簡化程序;
4.掌握JButton組件的基本API;
5.掌握Java中事件處理的基本編程模型。
1 package test; 2 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 /** 8 * 帶按鈕面板的框架 9 */ 10 11 12 public class ButtonFrame extends JFrame 13 { 14 private JPanel buttonPanel; 15 private static final int DEFAULT_WIDTH = 500; 16 private static final int DEFAULT_HEIGHT = 600; 17 18 public ButtonFrame() 19 { 20 setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); 21 22 // 建立三個按鈕 23 // JButton yellowButton = new JButton("Yellow"); 24 // JButton blueButton = new JButton("Blue"); 25 // JButton redButton = new JButton("Red"); 26 27 buttonPanel = new JPanel(); 28 29 // 向面板添加按鈕 30 // buttonPanel.add(yellowButton); 31 // buttonPanel.add(blueButton); 32 // buttonPanel.add(redButton); 33 34 // 將面板添加到幀 35 add(buttonPanel); 36 37 // 建立按鈕動做 38 // ColorAction yellowAction = new ColorAction(Color.YELLOW); 39 // ColorAction blueAction = new ColorAction(Color.BLUE); 40 // ColorAction redAction = new ColorAction(Color.RED); 41 // 42 // 用按鈕關聯動做 43 // yellowButton.addActionListener(yellowAction); 44 // blueButton.addActionListener(blueAction); 45 // redButton.addActionListener(redAction); 46 47 MakeButton("黃色",Color.yellow); 48 MakeButton("藍色",Color.blue); 49 MakeButton("紅色",Color.red); 50 } 51 public void MakeButton(String name , Color backgroundColor) 52 { 53 JButton button=new JButton(name); 54 buttonPanel.add(button); 55 // ColorAction action=new ColorAction(backgroundColor); 56 // button.addActionListener(action); 57 button.addActionListener(new ActionListener() 58 { 59 public void actionPerformed(ActionEvent event) 60 { 61 buttonPanel.setBackground(backgroundColor); 62 } 63 }); 64 65 } 66 67 68 /** 69 * 設置面板背景顏色的動做偵聽器 70 */ 71 private class ColorAction implements ActionListener 72 { 73 private Color backgroundColor; 74 75 public ColorAction(Color c) 76 { 77 backgroundColor = c; 78 } 79 80 public void actionPerformed(ActionEvent event) 81 { 82 buttonPanel.setBackground(backgroundColor); 83 } 84 } 85 }
1 package button; 2 3 import java.awt.*; 4 import javax.swing.*; 5 6 /** 7 * @version 1.34 2015-06-12 8 * @author Cay Horstmann 9 */ 10 public class ButtonTest 11 { 12 public static void main(String[] args) 13 { 14 EventQueue.invokeLater(() -> { 15 JFrame frame = new ButtonFrame(); 16 frame.setTitle("ButtonTest"); 17 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 18 frame.setVisible(true); 19 }); 20 } 21 }
測試程序2:
1.在elipse IDE中調試運行教材449頁程序11-2,結合程序運行結果理解程序;
2.在組件觀感設置代碼處添加註釋;
3.瞭解GUI程序中觀感的設置方法。
1 package plaf; 2 3 import javax.swing.JButton; 4 import javax.swing.JFrame; 5 import javax.swing.JPanel; 6 import javax.swing.SwingUtilities; 7 import javax.swing.UIManager; 8 9 /** 10 * 帶有按鈕面板的框架,用於改變外觀和感受 11 */ 12 public class PlafFrame extends JFrame 13 { 14 private JPanel buttonPanel; 15 16 public PlafFrame() 17 { 18 buttonPanel = new JPanel(); 19 20 UIManager.LookAndFeelInfo[] infos = UIManager.getInstalledLookAndFeels(); 21 for (UIManager.LookAndFeelInfo info : infos) 22 makeButton(info.getName(), info.getClassName()); 23 24 add(buttonPanel); 25 pack(); 26 } 27 28 /** 29 * 製做一個按鈕來改變可插拔的外觀和感受. 30 * @param 命名按鈕名稱 31 * @param 類名:外觀類的名稱 32 */ 33 private void makeButton(String name, String className) 34 { 35 // 向面板添加按鈕 36 37 JButton button = new JButton(name); 38 buttonPanel.add(button); 39 40 // 設置按鈕動做 41 42 button.addActionListener(event -> { 43 //按鈕動做:切換到新的外觀和感受 44 try 45 { 46 UIManager.setLookAndFeel(className); 47 SwingUtilities.updateComponentTreeUI(this); 48 pack(); 49 } 50 catch (Exception e) 51 { 52 e.printStackTrace(); 53 } 54 }); 55 } 56 }
1 package plaf; 2 3 import java.awt.*; 4 import javax.swing.*; 5 6 /** 7 * @version 1.32 2015-06-1222222222222222222222222222 8 * @author Cay Horstmann 9 */ 10 public class PlafTest 11 { 12 public static void main(String[] args) 13 { 14 EventQueue.invokeLater(() -> { 15 JFrame frame = new PlafFrame(); 16 frame.setTitle("PlafTest"); 17 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 18 frame.setVisible(true); 19 }); 20 } 21 }
測試程序3:
1.在elipse IDE中調試運行教材457頁-458頁程序11-3,結合程序運行結果理解程序;
2.掌握AbstractAction類及其動做對象;
3.掌握GUI程序中按鈕、鍵盤動做映射到動做對象的方法。
1 package action; 2 3 import java.awt.*; 4 import javax.swing.*; 5 6 /** 7 * @version 1.34 2015-06-1233333333333333333333333333 8 * @author Cay Horstmann 9 */ 10 public class ActionTest 11 { 12 public static void main(String[] args) 13 { 14 EventQueue.invokeLater(() -> { 15 JFrame frame = new ActionFrame(); 16 frame.setTitle("ActionTest"); 17 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 18 frame.setVisible(true); 19 }); 20 } 21 }
1 package action; 2 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 /** 8 * 具備顯示顏色變化動做的面板的框架 9 */ 10 public class ActionFrame extends JFrame 11 { 12 private JPanel buttonPanel; 13 private static final int DEFAULT_WIDTH = 300; 14 private static final int DEFAULT_HEIGHT = 200; 15 16 public ActionFrame() 17 { 18 setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); 19 20 buttonPanel = new JPanel(); 21 22 // 定義動做 23 Action yellowAction = new ColorAction("Yellow", new ImageIcon("yellow-ball.gif"), 24 Color.YELLOW); 25 Action blueAction = new ColorAction("Blue", new ImageIcon("blue-ball.gif"), Color.BLUE); 26 Action redAction = new ColorAction("Red", new ImageIcon("red-ball.gif"), Color.RED); 27 28 // 爲這些操做添加按鈕 29 buttonPanel.add(new JButton(yellowAction)); 30 buttonPanel.add(new JButton(blueAction)); 31 buttonPanel.add(new JButton(redAction)); 32 33 // 將面板添加到幀 34 add(buttonPanel); 35 36 // 將Y、B和R鍵與名稱關聯 37 InputMap imap = buttonPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); 38 imap.put(KeyStroke.getKeyStroke("ctrl Y"), "panel.yellow"); 39 imap.put(KeyStroke.getKeyStroke("ctrl B"), "panel.blue"); 40 imap.put(KeyStroke.getKeyStroke("ctrl R"), "panel.red"); 41 42 // 把名字和動做聯繫起來 43 ActionMap amap = buttonPanel.getActionMap(); 44 amap.put("panel.yellow", yellowAction); 45 amap.put("panel.blue", blueAction); 46 amap.put("panel.red", redAction); 47 } 48 49 public class ColorAction extends AbstractAction 50 { 51 /** 52 * 構造顏色動做。 53 * @param 在按鈕上顯示要顯示的名稱 54 * @param 圖標按鈕上顯示的圖標 55 * @param 背景顏色 56 */ 57 public ColorAction(String name, Icon icon, Color c) 58 { 59 putValue(Action.NAME, name); 60 putValue(Action.SMALL_ICON, icon); 61 putValue(Action.SHORT_DESCRIPTION, "Set panel color to " + name.toLowerCase()); 62 putValue("color", c); 63 } 64 65 public void actionPerformed(ActionEvent event) 66 { 67 Color c = (Color) getValue("color"); 68 buttonPanel.setBackground(c); 69 } 70 } 71 }
測試程序4:
1.在elipse IDE中調試運行教材462頁程序11-四、11-5,結合程序運行結果理解程序;
2.掌握GUI程序中鼠標事件處理技術。
1 package mouse; 2 3 import java.awt.*; 4 import javax.swing.*; 5 6 /** 7 * @version 1.34 2015-06-12 8 * @author Cay Horstmann 9 */ 10 public class MouseTest 11 { 12 public static void main(String[] args) 13 { 14 EventQueue.invokeLater(() -> { 15 JFrame frame = new MouseFrame(); 16 frame.setTitle("MouseTest"); 17 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 18 frame.setVisible(true); 19 }); 20 } 21 }
1 package mouse; 2 3 import javax.swing.*; 4 5 /** 6 * 包含用於測試鼠標操做的面板的框架 7 */ 8 public class MouseFrame extends JFrame 9 { 10 public MouseFrame() 11 { 12 add(new MouseComponent()); 13 pack(); 14 } 15 }
1 package mouse; 2 3 import java.awt.*; 4 import java.awt.event.*; 5 import java.awt.geom.*; 6 import java.util.*; 7 import javax.swing.*; 8 9 /** 10 *一個帶有鼠標操做的用於添加和刪除正方形的組件。 11 */ 12 public class MouseComponent extends JComponent 13 { 14 private static final int DEFAULT_WIDTH = 300; 15 private static final int DEFAULT_HEIGHT = 200; 16 17 private static final int SIDELENGTH = 10; 18 private ArrayList<Rectangle2D> squares; 19 private Rectangle2D current; // 包含鼠標光標的正方形 20 21 public MouseComponent() 22 { 23 squares = new ArrayList<>(); 24 current = null; 25 26 addMouseListener(new MouseHandler()); 27 addMouseMotionListener(new MouseMotionHandler()); 28 } 29 30 public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); } 31 32 public void paintComponent(Graphics g) 33 { 34 Graphics2D g2 = (Graphics2D) g; 35 36 // 繪製全部正方形 37 for (Rectangle2D r : squares) 38 g2.draw(r); 39 } 40 41 /** 42 * 找到包含一個點的第一個方塊。 43 * @param P—A點 44 * @return 包含P的第一個正方形 45 */ 46 public Rectangle2D find(Point2D p) 47 { 48 for (Rectangle2D r : squares) 49 { 50 if (r.contains(p)) return r; 51 } 52 return null; 53 } 54 55 /** 56 * 向集合中添加正方形。 57 * @param 新聞中心 58 */ 59 public void add(Point2D p) 60 { 61 double x = p.getX(); 62 double y = p.getY(); 63 64 current = new Rectangle2D.Double(x - SIDELENGTH / 2, y - SIDELENGTH / 2, SIDELENGTH, 65 SIDELENGTH); 66 squares.add(current); 67 repaint(); 68 } 69 70 /** 71 * 從集合中移除正方形。 72 * @param S方移除 73 */ 74 public void remove(Rectangle2D s) 75 { 76 if (s == null) return; 77 if (s == current) current = null; 78 squares.remove(s); 79 repaint(); 80 } 81 82 private class MouseHandler extends MouseAdapter 83 { 84 public void mousePressed(MouseEvent event) 85 { 86 // 若是光標不在正方形中,則添加一個新的正方形 87 current = find(event.getPoint()); 88 if (current == null) add(event.getPoint()); 89 } 90 91 public void mouseClicked(MouseEvent event) 92 { 93 // 若是雙擊,則移除當前正方形 94 current = find(event.getPoint()); 95 if (current != null && event.getClickCount() >= 2) remove(current); 96 } 97 } 98 99 private class MouseMotionHandler implements MouseMotionListener 100 { 101 public void mouseMoved(MouseEvent event) 102 { 103 // 設置鼠標光標,若是裏面是交叉頭髮 104 // 矩形 105 106 if (find(event.getPoint()) == null) setCursor(Cursor.getDefaultCursor()); 107 else setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); 108 } 109 110 public void mouseDragged(MouseEvent event) 111 { 112 if (current != null) 113 { 114 int x = event.getX(); 115 int y = event.getY(); 116 117 // 拖動當前矩形將其置於(x,y)中心 118 current.setFrame(x - SIDELENGTH / 2, y - SIDELENGTH / 2, SIDELENGTH, SIDELENGTH); 119 repaint(); 120 } 121 } 122 } 123 }
實驗2:結對編程練習
利用班級名單文件、文本框和按鈕組件,設計一個有界面的點名器,要求用戶點擊開始按鈕後在文本輸入框隨機顯示2017級網絡與信息安全班同窗姓名,點擊中止按鈕後,文本輸入框再也不變換同窗姓名,此同窗則是被點到的同窗姓名。
1 package Roll_call_device; 2 3 4 import java.awt.Color; 5 import java.awt.FlowLayout; 6 import java.awt.Label; 7 import java.awt.event.ActionEvent; 8 import java.awt.event.ActionListener; 9 import java.io.BufferedReader; 10 import java.io.File; 11 import java.io.FileInputStream; 12 import java.io.IOException; 13 import java.io.InputStreamReader; 14 import java.util.ArrayList; 15 16 import javax.swing.JButton; 17 import javax.swing.JFrame; 18 import javax.swing.Timer; 19 20 public class Rollcall 21 { 22 public static void main(String args[]) 23 { 24 try { 25 Dmq dmq = new Dmq(); 26 dmq.lab.setText("隨機點名器"); 27 dmq.setTitle("點名器"); 28 } catch (IOException e) 29 { 30 // TODO Auto-generated catch block 31 e.printStackTrace(); 32 } 33 } 34 } 35 36 class Dmq extends JFrame 37 { 38 final Label lab = new Label(); 39 ArrayList<String> namelist = new ArrayList<String>(); 40 41 public Dmq() throws IOException 42 { 43 File file = new File("src/studentnamelist.txt"); 44 FileInputStream fis = new FileInputStream(file); 45 InputStreamReader isr = new InputStreamReader(fis, "GBK"); 46 BufferedReader br = new BufferedReader(isr); 47 String line = ""; 48 while ((line = br.readLine()) != null) 49 { 50 if (line.lastIndexOf("---") < 0) 51 { 52 namelist.add(line); 53 } 54 } 55 setBounds(550, 270, 200, 150); 56 final Timer timer = new Timer(50, new ActionListener() 57 { 58 public void actionPerformed(ActionEvent e) 59 { 60 lab.setText(namelist.get((int) (Math.random() * namelist.size()))); 61 } 62 }); 63 64 JButton jbutton = new JButton("開始"); 65 jbutton.addActionListener(new ActionListener() 66 { 67 public void actionPerformed(ActionEvent e) 68 { 69 JButton jbutton = (JButton) e.getSource(); 70 if (jbutton.getText().equals("開始")) 71 { 72 jbutton.setText("中止"); 73 timer.start(); 74 } else if (jbutton.getText().equals("中止")) 75 { 76 jbutton.setText("開始"); 77 timer.stop(); 78 } 79 80 } 81 }); 82 jbutton.setBounds(30, 30, 30, 30); 83 lab.setBackground(new Color(255, 255, 255)); 84 this.setLayout(new FlowLayout()); 85 this.add(lab); 86 this.add(jbutton); 87 this.setSize(300, 200); 88 this.setVisible(true); 89 this.setDefaultCloseOperation(EXIT_ON_CLOSE); 90 br.close(); 91 } 92 93 }
第三部分:總結
經過本週的學習,我掌握了事件處理的基本原理,理解了用途;並瞭解學習瞭如下幾點。AWT事件模型的工做機制;事件處理的基本編程模型;瞭解了GUI界面組件觀感設置方法;WindowAdapter類、AbstractAction類的用法;GUI程序中鼠標事件處理技術。而且在看了助教學長的教學視頻和同窗的幫助下,學會了如何設計一個小型界面,受益頗多!