900 likes | 1.08k Views
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
E N D
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 • 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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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”);
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
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
Sketch of Kilometer Converter Graphical User Interface Text Field WindowTitle Label Button
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)
Class Hierarchy AWT above this line,Swingbelow it Note the naming conventions – concrete Swing class names almost always start with “J”
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
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);
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
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
Example This line is required to avoid a warning message Proper way to start a simple GUI application Resulting application window
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
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
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
Connector for inner classes UML – inner classes Calculator class with 3 inner “listener” classes and a separate driver class
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
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 }
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
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
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
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
Example: using colors Continued …
Example: colors, continued Driver …
Example, continued Initial window After clicking Red After clicking Blue After clicking Yellow
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
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
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
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( ));
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
Flow Layout Example After stretching window horizontally Initial Window After resizing again
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));
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));