Programming Languages: Java

Size: px
Start display at page:

Download "Programming Languages: Java"

Transcription

1 Programming Languages: Java Lecture 5 GUI Components File and Streams Applets Instructor: Omer Boyaci 1

2 2 GUI Components

3 3 We will cover The design principles of graphical user interfaces (GUIs). To build GUIs and handle events generated by user interactions with GUIs. To understand the packages containing GUI components, event-handling classes and interfaces. To create and manipulate buttons, labels, lists, text fields and panels. To handle mouse events and keyboard events. To use layout managers to arrange GUI components

4 Introduction Simple GUI-Based Input/Output with JOptionPane Overview of Swing Components Displaying Text and Images in a Window Text Fields and an Introduction to Event Handling with Nested Classes Common GUI Event Types and Listener Interfaces How Event Handling Works JButton Buttons That Maintain State JCheckBox JRadioButton JComboBox and Using an Anonymous Inner Class for Event Handling

5 JList Multiple-Selection Lists Mouse Event Handling Adapter Classes JPanel Subclass for Drawing with the Mouse Key-Event Handling Layout Managers FlowLayout BorderLayout GridLayout Using Panels to Manage More Complex Layouts JTextArea Wrap-Up

6 Introduction Graphical user interface (GUI) Presents a user-friendly mechanism for interacting with an application Often contains title bar, menu bar containing menus, buttons and combo boxes Built from GUI components

7 7 button menus title bar menu bar combo box scroll bars Fig Internet Explorer window with GUI components.

8 11.2 Simple GUI-Based Input/Output with JOptionPane Dialog boxes Used by applications to interact with the user Provided by Java s JOptionPane class Contains input dialogs and message dialogs 8

9 Outline Input dialog displayed by lines Prompt to the user Text field in which the user types a value When the user clicks OK, howinputdialog returns to the program the 100 typed by the user as a String. The program must convert the String to an int 9 Addition.java (2 of 2) Input dialog displayed by lines title bar Message dialog displayed by lines When the user clicks OK, the message dialog is dismissed (removed from the screen)

10 // Fig. 11.2: Addition.java // Addition program that uses JOptionPane for input and output. import javax.swing.joptionpane; // program uses JOptionPane Outline 10 public class Addition Show input dialog to receive first integer Addition.java public static void main( String args[] ) (1 of 2) // obtain user input from JOptionPane input dialogs String firstnumber = Show input dialog to receive JOptionPane.showInputDialog( "Enter first integer" ); integer second String secondnumber = JOptionPane.showInputDialog( "Enter second integer" ); // convert String inputs to int values for use in a calculation int number1 = Integer.parseInt( firstnumber ); int number2 = Integer.parseInt( secondnumber ); int sum = number1 + number2; // add numbers Show message dialog to output sum to user 21 // display result in a JOptionPane message dialog 22 JOptionPane.showMessageDialog( null, "The sum is " + sum, 23 "Sum of Two Integers", JOptionPane.PLAIN_MESSAGE ); 24 } // end method main 25 } // end class Addition

11 11 Message dialog type Icon Description ERROR_MESSAGE A dialog that indicates an error to the user. INFORMATION_MESSAGE A dialog with an informational message to the user. WARNING_MESSAGE A dialog warning the user of a potential problem. QUESTION_MESSAGE PLAIN_MESSAGE A dialog that poses a question to the user. This dialog normally requires a response, such as clicking a Yes or a No button. no icon A dialog that contains a message, but no icon. Fig JOptionPane static constants for message dialogs.

12 Overview of Swing Components Swing GUI components Declared in package javax.swing Most are pure Java components Part of the Java Foundation Classes (JFC)

13 13 Component Description JLabel Displays uneditable text or icons. JTextField Enables user to enter data from the keyboard. Can also be used to display editable or uneditable text. JButton Triggers an event when clicked with the mouse. JCheckBox Specifies an option that can be selected or not selected. JComboBox Provides a drop-down list of items from which the user can make a selection by clicking an item or possibly by typing into the box. JList Provides a list of items from which the user can make a selection by clicking on any item in the list. Multiple elements can be selected. JPanel Provides an area in which components can be placed and organized. Can also be used as a drawing area for graphics. Fig Some basic GUI components.

14 14 Swing vs. AWT Abstract Window Toolkit (AWT) Precursor to Swing Declared in package java.awt Does not provide consistent, cross-platform look-and-feel

15 Lightweight vs. Heavyweight GUI Components Lightweight components Not tied directly to GUI components supported by underlying platform Heavyweight components Tied directly to the local platform AWT components Some Swing components 15

16 Superclasses of Swing s Lightweight GUI Components Class Component (package java.awt) Subclass of Object Declares many behaviors and attributes common to GUI components Class Container (package java.awt) Subclass of Component Organizes Components Class JComponent (package javax.swing) Subclass of Container Superclass of all lightweight Swing components 16

17 17 Fig Common superclasses of many of the Swing components.

18 Superclasses of Swing s Lightweight GUI Components Common lightweight component features Pluggable look-and-feel to customize the appearance of components Shortcut keys (called mnemonics) Common event-handling capabilities Brief description of component s purpose (called tool tips) Support for localization 18

19 11.4 Displaying Text and Images in a Window Class JFrame Most windows are an instance or subclass of this class Provides title bar Provides buttons to minimize, maximize and close the application 19

20 20 Labeling GUI Components Label Text instructions or information stating the purpose of each component Created with class JLabel

21 21 Specifying the Layout Laying out containers Determines where components are placed in the container Done in Java with layout managers One of which is class FlowLayout Set with the setlayout method of class JFrame

22 22 Labels

23 1 2 // Fig. 11.6: LabelFrame.java // Demonstrating the JLabel class. 3 import java.awt.flowlayout; // specifies how components are arranged import javax.swing.jframe; // provides basic window features import javax.swing.jlabel; // displays text and images import javax.swing.swingconstants; // common constants used with Swing import javax.swing.icon; // interface used to manipulate images import javax.swing.imageicon; // loads images Outline 23 LabelFrame.java (1 of 2) 10 public class LabelFrame extends JFrame private JLabel label1; // JLabel with just text private JLabel label2; // JLabel constructed with text and icon private JLabel label3; // JLabel with added text and icon // LabelFrame constructor adds JLabels to JFrame public LabelFrame() super( "Testing JLabel" ); setlayout( new FlowLayout() ); // set frame layout // JLabel constructor with a string argument label1 = new JLabel( "Label with text" ); label1.settooltiptext( "This is label1" ); add( label1 ); // add label1 to JFrame

24 27 28 // JLabel constructor with string, Icon and alignment arguments Icon bug = new ImageIcon( getclass().getresource( "bug1.gif" ) ); label2 = new JLabel( "Label with text and icon", bug, SwingConstants.LEFT ); 31 label2.settooltiptext( "This is label2" ); 32 add( label2 ); // add label2 to JFrame LabelFrame.java label3 = new JLabel(); // JLabel constructor no arguments label3.settext( "Label with icon and text at bottom" ); label3.seticon( bug ); // add icon to JLabel (2 of 2) label3.sethorizontaltextposition( SwingConstants.CENTER ); label3.setverticaltextposition( SwingConstants.BOTTOM ); label3.settooltiptext( "This is label3" ); add( label3 ); // add label3 to JFrame Outline } // end LabelFrame constructor 42 } // end class LabelFrame

25 1 // Fig. 11.7: LabelTest.java 2 // Testing LabelFrame. 3 import javax.swing.jframe; Outline public class LabelTest 6 7 public static void main( String args[] ) 8 LabelTest.java 9 LabelFrame labelframe = new LabelFrame(); // create LabelFrame 10 labelframe.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); 11 labelframe.setsize( 275, 180 ); // set frame size 12 labelframe.setvisible( true ); // display frame 13 } // end main 14 } // end class LabelTest

26 26 Creating and Attaching label1 Method add of class Container Adds a component to a container Method settooltiptext of class JComponent Specifies the tool tip

27 27 Creating and Attaching label2 Interface Icon Can be added to a JLabel with the seticon method Implemented by class ImageIcon Interface SwingConstants Declares a set of common integer constants such as those used to set the alignment of components Can be used with methods sethorizontalalignment and setverticalalignment

28 28 Creating and Attaching label3 Other JLabel methods gettext and settext For setting and retrieving the text of a label geticon and seticon For setting and retrieving the icon displayed in the label gethorizontaltextposition and sethorizontaltextposition For setting and retrieving the horizontal position of the text displayed in the label

29 29 Constant Description Horizontal-position constants SwingConstants.LEFT SwingConstants.CENTER SwingConstants.RIGHT Place text on the left. Place text in the center. Place text on the right. Vertical-position constants SwingConstants.TOP SwingConstants.CENTER SwingConstants.BOTTOM Place text at the top. Place text in the center. Place text at the bottom. Fig Some basic GUI components.

30 Creating and Displaying a LabelFrame Window Other JFrame methods setdefaultcloseoperation Dictates how the application reacts when the user clicks the close button setsize Specifies the width and height of the window setvisible Determines whether the window is displayed (true) or not (false) 30

31 11.5 Text Fields and an Introduction to Event Handling with Nested Classes GUIs are event-driven A user interaction creates an event Common events are clicking a button, typing in a text field, selecting an item from a menu, closing and window and moving the mouse The event causes a call to a method called an event handler 31

32 11.5 Text Fields and an Introduction to Event Handling with Nested Classes Class JTextComponent Superclass of JTextField Superclass of JPasswordField Adds echo character to hide text input in component Allows user to enter text in the component when component has the application s focus 32

33 33 Text Fields and Event Handling

34 1 // Fig. 11.9: TextFieldFrame.java // Demonstrating the JTextField class. import java.awt.flowlayout; import java.awt.event.actionlistener; import java.awt.event.actionevent; import javax.swing.jframe; import javax.swing.jtextfield; import javax.swing.jpasswordfield; import javax.swing.joptionpane; Outline 34 TextFieldFrame.java (1 of 3) public class TextFieldFrame extends JFrame private JTextField textfield1; // text field with set size 14 private JTextField textfield2; // text field constructed with text 15 private JTextField textfield3; // text field with text and size private JPasswordField passwordfield; // password field with text // TextFieldFrame constructor adds JTextFields to JFrame public TextFieldFrame() super( "Testing JTextField and JPasswordField" ); setlayout( new FlowLayout() ); // set frame layout Create a new JTextField // construct textfield with 10 columns textfield1 = new JTextField( 10 ); add( textfield1 ); // add textfield1 to JFrame

35 28 29 // construct textfield with default text textfield2 = new JTextField( "Enter text here" ); add( textfield2 ); // add textfield2 to JFrame Outline Create a new JTextField // construct textfield with default text and 21 columns textfield3 = new JTextField( "Uneditable text field", 21 ); textfield3.seteditable( false ); // disable editing add( textfield3 ); // add textfield3 to JFrame Make this TextFieldFrame.java (2 of 3) JTextField uneditable // construct passwordfield with default text passwordfield = new JPasswordField( "Hidden text" ); add( passwordfield ); // add passwordfield to JFrame Create a new JPasswordField // register event handlers TextFieldHandler handler = new TextFieldHandler(); textfield1.addactionlistener( handler ); Create textfield2.addactionlistener( handler ); textfield3.addactionlistener( handler ); passwordfield.addactionlistener( handler ); } // end TextFieldFrame constructor // private inner class for event handling private class TextFieldHandler implements ActionListener // process text field events public void actionperformed( ActionEvent event ) event handler Register event handler Create event handler class by implementing the ActionListener interface String string = ""; // declare string to display Declare actionperformed method

36 57 // user pressed Enter in JTextField textfield if ( event.getsource() == textfield1 ) string = String.format( "textfield1: %s", event.getactioncommand() ); else if ( event.getsource() == textfield2 ) string = String.format( "textfield2: %s", event.getactioncommand() ); else if ( event.getsource() == textfield3 ) string = String.format( "textfield3: %s", event.getactioncommand() ); // user pressed Enter in JTextField passwordfield else if ( event.getsource() == passwordfield ) string = String.format( "passwordfield: %s", new String( passwordfield.getpassword() ) ); Test if the source of the event is the Outline first text field 36 Get text from text field // user pressed Enter in JTextField textfield2 // user pressed Enter in JTextField textfield3 77 // display JTextField content 78 JOptionPane.showMessageDialog( null, string ); 79 } // end method actionperformed 80 } // end private inner class TextFieldHandler 81 } // end class TextFieldFrame TextFieldFrame.java Test if the source of the event is the second text field (3 of 3) Get text from text field Test if the source of the event is the third text field Get text from text field Test if the source of the event is the password field Get password from password field

37 1 // Fig : TextFieldTest.java 2 // Testing TextFieldFrame. 3 import javax.swing.jframe; Outline public class TextFieldTest 6 7 public static void main( String args[] ) 8 TextFieldTest.java (1 of 2) 9 TextFieldFrame textfieldframe = new TextFieldFrame(); 10 textfieldframe.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); 11 textfieldframe.setsize( 325, 100 ); // set frame size 12 textfieldframe.setvisible( true ); // display frame 13 } // end main 14 } // end class TextFieldTest

38 Outline 38 TextFieldTest.java (2 of 2)

39 Steps Required to Set Up Event Handling for a GUI Component Several coding steps are required for an application to respond to events Create a class for the event handler Implement an appropriate event-listener interface Register the event handler 39

40 Using a Nested Class to Implement an Event Handler Top-level classes Not declared within another class Nested classes Declared within another class Non-static nested classes are called inner classes Frequently used for event handling 40

41 41 Software Engineering Observation 11.2 An inner class is allowed to directly access its top-level class s variables and methods, even if they are private.

42 Using a Nested Class to Implement an Event Handler JTextFields and JPasswordFields Pressing enter within either of these fields causes an ActionEvent Processed by objects that implement the ActionListener interface 42

43 Registering the Event Handler for Each Text Field Registering an event handler Call method addactionlistener to register an ActionListener object ActionListener listens for events on the object 43

44 Details of Class TextFieldHandler s actionperformed Method Event source Component from which event originates Can be determined using method getsource Text from a JTextField can be acquired using getactioncommand Text from a JPasswordField can be acquired using getpassword 44

45 11.6 Common GUI Event Types and Listener Interfaces Event types All are subclasses of AWTEvent Some declared in package java.awt.event Those specific to Swing components declared in javax.swing.event 45

46 11.6 Common GUI Event Types and Listener Interfaces Delegation event model Event source is the component with which user interacts Event object is created and contains information about the event that happened Event listener is notified when an event happens 46

47 47 Fig Some event classes of package java.awt.event.

48 48 Fig Some common event-listener interfaces of package java.awt.event.

49 How Event Handling Works Remaining questions How did the event handler get registered? How does the GUI component know to call actionperformed rather than some other eventhandling method?

50 50 Registering Events Every JComponent has instance variable listenerlist Object of type EventListenerList Maintains references to all its registered listeners

51 51 Fig Event registration for JTextField textfield1.

52 52 Event-Handler Invocation Events are dispatched to only the event listeners that match the event type Events have a unique event ID specifying the event type MouseEvents are handled by MouseListeners and MouseMotionsListeners KeyEvents are handled by KeyListeners

53 JButton Button Component user clicks to trigger a specific action Can be command button, check box, toggle button or radio button Button types are subclasses of class AbstractButton

54 JButton Command button Generates an ActionEvent when it is clicked Created with class JButton Text on the face of the button is called button label

55 55 Fig Swing button hierarchy.

56 56 Buttons

57 1 // Fig : ButtonFrame.java // Creating JButtons. import java.awt.flowlayout; import java.awt.event.actionlistener; import java.awt.event.actionevent; import javax.swing.jframe; import javax.swing.jbutton; import javax.swing.icon; import javax.swing.imageicon; Outline ButtonFrame.java (1 of 2) 10 import javax.swing.joptionpane; Declare two 11 variables 12 public class ButtonFrame extends JFrame private JButton plainjbutton; // button with just text 15 private JButton fancyjbutton; // button with icons // ButtonFrame adds JButtons to JFrame public ButtonFrame() super( "Testing Buttons" ); Create setlayout( new FlowLayout() ); // set frame layout JButton instance new JButton plainjbutton = new JButton( "Plain Button" ); // Create button two withimageicons text add( plainjbutton ); // add plainjbutton to JFrame Create new JButton Icon bug1 = new ImageIcon( getclass().getresource( "bug1.gif" ) ); Icon bug2 = new ImageIcon( getclass().getresource( "bug2.gif" ) ); fancyjbutton = new JButton( "Fancy Button", bug1 ); // set image Set rollover icon for JButton fancyjbutton.setrollovericon( bug2 ); // set rollover image add( fancyjbutton ); // add fancyjbutton to JFrame

58 // create new ButtonHandler for button event handling ButtonHandler handler = new ButtonHandler(); fancyjbutton.addactionlistener( handler ); Create plainjbutton.addactionlistener( handler ); } // end ButtonFrame constructor Outline 58 handler for buttons ButtonFrame.java Register event handlers // inner class for button event handling private class ButtonHandler implements ActionListener // handle button event public void actionperformed( ActionEvent event ) Inner class implements JOptionPane.showMessageDialog( ButtonFrame.this, String.format( 45 "You pressed: %s", event.getactioncommand() ) ); 46 } // end method actionperformed Access outer class s 47 } // end private inner class ButtonHandler this reference 48 } // end class ButtonFrame (2 of 2) ActionListener instance using Get text of JButton pressed

59 1 // Fig : ButtonTest.java 2 // Testing ButtonFrame. 3 import javax.swing.jframe; Outline public class ButtonTest 6 ButtonTest.java 7 public static void main( String args[] ) 8 (1 of 2) 9 ButtonFrame buttonframe = new ButtonFrame(); // create ButtonFrame 10 buttonframe.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); 11 buttonframe.setsize( 275, 110 ); // set frame size 12 buttonframe.setvisible( true ); // display frame 13 } // end main 14 } // end class ButtonTest

60 Outline 60 ButtonTest.java (2 of 2)

61 JButton JButtons can have a rollover icon Appears when mouse is positioned over a button Added to a JButton with method setrollovericon

62 62 Software Engineering Observation 11.4 When used in an inner class, keyword this refers to the current inner-class object being manipulated. An inner-class method can use its outer-class object s this by preceding this with the outer-class name and a dot, as in ButtonFrame.this.

