26.07.2013 Views

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 12 Graphical User Interface Components: Part 1 663<br />

13<br />

14 // set up GUI<br />

15 public But<strong>to</strong>nTest()<br />

16 {<br />

17 super( "Testing But<strong>to</strong>ns" );<br />

18<br />

19 // get content pane and set its layout<br />

20 Container container = getContentPane();<br />

21 container.setLayout( new FlowLayout() );<br />

22<br />

23 // create but<strong>to</strong>ns<br />

24 plainBut<strong>to</strong>n = new JBut<strong>to</strong>n( "Plain But<strong>to</strong>n" );<br />

25 container.add( plainBut<strong>to</strong>n );<br />

26<br />

27 Icon bug1 = new ImageIcon( "bug1.gif" );<br />

28 Icon bug2 = new ImageIcon( "bug2.gif" );<br />

29 fancyBut<strong>to</strong>n = new JBut<strong>to</strong>n( "Fancy But<strong>to</strong>n", bug1 );<br />

30 fancyBut<strong>to</strong>n.setRolloverIcon( bug2 );<br />

31 container.add( fancyBut<strong>to</strong>n );<br />

32<br />

33 // create an instance of inner class But<strong>to</strong>nHandler<br />

34 // <strong>to</strong> use for but<strong>to</strong>n event handling<br />

35 But<strong>to</strong>nHandler handler = new But<strong>to</strong>nHandler();<br />

36 fancyBut<strong>to</strong>n.addActionListener( handler );<br />

37 plainBut<strong>to</strong>n.addActionListener( handler );<br />

38<br />

39 setSize( 275, 100 );<br />

40 setVisible( true );<br />

41 }<br />

42<br />

43 // execute application<br />

44 public static void main( String args[] )<br />

45 {<br />

46 But<strong>to</strong>nTest application = new But<strong>to</strong>nTest();<br />

47<br />

48 application.setDefaultCloseOperation(<br />

49 JFrame.EXIT_ON_CLOSE );<br />

50 }<br />

51<br />

52 // inner class for but<strong>to</strong>n event handling<br />

53 private class But<strong>to</strong>nHandler implements ActionListener {<br />

54<br />

55 // handle but<strong>to</strong>n event<br />

56 public void actionPerformed( ActionEvent event )<br />

57 {<br />

58 JOptionPane.showMessageDialog( null,<br />

59 "You pressed: " + event.getActionCommand() );<br />

60 }<br />

61<br />

62 } // end private inner class But<strong>to</strong>nHandler<br />

63<br />

64 } // end class But<strong>to</strong>nTest<br />

Fig. Fig. 12.10 12.10 Demonstrating command but<strong>to</strong>ns and action events (part 2 of 3).<br />

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!