Download 3.4 Adjusting the CelsiusConverter GUI (As shown in Figure 1.9)

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Faculty of Computing and IT NJB
King Abdulaziz University
North Jeddah Branch
Saudi Arabia
Laboratory Manual
Course Codes: CPCS-354, CPIT- 280 and CPIS-354
Course Title: Human Computer Interaction
Faculty of Computing and IT NJB
Document Version History
Version
Date
Prepared By
Reviewed By
Approved By
1.0
20/09/2012
Shahzad Qamar
Dr. Muhammad Tahir
Dr. Muhammad Tahir
1.1
19/11/2013
Bandar Alkhalil
…………………..
……………………..
Faculty of Computing and IT NJB
Table of Contents
Table of Contents
Lab 1 - Introduction to Java Swings ...................................................... Error! Bookmark not defined.
Lab 2 - .................................................................................................. Error! Bookmark not defined.
Lab 3 - Topic ......................................................................................... Error! Bookmark not defined.
Lab 4 - Topic ......................................................................................... Error! Bookmark not defined.
Lab 5 - Topic ......................................................................................... Error! Bookmark not defined.
Lab 6 - Topic ......................................................................................... Error! Bookmark not defined.
Lab 7 - Topic ......................................................................................... Error! Bookmark not defined.
Lab 8 - Topic ......................................................................................... Error! Bookmark not defined.
Lab 9 - Topic ......................................................................................... Error! Bookmark not defined.
Lab 10 - Topic ....................................................................................... Error! Bookmark not defined.
Lab 11 - Topic ....................................................................................... Error! Bookmark not defined.
Lab 12 - Topic ....................................................................................... Error! Bookmark not defined.
Lab 13 - Topic ....................................................................................... Error! Bookmark not defined.
Lab 14 - Topic ....................................................................................... Error! Bookmark not defined.
Lab 15 - Topic ....................................................................................... Error! Bookmark not defined.
Faculty of Computing and IT NJB
AIMS AND OBJECTIVES OF THE HCI LAB
AIMS





Practical Programming of Human Computer Interfaces
Introduction to HCI programming in Java: AWT and Swing
Introduction to Mobile HCI programming in Java: Java MIDlets
Introduction to basic HCI components and how to use them
Overview of other Java Foundation Classes: AWT, Accessibility, 2D API and Drag and
Drop
OBJECTIVES




Knowledge of availability and usage of basic HCI components
Understand how components can effectively be used together
Understand the Java Foundation Class (JFC) Packages
Be able to program in Java Swing, Java MIDlet and other JFC packages
Recommended Book
Java Swing by Robert Eckstein, Marc Loy, Dave Wood O'Reilly and Associates; ISBN:
156592455X
Faculty of Computing and IT NJB
Laboratory Session 1: Introduction to HCI and Java Swings
Objectives: The objective of this Lab is to familiarize students with the importance of HCI, to
introduce them with Java Swings and to teach them how to create a project in NetBeans.
Outcomes:



By the end of this Lab student will know the importance of HCI.
Students will be familiarized with Java Swings and AWT.
Students will be able to use NetBeans for creating Java Swings applications.
1. Introduction to Human Computer Interaction
The term Human Computer Interaction (HCI) was adopted in the mid-1980s as a means of
describing this new field of study. The well known definition of HCI is the following. “HumanComputer Interaction is a discipline concerned with the design, evaluation and implementation of
interactive computing systems for human use and with the study of major phenomena
surrounding them” (IEEE/ACM)
1.1 Difference between Software Engineering and HCI
There is a basic fundamental difference between the approaches taken by software engineers and
human-computer interaction specialists. Human-computer interface (HCI) specialists are usercentered and software engineers are system-centered. Therefore in this course our focus will be
mainly on the development of good designs.
2. Introduction to Java Swings
Swing did not exist in the early days of Java. Rather, it was a response to deficiencies present in
Java’s original GUI subsystem: the Abstract Window Toolkit. The AWT defines a basic set of
controls, windows, and dialog boxes that support a usable, but limited graphical interface. In
order to eliminate the deficiencies in AWT, Swing was introduced in 1997. Swing was initially
available for use with Java 1.1 as a separate library. However, beginning with Java 1.2, Swing
(and the rest of the JFC) was fully integrated into Java.
Swing is basically a set of customisable graphical components whose look-and-feel can be
dictated at runtime.
2.1.
Swing Features