63 Buttons That Maintain State State buttons Swing contains three types of state buttons JToggleButton, JCheckBox and JRadioButton JCheckBox and JRadioButton are subclasses of JToggleButton

64 JCheckBox JCheckBox Contains a check box label that appears to right of check box by default Generates an ItemEvent when it is clicked ItemEvents are handled by an ItemListener Passed to method itemstatechanged Method isselected returns whether check box is selected (true) or not (false)

65 65 JCheckBox

66 1 // Fig : CheckBoxFrame.java // Creating JCheckBox buttons. import java.awt.flowlayout; import java.awt.font; import java.awt.event.itemlistener; import java.awt.event.itemevent; import javax.swing.jframe; import javax.swing.jtextfield; import javax.swing.jcheckbox; Outline 66 CheckBoxFrame.java (1 of 3) Declare two JCheckBox instance variables public class CheckBoxFrame extends JFrame private JTextField textfield; // displays text in changing fonts 14 private JCheckBox boldjcheckbox; // to select/deselect bold 15 private JCheckBox italicjcheckbox; // to select/deselect italic // CheckBoxFrame constructor adds JCheckBoxes to JFrame public CheckBoxFrame() super( "JCheckBox Test" ); setlayout( new FlowLayout() ); // set frame layout Set font of text field // set up JTextField and set its font textfield = new JTextField( "Watch the font style change", 20 ); textfield.setfont( new Font( "Serif", Font.PLAIN, 14 ) ); add( textfield ); // add textfield to JFrame

67 28 boldjcheckbox = new JCheckBox( "Bold" ); // create bold checkbox 29 italicjcheckbox = new JCheckBox( "Italic" ); // create italic add( boldjcheckbox ); // add bold checkbox to JFrame add( italicjcheckbox ); // add italic checkbox tocreate JFrametwo // register listeners for JCheckBoxes CheckBoxHandler handler = new CheckBoxHandler(); boldjcheckbox.additemlistener( handler ); italicjcheckbox.additemlistener( handler ); } // end CheckBoxFrame constructor Outline 67 JCheckBoxes Create event handler CheckBoxFrame.java (2 of 3) Register event handler with JCheckBoxes // private inner class for ItemListener event handling private class CheckBoxHandler implements ItemListener Inner class implements private int valbold = Font.PLAIN; // controls bold font style ItemListener private int valitalic = Font.PLAIN; // controls italic font style // respond to checkbox events public void itemstatechanged( ItemEvent event ) itemstatechanged method is called when a JCheckBox is clicked // process bold checkbox events if ( event.getsource() == boldjcheckbox ) valbold = boldjcheckbox.isselected()? Font.BOLD : Font.PLAIN; Test whether JCheckBox is selected

68 53 // process italic checkbox events 54 if ( event.getsource() == italicjcheckbox ) valitalic = italicjcheckbox.isselected()? Font.ITALIC : Font.PLAIN; // set text field font 59 textfield.setfont( Test source of the event Outline 68 CheckBoxFrame isselected method returns.java whether JCheckBox is selected new Font( "Serif", valbold + valitalic, 14 ) ); } // end method itemstatechanged (3 of 3) } // end private inner class CheckBoxHandler 63 } // end class CheckBoxFrame

69 1 // Fig : CheckBoxTest.java 2 // Testing CheckBoxFrame. 3 import javax.swing.jframe; Outline public class CheckBoxTest 6 7 public static void main( String args[] ) 8 CheckBoxTest.java 9 CheckBoxFrame checkboxframe = new CheckBoxFrame(); 10 checkboxframe.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); 11 checkboxframe.setsize( 275, 100 ); // set frame size 12 checkboxframe.setvisible( true ); // display frame 13 } // end main 14 } // end class CheckBoxTest

70 JRadioButton JRadioButton Has two states selected and unselected Normally appear in a group in which only one radio button can be selected at once Group maintained by a ButtonGroup object Declares method add to add a JRadioButton to group Usually represents mutually exclusive options

71 71 JRadioButton

72 1 2 // Fig : RadioButtonFrame.java // Creating radio buttons using ButtonGroup and JRadioButton import import import import import import import import Outline java.awt.flowlayout; java.awt.font; java.awt.event.itemlistener; java.awt.event.itemevent; javax.swing.jframe; javax.swing.jtextfield; javax.swing.jradiobutton; javax.swing.buttongroup; 72 RadioButtonFrame.java (1 of 3) public class RadioButtonFrame extends JFrame 13 Declare four JRadioButtons 14 private JTextField textfield; // used to display font changes and a ButtonGroup to manage 15 private Font plainfont; // font for plain text them 16 private Font boldfont; // font for bold text private private private private private private private // RadioButtonFrame constructor adds JRadioButtons to JFrame public RadioButtonFrame() super( "RadioButton Test" ); setlayout( new FlowLayout() ); // set frame layout Font italicfont; // font for italic text Font bolditalicfont; // font for bold and italic text JRadioButton plainjradiobutton; // selects plain text JRadioButton boldjradiobutton; // selects bold text JRadioButton italicjradiobutton; // selects italic text JRadioButton bolditalicjradiobutton; // bold and italic ButtonGroup radiogroup; // buttongroup to hold radio buttons

73 31 textfield = new JTextField( "Watch the font style change", 25 ); add( textfield ); // add textfield to JFrame // create radio buttons plainjradiobutton = new JRadioButton( "Plain", true ); boldjradiobutton = new JRadioButton( "Bold", false ); italicjradiobutton = new JRadioButton( "Italic", false );.java bolditalicjradiobutton = new JRadioButton( "Bold/Italic", false ); add( plainjradiobutton ); // add plain button to JFrame (2 of 3) add( boldjradiobutton ); // add bold button to JFrame add( italicjradiobutton ); // add italic button to JFrame Create the four JRadioButtons add( bolditalicjradiobutton ); // add bold and italic button // create logical relationship between JRadioButtons radiogroup = new ButtonGroup(); // create ButtonGroup radiogroup.add( plainjradiobutton ); // add plain to group Create radiogroup.add( boldjradiobutton ); // add bold to group Outline 73 RadioButtonFrame the ButtonGroup radiogroup.add( italicjradiobutton ); // add italic to group radiogroup.add( bolditalicjradiobutton ); // add bold and italic bolditalicfont = new Font( "Serif", Font.BOLD + Font.ITALIC, 14 ); textfield.setfont( plainfont ); // set initial font to plain Add each JRadioButton to the // create font objects ButtonGroup plainfont = new Font( "Serif", Font.PLAIN, 14 ); boldfont = new Font( "Serif", Font.BOLD, 14 ); italicfont = new Font( "Serif", Font.ITALIC, 14 );

74 58 // register events for JRadioButtons plainjradiobutton.additemlistener( new RadioButtonHandler( plainfont ) ); boldjradiobutton.additemlistener( new RadioButtonHandler( boldfont ) ); italicjradiobutton.additemlistener( new RadioButtonHandler( italicfont ) ); bolditalicjradiobutton.additemlistener( new RadioButtonHandler( bolditalicfont ) ); Outline 74 Register an event handler with each JRadioButton RadioButtonFrame.java (3 of 3) } // end RadioButtonFrame constructor // private inner class to handle radio button events private class RadioButtonHandler implements ItemListener Event handler inner class implements ItemListener private Font font; // font associated with this listener public RadioButtonHandler( Font f ) When radio button is selected, the text field s font will be set to the value passed to the constructor font = f; // set the font of this listener } // end constructor RadioButtonHandler // handle radio button events public void itemstatechanged( ItemEvent event ) textfield.setfont( font ); // set font of textfield 83 } // end method itemstatechanged 84 } // end private inner class RadioButtonHandler 85 } // end class RadioButtonFrame

75 1 // Fig : RadioButtonTest.java 2 // Testing RadioButtonFrame. 3 import javax.swing.jframe; Outline public class RadioButtonTest 6 7 public static void main( String args[] ) 8 RadioButtonTest.java 9 RadioButtonFrame radiobuttonframe = new RadioButtonFrame(); 10 radiobuttonframe.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); 11 radiobuttonframe.setsize( 300, 100 ); // set frame size 12 radiobuttonframe.setvisible( true ); // display frame 13 } // end main 14 } // end class RadioButtonTest

76 JComboBox and Using an Anonymous Inner Class for Event Handling Combo box Also called a drop-down list Implemented by class JComboBox Each item in the list has an index setmaximumrowcount sets the maximum number of rows shown at once JComboBox provides a scrollbar and up and down arrows to traverse list

77 Using an Anonymous Inner Class for Event Handling Anonymous inner class Special form of inner class Declared without a name Typically appears inside a method call Has limited access to local variables 77

78 78 JComboBox Scrollbar to scroll through the items in the list scroll arrows scroll box

79 1 // Fig : ComboBoxFrame.java 2 // Using a JComboBox to select an image to display import import import import java.awt.flowlayout; java.awt.event.itemlistener; java.awt.event.itemevent; javax.swing.jframe; import import import import javax.swing.jlabel; javax.swing.jcombobox; javax.swing.icon; javax.swing.imageicon; Outline 79 ComboBoxFrame.java (1 of 2) public class ComboBoxFrame extends JFrame private JComboBox imagesjcombobox; // combobox to hold names of icons private JLabel label; // label to display selected icon private String names[] = Declare JComboBox instance variable "bug1.gif", "bug2.gif", "travelbug.gif", "buganim.gif" }; private Icon icons[] = new ImageIcon( getclass().getresource( names[ 0 ] ) ), new ImageIcon( getclass().getresource( names[ 1 ] ) ), new ImageIcon( getclass().getresource( names[ 2 ] ) ), new ImageIcon( getclass().getresource( names[ 3 ] ) ) }; // ComboBoxFrame constructor adds JComboBox to JFrame public ComboBoxFrame() super( "Testing JComboBox" ); setlayout( new FlowLayout() ); // set frame layout

80 31 imagesjcombobox = new JComboBox( names ); // set up JComboBox 32 Create JComboBox imagesjcombobox.setmaximumrowcount( 3 ); // display three rows imagesjcombobox.additemlistener( new ItemListener() // anonymous inner class and set maximum row count Create anonymous inner class as ComboBoxrame the event handler.java // handle JComboBox event public void itemstatechanged( ItemEvent event ) Declare method // determine whether check box selected itemstatechanged if ( event.getstatechange() == ItemEvent.SELECTED ) label.seticon( icons[ imagesjcombobox.getselectedindex()test ] );state change } // end method itemstatechanged } // end anonymous inner class ); // end call to additemlistener Outline 80 (2 of 2) of JComboBox Method getselectedindex locates selected item 48 add( imagesjcombobox ); // add combobox to JFrame 49 label = new JLabel( icons[ 0 ] ); // display first icon 50 add( label ); // add label to JFrame 51 } // end ComboBoxFrame constructor 52 } // end class ComboBoxFrame

81 1 // Fig : ComboBoxTest.java 2 // Testing ComboBoxFrame. 3 import javax.swing.jframe; Outline public class ComboBoxTest 6 7 public static void main( String args[] ) 8 ComboBoxTest.java 9 ComboBoxFrame comboboxframe = new ComboBoxFrame(); 10 comboboxframe.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); comboboxframe.setsize( 350, 150 ); // set frame size comboboxframe.setvisible( true ); // display frame } // end main 14 } // end class ComboBoxTest Scrollbar to scroll through the items in the list scroll arrows scroll box

82 JList List Displays a series of items from which the user may select one or more items Implemented by class JList Allows for single-selection lists or multiple-selection lists A ListSelectionEvent occurs when an item is selected Handled by a ListSelectionListener and passed to method valuechanged

83 1 // Fig : ListFrame.java // Selecting colors from a JList. import java.awt.flowlayout; import java.awt.color; import javax.swing.jframe; import javax.swing.jlist; import import import import Outline ListFrame.java javax.swing.jscrollpane; javax.swing.event.listselectionlistener; javax.swing.event.listselectionevent; javax.swing.listselectionmodel; (1 of 2) 12 public class ListFrame extends JFrame private JList colorjlist; // list to display colors 15 private final String colornames[] = "Black", "Blue", "Cyan", 16 "Dark Gray", "Gray", "Green", "Light Gray", "Magenta", Declare JList instance "Orange", "Pink", "Red", "White", "Yellow" }; private final Color colors[] = Color.BLACK, Color.BLUE, Color.CYAN, Color.DARK_GRAY, Color.GRAY, Color.GREEN, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED, Color.WHITE, Color.YELLOW }; // ListFrame constructor add JScrollPane containing JList to JFrame public ListFrame() super( "List Test" ); variable setlayout( new FlowLayout() ); // set frame layout

84 29 colorjlist = new JList( colornames ); // create with colornames 30 colorjlist.setvisiblerowcount( 5 ); // display five rows at once // do not allow multiple selections colorjlist.setselectionmode( ListSelectionModel.SINGLE_SELECTION ); Create JList // add a JScrollPane containing JList to frame add( new JScrollPane( colorjlist ) ); Outline 84 ListFrame.java Set selection mode of JList (2 of 2) colorjlist.addlistselectionlistener( new ListSelectionListener() // anonymous inneradd class JList to ScrollPane add to application // handle list selection events and public void valuechanged( ListSelectionEvent event ) getcontentpane().setbackground( colors[ colorjlist.getselectedindex() ] ); 46 } // end method valuechanged 47 } // end anonymous inner class 48 ); // end call to addlistselectionlistener 49 } // end ListFrame constructor 50 } // end class ListFrame Get index of selected item

85 1 // Fig : ListTest.java 2 // Selecting colors from a JList. 3 import javax.swing.jframe; Outline public class ListTest 6 ListTest.java 7 public static void main( String args[] ) 8 9 ListFrame listframe = new ListFrame(); // create ListFrame 10 listframe.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); 11 listframe.setsize( 350, 150 ); // set frame size 12 listframe.setvisible( true ); // display frame 13 } // end main 14 } // end class ListTest

86 Multiple-Selection Lists Multiple-selection list Enables users to select many items Single interval selection allows only a continuous range of items Multiple interval selection allows any set of elements to be selected

87 1 2 // Fig : MultipleSelectionFrame.java // Copying items from one List to another. 3 4 import java.awt.flowlayout; import java.awt.event.actionlistener; 5 6 import java.awt.event.actionevent; import javax.swing.jframe; 7 import javax.swing.jlist; 8 9 import javax.swing.jbutton; import javax.swing.jscrollpane; Outline 87 Multiple SelectionFrame.java (1 of 3) 10 import javax.swing.listselectionmodel; public class MultipleSelectionFrame extends JFrame private JList colorjlist; // list to hold color names 15 private JList copyjlist; // list to copy color names into 16 private JButton copyjbutton; // button to copy selected names private final String colornames[] = "Black", "Blue", "Cyan", "Dark Gray", "Gray", "Green", "Light Gray", "Magenta", "Orange", "Pink", "Red", "White", "Yellow" }; // MultipleSelectionFrame constructor public MultipleSelectionFrame() 24 super( "Multiple Selection Lists" ); setlayout( new FlowLayout() ); // set frame layout

88 27 colorjlist = new JList( colornames ); // holds names of all colors colorjlist.setvisiblerowcount( 5 ); // show five rows colorjlist.setselectionmode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION ); add( new JScrollPane( colorjlist ) ); // add listuse with scrollpane a multiple interval copyjbutton = new JButton( "Copy >>>" ); // create copy button copyjbutton.addactionlistener( Outline 88 selection list Multiple SelectionFrame.java (2 of 3) new ActionListener() // anonymous inner class // handle button event public void actionperformed( ActionEvent event ) // place selected values in copyjlist copyjlist.setlistdata( colorjlist.getselectedvalues() ); } // end method actionperformed } // end anonymous inner class ); // end call to addactionlistener Use methods setlistdata and getselectedvalues to copy values from one JList to the other

89 47 add( copyjbutton ); // add copy button to JFrame Outline copyjlist = new JList(); // create list to hold copied Set cellcolor widthnames for presentation 50 copyjlist.setvisiblerowcount( 5 ); // show 5 rows 51 copyjlist.setfixedcellwidth( 100 ); // set width 52 copyjlist.setfixedcellheight( 15 ); // set height 53 copyjlist.setselectionmode( Multiple SelectionFrame Set cell height for presentation.java ListSelectionModel.SINGLE_INTERVAL_SELECTION ); (3 of 3) Set selection model to single interval selection add( new JScrollPane( copyjlist ) ); // add list with scrollpane } // end MultipleSelectionFrame constructor 57 } // end class MultipleSelectionFrame

90 1 // Fig : MultipleSelectionTest.java 2 // Testing MultipleSelectionFrame. 3 4 import javax.swing.jframe; public class MultipleSelectionTest public static void main( String args[] ) Outline 90 Multiple SelectionTest.java MultipleSelectionFrame multipleselectionframe = new MultipleSelectionFrame(); multipleselectionframe.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); 13 multipleselectionframe.setsize( 350, 140 ); // set frame size 14 multipleselectionframe.setvisible( true ); // display frame 15 } // end main 16 } // end class MultipleSelectionTest

91 Mouse Event Handling Mouse events Create a MouseEvent object Handled by MouseListeners and MouseMotionListeners MouseInputListener combines the two interfaces Interface MouseWheelListener declares method mousewheelmoved to handle MouseWheelEvents

92 92 MouseListener and MouseMotionListener interface methods Methods of interface MouseListener public void mousepressed( MouseEvent event ) Called when a mouse button is pressed while the mouse cursor is on a component. public void mouseclicked( MouseEvent event ) Called when a mouse button is pressed and released while the mouse cursor remains stationary on a component. This event is always preceded by a call to mousepressed. public void mousereleased( MouseEvent event ) Called when a mouse button is released after being pressed. This event is always preceded by a call to mousepressed and one or more calls to mousedragged. public void mouseentered( MouseEvent event ) Called when the mouse cursor enters the bounds of a component. Fig MouseListener and MouseMotionListener interface methods. (Part 1 of 2.)

93 93 MouseListener and MouseMotionListener interface methods public void mouseexited( MouseEvent event ) Called when the mouse cursor leaves the bounds of a component. Methods of interface MouseMotionListener public void mousedragged( MouseEvent event ) Called when the mouse button is pressed while the mouse cursor is on a component and the mouse is moved while the mouse button remains pressed. This event is always preceded by a call to mousepressed. All drag events are sent to the component on which the user began to drag the mouse. public void mousemoved( MouseEvent event ) Called when the mouse is moved when the mouse cursor is on a component. All move events are sent to the component over which the mouse is currently positioned. Fig MouseListener and MouseMotionListener interface methods. (Part 2 of 2.)

