日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

李晓菁201771010114《面向对象程序设计(java)》第十三周学习总结

發(fā)布時間:2023/12/10 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 李晓菁201771010114《面向对象程序设计(java)》第十三周学习总结 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

理論知識:事件處理

1.事件源:能夠產(chǎn)生事件的對象都可以成為事件源,如文本框,按鈕等。一個事件源是一個能夠注冊監(jiān)聽器并向監(jiān)聽器發(fā)送事件對象的對象。

2.事件監(jiān)聽器:事件監(jiān)聽器對象接收事件源發(fā)送的通告(事件對象),并對發(fā)生的事件作出響應(yīng)。一個監(jiān)聽器對象就是一個實現(xiàn)了專門監(jiān)聽器接口的類實例,該類必須實現(xiàn)接口中的方法,這些方法當事件發(fā)生時,被自動執(zhí)行。

3.事件對象:Java將事件的相關(guān)信息封裝在一個事件對象中,所有的事件對象都最終被派生于Java.util.EventObject類。不同的事件源可以產(chǎn)生不同類別的事件。

2.AWT事件處理機制的概要;

監(jiān)聽器對象 :是一個實現(xiàn)了特定監(jiān)聽器接口 ( listener interface )的類實例 。

當事件發(fā)生時,事件源將事件對象自動傳遞給所有注冊的監(jiān)聽器 。

監(jiān)聽器對象利用事件對象中的信息決定如何對事件做出響應(yīng)。

?3.事件源與監(jiān)聽器之間的關(guān)系:

?

4.GUI設(shè)計中,程序員需要對組件的某種事件進行響應(yīng)和處理時,必須完成兩個步驟;

(1)定義實現(xiàn)某事件監(jiān)聽器接口的事件監(jiān)聽器類,并具體化接口中聲明的事件的處理抽象方法。

(2)為組件注冊實現(xiàn)了規(guī)定接口的事件監(jiān)聽器對象;

5.注冊監(jiān)聽器方法:eventSourceObject.addEventListener(eventListenerObject)

?6.動態(tài)事件:當特定組件動作(點擊按鈕)發(fā)生時,該組件生成此動作事件。

該事件被傳遞給組件注冊的每一個ActionListener對象,并調(diào)用監(jiān)聽器對象的actionPerformed方法以接受這類事件對象。

能夠觸發(fā)事件動作的動作,主要包括:

(1)點擊按鈕

(2)雙擊一個列表中的選項

(3)選擇菜單項

(4)在文本框中輸入回車

7.監(jiān)聽器接口的實現(xiàn)

監(jiān)聽器類必須實現(xiàn)與事件源相對應(yīng)的接口,即必須提供接口中方法的實現(xiàn)。

監(jiān)聽器接口的方法實現(xiàn)

class MyListener implenments ActionListener

{

? ? public void actionPerformed(ActionEvent event)

{......}

}

8.命令按鈕Jbutton主要API

(1)創(chuàng)建按鈕對象

Jbutton類常用的一組構(gòu)造方法;

(1) JButton(String text):創(chuàng)建一個帶文本的按鈕。
(2) JButton(Icon icon) :創(chuàng)建一個帶圖標的按鈕。
(3)JButton(String text, Icon icon) :創(chuàng)建一個帶文本和圖標
的按鈕

(2)按鈕對象的常用方法:

① getLabel( ):返回按鈕的標簽字符串;
② setLabel(String s):設(shè)置按鈕的標簽為字符串s。

9.?用匿名類、lambda表達式簡化程序

例ButtonTest.java中,各按鈕需要同樣的處理:
1) 使用字符串構(gòu)造按鈕對象;
2) 把按鈕添加到面板上;
3) 用對應(yīng)的顏色構(gòu)造一個動作監(jiān)聽器;
4) 注冊動作監(jiān)聽器

10.適配器類

