1. 程式人生 > >201771010101 白瑪次仁 《2018面向物件程式設計(Java)》第十三週學習總結

201771010101 白瑪次仁 《2018面向物件程式設計(Java)》第十三週學習總結

實驗十三  圖形介面事件處理技術

實驗時間 2018-11-22

學習總結:

 Compoment類提供的功能:
–基本的繪畫支援。
–外形控制。
–大小和位置控制。
–影象處理。
–元件狀態控制

每個容器:
– add() 方法向容器新增某個元件,
–  remove()方法從容器中刪除某個元件。

容器通過方法  setLayout () 設定某種佈局。

Swing比AWT 元件具有更強的實用性和美觀性。

 Swing元件必須新增到一個與  Swing 頂層容器相 關聯的內容面板( contentpane)上。

事件物件  (event  object):Java 將事件的相關資訊 將事件的相關資訊 封裝在一個事件物件中 ,所有的事件物件都最終派生於 java.util.EventObject 類。不 同的事件源可以產生不 同的類別的事件。

事件源來通知事件發生,然後監聽器物件註冊事件源。

註冊監聽器方法eventSourceObject.addEvenListtener(evenListenerObject)

能夠觸發動作 事件的,主要包括:
(1)點選按鈕
(2)雙擊一個列表中的選項;
(3)選擇選單項;
(4)在文字框中輸入回車 。

監聽器類必須實現與事件源相對應的介面 ,即必 須提供介面中方法 的實現 。

當程式使用者試圖關閉一個框架視窗時,  Jframe 物件就是 WindowEvent 的事件源。

視窗監聽器必須是實現 WindowListener類的一個物件  ,WindowListener介面中有七個方法.

Swing 包提供了非常實用的機制來封裝命令 ,並將它 們連線到多個事件源 ,這就是 Action 介面 。

圖形編輯器應用程式 ,其允許使用者在畫布上放置、移動和擦除方塊
1. 當滑鼠點選在所有小方塊的畫素之外時,會繪製一個新的小方塊;
2. 當雙擊一個小方塊內部時,會擦除該;
3. 當滑鼠在窗體上移動時,如果經過一個小方塊的內部,游標會變成一個十字形;
4. 實現用滑鼠拖動小方塊。

監聽滑鼠移動事件,實現 MouseMotionListener 介面。

1、實驗目的與要求

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

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

(3) 掌握事件處理的基本程式設計模型;

(4) 瞭解GUI介面元件觀感設定方法;

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

(6) 掌握GUI程式中滑鼠事件處理技術。

2、實驗內容和步驟

實驗1: 匯入第11章示例程式,測試程式並進行程式碼註釋。

測試程式1:

l 在elipse IDE中除錯執行教材443頁-444頁程式11-1,結合程式執行結果理解程式;

l 在事件處理相關程式碼處添加註釋;

l 用lambda表示式簡化程式;

l 掌握JButton元件的基本API;

l 掌握Java中事件處理的基本程式設計模型。

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 = 400;
   private static final int DEFAULT_HEIGHT = 300;

   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);

      // 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.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");//應用名
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setVisible(true);
      });
   }

 

測試程式2:

l 在elipse IDE中除錯執行教材449頁程式11-2,結合程式執行結果理解程式;

l 在元件觀感設定程式碼處添加註釋;

l 瞭解GUI程式中觀感的設定方法。

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();//例項化一個新的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); // 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(); } }); } }

 

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();
//生成PlafFrame物件 frame.setTitle("PlafTest");
//設定組建的自定義標題測試按鈕 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }

 

 

測試程式3:

l 在elipse IDE中除錯執行教材457頁-458頁程式11-3,結合程式執行結果理解程式;

l 掌握AbstractAction類及其動作物件;