Pluggable look-and feels
Lightweight components
o Do not depend on native peers to render themselves.
o Simplified graphics to paint on screen
o Similar behaviour across all platforms
o Portable look and feel
o Only a few top level containers not lightweight.
Faculty of Computing and IT NJB




New components -- tress tables, sliders progress bars, frames, text components.
Tooltips -- textual popup to give additional help
arbitrary keyboard event binding
Debugging support
3. Practical Work
3.1.
Learning Swing with Net Beans IDE and Setting Up New Project:
The Net Beans IDE is a free, open-source, cross-platform integrated development environment
with built-in support for the Java programming language. It offers many advantages over coding
with a text editor.
Step 1: Run Net Beans and close down any open projects. Move to File tab and select New
Project. From the pop-up Form select Java and Java Application, you should have something
similar to figure 1.1.
Figure 1.1 Setting up a Java Application Project
Step No 2: Click Next and change the following.
Project Name: Celsius ConvertorProject
Project Location: C:\HCI
Faculty of Computing and IT NJB
Project Folder: C:\HCI\CelsiusConvertorProject
VERY IMPORTANT
1:
Ensure that Set as Main Project is checked.
2:
Create Main class is un-checked.
You should have something similar to Figure 1.2. Click Finish
Figure
1.2:
Setting
up
a
Java
Application
Project
When the IDE finishes loading, you will see a screen similar to the below Figure 1.3. All panes
will be empty except for the Projects pane in the upper left hand corner, which shows the newly
created project.
Faculty of Computing and IT NJB
Figure 1.3: Setting up a Java Application Project
Step # 3: Adding a JFrame Form
Right click on the CeliusConvertorProject and choose New -> JFrame Form (JFrame is the Swing
class responsible for the main frame for your application). You should have something similar to
Figure 1.4.
Figure 1.4: Creating a Java Swing
Faculty of Computing and IT NJB
Step # 4:
Name the GUI Class
Change the following.
Class Name:
CelsiusConvertorGUI
The remainder of the fields should automatically be filled in, as shown above. Click the Finish
button when you are done, you will see something like Figure 1.5.
Figure 1.5:
The Java Swing editor
When the IDE finishes loading, the right pane will display a design-time, graphical view of
the CelsiusConverterGUI. It is on this screen that you will visually drag, drop, and manipulate the
various Swing components.
3.2.
NetBeans IDE Basics
It is not necessary to learn every feature of the NetBeans IDE before exploring its GUI creation
capabilities. In fact, the only features that you really need to understand are thePalette, the Design
Area, the Property Editor, and the Inspector. We will discuss these features below.
3.2.1
The Palette
The Palette contains all of the components offered by the Swing API. You can probably already
guess what many of these components are for, even if this is your first time using them
(JLabel is a text label, JList is a drop-down list, etc).
Faculty of Computing and IT NJB
Figure 1.6: Palette
3.2.2.
The Design Area
The Design Area is where you will visually construct your GUI. It has two views: source view,
and design view. Design view is the default, as shown below. You can toggle between views at
any time by clicking their respective tabs.
Figure 1.6: The Design Area
3.2.3.
The Property Editor
The Property Editor does what its name implies: it allows you to edit the properties of each
component. The Property Editor is intuitive to use; in it you will see a series of rows — one row
per property — that you can click and edit without entering the source code directly. The
following figure shows the Property Editor for the newly added JFrameobject.
Faculty of Computing and IT NJB
Figure 1.7: The Property Editor
3.3
Creating CelsiusConvertor GUI (As shown in the Figure 1.8)




