Chapter 1 Advanced Programming Part II
Chapter 1 Advanced Programming Part II
Introduction to Java
(Review)
Part II
Mulugeta G.
Java GUI (Graphical User Interface)
Java GUI
• A visual interface to a program that are built from GUI
components (buttons, menus, labels etc).
• A GUI component is an object with which the user interacts
via the mouse or keyboard.
• The classes that are used to create GUI components are
part of the java.awt or javax.swing package.
• Both these packages provide rich set of user interface
2
components.
Java GUI (Graphical User Interface)
AWT (Abstract Window Toolkit)
• is an API to develop GUI or window-based applications in java.
• It provided only the minimal amount of functionality necessary to
create a windowing application.
import java.awt.*; // for AWT graphics
• AWT Components such as Frame, Label, Button, TextField,
ComboBox, Radiobox, Textbox etc.
• As Java technologies became more popular, users realized AWT
4
Java GUI (Graphical User Interface)
Swing
5 component.
Java GUI (Graphical User Interface)
Swing
Swing VS AWT
• OS independent • OS dependent
• Light weight • Heavy weight
• base on Write once use • Not consistent as compared
anywhere to Swing
• Uniform feel and look • change behavior due to OS
• rich set of object • less as compared to swing
7
Java GUI (Graphical User Interface)
Swing
9
Java GUI (Graphical User Interface)
Container
• Window
a container that have no borders and no menu bars.
• Panel
A container that doesn't contain title bar and menu bars.
It provides space in which any other component like button,
textfield etc can be placed, including other panels.
• Frame
A container that contain title and border.
It can have other components like button, textfield etc.
10
Java GUI (Graphical User Interface)
Methods of Component Class
• add(Component C)
• Inserts a component of the component
• setSize (int width, int Height)
• Sets the size of the component
• setLayout(LayoutManager M)
• Defines the layout manager for the component
• setVisible(Boolean status)
• Changes the visibility of the component, by default false
11
Java GUI (Graphical User Interface)
Methods of Component Class
setTitle(String)
• used to set display user defined message on title bar.
setBackground(color)
• used to set background color.
setForeground(color)
• used to set Foreground or text color.
12
Java Layouts Managers
The most important layout managers are:
• BorderLayout
• Provides five areas into which you can put components
• default layout manager for both JFrame and Japplet
• FlowLayout: Components are added left to right, top to bottom
• GridLayout: Components are put in a rectangular grid with the
same size and shape
• BoxLayout: Creates a horizontal row or a vertical stack and it’s
a little weird to use
13
Java Layouts Managers
Nested Layouts
A JPanel is both a JContainer and a Component
Because it’s a container, you can put other components into it
Because it’s a component, you can put it into other containers
Simplest GUIs are built by creating several JPanels, arranging
them, and putting components (possibly other JPanels) into them
A good approach is to draw (on paper) the arrangement you want,
then finding an arrangement of JPanels and their layout
managers that accomplishes this
14
Event Handling
• Changing the state of an object is known as an event.
• Involves the process of responding to an action or occurrence triggered by
a user, system, or other external source.
• The action or occurrence is called event, and the code that execute in
response to the even is called event handler.
• The java.awt.event package provides many event classes and Listener
interfaces for event handling.
• Steps for java event handling
• Define the event source
• Register an event listener
• Implement the event listener
• Handle the event
18
JLabel label = new JLabel("Dog");
Java GUI Swing Elements
JButton
19
Java GUI Swing Elements
JButton Constructors
public JButton() public JButton(Action action)
JButton button = new JButton(); Action action = ...;
public JButton(Icon image) JButton button = new JButton(action);
Icon icon = new ImageIcon("dog.jpg");
JButton button = new JButton(icon);
public JButton(String text)
JButton button = new JButton("Dog");
23
Java GUI Swing Elements
JTextField Constructor
public JTextField()
JTextField textField = new JTextField();
public JTextField(String text)
JTextField textField = new JTextField("Initial Text");
public JTextField(int columnWidth)
JTextField textField = new JTextField(14);
public JTextField(String text, int columnWidth)
JTextField textField = new JTextField("Initial Text", 14);
24
Java GUI Swing Elements
JTextField Events
• actionListeners: is used to declare and define listeners for
textfield objects.
• Actions for a textfield happens when the user types in the
textfield and press enter key.
• Like Button object, textfield actionListeners listens and take
actions by implementing actionPerformed method as shown
in the following code fragement.
• Syntax: ActionListener actionListener = new ActionListener(){
• public void actionPerformed(ActionEvent event){
• //the code goes here.
25
• }}
Java GUI Swing Elements
JTextField Properties
• setEditable(boolean bool): used to change the editability of a
textfield object.
• if bool is true then user can write into a textfield and edit its
content otherwise it’s false not to edit the content.
• Eg. userText.setEditable(false);
• setHorizontalAlignment(int): used to adjust the position of the
text in the textfield object.
• The int has three types of values: JTextField.LEFT,
JTextField.CENTER, JTextField.RIGHT.
Syntax: textField.setHorizontalAlignment(JTextField.RIGHT);
26
Java GUI Swing Elements
JTextField Example
addition.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String s1=text1.getText();
String s2=text2.getText();
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
int c=0;
c=a+b;
String result=String.valueOf(c);
27
text3.setText(result); } });
Java GUI Swing Elements
JPasswordField
Used for password entry and you cannot use cut or copy operations within
the component, but you can paste text into it.
data written in the passwordfield is retrieved by getText() method
javax.swing.JPasswordField class.
Example:
Swing Components
29
Java GUI Swing Elements
JCheckBox
31
Java GUI Swing Elements
• JToggleButton
• it is two-states button to switch on or off.
• a button that stays depressed when selected.
• It is identical with the JCheckBox Components
JToggleButton tb=new JToggleButton(“ON");
• JFormattedTextField:
• Provides for the input of formatted text like
• numeric values, phone numbers,
• dates, or social security numbers.
32
Java GUI Swing Elements
JRadioButton
35
Java GUI Swing Elements
• JProgressBar
• allows the user to visually see the progress of an activity.
• used to display the progress of the task
• JProgressBar Constructors
JPrograssBar() eg. JPrograssBar jb=new JProgressBar();
JPrograssBar(int min, int max) eg.JPrograssBar jb=new JProgressBar(0,
200);
JPrograssBar(int orient)
• JPrograssBar jb=new JProgressBar(Horizontal or vertical);
JPrograssBar(int orient, int min, int max)
• JPrograssBar jb=new JProgressBar(horizontal/ vertical, value, value);
36
Java GUI Swing Elements
• JTable
• used to display data in tabular form
• JTable Constructors
Jtable()
• JTable jt=new JTable();
• JTree Constructors
JTree()
• JTree jt=new JTree(style);
JTree (object [] value)
• Constructors
JcolorChooser()
JColorChooser(color initialcolor)
Jcolor color=Jcolor(color,initialcolor);
39
Java GUI Swing Elements
• JTabbedPane
• used to switch between a group of components by clicking on a
tab with a given title or icon
• Constructors
JTabbedPane()
40
Java GUI Swing Elements
JList
• Used for selecting one or more items from a set of choices.
• You present the list of choices to the user, and the user can pick
one or several, depending on the selection mode of the
component.
• Three key elements and their implementations define the JList
structure:
• A data model for holding the JList data
• A cell renderer for drawing the elements of the JList
• A selection model for selecting elements of the JList
41
Java GUI Swing Elements
JList Constructors
public JList()
Empty
Eg. JList list = new JList(); // Creates an empty JList instance
42
Java GUI Swing Elements
JList Properties
• selectedValue: It works only when a single item is selected in the list.
• Eg. regionList.setSelectedValue(“Afar”);
• Eg. regionList.getSelectedValue();
• selectedIndex: allows you deal with the index of an item.
• Two methods exist: setSelectedIndex(int) & getSelectedIndex();
• Eg. regionList.setSelectedIndex(1); //Selects “Amhara”
• Eg. regionList.getSelectedIndex(); //Returns index of selected item
• Eg. int region[] = {1,3};
• regionList.setSelectedIndexes(region); //Selects “Amhara” & “Oromia
43
Java GUI Swing Elements
JList Properties
• visibleRowCount: allows you to deal with number of rows of items
that can be visible at a time.
• Eg. regionList.setVisibleRowCount(4);
• You must place the component within a JScrollPane
• JScrollPane offers the Jlist a vertical scrollbar
to move through all the available choices.
Otherwise only the top group of choices will be visible
44
Java GUI Swing Elements
• Scrolling JList components and displaying them on containers:
• Create JList component as usual
String regions[] = {“Tigray”,”Afar”,”Amhara”,”Oromia”,”Somali”,”SNNP”};
frame.add(regionPane);
45
Java GUI Swing Elements
• JComboBox
• is a multiple-part component.
• Allows a user to choose from a predefined set of choices with the
help of a pull-down list.
• When the desired choice isn’t available, the JComboBox can use
a JTextField to enter a new choice.
• The text field for editing is disabled by default, permitting a
user to select from the set of predefined choices only
46
Java GUI Swing Elements
• JComboBox Constructors
public JComboBox()
JComboBox emp = new JComboBox();
– Creates an empty list JComboBox instance.
48
Java GUI Swing Elements
• JTextArea
• The text component for multiple-line input.
49
Java GUI Swing Elements
• JTextArea Constructors
JTextArea() Creates a text area that displays no
text initially.
JTextArea(String s) Creates a text area that displays
specified text initially.
JTextArea(int row, int cols) Creates a text area with the specified
number of rows and columns that
displays no text initially.
JTextArea(String s, int row, Creates a text area with the specified
int column) number of rows and columns that
displays specified text.
50
Java GUI Swing Elements
• JTextArea Methods
Methods Description
void setRows(int rows) It is used to set specified number of
rows.
void setColumns(int cols) It is used to set specified number of
columns.
void setFont(Font f) It is used to set the specified font.
void insert(String s, int position) It is used to insert the specified
text on the specified position.
void append(String s) It is used to append the given text
to the end of the document.
51
Part IV
Swing Components
52
53
Java GUI Swing Elements
• JMenuBar
• is the top-level widget.
54
Java GUI Swing Elements
• JMenuBar
• Once you create the menu bar, you can add it to a window with
the setJMenuBar() method and appears at the top of the window
• You can also use the add() method of a Container to add a
JMenuBar to a window. And is arranged by the layout manager of
the Container.
JFrame f = new JFrame("Menu Example");
JMenuBar menuBar = new JMenuBar();
f.setJMenuBar(menuBar); // f.add(menuBar);
55
Java GUI Swing Elements
• JMenu
• is a pull down menu component which is displayed from the
menu bar
57
Java GUI Swing Elements
• JMenu
• By default, consecutively added menus are displayed from left to
right.
• add(Component component, int index) method, which allows
you to specify the position in which the new JMenu is to appear.
JMenuBar menuBar = new JMenuBar();
JMenu menu1 = new JMenu(“File”);
menuBar.add(menu1,0);
• To Remove Menu use: menuBar.remove(menu1);
58
Java GUI Swing Elements
• JMenuItem
• is the predefined component that a user selects on a menu bar.
• acts as a specialized button component similar to a JButton.
• Once you have a JMenu, you need to add JMenuItem objects to
it; otherwise, the menu will not display any choices.
• You have to add a separator to JMenu after adding a JMenuItem
JMenuItem jMenuItem = new JMenuItem();
• To add separator use: jMenuItem.addSeparator() Method
59
Java GUI Swing Elements
• JMenuItem Constructor
public JMenuItem()
• JMenuItem jMenuItem = new JMenuItem();
public JMenuItem(Icon icon)
• Icon atIcon = new ImageIcon("at.gif");
• JMenuItem jMenuItem = new JMenuItem(atIcon);
public JMenuItem(String text)
• JMenuItem jMenuItem = new JMenuItem("Cut");
60
Java GUI Swing Elements
• JMenuItem Constructor
public JMenuItem(String text, Icon icon)
• Icon atIcon = new ImageIcon("at.gif");
• JMenuItem jMenuItem = new JMenuItem("Options", atIcon);
public JMenuItem(String text, int mnemonic)
• JMenuItem jMenuItem = new JMenuItem("Cut",
KeyEvent.VK_T); // Alt - C
Mnemonic allows you to select the menu through keyboard navigation
61
Java GUI Swing Elements
• JMenuItem Properties
• accelerator: This property allows you to add a functionality that
can help you use the menu item from your keyboard.
• It uses a KeyStroke factory class that lets you create
instances based on key and modifier combinations.
• Here is how you can use this property:
• First create an instance of KeyStroke class and use the
setAccelarator(KeyStroke) method to set up an accelerator for
the menu item.
KeyStroke cutMenuItemStroke = KeyStroke.getKeyStroke("control X");
cutMenuItem.setAccelerator(cutMenuItemStroke);
62
Java GUI Swing Elements
• JMenuItem Events
• allow you to listen for the firing of ChangeEvent and ActionEvent
through the ChangeListener and ActionListener registration
methods of AbstractButton.
• The better listener to attach to a JMenuItem is the
ActionListener.
• It allows you to find out when a menu item is selected.
• MenuKeyEvent - represents an event occurred on a menu item.
63
Java GUI Swing Elements
• JMenuItem Events
• getSource(): returns the object where the event occurred. Not
very useful.
• getKeyChar(): returns the character represented by the key that
triggered event.
• getKeyCode(): returns the code value represented by the key
that triggered event.
• getKeyText(): returns the text name of a given key code value.
• getPath(): returns a list of menu objects representing a path in
the menu tree.
64
Java GUI Swing Elements
• Here is the general way you have to do when you work with JMenu:
• Create a JMenuBar and add it to conatiner
• Create a JMenu component and add it to the JMenuBar.
• For the selections available from the JMenu, you create JMenuItem
components and add them to the JMenu.
• To create submenus, you add a new JMenu to a Jmenu and place
JMenuItem options on the new menu.
• Then, when a JMenu is selected, the system displays its current set of
components within a JPopupMenu.
65 • JPopupMenu dynamically popped up at specific position
Java GUI Swing Elements
• JSeparator
• used to provide a general purpose component for implementing
divider lines.
• It is used to draw a line to separate widgets in a Layout.
• Jseparator Constructors
Jseparator()
JSeparator sep = new JSeparator();
Jseparator(int orientation)
JSeparator sep = new JSeparator(horizontal);
66
Java GUI Swing Elements
• JToolBar
• allows us to group other components, usually buttons with icons
in a row or column.
• provides a component which is useful for displaying commonly
used actions or controls.
67
Java GUI Swing Elements
• JToolBar Constructors
Constructor Description
JToolBar() It creates a new tool bar; orientation
defaults to HORIZONTAL.
JToolBar(int orientation) It creates a new tool bar with the
specified orientation.
JToolBar(String name) It creates a new tool bar with the
specified name.
JToolBar(String name, int It creates a new tool bar with a
orientation) specified name and orientation
68
Java GUI Swing Elements
• JFileChooser
• represents a dialog window from which the user can select
file
JFileChooser fc=new JFileChooser();
• JFileChooser Constructors
• JFileChooser()
• JFileChooser(File currentDirectory)
• JFileChooser(String currentDirectoryPath)
69
Java GUI Swing Elements
• JOptionPane
• used to provide standard dialog boxes such as message dialog
box, confirm dialog box and input dialog box.
• JOptionPane Constructors
• JOptionPane()
• JOptionPane(object, Message)
• JOptionPane(Object, Message, Message type)
70
Thank You
Next: Chapter 2
71