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 Using Swing Components Summary and Homework Java Programming - L6... 2/32
Dialog Boxes Output Dialog Boxes Parsing the Input String Example: Popup Java Programming - L6... 3/32
Input Dialog Boxes String s = JOptionPane.showInputDialog ( ".."); We call the showinputdialog() function of the class JOptionPane class and supply the message that the dialog box will display. A dialog box pops up in the center of the screen. It displays our message, followed by a white area in which the user is supposed to type an input. This input is delivered to your program in the form of a string, not a number. Java Programming - L6... 4/32
Output Dialog Boxes JOptionPane.showMessageDialog (null, "..."); We call the showmessagedialog() function of the class JOptionPane class and supply the message that the dialog box will display. A dialog box pops up in the center of the screen. It displays our message. The form and contents of this window are the default style for JOptionPane. To close the window, press the OK button. Java Programming - L6... 5/32
Parsing the Input String When we use a Scanner, it parses the input stream for us, and handles number conversion and input errors. If you use a dialog box, however, this work must be done by your own code. It is like reinventing the wheel. Java had dialog boxes many years ago. Many people complained about Java being a primitive language, unsuitable for beginners. The Scanner class was introduced in Java 5. An input dialog box delivers the input to your program in the form of a string. Use parseint() to analyze the string and do the ASCII-to-integer conversion. It will throw an exception if the string is not a legal integer. Java Programming - L6... 6/32
Purpose of Derivation Class derivation is used in Java and other OO languages for several purposes: Hooking into the power of a pre-existing system like Swing: your program 6. Polymorphic data: A basic data class, with variations. Demo: Jack-O-Lantern Reusable code: The existing class is almost what you want, but not quite. We will see this when we get to adapter classes. Java Programming - L6... 7/32
What is Derivation? A new class is defined by saying what it has or does that is slightly different from an existing class. The keyword is extends The existing class is the base class, or superclass. The new class is the derived class or subclass. A subclass object has ALL the properties of the original class, plus those it defines. Even though the subclass object HAS those members, private members of the base class are not visible to it. When you create a class that is intended as a base class, you often declare some of its members to be protected. Protected members are visible to derived classes but are otherwise like private members. Java Programming - L6... 8/32
Derivation Example Suppose you are writing a payroll program for a company with three kinds of employees: Salaried, Hourly, and Contractor. Employee would be the base class, with these members, inherited by all subclasses: Name, payrate, and other basic info. A constructor and tostring function. A pay() function that does basic operations common to all employees. The Salaried class would extend Employee and add one member: A pay() function that uses the right formula for salaried employees. An hourly employee would have additional members to deal with overtime, and another method for tostring(). Java Programming - L6... 9/32
Derived Classes Inherit Members This is a polymorphic data class. base class derived class Employee Salaried employee Hourly employee name payrate name payrate Contractor hoursworked Salaried Hourly Java Programming - L6... 10/32
Using a Pre-existing System Class derivation is used in Java to allow users to use Swing without understanding it or being able to create it. We start by extending JFrame and giving it a layout. We then add panels or objects derived from the Panel class. Widgets and artwork go inside the panels. Everything we use in a Swing window is either An instance of a predefined Java class. An instance of a class derived from a predefined Java class. When we make window applications, we are always dealing with something we can t see and don t fully understand. We do it by learning a few simple rules! Java Programming - L6... 11/32
Deriving from JFrame Swing JFrame can contain JPanel Lantern can contain Canvas Canvas3 Canvas2 Canvas4 Java Programming - L6... 12/32
Why do we need Derivation? We use Java s GUI libraries by extending the pre-defined classes. To make an application with a window, we extend JFrame To put buttons or dialog boxes in part of the window, we extend JPanel Java is organized this way so that we can use the windowing toolkit without understanding (or even seeing) all the complex things that are inside it. When we make window applications, we are always dealing with something we can t see and don t fully understand. We do it by learning a few simple rules! Java Programming - L6... 13/32
The First Swing Programs Snow: JFrames, windows, fonts, color. Moving: JFrames, windows, fonts, color, size and position. Window events. Smile: RGB colors, button events. Java Programming - L6... 14/32
Moving What is going on here? The number increases whenever the window is repainted. The window is repainted when it is resized. The system does window management, but calls the application s paint() function as part of the process of repainting the window. The window is repainted when you minimize it and when you expand it again. Nothing happens when you move or click the mouse, unless you are resizing the window. Nothing happens when you move the window without resizing. Java Programming - L6... 15/32
How Moving Works When you resize the window, That generates an event. The event is handled (like an exception is handled) in the event thread. The proper handler (in this case, the default) for this kind of event is called and runs. It calls your paint function, which calls the JFrame s paint function. You see the screen repainted. Java Programming - L6... 16/32
Creating Colors The Colors class is in the package java.awt. The predefined Colors are black, blue, cyan, darkgray, gray, green, lightgray, magenta, orange, pink, red, white, yellow. UPPER CASE also works: BLACK, BLUE, DARK_GRAY, LIGHT_GRAY, YELLOW, etc. You can and should create your own colors. Color lilac = new Color (100, 100, 200); Colors are specified in the RGB coordinate system (0, 0, 0) is black. (128, 128, 128) is medium gray. (255, 255, 255) is white. Java Programming - L6... 17/32
Creating Fonts You can and should create your own fonts. Font myfont = new Font("serif", Font.BOLD+Font.ITALIC, 24); Choose style, face, and size: Serif (with hats and shoes), SansSerif (bare) and Monospaced (fixed-width) Alternative names are: Times, Helvetica and Arial, Courier. Choose any reasonable size. Bold, plain, italic or bold-italic. The default font is SansSerif, Plain, size 12. Java Programming - L6... 18/32
Using Fonts Use the setfont and setcolor functions: g.setfont(myfont); g.setcolor(color.magenta); When you draw a string, it will be displayed in the current font and color, and at the given (x,y) screen coordinates. g.drawstring(message, 0, 36); Java Programming - L6... 19/32
The Second Swing Program: Smile JFrames, JPanels, and the graphics window Widgets: JButton, JLabel, JTextbox The placement of widgets in panels. Layouts Shapes: Rectangle, Oval Java Programming - L6... 20/32
Swing Components Application vs. Applet An application has a main function. An applet does not it has an init() function instead. An application runs in an IDE or in a command window. An applet is run by running an.html file in a browser. Some IDEs make it easy to test applets, others don t. In a graphics application, the main function must create a new object that extends JFrame.. Smile S = new Smile(); It is helpful to set the window closing operation, also: S.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Java Programming - L6... 21/32
Swing Components Frames and Panels The main Swing window is a JFrame. It wraps, organizes, and controls a set of panels within it. You can put JPanels inside the JFrame to hold and organize other widgets. One frame may have many JPanels. They are arranged according to a layout. JPanels also have layouts, which are used to organize the smaller panels within. For a JFrame, the default layout is BorderLayout. Java Programming - L6... 22/32
Swing Components Layouts Elements are placed into a JFrame or JPanel according to its current layout. The simplest layouts are: BorderLayout: Panels can go on any edge or in the center. Positions are called North, South, East, West, and Center, and can be written two ways: BorderLayout.NORTH or "North". FlowLayout: Add elements left to right until the width is filled, then start another line. GridLayout( r, c): A matrix with r rows and c columns, which is filled left to right and top to bottom. There are many other layouts, with tabs, cards, and much more. Java Programming - L6... 23/32
Swing Components Widgets A widget is an element, large or small, complex or simple, that you might put into a graphics window. The basic Swing widgets are: JPanel: A container to organize other widgets. JButton: Click it to cause some action. JTextField: a box into which the user can enter input. JLabel: The label for a text field. JTextArea: A big output box able to hold several lines of data. JCheckBox: a box for entering a boolean off/on input. JRadioButton: one of a set of mutually-exclusive off/on elements. These are organized into ButtonGroups. Java Programming - L6... 24/32
Using Swing Components To Create a JFrame In your main() function: 1. Declare and create the app window: Smile s = new Smile(); 2. Set the app to terminate when the window is closed: s.setdefaultcloseoperation(jframe.exit_on_close); Java Programming - L6... 25/32
Using Swing Components To Customize and Use your JFrame In your JFrame-class constructor: 1. Give the window a title: super("smile"); 2. Control its position and size: setbounds( x, y, width, height); 3. Grab the graphics area: Container pane = getcontentpane(); 4. Change the layout if you don t want a BorderLayout. 5. Add components to the graphics area: pane.add(p1, "North"); 6. Make the window visible: setvisible(true); Java Programming - L6... 26/32
Using Swing Components To Use a Panel 1. Declare and create it: private JPanel p1 = newjpanel(); 2. Give it a layout: p1.setlayout( new GridLayout(1, 2)); 3. Add widgets to it: p1.add(red); p1.add(rlabel); 4. Put your panel into the JFrame object named pane: pane.add(p1, "North") or pane.add(p1, BorderLayout.NORTH) Java Programming - L6... 27/32
Using Swing Components To Use a Text Field Text fields can be used for input and output. 1. Declare it, name it, and supply an initial value for the display. The second parameter is the minimum width of the box. private JTextField red = new JTextField("0", 5); 2. Create a label for it: private JLabel rlabel = new JLabel("red"); 3. Add both to a panel so that one is next to or above the other: p1.add(red); p1.add(rlabel); Java Programming - L6... 28/32
Using Swing Components To Make a Clickable Button 1. Declare it, name it, and supply a label for the display: private JButton submit = new JButton ("submit") 2. Add it to a panel : p5.add(submit); 3. Register the button so that Swing will listen for button events: submit.addactionlistener(this); 4. Define a handler for these events: public void actionperformed(actionevent event) { Object source = event.getsource(); if (source == submit){...} } Java Programming - L6... 29/32
Using Swing Components A Button Handler 1. Declare that your class implements the ActionListener interface: class Smile extends JFrame implements ActionListener { 2. Define the method : public void actionperformed(actionevent event) { 3. Grab the event information: Object source = event.getsource(); 4. Use if...else to identify which button was clicked: if (source == submit) {...} 5. Download information from relevant TextFields and use that info to modify your model: rd = new Integer (red.gettext()).intvalue(); 6. Do other appropriate actions for that button and repaint the window: repaint(); Java Programming - L6... 30/32
Java Summary We have discussed the following packages, classes, methods, and concepts today: try, catch, finally, throw getmessage(), getcause(), printstacktrace(), System.exit(0) Dialog boxes for input and output The concept of derivation and extends, super Font and setfont() RGB colors, Color(), and setcolor() Screen coordinates and drawstring() The paint() function Java Programming - L6... 31/32
Homework This Week Read Chapter 12: GUI Basics P6. Hello Swing! Due Friday, February 24. Write a simple Swing program, using Moving as an example. Create three fonts (different sizes and styles) and two new colors. Use these with one pre-defined color to display your full name three times on the screen in non-overlapping places, and at random-looking coordinates. Give a title to your JFrame window. Be sure the main thread terminates when you close the window. Hand in your code (one class) and a screen shot of your output. Java Programming - L6... 32/32