94 Outline 94 MouseTracker Frame.java (2 of 2)

95 1 // Fig : MouseTrackerFrame.java // Demonstrating mouse events. import java.awt.color; import java.awt.borderlayout; import java.awt.event.mouselistener; import java.awt.event.mousemotionlistener; import java.awt.event.mouseevent; import javax.swing.jframe; import javax.swing.jlabel; import javax.swing.jpanel; Outline 95 MouseTracker Frame.java (1 of 4) public class MouseTrackerFrame extends JFrame private JPanel mousepanel; // panel in which mouse events will occur 15 private JLabel statusbar; // label that displays event information // MouseTrackerFrame constructor sets up GUI and // registers mouse event handlers public MouseTrackerFrame() super( "Demonstrating Mouse Events" ); Create JPanel to capture mouse events Set background to white mousepanel = new JPanel(); // create panel mousepanel.setbackground( Color.WHITE ); // set background color Create JLabel add( mousepanel, BorderLayout.CENTER ); // add panel to JFrame and add to application statusbar = new JLabel( "Mouse outside JPanel" ); add( statusbar, BorderLayout.SOUTH ); // add label to JFrame

96 30 // create and register listener for mouse and mouse motion events Outline Create event handler for mouse events MouseHandler handler = new MouseHandler(); mousepanel.addmouselistener( handler ); mousepanel.addmousemotionlistener( handler ); } // end MouseTrackerFrame constructor private class MouseHandler implements MouseListener, MouseMotionListener Implement mouse // MouseListener event handlers // handle event when mouse released immediately after press public void mouseclicked( MouseEvent event ) Register event handler 96 MouseTracker Frame.java listener interfaces (2 of 4) Declare mouseclicked method public void mousepressed( MouseEvent event ) Declare mousepressed statusbar.settext( String.format( "Pressed at [%d, %d]", event.getx(), event.gety() ) ); } // end method mousepressed public void mousereleased( MouseEvent event ) Declare mousereleased statusbar.settext( String.format( "Released at [%d, %d]", event.getx(), event.gety() ) ); } // end method mousereleased statusbar.settext( String.format( "Clicked at [%d, %d]", event.getx(), event.gety() ) ); } // end method mouseclicked Find location of mouse click // handle event when mouse pressed method // handle event when mouse released after dragging method

97 60 Outline // handle event when mouse enters area public void mouseentered( MouseEvent event ) Declare mouseentered method statusbar.settext( String.format( "Mouse entered at [%d, %d]", event.getx(), event.gety() ) ); MouseTracker mousepanel.setbackground( Color.GREEN ); Frame.java Set background of JPanel } // end method mouseentered // handle event when mouse exits area public void mouseexited( MouseEvent event ) statusbar.settext( "Mouse outside JPanel" ); mousepanel.setbackground( Color.WHITE ); } // end method mouseexited 97 (3 of 4) Declare mouseexited method Set background of JPanel

98 76 77 // MouseMotionListener event handlers // handle event when user drags mouse with button pressed public void mousedragged( MouseEvent event ) Declare mousedragged statusbar.settext( String.format( "Dragged at [%d, %d]", event.getx(), event.gety() ) ); } // end method mousedragged public void mousemoved( MouseEvent event ) Declare mousemoved statusbar.settext( String.format( "Moved at [%d, %d]", event.getx(), event.gety() ) ); Outline 98 method MouseTracker Frame.java (4 of 4) // handle event when user moves mouse method 89 } // end method mousemoved 90 } // end inner class MouseHandler 91 } // end class MouseTrackerFrame

99 1 // Fig : MouseTrackerFrame.java 2 // Testing MouseTrackerFrame. 3 import javax.swing.jframe; Outline public class MouseTracker 6 7 public static void main( String args[] ) 8 MouseTracker Frame.java 9 MouseTrackerFrame mousetrackerframe = new MouseTrackerFrame(); 10 mousetrackerframe.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); 11 mousetrackerframe.setsize( 300, 100 ); // set frame size 12 mousetrackerframe.setvisible( true ); // display frame 13 (1 of 2) } // end main 14 } // end class MouseTracker

100 Outline 100 MouseTracker Frame.java (2 of 2)

101 Adapter Classes Adapter class Implements event listener interface Provides default implementation for all event-handling methods

102 102 Extending MouseAdapter MouseAdapter Adapter class for MouseListener and MouseMotionListener interfaces Extending class allows you to override only the methods you wish to use

103 103 Event-adapter class in java.awt.event Implements interface ComponentAdapter ContainerAdapter FocusAdapter KeyAdapter MouseAdapter MouseMotionAdapter WindowAdapter ComponentListener ContainerListener FocusListener KeyListener MouseListener MouseMotionListener WindowListener Fig Event-adapter classes and the interfaces they implement in package java.awt.event.

104 1 // Fig : MouseDetailsFrame.java // Demonstrating mouse clicks and distinguishing between mouse buttons. import java.awt.borderlayout; import java.awt.graphics; import java.awt.event.mouseadapter; import java.awt.event.mouseevent; import javax.swing.jframe; import javax.swing.jlabel; Outline 104 MouseDetails Frame.java (1 of 2) 10 public class MouseDetailsFrame extends JFrame private String details; // String representing 13 private JLabel statusbar; // JLabel that appears at bottom of window // constructor sets title bar String and register mouse listener public MouseDetailsFrame() super( "Mouse clicks and buttons" ); addmouselistener( new MouseClickHandler() ); // add handler } // end MouseDetailsFrame constructor Register event statusbar = new JLabel( "Click the mouse" ); add( statusbar, BorderLayout.SOUTH ); handler

105 25 // inner class to handle mouse events private class MouseClickHandler extends MouseAdapter // handle mouse click event and determine which button was pressed public void mouseclicked( MouseEvent event ) int xpos = event.getx(); // get x position of mouse int ypos = event.gety(); // get y position of mouse Outline 105 MouseDetails Frame.java (2 of 2) details = String.format( "Clicked %d time(s)", event.getclickcount() ); Get number of times mouse button was clicked if ( event.ismetadown() ) // right mouse button details += " with right mouse button"; Test for right mouse button else if ( event.isaltdown() ) // middle mouse button details += " with center mouse button"; Test for middle mouse button 41 else // left mouse button 42 details += " with left mouse button"; statusbar.settext( details ); // display message in statusbar 45 } // end method mouseclicked 46 } // end private inner class MouseClickHandler 47 } // end class MouseDetailsFrame

106 1 2 // Fig : MouseDetails.java // Testing MouseDetailsFrame. 3 import javax.swing.jframe; 4 5 public class MouseDetails Outline 106 MouseDetails.java public static void main( String args[] ) MouseDetailsFrame mousedetailsframe = new MouseDetailsFrame(); mousedetailsframe.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); (1 of 2) 11 mousedetailsframe.setsize( 400, 150 ); // set frame size 12 mousedetailsframe.setvisible( true ); // display frame 13 } // end main 14 } // end class MouseDetails

107 Outline 107 MouseDetails.java (2 of 2)

108 11.15 JPanel Subclass for Drawing with the Mouse 108 Overriding class JPanel Provides a dedicated drawing area

109 109 InputEvent method Description ismetadown() Returns true when the user clicks the right mouse button on a mouse with two or three buttons. To simulate a right-mousebutton click on a one-button mouse, the user can hold down the Meta key on the keyboard and click the mouse button. isaltdown() Returns true when the user clicks the middle mouse button on a mouse with three buttons. To simulate a middle-mousebutton click on a one- or two-button mouse, the user can press the Alt key on the keyboard and click the only- or left-mouse button, respectively. Fig InputEvent methods that help distinguish among left-, center- and right-mouse-button clicks.

110 110 Method paintcomponent Method paintcomponent Draws on a Swing component Overriding method allows you to create custom drawings Must call superclass method first when overridden

111 111 Look-and-Feel Observation Most Swing GUI components can be transparent or opaque. If a Swing GUI component is opaque, its background will be cleared when its paintcomponent method is called. Only opaque components can display a customized background color. JPanel objects are opaque by default.

112 112 Error-Prevention Tip 11.1 In a JComponent subclass s paintcomponent method, the first statement should always be a call to the superclass s paintcomponent method to ensure that an object of the subclass displays correctly.

113 113 Defining the Custom Drawing Area Customized subclass of JPanel Provides custom drawing area Class Graphics is used to draw on Swing components Class Point represents an x-y coordinate

114 1 // Fig : PaintPanel.java // Using class MouseMotionAdapter. import java.awt.point; import java.awt.graphics; import java.awt.event.mouseevent; import java.awt.event.mousemotionadapter; Outline PaintPanel.java 7 import javax.swing.jpanel; 8 9 public class PaintPanel extends JPanel private int pointcount = 0; // count number of points (1 of 2) // array of java.awt.point references private Point points[] = new Point[ ]; Create array of Points // set up GUI and register mouse event handler public PaintPanel() // handle frame mouse motion event addmousemotionlistener(

115 new MouseMotionAdapter() // anonymous inner class Anonymous inner class for event handling // store drag coordinates and repaint public void mousedragged( MouseEvent event ) Override mousedragged if ( pointcount < points.length ) points[ pointcount ] = event.getpoint(); // find point pointcount++; // increment number of points in array Outline 115 method PaintPanel.java (2 of 2) Get location of mouse cursor repaint(); // repaint JFrame } // end if } // end method mousedragged } // end anonymous inner class ); // end call to addmousemotionlistener } // end PaintPanel constructor // draw oval in a 4-by-4 bounding box at specified location on window public void paintcomponent( Graphics g ) super.paintcomponent( g ); // clears drawing area Repaint the JFrame 43 // draw all points in array 44 for ( int i = 0; i < pointcount; i++ ) 45 g.filloval( points[ i ].x, points[ i ].y, 4, 4 ); 46 } // end method paintcomponent Get the 47 } // end class PaintPanel x and y-coordinates of the Point

116 116 Look-and-Feel Observation Calling repaint for a Swing GUI component indicates that the component should be refreshed on the screen as soon as possible. The background of the GUI component is cleared only if the component is opaque. JComponent method setopaque can be passed a boolean argument indicating whether the component is opaque (true) or transparent (false).

117 117 Look-and-Feel Observation Drawing on any GUI component is performed with coordinates that are measured from the upper-left corner (0, 0) of that GUI component, not the upper-left corner of the screen.

118 // Fig : Painter.java // Testing PaintPanel. import java.awt.borderlayout; import javax.swing.jframe; import javax.swing.jlabel; Outline 118 Painter.java public class Painter public static void main( String args[] ) // create JFrame JFrame application = new JFrame( "A simple paint program" ); (1 of 2) PaintPanel paintpanel = new PaintPanel(); // create paint panel application.add( paintpanel, BorderLayout.CENTER ); // in center // create a label and place it in SOUTH of Create instance of custom drawing BorderLayout panel application.add( new JLabel( "Drag the mouse to draw" ), BorderLayout.SOUTH ); application.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); application.setsize( 400, 200 ); // set frame size 23 application.setvisible( true ); // display frame 24 } // end main 25 } // end class Painter

119 Outline 119 Painter.java (2 of 2)

120 Key-Event Handling KeyListener interface For handling KeyEvents Declares methods keypressed, keyreleased and keytyped

121 1 // Fig : KeyDemo.java 2 // Testing KeyDemoFrame. 3 import javax.swing.jframe; Outline public class KeyDemo 6 KeyDemo.java 7 public static void main( String args[] ) 8 (1 of 2) 9 KeyDemoFrame keydemoframe = new KeyDemoFrame(); 10 keydemoframe.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); 11 keydemoframe.setsize( 350, 100 ); // set frame size 12 keydemoframe.setvisible( true ); // display frame 13 } // end main 14 } // end class KeyDemo

122 Outline 122 KeyDemo.java (1 of 2)

123 1 2 // Fig : KeyDemoFrame.java // Demonstrating keystroke events import import import import import Outline java.awt.color; java.awt.event.keylistener; java.awt.event.keyevent; javax.swing.jframe; javax.swing.jtextarea; KeyDemoFrame.java (1 of 3) public class KeyDemoFrame extends JFrame implements KeyListener private String line1 = ""; // first line of textarea Implement KeyListener private String line2 = ""; // second line of textarea interface private String line3 = ""; // third line of textarea private JTextArea textarea; // textarea to display output // KeyDemoFrame constructor public KeyDemoFrame() Set background color super( "Demonstrating Keystroke Events" ); textarea = new JTextArea( 10, 15 ); // set up JTextArea textarea.settext( "Press any key on the keyboard..." ); textarea.setenabled( false ); // disable textarea textarea.setdisabledtextcolor( Color.BLACK ); // set text color add( textarea ); // add textarea to JFrame Register application as event handler for itself addkeylistener( this ); // allow frame to process key events } // end KeyDemoFrame constructor

124 30 // handle press of any key public void keypressed( KeyEvent event ) Declare keypressed method line1 = String.format( "Key pressed: %s", event.getkeytext( event.getkeycode() ) ); // output pressed key setlines2and3( event ); // set output lines two and three KeyDemoFrame Get code of pressed key } // end method keypressed.java // handle press of an action key Declare keytyped public void keytyped( KeyEvent event ) line1 = String.format( "Key typed: %s", event.getkeychar() ); setlines2and3( event ); // set output lines two and three } // end method keytyped Outline 124 (2 of 3) // handle release of any key public void keyreleased( KeyEvent event ) Declare keyreleased method line1 = String.format( "Key released: %s", event.getkeytext( event.getkeycode() ) ); // output released key setlines2and3( event ); // set output lines two and three Get code of released } // end method keyreleased key method Get character typed

125 53 // set second and third lines of output 54 private void setlines2and3( KeyEvent event ) Outline line2 = String.format( "This key is %san action key", ( event.isactionkey()? "" : "not " ) ); Test if it was an action key String temp = event.getkeymodifierstext( event.getmodifiers() ); KeyDemoFrame.java (3 of 3) Determine any modifiers pressed line3 = String.format( "Modifier keys pressed: %s", ( temp.equals( "" )? "none" : temp ) ); // output modifiers textarea.settext( String.format( "%s\n%s\n%s\n", line1, line2, line3 ) ); // output three lines of text } // end method setlines2and3 67 } // end class KeyDemoFrame

126 Layout Managers Layout managers Provided to arrange GUI components in a container Provide basic layout capabilities Implement the interface LayoutManager

127 127 Look-and-Feel Observation Most Java programming environments provide GUI design tools that help a programmer graphically design a GUI; the design tools then write the Java code to create the GUI. Such tools often provide greater control over the size, position and alignment of GUI components than do the built-in layout managers.

128 128 Look-and-Feel Observation It is possible to set a Container s layout to null, which indicates that no layout manager should be used. In a Container without a layout manager, the programmer must position and size the components in the given container and take care that, on resize events, all components are repositioned as necessary. A component s resize events can be processed by a ComponentListener.

129 FlowLayout FlowLayout Simplest layout manager Components are placed left to right in the order they are added Components can be left aligned, centered or right aligned

130 130 Layout manager Description FlowLayout Default for javax.swing.jpanel. Places components sequentially (left to right) in the order they were added. It is also possible to specify the order of the components by using the Container method add, which takes a Component and an integer index position as arguments. BorderLayout Default for JFrames (and other windows). Arranges the components into five areas: NORTH, SOUTH, EAST, WEST and CENTER. GridLayout Arranges the components into rows and columns. Fig Layout managers.

131 1 2 // Fig : FlowLayoutFrame.java // Demonstrating FlowLayout alignments import import import import import import Outline java.awt.flowlayout; java.awt.container; java.awt.event.actionlistener; java.awt.event.actionevent; javax.swing.jframe; javax.swing.jbutton; 131 FlowLayoutFrame.java (1 of 3) public class FlowLayoutFrame extends JFrame private private private private private // set up GUI and register button listeners public FlowLayoutFrame() super( "FlowLayout Demo" ); JButton leftjbutton; // button to set alignment left JButton centerjbutton; // button to set alignment center JButton rightjbutton; // button to set alignment right FlowLayout layout; // layout object Container container; // container to set layout Create FlowLayout layout = new FlowLayout(); // create FlowLayout container = getcontentpane(); // get container to layout setlayout( layout ); // set frame layout Set layout of application

132 27 28 // set up leftjbutton and register listener leftjbutton = new JButton( "Left" ); // create Left button add( leftjbutton ); // add Left button to frame leftjbutton.addactionlistener( Outline Add JButton; FlowLayout will handle placement new ActionListener() // anonymous inner class // process leftjbutton event public void actionperformed( ActionEvent event ) FlowLayoutFrame.java (2 of 3) layout.setalignment( FlowLayout.LEFT ); Set alignment to left // realign attached components layout.layoutcontainer( container ); } // end method actionperformed } // end anonymous inner class ); // end call to addactionlistener // set up centerjbutton and register listener centerjbutton = new JButton( "Center" ); // create Center button add( centerjbutton ); // add Center button to frame centerjbutton.addactionlistener( new ActionListener() // anonymous inner Adjust layout Add JButton; FlowLayout will handle placement class // process centerjbutton event Set alignment public void actionperformed( ActionEvent event ) layout.setalignment( FlowLayout.CENTER ); to center

133 57 // realign attached components Outline layout.layoutcontainer( container ); } // end method actionperformed } // end anonymous inner class ); // end call to addactionlistener // set up rightjbutton and register listener rightjbutton = new JButton( "Right" ); // create Right button add( rightjbutton ); // add Right button to frame rightjbutton.addactionlistener( Adjust layout FlowLayoutFrame.java (3 of 3) Add JButton; FlowLayout will handle placement class new ActionListener() // anonymous inner // process rightjbutton event public void actionperformed( ActionEvent event ) layout.setalignment( FlowLayout.RIGHT ); Set alignment to right // realign attached components layout.layoutcontainer( container ); 77 } // end method actionperformed 78 } // end anonymous inner class 79 ); // end call to addactionlistener 80 } // end FlowLayoutFrame constructor 81 } // end class FlowLayoutFrame Adjust layout

