Chapter 1 Advanced Programming - Part II
Chapter 1 Advanced Programming - Part II
Introduction to Java
( Java GUI Design)
Part II
J a v a GUI (Graphical User Interface)
⦁ J ava GUI
• A visual interface to a program that are built from GUI
components (buttons, menus, labels etc).
• A G U I component is an object with which the user interacts
via the mouse or keyboard.
4
J a v a GUI (Graphical User Interface)
⦁ Swing
• a next-generation G U I toolkit that enable enterprise development
• A set of customizable graphical components whose look-and-feel
can be dictated at runtime.
import javax.swing.*;
• Consists nine AWT components, plus menus and containers, ha s
grown to a more complete and complex set of around 50 Swing
component.
5
J a v a GUI (Graphical User Interface)
⦁ Swing
• Swing components are the newest G U I components and called
pure java components.
6
J a v a GUI (Graphical User Interface)
Swing VS AWT
• O S independent • O S dependent
7
J a v a GUI (Graphical User Interface)
⦁ Swing
• Some of the components that didn’t originate in the AWT are:-
• JPasswordField: • JToolTip:
• JEditorPane and JTextPane: • JToolBar:
• JSpinner • JRadioButtonMenuItem
• JToggleButton: • JSeparator:
• JSlider: • JDesktopPaneand
• JProgressBar: JInternalFrame:
• JFormattedTextField: • JOptionPane:
• JTable: • JColorChooser:
• JTree: • JSplitPane:
8 • JTabbedPane:
J a v a GUI (Graphical User Interface)
⦁ Container
• a component that can contain another components like buttons,
Textfields, labels etc.
• S u b classes of Container are called as Container.
9
J a v a 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
J a v a 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
J a v a 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
J a v a 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
• The AWT Label is limited to a single line of text, the Swing JLabel
can have text, images, or both.
17
J a v a 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);
18
J a v a 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 • }}
J a v a 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);
20
J a v a 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);
21
text3.setText(result); }});
J a v a GUI Swing Elements
⦁ J B u t to n
used to create a labeled button that has platform independent
implementation.
22
J a v a GUI Swing Elements
⦁ J B u t to n 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");
24
J a v a GUI Swing Elements
⦁ J B u t to n Events
⦁ The most helpful listener with the J B u t to n is the ActionListener.
21
J a v a GUI Swing Elements
⦁ J B u t to n Events Example
buttn1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
txt1.setText("Mr. Hayelom");
txt2.setText(“Computer Science");
txt3.setText(“2 nd Year");
}});
buttn2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
txt1.setText(" ");
txt2.setText(" ");
txt3.setText(" ");
22
} });
J a v a 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.
javax.swing.JPasswordField class.
Example:
Swing Components
29
J a v a GUI Swing Elements
⦁ J C h e c k B ox
• is used to provide more than one choices to the user.
• D isplays a check box icon next to the text label for a two-state
option.
• The Icon u ses an optional check mark to show the cu rrent state
of the object.
30
J a v a 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 J C h e c k B ox Components
• JFormattedTextField:
• Provides for the input of formatted text like
• numeric values, phone numbers,
• dates, or social security numbers.
31
J a v a GUI Swing Elements
⦁ JRadioButton
• a graphical component that can be in either on (true) or off (false)
state in a group. (selected or deselected)
• With the predefined look and feel types, JRadi o B utton and
J C h e c k B ox components look different.
32
J a v a GUI Swing Elements
⦁ JRadioButton Constructors
public JRadioButton()
Eg. JRadioButton emptyButton = new JRadioButton();
public JRadioButton(String text)
Eg . JRadioButton fantaButton = new JRadioButton(“Fanta");
public JRadioButton(String text, Icon icon)
Icon fantaIcon = new ImageIcon(“fantaImage.jpg”);
JRadioButton fantaIconButton=new JRadioButton(“Fanta”, fantaIcon);
public JRadioButton(String text, boolean selected)
JRadioButton fantaSelectedButton = new JRadioButton(“Fanta”,true);
33
J a v a GUI Swing Elements
⦁ JToolTip
• display pop-up messages when the cursor rests over them.
• Tooltip text is normally one line long.
• component.setToolTipText(String text);
34
J a v a 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);
35
J a v a 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)
38
JTree (TreeNode root)
J a v a GUI Swing Elements
• JColorChooser
• used to create a color chooser dialog box so that user can select
any color.
• Constructors
JcolorChooser()
JColorChooser(color initialcolor)
Jcolor color=Jcolor(color,initialcolor);
38
J a v a 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()
39
J a v a 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
40
J a v a GUI Swing Elements
⦁ J L i s t Constructors
public JList()
Empty
Eg . JLi st list = new JList(); / / Creates an empty JList instance
41
J a v a GUI Swing Elements
⦁ J L i s t 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
42
J a v a GUI Swing Elements
⦁ J L i s t Properties
• visibleRowCount: allows you to deal with n um ber of rows of items
that can be visible at a time.
• E g . regionList.setVisibleRowCount(4);
frame.add(regionPane);
44
J a v a 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.
47
J a v a GUI Swing Elements
• JTextArea
• The text component for multiple-line input.
48
J a v a 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.
49
J a v a 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
52
J a v a GUI Swing Elements
• JMenuBar
• is the top-level widget.
52
J a v a 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
55
J a v a GUI Swing Elements
• JMenu
• By default, consecutively added menus are displayed from left to
right.
58
J a v a 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
59
J a v a 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);
60
J a v a 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.
65
J a v a 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
66
J a v a GUI Swing Elements
• JFileChooser
• represents a dialog window from which th e user c an select
file
• JFileChooser Constructors
• JFileChooser()
• JFileChooser(File currentDirectory)
• JFileChooser(String currentDirectoryPath)
67
J a v a 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)
68
Thank You
Next:Chapter 2
70