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對象是一個可在容器中放置文本的組件。一個標簽只顯示一行只讀文本。文本可由應用程序更改,但是用戶不能直接對其進行編輯。
但是這個代碼還存在著很多問題,對於很多知識我還需更多的掌握,不論是從程序的實用,還是外觀,都還需更加深入的學習。
201771010110孔維瀅《面向對象程序設計(java)》第十三周學習總結