134 1 // Fig : FlowLayoutDemo.java 2 // Testing FlowLayoutFrame. 3 import javax.swing.jframe; Outline public class FlowLayoutDemo 6 7 public static void main( String args[] ) 8 FlowLayoutDemo.java 9 FlowLayoutFrame flowlayoutframe = new FlowLayoutFrame(); 10 flowlayoutframe.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); 11 flowlayoutframe.setsize( 300, 75 ); // set frame size 12 flowlayoutframe.setvisible( true ); // display frame 13 (1 of 2) } // end main 14 } // end class FlowLayoutDemo

135 Outline 135 FlowLayoutDemo.java (2 of 2)

136 BorderLayout BorderLayout Arranges components into five regions north, south, east, west and center Implements interface LayoutManager2 Provides horizontal gap spacing and vertical gap spacing

137 137 Common Programming Error 11.6 When more than one component is added to a region in a BorderLayout, only the last component added to that region will be displayed. There is no error that indicates this problem.

138 1 2 // Fig : BorderLayoutFrame.java // Demonstrating BorderLayout import import import import import BorderLayout Frame.java public class BorderLayoutFrame extends JFrame implements ActionListener Outline java.awt.borderlayout; java.awt.event.actionlistener; java.awt.event.actionevent; javax.swing.jframe; javax.swing.jbutton; 138 (1 of 2) private JButton buttons[]; // array of buttons to hide portions private final String names[] = "Hide North", "Hide South", "Hide East", "Hide West", "Hide Center" }; private BorderLayout layout; // borderlayout object // set up GUI and event handling public BorderLayoutFrame() Declare BorderLayout instance variable Create BorderLayout super( "BorderLayout Demo" ); layout = new BorderLayout( 5, 5 ); // 5 pixel gaps setlayout( layout ); // set frame layout buttons = new JButton[ names.length ]; // set size of array for ( int count = 0; count < names.length; count++ ) Register buttons[ count ] = new JButton( names[ count ] ); buttons[ count ].addactionlistener( this ); } // end for Set layout // create JButtons and register listeners for them event handler

139 add( buttons[ 0 ], BorderLayout.NORTH ); // add button to north add( buttons[ 1 ], BorderLayout.SOUTH ); // add button to south add( buttons[ 2 ], BorderLayout.EAST ); // add button to east add( buttons[ 3 ], BorderLayout.WEST ); // add button to west add( buttons[ 4 ], BorderLayout.CENTER ); // add button to center } // end BorderLayoutFrame constructor // handle button events public void actionperformed( ActionEvent event ) Outline 139 BorderLayout Frame.java Add buttons to application using layout manager constants (2 of 2) // check event source and layout content pane correspondingly for ( JButton button : buttons ) Make button invisible if ( event.getsource() == button ) button.setvisible( false ); // hide buttonmake clicked button visible 47 else 48 button.setvisible( true ); // show other buttons 49 } // end for layout.layoutcontainer( getcontentpane() ); // layout content pane 52 } // end method actionperformed Update layout 53 } // end class BorderLayoutFrame

140 1 // Fig : BorderLayoutDemo.java 2 // Testing BorderLayoutFrame. 3 import javax.swing.jframe; Outline public class BorderLayoutDemo 6 7 public static void main( String args[] ) 8 BorderLayout Demo.java 9 BorderLayoutFrame borderlayoutframe = new BorderLayoutFrame(); 10 borderlayoutframe.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); 11 borderlayoutframe.setsize( 300, 200 ); // set frame size 12 borderlayoutframe.setvisible( true ); // display frame 13 (1 of 2) } // end main 14 } // end class BorderLayoutDemo horizontal gap vertical gap

141 Outline 141 BorderLayout Demo.java (2 of 2)

142 GridLayout GridLayout Divides container into a grid Every component has the same width and height

143 1 2 // Fig : GridLayoutFrame.java // Demonstrating GridLayout import import import import import import Outline java.awt.gridlayout; java.awt.container; java.awt.event.actionlistener; java.awt.event.actionevent; javax.swing.jframe; javax.swing.jbutton; GridLayout Frame.java (1 of 2) public class GridLayoutFrame extends JFrame implements ActionListener private JButton buttons[]; // array of buttons private final String names[] = Declare two GridLayout "one", "two", "three", "four", "five", "six" }; instance variables private boolean toggle = true; // toggle between two layouts private Container container; // frame container private GridLayout gridlayout1; // first gridlayout private GridLayout gridlayout2; // second gridlayout // no-argument constructor public GridLayoutFrame() super( "GridLayout Demo" ); gridlayout1 = new GridLayout( 2, gridlayout2 = new GridLayout( 3, container = getcontentpane(); // setlayout( gridlayout1 ); // set Create GridLayout 3, 5, 5 ); // 2 by 3; gaps of 5 2 ); // 3 by 2; no gaps get content pane JFrame layout buttons = new JButton[ names.length ]; // create array of JButtons Set layout

144 30 for ( int count = 0; count < names.length; count++ ) 31 Outline 32 buttons[ count ] = new JButton( names[ count ] ); 33 buttons[ count ].addactionlistener( this ); // register listener 34 add( buttons[ count ] ); // add button to JFrame } // end for } // end GridLayoutFrame constructor Add button to JFrame // handle button events by toggling between layouts 39 public void actionperformed( ActionEvent event ) GridLayout Frame.java (2 of 2) Use second layout if ( toggle ) container.setlayout( gridlayout2 ); // set layout to second else Use first layout container.setlayout( gridlayout1 ); // set layout to first toggle =!toggle; // set toggle to opposite value 47 container.validate(); // re-layout container 48 } // end method actionperformed Update layout 49 } // end class GridLayoutFrame

145 1 // Fig : GridLayoutDemo.java 2 // Testing GridLayoutFrame. 3 import javax.swing.jframe; Outline public class GridLayoutDemo 6 7 public static void main( String args[] ) 8 GridLayoutDemo.java 9 GridLayoutFrame gridlayoutframe = new GridLayoutFrame(); 10 gridlayoutframe.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); 11 gridlayoutframe.setsize( 300, 200 ); // set frame size 12 gridlayoutframe.setvisible( true ); // display frame 13 } // end main 14 } // end class GridLayoutDemo

146 11.18 Using Panels to Manage More Complex Layouts 146 Complex GUIs often require multiple panels to arrange their components properly

147 1 // Fig : PanelFrame.java // Using a JPanel to help lay out components. import java.awt.gridlayout; import java.awt.borderlayout; import javax.swing.jframe; import javax.swing.jpanel; Outline PanelFrame.java 7 import javax.swing.jbutton; 8 9 public class PanelFrame extends JFrame private JPanel buttonjpanel; // panel to hold buttons private JButton buttons[]; // array of buttons // no-argument constructor public PanelFrame() 147 (1 of 2) Declare a JPanel to hold buttons Create JPanel super( "Panel Demo" ); buttons = new JButton[ 5 ]; // create buttons array buttonjpanel = new JPanel(); // set up panel buttonjpanel.setlayout( new GridLayout( 1, buttons.length ) ); Set layout

148 22 // create and add buttons 23 for ( int count = 0; count < buttons.length; count++ ) buttons[ count ] = new JButton( "Button " + ( count + 1 ) ); 26 buttonjpanel.add( buttons[ count ] ); // add button to panel 27 } // end for Add button to panel add( buttonjpanel, BorderLayout.SOUTH ); // add panel to JFrame 30 } // end PanelFrame constructor Add panel to application 31 } // end class PanelFrame Outline 148 PanelFrame.java (2 of 2)

149 1 // Fig : PanelDemo.java 2 // Testing PanelFrame. 3 import javax.swing.jframe; Outline public class PanelDemo extends JFrame 6 PanelDemo.java 7 public static void main( String args[] ) 8 9 PanelFrame panelframe = new PanelFrame(); 10 panelframe.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); 11 panelframe.setsize( 450, 200 ); // set frame size 12 panelframe.setvisible( true ); // display frame 13 } // end main 14 } // end class PanelDemo

150 JTextArea JTextArea Provides an area for manipulating multiple lines of text Box container Subclass of Container Uses a BoxLayout layout manager

151 1 // Fig : TextAreaFrame.java // Copying selected text from one textarea to another. import java.awt.event.actionlistener; import java.awt.event.actionevent; import javax.swing.box; import javax.swing.jframe; import javax.swing.jtextarea; import javax.swing.jbutton; import javax.swing.jscrollpane; Outline TextAreaFrame.java (1 of 2) 10 Declare JTextArea 11 public class TextAreaFrame extends JFrame variables private JTextArea textarea1; // displays demo string private JTextArea textarea2; // highlighted text is copied here private JButton copyjbutton; // initiates copying of text // no-argument constructor public TextAreaFrame() 151 instance Create a Box container super( "TextArea Demo" ); Box box = Box.createHorizontalBox(); // create box String demo = "This is a demo string to\n" + "illustrate copying text\nfrom one textarea to \n" + Create text "another textarea using an\nexternal event\n"; textarea1 = new JTextArea( demo, 10, 15 ); // create textarea1 box.add( new JScrollPane( textarea1 ) ); // add scrollpane area and add to box

152 29 copyjbutton = new JButton( "Copy >>>" ); // create copy button box.add( copyjbutton ); // add copy button to box copyjbutton.addactionlistener( Outline 152 Add button to box new ActionListener() // anonymous inner class // set text in textarea2 to selected text from textarea1 public void actionperformed( ActionEvent event ) textarea2.settext( textarea1.getselectedtext() ); } // end method actionperformed } // end anonymous inner class ); // end call to addactionlistener TextAreaFrame.java (2 of 2) Copy selected text from one text area to the other textarea2 = new JTextArea( 10, 15 ); // create second textarea textarea2.seteditable( false ); // disable editing 45 box.add( new JScrollPane( textarea2 ) ); // add scrollpane 46 Create second 47 add( box ); // add box to frame 48 } // end TextAreaFrame constructor to box 49 } // end class TextAreaFrame text area and add it

153 1 // Fig : TextAreaDemo.java 2 // Copying selected text from one textarea to another. 3 import javax.swing.jframe; Outline public class TextAreaDemo 6 7 public static void main( String args[] ) 8 TextAreaDemo.java (1 of 2) 9 TextAreaFrame textareaframe = new TextAreaFrame(); 10 textareaframe.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); 11 textareaframe.setsize( 425, 200 ); // set frame size 12 textareaframe.setvisible( true ); // display frame 13 } // end main 14 } // end class TextAreaDemo

154 Outline 154 TextAreaDemo.java (2 of 2)

155 155 JScrollPane Scrollbar Policies JScrollPane has scrollbar policies Horizontal policies Always (HORIZONTAL_SCROLLBAR_ALWAYS) As needed (HORIZONTAL_SCROLLBAR_AS_NEEDED) Never (HORIZONTAL_SCROLLBAR_NEVER) Vertical policies Always (VERTICAL_SCROLLBAR_ALWAYS) As needed (VERTICAL_SCROLLBAR_AS_NEEDED) Never (VERTICAL_SCROLLBAR_NEVER)

156 156 Files and Streams

157 157 WE WILL COVER To create, read, write and update files. To use class File to retrieve information about files and directories. The Java input/output stream class hierarchy. The differences between text files and binary files. Sequential-access and random-access file processing. To use classes Scanner and Formatter to process text files. To use the FileInputStream and FileOutputStream classes. To use a JFileChooser dialog. To use the ObjectInputStream and ObjectOutputStream classes

158 Introduction 14.2 Data Hierarchy 14.3 Files and Streams 14.4 Class File 14.5 Sequential-Access Text Files Creating a Sequential-Access Text File Reading Data from a Sequential-Access Text File Case Study: A Credit-Inquiry Program Updating Sequential-Access Files

159 Object Serialization Creating a Sequential-Access File Using Object Serialization Reading and Deserializing Data from a SequentialAccess File 14.7 Additional java.io Classes 14.8 Opening Files with JFileChooser 14.9 Wrap-Up

160 Introduction Storage of data in variables and arrays is temporary Files used for long-term retention of large amounts of data, even after the programs that created the data terminate Persistent data exists beyond the duration of program execution Files stored on secondary storage devices Stream ordered data that is read from or written to a file

161 Data Hierarchy Computers process all data items as combinations of zeros and ones Bit smallest data item on a computer, can have values 0 or 1 Byte 8 bits Characters larger data item Consists of decimal digits, letters and special symbols Character set set of all characters used to write programs and represent data items Unicode characters composed of two bytes ASCII

162 Data Hierarchy Fields a group of characters or bytes that conveys meaning Record a group of related fields File a group of related records Data items processed by computers form a data hierarchy that becomes larger and more complex from bits to files Record key identifies a record as belonging to a particular person or entity used for easy retrieval of specific records Sequential file file in which records are stored in order by the record-key field Database a group of related files Database Management System a collection of programs designed to create and manage databases

163 163 Fig Data hierarchy.

164 Files and Streams Java views each files as a sequential stream of bytes Operating system provides mechanism to determine end of file End-of-file marker Count of total bytes in file Java program processing a stream of bytes receives an indication from the operating system when program reaches end of stream

165 Files and Streams File streams Byte-based streams stores data in binary format Binary files created from byte-based streams, read by a program that converts data to human-readable format Character-based streams stores data as a sequence of characters Text files created from character-based streams, can be read by text editors Java opens file by creating an object and associating a stream with it Standard streams each stream can be redirected System.in standard input stream object, can be redirected with method setin System.out standard output stream object, can be redirected with method setout System.err standard error stream object, can be redirected with method seterr

166 Files and Streams java.io classes FileInputStream and FileOutputStream bytebased I/O FileReader and FileWriter character-based I/O ObjectInputStream and ObjectOutputStream used for input and output of objects or variables of primitive data types File useful for obtaining information about files and directories Classes Scanner and Formatter Scanner can be used to easily read data from a file Formatter can be used to easily write data to a file

167 167 Fig Java s view of a file of n bytes.

168 Class File Class File useful for retrieving information about files and directories from disk Objects of class File do not open files or provide any file-processing capabilities

169 169 Creating File Objects Class File provides four constructors: 1. Takes String specifying name and path (location of file on disk) 2. Takes two Strings, first specifying path and second specifying name of file 3. Takes File object specifying path and String specifying name of file 4. Takes URI object specifying name and location of file Different kinds of paths Absolute path contains all directories, starting with the root directory, that lead to a specific file or directory Relative path normally starts from the directory in which the application began executing

170 170 Method Description boolean canread() Returns true if a file is readable by the current application; false otherwise. boolean canwrite() Returns true if a file is writable by the current application; false otherwise. boolean exists() Returns true if the name specified as the argument to the File constructor is a file or directory in the specified path; false otherwise. boolean isfile() Returns true if the name specified as the argument to the File constructor is a file; false otherwise. boolean isdirectory() Returns true if the name specified as the argument to the File constructor is a directory; false otherwise. boolean isabsolute() Returns true if the arguments specified to the File constructor indicate an absolute path to a file or directory; false otherwise. Fig File methods. (Part 1 of 2)

171 171 Method Description String getabsolutepath() Returns a string with the absolute path of the file or directory. String getname() Returns a string with the name of the file or directory. String getpath() Returns a string with the path of the file or directory. String getparent() Returns a string with the parent directory of the file or directory (i.e., the directory in which the file or directory can be found). long length() Returns the length of the file, in bytes. If the File object represents a directory, 0 is returned. long lastmodified() Returns a platform-dependent representation of the time at which the file or directory was last modified. The value returned is useful only for comparison with other values returned by this method. String[] list() Returns an array of strings representing the contents of a directory. Returns null if the File object does not represent a directory. Fig.14.3 File methods. (Part 2 of 2)

172 172 Error-Prevention Tip 14.1 Use File method isfile to determine whether a File object represents a file (not a directory) before attempting to open the file.

173 173 Demonstrating Class File Common File methods exists return true if file exists where it is specified isfile returns true if File is a file, not a directory isdirectory returns true if File is a directory getpath return file path as a string list retrieve contents of a directory Separator character used to separate directories and files in a path Windows uses \ UNIX uses / Java process both characters, File.pathSeparator can be used to obtain the local computer s proper separator character

174 1 // Fig. 14.4: FileDemonstration.java // Demonstrating the File class. import java.io.file; public class FileDemonstration // display information about file user specifies public void analyzepath( String path ) // create File object based on user input File name = new File( path ); if ( name.exists() ) // if name exists, output information about it // display file (or directory) information System.out.printf( "%s%s\n%s\n%s\n%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s", Returns true if name is a directory, not a file name.getname(), " exists", ( name.isfile()? "is a file" : "is not a file" ), ( name.isdirectory()? "is a directory" : "is not a directory" ), ( name.isabsolute()? "is absolute path" : "is not absolute path" ), "Last modified: ", name.lastmodified(), "Length: ", name.length(), "Path: ", name.getpath(), "Absolute path: ", name.getabsolutepath(), "Parent: ", name.getparent() ); Retrieve length of file in bytes Retrieve parent directory (path Retrieve absolute path of file or directory where File object s file or directory can be found)

175 28 if ( name.isdirectory() ) // output directory listing Returns true if File is a directory, not a file 30 String directory[] = name.list(); 31 System.out.println( "\n\ndirectory contents:\n" ); for ( String directoryname : directory ) } // end else 36 } // end outer if 37 else // not file or directory, output error message Retrieve and display contents of directory System.out.printf( "%s\n", directoryname ); System.out.printf( "%s %s", path, "does not exist." ); } // end else } // end method analyzepath 42 } // end class FileDemonstration

176 1 // Fig. 14.5: FileDemonstrationTest.java 2 // Testing the FileDemonstration class. 3 import java.util.scanner; public class FileDemonstrationTest 6 7 public static void main( String args[] ) 8 9 Scanner input = new Scanner( System.in ); 10 FileDemonstration application = new FileDemonstration(); System.out.print( "Enter file or directory name here: " ); 13 application.analyzepath( input.nextline() ); 14 } // end main 15 } // end class FileDemonstrationTest

177 Enter file or directory name here: C:\Program Files\Java\jdk1.5.0\demo\jfc jfc exists is not a file is a directory is absolute path Last modified: Length: 0 Path: C:\Program Files\Java\jdk1.5.0\demo\jfc Absolute path: C:\Program Files\Java\jdk1.5.0\demo\jfc Parent: C:\Program Files\Java\jdk1.5.0\demo 177 Directory contents: CodePointIM FileChooserDemo Font2DTest Java2D Metalworks Notepad SampleTree Stylepad SwingApplet SwingSet2 TableExample