當程序用戶試圖關(guān)閉一個框架窗口時,Jframe
對象就是WindowEvent的事件源。
? 捕獲窗口事件的監(jiān)聽器:

WindowListener listener=…..;
frame.addWindowListener(listener);
? 窗口監(jiān)聽器必須是實現(xiàn)WindowListener接口的
類的一個對象,WindowListener接口中有七個
方法,它們的名字是自解釋的。

11.鑒于代碼簡化的要求,對于有不止一個方法的AWT監(jiān)聽器接口都有一個實現(xiàn)了它的所有方法,但卻

不做任何工作的適配器類。
例:WindowAdapter類。

適配器類動態(tài)地滿足了Java中實現(xiàn)監(jiān)視器類的技術(shù)要求。

? 通過擴展適配器類來實現(xiàn)窗口事件需要的動作

12.注冊事件監(jiān)聽器

可將一個Terminator對象注冊為事件監(jiān)聽器:
WindowListener listener=new Terminator();
frame.addWindowListener(listener);
? 只要框架產(chǎn)生一個窗口事件,該事件就會傳遞給
監(jiān)聽器對象。

創(chuàng)建擴展于WindowAdapter的監(jiān)聽器類是很好的
改進,但還可以進一步將上面語句也可簡化為:
frame.addWindowListener(new Terminator());

13.動作事件

(1)激活一個命令可以有多種方式,如用戶可以通過
菜單、擊鍵或工具欄上的按鈕選擇特定的功能。
(2)在AWT事件模型中,無論是通過哪種方式下達命
令(如:點擊按鈕、菜單選項、按下鍵盤),其
操作動作都是一樣的。

14.動作接口及其類

Swing包提供了非常實用的機制來封裝命令,并將它
們連接到多個事件源,這就是Action接口。
? 動作對象是一個封裝下列內(nèi)容的對象:
–命令的說明:一個文本字符串和一個可選圖標;
–執(zhí)行命令所需要的參數(shù)。

? Action是一個接口,而不是一個類,實現(xiàn)這個接
口的類必須要實現(xiàn)它的7個方法。
? AbstractAction 類 實 現(xiàn) 了 Action 接 口 中 除
actionPerformed方法之外的所有方法,這個類存
儲了所有名/值對,并管理著屬性變更監(jiān)聽器。

在 動 作 事 件 處 理 應(yīng) 用 中 , 可 以 直 接 擴 展
AbstractAction 類 , 并 在 擴 展 類 中 實 現(xiàn)
actionPerformed方法。

15.鼠標事件

? 鼠標事件
– MouseEvent
? 鼠標監(jiān)聽器接口
– MouseListener
– MouseMotionListener
? 鼠標監(jiān)聽器適配器
– MouseAdapter
– MouseMotionAdapter

用戶點擊鼠標按鈕時,會調(diào)用三個監(jiān)聽器方法:
– 鼠標第一次被按下時調(diào)用mousePressed方法;
– 鼠標被釋放時調(diào)用mouseReleased方法;
– 兩個動作完成之后,調(diào)用mouseClicked方法。
? 鼠標在組件上移動時,會調(diào)用mouseMoved方法。

如果鼠標在移動的時候還按下了鼠標,則會調(diào)用
mouseDragged方法

? 鼠標事件返回值
– 鼠標事件的類型是MouseEvent,當發(fā)生鼠標事件時:
MouseEvent類自動創(chuàng)建一個事件對象,以及事件發(fā)生
位置的x和y坐標,作為事件返回值。

MouseEvent類中的重要方法
– public int getX( );
– public int getY( );
– public Point getPoint( );
– public int getClickCount( );

實驗十三 ?圖形界面事件處理技術(shù)

實驗時間 2018-11-22

1、實驗?zāi)康呐c要求

(1) 掌握事件處理的基本原理,理解其用途;

(2) 掌握AWT事件模型的工作機制;

(3)?掌握事件處理的基本編程模型;

(4) 了解GUI界面組件觀感設(shè)置方法;

