1. 程式人生 > >201771010110孔維瀅《面向物件程式設計(java)》第十三週學習總結

201771010110孔維瀅《面向物件程式設計(java)》第十三週學習總結

理論知識部分

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

                    監聽器介面方法實現

                                class Mylistener implements ActionListener {  public void actionPerformed (ActionEvent event) {  …… } }

2.用匿名類、lambda表示式簡化程式:

    例ButtonTest.java中,各按鈕需要同樣的處理:

                a.使用字串構造按鈕物件;

                b.把按鈕新增到面板上;

                c.用對應的顏色構造一個動作監聽器;

                d.註冊動作監聽器。

3.介面卡類:

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

    捕獲視窗事件的監聽器:

             WindowListener listener=…..; frame.addWindowListener(listener);

    註冊事件監聽器:

              可將一個Terminator物件註冊為事件監聽器:

                              WindowListener listener=new Terminator();

                              frame.addWindowListener(listener);

4.動作事件:

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

    動作物件是一個封裝下列內容的物件:

                           –命令的說明:一個文字字串和一個可選圖示;

                           –執行命令所需要的引數。

5.滑鼠事件:

    滑鼠事件 – MouseEvent

    滑鼠監聽器介面

                              – MouseListener

                              – MouseMotionListener

    滑鼠監聽器介面卡

                              – MouseAdapter

                              – MouseMotionAdapter

實驗部分:

    實驗1:

測試程式1:

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();//構建一個ButtonFrame類物件
         frame.setTitle("ButtonTest");//設定Title屬性,確定框架標題欄中的文字
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//設定預設關閉操作,退出並關閉
         frame.setVisible(true);//設定Visible屬性,元件可見
      });
   }
}

  

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

      // 建立按鈕
      JButton yellowButton = new JButton("Yellow");
      JButton blueButton = new JButton("Blue");
      JButton redButton = new JButton("Red");

      buttonPanel = new JPanel();

      // 新增按鈕到面板
      buttonPanel.add(yellowButton);//呼叫add方法將按鈕新增到面板
      buttonPanel.add(blueButton);
      buttonPanel.add(redButton);

      // 新增面板到框架
      add(buttonPanel);

      // 建立按鈕事件
      ColorAction yellowAction = new ColorAction(Color.YELLOW);
      ColorAction blueAction = new ColorAction(Color.BLUE);
      ColorAction redAction = new ColorAction(Color.RED);

      // 將時間與按鈕關聯
      yellowButton.addActionListener(yellowAction);
      blueButton.addActionListener(blueAction);
      redButton.addActionListener(redAction);
   }

   /**
    * An action listener that sets the panel's background color.
    */
   private class ColorAction implements ActionListener//實現了ActionListener的介面類
   {
      private Color backgroundColor;

      public ColorAction(Color c)
      {
         backgroundColor = c;
      }

      public void actionPerformed(ActionEvent event)//actionListener方法接收一個ActionEvent物件引數
      {
         buttonPanel.setBackground(backgroundColor);
      }
   }
}

  輸出結果:

測試程式2:

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");//設定Title屬性,確定框架標題欄中的文字
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//設定預設關閉操作,退出並關閉
         frame.setVisible(true);//設定Visible屬性,元件可見
      });
   }
}

  

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

      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)
   {
	   // 新增按鈕到面板

      JButton button = new JButton(name);
      buttonPanel.add(button);

      // 設定按鈕事件

      button.addActionListener(event -> {
         // 按鈕動作:切換到新的外觀
         try
         {
            UIManager.setLookAndFeel(className);
            SwingUtilities.updateComponentTreeUI(this);
            pack();
         }
         catch (Exception e)
         {
            e.printStackTrace();
         }
      });
   }//使用輔助方法makeButton和匿名內部類指定按鈕動作
}

 輸出結果:

測試程式3:

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();//構建一個ActionFrame類物件
         frame.setTitle("ActionTest");//設定Title屬性,確定框架標題欄中的文字
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//設定預設關閉操作,退出並關閉
         frame.setVisible(true);//設定Visible屬性,元件可見
      });
   }
}

  

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

      // 定義操作
      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);

      // 為這些操作新增按鈕
      buttonPanel.add(new JButton(yellowAction));
      buttonPanel.add(new JButton(blueAction));
      buttonPanel.add(new JButton(redAction));

      // 將面板新增到框架
      add(buttonPanel);

      // 將Y、B和R鍵與名稱關聯起來
      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");

      // 將名稱與操作關聯起來
      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);
      }
   }
}

  輸出結果:

