Lecture 8 Graphical User Interface
Lecture 8 Graphical User Interface
Programming an interface
The GUI components that you use . The way that these components are laid out on a screen . The way that the program that uses the interface responds to events that occur with an interface, such as a mouse being clicked or text being entered into a text field.
The AWT is the part of the Java run-time system that is responsible for user interaction with window objects.
The Swing library components look the same on every platform and so you do not have to worry about any inconsistencies between platforms.
Unlike the AWT components, Swing components are not closely tied to the underlying operating system.
JFrame, which provides the basic attributes of a window, and contains all of the visual components, including other containers such as JPanel. JPanel, which group elements in an area of a window and is then added to a JFrame component.
(2) Layout managers. These are used with containers to arrange embedded components into a particular layout style. There are various layout managers include BorderLayout, FlowLayout, GridLayout, GridBagLayout and BoxLayout. (3) Visual components. This group of components provides the means by which users will usually interact with your applications, e.g. buttons.
(1) Containers
We will start by looking at how visual components are placed in a component known as a container.
JPanel This is a container that can be used in both applications and applets.
Panels, like all containers, can contain both visual components and other containers. A panel is a container that can contain other containers and also GUI visual components such as buttons. Thus panels allow you to modularize the layout of the GUI.
JApplet This is a container that can be embedded in a web page (unit 9).
JFrame
The actual elements within a JFrame are held in the contentPane. The content pane is the usable area of a frame in which other components can be placed.
Layout Managers
BorderLayout
Add buttons to the JFrame using the BorderLayout (inside the constructor) If you dont set the layout, then the default layout is used, which is BorderLayout for Jframe. When using the BorderLayout each element is placed in the frame using a static constant NORTH, EAST, SOUTH, WEST and CENTER.
Add buttons to the JFrame using the FlowLayout (you dont need to set location)
FlowLayout
This layout places the items in the order in which they are added. If there isn't enough room on a line to include all of the components then they will flow onto the next line.
GridLayout
Add buttons to the JFrame using the GridLayout This layout places the elements according to a grid of rows and columns. When you define a GridLayout object it has two arguments: the first is the number of rows and the second is the number of columns.
It is also possible not to use any layout manager and to place components manually. This is known as absolute positioning. It is done in 3 STEPS:
1. 2. 3.
specifying the layout manager to be null, adding the component to the holder in the normal way using the setBounds method to place and size the component in the holder.
For example:
Advantage: you get greater control over placement. Disadvantage: every element has to be placed manually, rather than relying on a layout manager. This can have major ramifications when you have to change the user interface; for example, inserting a new element will mean that many of the existing elements will need to be moved.
Visual Components
Buttons
A button is used so that the user can ask for action from a program. How to create:
JButton offButton = new JButton(); // without label JButton onButton = new JButton("Cancel"); //with label
Labels
How to create:
JLabel lb = new JLabel("Hello there");
Check boxes
Check boxes are used for the input of boolean data. How to create:
JCheckBox noviceUserType = new JCheckBox("Novice"); JCheckBox expeUserType = new JCheckBox("Experienced");
Getting: The state of a check box whether or not it is on can be discovered by means of the method isSelected, which returns a boolean result.
boolean b = expeUserType.isSelected();
Radio buttons
Radio buttons are grouped together and have the property that only one of the buttons can be selected at a time.
// (1) Create the buttons JRadioButton fr = new JRadioButton("French", true); //initially selected JRadioButton en = new JRadioButton("English", false); // (2) Group the buttons
How to create:
Note:
when you add elements to the JFrame (or JPanel), you must add the RadioButton objects, not the ButtonGroup object. The aim of using a ButtonGroup object is to tell Java that a set of buttons are are grouped together and have the property that only one of the buttons can be selected at a time.
A combo box is a drop-down list that allows the programmer to specify a number of strings, one of which can be selected. How to create:
// (1) Create the ComboBox JComboBox computerChoice = new JComboBox(); // (2) Add items to the ComboBox computerChoice.addItem("VAX"); computerChoice.addItem("PC"); computerChoice.addItem("Mac"); computerChoice.setSelectedItem("VAX"); //initially selected
Getting: using a method to return the string of the currently selected item.
String s = computerChoice.getSelectedItem();
Lists
A list of items where the user can select a single string or a number of strings.
Example: String [] names = nameList.getSelectedValues(); places the strings in the data array that have been selected by the user in the string array names.
int[] getSelectedIndices() returns an array of all the selected indices in increasing order. String getElementAt(int) returns the string that can be found at the specified index.
Text fields
Text fields are used for the input of small items of textual data. How to create:
JTextField txfA = new JTextField(); // empty textbox JTextField txfB = new JTextField(20); // empty, width = 20 characters JTextField txfC = new JTextField("Type here"); // not empty JTextField txfD = new JTextField("Type here", 20); // not empty, width=20
Getting: String
t = txfA.getText();
Text areas
A text area is used for entering comparatively large amounts of textual data.
containing a number of lines of text, rather than the single line found in a text field. Both the class JTextArea and the class JTextField inherit from a class known as JTextComponent.
How to create:
JTextArea ta = new JTextArea (4, 20); // empty, 4 rows, 20 columns JTextArea ta = new JTextArea ("line1\nline2", 4, 20);//not empty, 4 r, 20 c
JOptionPane
makes it easy to pop up a standard dialog box that prompts users for a value or informs them of something. The JOptionPane class is part of the javax.swing library. Two of the dialog boxes are:
Message Dialog - a dialog box that displays a message (left figure). Input Dialog - a dialog box that prompts the user for input (right figure).
showInputDialog
JOptionPane
The parameters to the JOptionPanes methods follow consistent patterns:
parentComponent: Defines the Component that is to be the parent of this dialog box. It is used in two ways:
1.
the Frame that contains it is used as the Frame parent for the dialog box, and its screen coordinates are used in the placement of the dialog box. This parameter may be null, in which case a default Frame is used as the parent, and the dialog will be centered on the screen.
2.
Message: A descriptive message to be placed in the dialog box. In the most common usage, message is just a String. title: The title for the dialog box.
messageType: Defines the style of the message and will often provide a default icon. The possible values are: ERROR_MESSAG, INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE, and PLAIN_MESSAGE.
Example :
Many IDEs provide the facilities to create user interfaces using a 'drag and drop approach from a palette of components.
The IDE automatically creates the code necessary to produce the interface that you have visually created. The IDE then allows you to adjust the parameters of the components and to add the code necessary to make them work. However, creating layouts in this way can produce code that is unnecessarily complex and may make the application less portable.
Exercise:
Events
Event-driven programming
To create this link between something happening in the graphical user interface an event and the execution of code. Event-driven programs are programs that respond to
Events initiated by the user for example:
a button being clicked; a text field being modified; a menu being accessed; a list element being selected.
Listeners:
A major part of event-driven programming is the creation of objects called listeners that are attached to components. As their name suggests they 'listen' for events happening to 'their' components. These listeners then 'fire' off the desired code.
Listeners can be 'told' to look at particular components and to look only at particular events. For example, a listener may be interested only in a mouse entering a particular part of the screen and not in it being clicked.
To describe how events are handled, two small items need to be introduced:
(1) An event source is an object that gives rise to an event.
An event listener is an object of a class that implements a specific type of listener interface. Inside the listener you put the code that triggers off the processing that you want to happen when an event occurs.
The source of the event and the place where the event is dealt with are separate.
Why separate? This nicely separates the interface (the visual components) from the implementation (the code that carries out the processing). If, at a later date, either the graphical user interface or the processing code has to change then these changes can be localized.
Event handling
3 steps to set up Event Handling for a GUI Component: 1. Create the GUI component on the graphical user interface. Define the event listener class that represents the event handler. This class should implement an appropriate listener interface. Create an object of the event listener class, and register this object with the GUI component addActionListener method
public class myFrame extends JFrame{ private JTextField textField1; //create a text box
// JFrame constructor public myFrame(){ myHandler handler = new myHandler(); textField1.addActionListener( handler ); // private inner class for event handling private class myHandler implements ActionListener{ public void actionPerformed( ActionEvent event ){ // do something here } }}
2.
3.
Example 2: when the button is clicked, the number on the right is incremented.
In Example 2
There are some final points worth making about the above code.
(1)
We need to import
javax.swing for the visual object classes java.awt.event for the event classes and interfaces;
(2)
However, it is not used in this example. This argument contains subsidiary information about the event, which can be used for more complicated processing. This is discussed in the next example!
Example 3: this example shows the use of the event argument. Notice the getsSource method
In Example 3
The first button increments the integer displayed in the label and the second decrements the integer.
Component Listeners
There are many listener interfaces being more complex than the ActionListener.
Although we will not be able to cover every aspect of all of the events and component combinations, you will have sufficient experience of them to be able to use the Java reference material for the rest.
(see list below)
The names of the listeners are formed by the name of the event word listener
+ the
The add and remove methods simply have the word add (or remove) prefixing the interface name
Mouse listeners
In Java there are two interfaces that can be used for mouse events:
MouseMotionListener: This defines two events concerned with dragging and moving the mouse (we will not focus on this one) MouseListener: This defines five methods that are used for monitoring:
Any listener that wants to react to any of the above events must implement the MouseListener interface, which contains the definition of the above five methods.
Mouse listeners Example The code defines a window that contains two labels and a panel,
with the panel being coloured yellow (this is achieved by means of the method setBackground, which uses the static variable Color.yellow).
When the mouse is clicked within the panel the labels display the xand y-coordinates of the point within the panel that the mouse was clicked in.
The methods getX and getY from the class MouseEvent are used to retrieve these values from the MouseEvent argument.
Adapter classes
These are classes that are analogues of the interfaces, which implement the methods asked for by the interfaces by means of providing the empty methods. The programmer who wants to react to a small number of events can inherit from these adapter classes (instead of implementing an interface) An example of an adapter class is MouseAdapter. This class provides empty bodies for the five methods detailed above. We use adapters in the same way as listeners by defining inner classes, except now we extend rather than implement.
Window listeners
In previous examples, clicking on the close window icon does not end the program, it simply closes the window.
(2)
Link the clicking of that icon with program code using the WindowAdapter class
WindowAdapter is the adapter class for the WindowListener interface WindowAdapter contains seven methods including windowOpening, windowClosing and windowClosed. We will use the windowClosing method to link the clicking of the close window icon with our program and get the program to stop when the window is closed.
(2)
Add the following line anywhere in the constructor of the our frame class in any previous example (after the call to super, of course).
addWindowListener(new CloseAndQuit());
By putting the class CloseAndQuit into the same package as NewMouser we will see that when we click the close icon on the window, the whole program stops.