Arrays, Exception Handling, Interfaces, Introduction To Swing

Size: px
Start display at page:

Download "Arrays, Exception Handling, Interfaces, Introduction To Swing"

Transcription

1 Arrays, Exception Handling, Interfaces, Introduction To Swing

2 Arrays: Definition An array is an ordered collection of items; an item in an array is called an element of the array. By item we mean a primitive, object or another array. Every element in an array has to be the same type. Elements in an array are referred to by index, where 0 is the index of the first item.

3 Arrays: Declaration We can declare a variable to be type array of... by using the index operator, []: int[] iarr; // iarr is type array of ints double[] darr; // darr is type array of doubles Turtle[] tarr; // tarr is an array of Turtles

4 Arrays: Creation Recall that declaring a variable to be type Turtle doesn t actually create a Turtle: Turtle tim; // tim is type Turtle, but no Turtle // actually exists. tim = new Turtle(); // A Turtle now exists and can be // accessed via tim. Similarly, before being used, an array must be created: int[] iarr; // iarr is type array of ints, but no // array actually exists. iarr = new int[20]; // An array of 20 ints now exists // and can be accessed via iarr. Like Turtles and other objects, an array can be declared and created in a single step: Turtle[] tots = new Turtle[10]; // tots is an array of 10 Turtles.

5 Arrays: Accessing Individual elements of an array are accessed using the index operator, with 0 as the first index: int[] iarr = new int[20]; iarr[0] = 5; // set the first element of iarr iarr[19] = 22; // set the last element of iarr int min = iarr[0]; // min == first element of iarr You can determine the size of an array by examining the array s length variable: for ( int inx = 0 ; inx < iarr.length ; ++inx ) System.out.println( iarr[inx] );

6 Arrays: Example 1 public class ArrayDemo1 public static void main(string[] args) Turtle[] tots = new Turtle[10]; for ( int inx = 0 ; inx < tots.length ; ++inx ) tots[inx] = new Turtle(); for ( int inx = 0 ; inx < tots.length ; inx += 2 ) tots[inx].switchto( Color.GREEN ); tots[inx+1].switchto( Color.RED ); int radius = 256; for ( int inx = 0 ; inx < tots.length ; ++inx ) tots[inx].fillcircle( radius ); radius -= 32;

7 Arrays: Example 2 public class ArrayDemo2 public static void main(string[] args) Random randy = new Random(); int[] iarr = new int[100]; for ( int inx = 0 ; inx < iarr.length ; ++inx ) iarr[inx] = randy.nextint( ); int min = getsmallest( iarr ); System.out.println( min );... continued on next slide

8 Arrays: Example 2 continued... // precondition: arr contains at least one element private static int getsmallest( int[] arr ) int smallest = arr[0]; for ( int inx = 1 ; inx < arr.length ; ++inx ) if ( arr[inx] < smallest ) smallest = arr[inx]; return smallest;

9 Arrays: Initialization You can (usually) initialize an array in its declaration using a block statement: private int[] iarr = 1, 2, 3, 4, 5 ; private String[] sarr = "alpha", "bravo", "charlie" ; private Turtle[] tarr = new Turtle(), new Turtle(), new Turtle() ;

10 Exercises 1. Write and test a method that takes an array of doubles and returns the largest value. 2. Write and test a method that takes an array of Strings and returns the shortest string; if two or more strings have the same, shortest, length, return the first one. 3. Write and test a method that takes an array of Strings and returns the shortest string; if two or more strings have the same, shortest, length, return the last one. 4. Write and test a method that takes an array of Vics. For each element of the array, advance the Vic by one spot, but only if the Vic can be advanced (i.e., seesslot returns true). 5. What type of array can hold both Vic and Turtle objects?

11 Exceptions When an exceptional circumstance arises java can respond by throwing an exception. Exceptions are usually, but not always, associated with error processing.

12 Exceptions: Example If you use Integer.parseInt to parse a string that is not a valid integer, Java will throw a NumberFormatException. public static void main(string[] args) int temp = Integer.parseInt( "sally" ); System.out.println( temp ); Runtime message: Exception in thread "main" java.lang.numberformatexception: For input string: "sally" at java.lang.numberformatexception.forinputstring(numberformatexception.java:65) at java.lang.integer.parseint(integer.java:580) at java.lang.integer.parseint(integer.java:615) at javaintro.test.main(test.java:8)

13 Exceptions: Try/Catch Blocks If an exception is thrown your program will crash unless you catch it, with a try/catch block. public static void main(string[] args) int temp; try temp = Integer.parseInt( "sally" ); System.out.println( temp ); catch ( NumberFormatException exc ) System.out.println( "EXCEPTION OCCURRED" ); Output: EXCEPTION OCCURRED

14 Try/Catch Block Example private static int askinteger( String prompt ) int result = 0; boolean valid = false; while (!valid ) String input = JOptionPane.showInputDialog( prompt ); try result = Integer.parseInt( input ); valid = true; catch ( NumberFormatException exc ) String msg = "That input was invalid; try again"; JOptionPane.showMessageDialog( null, msg ); return result;

15 Lazy Catchers Most exception objects extend the Exception class catch (Exception exc) will catch all of these This example will... this is generally a BAD thing. catch any try exception. If something odd result = Integer.parseInt( input ); goes wrong in valid = true; parseint you will think it is an catch ( Exception exc ) operator error. String msg = "That input was invalid; try again"; JOptionPane.showMessageDialog( null, msg );

16 Multiple Catchers If an operation can throw multiple exceptions you can catch them with multiple catch blocks. try result = someoperation(); catch ( NumberFormatException exc )... catch ( ArithmeticException exc )... catch ( Exception exc )...

17 Throwing Exceptions You can throw (or raise) an Exception yourself if it s convenient. When a method throws an exception it must usually be declared with the throws keyword. private static void process( int param ) throws Exception if ( param < 1 param > 100 ) throw new Exception( "Value out of range" );

18 Declaring Throws Even if your method doesn t explicitly throw an exception, an exception may be thrown by a method that it calls in this case your method must handle the exception, or declare that it throws the exception. private static void initialize() throws Exception process( 1 ); private static void process( int param ) throws Exception if ( param < 1 param > 100 ) throw new Exception( "Value out of range" );

19 Creating Your Own Exceptions You can define your own exceptions, usually by extending Exception: // OpCanceledException.java public class OpCanceledException extends Exception

20 Creating Your Own Exceptions: Example private static int askinteger( String prompt ) throws OpCanceledException int result = 0; boolean valid = false; while (!valid ) String input = JOptionPane.showInputDialog( prompt ); try if ( input == null ) throw new OpCanceledException(); result = Integer.parseInt( input ); valid = true; catch ( NumberFormatException exc ) String msg = "That input was invalid; try again"; JOptionPane.showMessageDialog( null, msg ); return result;