(5) 掌握WindowAdapter類、AbstractAction類的用法;

(6) 掌握GUI程序中鼠標事件處理技術(shù)。

2、實驗內(nèi)容和步驟

實驗1:?導(dǎo)入第11章示例程序,測試程序并進行代碼注釋。

測試程序1:

l?在elipse IDE中調(diào)試運行教材443頁-444頁程序11-1,結(jié)合程序運行結(jié)果理解程序;

l?在事件處理相關(guān)代碼處添加注釋;

l?lambda表達式簡化程序;

l?掌握JButton組件的基本API;

l?掌握Java中事件處理的基本編程模型。

package button;import java.awt.*; import javax.swing.*;/*** @version 1.34 2015-06-12* @author Cay Horstmann*/ public class ButtonTest {public static void main(String[] args){EventQueue.invokeLater(() -> {JFrame frame = new ButtonFrame();frame.setTitle("ButtonTest");//設(shè)置窗口的標題 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);//將窗口設(shè)為可見的 });} } button package button;import java.awt.*; import java.awt.event.*; import javax.swing.*;/*** A frame with a button panel*/ public class ButtonFrame extends JFrame {private JPanel buttonPanel;//該類對象屬性private static final int DEFAULT_WIDTH = 300;private static final int DEFAULT_HEIGHT = 200;public ButtonFrame(){ setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);//通過setsize來更改框架的寬度和高度// create buttonsJButton yellowButton = new JButton("Yellow");JButton blueButton = new JButton("Blue");JButton redButton = new JButton("Red");//生成三個按鈕對象,string影響的是顯示在button上的文本 buttonPanel = new JPanel();// add buttons to panel buttonPanel.add(yellowButton);buttonPanel.add(blueButton);buttonPanel.add(redButton);//向內(nèi)容窗格添加三個容器組件// add panel to frame add(buttonPanel);// create button actionsColorAction yellowAction = new ColorAction(Color.YELLOW);ColorAction blueAction = new ColorAction(Color.BLUE);ColorAction redAction = new ColorAction(Color.RED);//生成三個ColorAction(監(jiān)聽器類)對象// associate actions with buttons yellowButton.addActionListener(yellowAction);blueButton.addActionListener(blueAction);redButton.addActionListener(redAction);//將對應(yīng)的監(jiān)聽器類和組件之間進行注冊 }/*** An action listener that sets the panel's background color.*/private class ColorAction implements ActionListener//實現(xiàn)監(jiān)聽器接口 {private Color backgroundColor;public ColorAction(Color c){backgroundColor = c;}public void actionPerformed(ActionEvent event){buttonPanel.setBackground(backgroundColor);//更改背景色 }} } buttonFrame

通過內(nèi)部類方法實現(xiàn):

package button;import java.awt.*; import java.awt.event.*; import javax.swing.*;/*** A frame with a button panel*/ public class ButtonFrame extends JFrame {private JPanel buttonPanel;// 該類對象屬性private static final int DEFAULT_WIDTH = 300;private static final int DEFAULT_HEIGHT = 200;public ButtonFrame() {setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);// 通過setsize來更改框架的寬度和高度 buttonPanel = new JPanel();add(buttonPanel);makeButton("yellow", Color.yellow);makeButton("blue", Color.blue);makeButton("red", Color.red);makeButton("green", Color.green);//添加一個新的組件只需要該條語句 }public void makeButton(String name, Color backgroundColor) {JButton button = new JButton(name);buttonPanel.add(button);ColorAction action = new ColorAction(backgroundColor);button.addActionListener(action);}/*** An action listener that sets the panel's background color.*/private class ColorAction implements ActionListener// 實現(xiàn)監(jiān)聽器接口 {private Color backgroundColor;public ColorAction(Color c) {backgroundColor = c;}public void actionPerformed(ActionEvent event) {buttonPanel.setBackground(backgroundColor);// 更改背景色 }} } buttonFrame

通過匿名內(nèi)部類方法實現(xiàn):

package button;import java.awt.*; import java.awt.event.*; import javax.swing.*;/*** A frame with a button panel*/ public class ButtonFrame extends JFrame {private JPanel buttonPanel;// 該類對象屬性private static final int DEFAULT_WIDTH = 300;private static final int DEFAULT_HEIGHT = 200;public ButtonFrame() {setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);// 通過setsize來更改框架的寬度和高度 buttonPanel = new JPanel();add(buttonPanel);makeButton("yellow", Color.yellow);makeButton("blue", Color.blue);makeButton("red", Color.red);makeButton("green", Color.green);// 添加一個新的組件只需要該條語句 }public void makeButton(String name, Color backgroundColor) {JButton button = new JButton(name);buttonPanel.add(button);// ColorAction action = new ColorAction(backgroundColor);// button.addActionListener(action);button.addActionListener(new ActionListener() {// 不能直接使用接口,new后面有一個匿名的類名,后面的ActionListener通過匿名類調(diào)用 @Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stub buttonPanel.setBackground(backgroundColor);}});}} buttonFrame

通過lambda表達式實現(xiàn):

package button;import java.awt.*; import java.awt.event.*; import javax.swing.*;/*** A frame with a button panel*/ public class ButtonFrame extends JFrame {private JPanel buttonPanel;// 該類對象屬性private static final int DEFAULT_WIDTH = 300;private static final int DEFAULT_HEIGHT = 200;public ButtonFrame() {setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);// 通過setsize來更改框架的寬度和高度 buttonPanel = new JPanel();add(buttonPanel);makeButton("yellow", Color.yellow);makeButton("blue", Color.blue);makeButton("red", Color.red);makeButton("green", Color.green);// 添加一個新的組件只需要該條語句 }public void makeButton(String name, Color backgroundColor) {JButton button = new JButton(name);buttonPanel.add(button);button.addActionListener((e) -> {buttonPanel.setBackground(backgroundColor);});}} buttonFrame

通過以上三種方式實現(xiàn)事件處理的基本代碼越來越簡化。

測試程序2:

l?在elipse IDE中調(diào)試運行教材449頁程序11-2,結(jié)合程序運行結(jié)果理解程序;

l?在組件觀感設(shè)置代碼處添加注釋;

l?了解GUI程序中觀感的設(shè)置方法。

package plaf;import java.awt.*; import javax.swing.*;/*** @version 1.32 2015-06-12* @author Cay Horstmann*/ public class PlafTest {public static void main(String[] args){EventQueue.invokeLater(() -> {JFrame frame = new PlafFrame();frame.setTitle("PlafTest");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);});} } plaf package plaf;import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.UIManager;/*** A frame with a button panel for changing look-and-feel*/ public class PlafFrame extends JFrame {private JPanel buttonPanel;public PlafFrame(){buttonPanel = new JPanel(); //組件觀感設(shè)置UIManager.LookAndFeelInfo[] infos = UIManager.getInstalledLookAndFeels();//UIManager 管理當前外觀、可用外觀集合及獲取各種默認值的便捷方法。//返回表示當前可用的 LookAndFeel 實現(xiàn)的 LookAndFeelInfo 數(shù)組。應(yīng)用程序可以使用 LookAndFeelInfo 對象為用戶構(gòu)造外觀選項的菜單,或確定在啟動時要設(shè)置哪個外觀 for (UIManager.LookAndFeelInfo info : infos)makeButton(info.getName(), info.getClassName()); //適合菜單或其他展示的形式返回外觀的名稱 ,返回實現(xiàn)此外觀的類名稱 add(buttonPanel);pack();//調(diào)整此窗口的大小,以適合其子組件的首選大小和布局 }/*** Makes a button to change the pluggable look-and-feel.* @param name the button name* @param className the name of the look-and-feel class*/private void makeButton(String name, String className){// add button to panel JButton button = new JButton(name);buttonPanel.add(button);// set button action button.addActionListener(event -> {// button action: switch to the new look-and-feeltry{UIManager.setLookAndFeel(className);SwingUtilities.updateComponentTreeUI(this);//簡單的外觀更改 pack();}catch (Exception e){e.printStackTrace();}});} } plafFrame

不同的組件有不同的觀感

測試程序3:

l?在elipse IDE中調(diào)試運行教材457頁-458頁程序11-3,結(jié)合程序運行結(jié)果理解程序;

l?掌握AbstractAction類及其動作對象;

l?掌握GUI程序中按鈕、鍵盤動作映射到動作對象的方法。

package action;import java.awt.*; import javax.swing.*;/*** @version 1.34 2015-06-12* @author Cay Horstmann*/ public class ActionTest {public static void main(String[] args){EventQueue.invokeLater(() -> {JFrame frame = new ActionFrame();frame.setTitle("ActionTest");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);});} } action package action;import java.awt.*; import java.awt.event.*; import javax.swing.*;/*** A frame with a panel that demonstrates color change actions.*/ public class ActionFrame extends JFrame {private JPanel buttonPanel;private static final int DEFAULT_WIDTH = 300;private static final int DEFAULT_HEIGHT = 200;public ActionFrame(){setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);buttonPanel = new JPanel();// define actionsAction yellowAction = new ColorAction("Yellow", new ImageIcon("yellow-ball.gif"),//Action 接口提供 ActionListener 接口的一個有用擴展,以便若干控件訪問相同的功能Color.YELLOW);//可以將此接口添加到現(xiàn)有類中,或者用它創(chuàng)建一個適配器(通常通過子類化 AbstractAction 來實現(xiàn))。Action blueAction = new ColorAction("Blue", new ImageIcon("blue-ball.gif"), Color.BLUE);Action redAction = new ColorAction("Red", new ImageIcon("red-ball.gif"), Color.RED); //根據(jù)指定的文件創(chuàng)建一個 ImageIcon。使用 MediaTracker 預(yù)載圖像以監(jiān)視圖像的加載狀態(tài)。指定 String 可以是一個文件名或是一條文件路徑。// add buttons for these actionsbuttonPanel.add(new JButton(yellowAction));buttonPanel.add(new JButton(blueAction));buttonPanel.add(new JButton(redAction));// add panel to frameadd(buttonPanel);//添加組件// associate the Y, B, and R keys with namesInputMap imap = buttonPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);//使用繼承自 JComponent 的組件//當接收組件是獲得焦點的組件的祖先或者其本身就是獲得焦點的組件時,應(yīng)該調(diào)用命令。 imap.put(KeyStroke.getKeyStroke("ctrl Y"), "panel.yellow");imap.put(KeyStroke.getKeyStroke("ctrl B"), "panel.blue");imap.put(KeyStroke.getKeyStroke("ctrl R"), "panel.red");//InputMap 提供輸入事件(目前只使用 KeyStroke)和 Object 之間的綁定。InputMap 通常與 ActionMap 一起使用,//以確定按下鍵時執(zhí)行一個 Action。InputMap 可以有一個父級,可搜索它來獲得 InputMap 中未定義的綁定。// associate the names with actionsActionMap amap = buttonPanel.getActionMap();amap.put("panel.yellow", yellowAction);amap.put("panel.blue", blueAction);amap.put("panel.red", redAction);//ActionMap 提供從 Object(稱為鍵 或 Action 名)到 Action 的映射。當按下某一個鍵時,ActionMap 通常與 InputMap 一起使用來定位特定操作。//與 InputMap 一同使用時,ActionMap 可以有一個父級,用來搜索沒有在該 ActionMap 中定義的鍵。 }public class ColorAction extends AbstractAction{/*** Constructs a color action.* @param name the name to show on the button* @param icon the icon to display on the button* @param c the background color*/public ColorAction(String name, Icon icon, Color c){//putvalue設(shè)置與指定鍵關(guān)聯(lián)的值putValue(Action.NAME, name);//用于菜單或按鈕的名字putValue(Action.SMALL_ICON, icon);//該鍵通常用于菜單,同時指定了要使用SMALL-ICONputValue(Action.SHORT_DESCRIPTION, "Set panel color to " + name.toLowerCase());//用來存儲動作的簡短 String 描述的鍵,用于工具提示文本。//toLowerCase使用默認語言環(huán)境的規(guī)則將此 String 中的所有字符都轉(zhuǎn)換為小寫putValue("color", c);}public void actionPerformed(ActionEvent event)//actionListener中的一個方法 {Color c = (Color) getValue("color");buttonPanel.setBackground(c);}} } actionFrame

?

測試程序4:

l?在elipse IDE中調(diào)試運行教材462頁程序11-4、11-5,結(jié)合程序運行結(jié)果理解程序;

l?掌握GUI程序中鼠標事件處理技術(shù)。

package mouse;import java.awt.*; import javax.swing.*;/*** @version 1.34 2015-06-12* @author Cay Horstmann*/ public class MouseTest {public static void main(String[] args){EventQueue.invokeLater(() -> {JFrame frame = new MouseFrame();frame.setTitle("MouseTest");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);});} } mouse package mouse;import javax.swing.*;/*** A frame containing a panel for testing mouse operations*/ public class MouseFrame extends JFrame {public MouseFrame(){add(new MouseComponent());pack();} } mouseFrame package mouse;import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.util.*; import javax.swing.*;/*** A component with mouse operations for adding and removing squares.*/ public class MouseComponent extends JComponent {private static final int DEFAULT_WIDTH = 300;private static final int DEFAULT_HEIGHT = 200;private static final int SIDELENGTH = 10;private ArrayList<Rectangle2D> squares;//Rectangle2D 類描述通過位置 (x,y) 和尺寸 (w x h) 定義的矩形private Rectangle2D current; // the square containing the mouse cursorpublic MouseComponent(){squares = new ArrayList<>();//構(gòu)造一個空列表current = null;addMouseListener(new MouseHandler());//添加鼠標監(jiān)聽器addMouseMotionListener(new MouseMotionHandler());//添加指定的鼠標移動偵聽器,以接收發(fā)自此組件的鼠標移動事件。 }public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); } //如果 preferredSize 已設(shè)置為一個非 null 值,則返回該值。如果 UI 委托的 getPreferredSize 方法返回一個非 null 值,則返回該值;public void paintComponent(Graphics g){Graphics2D g2 = (Graphics2D) g;// draw all squaresfor (Rectangle2D r : squares)g2.draw(r);//在畫布上畫出一個矩形 }/*** Finds the first square containing a point.* @param p a point* @return the first square that contains p*/public Rectangle2D find(Point2D p)//通過位置 (x,y) 和尺寸 (w x h) 定義的矩形。 {for (Rectangle2D r : squares){if (r.contains(p)) return r;//測試指定的 Point2D 是否在 Shape 的邊界內(nèi) }return null;}/*** Adds a square to the collection.* @param p the center of the square*/public void add(Point2D p){double x = p.getX();//返回該圖形的X,Y坐標double y = p.getY();current = new Rectangle2D.Double(x - SIDELENGTH / 2, y - SIDELENGTH / 2, SIDELENGTH,SIDELENGTH);squares.add(current);repaint();}/*** Removes a square from the collection.* @param s the square to remove*/public void remove(Rectangle2D s){if (s == null) return;if (s == current) current = null;squares.remove(s);repaint();}private class MouseHandler extends MouseAdapter//鼠標監(jiān)聽器適配器 {public void mousePressed(MouseEvent event)//鼠標按鍵在組件上按下時調(diào)用mousepressed方法, {// add a new square if the cursor isn't inside a squarecurrent = find(event.getPoint());if (current == null) add(event.getPoint());//若鼠標指針不在之前的矩形內(nèi),則點擊鼠標時,重新畫一個矩形 }public void mouseClicked(MouseEvent event)//鼠標按鍵在組件上單擊(按下并釋放)時調(diào)用。 {// remove the current square if double clickedcurrent = find(event.getPoint());if (current != null && event.getClickCount() >= 2) remove(current);//當鼠標在矩形框內(nèi)雙擊時,取消該矩形框 }}private class MouseMotionHandler implements MouseMotionListener//實現(xiàn)移動監(jiān)聽器接口 {public void mouseMoved(MouseEvent event)//鼠標光標移動到組件上但無按鍵按下時調(diào)用 {// set the mouse cursor to cross hairs if it is inside// a rectangleif (find(event.getPoint()) == null) setCursor(Cursor.getDefaultCursor());//為指定的光標設(shè)置光標圖像else setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));//十字光標類型。 }public void mouseDragged(MouseEvent event)//鼠標按鍵在組件上按下并拖動時調(diào)用。在釋放鼠標按鍵前,MOUSE_DRAGGED 事件被連續(xù)地傳遞到發(fā)起該拖動的組件(而不管鼠標位置是否處于該組件的邊界內(nèi))。 {if (current != null){int x = event.getX();int y = event.getY(); //當發(fā)生鼠標事件時: MouseEvent類自動創(chuàng)建一個事件對象,以及事件發(fā)生位置的x和y坐標,作為事件返回值。// drag the current rectangle to center it at (x, y)current.setFrame(x - SIDELENGTH / 2, y - SIDELENGTH / 2, SIDELENGTH, SIDELENGTH);repaint();//重組此繪件 }}} } mousecomponent

當鼠標點擊畫布時,繪制一個矩形,當鼠標在窗體上移動時,如果鼠標經(jīng)過一個小方塊的內(nèi)部,光標會變成一個十字形;

當雙擊一個小方塊內(nèi)部時,會擦除該小方塊;實現(xiàn)用鼠標拖動小方塊。

當鼠標點擊在所有小方塊的像素之外時,會繪制一個新的小方塊;

實驗2:結(jié)對編程練習(xí)

利用班級名單文件、文本框和按鈕組件,設(shè)計一個有如下界面(圖1)的點名器,要求用戶點擊開始按鈕后在文本輸入框隨機顯示2017級網(wǎng)絡(luò)與信息安全班同學(xué)姓名,如圖2所示,點擊停止按鈕后,文本輸入框不再變換同學(xué)姓名,此同學(xué)則是被點到的同學(xué)姓名。

?

1 點名器啟動界面

?

2 點名器點名界面

?

?

package 點名器;import java.util.*; import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.io.File; import java.io.FileNotFoundException;import javax.swing.event.*;public class NameFrame extends JFrame implements ActionListener {//采用多線程private JLabel jla;//JLabel 對象可以顯示文本、圖像或同時顯示二者。private JLabel jlb;private JButton jba;private static boolean flag = true;//定義一個靜態(tài)常量并將其值設(shè)置為truepublic NameFrame() {this.setLayout(null);//類 Container 中的 setLayout,設(shè)置 LayoutManager。重寫此方法,從而有條件地將調(diào)用轉(zhuǎn)發(fā)到 contentPane jla = new JLabel("姓名");jlb = new JLabel("準備中");jba = new JButton("開始");//創(chuàng)建按鈕并將其命名為開始this.add(jla);this.add(jlb);jla.setFont(new Font("Courier", Font.PLAIN, 25));//設(shè)置該組件的字體jla.setHorizontalAlignment(JLabel.CENTER);//設(shè)置標簽內(nèi)容沿 X 軸的對齊方式并在該區(qū)域的中心位置jla.setVerticalAlignment(JLabel.CENTER);//設(shè)置標簽內(nèi)容沿 Y 軸的對齊方式并在該區(qū)域的中心位置jla.setBounds(20, 100, 180, 30);jlb.setOpaque(true);//如果為 true,則該組件繪制其邊界內(nèi)的所有像素。否則該組件可能不繪制部分或所有像素,從而允許其底層像素透視出來。 jlb.setBackground(Color.cyan);//設(shè)置此組件的背景色。jlb.setFont(new Font("Courier", Font.PLAIN, 22));jlb.setHorizontalAlignment(JLabel.CENTER);jlb.setVerticalAlignment(JLabel.CENTER);jlb.setBounds(150, 100, 120, 30);this.add(jba);//設(shè)置開始按鈕的一些屬性jba.setBounds(150, 150, 80, 26);//移動組件并調(diào)整其大小。由 x 和 y 指定左上角的新位置,由 width 和 height 指定新的大小。 jba.addActionListener(this);//將一個 ActionListener 添加到按鈕中this.setTitle("點名器");this.setBounds(400, 400, 400, 300);this.setVisible(true);this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);//調(diào)用任意已注冊 WindowListener 的對象后自動隱藏并釋放該窗體。 }public void actionPerformed(ActionEvent e) {int i = 0;String names[] = new String[50];//創(chuàng)建一個數(shù)組,該數(shù)組的最大容量為50try {Scanner in = new Scanner(new File("D:\\studentnamelist.txt"));while (in.hasNextLine()) {//如果在此掃描器的輸入中存在另一行,則返回 true。在等待輸入信息時,此方法可能阻塞。掃描器不執(zhí)行任何輸入。 names[i] = in.nextLine();i++;//遍歷名單 }} catch (FileNotFoundException e1) {// TODO Auto-generated catch block e1.printStackTrace();}if (jba.getText() == "開始") {//返回按鈕的文本jlb.setBackground(Color.BLUE);//設(shè)置組件的背景色flag = true;new Thread() {//分配新的 Thread 對象。這種構(gòu)造方法與 Thread(null, null, gname) 具有相同的作用,其中 gname 是一個新生成的名稱。自動生成的名稱的形式為 "Thread-"+n,其中的 n 為整數(shù)。public void run() {while (NameFrame.flag) {Random r = new Random();int i = r.nextInt(47);jlb.setText(names[i]);//定義此組件將要顯示的單行文本。如果 text 值為 null 或空字符串,則什么也不顯示,此時為name則顯示停止時的名字 }}}.start();//使該線程開始執(zhí)行;Java 虛擬機調(diào)用該線程的 run 方法。jba.setText("停止");jba.setBackground(Color.ORANGE);} else if (jba.getText() == "停止") {flag = false;//當點擊按鈕的停止時,返回該按鈕的名字,并且變量flag的布爾值為flasejba.setText("開始");//按鈕的名字為開始jba.setBackground(Color.WHITE);//開始按鈕的顏色為白色jlb.setBackground(Color.gray);//未開始點擊開始按鈕時,姓名輸入框為灰色 }}public static void main(String arguments[]) {new NameFrame();} } nameframe

在點名器的程序設(shè)計中,完全沒有思路該如何寫,在學(xué)長的實例程序上做了注釋及稍許改動,但對于多線程還是沒有理解該如何使用。

?

?實驗總結(jié):通過本周學(xué)習(xí),我基本掌握了事件處理的基本原理及AWT事件模型的工作機制;掌握事件處理的基本編程模型;并用多種方法簡化代碼,在老師和學(xué)長的教導(dǎo)進一步

理解了匿名內(nèi)部類,但對于?GUI界面組件觀感設(shè)置方法還不太理解;?掌握了AbstractAction類的用法及GUI程序中鼠標事件處理技術(shù)。

?

轉(zhuǎn)載于:https://www.cnblogs.com/li-xiaojing/p/10002768.html

總結(jié)

以上是生活随笔為你收集整理的李晓菁201771010114《面向对象程序设计(java)》第十三周学习总结的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。