MTS 2023 Object Oriented Programming Graphical User Interface
1
Introduction
GUI is used to make your program attractive and user friendly such as buttons, menus, text fields and scrollbars GUI are built from GUI components. A GUI component is an object with which the user interacts via mouse, keyboard or another form of input.
2
GUI components Component
Description
JLabel
An area where uneditable text or icons can be displayed
JTextField
An area in which the user inputs data form keyboard. The area also can display information
JButton
An area that trigger an event when clicked
JCheckBox
A GUI component that is either selected or not selected
JComboBox
A dropdown list of items from which the user can make a selection by clicking an item in the list or possibly by typing into the box
JList
An area where a list of items is displayed from which the user can make a selection by clicking once on any element in the list. Double clicking an element in the list generates an action event. Multiple elements can be selected
JPanel
A container in which components can be placed 3
Example of a program- area of a rectangle //program to determine the area of a rectangle import javax.swing.JOptionPane;
public class Rectangle { public static void main (String [] args) { double width, length, area; String lengthStr,widthStr,outputStr; lengthStr = JOptionPane.showInputDialog("Enter the length: "); length = Double.parseDouble(lengthStr); widthStr = JOptionPane.showInputDialog("Enter the width: "); width = Double.parseDouble(widthStr); area = length*width; outputStr = "Area: " + area + "square units\n"; JOptionPane.showMessageDialog(null, outputStr, "Rectangle", JOptionPane.INFORMATION_MESSAGE);
}
}
System.exit(0);
4
Output - area of a rectangle
5
Creating a window
GUI component such as windows and labels are objects JFrame is a class and the GUI component window can be created by using a JFrame object. Various attributes are associated with a window such as
Every window has a title Every window has width and length
6
JFrame
The class JFrame provides various methods to control the attributes of a window Table 6-1 shows some methods provided by the class JFrame Two ways to make an application program create a window:
Declare an object of the type JFrame, instantiate an object and use various methods to manipulate the window. or Create the class containing the application program by extending the definition of the class JFrame – uses inheritance 7
JFrame
we will use the second way to create a window Extend the definition of the class JFrame by using the modifier extends
8
Example of a program - create a //java program to create a window window
import javax.swing.JFrame; public class RectangleProgram extends JFrame { private static final int WIDTH = 400; private static final int HEIGHT = 300; public RectangleProgram() { setTitle("Area of a Rectangle"); setSize(WIDTH,HEIGHT); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); }
}
public static void main(String args[]) { RectangleProgram rectProg = new RectangleProgram(); } 9
Output - - create a window
10
Getting access to the content pane
Content pane – inner area of the window Class JFrame has the method getContentPane that you can use to access the content pane of the window. But the class does not have the necessary tools to manage the component of the content pane
You have to declare a reference variable of the Container type Container pane; pane = getContentPane(); or Container pane = getContentPane(); 11
The class Container provides methods:
public void add (Object obj)
public void setLayout (Object obj)
//method to set the layout of the pane
Class container contained in the package java.awt
//method to add an object to the pane
import java.awt.Container;
The statement pane.setLayout(new GridLayout (5,2)) – set the layout of the content pane, pane to 5 rows and 2 columns. If you do not specify a layout, Java uses a default layout 12
JLabel
Labels provide text instructions or information on a GUI. Labels are defined with class JLabel – a subclass of JComponent A label displays a single line of read-only text, an image or both text and an image. Contained in the package javax.swing. Some methods provided by the class JLabel is shown in Table 6-3 13
Methods provided by the class JLabel Public JLabel (String str)
Constructor to create a label with left-aligned text specified by str Example: JLabel lengthL; lengthL = new JLabel(“Enter the length”);
Public JLabel(String str, int align)
Constructor to create a label with the text specified by str. The value of align can be one of the following:
SwingConstants.LEFT, SwingConstant.RIGHT, SwingConstant.CENTER 14
Methods provided by the class JLabel
Public JLabel (String t, Icon icon, int align)
Constructor a JLabel with both text and an icon The icon is to the left of the text
Public JLabel(Icon icon)
Constructor a JLabel with an icon
15
Example of a program JLabel import javax.swing.*; import java.awt.*; public class RectangleProgramTwo extends JFrame { private static final int WIDTH = 400; private static final int HEIGHT = 300; private JLabel lengthL, widthL, areaL; public RectangleProgramTwo() { setTitle("Area of a Rectangle"); lengthL = new JLabel ("Enter the length : ", SwingConstants.RIGHT); widthL = new JLabel ("Enter the width : ", SwingConstants.RIGHT); areaL = new JLabel ("Area : ", SwingConstants.RIGHT); Container pane = getContentPane(); pane.setLayout(new GridLayout(4,1));
16
pane.add(lengthL); pane.add(widthL); pane.add(areaL); setSize(WIDTH,HEIGHT); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); } public static void main(String args[]) { RectangleProgramTwo rectObject = new RectangleProgramTwo(); } }
17
Output - JLabel
18
JTextField
Single line areas in which text can be entered by the user from the keyboard or text can be displayed Table 6-4 shows some methods of the class JTextField
19
Example of a program JTextField // Program to create a window and place four labels and four text field import javax.swing.*; import java.awt.*; public class RectangleProgramThree extends JFrame { private static final int WIDTH = 400; private static final int HEIGHT = 300; private JLabel lengthL, widthL, areaL; private JTextField lengthTF, widthTF, areaTF; public RectangleProgramThree() { setTitle("Area of a Rectangle"); lengthL = new JLabel ("Enter the length : ", SwingConstants.RIGHT); widthL = new JLabel ("Enter the width : ", SwingConstants.RIGHT); areaL = new JLabel ("Area : ", SwingConstants.RIGHT); lengthTF = new JTextField(10); //width of the text field is 10 character widthTF = new JTextField(10); areaTF = new JTextField(10);
20
Container pane = getContentPane(); pane.setLayout(new GridLayout(3,2)); pane.add(lengthL); pane.add(lengthTF); pane.add(widthL); pane.add(widthTF); pane.add(areaL); pane.add(areaTF); setSize(WIDTH,HEIGHT); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); }
}
public static void main(String args[]) { RectangleProgramThree rectObject = new RectangleProgramThree(); }
21
Output of a program JTextField
22
JButton
A button is a component the user clicks to trigger a specific action. Several types of button – command buttons, check boxes, toggle buttons and radio buttons. A command button generates an ActionEvent when the user clicks the button with the mouse.
23
The button hierarchy javax.swing.JComponent
javax.swing.Abstraction
javax.swing.JButton
javax.swing.ToggleButton
javax.swing.JCheckBox
javax.swing.JRadioButton
24
Table 6-5 shows some methods of the class JButton The following lines will create two buttons, Calculate and Exit JButton calculateB,exitB; calculateB = new JButton(“Calculate”); exitB = new JButton(“Exit”);
25
JButton
The button calculateB and exitB can be placed into the container pane by using the method add. pane.add(calculateB); pane.add(exitB);
26
Result
27
Handling an event
When you create a button you need to specify how the button should behave when you click it When you click a JButton, an event is created known as action event which sends a message to another object, known as action listener When the listener receives the message, it performs some action - some method in the listener object is invoked with the event as the argument. The invocation happens automatically.
28
But, you must specify:
For each JButton, you must specify the corresponding listener object – registering the listener Define the methods that will be invoked when the event is sent to the listener
29
Action event is handled by the class ActionListener
It contains only method actionPerformed. Special type of class – interface – class that contains only the method headings and each method headings is terminated with a semicolon Definition of interface ActionListener with method actionPerformed public interface ActionListener { public void actionPerformed(Actionevent e); } Contained in the package java.awt.event
import java.awt.event.ActionListener; 30
How to register an action listener with the object calculateB The class CalculateButtonHandler is created on top of the interface ActionListener
This is because you cannot instantiate an object of the type ActionListener
The class is private because you want this class to be used only within RectangleProgram and uses another modifier implements.
31
To create a listener object of the type CalculateButtonHandler CalculateButtonHandler cbHandler; cbHandler = new CalculateButtonHandler(); To register cbHandler as the listener object of calculateB: calculateB.addActionListener(cbHandler);
32
Definition of the class CalculateButtonHandler private class CalculateButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e ) { //the code to calculate the area } } 33
Hint : you may use method getText() to retrieve the string from the text field To create and register an action listener with the JButton exitB you may use the statement System.exit(0);
34
Result
35
JCheckBox & JRadioButton
On/off or true false values Both classes are subclasses of JToggleFolder JRadioButton is different from a JCheckBox in that there are normally several JRadioButtons that are grouped together and only one JRadioButton in the group can be selected (true) at any time.
36
Example program CheckBox //creating Checkbox buttons import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CheckBoxTest extends JFrame { private JTextField field; private JCheckBox bold, italic; public CheckBoxTest () { super ("JCheckBoxTest"); Container container = getContentPane(); container.setLayout (new FlowLayout()); field = new JTextField ("Watch the font style change", 20); field.setFont (new Font("Serif", Font.PLAIN, 14)); container.add(field); bold = new JCheckBox("Bold"); container.add(bold); italic = new JCheckBox ("Italic"); container.add (italic); 37
CheckBoxHandler handler = new CheckBoxHandler(); bold.addItemListener(handler); italic.addItemListener(handler); setSize(275,100); setVisible(true); } public static void main(String args[]) { CheckBoxTest application = new CheckBoxTest(); application.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); }
38
private class CheckBoxHandler implements ItemListener { private int valBold = Font.PLAIN; private int valItalic = Font.PLAIN; public void itemStateChanged(ItemEvent event) { if (event.getSource()==bold) if (event.getStateChange() == ItemEvent.SELECTED) valBold = Font.BOLD; else valBold = Font.PLAIN; if (event.getSource()==italic) if (event.getStateChange() == ItemEvent.SELECTED) valItalic = Font.ITALIC; else valItalic = Font.PLAIN;
}
field.setFont (new Font("Serif", valBold + valItalic, 14)); }
} 39
Output
40
JRadioButton Refer to the program CheckBox buttons In the contstructor class, you must : Create variables of type JRadioButton and a variable of type ButtonGroup
3.
private JRadioButton plainButton, boldButton; private ButtonGroup radioGroup;
Create radio button
4.
plainButton = new JRadioButton (“Plain”, true); Container.add (plainButton); 41
JRadioButton Register events for JRadioButtons
1.
RadioButtonHandler handler = new RadioButtonHandler(); plainButton.addItemListener(handler); boldButton.addItemListener(handler);
Create logical relationship between JRadioButtons
2.
radioGroup = new ButtonGroup(); radioGroup.add(plainButton); radioGroup.add(boldButton); 42
JRadioButton Create font objects
1.
plainFont = new Font(“Serif”, Font.PLAIN, 14); boldFont = new Font(“Serif”, Font.BOLD, 14);
43
JRadioButton
In the class RadioButtonHandler: public void itemStateChanged(ItemEvent event) { if (event.getSource() == plainButton) field.setFont(plainFont); else if (event.getSource() ==boldButton) field.setFont(boldFont); }
44
JComboBox
A combo box provides a list of items from which the user can make a selection. It generate ItemEvent like JCheckBox and JRadioButton
45
Example Program JComboBox //creating Combobox buttons import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ComboBoxTest extends JFrame { private JComboBox imagesComboBox; private JLabel label; private String names[] = {“rerama.gif", “bunga.gif"}; private Icon icons[] = {new ImageIcon (names[0]), new ImageIcon (names[1])}; public ComboBoxTest () { super ("JComboBoxTest"); Container container = getContentPane(); container.setLayout (new FlowLayout()); //set up JComboBox and register its event handler imagesComboBox = new JComboBox(names); imagesComboBox.setMaximumRowCount(3);
46
Example Program JComboBox (cont) imagesComboBox.addItemListener( //anonymous inner class to handle JComboBox events new ItemListener(){ public void itemStateChanged(ItemEvent event) { if (event.getStateChange() == ItemEvent.SELECTED) label.setIcon(icons[imagesComboBox.getSelectedIndex()]); } } ); //end call to addItemListener container.add(imagesComboBox); label = new JLabel(icons[0]); container.add(label); setSize(350, 100); setVisible(true); } 47
Example Program JComboBox public static void main (String args[]) (cont) {
ComboBoxTest application = new ComboBoxTest();
}
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } //end class
Output of Program JComboBox
48
Explanation of Program JComboBox It register an instance of an anonymous inner class that implements ItemListener as new ItemListener(){ public void the listener for JComboBox itemStateChanged(ItemEvent event) images.
imagesComboBox.addItemListener(
{
}
if (event.getStateChange() == ItemEvent.SELECTED) label.setIcon (icons[imagesComboBox. getSelectedIndex()]);
} ); //end call to addItemListener
When user make a selection from images, method itemStateChanged set the Icon for label. The Icon is selected from array icons by determining the index number of the selected item in the JComboBox with method getSelectedIndex.
49
JList
A list displays a series of items from which the user may select one or more items Lists are created with class JList which inherits from class JComponent Unlike JComboBox, JList do not provide a scrollbar if there are more items in the list than the number of visible rows. JScrollPane object is used to provide the automatic scrolling capability for the JList 50
Multiple Selection Lists
It enables the user to select many items from a JList A SINGLE_INTERVAL_SELECTION list allows selection of a contiguous range of items in the list by clicking the first item, then holding the Shift key while clicking the last item to select in the range.
51
Multiple Selection Lists
A MULTIPLE_INTERVAL_SELECTION list allows continuous range selection as described for a SINGLE_INTERVAL_SELECTION list and allows miscellaneous items to be selected by holding the Ctrl key while clicking each item to select To deselect, hold the Ctrl key while clicking the item a second time. 52
Layout Managers
Provided to arrange GUI components on a container for presentation purposes. Provide basic layout capabilities that are easier to use than determining the exact position and size of every GUI component
53
Layout Managers Layout Managers
Description
FlowLayout
Default for java.awt.Applet, java.awt.Panel and javax.swing.JPanel. Places components sequentially (left to right) in order they were added. It is also possible to specify the order of the components using Container method add that takes a Component and an integer index position as arguments Allows GUI component to be left-aligned (FlowLayout.LEFT), centered (default)(FlowLayout.CENTER), and right-aligned. (FlowLayout.RIGHT),
BorderLayout
Default for the correct panes of JFrame (and other windows) and JApplet. Arrange the components into five areas : North, South, East, West and Center Example : BorderLayout.NORTH;
GridLayout
Arranges the components into rows and columns 54
Flow Layout Example 1.
Declaration private Container container private FlowLayout layout
5.
Get content pane and set its layout container = getContentPane; container = setlayout(layout);
6.
Process left button event public void actionPerformed (ActionEvent event) { layout.setAlignment(FlowLayout.LEFT); //re-aligned attached components layout.layoutContainer(container); } 55
Mouse Event Handling
Can be trapped for any GUI component that derives from java.awt.Component. Using MouseListener and MouseMotionListener event-listener interfaces
56
Methods of Interface public void mousePressed (MouseEvent event) MouseListener Called when mouse button is pressed with the mouse cursor on a
component
public void mouseClicked (MouseEvent event) Called when mouse button is pressed and released on a component without moving the mouse cursor
public void mouseReleased (MouseEvent event) Called when mouse button is released after being pressed. This event is always preceded by a mousePressed event
public void mouseEntered(MouseEvent event) Called when mouse cursor enters the bounds of a component
public void mouseExited (MouseEvent event) Called when mouse cursor leaves the bounds of a component 57
Methods of Interface MouseMotionListener
public void mouseDragged (MouseEvent event)
Called when the mouse button is pressed with the mouse cursor on a component and the mouse is moved. This event is always preceded by a call to MousePressed
public void mouseMoved (MouseEvent event)
Called when the mouse is moved with the mouse cursor on a component 58
Keyboard event handling
Using KeyListener event-listener interface Methods of Interface KeyListener
public void keyPressed (KeyEvent event)
public void keyReleased (KeyEvent event)
Called in response to pressing any key Called when the key is released after any KeyPressed or keyTyped event
public void keyTyped (KeyEvent event)
Called in response to pressing any key that is not and action key (e.g an arrow key,Home,End) 59
Menus
Allows you to provide various functions without cluttering the GUI with too many components Menus can be attached to objects such as JFrame and JApplet – both have the method setJMenuBar that allows you to set a menu bar
60
Menus
To create a menu bar
To set the menu bar
private JMenuBar menuMB = new JMenuBar(); setMenyBar(menuMB);
Then, you can add menus and in each menu you can add menu items. Example, to create an Edit menu and add it to the menu bar:
JMenu editM = new JMenu(“Edit”); menuMB.add(editM); 61
Likewise, if you need to create a File menu, you may do so by adding the following lines of code:
JMenu fileM = new JMenu(“file”); menuMB.add(fileM);
The order in which you add menus to the menu bar determines the order in which they appear
62
Program segment in the method actionPerformed
declaration Private JMenuItem exitI, copyI; Private JTextArea pageTA =new JTextArea (); Private String scratchpad = “”;
In method actionPerformed(ActionEvent e) JMenuItem mItem = (JMenuItem) e.getSource(); if (mItem == exitI) System.exit(0); else if (mItem == mItem == copyI) scratchpad = pageTA.getSelectedText();
63