21 Exercises 1. Write and compile the OpCanceledException class as shown in the slides. 2. Create the IOUtils class, and add the following two methods: a) public static void askintdlg( String prompt, int min, int max ) Like a similar method shown in the slides, use a JOptionPane input dialog to prompt the operator for a number. If the operator enters an invalid number, or a number less than min or greater than max, show an error message and reprompt. If the operator cancels the operation, throw an OpCanceledException. b) public static int askintdlg( String prompt ) This method calls askintdlg( String, int, int ), passing Integer.MIN_VALUE and Integer.MAX_VALUE for the min and max arguments.

22 Interfaces

23 Interfaces: Declaration An interface in Java describes one or more methods to be implemented by another class. Interfaces are defined like classes, but using the interface keyword instead of the class keyword. Like classes, interfaces must be defined in.java files that have the same name as the interface. An interface consists of method signatures only. public interface Description public String getlongdescription(); public String getshortdescription();

24 Interfaces: Implementation (1) A Java class declares the implementation of an interface using the implements keyword. public class SomeClass extends AnotherClass implements Interface1, Interface2, You can only extend one other class, but you can implement as many interfaces as you like.

25 Interfaces: Implementation (2) When you implement an interface you must provide a body for every method declared in the interface. public class Moe extends Turtle implements Description public static void main( String[] args ) Moe manny = new Moe(); Logger. logobjectcreation( moe );... continued on next slide

26 continued Interfaces: Implementation (3)... public String getlongdescription() return "This is Moe the Turtle. Moe is a talented artiste who " + "delights in creating wonderful pictures that amaze " + "and entrance Moe s many admirers. Moe can be found " + "most Friday nights at Harry O'Hare s, signing " + "autographs and recounting clever tales of his antics " + "as a youth."; public String getshortdescription() return "Moe draws delightful pictures.";

27 Interfaces: Utilizing An object of a class that implements an interface can be used with a variable or parameter declared to be that type. public class Logger public static void logobjectcreation( Description obj ) String msg = "Object creation: " + obj.getshortdescription(); System.out.println( msg ); Note: logging operations are usually much more complicated than this.

28 Interfaces: Predefined Java has defined many interfaces for you to use; see, for example, the java.util.list interface an ArrayList, LinkedList, Stack or Vector can be used anywhere a List is required.

29 Exercises 1. Modify the Description interface from the slides so that it has public String getname() and public String getfavoritecolor() method signatures. 2. Fix the Moe class so that it compiles. 3. Add a method to the Logger class that displays a message dialog that says something like " 's favorit color is."; fill in the blanks by calling the getname and getfavoritecolor methods for the object that it is describing. Write a test program that demonstrates that the new methods work.

30 JFrames The JFrame class, from the javax.swing package, is used to create dialogs such as those provided by JOptionPane. public class JFrameIntro1 public static void main(string[] args) new JFrameIntro1(); Note: Creating a usable GUI is a little more complicated than this. public JFrameIntro1() frame.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); JFrame frame = new JFrame(); frame.setsize( 512, 1024 ); frame.setvisible( true );

31 JFrames: Extending GUI applications often extend the JFrame class: public class JFrameIntro2 extends JFrame public static void main(string[] args) new JFrameIntro2(); public JFrameIntro2() frame.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); setsize( 512, 1024 ); setvisible( true );

32 Event Listeners: Windows In this context an event is something that can occur to an application window, such as: Window is activated Window is deactivated Five additional methods public class EventsIntro1 implements WindowListener public void windowactivated(windowevent event ) public void windowdeactivated(windowevent event ) public void windowopened(windowevent event )...

33 continued Sample Window Event Handler public class EventsIntro1 implements WindowListener... public void windowclosed(windowevent event ) public void windowclosing(windowevent event ) public void windowiconified(windowevent event ) System.out.println( "Window Iconified" ); public void windowdeiconified(windowevent event ) System.out.println( "Window Deiconified" ); continued on next slide

34 continued Sample Window Event Handler To listen for window events in a JFrame add a WindowListener to it. public class JFrameIntro3 extends JFrame public static void main(string[] args) new JFrameIntro3(); public JFrameIntro3() frame.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); addwindowlistener( new EventsIntro1() ); setsize( 512, 1024 ); setvisible( true ); See also: WindowStateListener, WindowFocusListener, JFrame.addWindowFocusListener, JFrame.addWindowStateListener

35 Abstract Classes An abstract class is a class in which some methods must be overridden by subclasses. An abstract class cannot be instantiated. An example of a simple abstract class is java.awt.event.windowadaptor. WindowAdaptor is a convenience class that implements all the methods in WindowListener, WindowStateListener and WindowFocusListener. To write your own class that needs some of the functionality provided by the above interfaces, extend WindowAdaptor and override the methods that you need.

36 Window Adaptor, Example public class EventsIntro2 extends WindowAdapter public void windowopened(windowevent event ) System.out.println( "Window opened" ); continued on next slide

37 Window Adaptor, Example continued public class JFrameIntro3 extends JFrame public static void main(string[] args) new JFrameIntro3(); public JFrameIntro3() EventsIntro2 eventlistener = new EventsIntro2(); setsize( 512, 1024 ); setvisible( true ); this.addwindowlistener( eventlistener ); this.addwindowstatelistener( eventlistener );

38 Exercises 1. Implement classes JFrameIntro3 and EventsIntro2. 2. Change EventsIntro2 so that it prints diagnostics when the window gains or loses keyboard focus. In JFrameIntro3 add an instance of EventsIntro2 as a WindowFocusListener.

39 Nested Classes A nested class is a class declared inside another class: public class OuterClass... private class InnerClass... Nested classes are a way of grouping together and/or compartmentalizing common code. Nested classes have other advantages.

40 Nested Classes: Example public class JFrameIntro4 extends JFrame public static void main( String[] args ) new JFrameIntro4(); public JFrameIntro4() EventProcessor eventlistener = new EventProcessor(); setsize( 512, 1024 ); setvisible( true ); addwindowlistener( eventlistener ); addwindowstatelistener( eventlistener ); private class EventProcessor extends WindowAdapter public void windowopened(windowevent event ) System.out.println( "Window opened" );

41 Exercises 1. Change JFrameIntro3 so that it uses a nested class for its window event processing. 2. Write a new application that: a) Extends JFrame. b) Implements WindowFocusListener. c) Adds itself as a window focus listener, for example: addwindowfocuslistener( this );

42 Launching A Swing Dialog 1. The class that assembles the dialog must implement Runnable; this requires adding a public void run() method to your class. 2. Launch the dialog as a separate thread using SwingUtilities.invokeLater( Runnable ); this will create a new thread and call its run method. 3. Assemble the dialog in the run method.