178 Enter file or directory name here: C:\Program Files\Java\jdk1.5.0\demo\jfc\Java2D\readme.txt readme.txt exists is a file is not a directory is absolute path Last modified: Length: 7501 Path: C:\Program Files\Java\jdk1.5.0\demo\jfc\Java2D\readme.txt Absolute path: C:\Program Files\Java\jdk1.5.0\demo\jfc\Java2D\readme.txt Parent: C:\Program Files\Java\jdk1.5.0\demo\jfc\Java2D Outline 178 FileDemonstration Test.java (3 of 3)

179 179 Common Programming Error 14.1 Using \ as a directory separator rather than \\ in a string literal is a logic error. A single \ indicates that the \ followed by the next character represents an escape sequence. Use \\ to insert a \ in a string literal.

180 Sequential-Access Text Files Records are stored in order by record-key field Can be created as text files or binary files

181 Creating a Sequential-Access Text File 181 Java imposes no structure on a file, records do not exist as part of the Java language Programmer must structure files Formatter class can be used to open a text file for writing Pass name of file to constructor If file does not exist, will be created If file already exists, contents are truncated (discarded) Use method format to write formatted text to file Use method close to close the Formatter object (if method not called, OS normally closes file when program exits)

182 Creating a Sequential-Access Text File 182 Possible exceptions SecurityException occurs when opening file using Formatter object, if user does not have permission to write data to file FileNotFoundException occurs when opening file using Formatter object, if file cannot be found and new file cannot be created NoSuchElementException occurs when invalid input is read in by a Scanner object FormatterClosedException occurs when an attempt is made to write to a file using an already closed Formatter object

183 // Fig. 14.6: AccountRecord.java // A class that represents one record of information. package com.deitel.jhtp7.ch14; // packaged for reuse 183 public class AccountRecord private int account; private String firstname; private String lastname; private double balance; // no-argument constructor calls other constructor with default values public AccountRecord() this( 0, "", "", 0.0 ); // call four-argument constructor } // end no-argument AccountRecord constructor // initialize a record public AccountRecord( int acct, String first, String last, double bal ) setaccount( acct ); setfirstname( first ); setlastname( last ); setbalance( bal ); } // end four-argument AccountRecord constructor

184 // set account number public void setaccount( int acct ) account = acct; } // end method setaccount 184 // get account number public int getaccount() return account; } // end method getaccount // set first name public void setfirstname( String first ) firstname = first; } // end method setfirstname // get first name public String getfirstname() return firstname; } // end method getfirstname // set last name public void setlastname( String last ) lastname = last; } // end method setlastname

185 57 // get last name 58 public String getlastname() return lastname; } // end method getlastname // set balance 64 public void setbalance( double bal ) balance = bal; } // end method setbalance // get balance 70 public double getbalance() return balance; } // end method getbalance 74 } // end class AccountRecord

186 1 // Fig. 14.9: CreateTextFileTest.java 2 // Testing the CreateTextFile class public class CreateTextFileTest 5 6 public static void main( String args[] ) 7 8 CreateTextFile application = new CreateTextFile(); 9 10 application.openfile(); 11 application.addrecords(); 12 application.closefile(); 13 } // end main 14 } // end class CreateTextFileTest

187 187 1 // Fig. 14.7: CreateTextFile.java 2 3 // Writing data to a text file with class Formatter. import java.io.filenotfoundexception; 4 5 import java.lang.securityexception; import java.util.formatter; 6 import java.util.formatterclosedexception; 7 8 import java.util.nosuchelementexception; import java.util.scanner; Used for writing data to file 9 10 import com.deitel.jhtp7.ch14.accountrecord; public class CreateTextFile Used for retrieving input from user private Formatter output; // object used to output text to file // enable user to open file public void openfile() 18 Object used to output data to file try output = new Formatter( "clients.txt" ); } // end try catch ( SecurityException securityexception ) Open file clients.txt for writing 25 System.err.println( "You do not have write access to this file." ); System.exit( 1 ); 28 } // end catch

188 29 catch ( FileNotFoundException filesnotfoundexception ) System.err.println( "Error creating file." ); System.exit( 1 ); } // end catch } // end method openfile // add records to file public void addrecords() // object to be written to file AccountRecord record = new AccountRecord(); Create AccountRecord to be filled with user input Scanner input = new Scanner( System.in ); System.out.printf( "%s\n%s\n%s\n%s\n\n", Create Scanner to retrieve "To terminate input, type the end-of-file indicator ", from user "when you are prompted to enter input.", input "On UNIX/Linux/Mac OS X type <ctrl> d then press Enter", "On Windows type <ctrl> z then press Enter" ); System.out.printf( "%s\n%s", "Enter account number (> 0), first name, last name and balance.", "? " ); 53

189 54 while ( input.hasnext() ) // loop until end-of-file indicator try // output values to file Loop while user is entering input // retrieve data to be output record.setaccount( input.nextint() ); // read account number record.setfirstname( input.next() ); // read first name record.setlastname( input.next() ); // read last name record.setbalance( input.nextdouble() ); // read balance } // end if else Write AccountRecord System.out.println( "Account number must be greater than 0." ); if ( record.getaccount() > 0 ) // write new record output.format( "%d %s %s %.2f\n", record.getaccount(), record.getfirstname(), record.getlastname(), record.getbalance() ); Retrieve input, store data in AccountRecord information to file File closed while to write to it } // end else trying } // end try catch ( FormatterClosedException formatterclosedexception ) System.err.println( "Error writing to file." ); return; } // end catch

190 82 catch ( NoSuchElementException elementexception ) System.err.println( "Invalid input. Please try again." ); 85 input.nextline(); // discard input so userwith can input try again Error entered 86 by user } // end catch System.out.printf( "%s %s\n%s", "Enter account number (>0),", 89 "first name, last name and balance.", "? " ); } // end while } // end method addrecords // close file 94 public void closefile() if ( output!= null ) 97 output.close(); 98 Close file } // end method closefile 99 } // end class CreateTextFile

191 191 Operating system Key combination UNIX/Linux/Mac OS X <return> <ctrl> d Windows <ctrl> z Fig.14.8 End-of-file key combinations for various popular operating systems.

192 To terminate input, type the end-of-file indicator when you are prompted to enter input. On UNIX/Linux/Mac OS X type <ctrl> d then press Enter On Windows type <ctrl> z then press Enter Enter? 100 Enter? 200 Enter? 300 Enter? 400 Enter? 500 Enter? ^Z account number (> Bob Jones account number (> Steve Doe account number (> Pam White 0.00 account number (> Sam Stone account number (> Sue Rich account number (> 192 0), first name, last name and balance. 0), first name, last name and balance. 0), first name, last name and balance. 0), first name, last name and balance. 0), first name, last name and balance. 0), first name, last name and balance.

193 193 Sample data Bob Steve Pam Sam Sue Jones Doe White Stone Rich Fig Sample data for the program in Fig

194 Reading Data from a SequentialAccess Text File 194 Data is stored in files so that it may be retrieved for processing when needed Scanner object can be used to read data sequentially from a text file Pass File object representing file to be read to Scanner constructor FileNotFoundException occurs if file cannot be found Data read from file using same methods as for keyboard input nextint, nextdouble, next, etc. IllegalStateException occurs if attempt is made to read from closed Scanner object

195 1 // Fig : ReadTextFileTest.java 2 // This program test class ReadTextFile public class ReadTextFileTest 5 6 public static void main( String args[] ) 7 8 ReadTextFile application = new ReadTextFile(); 9 10 application.openfile(); 11 application.readrecords(); 12 application.closefile(); 13 } // end main 14 } // end class ReadTextFileTest Account First Name Bob Steve Pam Sam Sue Last Name Jones Doe White Stone Rich Balance

196 // Fig : ReadTextFile.java // This program reads a text file and displays each record. import java.io.file; import java.io.filenotfoundexception; import java.lang.illegalstateexception; import java.util.nosuchelementexception; import java.util.scanner; import com.deitel.jhtp7.ch14.accountrecord; public class ReadTextFile private Scanner input; // enable user to open file 16 public void openfile() try Open input = new Scanner( new File( "clients.txt" ) ); 21 } // end try 22 catch ( FileNotFoundException filenotfoundexception ) System.err.println( "Error opening file." ); file clients.txt for reading System.exit( 1 ); } // end catch } // end method openfile

197 29 // read record from file public void readrecords() // object to be written to screen AccountRecord record = new AccountRecord(); System.out.printf( "%-10s%-12s%-12s%10s\n", "Account", Create AccountRecord "First Name", "Last Name", "Balance" ); to store input from file try // read records from file using Scanner object while ( input.hasnext() ) While there is data to record.setaccount( input.nextint() ); // read account number record.setfirstname( input.next() ); // read first name be read from file record.setlastname( input.next() ); // read last name record.setbalance( input.nextdouble() ); // read balance // display record contents System.out.printf( "%-10d%-12s%-12s%10.2f\n", record.getaccount(), record.getfirstname(), record.getlastname(), record.getbalance() ); } // end while } // end try Read data from file, store in AccountRecord Display AccountRecord contents

198 53 catch ( NoSuchElementException elementexception ) System.err.println( "File improperly formed." ); input.close(); System.exit( 1 ); } // end catch catch ( IllegalStateException stateexception ) System.err.println( "Error reading from file." ); System.exit( 1 ); } // end catch } // end method readrecords // close file and terminate application public void closefile() 69 if ( input!= null ) 70 input.close(); // close file 71 } // end method closefile 72 } // end class ReadTextFile Close file

199 Case Study: A Credit-Inquiry Program 199 To retrieve data sequentially from a file, programs normally start reading from beginning of the file and read all the data consecutively until desired information is found Class Scanner provides no way to reposition to beginning of file Instead, file is closed and reopened

200 // Fig : MenuOption.java // Defines an enum type for the credit inquiry program's options. 200 public enum MenuOption // declare contents of enum type ZERO_BALANCE( 1 ), CREDIT_BALANCE( 2 ), DEBIT_BALANCE( 3 ), END( 4 ); private final int value; // current menu option MenuOption( int valueoption ) value = valueoption; } // end MenuOptions enum constructor public int getvalue() return value; } // end method getvalue } // end enum MenuOption

201 // Fig : CreditInquiry.java // This program reads a file sequentially and displays the // contents based on the type of account the user requests // (credit balance, debit balance or zero balance). import java.io.file; import java.io.filenotfoundexception; import java.lang.illegalstateexception; import java.util.nosuchelementexception; import java.util.scanner; 201 import com.deitel.jhtp7.ch14.accountrecord; public class CreditInquiry private MenuOption accounttype; private Scanner input; Scanner used to read data private MenuOption choices[] = MenuOption.ZERO_BALANCE, MenuOption.CREDIT_BALANCE, MenuOption.DEBIT_BALANCE, MenuOption.END }; from file // read records from file and display only records of appropriate type private void readrecords() AccountRecord stores record being read from file // object to be written to file AccountRecord record = new AccountRecord();

202 27 try // read records // open file to read from beginning input = new Scanner( new File( "clients.txt" ) ); Open file clients.txt for reading While there is data to read from file while ( input.hasnext() ) // input the values from the file record.setaccount( input.nextint() ); // read account number record.setfirstname( input.next() ); // read first name record.setlastname( input.next() ); // read last name record.setbalance( input.nextdouble() ); // read balance Check if record is of requested type Retrieve input, store data in AccountRecord // if proper acount type, display record if ( shoulddisplay( record.getbalance() ) ) System.out.printf( "%-10d%-12s%-12s%10.2f\n", record.getaccount(), record.getfirstname(), record.getlastname(), record.getbalance() ); } // end while } // end try catch ( NoSuchElementException elementexception ) Display record System.err.println( "File improperly formed." ); input.close(); Close Scanner System.exit( 1 ); } // end catch data to screen

203 catch ( IllegalStateException stateexception ) System.err.println( "Error reading from file." ); System.exit( 1 ); } // end catch catch ( FileNotFoundException filenotfoundexception ) System.err.println( "File cannot be found." ); System.exit( 1 ); } // end catch finally if ( input!= null ) input.close(); // close the Scanner and the file } // end finally } // end method readrecords // use record type to determine if record should be private boolean shoulddisplay( double balance ) if ( ( accounttype == MenuOption.CREDIT_BALANCE ) && ( balance < 0 ) ) Close file Method determines if record is of proper type displayed return true; else if ( ( accounttype == MenuOption.DEBIT_BALANCE ) && ( balance > 0 ) ) return true; 79

204 else if ( ( accounttype == MenuOption.ZERO_BALANCE ) && ( balance == 0 ) ) return true; 204 return false; } // end method shoulddisplay // obtain request from user private MenuOption getrequest() Scanner textin = new Scanner( System.in ); int request = 1; // display request options System.out.printf( "\n%s\n%s\n%s\n%s\n%s\n", "Enter request", " 1 - List accounts with zero balances", " 2 - List accounts with credit balances", " 3 - List accounts with debit balances", " 4 - End of run" ); try // attempt to input menu choice Loop until user enters valid request do // input user request System.out.print( "\n? " ); request = textin.nextint(); Retrieve request entered } while ( ( request < 1 ) ( request > 4 ) ); } // end try

205 catch ( NoSuchElementException elementexception ) System.err.println( "Invalid input." ); System.exit( 1 ); } // end catch return choices[ request - 1 ]; // return enum value for option } // end method getrequest public void processrequests() // get user's request (e.g., zero, credit or debit balance) 119 accounttype = getrequest(); while ( accounttype!= MenuOption.END ) switch ( accounttype ) case ZERO_BALANCE: System.out.println( "\naccounts with zero balances:\n" ); break;

206 128 case CREDIT_BALANCE: System.out.println( "\naccounts with credit balances:\n" ); 130 break; 131 case DEBIT_BALANCE: 132 System.out.println( "\naccounts with debit balances:\n" ); 133 break; 134 } // end switch Read file, display proper records readrecords(); 137 accounttype = getrequest(); } // end while } // end method processrequests 140 } // end class CreditInquiry

207 1 // Fig : CreditInquiryTest.java 2 // This program tests class CreditInquiry public class CreditInquiryTest 5 6 public static void main( String args[] ) 7 8 CreditInquiry application = new CreditInquiry(); 9 application.processrequests(); 10 } // end main 11 } // end class CreditInquiryTest

208 208 Enter request 1 - List accounts with zero balances 2 - List accounts with credit balances 3 - List accounts with debit balances 4 - End of run? 1 Accounts with zero balances: 300 Pam White 0.00 Enter request 1 - List accounts with zero balances 2 - List accounts with credit balances 3 - List accounts with debit balances 4 - End of run? 2 Accounts with credit balances: 200 Steve Doe 400 Sam Stone Enter request 1 - List accounts with zero balances 2 - List accounts with credit balances 3 - List accounts with debit balances 4 - End of run? 3 Accounts with debit balances: 100 Bob Jones 500 Sue Rich ? 4

209 Updating Sequential-Access Files Data in many sequential files cannot be modified without risk of destroying other data in file Old data cannot be overwritten if new data is not same size Records in sequential-access files are not usually updated in place. Instead, entire file is usually rewritten.

210 Object Serialization With text files, data type information lost Object serialization mechanism to read or write an entire object from a file Serialized object object represented as sequence of bytes, includes object s data and type information about object Deserialization recreate object in memory from data in file Serialization and deserialization performed with classes ObjectInputStream and ObjectOutputStream, methods readobject and writeobject

211 Creating a Sequential-Access File Using Object Serialization: Defining the AccountRecordSerializable Class 211 Serializable interface programmers must declare a class to implement the Serializable interface, or objects of that class cannot be written to a file To open a file for writing objects, create a FileOutputStream wrapped by an ObjectOutputStream FileOutputStream provides methods for writing byte-based output to a file ObjectOutputStream uses FileOutputStream to write objects to file ObjectOutputStream method writeobject writes object to output file ObjectOutputStream method close closes both objects

212 // Fig : AccountRecordSerializable.java // A class that represents one record of information. package com.deitel.jhtp7.ch14; // packaged for reuse import java.io.serializable; public class AccountRecordSerializable implements Serializable private int account; Interface Serializable specifies that private String firstname; AccountRecordSerializable private String lastname; objects can be written to file private double balance; // no-argument constructor calls other constructor with default values public AccountRecordSerializable() this( 0, "", "", 0.0 ); } // end no-argument AccountRecordSerializable constructor // four-argument constructor initializes a record public AccountRecordSerializable( int acct, String first, String last, double bal ) setaccount( acct ); setfirstname( first ); setlastname( last ); setbalance( bal ); } // end four-argument AccountRecordSerializable constructor

213 30 31 // set account number public void setaccount( int acct ) } // end method setaccount // get account number public int getaccount() } // end method getaccount // set first name public void setfirstname( String first ) firstname = first; } // end method setfirstname // get first name public String getfirstname() return firstname; } // end method getfirstname // set last name public void setlastname( String last ) lastname = last; } // end method setlastname 213 account = acct; return account;

214 60 // get last name 61 public String getlastname() return lastname; 64 } // end method getlastname // set balance 67 public void setbalance( double bal ) balance = bal; 70 } // end method setbalance // get balance 73 public double getbalance() return balance; 76 } // end method getbalance 77 } // end class AccountRecordSerializable 214

215 // Fig : CreateSequentialFile.java // Writing objects sequentially to a file with class ObjectOutputStream. Class used to create byte-based output stream import java.io.fileoutputstream; import java.io.ioexception; import java.io.objectoutputstream; Class used to create output object data to import java.util.nosuchelementexception; byte-based stream import java.util.scanner; 215 import com.deitel.jhtp7.ch14.accountrecordserializable; public class CreateSequentialFile private ObjectOutputStream output; // outputs data to file // allow user to specify file name public void openfile() try // open file output = new ObjectOutputStream( new FileOutputStream( "clients.ser" ) ); } // end try catch ( IOException ioexception ) System.err.println( "Error opening file." ); } // end catch } // end method openfile Open file clients.ser for writing

