720 likes | 734 Views
Learn to build graphical user interfaces using Swing components, layout managers, event handling, and containers in Java. This chapter covers creating interactive displays and writing event handlers for applications. Dive into Swing components like buttons, labels, text fields, containers, and basic classes like Color and Dimension. Discover how to gather input with buttons and input fields, and present information with labels, progress bars, and tables. Explore organizing components with panels, scroll panes, and tabbed panes. Practice creating interactive interfaces using intermediate components like panels and split panes. Master the fundamentals of Swing components for creating dynamic and user-friendly applications.
E N D
Objectives • After studying this chapter you should understand the following: • the idea of an event driven interface; • Java’s Swing component and container structure; • the use of layout managers to manage component positioning and sizing; • handling events occurring in a component.. NH-Chapter 17
Objectives • Also, you should be able to: • build a simple display from graphical components; • write event handlers that listen for high-level events; • build a simple graphical user interface for an application NH-Chapter 17
Application interfaces • algorithm-driven • Application is active • Application determines exactly what information it needs from environment, and when to get it. • The text-based interfaces are algorithm driven. NH-Chapter 17
Application interfaces • event-driven • Application it is passive. • Application waits for an event to happen in the environment • When an event occurs, the application responds to the event, and then waits for the next event. • Applications with a graphical, window-based user interface are almost always event driven NH-Chapter 17
Event-driven applications • A window-based system, has windowing system managing display and event detection. • A Java application interacts with native windowing system through AWT components. • Application communicates with native windowing system to create a display. NH-Chapter 17
Event-driven applications • Events occurring in display are • awaited for by application • detected by the native windowing system • delivered to application. • responded-to by application. NH-Chapter 17
An introduction to Swing: Components • Basic (atomic) components, • present information to or get information from user. • Examples: button, label, text field,editor pane, combo box. • Containers • hold and position other components. • Example: JFrame, JPanel. • top-level container • contains all of the visual components of a GUI • provides the screen real estate used by application. • Intermediate containers • used to organize and position GUI components. NH-Chapter 17
JComponent • Subclass of java.awt.Component. • Component properties, obtained with queries: • And set via corresponding methods: public Color getForeground (); public Color getBackground (); public Point getLocation (); public Dimension getSize () public Font getFont (); public void setForeground (Color fg); public void setBackground (Color bg); public void setLocation (Point p); public void setSize (Dimension d); public void setFont (Font f); NH-Chapter 17
Other basic classes • AWT classes defined in the package java.awt • Color, ( an immutable class) • Point, • Dimension, • Font NH-Chapter 17
Basic components to gather input • JButton • JCheckBox a toggled on/off buttondisplaying state to user. • JRadioButtona toggled on/off buttondisplaying its state to user. • JComboBox a drop-down list with optional editable text field. The user can key in a value or select a value from drop-down list. • Jlistallows a user to select one or more items from a list. • Jmenupopup list of items from which the user can select. • Jslider lets user select a value by sliding a knob. • JTextField area for entering a single line of input. NH-Chapter 17
Basic components to present information • Jlabelcontains text string, an image, or both. • JProgressBarcommunicates progress of some work. • JToolTip describes purpose of another component. • Jtreea component that displays hierarchical data in outline form. • Jtablea component user to edit and display data in a two-dimensional grid. • JTextArea, JTextPane, JEditorPane • define multi-line areas for displaying, entering, and editing text. NH-Chapter 17
Swing components NH-Chapter 17
Swing components A JTree A JTable NH-Chapter 17
Container • Component that can contain other components and containers. NH-Chapter 17
Intermediate components • Used to organize and position other components. • JPanel used for collecting other components. • JScrollPane provides view with scroll bars. • JSplitPane divides two components graphically. • JTabbedPane lets the user switch between a group of components by clicking on a labeled tab; • JToolBar used for displaying a set of commonly used controls. NH-Chapter 17
Example of component organization • The following creates a JPanel and adds two buttons, labeled “on” and “off.” • Wherever this panel is used, it will present the two buttons. JPanel p = new JPanel(); p.add(new JButton("on")); p.add(new JButton("off")); NH-Chapter 17
Top-level container • It’s not contained in any other container. • provide screen area where other components can display themselves. • JApplet, JDialog, JFrame, and JWindow are commonly used as top-level containers. NH-Chapter 17
JFrame • It’s a window with title, border, (optional) menu bar and user-specified components. • It can be moved, resized, iconified. • It is not a subclass of JComponent. • Delegates responsibility of managing user-specified components to a content pane, an instance of JPanel. NH-Chapter 17
Jframe Jframe Jframe internal structure NH-Chapter 17
JFrame • To add a component to a JFrame, add it to the content pane: JFrame f = new JFrame("A Frame"); JButton b = new JButton("Press"); Container cp = f.getContentPane(); cp.add(b) NH-Chapter 17
content pane JFrame Container * Component JFrame components are in its content pane. NH-Chapter 17
Heavyweight and lightweight components • Heavyweight components • Instances of classes JApplet, JDialog, JFrame, and JWindow. • Created by association to a native GUI component part of the native windowing system. • Their look and feel depends on the native GUI component. • Lightweight components • Any other Swing component. • They are completely implemented in Java. NH-Chapter 17
A Simple app displaying a JFrame import javax.swing.*; public class DisplayFrame { public static void main (String[] args) { JFrame f = new JFrame("A Frame"); //… components are added to its content frame. f.setSize(300,200); f.setVisible(true); } } NH-Chapter 17
Sequential/Concurrent programming • A thread is a sequence of instructions being executed by the processor. • Sequential programming: So far programs consisted of a single thread, which executes the sequence of actions in the main method (main thread). • Concurrent programming: A program can contain several threads each executing independent sequences of actions. NH-Chapter 17
Sequential/Concurrent programming • Event-dispatching thread: executes all the code that involves repainting components and handling events. • After the JFrame has been made visible, the main thread should not perform actions that affect or depend on the state of the user interface. NH-Chapter 17
LayoutManager • Responsible for positioning and sizing components added to a container. • Each container is associated with a LayoutManager. • Setting and accessing Container’s layout manager: public LayoutManager getLayout(); public void setLayout (LayoutManager manager); NH-Chapter 17
LayoutManager classes • FlowLayout lays out components left to right, top to bottom. • BorderLayout lays out up to five components, positioned “north,” “south,” “east,” “west,” and “center.” • GridLayoutlays out components in a two-dimensional grid. • CardLayout displays components one at a time from a preset deck of components. NH-Chapter 17
LayoutManager classes • GridBagLayout lays out components vertically and horizontally according to a specified set of constraints. • BoxLayout lays out components in either a single horizontal row or single vertical column. • OverlayLayout components are laid out on top of each other. NH-Chapter 17
Default layout managers • A FlowLayout lays out components in order added to container. • In BorderLayout, a component’s position is specified by a second argument to add. • Jpanel default layout manager: FlowLayout. • JFrame’s content pane default layout manager: BorderLayout. NH-Chapter 17
Component layout figures NH-Chapter 17
CardLayout view 2 CardLayout view 1 Component layout figures NH-Chapter 17
Events and components • Events are objects. • Events: subclasses of abstract class java.awt.AWTEvent. • Components generate events. • An event object knows event source and other relevant information about the event. • Given an event, to query for its component’s source: public Object getSource(); NH-Chapter 17
Listener or Event handler • Listener: An object interested in being notified when an event occurs in a given component. • A Listener object registers with a component to be notified of events generated by it. • Listener must implement the eventlistener interface associated with events for which it registered. • Programming a handler for an event consists of implementing the interface associated with the event type. NH-Chapter 17
GUI programming example • Program an application that displays a button. When the button is pressed, its foreground and background colors are swapped. • Design: extended the class JFrame with OnOffSwitch, and its constructor builds the frame containing the button. NH-Chapter 17
import java.awt.*; • import javax.swing.*; • import java.awt.event.*; • class OnOffSwitch extends JFrame { • public OnOffSwitch () { • super("On/Off Switch"); // frame title • JButton button = new JButton("On/Off"); • button.setForeground(Color.black); • button.setBackground(Color.white); • this.getContentPane().add(button, BorderLayout.CENTER); • } • }//end of OnOffSwitch • public class OnOffTest { • public static void main (String[] args) { • OnOffSwitch frame = new OnOffSwitch(); • frame.setSize(300,200); • frame.setVisible(true); • } • } NH-Chapter 17
Program does not work • Pressing the button has no effect at all. • When the button is pressed, it generates an ActionEvent. • Have not “programmed” the user interface to respond to that event. NH-Chapter 17
Programming the gui: adding an ActionListener for the JButton • Implement a listener to handle event generated by JButton instance. • If user presses button, it generates an ActionEvent. • To do: • Define a class, Switcher, that implements ActionEvent. • Register an instance of Switcher with the Jbutton instance. NH-Chapter 17
public OnOffSwitch () { • super("On/Off Switch"); // frame title • // create button and set its colors • JButton button = new JButton("On/Off"); • button.setForeground(Color.black); • button.setBackground(Color.white); • // create and register button’s listener: • button.addActionListener(new Switcher()); • // add button to JFrame’s content pane: • this.getContentPane().add( • button, BorderLayout.CENTER); • } • Revise OnOffSwitch to create a Switcher listener and register it with the JButton component NH-Chapter 17
Defining Switcher class Switcher implements ActionListener { public void actionPerformed (ActionEvent e) { Component source = (Component)e.getSource(); Color oldForeground = source.getForeground(); source.setForeground(source.getBackground()); source.setBackground(oldForeground); } } NH-Chapter 17
Programming the JFrame close • To terminate the program need to program a window listener to close the window. • A window listener must implement the 7 methods in WindowListener interface. • We only want to implement 2 of those methods: void windowClosed (WindowEvent e) void windowClosing (WindowEvent e) NH-Chapter 17
Adapter classes: WindowAdapter • Java provides a collection of abstract event adapter classes. • These adapter classes implement listener interfaces with empty, do-nothing methods. • To implement a listener class, we extend an adapter class and override only methods needed. NH-Chapter 17
Terminator class //implements window events to close a window class Terminator extends WindowAdapter { public void windowClosing(WindowEvent e) { Window w = e.getWindow(); w.dispose(); } public void windowClosed(WindowEvent e) { System.exit(0); } } NH-Chapter 17
Revise OnOffSwith class to create a Terminator instance and register with the JFrame instance. • public OnOffSwitch () { • super("On/Off Switch"); // frame title • this.addWindowListener(new Terminator()); • // create button and set its colors • JButton button = new JButton("On/Off"); • button.setForeground(Color.black); • button.setBackground(Color.white); • // create and register button’s listener: • button.addActionListener(new Switcher()); • // add button to JFrame’s content pane: • this.getContentPane().add( • button, BorderLayout.CENTER); • } NH-Chapter 17
Basic GUI programming review • To a JFrame instance • add components comprising the interface. • Program a Terminator class to allow user to close window. • For every GUI component that generates events for which your application needs to react to: • Define a class that implements the Listener interface for desired events. • Instantiate and register Listener class with the component that generates desired events. NH-Chapter 17
Building GUIs • Use JPanel as a decomposition tool for complex views. • A standard technique. • Provides more flexibility; • JPanel can be added to other structures to expand or modify application. • Build app view on a JPanel and add to a JFrame content pane. NH-Chapter 17
Building GUIs • Components can have borders to give them desired looks. • The JComponent method adds a border to a component: public void setBorder (Border border) • Standard borders are obtained from the class javax.swing.BorderFactory. NH-Chapter 17
MenuBar and Menu • A menu offers options to user. • Menus are not generally added to user interface. • menu usually appears either in a menu bar or as a popup menu. • A JFrame often has a menu bar containing many menus; and each menu can contain many choices. NH-Chapter 17
MenuBar and Menu • Menu bar can be added to a JFrame with the method setJMenuBar: JFrame window = new JFrame("Some Application"); JMenuBar menuBar = new JMenuBar(); window.setJMenuBar(menuBar); NH-Chapter 17
Menu • Menus are JMenu instances and added to menu bar: JMenu batter = new JMenu("Batter"); menuBar.add(batter); • Menu choices are JMenuItem instances, and are added to menu: JMenuItem swing = new JMenuItem("Swing"); JMenuItem take = new JMenuItem("Take"); JMenuItem bunt = new JMenuItem("Bunt"); batter.add(swing); batter.add(take); batter.add(bunt); NH-Chapter 17