43 Launching A Swing Dialog: Example public class JFrameIntro5 implements Runnable public static void main(string[] args) JFrameIntro5 dlg = new JFrameIntro5(); SwingUtilities.invokeLater( dlg ); public void run() JFrame frame = new JFrame(); frame.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); frame.setsize( 512, 1024 ); frame.setvisible( true );

44 Adding GUI Components To A JFrame 1. Obtain the frame s content pane. 2. Add the new components to the content pane. 3. Optional: instead of setting the size of the frame, pack it, which will cause the frame to be sized according to the needs of the components that you add to it. public void run() JFrame frame = new JFrame(); frame.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); Container pane = frame.getcontentpane(); JButton button = new JButton( "OK" ); pane.add( button ); frame.pack(); frame.setvisible( true );

45 Exercises 1. Implement DialogIntro1 from the slides. 2. Change DialogIntro1 so that it extends JFrame. 3. Add some more buttons to the JFrame: pane.add( button ); pane.add( new JButton( "Cancel" ) ); pane.add( new JButton( "Spot" ) ); How many buttons can you see in the JFrame? Can you explain why? Try adding the JButtons to the frame s content pane in a different order; what happens?

46 Layout Managers A layout manager can be added to a container in order to control the size and position of each component. The layout managers provided by Java come from java.awt. Layout managers come in different levels of complexity; one of the simplest is FlowLayout, which lays out one component after the other. public void run() JFrame frame = new JFrame( "JFrame Demo" ); frame.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); Container pane = frame.getcontentpane(); pane.setlayout( new FlowLayout() ); pane.add( new JButton( "OK" ) ); pane.add( new JButton( "Cancel" ) ); pane.add( new JButton( "Go dog, go!" ) ); frame.pack(); frame.setvisible( true );

47 GridLayout The GridLayout class provides a layout manager that lays out components in rows and columns. public void run() setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); Container pane = getcontentpane(); pane.setlayout( new GridLayout( 3, 2 ) ); pane.add( new JButton( "OK" ) ); pane.add( new JButton( "Cancel" ) ); pane.add( new JButton( "Go dog, go!" ) ); pane.add( new JLabel( "Red dog, yellow dog" ) ); pane.add( new JButton( "Component #5" ) ); pane.add( new JLabel( "Yo mama" ) ); pack(); setvisible( true ); Three rows of two columns each

48 GridLayout Example public class GridLayoutDemo extends JFrame implements Runnable public static void main(string[] args) GridLayoutDemo dlg = new GridLayoutDemo(); SwingUtilities.invokeLater( dlg ); public void run() setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); Container pane = getcontentpane(); pane.setlayout( new GridLayout( 3, 2 ) ); pane.add( new JButton( "OK" ) ); pane.add( new JButton( "Cancel" ) ); pane.add( new JButton( "Go dog, go!" ) ); pane.add( new JLabel( "Red dog, yellow dog" ) ); pane.add( new JButton( "Component #5" ) ); pane.add( new JLabel( "Yo mama" ) ); pack(); setvisible( true );

49 Exercises 1. Write a class that extends JFrame. Add a combination of 10 JButton and JLabel components to the frame; use a FlowLayout layout manager. 2. Rewrite the application above so that a) It does not extend anything; and b) It uses a GridLayout layout manager.

50 JPanels The JPanel class allows you to create rectangular areas for laying out components. JPanels can be nested. Each JPanel has its own layout manager. A JPanel has a FlowLayout layout manager by default. The JPanel( LayoutManager ) constructor allows you to create a JPanel with a given layout manager. Components are added directly to the JPanel.

51 JPanel Example public class JPanelDemo1 extends JFrame implements Runnable public static void main(string[] args) JPanelDemo1 demo = new JPanelDemo1(); SwingUtilities.invokeLater( demo ); public void run() settitle( "JPanel Demo 1" ); setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); Container pane = getcontentpane(); pane.setlayout( new GridLayout( 2, 1 ) ); pane.add( makepanel1() ); pane.add( makepanel2() ); pack(); setvisible( true );... continued on next slide

52 JPanel Example continued private JPanel makepanel1() JPanel panel = new JPanel(); for ( int inx = 0 ; inx < 5 ; ++inx ) panel.add( new JButton( "JButton " + (inx + 1) ) ); return panel; private JPanel makepanel2() JPanel panel = new JPanel( new GridLayout( 4, 2 ) ); for ( int inx = 0 ; inx < 4 ; ++inx ) panel.add( new JLabel( "Label: " + (inx + 1) ) ); panel.add( new JButton( "Spot " + (inx +1) ) ); return panel; continued on next slide

53 continued JPanel Example Panel1; FlowLayout() Content Pane; GridLayout( 2, 1 ) Panel2; GridLayout( 4, 2 )

54 Nested Classes, Revisited It s not unusual for GUI components to be built from nested classes. public class JPanelDemo2 extends JFrame implements Runnable... public void run() settitle( "JPanel Demo 2" ); setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); Container pane = getcontentpane(); pane.setlayout( new GridLayout( 2, 1 ) ); pane.add( new Panel1() ); pane.add( new Panel2() ); pack(); setvisible( true ); continued on next slide

55 GUIs And Nested Classes, Example public class JPanelDemo2 extends JFrame implements Runnable public static void main(string[] args) JPanelDemo2 demo = new JPanelDemo2(); SwingUtilities.invokeLater( demo ); public void run() settitle( "JPanel Demo 2" ); setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); Container pane = getcontentpane(); pane.setlayout( new GridLayout( 2, 1 ) ); pane.add( new Panel1() ); pane.add( new Panel2() ); pack(); setvisible( true );... continued on next slide

56 GUIs And Nested Classes, Example continued private class Panel1 extends JPanel public Panel1() for ( int inx = 0 ; inx < 5 ; ++inx ) add( new JButton( "JButton " + (inx + 1) ) ); private class Panel2 extends JPanel public Panel2() super( new GridLayout( 4, 2 ) ); for ( int inx = 0 ; inx < 4 ; ++inx ) add( new JLabel( "Label: " + (inx + 1) ) ); add( new JButton( "Spot " + (inx +1) ) );

57 Exercises (page 1 of 2) 1. Write a class that extends JFrame, and has four panels laid out in a 2x2 grid. Each panel should be implemented as a nested class. The final dialog should look like this: Hints: The upper left panel has a FlowLayout The upper right panel has a GridLayout( 2, 2 ) The lower left panel has a GridLayout( 3, 2 ) The lower right panel has a GridLayout( 1, 3 )