216 // add records to file public void addrecords() AccountRecordSerializable record; // object to be written to file int accountnumber = 0; // account number for record object String firstname; // first name for record object String lastname; // last name for record object double balance; // balance for record object 216 Scanner input = new Scanner( System.in ); System.out.printf( "%s\n%s\n%s\n%s\n\n", "To terminate input, type the end-of-file indicator ", "when you are prompted to enter input.", "On UNIX/Linux/Mac OS X type <ctrl> d then press Enter", "On Windows type <ctrl> z then press Enter" ); System.out.printf( "%s\n%s", "Enter account number (> 0), first name, last name and balance.", "? " ); while ( input.hasnext() ) // loop until end-of-file indicator try // output values to file accountnumber = input.nextint(); // read account number firstname = input.next(); // read first name lastname = input.next(); // read last name balance = input.nextdouble(); // read balance

217 59 60 if ( accountnumber > 0 ) // create new record record = new AccountRecordSerializable( accountnumber, Write record object firstname, lastname, balance ); output.writeobject( record ); // output record Create AccountRecord based on } // end if user input else System.out.println( "Account number must be greater than 0." ); } // end else } // end try catch ( IOException ioexception ) System.err.println( "Error writing to file." ); return; } // end catch catch ( NoSuchElementException elementexception ) System.err.println( "Invalid input. Please try again." ); input.nextline(); // discard input so user can try again } // end catch to file System.out.printf( "%s %s\n%s", "Enter account number (>0),", "first name, last name and balance.", "? " ); } // end while } // end method addrecords

218 88 // close file and terminate application 89 public void closefile() try // close file if ( output!= null ) 94 output.close(); 95 } // end try 96 catch ( IOException ioexception ) System.err.println( "Error closing file." ); 99 System.exit( 1 ); } // end catch } // end method closefile 102 } // end class CreateSequentialFile

219 1 // Fig : CreateSequentialFileTest.java // Testing class CreateSequentialFile. 219 public class CreateSequentialFileTest public static void main( String args[] ) CreateSequentialFile application = new CreateSequentialFile(); 10 application.openfile(); 11 application.addrecords(); 12 application.closefile(); 13 } // end main 14 } // end class CreateSequentialFileTest To terminate input, type the end-of-file indicator when you are prompted to enter input. On UNIX/Linux/Mac OS X type <ctrl> d then press Enter On Windows type <ctrl> z then press Enter Enter? 100 Enter? 200 Enter? 300 Enter? 400 Enter? 500 Enter? ^Z account number (> Bob Jones account number (> Steve Doe account number (> Pam White 0.00 account number (> Sam Stone account number (> Sue Rich account number (> 0), first name, last name and balance. 0), first name, last name and balance. 0), first name, last name and balance. 0), first name, last name and balance. 0), first name, last name and balance. 0), first name, last name and balance.

220 Reading and Deserializing Data from a Sequential-Access File 220 To open a file for reading objects, create a FileInputStream wrapped by an ObjectInputStream FileInputStream provides methods for reading bytebased input from a file ObjectInputStream uses FileInputStream to read objects from file ObjectInputStream method readobject reads in object, which is then downcast to proper type EOFException occurs if attempt made to read past end of file ClassNotFoundException occurs if the class for the object being read cannot be located ObjectInputStream method close closes both objects

221 // Fig : ReadSequentialFile.java // This program reads a file of objects sequentially // and displays each record. import java.io.eofexception; 5 import java.io.fileinputstream; import java.io.ioexception; import java.io.objectinputstream; 221 Class used to create byte-based input stream Class used to read input object data to bytebased stream import com.deitel.jhtp7.ch14.accountrecordserializable; public class ReadSequentialFile private ObjectInputStream input; // enable user to select file to open public void openfile() try // open file Open input = new ObjectInputStream( new FileInputStream( "clients.ser" ) ); } // end try catch ( IOException ioexception ) System.err.println( "Error opening file." ); } // end catch } // end method openfile file clients.ser for reading

222 29 30 // read record from file public void readrecords() AccountRecordSerializable record; System.out.printf( "%-10s%-12s%-12s%10s\n", "Account", "First Name", "Last Name", "Balance" ); try // input the values from the file while ( true ) Read record from file record = ( AccountRecordSerializable ) input.readobject(); // display record contents System.out.printf( "%-10d%-12s%-12s%10.2f\n", record.getaccount(), record.getfirstname(), record.getlastname(), record.getbalance() ); } // end while } // end try catch ( EOFException endoffileexception ) return; // end of file was reached } // end catch Output record information to screen

223 52 53 catch ( ClassNotFoundException classnotfoundexception ) System.err.println( "Unable to create object." ); } // end catch catch ( IOException ioexception ) System.err.println( "Error during read from file." ); } // end catch } // end method readrecords // close file and terminate application public void closefile() try // close file and exit if ( input!= null ) input.close(); } // end try 223 Close file 70 catch ( IOException ioexception ) System.err.println( "Error closing file." ); 73 System.exit( 1 ); 74 } // end catch 75 } // end method closefile 76 } // end class ReadSequentialFile

224 // Fig : ReadSequentialFileTest.java // This program test class ReadSequentialFile. 224 public class ReadSequentialFileTest public static void main( String args[] ) ReadSequentialFile application = new ReadSequentialFile(); application.openfile(); application.readrecords(); application.closefile(); } // end main } // end class ReadSequentialFileTest Account First Name Bob Steve Pam Sam Sue Last Name Jones Doe White Stone Rich Balance

225 Additional java.io Classes: Interfaces and Classes for Byte-Based Input and Output InputStream and OutputStream classes abstract classes that declare methods for performing byte-based input and output PipedInputStream and PipedOutputStream classes Establish pipes between two threads in a program Pipes are synchronized communication channels between threads FilterInputStream and FilterOutputStream classes Provides additional functionality to stream, such as aggregating data byte into meaningful primitive-type units PrintStream class Performs text output to a specified stream DataInput and DataOutput interfaces For reading and writing primitive types to a file DataInput implemented by classes RandomAccessFile and DataInputStream, DataOutput implemented by RandomAccessFile and DataOuputStream SequenceInputStream class enables concatenation of several InputStreams program sees group as one continuous InputStream

226 226 Interfaces and Classes for Byte-Based Input and Output Buffering is an I/O-performance-enhancement technique Greatly increases efficiency of an application Output (uses BufferedOutputStream class) Each output statement does not necessarily result in an actual physical transfer of data to the output device data is directed to a region of memory called a buffer (faster than writing to file) When buffer is full, actual transfer to output device is performed in one large physical output operation (also called logical output operations) Partially filled buffer can be forced out with method flush Input (uses BufferedInputStream class) Many logical chunks of data from a file are read as one physical input operation (also called logical input operation) When buffer is empty, next physical input operation is performed ByteArrayInputStream and ByteArrayOutputStream classes used for inputting from byte arrays in memory and outputting to byte arrays in memory

227 Interfaces and Classes for CharacterBased Input and Output 227 Reader and Writer abstract classes Unicode two-byte, character-based streams BufferedReader and BufferedWriter classes Enable buffering for character-based streams CharArrayReader and CharArrayWriter classes Read and write streams of characters to character arrays LineNumberReader class Buffered character stream that keeps track of number of lines read PipedReader and PipedWriter classes Implement piped-character streams that can be used to transfer information between threads StringReader and StringWriter classes Read characters from and write characters to Strings

228 Opening Files with JFileChooser JFileChooser class used to display a dialog that enables users to easily select files Method setfileselectionmode specifies what user can select from JFileChooser FILES_AND_DIRECTORIES constant indicates files and directories FILES_ONLY constant indicates files only DIRECTORIES_ONLY constant indicates directories only Method showopendialog displays JFileChooser dialog titled Open, with Open and Cancel buttons (to open a file/directory or dismiss the dialog, respectively) CANCEL_OPTION constant specifies that user click Cancel button Method getselectedfile retrieves file or directory user selected

229 // Fig : FileDemonstration.java // Demonstrating the File class. import java.awt.borderlayout; import java.awt.event.actionevent; import java.awt.event.actionlistener; import java.io.file; import javax.swing.jfilechooser; import javax.swing.jframe; import javax.swing.joptionpane; import javax.swing.jscrollpane; import javax.swing.jtextarea; import javax.swing.jtextfield; 229 Class for display JFileChooser dialog public class FileDemonstration extends JFrame private JTextArea outputarea; // used for output 17 private JScrollPane scrollpane; // used to provide scrolling to output // set up GUI 20 public FileDemonstration() super( "Testing class File" ); outputarea = new JTextArea(); // add outputarea to scrollpane 27 scrollpane = new JScrollPane( outputarea ); add( scrollpane, BorderLayout.CENTER ); // add scrollpane to GUI 30

230 31 setsize( 400, 400 ); // set GUI size setvisible( true ); // display GUI analyzepath(); // create and analyze File object } // end FileDemonstration constructor // allow user to specify file name private File getfile() // display file dialog, so user can choose file to open 41 JFileChooser filechooser = new JFileChooser(); filechooser.setfileselectionmode( JFileChooser.FILES_AND_DIRECTORIES ); int result = filechooser.showopendialog( this ); // if user clicked Cancel button on dialog, return if ( result == JFileChooser.CANCEL_OPTION ) Create JFileChooser Allow user to select both files and directories Display dialog User clicked Cancel System.exit( 1 ); Retrieve file or directory selected selected file by user File filename = filechooser.getselectedfile(); // get // display error if invalid if ( ( filename == null ) ( filename.getname().equals( "" ) ) ) JOptionPane.showMessageDialog( this, "Invalid File Name", "Invalid File Name", JOptionPane.ERROR_MESSAGE ); System.exit( 1 ); } // end if

231 61 62 return filename; 231 } // end method getfile // display information about file user specifies 65 public void analyzepath() // create File object based on user input 68 File name = getfile(); 69 Display information about file 70 if ( name.exists() ) // if name exists, output information about it // display file (or directory) information 73 outputarea.settext( String.format( 74 "%s%s\n%s\n%s\n%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s", 75 name.getname(), " exists", 76 ( name.isfile()? "is a file" : "is not a file" ), 77 ( name.isdirectory()? "is a directory" : "is not a directory" ), ( name.isabsolute()? "is absolute path" : 80 "is not absolute path" ), "Last modified: ", 81 name.lastmodified(), "Length: ", name.length(), 82 "Path: ", name.getpath(), "Absolute path: ", 83 name.getabsolutepath(), "Parent: ", name.getparent() ) ); 84

232 85 if ( name.isdirectory() ) // output directory listing String directory[] = name.list(); 88 outputarea.append( "\n\ndirectory contents:\n" ); for ( String directoryname : directory ) 91 outputarea.append( directoryname + "\n" ); 92 } // end else 93 } // end outer if 94 else // not file or directory, output error message JOptionPane.showMessageDialog( this, name + " does not exist.", "ERROR", JOptionPane.ERROR_MESSAGE ); } // end else } // end method analyzepath 100 } // end class FileDemonstration

233 // Fig : FileDemonstrationTest.java // Testing the FileDmonstration class. import javax.swing.jframe; 233 public class FileDemonstrationTest public static void main( String args[] ) FileDemonstration application = new FileDemonstration(); application.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); } // end main } // end class FileDemonstrationTest Select location for file here Click Open to submit new file name to program Files and directories are displayed here

234 234

235 Introduction to Java Applets

236 236 WE WILL COVER To differentiate between applets and applications. To observe some of Java's exciting capabilities through the JDK's demonstration applets. To write simple applets. To write a simple HyperText Markup Language (HTML) document to load an applet into an applet container and execute the applet. Five methods that are called automatically by an applet container during an applet's life cycle.

237 Introduction 20.2 Sample Applets Provided with the JDK 20.3 Simple Java Applet: Drawing a String Executing an Applet in the appletviewer Executing an Applet in a Web Browser 20.4 Applet Life-Cycle Methods 20.5 Initializing an Instance Variable with Method init 20.6 Sandbox Security Model 20.7 Internet and Web Resources 20.8 Wrap-Up

238 Introduction Applets Java programs that can be embedded in HyperText Markup Language (HTML) documents The browser that executes an applet is generically known as the applet container

239 20.2 Sample Applets Provided with the JDK 239 Demonstration applets provided with the JDK Demonstration programs are located in directory demo Default location in Windows: C:\Program Files\Java\jdk1.5.0\demo Default location in UNIX/Linux/Mac OS X: the directory in which you install the JDK followed by jdk1.5.0/demo JDK and the demos can be downloaded from the Sun Microsystems Java Web site java.sun.com/j2se/5.0/ Live at

240 240 Example Description Animator Performs one of four separate animations. Demonstrates drawing arcs. You can interact with the applet to change attributes of the arc that is displayed. Draws a simple bar chart. Displays blinking text in different colors. Demonstrates several GUI components and layouts. Draws a clock with rotating hands, the current date and the current time. The clock updates once per second. Demonstrates drawing with a graphics technique known as dithering that allows gradual transformation from one color to another. Allows the user mouse to draw lines and points in different colors by dragging the mouse. Draws a fractal. Fractals typically require complex calculations to determine how they are displayed. Draws shapes to illustrate graphics capabilities. ArcTest BarChart Blink CardTest Clock DitherTest DrawTest Fractal GraphicsTest Fig The examples from the applets directory. (Part 1 of 3.)

241 241 Example Description GraphLayout Draws a graph consisting of many nodes (represented as rectangles) connected by lines. Drag a node to see the other nodes in the graph adjust on the screen and demonstrate complex graphical interactions. Demonstrates an image with hot spots. Positioning the mouse pointer over certain areas of the image highlights the area and displays a message in the lower-left corner of the applet container window. Position over the mouth in the image to hear the applet say hi. ImageMap JumpingBox Moves a rectangle randomly around the screen. Try to catch it by clicking it with the mouse! Fig The examples from the applets directory. (Part 2 of 3.)

242 242 Example Description MoleculeViewer Presents a three-dimensional view of several chemical molecules. Drag the mouse to view the molecule from different angles. NervousText Draws text that jumps around the applet. SimpleGraph Draws a complex curve. SortDemo Compares three sorting techniques. Sorting (described in Chapter 16) arranges information in order like alphabetizing words. When you execute this example from a command window, three appletviewer windows appear. When you execute this example in a browser, the three demos appear side-by-side. Click in each demo to start the sort. Note that the sorts all operate at different speeds. SpreadSheet Demonstrates a simple spreadsheet of rows and columns. TicTacToe Allows the user to play Tic-Tac-Toe against the computer. WireFrame Draws a three-dimensional shape as a wire frame. Drag the mouse to view the shape from different angles. Fig The examples from the applets directory. (Part 3 of 3.)

243 20.2 Sample Applets Provided with the JDK (Cont.) 243 TicTacToe applet Allows you to play Tic-Tac-Toe against the computer Run the applet with the appletviewer command Change directories to subdirectory TicTacToe Type command appletviewer example1.html Point the mouse at the square where you want to place an X To play again Click the Applet menu Select the Reload menu item To terminate the appletviewer Click the Applet menu Select the Quit menu item

244 244 Fig TicTacToe applet sample execution.

245 245 Reload the applet to execute it again. Select Quit to terminate the appletviewer. Fig Applet menu in the appletviewer.

246 20.2 Sample Applets Provided with the JDK (Cont.) 246 DrawTest applet Allows you to draw lines and points in different colors Run the applet with the appletviewer command Change directories to subdirectory drawtest Type command appletviewer example1.html Drag the mouse across the applet to draw lines Select a color by clicking one of the radio buttons at the bottom of the applet Select from red, green, blue, pink, orange and black Change the shape to draw from Lines to Points by selecting Points from the combo box Select Reload from the Applet menu to start a new drawing

247 247 Drag the mouse in the white area to draw. Select Lines or Points from the combo box to specify what will be drawn when you drag the mouse. Select the drawing color by clicking one of the radio buttons. Fig DrawTest applet sample execution.

248 20.2 Sample Applets Provided with the JDK (Cont.) 248 Java2D applet Demonstrates many features of the Java 2D API Run the applet with the appletviewer command Change directories to the jfc directory in the JDK s demo directory, then change to the Java2D directory Type command appletviewer Java2Demo.html To change to a different part of the demo, click a different tab at the top of the applet Change the options in the upper-right corner Example: click the checkbox to the left of the word AntiAliasing A graphical technique for producing smoother graphics in which edges of the graphic are blurred

249 249 Click a tab to select a two-dimensional graphics demo. Try changing the options to see their effect on the demonstration. Fig Java2D applet sample execution.

250 20.3 Simple Java Applet: Drawing a String 250 Creating the applet class An applet container can create only objects of classes that are public and extend JApplet An applet container expects every Java applet class to have methods named init, start, paint, stop and destroy These methods are inherited from class JApplet and can be overridden When an applet container loads an applet class, the container creates an object of the class then calls methods init, start and paint

251 1 2 // Fig. 20.6: WelcomeApplet.java // A first applet in Java import java.awt.graphics; // program uses class Graphics import javax.swing.japplet; // program uses class JApplet public class WelcomeApplet extends JApplet // draw text on applet s background public void paint( Graphics g ) // call superclass version of method paint 12 super.paint( g ); // draw a String at x-coordinate 25 and y-coordinate g.drawstring( "Welcome to Java Programming!", 25, 25 ); 16 } // end method paint 17 } // end class WelcomeApplet Import Graphics and JApplet Class WelcomeApplet extends class JApplet Call the superclass version of method paint Use Graphics method drawstring to draw Welcome to Java Programming!

252 252 WelcomeApplet executing in the appletviewer x-axis y-axis Upper-left corner of drawing area is location (0, 0). Drawing area extends from below the Applet menu to above the status bar. xcoordinates increase from left to right. y-coordinates increase from top to bottom. Applet menu Status bar mimics what would be displayed in the browser s status bar as the applet loads and begins executing. Pixel coordinates (25, 25) at which the string is displayed WelcomeApplet executing in Microsoft Internet Explorer Upper-left corner of drawing area Pixel coordinate (25, 25) Status bar Fig Sample outputs of the WelcomeApplet in Fig

253 20.3 Simple Java Applet: Drawing a String (Cont.) 253 Overriding method paint for drawing The applet container calls method paint with a Graphics object as an argument to tell the applet when to draw

254 Executing an Applet in the appletviewer 254 Applets are embedded in Web pages for execution in an applet container Before executing the applet, you must create an HTML document that specifies which applet to execute HTML documents typically end with an.html or.htm file-name extension Most HTML elements are delimited by pairs of tags All HTML tags begin with a left angle bracket, <, and end with a right angle bracket, > Execute WelcomeApplet in the appletviewer In the directory containing your applet and HTML document, type appletviewer WelcomeApplet.html The appletviewer understands only the <applet> and </applet> HTML tags and ignores all other tags

