1 / 91

Chapter 9 Improving the User Interface

Chapter 9 Improving the User Interface. Go. Section 1 - Query Controlled Programs Section 2 - Menu Controlled Programs Section 3 - Introduction to Try-Catch Statements Section 4 - GUI Driven Programs Section 5 - Printf and String.format Statements

africa
Download Presentation

Chapter 9 Improving the User Interface

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 9Improving the User Interface Go Section 1 - Query Controlled Programs Section 2 - Menu Controlled Programs Section 3 - Introduction to Try-Catch Statements Section 4 - GUI Driven Programs Section 5 - Printf and String.format Statements Section 6 - Processing Numerous ActionListeners Go Go Go Go Go 1

  2. Chapter 9 Objectives • Design a query-controlled program. • Design a menu-controlled program. • Understand the model-view program design • Write try-catch and throw statements for error processing • Design a graphical user interface for an Applet program. • Understand the model-view-controller program design • Format output text for a GUI program using System.format 2

  3. Section 1Query Controlled Programs 3

  4. // The Thermometer model class. • publicclass Thermometer • { • privatedoubledegreesCelsius; • // Java will provide a default constructor! • publicdouble getCelsius() • { • returndegreesCelsius; • } • publicdouble getFahrenheit() • { • returndegreesCelsius * 9.0 / 5.0 + 32.0; • } • publicvoid setCelsius(double degrees) • { • degreesCelsius = degrees; • } • publicvoid setFahrenheit(double degrees) • { • degreesCelsius = (degrees - 32.0) * 5.0 / 9.0; • } • } // end of class 9.1 A Thermometer Class This is a model class that we will be using in a number of demo programs in this chapter. 4

  5. We have studied count-controlled loops (entering data inside a for loop a prescribed number of times) and sentinel-controlled loops (entering data until a sentinel value is entered, like -1) and also query-controlled loops that ask the user if they want to run a loop another time and they answer either “yes” or “no”. Here is the sample output of a new program named ConvertWithQuery_9_1. 9.1 Query Controlled Programs 5

  6. 9.1 Repeating Sets of Inputs • The Query Program is implemented by two classes: • The View class ConvertWithQuery_9_1 (the driver) • The Model class Thermometerthat models a Thermometer object. • Did you notice that the Thermometer class has only one instance variable, degreesCelsius. • If the fahrenheit equivalent is needed it is returned by the accessor method getFahrenheit(). 6

  7. publicclass ConvertWithQuery_9_1 • { • publicstaticvoid main(String [] args) • { • Scanner reader = new Scanner(System.in); • Thermometer thermo = new Thermometer(); • String doItAgain = “y”; • while (doItAgain.equals(“y”) || doItAgain.equals(“Y”)) • { • System.out.print(“\nEnter degrees Fahrenheit: ”); • double fahr = reader.nextDouble(); • thermo.setFahrenheit(fahr); • reader.nextLine(); // Consume the trailing end of line • System.out.println(“The equivalent in Celsius is ” + thermo.getCelsius()); • System.out.print(“\nDo it again (y/n)?”); • doItAgain = reader.nextLine(); • } • } • } 9.1 ConvertWithQuery_9_1 Driver Program 7

  8. 9.1 ConvertWithQuery_9_1 Program Let’s stop and run the program ConvertWithQuery_9_1.java with …. the model class Thermometer.java and the view class ConvertWithQuery_9_1.java ConvertWithQuery_9_1 view class Thermometer model class The driver class is ConvertWithQuery_9_1.java and it is also the view class. This class calls methods of the model class, Thermometer. 8

  9. Section 2Menu Controlled Programs 9

  10. 9.2 Form of Menu Controlled Programs In amenu-driven program, a list of options are displayed for the user so an operation can be selected to perform. Once the operation is complete, the program redisplays the menu so another operation can be selected. One of the operations always available is to quit the program. The run of a sample menu controlled program is shown on the next slide. 10

  11. 1) Convert from Fahrenheit to Celsius 2) Convert from Celsius to Fahrenheit 3) Quit Enter your option: 1 Enter degrees Fahrenheit: 32 The equivalent in Celsius is 0.0 1) Convert from Fahrenheit to Celsius 2) Convert from Celsius to Fahrenheit 3) Quit Enter your option: 2 Enter degrees Celsius: 100 The equivalent in Fahrenheit is 212.0 1) Convert from Fahrenheit to Celsius 2) Convert from Celsius to Fahrenheit 3) Quit Enter your option: 9.2 ConvertWithMenu_9_2 Program Output Sample program run of the menu controlled program namedConvertWithMenu_9_2 11

  12. menuOption = 4; // prime the loop to start • while (menuOption != 3) • { • System.out.print(menu); // Display the menu and get the user's option • menuOption = reader.nextInt(); • System.out.println (); • if (menuOption == 1) • { • System.out.print("Enter degrees Fahrenheit: "); • double farh = reader.nextDouble(); • thermo.setFahrenheit(fahr); • System.out.println ("The equivalent in Celsius is " + thermo.getCelsius()); • } • elseif (menuOption == 2) • { • System.out.print("Enter degrees Celsius: "); • double celsius = reader.nextDouble(); • thermo.setCelsius(celsius); • System.out.println ("The equivalent in Fahrenheit is " + thermo.getFahrenheit()); • } • elseif (menuOption == 3) • System.out.println("Goodbye!"); // this selection ends the loop • else • System.out.println ("Invalid option"); // Invalid option; re-enter option • } 9.2 ConvertWithMenu_9_2 Code 12

  13. 9.2 ConvertWithMenu_9_2 View Program Let’s stop and run the program ConvertWithMenu_9_2.java with …. the model class Thermometer.java and the view class ConvertWithMenu_9_2.java ConvertWithMenu_9_2 view class Thermometer model class The driver class is ConvertWithMenu_9_2.java and it is also the view class. This class calls methods of the model class, Thermometer. 13

  14. Section 3Try - Catch StatementsAllowing Programs toGracefully Continue 14

  15. 9.3 Handling Number Format Exceptions To this point, if data input is of the wrong type, a program will throw an exception and display an error message in the terminal window and halt the program. (An applet program may just do nothing in response to invalid data and you wouldn’t know there is a problem.) What we really want is for a program to identify invalid data and output an error message, but then allow the program to runwithout crashing it. 15

  16. 9.3 Handling Number Format Exceptions In a console program where we are asking for numeric input and characters other than numeric digits are entered from the keyboard, then the program will crash unless the code is embedded within a try-catch statement. Methods like nextInt() and nextDouble() actually implicitly (behind the scene) parse the data input from the keyboard when using a Scanner object. However, if the data is not numeric, then an exception will be thrown by the program and it will be halted … unless the reader.nextInt() or reader.nextDouble() is imbedded in a try-catch statement. 16

  17. Programmers write the code in the try clause (branch) that they need in a program to call various operations. If one of the operations fails and an exception is thrown - “it will be caught” and the catch clause (branch) will be executed and an error message displayed. try { // code here that has the possibility of throwing an exception } catch (Exception e) { // error message here that describes the exception } 9.3 General Form of a Try-Catch Statement 17

  18. Statements within a try branch are executed until an exception is thrown or all statements are executed. If an exception is thrown, execution is immediately sent to the catch branch, skipping the remainder of any code in the try branch. try { System.out.print("Enter degrees Fahrenheit: "); double fahr = reader.nextDouble(); thermo.setFahrenheit(fahr); System.out.println("The equivalent Celsius is " + thermo.getCelsius()); } catch (Exception e) { System.out.println(“Bad Number Format! You did not input a number.”); } 9.3 Try-Catch Statement Example 18

  19. 9.3 Handling Number Format Exceptions If no statement throws an exception within the try clause, the catch clause is skipped. Many types of exceptions can be thrown. There is an Exception class that is at the top of a hierarchy for all exception types. Catching an Exception object will catch any of them. However, it is better to be specific about the kind of exception when you can. For example, you may want a program to output the error message “divide by zero error” if an exception is thrown. So it would be better to use an ArithmeticException. 19

  20. Let’s stop and run the program ConvertWithQuery_9_3.java and see how a try-catch statement can provide error checking and allow a program to “gracefully continue”. We’ll use …. the model class Thermometer.java and the view class ConvertWithQuery_9_3.java 9.3 ConvertWithQuery_9_3 Program ConvertWithQuery_9_3 view class Thermometer model class The driver class is ConvertWithQuery_9_3.java and it is also the view class. This class calls methods of the model class, Thermometer. 20

  21. 9.3 Original getScore method of Student Class This method trusts whoever calls this method to pass it a correct value, either a 1, 2, or 3, since there are only 3 tests for a Student object. Remember the code for the getScore method of the Student class. It looked like this. publicint getScore (int i) { if (i == 1) returntest1; elseif (i == 2) returntest2; else returntest3; } Programmers build in their own kind of error messages into code like this by writing “throw” statements in their methods . (See next slide) 21

  22. 9.3 Modified getScore method of Student Class Here is an example of how to add a Java “throw” statement to a method like getScore and change its method signature: publicint getScore (int i) throws IOException { if ( i < 1 | | i > 3 ) thrownewIOException(“Test number out of range. Must be 1, 2, or 3”); if (i == 1) returntest1; elseif (i == 2) returntest2; else returntest3; } To be able to use a throw statement with IOException you must import the following: import java.io.IOException; 22

  23. In some other file, (other than Student.java) we could then call the getScore method in a try-catch statement as follows: try { Student s1 = new Student(“Ann”, 95, 88, 92); System.out.print(“Which test score do you want? ”); int whichTestScore = reader.nextInt(); int testScore = s1.getScore(whichTestScore )); System.out.println("The test score is: ” + testScore); } catch (Exception e) { System.out.println(e); } 9.3 Calling getScore in a Try-Catch Statement Note: if the user enters some integer other than 1, 2, or 3, then the error message from the throw statement in the method “Test number out of range. Must be 1, 2, or 3”comes back in the parameter e and is printed by the System.out.println statement. 23

  24. 9.3 Throw Statement Specify Errors More Clearly Writing throw statements in methodshelps clarify the errors that occur in a program. If a user enters a String, the error message still makes sense and instructs the user what he or she should do. publicint getScore (int i) throws IOException { if ( i < 1 | | i > 3 ) thrownewIOException(“Test number out of range. Must be 1, 2, or 3”); if (i == 1) returntest1; elseif (i == 2) returntest2; else returntest3; } 24

  25. 9.3 When to Write a Throw Statement In conclusion, if you are writing a method that has the possibility of failing based on user input, then you can include a throw statement in your method like the one in getScore. However, if you don’t have access to the code of the method, then you can write an appropriate error message in the catch clause so it is printed instead of printing e. catch (Exception e) { System.out.println(“Error! Your input is out of range!”); } instead of catch (Exception e) { System.out.println(e); } 25

  26. Section 4GUI Driven Programs 26

  27. 9.4 GUI programs are event-driven • GUI programs are event-driven. • when a program opens, it waits for events • Events are generated when the user interacts with the GUI by …. • entering data in text fields • clicking buttons • making selections from menus or other GUI components. • Events invoke controller classes, which in turn invoke model classes. 27

  28. 9.4 GUI Programs In many ways, GUI programs providemore user-friendly interaction with a program. However, some GUI components are more user-friendly than others. JOptionPane boxes, like we have used previously, can be limiting and tedious to use if a lot of input needs to be entered. A JTextField is one GUI component that is easier to use than a JOptionPane box. We are going to examine and use the basic components in many GUI programs … JLabels, JTextFields, JButtons, and JTextAreas. We will also look at the basic ways of controlling the placement of GUI components using border, flow, and gridlayouts. 28

  29. 9.4 ConvertWithGUI_9_4 Applet Program Title only available for JFrame programs not Applet programs. JLabels JTextFields JButton - note a button can have a name or label on it that isn’t a JLabel The User Interface components of the GUI-based temperature conversion program 29

  30. 9.4 The JLabel Component JLabelsprovide labeling of other GUI components, but primarily labeling or identifying JTextFields. They may be located anywhere near the component they are identifying, above, below, to the left, or to the right of a component. The choice is up to the user and is only limited by the demands of the particular kind of layout that is being implemented. Placing JLabels near JTextFields helps the user understand what the JTextFields are for. 30

  31. 9.4 The JTextField Component JTextFieldsallow for the input of data into a GUI program, but also allow for output of data. After data is entered into a JTextField, if a button is clicked or a menu item selected, then the data can be received and processed. All input from a JTextField must be processed first as String data.If the string data is numeric, it can then be processed using parsing. A program can have any number of JTextFields and each can be set up to receive or display different sets of data in a GUI program. 31

  32. 9.4 The JButton Component JButtonsallow for controlling events in a GUI program. As we just mentioned on the last slide, after data is entered into a JTextField, if a button is clicked, then the data can be received and processed. All JButtons in a program have “listeners” so that the events specified by the program can take place when the buttons are clicked. A program can have any number of JButtons with each button designated to process one of the specific events in the GUI program. 32

  33. 9.4 The JTextArea Component JTextAreasalso allow for the entry of data into a GUI program, but are mostly used for the output of data. JTextAreas are usually more appropriate for outputting data in a GUI program than JTextFields, because they provide more area for output to be displayed in. Many times more than just a single number or single word needs to be displayed or you want to display data in columns. It is possible to concatenate String and numeric output in JTextAreas and then format it using the String.format()method, which is similar toSystem.out.printf. A program can have any number of JTextAreas each with a designated purpose within a GUI program. 33

  34. 9.4 The ConvertWithGUI_9_4 View Class • ConvertWithGUI_9_4 is the main view class and it will … • construct and maintain a variable to a Thermometer object. The Thermometer class is the model class. • construct and maintain variables for JLabels, JTextFields, and a JButton and add these GUI components to the window’s container. • construct and attach a FahrenheitListener object to the JButton. • provide a private inner class named FahrenheitListener that is the controller class for the program. This program is a GUI Driven applet program. 34

  35. publicclass ConvertWithGUI_9_4 extends JApplet • { • // >>>>>>> The model <<<<<<<< • // Declare and instantiate the thermometer • Thermometer thermo = new Thermometer(); • // >>>>>>> The view <<<<<<<< • // Declare and instantiate the window objects. • JLabel titleLabel = new JLabel("Temperature Converter Applet"); • JLabel fahrLabel = new JLabel(" Degrees Fahrenheit"); • JLabel celsiusLabel = new JLabel(" Degrees Celsius"); • JTextField fahrField = new JTextField("32.0"); • JTextField celsiusField = new JTextField("0.0"); • JButton fahrButton = new JButton("Convert >>>"); • JButton celsiusButton = new JButton("<<< Convert"); 9.4 The ConvertWithGUI_9_4 View Code Here we construct the Thermometer object for the program and all of the GUI components. They are all global and are declared and constructed immediately after the class definition. Initial Code of ConvertWithGUI_9_4.java 35

  36. Here is a representation of a BorderLayout. The largest region is the Center region, so that is where you usually place the panel with the most components. The other four regions will become larger as components are added to them. You don’t have to use any region. 9.4 BorderLayout With Five Regions We will put our GUI components in panels and then add them to the regions we want to use. north region center region east region west region south region 36

  37. public void init () • { • // declare title panel and add components • JPanel titlePanel = new JPanel(); • titlePanel.add(titleLabel); • // declare data panel and add components • JPanel dataPanel = new JPanel(new GridLayout(2, 2, 12, 6)); • dataPanel.add(fahrLabel); • dataPanel.add(celsiusLabel); • dataPanel.add(fahrField); • dataPanel.add(celsiusField); • // declare button panel and add components • JPanel buttonPanel = new JPanel(); • buttonPanel.add(fahrButton); • // set up container and add panels • Container container = getContentPane(); • container.add(titlePanel, BorderLayout.NORTH); • container.add(dataPanel, BorderLayout.CENTER); • container.add(buttonPanel, BorderLayout.SOUTH); • // Attach a listener to the convert button • fahrButton.addActionListener(new FahrenheitListener()); • } 9.4 The ConvertWithGUI_9_4 View Code The init method for the program creates panels for the components and then adds them to the panels. It also establishes the placement of the panels in the BorderLayout. It finally, adds a listener to the JButton. 37

  38. 9.4 ConvertWithGUI_9_4 Applet Program titlePanel in NORTH dataPanel in CENTER buttonPanel in SOUTH For this applet, only the north, center, and south regions of the BorderLayout are used. Each of these regions contains a panel and each of the panels contains one or more components. 38

  39. When the user clicks the Convert button, the following code is executed. • // >>>>>>> The controller <<<<<<<< • privateclassFahrenheitListenerimplements ActionListener • { • publicvoid actionPerformed(ActionEvent e) • { • String input = fahrField.getText();// Obtain input • double fahr = Double.parseDouble(input); // Convert to double • thermo.setFahrenheit(fahr); // Reset thermometer • double celsius = thermo.getCelsius(); // Obtain Celsius • celsiusField.setText("" + celsius); // output result • } • } 9.4 The Private Inner Listener Controller Class The private inner listener class must implement ActionListener and needs only one method … the actionPerformed() method. 39

  40. 9.4 The getText() JTextField Method The JTextField class has a number of important methods. One of the most important is the getText() method that retrieves what has been entered into a JTextField, like fahrField, as a String. If by program design the value is intended to be a number, then it must be parsed to the type of number that is expected. After it is parsed it can be used as needed in the program. 40

  41. 9.4 The setText() JTextField Method The setText() method erases everything in a JTextField and then places a String value back in it. If the value is a number, it must be first converted to a String. Remember this code that draws the number 10 with g … g.drawString( "" + 10, 100, 100 ); To convert 10 to a String, we had to concatenate it to empty string. The same thing is being done with the line of code: celsiusField.setText("" + celsius); It converts the number stored in celsius to a String before placing the String in the JTextField. 41

  42. The most important JTextField and JTextArea methods are: 9.4 The JTextField and JTextArea Methods 42

  43. Many times we may want to have a JTextField or JTextArea that is only for displaying output and we don’t want the user to be able to delete or edit any of the information. This is where we can use the setEditable() method. Let’s say we have the following JTextArea declared: JTextArea output = new JTextArea (); output.setEditable(false); Programmers make JTextAreas un-editable more often than JTextFields.Typically, JTextFields are used for input and JTextAreas are used for output. 9.4 Using The setEditable Method 43

  44. You can use requestFocus with either a JTextField or JTextArea, however, since users aren’t usually typing in a JTextArea it doesn’t make sense to request the focus for that component. We use requestFocus when we want to save the user effort by placing the mouse cursor in an obvious place where something needs to be entered for input. So, if you have a JTextField variable named fahrFld and you have declared and instantiated it in a GUI program, then when it loads you can make the cursor go immediately to fahrFld, without the user clicking the mouse in the JTextField, by using the line of code: fahrFld.requestFocus(); However, there are times when this method doesn’t seem to work. 9.4 Using The requestFocus Method 44

  45. 9.4 JTextField ActionListeners After entering data into a JTextField named fahrFld , if you want the input to be processed by pressing the “enter” or “return” key on your keyboard without clicking a GUI button, you can add an action listener to the JTextField variable. fahrFld.addActionListener(new FahrenheitListener()); If you have a private inner class already defined named FahrenheitListener that you are using for a button, then you simply add an anonymous call to the class constructor as the parameter for the addActionListener ( ) method as seen above. 45

  46. 9.4 Model-View-Controller Pattern • The model-view/controllerpattern is used by most programmers as a way to consistently divide the responsibility of different parts of an application between the different classes in an organized manner. • Model: The data that the program uses and the operations that can be performed on that data. In this program, the Thermometer class serves as the model. • View: What the user of the program interacts with. In this program, the ConvertWithGUI_9_4 class contains the view and sets up the model. • Controller: Usually a private inner listener class that coordinates model and view classes by passing messages and data between them. In this program the controller is the private inner listener class FahrenheitListener. • Driver: Since ConvertWithGUI_9_4 is an applet class it acts as a driver. It is the file you compile to run the program. 46

  47. 9.4 Variations of Model-View-Controller • Finally, GUI programs that are just JFrame programs are meant to be stand-alone programs that will not appear in a web page and may include the following files: • model classes • a view class • a private inner class that is a listener • an application class or driver class that starts the program • However, applet programsusually combine the view class and are the driver so that many times you have only the following files: • model classes • a view class that is also a driver class • a private inner class that is a listener 47

  48. 9.4 Variations of Model-View-Controller Note: it is possible for JFrame orapplet programsboth to have only one file. A file that contains both of the following: • a view class that is also a driver class that doesn’t use a model class • a private inner class that is a listener GUI programs like these do not use a model class and may just contain methods that do mathematical calculations or process data in a way such that a model class is not needed. In this case, everything is stored in one file. This will be the case when you work on the PI_Approximator GUI program. 48

  49. 9.4 Handling Exceptions in a GUI Program In GUI programs, we have to actually explicitly perform the parsing of input with lines of code that use parseInt() and parseDouble(), since a user on the internet would not be able to see any exception errors in a terminal window. To allow a GUI or terminal program to continue, we can place our lines that parse the input insidetry-catch statements. The try-catch statement allows exceptions to be caught and handled appropriately. 49

  50. Here a try-catch statement is used to process the input from a GUI program. Notice the input has to be parsed to make sure the input is of type double. If it is not parsed, an exception will be thrown. try { String input = fahrField.getText(); // get the input from a GUI field double fahr = Double.parseDouble(input);// parse the input to a double … // other code } catch (Exception e) { System.out.println(“Bad Number Format!”); } More about this on the next slide … 9.4 Number Format Exceptions in a GUI 50

More Related