Set the Tile
Add JText Field
Add two JLabels
Add JButton
Figure 1.8. Simple Layout
Faculty of Computing and IT NJB
3.4
Adjusting the CelsiusConverter GUI (As shown in Figure 1.9)
Step 1: Set the Component Text
Step 2: Set the Component Size
Step 3: Remove Extra Space
3.5
Adding the Application Logic
Step 1: Change the Default Variable Names
The default names are not very relevant in the context of this application, so it makes sense to
change them from their defaults to something that is more meaningful. Right-click each variable
name and choose "Change variable name."
Make the following changes:
JText
to
tempTextField
JLabel1
to
Jbutton to
convertButton
JLabel2 to
fahrenheitLabel
celsiusButton
Step 2: Register the Event Listeners
When an end-user interacts with a Swing GUI component (such as clicking the Convert button),
that component will generate a special kind of object — called an event object— which it will
then broadcast to any other objects that have previously registered themselves as listeners for that
event. The NetBeans IDE makes event listener registration extremely simple:
Faculty of Computing and IT NJB
Figure 1.10: Event Listener
Step 3: Add the Temperature Conversion Code
The final step is to simply paste the temperature conversion code into the empty method body.
The following code is all that is necessary to convert a temperature from Celsius to Fahrenheit:
private void convertButtonActionPerformed(java.awt.event.ActionEvent evt) {
int tempFahr = (int) ((Double.parseDouble(tempTextField.getText())) * 1.8 + 32);
fahrenheitLabel.setText(tempFahr + " Fahrenheit");
}
Step 4: Run the Application
Running the application is simply a matter of choosing Run -> Run Main Project within the
NetBeans IDE. The first time you run this application, you will be prompted with a dialog asking
to set CelsiusConverterGUI as the main class for this project. Click the OK button, and
when the program finishes compiling, you should see the application running in its own window.
You can see something like Figure 1.11.
Figure 1.11: Output
Home Tasks