255 1 <html> 2 <applet code = "WelcomeApplet.class" width = "300" height = "45"> 3 </applet> 4 </html> 255 Applet element attributes Specify an applet element Fig WelcomeApplet.html loads WelcomeApplet (Fig. 20.6) into an applet container.

256 256 Error-Prevention Tip 20.2 Test your applets in the appletviewer applet container before executing them in a Web browser. Browsers often save a copy of an applet in memory until all the browser s windows are closed. If you change an applet, recompile it, then reload it in your browser, the browser may still execute the original version of the applet. Close all your browser windows to remove the old applet from memory. Open a new browser window and load the applet to see your changes.

257 Executing an Applet in a Web Browser 257 To execute an applet in Internet Explorer: Select Open from the File menu Click the Browse button Locate the directory containing the HTML document for the applet you wish to execute Select the HTML document Click the Open button Click the OK button

258 Executing an Applet in a Web Browser (Cont.) 258 If your applet executes in the appletviewer but not in your Web browser Java may not be installed and configured for your browser Visit the Web site java.com and click the Get It Now button to install Java for your browser You may need to manually configure Internet Explorer to use J2SE 5.0 Click the Tools menu Select Internet Options Click the Advanced tab Check the Use JRE v1.5.0 for <applet> (requires restart) option Click OK Close all browser windows before attempting to execute another applet in the browser

259 259 Method When the method is called and its purpose public void init() Called once by the applet container when an applet is loaded for execution. This method initializes an applet. Typical actions performed here are initializing fields, creating GUI components, loading sounds to play, loading images to display (see Chapter 20, Multimedia: Applets and Applications) and creating threads (see Chapter 23, Multithreading). public void start() Called by the applet container after method init completes execution. In addition, if the user browses to another Web site and later returns to the applet s HTML page, method start is called again. The method performs any tasks that must be completed when the applet is loaded for the first time and that must be performed every time the applet s HTML page is revisited. Actions performed here might include starting an animation (see Chapter 21) or starting other threads of execution (see Chapter 23). Fig JApplet life cycle methods that are called by an applet container during an applet s execution. (Part 1 of 3.)

260 260 Method When the method is called and its purpose public void paint( Graphics g ) Called by the applet container after methods init and start. Method paint is also called when the applet needs to be repainted. For example, if the user covers the applet with another open window on the screen and later uncovers the applet, the paint method is called. Typical actions performed here involve drawing with the Graphics object g that is passed to the paint method by the applet container. public void stop() This method is called by the applet container when the user leaves the applet s Web page by browsing to another Web page. Since it is possible that the user might return to the Web page containing the applet, method stop performs tasks that might be required to suspend the applet s execution, so that the applet does not use computer processing time when it is not displayed on the screen. Typical actions performed here would stop the execution of animations and threads. Fig JApplet life cycle methods that are called by an applet container during an applet s execution. (Part 2 of 3.)

261 261 Method When the method is called and its purpose public void destroy() This method is called by the applet container when the applet is being removed from memory. This occurs when the user exits the browsing session by closing all the browser windows and may also occur at the browser s discretion when the user has browsed to other Web pages. The method performs any tasks that are required to clean up resources allocated to the applet. Fig JApplet life cycle methods that are called by an applet container during an applet s execution. (Part 3 of 3.)

262 20.5 Initializing an Instance Variable with Method init 262 Applet AdditionApplet computes the sum of two values input by the user and displays the result by drawing a String inside a rectangle on the applet The sum is stored in an instance variable of class AdditionApplet So it can be used in both method init and method paint

263 // Fig : AdditionApplet.java // Adding two floating-point numbers. import java.awt.graphics; // program uses class Graphics import javax.swing.japplet; // program uses class JApplet import javax.swing.joptionpane; // program uses class JOptionPane 263 Declare instance variable sum of type double public class AdditionApplet extends JApplet private double sum; // sum of values entered by user // initialize applet by obtaining values from user public void init() String firstnumber; // first string entered by user String secondnumber; // second string entered by user init method called once when the container loads this applet double number1; // first number to add double number2; // second number to add // obtain first number from user firstnumber = JOptionPane.showInputDialog( "Enter first floating-point value" ); // obtain second number from user secondnumber = JOptionPane.showInputDialog( "Enter second floating-point value" );

264 28 // convert numbers from type String to type double 29 number1 = Double.parseDouble( firstnumber ); 30 number2 = Double.parseDouble( secondnumber ); 31 Sum the values and assign the 32 sum = number1 + number2; // add numbers result to instance variable sum 33 } // end method init // draw results in a rectangle on applet s background 36 public void paint( Graphics g ) super.paint( g ); // call superclass version of method paint // draw rectangle starting from (15, 10) that is // pixels wide and 20 pixels tall 42 g.drawrect( 15, 10, 270, 20 ); // draw results as a String at (25, 25) 45 g.drawstring( "The sum is " + sum, 25, 25 ); 46 } // end method paint 47 } // end class AdditionApplet Call drawstring to 264 display sum

265 265

GUI Components: Part Pearson Education, Inc. All rights reserved.

GUI Components: Part Pearson Education, Inc. All rights reserved. 1 11 GUI Components: Part 1 2 11.1 Introduction Graphical user interface (GUI) Presents a user-friendly mechanism for interacting with an application Often contains title bar, menu bar containing menus,

More information

User Interface components with swing

User Interface components with swing User Interface components with swing A graphical user interface (GUI) presents a user-friendly mechanism for interacting with an application. A GUI (pronounced GOO-ee ) gives an application a distinctive

More information

14.2 Java s New Nimbus Look-and-Feel 551 Sample GUI: The SwingSet3 Demo Application As an example of a GUI, consider Fig. 14.1, which shows the SwingS

14.2 Java s New Nimbus Look-and-Feel 551 Sample GUI: The SwingSet3 Demo Application As an example of a GUI, consider Fig. 14.1, which shows the SwingS 550 Chapter 14 GUI Components: Part 1 14.1 Introduction 14.2 Java s New Nimbus Look-and-Feel 14.3 Simple GUI-Based Input/Output with JOptionPane 14.4 Overview of Swing Components 14.5 Displaying Text and

More information

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7 PROGRAMMING DESIGN USING JAVA (ITT 303) Graphical User Interface Unit 7 Learning Objectives At the end of this unit students should be able to: Build graphical user interfaces Create and manipulate buttons,

More information

Dr. Hikmat A. M. AbdelJaber

Dr. Hikmat A. M. AbdelJaber Dr. Hikmat A. M. AbdelJaber GUI are event driven (i.e. when user interacts with a GUI component, the interaction (event) derives the program to perform a task). Event: click button, type in text field,

More information

Chapter 13 - Graphical User Interface Components: Part 1

Chapter 13 - Graphical User Interface Components: Part 1 Chapter 13 - Graphical User Interface Components: Part 1 13.1 Introduction 13.2 Overview of Swing Components 13.3 JLabel 13.4 Event Handling 13.5 TextFields 13.6 How Event Handling Works 13.7 JButton 13.8

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 10(b): Working with Controls Agenda 2 Case study: TextFields and Labels Combo Boxes buttons List manipulation Radio buttons and checkboxes

More information

GUI Components: Part 1

GUI Components: Part 1 1 2 11 GUI Components: Part 1 Do you think I can listen all day to such stuff? Lewis Carroll Even a minor event in the life of a child is an event of that child s world and thus a world event. Gaston Bachelard

More information

Programação Orientada a Objetos

Programação Orientada a Objetos Planejamento Programação Orientada a Objetos Prof. pauloac@ita.br www.comp.ita.br/~pauloac ITA Stefanini Aula 1 Introdução Conceitos Básicos Classe, Objeto, Método,Herança, interfaces, polimorfismo, Encapsulamento

More information

12/22/11. Copyright by Pearson Education, Inc. All Rights Reserved.

12/22/11. Copyright by Pearson Education, Inc. All Rights Reserved. } Radio buttons (declared with class JRadioButton) are similar to checkboxes in that they have two states selected and not selected (also called deselected). } Radio buttons normally appear as a group

More information

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Starting Out with Java: From Control Structures Through Objects Sixth Edition Starting Out with Java: From Control Structures Through Objects Sixth Edition Chapter 12 A First Look at GUI Applications Chapter Topics 12.1 Introduction 12.2 Creating Windows 12.3 Equipping GUI Classes

More information

PIC 20A GUI with swing

