1 / 90

Starting Out with Java: Early Objects Third Edition by Tony Gaddis as modified for CSCI 1260

Chapter 11: GUI Applications – Part 1. Starting Out with Java: Early Objects Third Edition by Tony Gaddis as modified for CSCI 1260. Chapter Topics. Chapter 11 discusses the following main topics: Introduction Dialog Boxes Creating Windows Equipping GUI Classes with a main method

gryta
Télécharger la présentation

Starting Out with Java: Early Objects Third Edition by Tony Gaddis as modified for CSCI 1260

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 11:GUI Applications–Part 1 Starting Out with Java: Early Objects Third Edition by Tony Gaddis as modified for CSCI 1260

  2. Chapter Topics Chapter 11 discusses the following main topics: • Introduction • Dialog Boxes • Creating Windows • Equipping GUI Classes with a main method • Layout Managers • Radio Buttons and Check Boxes • Borders • Focus on Problem Solving: Extending Classes from JPanel • Splash Screens • Using Console Output to Debug a GUI Application

  3. Introduction • Many Java applications use a graphical user interfaceor GUI(pronounced “gooey) • A GUI is a graphical window or windows that provide interaction with the user • GUI’sdoes not use the console window, but it accepts input from: • the keyboard • a mouse • A window in a GUI consists of componentsthat: • present data to the user • allow interaction with the application

  4. Introduction Frame with caption, icon, and buttons • Some common GUI components are: • buttons, labels, text fields, check boxes, radio buttons, combo boxes, and sliders. Check box Label Text field Combo Box Radio buttons List control Slider control Button

  5. JFC, AWT, Swing • Java programmers use the Java Foundation Classes (JFC)to create GUIapplications • The JFC consists of severalsets of classes, many of which are beyond our scope • The two sets of JFC classes that we focus on are AWT and Swingclasses • These classes are part of the Abstract Windowing Toolkit (AWT) • This set of classes is for drawing graphics and creating graphical user interfaces

  6. JFC, AWT, Swing • The AWT allows creation of applications and applets with GUIcomponents • The AWT does not actually draw user interface components on the screen • The AWT communicates with a layer of software in the operating system called peerclasses • Each version of Java for a particular operating system has its own set of peer classes • In other words, AWT lets each operating system draw its own windows and GUI controls

  7. JFC, AWT, Swing • Java programs using the AWT: • look consistent with other applications on the same system • can offer only components that are common to all the operating systems that support Java • The behavior of components across various operatingsystems can differ • Programmers cannot easily extend the AWTcomponents • AWT components are commonly called heavyweight componentsbecause of their dependence on the operating system

  8. JFC, AWT, Swing • Swing was introduced with the release of Java 2 • Now at Java 7 • Swingis a libraryofclasses that provide an improved alternative for creating GUI applications and applets • Very few Swing classes rely on peer classes, so they are referred to called lightweightcomponents • Swing draws most of its own components • Swingcomponents have a consistentlookandpredictablebehavior on any operating system • Swing components can be extended easily

  9. javax.swing and java.awt • In an application that usesSwing classes, it is necessary to use the following statement: import javax.swing.*; • Note the letterxthat appears after the wordjavain javax • Some of the AWT classes are used to determine when events, such as the clicking of a mouse, moving the cursor, pressing a key, scrolling, and so forth, take place in applications • In an application that uses an AWT class, it is necessary to use the following statement. import java.awt.*; • Note: there is nox after javain this package name

  10. Eclipse Tip • It is tedious to import classes or packages manually one at a time • In Eclipse, one may use a “Consume First” approach to get Eclipse to help . . . • Type a Java instruction that uses a class for which no “import” has been specified yet • Eclipse will put a red squiggly line underneath the not-yet-imported class name • Press shift-ctrl-O and Eclipse will generate the properimport command if the class name is valid

  11. Event Driven Programming • Programs that operate in a GUI environment must be event-driven • An eventis something that happens (possibly the result of a user action) while running a program, such as • Clicking a button • Pressing a key on the keyboard • Moving a mouse • Part of writing a GUI application is creating eventlisteners • An eventlisteneris an object that automaticallyexecutes one of its methods when its specificevent occurs. It does something in response to the event that happened

  12. Creating Windows • Often, applications need one or more windows with various components • A window has 3 distinct but interrelated roles • A window is a Java object just like other objects such as Strings, Employees, Customers, Students, … It has attributes and methods just like other types of objects, and it may interact with other objects • A window has a graphical depiction on the screen as the program runs • A window is a container, which is simply a component that holds other components such as labels, buttons, captions, textfields, and so forth • A container that can be displayed as a window is called a frame • In a Swing application, you may either • Create a frame directly from the JFrameclass • Derive a new class from the JFrame class and create an object from it

  13. Creating Windows • A frame is a basic window that has: • a border around it • a titlebar • a set of buttons for: • minimizing • maximizing • closing the window • These standard features are sometimes referred to as windowdecorations

  14. Creating Windows • In the main method, two constants are declared in the example coming in few slides: final int WINDOW_WIDTH = 350, WINDOW_HEIGHT = 250; • We use these constants later in the program to set the size of the window • The window’s size is measured in pixels • A pixel (picture element) is one of the small dots that make up a screen display • The actual size of the window on the screen depends not only on its height and width, but also on the screen resolution • A 350 x 250 window will be fairly large on a 640 x 480 screen, but it will be much smaller on a 1920 x 1080 screen

  15. Creating Windows • An instance of the JFrame class needs to be created: JFrame window = new JFrame("A Simple Window"); • This statement: • creates a JFrame object in memory and • assigns its address to the windowvariable • The string that is passed to the constructor will appear in the window’s title bar when it is displayed; it is the caption for the window • A JFrame is initially invisible

  16. Creating Windows • To set the size of the window: window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT); • To specify the action to take place when the user clicks on the close button window.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); • The setDefaultCloseOperation method takes an int argument which specifies the action • JFrame.HIDE_ON_CLOSE - causes the window to be hidden from view, but the application does not end • The default action is JFrame.HIDE_ON_CLOSE

  17. Creating Windows • The following code displays the window by making it visible on the screen: window.setVisible (true); • The setVisible method takes a booleanargument • true - display the window • false - hide the window (this is default) • You may use setTitle (string) to modify the window’s title (caption) window.setTitle(“My First GUI App”);

  18. A First Example

  19. Extending JFrame • The previous example is a quick-and-dirty example that illustrates some important points, but it is not the preferred way to write a GUI application • We usually use inheritance to create a new class that extends the JFrameclass • New fields and methods can be added to the new class declaration • This allows specialized methods and fields to be added to your window • An example follows on the next slide

  20. Example 2

  21. Adding Components • Swing provides numerous components (controls) that can be added to a window • Three fundamental controls are: JLabel: An area that can display text JTextField: An area in which the user may type a single line of input from the keyboard JButton: A button that can cause an action to occur when it is clicked • Objects of these classes can be created and used inside a window

  22. Sketch of Kilometer Converter Graphical User Interface Text Field WindowTitle Label Button

  23. Adding Components Width of the TextField is 10 characters – a character width is measured using an “m”, the widest character in the alphabet. private JLabel messageLabel; private JTextField kiloTextField; private JButton calcButton; … messageLabel = new JLabel( "Enter a distance in kilometers"); kiloTextField = new JTextField(10); calcButton = new JButton("Calculate"); • This code declares and instantiates three Swingcomponents named: • messageLabel (a JLabel object) • kiloTextField (a JTextField object) • calcButton (a JButton object)

  24. Class Hierarchy AWT above this line,Swingbelow it Note the naming conventions – concrete Swing class names almost always start with “J”

  25. Adding Components • A content paneis a container that is part of every JFrameobject • Every component added to a JFrame must be added to its content pane. You do this with the JFrame class's addmethod • The content pane isnotvisible and it doesnot have a border • Apanelis another container that can hold GUI components – see JPanel This area can be “thought of” as where the content pane is

  26. Adding Components • Panels cannot be displayed by themselves • Usually added to content pane or even to other panels • Panels are commonly used to hold and organize collections of related components • Create panels with the JPanelclass private JPanel panel; … panel = new JPanel( ); panel.add (messageLabel); panel.add (kiloTextField); panel.add (calcButton);

  27. Example Window with 3 Panels Header panel has 2 controls Selection Panel has 6 checkboxes and 3 label controls Button Panel has 2 button controls

  28. Adding Components • Components are typically placed on a panel and then the panel is added to the JFrame's contentpane add(panel); • Examples: KiloConverterWindow.java, KilometerConverter.java

  29. Example This line is required to avoid a warning message Proper way to start a simple GUI application Resulting application window

  30. Handling Action Events • An eventis an action that takes place when the program is running, such as the user clicking of a button, moving a mouse, typing in a JTextField, etc. • When an event takes place, the component that is responsible for the event creates an event object in memory • The eventobjectcontains information about the event such as which component created the event and so forth • The componentthatgenerated the eventobject is known as the eventsource • It is possible that the event source component is connected to one or more eventlisteners

  31. Handling Action Events • An event listeneris an object that responds to specific events • The source component fires an event which is passed to a method in the event listener • Eventlistener classes are specific to each application • Eventlistener classes are commonly written as privateinnerclasses in an application

  32. Writing Event Listener Classes as Private Inner Classes A class that is definedinside of anotherclass is called an inner class public class Outer { Fields and methods of the Outer class appear here private class Inner { Fields and methods of the Inner class appear here } } Private class Inner is only accessible and usable internally by its containing class –Outer in this case

  33. Connector for inner classes UML – inner classes Calculator class with 3 inner “listener” classes and a separate driver class

  34. Event Listeners Must Implement an Interface • All event listener classesmustimplement a specific interface • Which interface it implements depends on the type of event for which it is listening • Implementing the interface provides one or more method(s) to be executed if/when the specified event occurs • This method takes the action appropriate for the program when that event happens

  35. Handling Action Events • JButton components generate actionevents, which require an actionlistenerclass • Actionlistenerclassesmay be named as you wish, but each must meet the following requirements: • It must implement the ActionListenerinterface • It must have a method named actionPerformed • The actionPerformed method takes an argument of the ActionEvent type public void actionPerformed (ActionEvent e) { Code to be executed when button is pressed goes here }

  36. Handling Action Events ActionEvent Object Action Listener Object void actionPerformed(ActionEvent e) JButton Component When the button is pressed … The JButton component generates an event object and passes it to the action listener object's actionPerformedmethod Examples: KiloConverterWindow.java, KilometerConverter.java

  37. Registering A Listener • The process of connecting an event listener object to a component is called registeringthe eventlistener • JButton components have a method named addActionListener calcButton.addActionListener( new CalcButtonListener()); • When the user clicks on the source button, the actionlistener object’s actionPerformedmethod will be executed

  38. Background and Foreground Colors • Many of the Swing component classes have methods named setBackground and setForeground • setBackground is used to change the color of the component itself • setForeground is used to change the color of the text displayed on the component • Each method takes a color constant as an argument

  39. Color Constants • Predefined constants can be used to designate colors Color.BLACK Color.BLUE Color.CYAN Color.DARK_GRAY Color.GRAY Color.GREEN Color.LIGHT_GRAY Color.MAGENTA Color.ORANGE Color.PINK Color.RED Color.WHITE Color.YELLOW • Examples: ColorWindow.java, ColorDemo.java

  40. Example: using colors Continued …

  41. Example: colors, continued Driver …

  42. Example, continued Initial window After clicking Red After clicking Blue After clicking Yellow

  43. The ActionEvent Object • Event objects contain certain information about the event • This information can be obtained by calling one of the event object’s methods • Two of these methods are: • getSource - returns a reference to the object that generated this event • getActionCommand - returns the action command for this event as a String • Example: • EventObjectWindow.java, EventObjectDemo.java

  44. Layout Managers • An important part of designing a GUI application is determining the layout of the components • The term layoutrefers to the positioning and sizing of components • In Java, you do not normally specify the exact location of a component within a window • A layoutmanager is an object that: • controls the positions and sizes of components • makes adjustments when necessary

  45. Layout Managers • The layout manager object and its container work together • Java provides several layout managers. Three are: • FlowLayout - Arranges components in rows. This is the default for panels. If something will not fit on one row it moves to the next row • BorderLayout - Arranges components in five regions: • North, South, East, West, and Center • This is the default layout manager for a JFrame object’s content pane • GridLayout - Arranges components in a grid with rows and columns

  46. Layout Managers • The Container class is one of the base classes from which many components are derived • Any component that is derived from the Container class can have a layout manager added to it • You add a layout manager to a container by calling the setLayoutmethod JPanel panel = new JPanel( ); panel.setLayout(new BorderLayout( )); • In a JFrame constructor you might use: setLayout(new FlowLayout( ));

  47. FlowLayout Manager • FlowLayout is the default layout manager for JPanelobjects • Components appear horizontally, from lefttoright, in the order that theywereadded. When there is no more room in a row, the next components “flow” to the next row • See example: FlowWindow.java

  48. Flow Layout Example After stretching window horizontally Initial Window After resizing again

  49. FlowLayout Manager • The FlowLayout manager allows you to align components: • in the center of each row • along the left or rightedges of each row • An overloaded constructor allows you to pass: • FlowLayout.CENTER • FlowLayout.LEFT • FlowLayout.RIGHT • Example: setLayout(new FlowLayout(FlowLayout.LEFT));

  50. FlowLayout Manager • FlowLayout inserts a gap of five pixels between components, horizontally and vertically by default • An overloaded FlowLayout constructor allows these to be adjusted • The constructor has the following format: FlowLayout(int alignment, int horizontalGap, int verticalGap) • Example: setLayout (new FlowLayout(FlowLayout.LEFT, 10, 7));

More Related