プロジェクト |
コンテンツ |
この作品は、コースに属し |
https://www.cnblogs.com/nwnu-daizh/ |
どこの仕事でこの要件 |
https://www.cnblogs.com/nwnu-daizh/p/11888568.html |
ジョブの学習目標 |
(1)は、その目的を理解し、イベント処理の基本原理を習得します。 (2)制御機構AWTイベントモデル。 (3)イベント処理のための基本的なプログラミングモデルを習得。 (4)GUIコンポーネント印象設定方法を学びます。 (5)WindowAdapterをマスタークラス、AbstractActionクラスの使用。 (6)GUIプログラムは、マウスイベント処理技術を習得します。 |
エッセイボーエン本文の内容は次のとおりです。
パートI:第十一章では、理論的な知識をまとめた(35ポイント)
11.1イベント処理モデル
イベントソース(イベントソース):イベントが生成することができるようにします
そのようなテキストボックス、ボタンなどなどイベントソース、になるために。イベントソースは、イベントオブジェクトを送信するリスナーオブジェクトにリスナーを登録することができます。
イベントリスナー(イベントリスナー):イベントリスナーオブジェクトイベントへの通知(イベントオブジェクト)イベント・ソース・送信し、応答を受け取ります。リスナーオブジェクトは、イベントが発生した場合、クラスは自動的に実行、インターフェースメソッド、これらのメソッドを実装する必要が実装リスナーインターフェースことクラスの特別なインスタンスです。
イベントオブジェクト(イベントオブジェクト):イベントオブジェクトのイベントでのJava関連情報パッケージは、すべてのイベント・オブジェクトは、最終的にjava.util.EventObjectクラスから派生されます。異なるイベント・ソースは、さまざまな種類のイベントを生成することができます。
11.1.1ハンドルのボタンのクリックイベント
私たちは熟練したイベント処理モデルを必要とするので、GUIアプリケーションの場合1.イベント処理は、必要不可欠です。イベントソースオブジェクトとリスナーオブジェクト:イベントのために我々は二つの用語を理解する必要があります。リスナーオブジェクトは、特定のクラスが実装するリスナーインタフェース(リスナーインタフェース)のインスタンスであり、イベントソースは、リスナーオブジェクトを登録することができ、イベントオブジェクトを送信します。文字通り、私たちは、のシステムを説明させ、について理解することができますオブジェクトは、イベントが発生したときに、すべての登録されたリスナーに渡されるイベントオブジェクトにイベント・ソース、リスナーオブジェクトは、それに応じてイベントにどのようにイベントオブジェクトを決定するための情報を使用します。
イベントが発生した場合、システムがイベントソースで、適切なリスナーにアクセスできるように、まず、我々は、イベントソースオブジェクトにリスナーオブジェクトを登録します。図は次のとおりです。
ときにトリガイベントのイベントソース、イベント情報システムは、イベントオブジェクトを対応するパッケージ型に入れ、イベントリスナーに対応するソース・レジスタに送信します。図は次のとおりです。
イベントオブジェクトがリスナーに、システムが応答するイベントを処理するための適切なイベントハンドラメソッドリスナーを呼び出すとき。図は次のとおりです。
注:リスナーとイベント・ソース間の「多くの多くの」の関係。
11.1.2シンプル指定されたリスナー
リスナーオブジェクトは、クラスが実装するリスナーインタフェースの特定のインスタンスで、リスナーインタフェースは、私たちが関係している質問です。トップレベルインターフェースリスナーインタフェースがたjava.util.EventListenerで、このインタフェースは、すべてのイベントリスナインタフェースがマーカーインターフェイスを拡張しなければならないということです。どのような驚きは、インターフェイスが空ああ内部のソースコードを表示するには、任意の抽象メソッドを定義しない、完全に空であるということです!
イベントリスナクラス(リスナーオブジェクトは、クラスに属する)イベントリスナインタフェースを実装したり、イベントリスナーのアダプタクラスを継承する必要があります。
イベントリスナーインタフェースは、イベントを処理するために実装しなければならないメソッドを定義します。
イベントリスナーアダプタクラスは、イベントリスナーインタフェースの簡単な実装です。目的は、プログラミングの労力を軽減することです。
Javaで、これらのインタフェースが定義されている、XXListener、および:イベントリスナーに名前を付けるのインタフェースです。イベントハンドラを定義し、実現すること(すなわち、プロトタイプのイベント処理方法、この方法は、再実装する必要があります)。
たとえば、次のActionListenerインターフェイス、のMouseListenerインターフェイス、のWindowListenerインターフェース、のKeyListenerインターフェイス、インターフェイスのItemListener、のMouseMotionListenerインタフェース、のFocusListenerインターフェイス、のComponentListenerインタフェース
11.1.3変更知覚
Swingのプログラムは、ルックアンドフィールを変更する2つの方法をデフォルトメタルルックアンドフィールを使用しています。
、Javaのインストールswing.propertiesサブディレクトリのjre / libの下にファイルの必要なルック&フィールクラス名にプロパティswing.defaultlafセット:最初。
swing.defaultlaf = com.sun.java.swing.plaf.motif.MotifLookAndFeel
秒:静的メソッドを呼び出すUIManagerのsetLookAndFeelは、動的に必要なルック&フィールクラス名を提供し、ルック&フィールを変更し、静的メソッドSwingUtilities.updateComponentTreeUIを呼び出します。コンポーネントのセット全体を更新します。
11.1.4アダプタクラス
番組枠ウィンドウを閉じる1.ときにユーザの試み、JFrameのオブジェクトは、イベントソースのWindowEventあります。
キャプチャウィンドウのイベントリスナー:リスナーのWindowListener = ... frame.addWindowListener(リスナーが );
ウィンドウリスナーは自分の名前が一目瞭然です、実装インタフェースクラスのWindowListener、のWindowListenerインタフェースは、7つのメソッドを持っていることをオブジェクトでなければなりません。
複数のリスナーメソッドAWTインターフェイスの簡略化されたコードの要件を考慮して2.すべてを達成するための方法を有しているが、ワーク・アダプタの任意の種類はありません。例:WindowAdapterをクラス。
モニターに実装されたJavaクラスの技術的な要件を満たすために動的にアダプタクラス。ウィンドウイベントアダプタクラスを拡張して必要なアクションを実装します。
3. WindowAdapterをクラス継承を6空の方法を拡張し、そして被覆WindowClosing()メソッド:
クラスターミネーターは、WindowAdapterをを拡張{
公共ボイドwindowClosing(WindowEvente){
でSystem.exit(0);}}
前記ターミネータオブジェクトは、イベントリスナとして登録されている:いるWindowListenerリスナー=新しいターミネーター() ; frame.addWindowListener(リスナー);
長いイベントを生成した窓枠のように、イベントは、リスナーオブジェクトに渡されます。
非常に良い改善ですが、また、さらに上記の文に簡略化することができWindowAdapterをリスナクラスへの拡張を作成します。frame.addWindowListener(新ターミネーター()) ;
11.2アクション
アクションイベント(のActionEvent):特定のコンポーネントのアクション自動的にこのアクションイベントを生成するコンポーネントに(ボタンをクリック)。
イベントのactionPerformed方法は、すべての登録されたActionListenerオブジェクトコンポーネントに渡され、そのようなイベントオブジェクトを受信するためにリスナーオブジェクトを呼び出しています。
アクションイベントが含まれます:(1)ボタン(2)オプションのリストをダブルクリックしてクリックすると、メニュー項目を選択(3)、(4)テキストボックスに改行を入力してください。
11.2.1クラス・インタフェースとその動作
コマンドの説明:操作コマンドをカプセル化するために非常に便利なメカニズムを提供し、Actionインタフェースパッケージアクションオブジェクトであるイベントソースの複数、に接続し、パッケージを1.Swingすると、次のオブジェクトであるテキスト文字列とAアイコンを選択し、必要なコマンドパラメータを実行します。
2.Actionは、その7つのメソッドを実装する必要があり、クラスを開くことによって、これを達成するためのインタフェースではなく、笑顔、です。
3.AbstractActionクラスにはactionPerformedメソッドを除くすべてのメソッド、このクラスの店のすべての名前/値ペアのインターフェイスアクションを実現し、プロパティ変更リスナーを管理します。
アプリケーションのイベント処理の動作において4は、直接AbstractActionクラスを拡張し、拡張されたクラスのactionPerformedメソッドを実装することができます。
11.2.2キーストロークマッピング協会
1.ユーザーは、このアクションを実行するために、キーボードコマンドをタップするように、キーストロークにアクションオブジェクトを追加します。
2.キーストロークに関連付けられた動作は、キーストロークがクラスオブジェクトを生成しなければなりません。= KeyStroke.getKeyStroke ctrBKey KeyStrokeの(「CtrlキーB」)、
オブジェクトまでの実施形態の動作に関連する3キーストローク(ブリッジ:操作キーオブジェクト記述列)
11.3マウスイベント
1.マウスイベントのMouseEvent
マウスリスナーインタフェース-のMouseListener -MouseMotionListener
マウスリスナーアダプタMouseAdapterのMouseMotionAdapter
マウスクリックのリスナーインタフェース
public interface WindowListener{
void windowOpened(WindowEvent e)
void windowClosing(WindowEvent e);
void windowClosed(WindowEvente);
void windowlconified(WindowEvent e);
void windowDeiconified(WindowEvent e);
void windowActivated(WindowEvent e);
void windowDeactivated(WindowEvent e);
}
2.用户点击鼠标按钮时,会调用三个监听器方法:标第一次被按下时调用mousePressed方法;鼠标被释放时调用mouseReleased方法;
两个动作完成之后,调用mouseClicked方法。鼠标在组件上移动时,会调用mouseMoved方法。
如果鼠标在移动的时候还按下了鼠标,则会调用mouseDragged方法。
3.鼠标事件返回值
鼠标事件的类型是MouseEvent,当发生鼠标事件时:
MouseEvent类自动创建一个事件对象,以及事件发生位置的x和y坐标,作为事件返回值。
MouseEvent类中的重要方法
一 public int getX( );
public int getY( );
public Point getPoint();
public int getClickCount();
11.4AWT事件继承层次
11.4.1AWT中的事件分类
AWT将事件分为低级(low-level)事件和语义(semantic)事件。
语义事件:表达用户动作的事件。例:点击按钮(ActionEvent)。
低级事件:形成语义事件的事件。例:点击按钮,包含了按下鼠标、连续移动鼠标、抬起鼠标事件。
AWT事件处理机制的概要:
监听器对象:是一个实现了特定监听器接口(listener interface)的类实例。
事件源:是一个能够注册监听器对象并发送事件对象的对象。
当事件发生时,事件源将事件对象自动传递给所有注册的监听器。
监听器对象利用事件对象中的信息决定如何对事件做出响应。
事件源与监听器之间的关系:
GUI设计中,程序员需要对组件的某种事件进行响应和处理时,必须完成两个步骤:
1) 定义实现某事件监听器接口的事件监听器类,并具体化接口中声明的事件处理抽象方法。
2) 为组件注册实现了规定接口的事件监听器对象;
动作事件(ActionEvent):当特定组件动作(点击按钮)发生时,该组件生成此动作事件。
该 事 件 被 传 递 给 组 件 注 册 的 每 一 个ActionListener 对 象 , 并 调 用 监 听 器 对 象 的actionPerformed方法以接收这类事件对象。
能够触发动作事件的动作,主要包括:
(1) 点击按钮
(2) 双击一个列表中的选项;
(3) 选择菜单项;
注意:监听器类必须实现与事件源相对应的接口,即必须提供接口中方法的实现。
第二部分:实验部分
实验1:测试程序1(5分)
l 调试运行教材443页-444页程序11-1,结合程序运行结果理解程序;
实验代码:
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); // create buttons JButton yellowButton = new JButton("Yellow"); JButton blueButton = new JButton("Blue"); JButton redButton = new JButton("Red"); //通过在按钮构造器中指定一个标签字符串,一个图标或两项都指定来创建一个按钮 buttonPanel = new JPanel(); // add buttons to panel buttonPanel.add(yellowButton); buttonPanel.add(blueButton); buttonPanel.add(redButton); // add panel to frame add(buttonPanel); //调用add方法将按钮添加到面板中 // create button actions 为每种颜色构造一个对象 ColorAction yellowAction = new ColorAction(Color.YELLOW); ColorAction blueAction = new ColorAction(Color.BLUE); ColorAction redAction = new ColorAction(Color.RED); // associate actions with buttons 将动作与按钮关联 yellowButton.addActionListener(yellowAction); blueButton.addActionListener(blueAction); redButton.addActionListener(redAction); } /** * An action listener that sets the panel's background color. */ //设置面板背景颜色的动作监听器 将面板的背景颜色设置为指定的颜色 private class ColorAction implements ActionListener { private Color backgroundColor; public ColorAction(Color c) { backgroundColor = c; } //颜色存储在监听器中 public void actionPerformed(ActionEvent event) { buttonPanel.setBackground(backgroundColor); } } }
package button; import java.awt.*; import javax.swing.*; /** * @version 1.35 2018-04-10 * @author Cay Horstmann */ public class ButtonTest { public static void main(String[] args) { EventQueue.invokeLater(() -> { var frame = new ButtonFrame(); frame.setTitle("ButtonTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
实验运行结果:
l 用lambda表达式简化程序;
代码如下:
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); buttonPanel = new JPanel(); makeButton("黄色", Color.yellow); makeButton("蓝色", Color.blue); makeButton("红色", Color.red); add(buttonPanel); } protected void makeButton(String name,Color backgound) { // create buttons JButton button = new JButton(name); // add buttons to panel buttonPanel.add(button); button.addActionListener((e)->{ buttonPanel.setBackground(backgound); }); } } /**create buttons JButton yellowButton = new JButton("Yellow"); JButton blueButton = new JButton("Blue"); JButton redButton = new JButton("Red"); //通过在按钮构造器中指定一个标签字符串,一个图标或两项都指定来创建一个按钮 buttonPanel = new JPanel(); // add buttons to panel buttonPanel.add(yellowButton); buttonPanel.add(blueButton); buttonPanel.add(redButton); // add panel to frame add(buttonPanel); //调用add方法将按钮添加到面板中 // create button actions 为每种颜色构造一个对象 ColorAction yellowAction = new ColorAction(Color.YELLOW); ColorAction blueAction = new ColorAction(Color.BLUE); ColorAction redAction = new ColorAction(Color.RED); // associate actions with buttons 将动作与按钮关联 yellowButton.addActionListener(yellowAction); blueButton.addActionListener(blueAction); redButton.addActionListener(redAction); } //设置面板背景颜色的动作监听器 将面板的背景颜色设置为指定的颜色 private class ColorAction implements ActionListener { private Color backgroundColor; public ColorAction(Color c) { backgroundColor = c; } //颜色存储在监听器中 public void actionPerformed(ActionEvent event) { buttonPanel.setBackground(backgroundColor); } } }**/
实验1:测试程序2(5分)
l 调试运行教材449页程序11-2,结合程序运行结果理解程序;
代码如下:
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 1ook-and-feel */ public class PlafFrame extends JFrame { private JPanel buttonPanel; public PlafFrame() { buttonPanel = new JPanel(); //创建一个面板对象 UIManager.LookAndFeelInfo[] infos = UIManager.getInstalledLookAndFeels(); //列举安装的所有观感实现 for(UIManager.LookAndFeelInfo info:infos)//得到每一种观感的名字和类名,并创建按钮 makeButton(info.getName(),info.getClassName()); //将按钮面板添加到框架上 add(buttonPanel); pack(); } /**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); buttonPanel.add(button); // set button action button.addActionListener(event -> { // button action: switch to the new look-and-feel //捕捉异常 try { //设置观感 UIManager.setLookAndFeel(className); SwingUtilities.updateComponentTreeUI(this);//刷新全部的组件 pack(); } catch (Exception e) { e.printStackTrace(); } }); } }
运行结果:
实验1:测试程序3(5分)
l 调试运行教材457页-458页程序11-3,结合程序运行结果理解程序;
代码如下:
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 actions 创建类的三个对象 var yellowAction = new ColorAction("Yellow", new ImageIcon("yellow-ball.gif"), Color.YELLOW); var blueAction = new ColorAction("Blue", new ImageIcon("blue-ball.gif"), Color.BLUE); var redAction = new ColorAction("Red", new ImageIcon("red-ball.gif"), Color.RED); // add buttons for these actions 为这些才做添加按钮 buttonPanel.add(new JButton(yellowAction)); buttonPanel.add(new JButton(blueAction)); buttonPanel.add(new JButton(redAction)); // add panel to frame 将面板添加到框架 add(buttonPanel); // associate the Y, B, and R keys with names 将Y,B和R键与名称相关联 InputMap inputMap = buttonPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); inputMap.put(KeyStroke.getKeyStroke("ctrl Y"), "panel.yellow"); inputMap.put(KeyStroke.getKeyStroke("ctrl B"), "panel.blue"); inputMap.put(KeyStroke.getKeyStroke("ctrl R"), "panel.red"); // associate the names with actions 将名称与动作相关联 ActionMap actionMap = buttonPanel.getActionMap(); actionMap.put("panel.yellow", yellowAction); actionMap.put("panel.blue", blueAction); actionMap.put("panel.red", redAction); } public class ColorAction extends AbstractAction { // 构造器设置名/值对,actionPerformed方法执行改变颜色的动作 /** * 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(Action.NAME, name); putValue(Action.SMALL_ICON, icon); putValue(Action.SHORT_DESCRIPTION, "Set panel color to " + name.toLowerCase()); putValue("color", c); } public void actionPerformed(ActionEvent event) { var color = (Color) getValue("color"); buttonPanel.setBackground(color); } } }
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(() -> { var frame = new ActionFrame(); frame.setTitle("ActionTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
运行结果:
实验1:测试程序1(5分)
l 调试运行教材462页程序11-4、11-5,结合程序运行结果理解程序;
代码如下:
package mouse; import java.awt.*; import javax.swing.*; /** * @version 1.35 2018-04-10 * @author Cay Horstmann */ public class MouseTest { public static void main(String[] args) { EventQueue.invokeLater(() -> { var frame = new MouseFrame(); frame.setTitle("MouseTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
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(); } } //程序清单
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; private Rectangle2D current; // the square containing the mouse cursor //包含鼠标光标的正方形 public MouseComponent() { squares = new ArrayList<>(); current = null; addMouseListener(new MouseHandler()); addMouseMotionListener(new MouseMotionHandler()); } public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); } public void paintComponent(Graphics g) { var g2 = (Graphics2D) g; // draw all squares 绘制所有正方形 for (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) { for (Rectangle2D r : squares) { if (r.contains(p)) return r; } return null; } /** * Adds a square to the collection. * @param p the center of the square */ public void add(Point2D p) { double x = p.getX(); 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 { public void mousePressed(MouseEvent event) { // add a new square if the cursor isn't inside a square current = find(event.getPoint()); //如果光标位于一个正方形的旁边,则添加一个新的正方形 if (current == null) add(event.getPoint()); //鼠标点击在所有小方块的像素之外 } public void mouseClicked(MouseEvent event) { // remove the current square if double clicked 如果双击,删除当前方块 current = find(event.getPoint()); if (current != null && event.getClickCount() >= 2) remove(current); } } private class MouseMotionHandler implements MouseMotionListener { public void mouseMoved(MouseEvent event) { // set the mouse cursor to cross hairs if it is inside a rectangle //如果鼠标光标位于矩形内,则将其设置为十字准线 if (find(event.getPoint()) == null) setCursor(Cursor.getDefaultCursor()); else setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); } public void mouseDragged(MouseEvent event) { if (current != null) { int x = event.getX(); int y = event.getY(); // drag the current rectangle to center it at (x, y) 拖动当前矩形,使其居中(,) current.setFrame(x - SIDELENGTH / 2, y - SIDELENGTH / 2, SIDELENGTH, SIDELENGTH); repaint(); } } } }
运行结果:
实验2:结对编程练习包含以下4部分:(20分)
利用班级名单文件、文本框和按钮组件,设计一个有如下界面(图1)的点名器,要求用户点击开始按钮后在文本输入框随机显示2018级计算机科学与技术(1)班同学姓名,如图2所示,点击停止按钮后,文本输入框不再变换同学姓名,此同学则是被点到的同学姓名,如图3所示。
图1 点名器启动界面图 2 点名器随机显示姓名界面
1) 程序设计思路简述;
2) 符合编程规范的程序代码;
3) 程序运行功能界面截图;
4) 结对过程描述,提供两人在讨论、细化和编程时的结对照片(非摆拍)。
代码如下:
package dianming; import java.awt.Color; import java.awt.FlowLayout; import java.awt.Label; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.Timer; public class Rollcall { public static void main(String args[]) { try { Dmq dmq = new Dmq(); dmq.lab.setText("随机点名器"); dmq.setTitle("点名器"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } class Dmq extends JFrame { final Label lab = new Label(); ArrayList<String> namelist = new ArrayList<String>(); public Dmq() throws IOException { File file = new File("src/2019studentlist.txt"); FileInputStream fis = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(fis, "GBK"); BufferedReader br = new BufferedReader(isr); String line = ""; while ((line = br.readLine()) != null) { if (line.lastIndexOf("---") < 0) { namelist.add(line); } } setBounds(550, 300, 200, 100); final Timer timer = new Timer(50, new ActionListener() { public void actionPerformed(ActionEvent e) { lab.setText(namelist.get((int) (Math.random() * namelist.size()))); } }); JButton jbutton = new JButton("开始"); jbutton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JButton jbutton = (JButton) e.getSource(); if (jbutton.getText().equals("开始")) { jbutton.setText("停止"); timer.start(); } else if (jbutton.getText().equals("停止")) { jbutton.setText("开始"); timer.stop(); } } }); jbutton.setBounds(60,60,60,60); jbutton.setBackground(Color.pink); lab.setBackground(Color.pink); this.setLayout(new FlowLayout()); this.add(lab); this.add(jbutton); this.setSize(300,150); this.setVisible(true); this.setDefaultCloseOperation(EXIT_ON_CLOSE); br.close(); } }
运行结果:
结对过程描述,提供两人在讨论、细化和编程时的结对照片(非摆拍)。
实验总结:(20分)
这一周学习了第十一章的内容,从掌握事件处理的基本原理开始,理解了它的用途,在基础性的概念理解之后,对这一章有了一定的认识,然后学习了AWT事件模型的工作机制,掌握的不是特别清楚,但是经过示例程序的编译和运行之后,也有了很大提升,然后学习了事件处理的基本编程模型,了解GUI界面组件观感设置方法;学习时知识点较多,故还需要自己在课后花更多的时间理解和记忆,最后在掌握了WindowAdapter类、AbstractAction类的用法后, 学习了GUI程序中鼠标事件处理技术,对利用java语言设计小型界面有了更多的学习,在最后一章学习后,经过学长的讲解,对这一章有了更深的理解,在做最后一个编程题时也发现自己的许多问题,也一定要通过自己的努力弥补不足。