Arrays, Exception Handling, Interfaces, Introduction To Swing
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.
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
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.
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] );
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;
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( 1000000 ); int min = getsmallest( iarr ); System.out.println( min );... continued on next slide
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;
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() ;
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?
Exceptions When an exceptional circumstance arises java can respond by throwing an exception. Exceptions are usually, but not always, associated with error processing.
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)
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
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;
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 );
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 )...
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" );
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" );
Creating Your Own Exceptions You can define your own exceptions, usually by extending Exception: // OpCanceledException.java public class OpCanceledException extends Exception
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;
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.
Interfaces
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();
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.
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
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.";
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.
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.
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.
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 );
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 );
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 )...
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
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
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.
Window Adaptor, Example public class EventsIntro2 extends WindowAdapter public void windowopened(windowevent event ) System.out.println( "Window opened" ); continued on next slide
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 );
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.
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.
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" );
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 );
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.
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 );
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 );
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?
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 );
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
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 );
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.
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.
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
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
continued JPanel Example Panel1; FlowLayout() Content Pane; GridLayout( 2, 1 ) Panel2; GridLayout( 4, 2 )
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
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
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) ) );
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 )
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
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.
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
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 );
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
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
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
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
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
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
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
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" ) );
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
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 );...
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
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;...
ActionTurtleFrame (3) ActionTurtleFrame has two constructors that provide a title for the frame:... public ActionTurtleFrame() super( "Action Turtle!" ); public ActionTurtleFrame( String title ) super( title );...
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
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 );
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
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
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
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 );
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
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 );
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
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 );
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.