l 掌握GUI程式中按鈕、鍵盤動作對映到動作物件的方法。

 

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
      Action yellowAction = new ColorAction("Yellow", new ImageIcon("yellow-ball.gif"),
            Color.YELLOW);
      Action blueAction = new ColorAction("Blue", new ImageIcon("blue-ball.gif"), Color.BLUE);
      Action 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
      InputMap imap = buttonPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
      imap.put(KeyStroke.getKeyStroke("ctrl Y"), "panel.yellow");
      imap.put(KeyStroke.getKeyStroke("ctrl B"), "panel.blue");
      imap.put(KeyStroke.getKeyStroke("ctrl R"), "panel.red");

      // associate the names with actions
      ActionMap amap = buttonPanel.getActionMap();
      amap.put("panel.yellow", yellowAction);
      amap.put("panel.blue", blueAction);
      amap.put("panel.red", redAction);
   }
   
   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(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)
      {
         Color c = (Color) getValue("color");
         buttonPanel.setBackground(c);
      }
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);
      });
   }
}

 

} }

測試程式4:

l 在elipse IDE中除錯執行教材462頁程式11-4、11-5,結合程式執行結果理解程式;

l 掌握GUI程式中滑鼠事件處理技術。

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());
//新增一個我們實現的類,這個類繼承了監測滑鼠點選情況的MouseListener } public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); } public void paintComponent(Graphics g) { Graphics2D 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();
//獲取x和y的座標 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();//重繪component的方法 } 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(); } } } }

 

package mouse;

import javax.swing.*;

/**
 * A frame containing a panel for testing mouse operations
 */
public class MouseFrame extends JFrame
{
   public MouseFrame()
   {
      add(new MouseComponent());//向框架中新增一個JComponent的例項
      pack();
   }
}

 

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();
//生成MonseFrame frame.setTitle("MouseTest");
//設定組建的定義標題測試按鈕 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }

 

實驗2:結對程式設計練習

利用班級名單檔案、文字框和按鈕元件,設計一個有如下介面(圖1)的點名器,要求使用者點選開始按鈕後在文字輸入框隨機顯示2017級網路與資訊安全班同學姓名,如圖2所示,點選停止按鈕後,文字輸入框不再變換同學姓名,此同學則是被點到的同學姓名。

 

點名器啟動介面

 

 

點名器點名介面

 

package dianming;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.Frame;
import java.io.File;
import java.io.FileNotFoundException;
 
public class dianmingqi extends JFrame implements ActionListener{
    private static final long serialVersionUID = 1L;

    private JButton but ;
 
    private JButton show;
    private static boolean flag = true;
    public static void main(String arguments []) {
         new dianmingqi();
 
        }
 
public  dianmingqi(){
 
but = new JButton("開始");
but.setBounds(100,150,100,40); 
show = new JButton("隨機點名");
show.setBounds(80,80,180,30);

 
add(but);
 
add(show);
 
setLayout(null);
setVisible(true);
setResizable(false);
setBounds(100,100,300,300);
this.getContentPane().setBackground(Color.white);
setTitle("點名");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
but.addActionListener(this);
}
 
    public void actionPerformed(ActionEvent e){
        int i=0;
        String names[]=new String[50];
        try {
            Scanner in=new Scanner(new File("D:\\studentnamelist.txt"));
            while(in.hasNextLine())
            {
                names[i]=in.nextLine();
                i++;
            }
        } catch (FileNotFoundException e1) {
             
            e1.printStackTrace();
        }
 
     
        if(but.getText()=="開始"){    
 
    show.setBackground(Color.gray);
    flag=true;
    new Thread(){   
        public void run(){
            while(dianmingqi.flag){
            Random r = new Random(); 
            int i= r.nextInt(47);
            show.setText(names[i]);
            }
        }
    }.start();
    but.setText("停止");
    but.setBackground(Color.darkGray);
}    
else if(but.getText()=="停止"){
    flag = false;
    but.setText("開始");
    but.setBackground(Color.WHITE);
    show.setBackground(Color.magenta);
}
    }
 
 
 
}

 

  

 

 

實驗總結:這次實驗的學習中知道了圖形編輯器應用程式 ,其允許使用者在畫布上放置、移動和擦除方塊等等,

更好想學敲程式碼。