201771010101 白玛次仁 《2018面向对象程序设计(Java)》第十三周学习总结
實驗十三??圖形界面事件處理技術
實驗時間?2018-11-22
學習總結:
?Compoment類提供的功能:
–基本的繪畫支持。
–外形控制。
–大小和位置控制。
–圖像處理。
–組件狀態(tài)控制
每個容器:
– add() 方法向容器添加某個組件,
–? remove()方法從容器中刪除某個組件。
容器通過方法? setLayout () 設置某種布局。
Swing比AWT 組件具有更強的實用性和美觀性。
?Swing組件必須添加到一個與? Swing 頂層容器相 關聯(lián)的內容面板( contentpane)上。
事件對象? (event? object):Java 將事件的相關信息 將事件的相關信息 封裝在一個事件對象中 ,所有的事件對象都最終派生于 java.util.EventObject 類。不 同的事件源可以產生不 同的類別的事件。
事件源來通知事件發(fā)生,然后監(jiān)聽器對象注冊事件源。
注冊監(jiān)聽器方法eventSourceObject.addEvenListtener(evenListenerObject)
能夠觸發(fā)動作 事件的,主要包括:
(1)點擊按鈕
(2)雙擊一個列表中的選項;
(3)選擇菜單項;
(4)在文本框中輸入回車 。
監(jiān)聽器類必須實現與事件源相對應的接口 ,即必 須提供接口中方法 的實現 。
當程序用戶試圖關閉一個框架窗口時,? Jframe 對象就是 WindowEvent 的事件源。
窗口監(jiān)聽器必須是實現 WindowListener類的一個對象? ,WindowListener接口中有七個方法.
Swing 包提供了非常實用的機制來封裝命令 ,并將它 們連接到多個事件源 ,這就是 Action 接口 。
圖形編輯器應用程序 ,其允許用戶在畫布上放置、移動和擦除方塊
1. 當鼠標點擊在所有小方塊的像素之外時,會繪制一個新的小方塊;
2. 當雙擊一個小方塊內部時,會擦除該;
3. 當鼠標在窗體上移動時,如果經過一個小方塊的內部,光標會變成一個十字形;
4. 實現用鼠標拖動小方塊。
監(jiān)聽鼠標移動事件,實現 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 panelbuttonPanel.add(yellowButton);//將按鈕添加到面板中buttonPanel.add(blueButton);buttonPanel.add(redButton);// add panel to frameadd(buttonPanel);// create button actions//每種顏色構造一個對象,并將這些對象設置為按鈕監(jiān)聽器ColorAction yellowAction = new ColorAction(Color.YELLOW);ColorAction blueAction = new ColorAction(Color.BLUE);ColorAction redAction = new ColorAction(Color.RED);// associate actions with buttonsyellowButton.addActionListener(yellowAction);blueButton.addActionListener(blueAction);redButton.addActionListener(redAction);}/*** An action listener that sets the panel's background color.*///實現一個監(jiān)聽器的接口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 actionbutton.addActionListener(event -> {// button action: switch to the new look-and-feeltry{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 actionsAction 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 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);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 actionsActionMap 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;//定義創(chuàng)造的正方形的邊長private ArrayList<Rectangle2D> squares;private Rectangle2D current; // the square containing the mouse cursorpublic MouseComponent(){squares = new ArrayList<>();current = null;addMouseListener(new MouseHandler());addMouseMotionListener(new MouseMotionHandler());//添加一個我們實現的類,這個類繼承了監(jiān)測鼠標點擊情況的MouseListener}public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); } 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)
//轉換我們需要使用的類型
//繪制所有正方形{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 squarecurrent = find(event.getPoint());if (current == null) add(event.getPoint());}public void mouseClicked(MouseEvent event){// remove the current square if double clickedcurrent = 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 rectangleif (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();//生成MonseFrameframe.setTitle("MouseTest");
//設置組建的定義標題測試按鈕frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);});} }
?
實驗2:結對編程練習
利用班級名單文件、文本框和按鈕組件,設計一個有如下界面(圖1)的點名器,要求用戶點擊開始按鈕后在文本輸入框隨機顯示2017級網絡與信息安全班同學姓名,如圖2所示,點擊停止按鈕后,文本輸入框不再變換同學姓名,此同學則是被點到的同學姓名。
?
圖1?點名器啟動界面
?
?
圖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); }}}?
?
?
實驗總結:這次實驗的學習中知道了圖形編輯器應用程序 ,其允許用戶在畫布上放置、移動和擦除方塊等等,
更好想學敲代碼。
?
?
轉載于:https://www.cnblogs.com/baimaciren/p/10002052.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的201771010101 白玛次仁 《2018面向对象程序设计(Java)》第十三周学习总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MySQL组提交(group commi
- 下一篇: Python 模板语言