58 Exercises (page 2 of 2) 2. Write a class that extends JFrame. You should add one JPanel to the frame s content pane; the panel should be implemented as a nested class. The final dialog should look like this: Hints: Use a GridLayout Use JButtons for the arrows Use JLabels for the blank areas

59 GridBagLayout: Introduction The GridBagLayout class provides a very flexible layout manager. Our examples will include the following features: Dynamically specify the row and column of a component; not all rows/columns need be occupied. Specify the width of a row; not all rows have to be the same width. Determine how a component fills its designated space.

60 GridBagConstraints A GridBagConstraints object is used to determine the size and position of a component when it is added to its parent. Such an object consists of public instance variables including: gridx: the horizontal position of a component. gridy: the vertical position of a component. gridwidth: the number of horizontal grid positions that a component will occupy. gridheight: the number of vertical grid positions that a component will occupy. fill: how a component will fill a space that it is too small for: GridBagConstraints.HORIZONTAL GridBagConstraints.VERTICAL GridBagConstraints.BOTH

61 GridBagConstraints, Example 1 public class GridBagTest extends JFrame implements Runnable... private class Panel1 extends JPanel public Panel1() super( new GridBagLayout() ); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 1; gbc.gridy = 0; add( new JButton( "Button 1" ), gbc ); gbc.gridx = 0; add( new JButton( "Button 2" ), gbc );

62 GridBagConstraints, Example 2 public class GridBagDemo1 extends JFrame implements Runnable public static void main(string[] args) GridBagDemo1 demo = new GridBagDemo1(); SwingUtilities.invokeLater( demo ); public void run() settitle( "GridBag Demo 1" ); setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); Container pane = getcontentpane(); pane.add( new Panel1() ); pack(); setvisible( true );... continued on next slide

63 continued GridBagConstraints, Example 2... private class Panel1 extends JPanel public Panel1() super( new GridBagLayout() ); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; add( new JButton( "Button 1" ), gbc ); gbc.gridx = 1; add( new JButton( "Button 2" ), gbc ); gbc.gridx = 2; add( new JButton( "Button 3" ), gbc );... continued on next slide

64 continued GridBagConstraints, Example 2... gbc.gridx = 0; gbc.gridy = 1; add( new JButton( "Button 4" ), gbc ); gbc.gridx = 1; gbc.gridwidth = 2; gbc.fill = GridBagConstraints.HORIZONTAL; add( new JButton( "Button 5" ), gbc ); gbc.gridx = 0; gbc.gridy = 2; gbc.gridwidth = 3; add( new JButton( "Button 6" ), gbc );... continued on next slide

65 continued GridBagConstraints, Example 2... gbc.gridx = 3; gbc.gridy = 0; gbc.gridwidth = 1; gbc.gridheight = 3; gbc.fill = GridBagConstraints.VERTICAL; add( new JButton( "Button 7" ), gbc ); Don t forget to use the add overload that takes two arguments! continued on next slide

66 GridBagConstraints, Example 2 continued.gridx = 0.gridy = 0.gridwidth = 1.gridheight = 1.fill = NONE.gridx = 1.gridy = 0.gridwidth = 1.gridheight = 1.fill = NONE.gridx = 3.gridy = 0.gridwidth = 1.gridheight = 3.fill = VERTICAL.gridx = 1.gridy = 1.gridwidth = 2.gridheight = 1.fill = HORIZONTAL.gridx = 0.gridy = 2.gridwidth = 3.gridheight = 1.fill = HORIZONTAL

67 Exercises 1. Starting with a JFrame that contains a JPanel that has a GridBag layout, write an application that displays the following dialog:.gridwidth = 2 JLabel.gridheight = 2.gridwidth = 4

68 JTextField The JTextField Swing component displays a single line in which a user may enter text: public void run() setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); Container pane = getcontentpane(); JPanel panel = new JPanel( new GridLayout( 2, 1 ) ); pane.add( panel ); panel.add( new JTextField( 20 ) ); panel.add( new ButtonPanel() ); pack(); setvisible( true ); continued on next slide

69 continued JTextField (For the sake of completeness, here is the code for ButtonPanel.) public class ButtonPanel extends JPanel public ButtonPanel() super( new GridLayout( 1, 2 ) ); add( new JButton( "OK" ) ); add( new JButton( "Cancel" ) );

70 GradBagConstraints.insets Look up the documentation for java.awt.gridbagconstraints. Look up the documentation for java.awt.insets. Use insets to put a margin around a dialog s components. private class Panel1 extends JPanel public Panel1() super( new GridBagLayout() ); GridBagConstraints gbc = new GridBagConstraints(); for ( int inx = 0 ; inx < 6 ; ++inx ) gbc.gridx = inx % 3; gbc.gridy = inx / 3; add( new JButton( "Button " + (inx + 1 ) ), gbc ); continued on next slide

71 GradBagConstraints.insets continued before after private class Panel1 extends JPanel public Panel1() super( new GridBagLayout() ); GridBagConstraints gbc = new GridBagConstraints(); gbc.insets = new Insets( 5, 5, 5, 5 );...

72 ActionTurtleFrame (1) ActionTurtleFrame will be the container for building our ActionTurtle application it extends JFrame and implements the Runnable interface. public class ActionTurtleFrame extends JFrame implements Runnable

73 ActionTurtleFrame (2) ActionTurtleFrame has two instance variables and two accessors: textbox_ is a JTextField that will hold operator input masterpanel_ is a JPanel that a developer can use to add components to the frame.... private JTextField textbox_ = new JTextField( 20 ); private JPanel masterpanel_ = new JPanel(); public JPanel getmasterpanel() return masterpanel_; public String getparameters() String parameters = textbox_.gettext(); return parameters;...

74 ActionTurtleFrame (3) ActionTurtleFrame has two constructors that provide a title for the frame:... public ActionTurtleFrame() super( "Action Turtle!" ); public ActionTurtleFrame( String title ) super( title );...

75 ActionTurtleFrame (4) ActionTurtleFrame uses a GridBag layout, and assembles itself in its run method; note that it does not call pack or setvisible.... public void run() setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); JLabel label = new JLabel( "Parameters" ); Container container = getcontentpane(); container.setlayout( new GridBagLayout() ); GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.NONE; gbc.insets = new Insets( 5, 5, 5, 5 );... continued on next slide

76 ActionTurtleFrame (4) continued... gbc.gridx = 0; gbc.gridy = 0; container.add( label, gbc ); gbc.gridx = 1; gbc.gridy = 0; container.add( textbox_, gbc );... gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 2; gbc.fill = GridBagConstraints.HORIZONTAL; container.add( masterpanel_, gbc );

