GUI IIIOutlineEvent HandlingEvent handlingMenu item exampleButton exampleGetting a value backMouseListener exampleAnonymous classAnonymous class diagramMouse example againAccess to External ValuesAccess to ValuesMouseListener interfaceEvent handling strategiesRecommendationEvent handling threadExampleGUI IIIIS 3135.6.03Outline Quiz #2 Homework #2 questions? Event handlingEvent HandlingEvent handlingMenu item exampleJMenu fileMenu = new JMenu ("File");JMenuItem exitItem = new JMenuItem ("Exit");exitItem.addActionListener (new ActionListener (){ public void actionPerformed (ActionEvent e){System.exit(0);}});Button examplecancelButton.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){ListDialog.dialog.setVisible(false);}});Getting a value backbutton.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){String selectedName = ListDialog.showDialog(null, name.getText());name.setText(selectedName);}});MouseListener exampleblankArea.addMouseListener(new MouseAdapter (){public void mouseClicked(MouseEvent e) {MouseEventDemo2.this.saySomething("Mouse clicked (# of clicks: " +e.getClickCount() + ")", e);}});Anonymous classnew ActionListener (){ public void actionPerformed (ActionEvent e){System.exit(0);}}Anonymous class diagramFoo$1ActionListener«implements»Mouse example againblankArea.addMouseListener(new MouseAdapter (){public void mouseClicked(MouseEvent e) {MouseEventDemo2.this.saySomething("Mouse clicked (# of clicks: " +e.getClickCount() + ")", e);}});Access to External Values Instance variables of enclosing class Final variables in creating methodAccess to Valuespublic class MyImagePanel{ String m_baz;public void foo (){ ... method body ...}... rest of class ...public void addImageLabel (String caption){ JLabel lbl = new JLabel (caption);final MyImage img = new MyImage (caption);lbl.addMouseListener (new MouseAdapter (){public void mouseClicked (MouseEvent e){ // need to access the outer classbar(MyImagePanel.this);// need to call outer class method// access final variable// access instance variableMyImagePanel.foo (img, m_baz);}});...MouseListener interfacevoid mouseClicked(MouseEvent e) void mouseEntered(MouseEvent e) void mouseExited(MouseEvent e) void mousePressed(MouseEvent e) void mouseReleased(MouseEvent e)Event handling strategies Location of EH code external component class named inner class anonymous inner class Base class or interface used Implement XxxListener Extend XxxAdapterRecommendation Use anonymous inner class unless EH is large, then used named inner class Extend Adapter unless all interface methods needed Note: no ActionAdapter classEvent handling thread Can only process one event at a time Time-consuming event handlers tie up the interface no other actions
View Full Document