Read more about HCI and Java Swings
Do the above process by yourself at home
Faculty of Computing and IT NJB
HCI Programming with Java Swing
We have seen how data can be communicated in a Java in a sequential type manner. There are
however times (most of the time) when we need to handle data in a more random manner from a
human computer interface (HCI). The Java Swings library handles this form of input and output
in Java. It contains pre-built classes of graphical interface elements and even basic drawing
primitives. The Swing can be broken down into a number of groups of related classes. Swing
library is an official Java GUI toolkit released by Sun Microsystems.
The main characteristics of the Swing toolkit
· platform independent
· customizable
· extensible
· configurable
· lightweight
Swing consists of the following packages
· javax.swing
· javax.swing.border
· javax.swing.colorchooser
· javax.swing.event
· javax.swing.filechooser
· javax.swing.plaf
· javax.swing.plaf.basic
· javax.swing.plaf.metal
· javax.swing.plaf.multi
· javax.swing.plaf.synth
· javax.swing.table
· javax.swing.text
· javax.swing.text.html
· javax.swing.text.html.parser
· javax.swing.text.rtf
· javax.swing.tree
· javax.swing.undo
Swing is a part of JFC, Java Foundation Classes. It is a collection of packages for creating full
featured desktop applications. JFC consists of AWT, Swing, Accessibility, Java 2D, and Drag and
Drop. Swing was released in 1997 with JDK 1.2. It is a mature toolkit.
HCI Elements:
JButtons:- JButtons are normally used to signify that some form of processing is required. A
JButton class within the Java Swing, consider: JButton onButton = new JButton(“On”); this
create a button with a lable “On”. As with any class of object there are number of methods
associated with the object, two commonly used methods are setLabel, which allows you to
Faculty of Computing and IT NJB
change the label and getLabel, which returns the buttons current label i.e. String name =
onButton.getLabel();
JLabel: Labels are just strings that can be palced within containers, consider: JLabel myLabel =
new JLabel (“Welcome to Java Swing”);
JCheckbox: A checkbox is used to indicate some change in sate of a system, and as with all
other control elements checkboxes are created using new, for example: JCheckbox myCheckbox
= new JCheckbox(“Hello”); Here again we have as set of methods to determine if a check box
has been clicked or not. The method getState returns a Boolean true if the check box had been
clicked using a mouse button or false if t has not. The checkboxes are independent and as such
they can both be checked or either one to be checked or neither be checked.
Radio Buttons: Radio buttons are a special case of check boxes. Radio buttons are grouped
together and have the property that only of the boxes s checked at a time. Radio buttons are
created from checkboxes by means of a constructor which connects them to a checkbox group,
consider:
JCheckboxGroup department = new CheckboxGroup();
JCheckbox Electronics = new JCheckbox(“Electronics”,department,true);
The getState method will find which radio button is true.
Choice: A choice is a pop-up menu, which allows the user to specify a number of strings that can
be selected. The code for creating a choice is shown below
JChoice departmentChoice = new JChoise();
DepartmentChoice.addItem(“Electronics”);
Text Fields: A text field is a part of interface object into which a user can type text. TextField are
created by using the JTextField class, for example JTextField myTextField = new JTextField
(“Type Text Here”, 240); Will create a text field which will have 24 columns, with the the text
“type Text Here” contained within one column in the text field.
Faculty of Computing and IT NJB
Laboratory Session 2: First Java Swing Application
Step 1: Run Netbeans and move to File tab and select New Project. From the pop-up form select
Java and Java Application. You will see something like figure 2.1.
Figure 2.1: Setting up a Java Project
Step 2: Click Next and changes the following.
Project Name: HCIProjects
Project Location: C:\HCI
Project Folder: C:\HCI\HCIProject
Very Important:
1. Ensure that Set as a Main Project is checked
2. Create Main class is un-checked
You will see something similar to figure 2.2.
Faculty of Computing and IT NJB
Figure 2.2:
Step 3: Right click on the HCIProjects and choose New -> Java Class. You should have similar
screen like Figure 2.3.
Figure 2.3:
Step 4: Name the Java Class
Faculty of Computing and IT NJB
Change the following.
Class Name: Sample
The remainder of the fields should automatically ne filled in. Click the Finish button when you
are done. You will see something like figure 4.
Figure 2.4:
Step 5: Write the following code for Sample Class.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Shahzad
*/
import javax.swing.JFrame;
public class Sample extends JFrame {
public Sample()
Faculty of Computing and IT NJB
{
setSize(300, 200);
setTitle("Simple");
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
Simple obj = new Simple();
obj.setVisible(true);
}
}
Step 6: Run your application and you will see the following output.
Figure 2.5: Result from Sample.java
Explanation:
While this code is very small, the application window can do quite a lot. It can be resized,
maximized, minimized. All the complexity that comes with it has been hidden from the
application programmer.
import javax.swing.JFrame;
Here we import the JFrame widget. It is a top level container, which is used for placing other
widgets.
setSize(300, 200);
setTitle("Simple");
Faculty of Computing and IT NJB
This code will resize the window to be 300px wide and 200px tall. It will set the title of the
window to Simple.
setDefaultCloseOperation(EXIT_ON_CLOSE);
This method will close the window, if we click on the close button. By default nothing happens.
Faculty of Computing and IT NJB
Laboratory Session 3: Centring window on the screen
By default, when the window is shown on the screen, it is not centered. It will pop up most likely
in the upper left corner. The following code example will show the window centered on the
screen.
Step 1: Run Netbeans and if you are not placed back in your project simply open it. Move to the
projects tab and right mouse click on the project name, from the pop-up menu select New and
from the next pop-up menu select Java Class. You will be presented with a New Java Class form,
edit the form to:
Class Name:
Project:
Location:
Package:
Create File:
CenterScreen
HCIProject (Should already be set)
Source Package (Should already be set)
Should already be set
Should already be set
Click finish and you should be placed back into the editor.
Step 2: Edit CenterScreen.java to:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Shahzad
*/
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class CenterOnScreen extends JFrame {
public CenterOnScreen()
{
setSize(300, 200);
setTitle("CenterOnScreen");
setDefaultCloseOperation(EXIT_ON_CLOSE);
Toolkit toolkit = getToolkit();
Dimension size = toolkit.getScreenSize();
setLocation(size.width/2 - getWidth()/2,size.height/2 – getHeight()/2);
}
public static void main(String[] args) {
CenterOnScreen cos = new CenterOnScreen();
cos.setVisible(true);
}
Faculty of Computing and IT NJB
}
Explanation:
To center the window on the screen, we must know the resolution of the monitor. For this, we use
the Toolkit class.
Toolkit toolkit = getToolkit();
Dimension size = toolkit.getScreenSize();
We get the toolkit and figure out the screen size.
setLocation(size.width/2 - getWidth()/2, size.height/2 - getHeight()/2);
To place the window on the screen, we call the setLocation() method.
Faculty of Computing and IT NJB
Laboratory Session 4: Tooltip
Tooltips are part of the internal application's help system. The Swing shows a small
rectangular window, if we put a mouse pointer over an object (e.g. Button, TextField, Menu etc).
Step 1: Run Netbeans and if you are not placed back in your project simply open it. Move to the
projects tab and right mouse click on the project name, from the pop-up menu select New and
from the next pop-up menu select Java Class. You will be presented with a New Java Class form,
edit the form to:
Class Name:
Project:
Location:
Package:
Create File:
Tooltip
HCIProject (Should already be set)
Source Package (Should already be set)
Should already be set
Should already be set
Click finish and you should be placed back into the editor.
Step 2: Edit Tooltip.java to:
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Shahzad
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Shahzad
*/
public class Tooltip extends JFrame {
private Toolkit toolkit;
public Tooltip()
{
//Constructor
Faculty of Computing and IT NJB
setTitle("Tooltip");
setSize(300, 200);
toolkit = getToolkit();
Dimension size = toolkit.getScreenSize();
setLocation((size.width - getWidth())/2, (size.height - getHeight())/2);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(null);
panel.setToolTipText("A Panel container");
JButton button = new JButton("Button");
button.setBounds(100, 60, 100, 30);
button.setToolTipText("A button component");
panel.add(button);
}
public static void main(String[] args) {
Tooltip tooltip = new Tooltip();
tooltip.setVisible(true);
}
}
Explanation:
In the example, we set the tooltip for the frame and the button.
panel.setToolTipText("A Panel container");
To enable a tooltip, we call the setTooltipText() method.
Faculty of Computing and IT NJB
Laboratory Session 5: Creating a Menu
A menu bar is one of the most visible parts of the GUI application. It is a group of commands
located in various menus. In Java Swing, to implement a menu bar, we use three objects. A
JMenuBar, a JMenu and a JMenuItem.
Step 1: Run Netbeans and if you are not placed back in your project simply open it. Move to the
projects tab and right mouse click on the project name, from the pop-up menu select New and
from the next pop-up menu select Java Class. You will be presented with a New Java Class form,
edit the form to:
Class Name:
Project:
Location:
Package:
Create File:
Menu
HCIProject (Should already be set)
Source Package (Should already be set)
Should already be set
Should already be set
Click finish and you should be placed back into the editor.
Step 2: Edit Menu.java to:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class Menu extends JFrame {
public Menu()
{
setTitle("JMenuBar");
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem fileClose = new JMenuItem("Close");
fileClose.setToolTipText("Exit application");
fileClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
menubar.add(file);
setJMenuBar(menubar);
file.add(fileClose);
setVisible(true);
setSize(320,260);
setLocationRelativeTo(null);
}
Faculty of Computing and IT NJB
public static void main(String[] args) {
Menu men = new Menu();
men.setVisible(true);
}
}
Step 6: Run your application and you will see the following output.
Explanation:
In the above example there is a menu with one item. Selecting the close menu item we close the
application.
JMenuBar menubar = new JMenuBar();
Here we create a menubar.
JMenu file = new JMenu("File");
We create a menu object. The menus can be accessed via the keybord as well. To bind a
menu to a particular key.
fileClose.setToolTipText("Exit application");
This code line creates a tooltip for a menu item.
Faculty of Computing and IT NJB
Laboratory Session 6: Creating a Sub Menu
Each menu can also have a submenu. This way we can group similar commands into
groups. For example we can place commands that hide/show various toolbars like personal bar,
address bar, status bar or navigation bar into a submenu called toolbars. Within a menu, we can
separate commands with a separator. It is a simple line. It is common practice to separate
commands like new, open, save from commands like print, print preview with a single separator.
Menus commands can be launched via keyboard shortcuts. For this, we define menu item
accelerators.
Step 1: Run Netbeans and if you are not placed back in your project simply open it. Move to the
projects tab and right mouse click on the project name, from the pop-up menu select New and
from the next pop-up menu select Java Class. You will be presented with a New Java Class form,
edit the form to:
Class Name:
Project:
Location:
Package:
Create File:
Submenu
HCIProject (Should already be set)
Source Package (Should already be set)
Should already be set
Should already be set
Click finish and you should be placed back into the editor.
Step 2: Edit Submenu.java to:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class Submenu extends JFrame {
public Submenu()
{
setTitle("Submenu");
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem a = new JMenuItem("a");
JMenuItem b = new JMenuItem("b");;
JMenuItem fileClose = new JMenuItem("Close");
/* File Close Code */
fileClose.setToolTipText("Exit application");
fileClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
Faculty of Computing and IT NJB
/* A Print Code */
a.setToolTipText("Print a");
a.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.out.println("A");
}
});
/* B Print Code */
b.setToolTipText("Print b");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.out.println("B");
}
});
file.add(a);
file.add(b);
file.addSeparator();
file.add(fileClose);
menubar.add(file);
setJMenuBar(menubar);
setSize(360, 250);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
Submenu men = new Submenu();
men.setVisible(true);
}
}
Step 3: Run the application and you will see the following output.
Explanation:
In this example, we create a submenu, a menu separator and an accelerator key.
A submenu is just like any other normal menu. It is created the same way. We simply add a menu
to existing menu.
file.addSeparator();
A separator is a vertical line that visually separates the menu items. This way we can group items
into some logical places.
Faculty of Computing and IT NJB
Laboratory Session 7: JCheckBoxMenuItem
A menu item that can be selected or deselected. If selected, the menu item typically
appears with a checkmark next to it. If unselected or deselected, the menu item appears
without a checkmark. Like a regular menu item, a check box menu item can have either
text or a graphic icon associated with it, or both.
Step 1: Run Netbeans and if you are not placed back in your project simply open it. Move to the
projects tab and right mouse click on the project name, from the pop-up menu select New and
from the next pop-up menu select Java Class. You will be presented with a New Java Class form,
edit the form to:
Class Name:
Project:
Location:
Package:
Create File:
CheckMenuItem
HCIProject (Should already be set)
Source Package (Should already be set)
Should already be set
Should already be set
Click finish and you should be placed back into the editor.
Step 2: Edit CkeckMenuItem.java to:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.border.EtchedBorder;
public class CheckMenuItem extends JFrame {
private JLabel statusbar;
public CheckMenuItem() {
setTitle("CheckBoxMenuItem");
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
JMenu view = new JMenu("View");
JCheckBoxMenuItem sbar = new JCheckBoxMenuItem("Show StatuBar");
sbar.setState(true);
sbar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (statusbar.isVisible()) {
Faculty of Computing and IT NJB
statusbar.setVisible(false);
} else
{
statusbar.setVisible(true);
}
}
});
view.add(sbar);
menubar.add(file);
menubar.add(view);
setJMenuBar(menubar);
statusbar = new JLabel("Statusbar");
statusbar.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
add(statusbar, BorderLayout.SOUTH);
setSize(360, 250);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new checkMenuItem();
}
}
Step 3: Run the application and you will see the following output.
Explanation:
The example shows a JCheckBoxMenuItem.. By selecting the menu item, we toggle the
visibility of the statusbar.
JCheckBoxMenuItem sbar = new JCheckBoxMenuItem("Show StatuBar");
sbar.setState(true);
We create the JCheckBoxMenuItem and check it by default. The statusbar is initially
visible.
if (statusbar.isVisible()) {
statusbar.setVisible(false);
} else {
statusbar.setVisible(true);
}
Here we toggle the visibility of the statusbar.
statusbar = new JLabel(" Statusbar");
statusbar.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
The statusbar is a simple JLabel component. We put a raised EtchedBorder around the
label, so that it is discernible.
Faculty of Computing and IT NJB
Laboratory Session 8: Creating Toolbar
Menus group commands that we can use in an application. Toolbars provide a quick access to the
most frequently used commands. In Java Swing, the JToolBar class creates a toolbar in an
application.
Step 1: Run Netbeans and if you are not placed back in your project simply open it. Move to the
projects tab and right mouse click on the project name, from the pop-up menu select New and
from the next pop-up menu select Java Class. You will be presented with a New Java Class form,
edit the form to:
Class Name:
Project:
Location:
Package:
Create File:
SimpleToolbar
HCIProject (Should already be set)
Source Package (Should already be set)
Should already be set
Should already be set
Click finish and you should be placed back into the editor.
Step 2: Edit Toolbars.java to:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JToolBar;
public class SimpleToolbar extends JFrame {
public SimpleToolbar() {
setTitle("SimpleToolbar");
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
menubar.add(file);
setJMenuBar(menubar);
JToolBar toolbar = new JToolBar();
JButton exit = new JButton("Exit");
toolbar.add(exit);
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
add(toolbar, BorderLayout.NORTH);
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
Faculty of Computing and IT NJB
}
public static void main(String[] args) {
new SimpleToolbar();
}
}
Step 3: Run the application and you will see the following output.
Explanation:
The example creates a toolbar with one exit button.
JToolBar toolbar = new JToolBar();
This is the JToolBar constructor.
JButton exit = new JButton(exit);
toolbar.add(exit);
We create a button and add it to the toolbar.