77 ActionTurtleFrame: Complete Code public class ActionTurtleFrame extends JFrame implements Runnable private JTextField textbox_ = new JTextField( 20 ); private JPanel masterpanel_ = new JPanel(); public ActionTurtleFrame() super( "Action Turtle!" ); public ActionTurtleFrame( String title ) super( title ); public JPanel getmasterpanel() return masterpanel_; public String getparameters() String parameters = textbox_.gettext(); return parameters;... continued on next slide

78 ActionTurtleFrame: Complete Code continued... public void run() setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); JLabel label = new JLabel( "Parameters" ); Container container = getcontentpane(); container.setlayout( new GridBagLayout() ); GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.NONE; gbc.insets = new Insets( 5, 5, 5, 5 );... continued on next slide

79 ActionTurtleFrame: Launching The GUI (1) (1) To test the ActionTurtleFrame GUI; a) write a Runnable class that creates an ActionTurtleFrame. b) Launch your class using SwingUtilites.invokeLater. c) from your run method call the frame s run method. d) Pack the frame and make it visible. continued on next slide

80 ActionTurtleFrame: continued Launching The GUI (1) public class ActionTurtleFrameTest1 implements Runnable private ActionTurtleFrame frame = new ActionTurtleFrame( "Action Turtle!" ); public static void main(string[] args) ActionTurtleFrameTest1 test = new ActionTurtleFrameTest1(); SwingUtilities.invokeLater( test ); public void run() frame.run(); frame.pack(); frame.setvisible( true );

81 ActionTurtleFrame: Launching The GUI (2) (2) To test the ActionTurtleFrame GUI; a) Write a Runnable class that extends ActionTurtleFrame. b) Implement Runnable c) Override ActionTurtleFrame.run d) Launch your class using SwingUtilites.invokeLater. e) From your run method, call the run method in the superclass. f) Pack the frame and make it visible. continued on next slide

82 ActionTurtleFrame: continued Launching The GUI (2) public class ActionTurtleFrameTest2 extends ActionTurtleFrame implements Runnable public static void main(string[] args) ActionTurtleFrameTest2 test = new ActionTurtleFrameTest2(); SwingUtilities.invokeLater( test ); public void run() super.run(); pack(); setvisible( true );

83 ActionTurtleFrame: Launching The GUI (3) (3) To test the ActionTurtleFrame GUI; a) Create and launch a runnable class as shown in the previous slides. b) From your run method, call the run method in the superclass. c) Get the master panel from the ActionTurtleFrame. d) Populate the master panel with GUI components. e) Pack the frame and make it visible. continued on next slide

84 ActionTurtleFrame: continued Launching The GUI (3) public class ActionTurtleFrameTest3 extends ActionTurtleFrame implements Runnable public static void main(string[] args) ActionTurtleFrameTest3 test = new ActionTurtleFrameTest3(); SwingUtilities.invokeLater( test ); public void run() super.run(); JPanel panel = getmasterpanel(); panel.setlayout( new GridLayout( 1, 2 ) ); panel.add( new JButton( "OK" ) ); panel.add( new JButton( "Cancel" ) ); pack(); setvisible( true );

85 Exercises 1. Write and test the ActionTurtleFrame class using either of the first two methods shown in the slide. 2. Write an ActionTurtleFrame application that produces a GUI that looks like this: 3. (Advanced) Write an ActionTurtleFrame application that looks like the following; the unfamiliar GUI component is a JComboBox.

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

Graphics User Defined Forms, Part I