測試程式4:

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();//構建一個MouseFrame類物件
         frame.setTitle("MouseTest");//設定Title屬性,確定框架標題欄中的文字
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//設定預設關閉操作,退出並關閉
         frame.setVisible(true);//設定Visible屬性,元件可見
      });
   }
}

 

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; // 包含滑鼠游標的正方形

   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)
   {
      Graphics2D g2 = (Graphics2D) g;

      // 畫出所有方塊
      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)
      {
         // 如果游標不在正方形內,則新增一個新的正方形
         current = find(event.getPoint());
         if (current == null) add(event.getPoint());
      }

      public void mouseClicked(MouseEvent event)
      {
         // 如果雙擊,則刪除當前方塊
         current = find(event.getPoint());
         if (current != null && event.getClickCount() >= 2) remove(current);
      }
   }

   private class MouseMotionHandler implements MouseMotionListener
   {
      public void mouseMoved(MouseEvent event)
      {
         // 如果滑鼠指標在內部,則將其設定為十字線
         // 一個矩形

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

            // 拖動當前矩形到(x, y)的中心
            current.setFrame(x - SIDELENGTH / 2, y - SIDELENGTH / 2, SIDELENGTH, SIDELENGTH);
            repaint();
         }
      }
   }   
}

 輸出結果:

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

結對程式設計夥伴:馮志霞

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 JButton but;

	private JButton show;
	private static boolean flag = true;

	public static void main(String arguments[]) {
		new Dianmingqi();

	}

	public Dianmingqi() {

		but = new JButton("START");
		but.setBounds(100, 150, 100, 40);

		show = new JButton("開始點名");
		show.setBounds(80, 80, 180, 30);
		show.setFont(new Font("宋體", Font.BOLD, 30));

		add(but);

		add(show);

		setLayout(null);// 佈局管理器必須先初始化為空才能賦值
		setVisible(true);
		setResizable(false);
		setBounds(100, 100, 300, 300);
        //setBackground(Color.red);不起作用
		this.getContentPane().setBackground(Color.cyan);
		setTitle("START");
		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("studentnamelist.txt"));
			while (in.hasNextLine()) {
				names[i] = in.nextLine();
				i++;
			}
		} catch (FileNotFoundException e1) {

			e1.printStackTrace();
		}

		if (but.getText() == "START") {

			show.setBackground(Color.BLUE);
			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("STOP");// 更改文字內容
			but.setBackground(Color.YELLOW);
		} else if (but.getText() == "STOP") {
			flag = false;
			but.setText("START");
			but.setBackground(Color.WHITE);
			show.setBackground(Color.GREEN);
		}
	}
}

  

實驗總結:

這個周的結對程式設計練習,由於對很多知識的不理解,無法完全實現程式設計題的內容,我深感自己的不足。對於程式碼中的一些方法還不是能夠完全理解。

package 點名器;

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.util.List;

import javax.swing.JFrame;

import java.util.ArrayList;

public class RollCaller extends JFrame{
    
    private String fileName="studentnamelist.txt";
    private File f;
    private FileReader fr;
    private BufferedReader br;
    private List<String> names=new ArrayList<String>();
    private String Name;
    private Label labelName;
    private Button button;
    
    public static void main(String[] args)
    {
        RollCaller rollcaller=new RollCaller();
        rollcaller.newFrame();
        rollcaller.read();
    }
    
    public void newFrame()
    {
        labelName=new Label("隨機點名");
        button=new Button("START");
        
        this.setLocation(300,300);
        this.setResizable(true);//設定此窗體是否可由使用者調整大小。
        this.setSize(1000,800);
        this.add(labelName,BorderLayout.NORTH);
        this.add(button,BorderLayout.CENTER);
        this.pack();
        this.setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        button.addActionListener(new ButtonAction());
    }

    public void read()
    {
        try{
            f=new File(fileName);
            if(!f.exists()){
                f.createNewFile();
            }
            fr=new FileReader(f);
            br=new BufferedReader(fr);
            String str=br.readLine();
            while(str!=null){
                names.add(str);
                str=br.readLine();
            }
        }catch(Exception e){
            e.printStackTrace();
            }
    }
    
    public void name()
    {
        try{
            int index=(int)(Math.random()*names.size());
            Name=names.get(index);
            }catch(Exception e){
                e.printStackTrace();
                }
        }
    
    private class ButtonAction implements ActionListener{
    
        public void actionPerformed(ActionEvent e){
            name();
            labelName.setText(Name);
        }
    }
}

 這次的作業,我在網路中查詢了很多,

 通過在網上查詢,我查到了BufferedReader由Reader類擴充套件而來,提供文字讀取。

 還有label物件是一個可在容器中放置文字的元件。一個標籤只顯示一行只讀文字。文字可由應用程式更改,但是使用者不能直接對其進行編輯。

 但是這個程式碼還存在著很多問題,對於很多知識我還需更多的掌握,不論是從程式的實用,還是外觀,都還需更加深入的學習。