PIC 20A GUI with swing PIC 20A GUI with swing Ernest Ryu UCLA Mathematics Last edited: November 22, 2017 Hello swing Let s create a JFrame. import javax. swing.*; public class Test { public static void main ( String [] args

More information

Summary. Section 14.1 Introduction. Section 14.2 Java s New Nimbus Look-and-Feel. 618 Chapter 14 GUI Components: Part 1

Summary. Section 14.1 Introduction. Section 14.2 Java s New Nimbus Look-and-Feel. 618 Chapter 14 GUI Components: Part 1 618 Chapter 14 GUI Components: Part 1 erence to a JScrollPane, the program can use JScrollPane methods sethorizontal- ScrollBarPolicy and setverticalscrollbarpolicy to change the scrollbar policies at

More information

SD Module-1 Advanced JAVA

SD Module-1 Advanced JAVA Assignment No. 4 SD Module-1 Advanced JAVA R C (4) V T Total (10) Dated Sign Title: Transform the above system from command line system to GUI based application Problem Definition: Write a Java program

More information

SD Module-1 Advanced JAVA. Assignment No. 4

SD Module-1 Advanced JAVA. Assignment No. 4 SD Module-1 Advanced JAVA Assignment No. 4 Title :- Transform the above system from command line system to GUI based application Problem Definition: Write a Java program with the help of GUI based Application

More information

Programação Orientada a Objetos. Herança e Interfaces com Graphic User Interfaces

Programação Orientada a Objetos. Herança e Interfaces com Graphic User Interfaces Programação Orientada a Objetos Herança e Interfaces com Graphic User Interfaces Sumário Introdução Interfaces e Herança Tratamento de Eventos com Interfaces Classes Adapter Tratamento de Eventos de Tecla

More information

Goals. Lecture 7 More GUI programming. The application. The application D&D 12. CompSci 230: Semester JFrame subclass: ListOWords

Goals. Lecture 7 More GUI programming. The application. The application D&D 12. CompSci 230: Semester JFrame subclass: ListOWords Goals By the end of this lesson, you should: Lecture 7 More GUI programming 1. Be able to write Java s with JTextField, JList, JCheckBox and JRadioButton components 2. Be able to implement a ButtonGroup

More information

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics Topic 9: Swing Outline Swing = Java's GUI library Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Assignment 7: Expand moving shapes from Assignment 4 into game. "Programming

More information

Packages: Putting Classes Together

Packages: Putting Classes Together Packages: Putting Classes Together 1 Introduction 2 The main feature of OOP is its ability to support the reuse of code: Extending the classes (via inheritance) Extending interfaces The features in basic

More information

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Swing = Java's GUI library Topic 9: Swing Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Assignment 5: Will be an open-ended Swing project. "Programming Contest"

More information

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun! Swing = Java's GUI library Topic 9: Swing Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Why are we studying Swing? 1. Useful & fun! 2. Good application of OOP techniques

More information

Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing

Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing Rui Moreira Some useful links: http://java.sun.com/docs/books/tutorial/uiswing/toc.html http://www.unix.org.ua/orelly/java-ent/jfc/

More information

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

Graphics. Lecture 18 COP 3252 Summer June 6, 2017 Graphics Lecture 18 COP 3252 Summer 2017 June 6, 2017 Graphics classes In the original version of Java, graphics components were in the AWT library (Abstract Windows Toolkit) Was okay for developing simple

More information

Chapter 12 GUI Basics

Chapter 12 GUI Basics Chapter 12 GUI Basics 1 Creating GUI Objects // Create a button with text OK JButton jbtok = new JButton("OK"); // Create a label with text "Enter your name: " JLabel jlblname = new JLabel("Enter your

More information

Class 16: The Swing Event Model

Class 16: The Swing Event Model Introduction to Computation and Problem Solving Class 16: The Swing Event Model Prof. Steven R. Lerman and Dr. V. Judson Harward 1 The Java Event Model Up until now, we have focused on GUI's to present

More information

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User CSE3461 Control Flow Paradigms: Reacting to the User Control Flow: Overview Definition of control flow: The sequence of execution of instructions in a program. Control flow is determined at run time by

More information

Handout 14 Graphical User Interface (GUI) with Swing, Event Handling

Handout 14 Graphical User Interface (GUI) with Swing, Event Handling Handout 12 CS603 Object-Oriented Programming Fall 15 Page 1 of 12 Handout 14 Graphical User Interface (GUI) with Swing, Event Handling The Swing library (javax.swing.*) Contains classes that implement

More information

Adding Buttons to StyleOptions.java

Adding Buttons to StyleOptions.java Adding Buttons to StyleOptions.java The files StyleOptions.java and StyleOptionsPanel.java are from Listings 5.14 and 5.15 of the text (with a couple of slight changes an instance variable fontsize is

More information

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT CSE 143 Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia http://www.cs.washington.edu/331/

More information

Course Status Networking GUI Wrap-up. CS Java. Introduction to Java. Andy Mroczkowski

Course Status Networking GUI Wrap-up. CS Java. Introduction to Java. Andy Mroczkowski CS 190 - Java Introduction to Java Andy Mroczkowski uamroczk@cs.drexel.edu Department of Computer Science Drexel University March 10, 2008 / Lecture 8 Outline Course Status Course Information & Schedule

More information

Chapter 6: Graphical User Interfaces

Chapter 6: Graphical User Interfaces Chapter 6: Graphical User Interfaces CS 121 Department of Computer Science College of Engineering Boise State University April 21, 2015 Chapter 6: Graphical User Interfaces CS 121 1 / 36 Chapter 6 Topics

More information

Java Programming Lecture 6

Java Programming Lecture 6 Java Programming Lecture 6 Alice E. Fischer Feb 15, 2013 Java Programming - L6... 1/32 Dialog Boxes Class Derivation The First Swing Programs: Snow and Moving The Second Swing Program: Smile Swing Components

More information

Example: Building a Java GUI

Example: Building a Java GUI Steven Zeil October 25, 2013 Contents 1 Develop the Model 3 2 Develop the layout of those elements 4 3 Add listeners to the elements 12 4 Implement custom drawing 15 1 The StringArt Program To illustrate

More information

Datenbank-Praktikum. Universität zu Lübeck Sommersemester 2006 Lecture: Swing. Ho Ngoc Duc 1

Datenbank-Praktikum. Universität zu Lübeck Sommersemester 2006 Lecture: Swing. Ho Ngoc Duc 1 Datenbank-Praktikum Universität zu Lübeck Sommersemester 2006 Lecture: Swing Ho Ngoc Duc 1 Learning objectives GUI applications Font, Color, Image Running Applets as applications Swing Components q q Text

More information

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling Frames, GUI and events Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling Introduction to Swing The Java AWT (Abstract Window Toolkit)

More information

Graphical User Interfaces in Java - SWING

Graphical User Interfaces in Java - SWING Graphical User Interfaces in Java - SWING Graphical User Interfaces (GUI) Each graphical component that the user can see on the screen corresponds to an object of a class Component: Window Button Menu...

More information

Introduction to the JAVA UI classes Advanced HCI IAT351

Introduction to the JAVA UI classes Advanced HCI IAT351 Introduction to the JAVA UI classes Advanced HCI IAT351 Week 3 Lecture 1 17.09.2012 Lyn Bartram lyn@sfu.ca About JFC and Swing JFC Java TM Foundation Classes Encompass a group of features for constructing

More information

Unit 7: Event driven programming

Unit 7: Event driven programming Faculty of Computer Science Programming Language 2 Object oriented design using JAVA Dr. Ayman Ezzat Email: ayman@fcih.net Web: www.fcih.net/ayman Unit 7: Event driven programming 1 1. Introduction 2.

More information

AP CS Unit 11: Graphics and Events

AP CS Unit 11: Graphics and Events AP CS Unit 11: Graphics and Events This packet shows how to create programs with a graphical interface in a way that is consistent with the approach used in the Elevens program. Copy the following two

More information

COSC 123 Computer Creativity. Graphics and Events. Dr. Ramon Lawrence University of British Columbia Okanagan

COSC 123 Computer Creativity. Graphics and Events. Dr. Ramon Lawrence University of British Columbia Okanagan COSC 123 Computer Creativity Graphics and Events Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Key Points 1) Draw shapes, text in various fonts, and colors. 2) Build

More information

Java GUI Design: the Basics

Java GUI Design: the Basics Java GUI Design: the Basics Daniel Brady July 25, 2014 What is a GUI? A GUI is a graphical user interface, of course. What is a graphical user interface? A graphical user interface is simply a visual way

More information

GUI Event Handlers (Part I)

GUI Event Handlers (Part I) GUI Event Handlers (Part I) 188230 Advanced Computer Programming Asst. Prof. Dr. Kanda Runapongsa Saikaew (krunapon@kku.ac.th) Department of Computer Engineering Khon Kaen University 1 Agenda General event

More information

Example: Building a Java GUI

Example: Building a Java GUI Steven Zeil October 25, 2013 Contents 1 Develop the Model 2 2 Develop the layout of those elements 3 3 Add listeners to the elements 9 4 Implement custom drawing 12 1 The StringArt Program To illustrate

More information

The AWT Event Model 9

The AWT Event Model 9 The AWT Event Model 9 Course Map This module covers the event-based GUI user input mechanism. Getting Started The Java Programming Language Basics Identifiers, Keywords, and Types Expressions and Flow

More information

Programming graphics

Programming graphics Programming graphics Need a window javax.swing.jframe Several essential steps to use (necessary plumbing ): Set the size width and height in pixels Set a title (optional), and a close operation Make it

More information

Graphical Applications

Graphical Applications Graphical Applications The example programs we've explored thus far have been text-based They are called command-line applications, which interact with the user using simple text prompts Let's examine

More information

Part I: Learn Common Graphics Components

Part I: Learn Common Graphics Components OOP GUI Components and Event Handling Page 1 Objectives 1. Practice creating and using graphical components. 2. Practice adding Event Listeners to handle the events and do something. 3. Learn how to connect

More information

Chapter 7: A First Look at GUI Applications

Chapter 7: A First Look at GUI Applications Chapter 7: A First Look at GUI Applications Starting Out with Java: From Control Structures through Objects Fourth Edition by Tony Gaddis Addison Wesley is an imprint of 2010 Pearson Addison-Wesley. All

More information

Window Interfaces Using Swing Objects

Window Interfaces Using Swing Objects Chapter 12 Window Interfaces Using Swing Objects Event-Driven Programming and GUIs Swing Basics and a Simple Demo Program Layout Managers Buttons and Action Listeners Container Classes Text I/O for GUIs

More information

Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science

Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science mluckner@mini.pw.edu.pl http://www.mini.pw.edu.pl/~lucknerm } Abstract Window Toolkit Delegates creation and

More information

To gain experience using GUI components and listeners.

To gain experience using GUI components and listeners. Lab 5 Handout 7 CSCI 134: Fall, 2017 TextPlay Objective To gain experience using GUI components and listeners. Note 1: You may work with a partner on this lab. If you do, turn in only one lab with both

More information

Graphical User Interface (GUI) components in Java Applets. With Abstract Window Toolkit (AWT) we can build an applet that has the basic GUI

Graphical User Interface (GUI) components in Java Applets. With Abstract Window Toolkit (AWT) we can build an applet that has the basic GUI CBOP3203 Graphical User Interface (GUI) components in Java Applets. With Abstract Window Toolkit (AWT) we can build an applet that has the basic GUI components like button, text input, scroll bar and others.

More information

Contents Chapter 1 Introduction to Programming and the Java Language

Contents Chapter 1 Introduction to Programming and the Java Language Chapter 1 Introduction to Programming and the Java Language 1.1 Basic Computer Concepts 5 1.1.1 Hardware 5 1.1.2 Operating Systems 8 1.1.3 Application Software 9 1.1.4 Computer Networks and the Internet

More information

BASICS OF GRAPHICAL APPS

BASICS OF GRAPHICAL APPS CSC 2014 Java Bootcamp Lecture 7 GUI Design BASICS OF GRAPHICAL APPS 2 Graphical Applications So far we ve focused on command-line applications, which interact with the user using simple text prompts In

More information

Lecture 5: Java Graphics

Lecture 5: Java Graphics Lecture 5: Java Graphics CS 62 Spring 2019 William Devanny & Alexandra Papoutsaki 1 New Unit Overview Graphical User Interfaces (GUI) Components, e.g., JButton, JTextField, JSlider, JChooser, Containers,

More information

Module 5 The Applet Class, Swings. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Module 5 The Applet Class, Swings. OOC 4 th Sem, B Div Prof. Mouna M. Naravani Module 5 The Applet Class, Swings OOC 4 th Sem, B Div 2016-17 Prof. Mouna M. Naravani The layout manager helps lay out the components held by this container. When you set a layout to null, you tell the

More information

Java & Graphical User Interface II. Wang Yang wyang AT njnet.edu.cn

Java & Graphical User Interface II. Wang Yang wyang AT njnet.edu.cn Java & Graphical User Interface II Wang Yang wyang AT njnet.edu.cn Outline Review of GUI (first part) What is Event Basic Elements of Event Programming Secret Weapon - Inner Class Full version of Event

More information

11/7/12. Discussion of Roulette Assignment. Objectives. Compiler s Names of Classes. GUI Review. Window Events

11/7/12. Discussion of Roulette Assignment. Objectives. Compiler s Names of Classes. GUI Review. Window Events Objectives Event Handling Animation Discussion of Roulette Assignment How easy/difficult to refactor for extensibility? Was it easier to add to your refactored code? Ø What would your refactored classes

More information

Chapter 12 Advanced GUIs and Graphics

Chapter 12 Advanced GUIs and Graphics Chapter 12 Advanced GUIs and Graphics Chapter Objectives Learn about applets Explore the class Graphics Learn about the classfont Explore the classcolor Java Programming: From Problem Analysis to Program

More information

CS 251 Intermediate Programming GUIs: Event Listeners

CS 251 Intermediate Programming GUIs: Event Listeners CS 251 Intermediate Programming GUIs: Event Listeners Brooke Chenoweth University of New Mexico Fall 2017 What is an Event Listener? A small class that implements a particular listener interface. Listener

More information

Class 14: Introduction to the Swing Toolkit

Class 14: Introduction to the Swing Toolkit Introduction to Computation and Problem Solving Class 14: Introduction to the Swing Toolkit Prof. Steven R. Lerman and Dr. V. Judson Harward 1 Class Preview Over the next 5 lectures, we will introduce

More information

1.00 Lecture 14. Lecture Preview

1.00 Lecture 14. Lecture Preview 1.00 Lecture 14 Introduction to the Swing Toolkit Lecture Preview Over the next 5 lectures, we will introduce you to the techniques necessary to build graphic user interfaces for your applications. Lecture

More information

Swing. By Iqtidar Ali

Swing. By Iqtidar Ali Swing By Iqtidar Ali Background of Swing We have been looking at AWT (Abstract Window ToolKit) components up till now. Programmers were not comfortable when doing programming with AWT. Bcoz AWT is limited

More information

Graphical User Interfaces. Comp 152

Graphical User Interfaces. Comp 152 Graphical User Interfaces Comp 152 Procedural programming Execute line of code at a time Allowing for selection and repetition Call one function and then another. Can trace program execution on paper from

More information

CompSci 125 Lecture 17. GUI: Graphics, Check Boxes, Radio Buttons

CompSci 125 Lecture 17. GUI: Graphics, Check Boxes, Radio Buttons CompSci 125 Lecture 17 GUI: Graphics, Check Boxes, Radio Buttons Announcements GUI Review Review: Inheritance Subclass is a Parent class Includes parent s features May Extend May Modify extends! Parent

More information

Part 3: Graphical User Interface (GUI) & Java Applets

Part 3: Graphical User Interface (GUI) & Java Applets 1,QWURGXFWLRQWR-DYD3URJUDPPLQJ (( Part 3: Graphical User Interface (GUI) & Java Applets EE905-GUI 7RSLFV Creating a Window Panels Event Handling Swing GUI Components ƒ Layout Management ƒ Text Field ƒ

More information

Command-Line Applications. GUI Libraries GUI-related classes are defined primarily in the java.awt and the javax.swing packages.

Command-Line Applications. GUI Libraries GUI-related classes are defined primarily in the java.awt and the javax.swing packages. 1 CS257 Computer Science I Kevin Sahr, PhD Lecture 14: Graphical User Interfaces Command-Line Applications 2 The programs we've explored thus far have been text-based applications A Java application is

More information

(listener)... MouseListener, ActionLister. (adapter)... MouseAdapter, ActionAdapter. java.awt AWT Abstract Window Toolkit GUI

(listener)... MouseListener, ActionLister. (adapter)... MouseAdapter, ActionAdapter. java.awt AWT Abstract Window Toolkit GUI 51 6!! GUI(Graphical User Interface) java.awt javax.swing (component) GUI... (container) (listener)... MouseListener, ActionLister (adapter)... MouseAdapter, ActionAdapter 6.1 GUI(Graphics User Interface

More information

Chapter 17 Creating User Interfaces

Chapter 17 Creating User Interfaces Chapter 17 Creating User Interfaces 1 Motivations A graphical user interface (GUI) makes a system user-friendly and easy to use. Creating a GUI requires creativity and knowledge of how GUI components work.

More information

Graphic User Interfaces. - GUI concepts - Swing - AWT

Graphic User Interfaces. - GUI concepts - Swing - AWT Graphic User Interfaces - GUI concepts - Swing - AWT 1 What is GUI Graphic User Interfaces are used in programs to communicate more efficiently with computer users MacOS MS Windows X Windows etc 2 Considerations

More information

GUI Event Handling 11. GUI Event Handling. Objectives. What is an Event? Hierarchical Model (JDK1.0) Delegation Model (JDK1.1)

GUI Event Handling 11. GUI Event Handling. Objectives. What is an Event? Hierarchical Model (JDK1.0) Delegation Model (JDK1.1) Objectives Write code to handle events that occur in a GUI 11 GUI Event Handling Describe the concept of adapter classes, including how and when to use them Determine the user action that originated the

More information

17 GUI API: Container 18 Hello world with a GUI 19 GUI API: JLabel 20 GUI API: Container: add() 21 Hello world with a GUI 22 GUI API: JFrame: setdefau

17 GUI API: Container 18 Hello world with a GUI 19 GUI API: JLabel 20 GUI API: Container: add() 21 Hello world with a GUI 22 GUI API: JFrame: setdefau List of Slides 1 Title 2 Chapter 13: Graphical user interfaces 3 Chapter aims 4 Section 2: Example:Hello world with a GUI 5 Aim 6 Hello world with a GUI 7 Hello world with a GUI 8 Package: java.awt and

More information

Window Interfaces Using Swing Objects

Window Interfaces Using Swing Objects Chapter 12 Window Interfaces Using Swing Objects Event-Driven Programming and GUIs Swing Basics and a Simple Demo Program Layout Managers Buttons and Action Listeners Container Classes Text I/O for GUIs

More information

Advanced Java Programming. Swing. Introduction to Swing. Swing libraries. Eran Werner, Tel-Aviv University Summer, 2005

Advanced Java Programming. Swing. Introduction to Swing. Swing libraries. Eran Werner, Tel-Aviv University Summer, 2005 Advanced Java Programming Swing Eran Werner, Tel-Aviv University Summer, 2005 19 May 2005 Advanced Java Programming, Summer 2005 1 Introduction to Swing The Swing package is part of the Java Foundation

More information

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011 GUI DYNAMICS Lecture July 26 CS2110 Summer 2011 GUI Statics and GUI Dynamics 2 Statics: what s drawn on the screen Components buttons, labels, lists, sliders, menus,... Containers: components that contain

More information

CSE 331. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

CSE 331. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT CSE 331 Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia http://www.cs.washington.edu/331/

More information

Handling Mouse and Keyboard Events

Handling Mouse and Keyboard Events Handling Mouse and Keyboard Events 605.481 1 Java Event Delegation Model EventListener handleevent(eventobject handleevent(eventobject e); e); EventListenerObject source.addlistener(this);

More information

COMPSCI 230. Software Design and Construction. Swing

COMPSCI 230. Software Design and Construction. Swing COMPSCI 230 Software Design and Construction Swing 1 2013-04-17 Recap: SWING DESIGN PRINCIPLES 1. GUI is built as containment hierarchy of widgets (i.e. the parent-child nesting relation between them)

More information

GUI in Java TalentHome Solutions

GUI in Java TalentHome Solutions GUI in Java TalentHome Solutions AWT Stands for Abstract Window Toolkit API to develop GUI in java Has some predefined components Platform Dependent Heavy weight To use AWT, import java.awt.* Calculator

More information

GUI Program Organization. Sequential vs. Event-driven Programming. Sequential Programming. Outline

GUI Program Organization. Sequential vs. Event-driven Programming. Sequential Programming. Outline Sequential vs. Event-driven Programming Reacting to the user GUI Program Organization Let s digress briefly to examine the organization of our GUI programs We ll do this in stages, by examining three example

More information

CS11 Java. Fall Lecture 3

CS11 Java. Fall Lecture 3 CS11 Java Fall 2014-2015 Lecture 3 Today s Topics! Class inheritance! Abstract classes! Polymorphism! Introduction to Swing API and event-handling! Nested and inner classes Class Inheritance! A third of

More information

Lecture 3: Java Graphics & Events

Lecture 3: Java Graphics & Events Lecture 3: Java Graphics & Events CS 62 Fall 2017 Kim Bruce & Alexandra Papoutsaki Text Input Scanner class Constructor: myscanner = new Scanner(System.in); can use file instead of System.in new Scanner(new

More information

JAVA NOTES GRAPHICAL USER INTERFACES

JAVA NOTES GRAPHICAL USER INTERFACES 1 JAVA NOTES GRAPHICAL USER INTERFACES Terry Marris July 2001 8 DROP-DOWN LISTS 8.1 LEARNING OUTCOMES By the end of this lesson the student should be able to understand and use JLists understand and use

More information

Table of Contents. Chapter 1 Getting Started with Java SE 7 1. Chapter 2 Exploring Class Members in Java 15. iii. Introduction of Java SE 7...

Table of Contents. Chapter 1 Getting Started with Java SE 7 1. Chapter 2 Exploring Class Members in Java 15. iii. Introduction of Java SE 7... Table of Contents Chapter 1 Getting Started with Java SE 7 1 Introduction of Java SE 7... 2 Exploring the Features of Java... 3 Exploring Features of Java SE 7... 4 Introducing Java Environment... 5 Explaining

More information

Swing/GUI Cheat Sheet

Swing/GUI Cheat Sheet General reminders To display a Swing component, you must: Swing/GUI Cheat Sheet Construct and initialize the component. Example: button = new JButton ("ButtonLabel"); Add it to the content pane of the

More information

Example Programs. COSC 3461 User Interfaces. GUI Program Organization. Outline. DemoHelloWorld.java DemoHelloWorld2.java DemoSwing.

Example Programs. COSC 3461 User Interfaces. GUI Program Organization. Outline. DemoHelloWorld.java DemoHelloWorld2.java DemoSwing. COSC User Interfaces Module 3 Sequential vs. Event-driven Programming Example Programs DemoLargestConsole.java DemoLargestGUI.java Demo programs will be available on the course web page. GUI Program Organization

More information

Advanced Java Unit 6: Review of Graphics and Events

Advanced Java Unit 6: Review of Graphics and Events Advanced Java Unit 6: Review of Graphics and Events This is a review of the basics of writing a java program that has a graphical interface. To keep things simple, all of the graphics programs will follow

More information

Unit 6: Graphical User Interface

Unit 6: Graphical User Interface Faculty of Computer Science Programming Language 2 Object oriented design using JAVA Dr. Ayman Ezzat Email: ayman@fcih.net Web: www.fcih.net/ayman Unit 6: Graphical User Interface 1 1. Overview of the

More information

Event Driven Programming

Event Driven Programming Event Driven Programming 1. Objectives... 2 2. Definitions... 2 3. Event-Driven Style of Programming... 2 4. Event Polling Model... 3 5. Java's Event Delegation Model... 5 6. How to Implement an Event

More information

Graphical User Interface (GUI) and Object- Oriented Design (OOD)

Graphical User Interface (GUI) and Object- Oriented Design (OOD) Chapter 6,13 Graphical User Interface (GUI) and Object- Oriented Design (OOD) Objectives To distinguish simple GUI components. To describe the Java GUI API hierarchy. To create user interfaces using frames,

More information

Graphics programming. COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson)

Graphics programming. COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson) Graphics programming COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson) Overview Aims To provide an overview of Swing and the AWT To show how to build

More information

GUI (Graphic User Interface) Programming. Part 2 (Chapter 8) Chapter Goals. Events, Event Sources, and Event Listeners. Listeners

GUI (Graphic User Interface) Programming. Part 2 (Chapter 8) Chapter Goals. Events, Event Sources, and Event Listeners. Listeners GUI (Graphic User Interface) Programming Part 2 (Chapter 8) Chapter Goals To understand the Java event model To install action and mouse event listeners To accept input from buttons, text fields, and the

More information

Systems Programming Graphical User Interfaces

Systems Programming Graphical User Interfaces Systems Programming Graphical User Interfaces Julio Villena Román (LECTURER) CONTENTS ARE MOSTLY BASED ON THE WORK BY: José Jesús García Rueda Systems Programming GUIs based on Java

More information

UNIT-3 : MULTI THREADED PROGRAMMING, EVENT HANDLING. A Multithreaded program contains two or more parts that can run concurrently.

UNIT-3 : MULTI THREADED PROGRAMMING, EVENT HANDLING. A Multithreaded program contains two or more parts that can run concurrently. UNIT-3 : MULTI THREADED PROGRAMMING, EVENT HANDLING 1. What are Threads? A thread is a single path of execution of code in a program. A Multithreaded program contains two or more parts that can run concurrently.

More information

Swing I CHAPTER EVENT-DRIVEN PROGRAMMING 921 Events and Listeners 921

Swing I CHAPTER EVENT-DRIVEN PROGRAMMING 921 Events and Listeners 921 CHAPTER 17 Swing I 17.1 EVENT-DRIVEN PROGRAMMING 921 Events and Listeners 921 17.2 BUTTONS, EVENTS, AND OTHER SWING BASICS 923 Example: A Simple Window 923 Buttons 930 Action Listeners and Action Events

More information

Dr. Hikmat A. M. AbdelJaber

Dr. Hikmat A. M. AbdelJaber Dr. Hikmat A. M. AbdelJaber JWindow: is a window without a title bar or move controls. The program can move and resize it, but the user cannot. It has no border at all. It optionally has a parent JFrame.

More information

Swing I Event-Driven Programming Buttons, Events, and Other Swing Basics Containers and Layout Managers 946

Swing I Event-Driven Programming Buttons, Events, and Other Swing Basics Containers and Layout Managers 946 17.1 Event-Driven Programming 925 Events and Listeners 925 17.2 Buttons, Events, and Other Swing Basics 926 Example: A Simple Window 927 Buttons 933 Action Listeners and Action Events 934 Example: A Better

More information

GUI Basics. Object Orientated Programming in Java. Benjamin Kenwright

GUI Basics. Object Orientated Programming in Java. Benjamin Kenwright GUI Basics Object Orientated Programming in Java Benjamin Kenwright Outline Essential Graphical User Interface (GUI) Concepts Libraries, Implementation, Mechanics,.. Abstract Windowing Toolkit (AWT) Java

More information

Java Swing. based on slides by: Walter Milner. Java Swing Walter Milner 2005: Slide 1

Java Swing. based on slides by: Walter Milner. Java Swing Walter Milner 2005: Slide 1 Java Swing based on slides by: Walter Milner Java Swing Walter Milner 2005: Slide 1 What is Swing? A group of 14 packages to do with the UI 451 classes as at 1.4 (!) Part of JFC Java Foundation Classes

More information

Overloading Example. Overloading. When to Overload. Overloading Example (cont'd) (class Point continued.)

Overloading Example. Overloading. When to Overload. Overloading Example (cont'd) (class Point continued.) Overloading Each method has a signature: its name together with the number and types of its parameters Methods Signatures String tostring() () void move(int dx,int dy) (int,int) void paint(graphicsg) (Graphics)

More information