Graphics User Defined Forms, Part I Graphics User Defined Forms, Part I Quick Start Compile step once always mkdir labs javac PropertyTax5.java cd labs mkdir 5 Execute step cd 5 java PropertyTax5 cp /samples/csc/156/labs/5/*. cp PropertyTax1.java

More information

CS 251 Intermediate Programming GUIs: Components and Layout

CS 251 Intermediate Programming GUIs: Components and Layout CS 251 Intermediate Programming GUIs: Components and Layout Brooke Chenoweth University of New Mexico Fall 2017 import javax. swing.*; Hello GUI public class HelloGUI extends JFrame { public HelloGUI ()

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

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

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

GUI Forms and Events, Part II

GUI Forms and Events, Part II GUI Forms and Events, Part II Quick Start Compile step once always mkdir labs javac PropertyTax6.java cd labs Execute step mkdir 6 java PropertyTax6 cd 6 cp../5/propertytax5.java PropertyTax6.java Submit

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

An Introduction To Graphical User Interfaces

An Introduction To Graphical User Interfaces An Introduction To Graphical User Interfaces The event-driven model Building simple graphical interfaces in Java Components They are all types of graphical controls and displays available: Button, Canvas,

More information

CS 180 Fall 2006 Exam II

CS 180 Fall 2006 Exam II CS 180 Fall 2006 Exam II There are 20 multiple choice questions. Each one is worth 2 points. There are 3 programming questions worth a total of 60 points. Answer the multiple choice questions on the bubble

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

CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing

CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing CSEN401 Computer Programming Lab Topics: Graphical User Interface Window Interfaces using Swing Prof. Dr. Slim Abdennadher 22.3.2015 c S. Abdennadher 1 Swing c S. Abdennadher 2 AWT versus Swing Two basic

More information

Collections, More About Swing

Collections, More About Swing Collections, More About Swing Collections A Java collection is a class that is used to organize a set of related objects. A collection implements one or more interfaces, including: List Set Oracle: Map

More information

Lecture 28. Exceptions and Inner Classes. Goals. We are going to talk in more detail about two advanced Java features:

Lecture 28. Exceptions and Inner Classes. Goals. We are going to talk in more detail about two advanced Java features: Lecture 28 Exceptions and Inner Classes Goals We are going to talk in more detail about two advanced Java features: Exceptions supply Java s error handling mechanism. Inner classes ease the overhead of

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

CSSE 220 Day 19. Object-Oriented Design Files & Exceptions. Check out FilesAndExceptions from SVN

CSSE 220 Day 19. Object-Oriented Design Files & Exceptions. Check out FilesAndExceptions from SVN CSSE 220 Day 19 Object-Oriented Design Files & Exceptions Check out FilesAndExceptions from SVN A practical technique OBJECT-ORIENTED DESIGN Object-Oriented Design We won t use full-scale, formal methodologies

More information

CS 209 Programming in Java #10 Exception Handling

CS 209 Programming in Java #10 Exception Handling CS 209 Programming in Java #10 Exception Handling Textbook Chapter 15 Spring, 2006 Instructor: J.G. Neal 1 Topics What is an Exception? Exception Handling Fundamentals Errors and Exceptions The try-catch-finally

More information

CSSE 220 Day 19. Object-Oriented Design Files & Exceptions. Check out FilesAndExceptions from SVN

CSSE 220 Day 19. Object-Oriented Design Files & Exceptions. Check out FilesAndExceptions from SVN CSSE 220 Day 19 Object-Oriented Design Files & Exceptions Check out FilesAndExceptions from SVN A practical technique OBJECT-ORIENTED DESIGN Object-Oriented Design We won t use full-scale, formal methodologies

More information

Summary Chapter 25 GUI Components: Part 2

Summary Chapter 25 GUI Components: Part 2 1040 Chapter 25 GUI Components: Part 2 ponent on the line. TheJTextField is added to the content pane with a call to our utility method addcomponent (declared at lines 79 83). MethodaddComponent takes

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

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

Fundamentals of Object Oriented Programming

Fundamentals of Object Oriented Programming INDIAN INSTITUTE OF TECHNOLOGY ROORKEE Fundamentals of Object Oriented Programming CSN- 103 Dr. R. Balasubramanian Associate Professor Department of Computer Science and Engineering Indian Institute of

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

Midterm assessment - MAKEUP Fall 2010

Midterm assessment - MAKEUP Fall 2010 M257 MTA Faculty of Computer Studies Information Technology and Computing Date: /1/2011 Duration: 60 minutes 1-Version 1 M 257: Putting Java to Work Midterm assessment - MAKEUP Fall 2010 Student Name:

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

Introduction This assignment will ask that you write a simple graphical user interface (GUI).

Introduction This assignment will ask that you write a simple graphical user interface (GUI). Computing and Information Systems/Creative Computing University of London International Programmes 2910220: Graphical Object-Oriented and Internet programming in Java Coursework one 2011-12 Introduction

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

Containers and Components

Containers and Components Containers and Components container A GUI has many components in containers. A container contains other components. A container is also a component; so a container may contain other containers. component

More information

Final Examination Semester 2 / Year 2010

Final Examination Semester 2 / Year 2010 Southern College Kolej Selatan 南方学院 Final Examination Semester 2 / Year 2010 COURSE : JAVA PROGRAMMING COURSE CODE : PROG1114 TIME : 2 1/2 HOURS DEPARTMENT : COMPUTER SCIENCE LECTURER : LIM PEI GEOK Student

More information

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class CHAPTER GRAPHICAL USER INTERFACES 10 Slides by Donald W. Smith TechNeTrain.com Final Draft 10/30/11 10.1 Frame Windows Java provides classes to create graphical applications that can run on any major graphical

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

RAIK 183H Examination 2 Solution. November 10, 2014

RAIK 183H Examination 2 Solution. November 10, 2014 RAIK 183H Examination 2 Solution November 10, 2014 Name: NUID: This examination consists of 5 questions and you have 110 minutes to complete the test. Show all steps (including any computations/explanations)

More information

Final Exam CS 251, Intermediate Programming December 13, 2017

Final Exam CS 251, Intermediate Programming December 13, 2017 Final Exam CS 251, Intermediate Programming December 13, 2017 Name: NetID: Answer all questions in the space provided. Write clearly and legibly, you will not get credit for illegible or incomprehensible

More information

University of Cape Town ~ Department of Computer Science. Computer Science 1016S / 1011H ~ November Exam

University of Cape Town ~ Department of Computer Science. Computer Science 1016S / 1011H ~ November Exam Name: Please fill in your Student Number and Name. Student Number : Student Number: University of Cape Town ~ Department of Computer Science Computer Science 1016S / 1011H ~ 2009 November Exam Question

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

CS Exam 1 Review Suggestions

CS Exam 1 Review Suggestions CS 235 - Fall 2015 - Exam 1 Review Suggestions p. 1 last modified: 2015-09-30 CS 235 - Exam 1 Review Suggestions You are responsible for material covered in class sessions, lab exercises, and homeworks;

More information

Chapter 1 GUI Applications

Chapter 1 GUI Applications Chapter 1 GUI Applications 1. GUI Applications So far we've seen GUI programs only in the context of Applets. But we can have GUI applications too. A GUI application will not have any of the security limitations

More information

SINGLE EVENT HANDLING

SINGLE EVENT HANDLING SINGLE EVENT HANDLING Event handling is the process of responding to asynchronous events as they occur during the program run. An event is an action that occurs externally to your program and to which

More information

MIT AITI Swing Event Model Lecture 17

MIT AITI Swing Event Model Lecture 17 MIT AITI 2004 Swing Event Model Lecture 17 The Java Event Model In the last lecture, we learned how to construct a GUI to present information to the user. But how do GUIs interact with users? How do applications

More information

Window Interfaces Using Swing. Chapter 12

Window Interfaces Using Swing. Chapter 12 Window Interfaces Using Swing 1 Reminders Project 7 due Nov 17 @ 10:30 pm Project 6 grades released: regrades due by next Friday (11-18-2005) at midnight 2 GUIs - Graphical User Interfaces Windowing systems

More information

Instruction to students:

Instruction to students: Benha University 2 nd Term (2012) Final Exam Class: 2 nd Year Students Subject: Object Oriented Programming Faculty of Computers & Informatics Date: 20/5/2012 Time: 3 hours Examiner: Dr. Essam Halim Instruction

More information

Review sheet for Final Exam (List of objectives for this course)

Review sheet for Final Exam (List of objectives for this course) Review sheet for Final Exam (List of objectives for this course) Please be sure to see other review sheets for this semester Please be sure to review tests from this semester Week 1 Introduction Chapter

More information

Java Swing. Recitation 11/(20,21)/2008. CS 180 Department of Computer Science, Purdue University

Java Swing. Recitation 11/(20,21)/2008. CS 180 Department of Computer Science, Purdue University Java Swing Recitation 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University Announcements Project 8 is out Milestone due on Dec 3rd, 10:00 pm Final due on Dec 10th, 10:00 pm No classes,

More information

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008 Overview Lecture 7: Inheritance and GUIs Written by: Daniel Dalevi Inheritance Subclasses and superclasses Java keywords Interfaces and inheritance The JComponent class Casting The cosmic superclass Object

More information

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Language Features. 1. The primitive types int, double, and boolean are part of the AP Language Features 1. The primitive types int, double, and boolean are part of the AP short, long, byte, char, and float are not in the subset. In particular, students need not be aware that strings are

More information

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4. 1 - What if the main method is declared as private? 1. The program does not compile 2. The program compiles but does not run 3. The program compiles and runs properly ( From Lectuer # 2) 4. The program

More information

First Name: AITI 2004: Exam 2 July 19, 2004

First Name: AITI 2004: Exam 2 July 19, 2004 First Name: AITI 2004: Exam 2 July 19, 2004 Last Name: Standard Track Read Instructions Carefully! This is a 3 hour closed book exam. No calculators are allowed. Please write clearly if we cannot understand

More information

Interfaces & Polymorphism part 2: Collections, Comparators, and More fun with Java graphics

Interfaces & Polymorphism part 2: Collections, Comparators, and More fun with Java graphics Interfaces & Polymorphism part 2: Collections, Comparators, and More fun with Java graphics 1 Collections (from the Java tutorial)* A collection (sometimes called a container) is simply an object that

More information

In this lab we will practice creating, throwing and handling exceptions.

In this lab we will practice creating, throwing and handling exceptions. Lab 5 Exceptions Exceptions indicate that a program has encountered an unforeseen problem. While some problems place programmers at fault (for example, using an index that is outside the boundaries of

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

Section Basic graphics

Section Basic graphics Chapter 16 - GUI Section 16.1 - Basic graphics Java supports a set of objects for developing graphical applications. A graphical application is a program that displays drawings and other graphical objects.

More information

Rules and syntax for inheritance. The boring stuff

Rules and syntax for inheritance. The boring stuff Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for

More information

CONTENTS. Chapter 1 Getting Started with Java SE 6 1. Chapter 2 Exploring Variables, Data Types, Operators and Arrays 13

CONTENTS. Chapter 1 Getting Started with Java SE 6 1. Chapter 2 Exploring Variables, Data Types, Operators and Arrays 13 CONTENTS Chapter 1 Getting Started with Java SE 6 1 Introduction of Java SE 6... 3 Desktop Improvements... 3 Core Improvements... 4 Getting and Installing Java... 5 A Simple Java Program... 10 Compiling

More information

Java Interfaces Part 1 - Events Version 1.1

Java Interfaces Part 1 - Events Version 1.1 Java Interfaces Part 1 - Events Version 1.1 By Dr. Nicholas Duchon July 22, 2007 Page 1 Overview Philosophy Large Scale Java Language Structures Abstract classes Declarations Extending a abstract classes

More information

COMP1008 Exceptions. Runtime Error

COMP1008 Exceptions. Runtime Error Runtime Error COMP1008 Exceptions Unexpected error that terminates a program. Undesirable Not detectable by compiler. Caused by: Errors in the program logic. Unexpected failure of services E.g., file server

More information

Graphical User Interface (GUI)

Graphical User Interface (GUI) Graphical User Interface (GUI) Layout Managment 1 Hello World Often have a static method: createandshowgui() Invoked by main calling invokelater private static void createandshowgui() { } JFrame frame

More information

CS 11 java track: lecture 3

CS 11 java track: lecture 3 CS 11 java track: lecture 3 This week: documentation (javadoc) exception handling more on object-oriented programming (OOP) inheritance and polymorphism abstract classes and interfaces graphical user interfaces

More information

Tool Kits, Swing. Overview. SMD158 Interactive Systems Spring Tool Kits in the Abstract. An overview of Swing/AWT

Tool Kits, Swing. Overview. SMD158 Interactive Systems Spring Tool Kits in the Abstract. An overview of Swing/AWT INSTITUTIONEN FÖR Tool Kits, Swing SMD158 Interactive Systems Spring 2005 Jan-28-05 2002-2005 by David A. Carr 1 L Overview Tool kits in the abstract An overview of Swing/AWT Jan-28-05 2002-2005 by David

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

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions G51PGP Programming Paradigms Lecture 009 Concurrency, exceptions 1 Reminder subtype polymorphism public class TestAnimals public static void main(string[] args) Animal[] animals = new Animal[6]; animals[0]

More information

1005ICT Object Oriented Programming Lecture Notes

1005ICT Object Oriented Programming Lecture Notes 1005ICT Object Oriented Programming Lecture Notes School of Information and Communication Technology Griffith University Semester 2, 2015 1 20 GUI Components and Events This section develops a program

More information

University of Cape Town Department of Computer Science. Computer Science CSC117F Solutions

University of Cape Town Department of Computer Science. Computer Science CSC117F Solutions University of Cape Town Department of Computer Science Computer Science CSC117F Solutions Class Test 4 Wednesday 14 May 2003 Marks: 40 Approximate marks per question are shown in brackets Time: 40 minutes

More information

Chapter 5: Enhancing Classes

Chapter 5: Enhancing Classes Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions for AP* Computer Science 3rd Edition by John Lewis, William Loftus, and Cara Cocking Java Software Solutions is published by

More information

Java, Swing, and Eclipse: The Calculator Lab.

Java, Swing, and Eclipse: The Calculator Lab. Java, Swing, and Eclipse: The Calculator Lab. ENGI 5895. Winter 2014 January 13, 2014 1 A very simple application (SomeimageswerepreparedwithanearlierversionofEclipseandmaynotlookexactlyasthey would with

More information

Chapter 14. More Swing

Chapter 14. More Swing Chapter 14 More Swing Menus Making GUIs Pretty (and More Functional) Box Containers and Box Layout Managers More on Events and Listeners Another Look at the Swing Class Hierarchy Chapter 14 Java: an Introduction

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

References. Chapter 5: Enhancing Classes. Enhancing Classes. The null Reference. Java Software Solutions for AP* Computer Science A 2nd Edition

References. Chapter 5: Enhancing Classes. Enhancing Classes. The null Reference. Java Software Solutions for AP* Computer Science A 2nd Edition Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition by John Lewis, William Loftus, and Cara Cocking Java Software Solutions is published

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

Programming Languages and Techniques (CIS120e)

Programming Languages and Techniques (CIS120e) Programming Languages and Techniques (CIS120e) Lecture 29 Nov. 19, 2010 Swing I Event- driven programming Passive: ApplicaHon waits for an event to happen in the environment When an event occurs, the applicahon

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

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters. CISC-124 20180215 These notes are intended to summarize and clarify some of the topics that have been covered recently in class. The posted code samples also have extensive explanations of the material.

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

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

RAIK 183H Examination 2 Solution. November 11, 2013

RAIK 183H Examination 2 Solution. November 11, 2013 RAIK 183H Examination 2 Solution November 11, 2013 Name: NUID: This examination consists of 5 questions and you have 110 minutes to complete the test. Show all steps (including any computations/explanations)

More information

Declarations and Access Control SCJP tips

Declarations and Access Control  SCJP tips Declarations and Access Control www.techfaq360.com SCJP tips Write code that declares, constructs, and initializes arrays of any base type using any of the permitted forms both for declaration and for

More information

Recitation 3. 2D Arrays, Exceptions

Recitation 3. 2D Arrays, Exceptions Recitation 3 2D Arrays, Exceptions 2D arrays 2D Arrays Many applications have multidimensional structures: Matrix operations Collection of lists Board games (Chess, Checkers) Images (rows and columns of

More information

Casting -Allows a narrowing assignment by asking the Java compiler to "trust us"

Casting -Allows a narrowing assignment by asking the Java compiler to trust us Primitives Integral types: int, short, long, char, byte Floating point types: double, float Boolean types: boolean -passed by value (copied when returned or passed as actual parameters) Arithmetic Operators:

More information

CS 201 Advanced Object-Oriented Programming Lab 6 - Sudoku, Part 2 Due: March 10/11, 11:30 PM

CS 201 Advanced Object-Oriented Programming Lab 6 - Sudoku, Part 2 Due: March 10/11, 11:30 PM CS 201 Advanced Object-Oriented Programming Lab 6 - Sudoku, Part 2 Due: March 10/11, 11:30 PM Introduction to the Assignment In this lab, you will finish the program to allow a user to solve Sudoku puzzles.

More information

encompass a group of features for building Graphical User Interfaces (GUI).

encompass a group of features for building Graphical User Interfaces (GUI). Java GUI (intro) JFC Java Foundation Classes encompass a group of features for building Graphical User Interfaces (GUI). javax.swing.* used for building GUIs. Some basic functionality is already there

More information

GUI and its COmponent Textfield, Button & Label. By Iqtidar Ali

GUI and its COmponent Textfield, Button & Label. By Iqtidar Ali GUI and its COmponent Textfield, Button & Label By Iqtidar Ali GUI (Graphical User Interface) GUI is a visual interface to a program. GUI are built from GUI components. A GUI component is an object with

More information

H212 Introduction to Software Systems Honors

H212 Introduction to Software Systems Honors Introduction to Software Systems Honors Lecture #19: November 4, 2015 1/14 Third Exam The third, Checkpoint Exam, will be on: Wednesday, November 11, 2:30 to 3:45 pm You will have 3 questions, out of 9,

More information

Introduction to Graphical Interface Programming in Java. Introduction to AWT and Swing

Introduction to Graphical Interface Programming in Java. Introduction to AWT and Swing Introduction to Graphical Interface Programming in Java Introduction to AWT and Swing GUI versus Graphics Programming Graphical User Interface (GUI) Graphics Programming Purpose is to display info and

More information

CS506 Web Programming and Development Solved Subjective Questions With Reference For Final Term Lecture No 1

CS506 Web Programming and Development Solved Subjective Questions With Reference For Final Term Lecture No 1 P a g e 1 CS506 Web Programming and Development Solved Subjective Questions With Reference For Final Term Lecture No 1 Q1 Describe some Characteristics/Advantages of Java Language? (P#12, 13, 14) 1. Java

More information

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written. QUEEN'S UNIVERSITY SCHOOL OF COMPUTING HAND IN Answers Are Recorded on Question Paper CISC124, WINTER TERM, 2012 FINAL EXAMINATION 9am to 12pm, 26 APRIL 2012 Instructor: Alan McLeod If the instructor is

More information

Topic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations

Topic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations Topic 6: Exceptions Exceptions are a Java mechanism for dealing with errors & unusual situations Goals: learn how to... think about different responses to errors write code that catches exceptions write

More information

First Name: AITI 2004: Exam 2 July 19, 2004

First Name: AITI 2004: Exam 2 July 19, 2004 First Name: AITI 2004: Exam 2 July 19, 2004 Last Name: JSP Track Read Instructions Carefully! This is a 3 hour closed book exam. No calculators are allowed. Please write clearly if we cannot understand

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

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

What is Widget Layout? Laying Out Components. Resizing a Window. Hierarchical Widget Layout. Interior Design for GUIs

What is Widget Layout? Laying Out Components. Resizing a Window. Hierarchical Widget Layout. Interior Design for GUIs What is Widget Layout? Laying Out Components Positioning widgets in their container (typically a JPanel or a JFrame s content pane) Basic idea: each widget has a size and position Main problem: what if

More information

CS 180 Final Exam Review 12/(11, 12)/08

CS 180 Final Exam Review 12/(11, 12)/08 CS 180 Final Exam Review 12/(11, 12)/08 Announcements Final Exam Thursday, 18 th December, 10:20 am 12:20 pm in PHYS 112 Format 30 multiple choice questions 5 programming questions More stress on topics

More information

Building a GUI in Java with Swing. CITS1001 extension notes Rachel Cardell-Oliver

Building a GUI in Java with Swing. CITS1001 extension notes Rachel Cardell-Oliver Building a GUI in Java with Swing CITS1001 extension notes Rachel Cardell-Oliver Lecture Outline 1. Swing components 2. Building a GUI 3. Animating the GUI 2 Swing A collection of classes of GUI components

More information

CS 3331 Advanced Object-Oriented Programming Final Exam

CS 3331 Advanced Object-Oriented Programming Final Exam Fall 2015 (Thursday, December 3) Name: CS 3331 Advanced Object-Oriented Programming Final Exam This test has 5 questions and pages numbered 1 through 10. Reminders This test is closed-notes and closed-book.

More information

Do not turn to the next page until the start of the exam.

Do not turn to the next page until the start of the exam. Principles of Java Language with Applications, PIC20a E. Ryu Winter 2017 Final Exam Monday, March 20, 2017 3 hours, 8 questions, 100 points, 11 pages While we don t expect you will need more space than

More information

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling Course Name: Advanced Java Lecture 5 Topics to be covered Exception Handling Exception HandlingHandlingIntroduction An exception is an abnormal condition that arises in a code sequence at run time A Java

More information

Graphical Interfaces

Graphical Interfaces Weeks 11&12 Graphical Interfaces All the programs that you have created until now used a simple command line interface, which is not user friendly, so a Graphical User Interface (GUI) should be used. The

More information

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong: Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception Ariel Shamir 1 Run-time Errors Sometimes when the computer

More information

Multiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks)

Multiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks) M257 MTA Spring2010 Multiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks) 1. If we need various objects that are similar in structure, but

More information

Eclipsing Your IDE. Figure 1 The first Eclipse screen.

Eclipsing Your IDE. Figure 1 The first Eclipse screen. Eclipsing Your IDE James W. Cooper I have been hearing about the Eclipse project for some months, and decided I had to take some time to play around with it. Eclipse is a development project (www.eclipse.org)

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

Hanley s Survival Guide for Visual Applications with NetBeans 2.0 Last Updated: 5/20/2015 TABLE OF CONTENTS

Hanley s Survival Guide for Visual Applications with NetBeans 2.0 Last Updated: 5/20/2015 TABLE OF CONTENTS Hanley s Survival Guide for Visual Applications with NetBeans 2.0 Last Updated: 5/20/2015 TABLE OF CONTENTS Glossary of Terms 2-4 Step by Step Instructions 4-7 HWApp 8 HWFrame 9 Never trust a computer

More information