For GUI-building, here are some "standard" components:
Each component can generate events and therefore has one or more
associated event-listeners.
In the sequel, we will learn how to create some of these
components and handle events related to them.
In-Class Exercise 11.1:
Download this file,
compile and execute it. It should produce a form. Try to identify
which of the above components are being used. Below, we will learn
to build this form step-by-step.
The program above used a CardLayout to place a number
of panels one behind another.
As a first step in constructing the form, we will do the
following:
As usual, we will create a frame and use it as follows:
We will place the code for creating the top panel (instructions),
centerpanel (questions) and bottom panel (buttons) in the
constructor.
But because the questions are large (a lot of code), we will
call methods to handle individual questions.
Here is the constructor:
Note:
Here is the complete source:
(source file)
Note:
When executed, the result looks like this:
In-Class Exercise 11.2:
Improve the font of each label in the four questions.
For Question 1, the user needs to enter of the numbers 1,2,3 or 4.
To allow a simple one-line input from the user, a JTextField
is best.
Here is the code for Question1:
(source file)
When executed, Question 1 looks like this:
Note:
When the user needs to select one or more items from
a known set of items, a collection of JCheckbox's is
convenient:
Here is the code for Question 2:
(source file)
Note:
Suppose we want to allow only one selection to be made.
This can be achieved by associating a ButtonGroup
instance with a group of JRadioButton's.
For example, in Question 3:
(source file)
Note:
Here is the result (the radio button looks different - a circle):
For Question 4, we want a list:
Such lists are implemented using a Choice instance:
(source file)
Note:
Now the four questions are done. A few more observations:
In-Class Exercise 11.3:
In this exercise, you are to use a JComboBox instead
of a JList in Question 4 of the above survey.
Download this template and add
code to the method fourthQuestion() to support
a JComboBox.
Note that a JComboBox uses an ActionListener.
Often, a panel or some other widget is too large to fit the
window.
Swing provides a JScrollPane which lets you place the
large widget inside, and has scrollbars to allow scanning of
the whole widget.
Let us take the four questions in the above survey, place them
all on one panel, and put the panel inside a JScrollPane.
Here is the desired effect:
To implement these changes
Note:
We will next design a simple form with a few text fields
that will have the following features:
In-Class Exercise 11.4:
First, familiarize yourself with the form by downloading
the file Form.java,
compiling and executing it. In particular, fill out the form,
"submit" it and look at the properties file it creates in
the same directory. Also observe the following features:
a file dialog, a popup menu.
We will design the form in stages, starting with a simple
form that writes to a properties file.
As a first step, we will do the following:
Here is the code:
(source file)
Note:
Next, we will use a Properties instance to store
the data:
We will place the data in a
Properties instance.
Here is the code:
(source file)
Note:
In-Class Exercise 11.5:
In this exercise, you will use the following
template to add a "Help"
menu to the menubar:
Next, we will fill out the loadFromFile method:
Here is the code in loadFromFile():
(source file)
Note:
Thus far, we have not handled errors gracefully.
For example, if the filename was incorrect, we killed
the program:
Next, we will bring up a simple dialog box with an "OK" button
to indicate the error.
This code is added to the load() method:
(source file)
Note:
Note: The mode (whether it grabs focus or not):
In-Class Exercise 11.6:
In this exercise, use your code from Ex.11.5
to add a dialog for the "About" option in the "Help" menu.
Typically, "About" displays copyright and version information.
Finally, we will add a simple popup menu with two items:
Popup menus are a little more complicated than regular menus:
Here are the relevant parts of the
source file:
Note:
About scroll positions:
In this section, we will learn how to use JSlider's
with the time-honored example of setting a red-green-blue
combination:
Here is the code:
(source file)
Note:
Next, we will look at an example of handling keyboard events:
We will modify the slider example above in the following ways:
Here are the relevant parts of the
source file:
Note:
In-Class Exercise 11.7:
Download the following template
and add the following functionality to the above slider program:
the user should be able to use the UP and DOWN arrows to
cycle between the colors (sliders). The only code you need
to add is in the keyPressed() method.
Swing topics we have not covered:
(Also comes with additional features, such as "selection").
Setting up a form with a CardLayout
(Later, we will place the actual questions in here).
class NewFrame extends JFrame {
// Constructor.
public NewFrame (int width, int height)
{
}
// ... other stuff ...
}
public class Survey {
public static void main (String[] argv)
{
NewFrame nf = new NewFrame (500, 300);
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class NewFrame extends JFrame {
JPanel centerpanel; // For the questions.
CardLayout card; // For the centerpanel.
// Constructor.
public NewFrame (int width, int height)
{
this.setTitle ("Snoot Club Membership Test");
this.setResizable (true);
this.setSize (width, height);
Container cPane = this.getContentPane();
// cPane.setLayout (new BorderLayout());
// First, a welcome message, as a Label.
JLabel L = new JLabel ("<html><b>Are you elitist enough for our exclusive club?"
+ " <br>Fill out the form and find out</b></html>");
L.setForeground (Color.blue);
cPane.add (L, BorderLayout.NORTH);
// Now the center panel with the questions.
card = new CardLayout ();
centerpanel = new JPanel ();
centerpanel.setLayout (card);
centerpanel.setOpaque (false);
// Each question will be created in a separate method.
// The cardlayout requires a label as second parameter.
centerpanel.add (firstQuestion (), "1");
centerpanel.add (secondQuestion(), "2");
centerpanel.add (thirdQuestion(), "3");
centerpanel.add (fourthQuestion(), "4");
cPane.add (centerpanel, BorderLayout.CENTER);
// Next, a panel of four buttons at the bottom.
// The four buttons: quit, submit, next-question, previous-question.
JPanel bottomPanel = getBottomPanel ();
cPane.add (bottomPanel, BorderLayout.SOUTH);
// Finally, show the frame.
this.setVisible (true);
}
// ...
}
(Alternatively, you can use the setText() method
of JLabel).
(But you can place a <p> in an HTML string to create
a new line).
L.setHorizontalAlignment (Label.RIGHT);
JPanel bottomPanel = getBottomPanel ();
cPane.add (bottomPanel, BorderLayout.SOUTH);
JPanel p = firstQuestion ();
centerpanel.add (p, "1");
card = new CardLayout ();
centerpanel.setLayout (card);
centerpanel.setLayout (new CardLayout());
centerpanel.add (p, "1");
class NewFrame extends JFrame {
JPanel centerpanel; // For the questions.
CardLayout card; // For the centerpanel.
// Constructor.
public NewFrame (int width, int height)
{
this.setTitle ("Snoot Club Membership Test");
this.setResizable (true);
this.setSize (width, height);
Container cPane = this.getContentPane();
// cPane.setLayout (new BorderLayout());
// First, a welcome message, as a Label.
JLabel L = new JLabel ("<html><b>Are you elitist enough for our exclusive club?"
+ " <br>Fill out the form and find out</b></html>");
L.setForeground (Color.blue);
cPane.add (L, BorderLayout.NORTH);
// Now the center panel with the questions.
card = new CardLayout ();
centerpanel = new JPanel ();
centerpanel.setLayout (card);
centerpanel.setOpaque (false);
// Each question will be created in a separate method.
// The cardlayout requires a label as second parameter.
centerpanel.add (firstQuestion (), "1");
centerpanel.add (secondQuestion(), "2");
centerpanel.add (thirdQuestion(), "3");
centerpanel.add (fourthQuestion(), "4");
cPane.add (centerpanel, BorderLayout.CENTER);
// Next, a panel of four buttons at the bottom.
// The four buttons: quit, submit, next-question, previous-question.
JPanel bottomPanel = getBottomPanel ();
cPane.add (bottomPanel, BorderLayout.SOUTH);
// Finally, show the frame.
this.setVisible (true);
}
// No-parameter constructor.
public NewFrame ()
{
this (500, 300);
}
JPanel getBottomPanel ()
{
// Create a panel into which we will place buttons.
JPanel bottomPanel = new JPanel ();
// A "previous-question" button.
JButton backward = new JButton ("Previous question");
backward.setFont (new Font ("Serif", Font.PLAIN | Font.BOLD, 15));
backward.addActionListener (
new ActionListener () {
public void actionPerformed (ActionEvent a)
{
// Go back in the card layout.
card.previous (centerpanel);
}
}
);
bottomPanel.add (backward);
// A forward button.
JButton forward = new JButton ("Next question");
forward.setFont (new Font ("Serif", Font.PLAIN | Font.BOLD, 15));
forward.addActionListener (
new ActionListener () {
public void actionPerformed (ActionEvent a)
{
// Go forward in the card layout.
card.next (centerpanel);
}
}
);
bottomPanel.add (forward);
// A submit button.
JButton submit = new JButton ("Submit");
submit.setFont (new Font ("Serif", Font.PLAIN | Font.BOLD, 15));
submit.addActionListener (
new ActionListener () {
public void actionPerformed (ActionEvent a)
{
// Perform submit task.
computeResult();
}
}
);
bottomPanel.add (submit);
JButton quitb = new JButton ("Quit");
quitb.setFont (new Font ("Serif", Font.PLAIN | Font.BOLD, 15));
quitb.addActionListener (
new ActionListener () {
public void actionPerformed (ActionEvent a)
{
System.exit (0);
}
}
);
bottomPanel.add (quitb);
return bottomPanel;
}
// This method will handle the panel for the first question.
JPanel firstQuestion ()
{
// We will package everything into a panel and return the panel.
JPanel subpanel = new JPanel ();
// For now, we'll just create a label.
JLabel L1 = new JLabel ("Question 1:");
subpanel.add (L1);
return subpanel;
}
// Second question.
JPanel secondQuestion ()
{
JPanel subpanel = new JPanel ();
JLabel L1 = new JLabel ("Question 2:");
subpanel.add (L1);
return subpanel;
}
// Third question.
JPanel thirdQuestion ()
{
JPanel subpanel = new JPanel ();
JLabel L1 = new JLabel ("Question 3:");
subpanel.add (L1);
return subpanel;
}
// Fourth question.
JPanel fourthQuestion ()
{
JPanel subpanel = new JPanel ();
JLabel L1 = new JLabel ("Question 4:");
subpanel.add (L1);
return subpanel;
}
// This method is called after submit is pressed.
void computeResult ()
{
// To be filled in ...
}
}
public class Survey0 {
public static void main (String[] argv)
{
NewFrame nf = new NewFrame (600, 300);
}
}
JPanel getBottomPanel ()
{
// Create a panel into which we will place buttons.
JPanel bottomPanel = new JPanel ();
// ... create the buttons ...
return bottomPanel;
}
quitb.addActionListener (
new ActionListener () {
public void actionPerformed (ActionEvent a)
{
System.exit (0);
}
}
);
public void actionPerformed (ActionEvent a)
{
// Perform submit task.
computeResult();
}
public void actionPerformed (ActionEvent a)
{
// Go back in the card layout.
card.previous (centerpanel);
}
public void actionPerformed (ActionEvent a)
{
// Go forward in the card layout.
card.next (centerpanel);
}
JPanel firstQuestion ()
{
// We will package everything into a panel and return the panel.
JPanel subpanel = new JPanel ();
// For now, we'll just create a label.
JLabel L1 = new JLabel ("Question 1:");
subpanel.add (L1);
return subpanel;
}
Using a JTextField for user input (Question 1)
// We will package everything into a panel and return the panel.
JPanel subpanel = new JPanel ();
// We will place things in a single column, so
// a GridLayout with one column is appropriate.
subpanel.setLayout (new GridLayout (8,1));
JLabel L1 = new JLabel ("Question 1:");
L1.setFont (new Font ("SansSerif", Font.ITALIC, 15));
subpanel.add (L1);
JLabel L2 = new JLabel (" Select a vacation destination");
L2.setFont (new Font ("SansSerif", Font.ITALIC, 15));
subpanel.add (L2);
JLabel L3 = new JLabel (" 1. Baltimore");
L3.setFont (new Font ("SansSerif", Font.ITALIC, 15));
subpanel.add (L3);
JLabel L4 = new JLabel (" 2. Disneyland");
L4.setFont (new Font ("SansSerif", Font.ITALIC, 15));
subpanel.add (L4);
JLabel L5 = new JLabel (" 3. Grand Canyon");
L5.setFont (new Font ("SansSerif", Font.ITALIC, 15));
subpanel.add (L5);
JLabel L6 = new JLabel (" 4. French Riviera");
L6.setFont (new Font ("SansSerif", Font.ITALIC, 15));
subpanel.add (L6);
JLabel L7 = new JLabel ("Enter 1,2,3 or 4 below:");
L7.setFont (new Font ("SansSerif", Font.ITALIC, 15));
subpanel.add (L7);
// Here's the textfield to get user-input.
tf = new JTextField ();
tf.addActionListener (
new ActionListener () {
// This interface has only one method.
public void actionPerformed (ActionEvent a)
{
String q1String = a.getActionCommand();
if (q1String.equals ("2"))
q1Score = 2;
else if (q1String.equals ("3"))
q1Score = 3;
else if (q1String.equals ("4"))
q1Score = 4;
else
q1Score = 1;
}
}
);
subpanel.add (tf);
return subpanel;
JLabel L5 = new JLabel (" 3. Grand Canyon");
L5.setFont (new Font ("SansSerif", Font.ITALIC, 20));
subpanel.add (L5);
Using Checkbox's for user input (Question 2)
(Here, two items have been selected - the first and the third).
// For the second question, a collection of checkboxes
// will be used. More than one selection can be made.
// A listener is required for each checkbox. The state
// of each checkbox is recorded.
JPanel secondQuestion ()
{
JPanel subpanel = new JPanel ();
subpanel.setLayout (new GridLayout (7,1));
JLabel L1 = new JLabel ("Question 2:");
L1.setFont (new Font ("SansSerif", Font.ITALIC, 15));
subpanel.add (L1);
JLabel L2 = new JLabel (" Select ONE OR MORE things that ");
L2.setFont (new Font ("SansSerif", Font.ITALIC, 15));
subpanel.add (L2);
JLabel L3 = new JLabel (" you put into your lunch sandwich");
L3.setFont (new Font ("SansSerif", Font.ITALIC, 15));
subpanel.add (L3);
// Initialize the selections to false.
q2Option1 = q2Option2 = q2Option3 = q2Option4 = false;
// First checkbox.
JCheckBox c1 = new JCheckBox ("Ham, beef or turkey");
c1.addItemListener (
new ItemListener () {
public void itemStateChanged (ItemEvent i)
{
JCheckBox c = (JCheckBox) i.getSource();
q2Option1 = c.isSelected();
}
}
);
subpanel.add (c1);
// Second checkbox.
JCheckBox c2 = new JCheckBox ("Cheese");
c2.addItemListener (
new ItemListener () {
// This is where we will react to a change in checkbox.
public void itemStateChanged (ItemEvent i)
{
JCheckBox c = (JCheckBox) i.getSource();
q2Option2 = c.isSelected();
}
}
);
subpanel.add (c2);
// Third checkbox.
JCheckBox c3 = new JCheckBox ("Sun-dried Arugula leaves");
c3.addItemListener (
new ItemListener () {
public void itemStateChanged (ItemEvent i)
{
JCheckBox c = (JCheckBox) i.getSource();
q2Option3 = c.isSelected();
}
}
);
subpanel.add (c3);
// Fourth checkbox.
JCheckBox c4 = new JCheckBox ("Lemon-enhanced smoked Siberian caviar");
c4.addItemListener (
new ItemListener () {
public void itemStateChanged (ItemEvent i)
{
JCheckBox c = (JCheckBox) i.getSource();
q2Option4 = c.isSelected();
}
}
);
subpanel.add (c4);
return subpanel;
}
JCheckbox c = (JCheckbox) i.getSource();
q2Option1 = c.isSelected();
q2Option1 = c1.isSelected();
(Since c1 is a local variable and not on the heap).
Using a ButtonGroup to force only one selection (Question 3)
// The third question allows only one among four choices
// to be selected. We will use radio buttons.
JPanel thirdQuestion ()
{
JPanel subpanel = new JPanel ();
subpanel.setLayout (new GridLayout (6,1));
JLabel L1 = new JLabel ("Question 3:");
L1.setFont (new Font ("SansSerif", Font.ITALIC, 15));
subpanel.add (L1);
JLabel L2 = new JLabel (" And which mustard do you use?");
L2.setFont (new Font ("SansSerif", Font.ITALIC, 15));
subpanel.add (L2);
// First, create the ButtonGroup instance.
// We will add radio buttons to this group.
ButtonGroup bGroup = new ButtonGroup();
// First checkbox.
JRadioButton r1 = new JRadioButton ("Who cares?");
r1.addItemListener (
new ItemListener () {
public void itemStateChanged (ItemEvent i)
{
JRadioButton r = (JRadioButton) i.getSource();
if (r.isSelected()) q3Score = 1;
}
}
);
bGroup.add (r1);
subpanel.add (r1);
// Second checkbox.
JRadioButton r2 = new JRadioButton ("Safeway Brand");
r2.addItemListener (
new ItemListener () {
public void itemStateChanged (ItemEvent i)
{
JRadioButton r = (JRadioButton) i.getSource();
if (r.isSelected()) q3Score = 2;
}
}
);
bGroup.add (r2);
subpanel.add (r2);
// Third checkbox.
JRadioButton r3 = new JRadioButton ("Fleishman's");
r3.addItemListener (
new ItemListener () {
public void itemStateChanged (ItemEvent i)
{
JRadioButton r = (JRadioButton) i.getSource();
if (r.isSelected()) q3Score = 3;
}
}
);
bGroup.add (r3);
subpanel.add (r3);
// Fourth checkbox.
JRadioButton r4 = new JRadioButton ("Grey Poupon");
r4.addItemListener (
new ItemListener () {
public void itemStateChanged (ItemEvent i)
{
JRadioButton r = (JRadioButton) i.getSource();
if (r.isSelected()) q3Score = 4;
}
}
);
bGroup.add (r4);
subpanel.add (r4);
return subpanel;
}
ButtonGroup bGroup = new ButtonGroup();
JRadioButton r1 = new JRadioButton ("Who cares?");
bGroup.add (r1);
Using a JList (Question 4)
JPanel subpanel = new JPanel ();
subpanel.setLayout (new GridLayout (3,1));
JLabel L1 = new JLabel ("Question 4:");
L1.setFont (new Font ("SansSerif", Font.ITALIC, 15));
subpanel.add (L1);
JLabel L2 = new JLabel (" Your movie preference, among these:");
L2.setFont (new Font ("SansSerif", Font.ITALIC, 15));
subpanel.add (L2);
// Create a JList with options.
String[] movies = { "Lethal Weapon IV", "Titanic", "Saving Private Ryan",
"Le Art Movie avec subtitles"};
q4Choice = new JList (movies);
q4Score = 1;
q4Choice.addListSelectionListener (
new ListSelectionListener () {
public void valueChanged (ListSelectionEvent e)
{
q4Score = 1 + q4Choice.getSelectedIndex();
}
}
);
subpanel.add (q4Choice);
return subpanel;
(Thus, the questions are removed).
void computeResult ()
{
// Clear the center panel.
centerpanel.removeAll();
// Create a new panel to display in the center.
JPanel subpanel = new JPanel (new GridLayout (5,1));
// ... Compute scores
// Now add the new subpanel.
centerpanel.add (subpanel, "5");
// Need to mark the centerpanel as "altered"
centerpanel.invalidate();
// Everything "invalid" (e.g., the centerpanel above)
// is now re-computed.
this.validate();
}
Using a JScrollPane to display large panels
Here is the code in the constructor:
(source file)
// The center panel with the questions.
centerpanel = new JPanel ();
// Use GridLayout for vertical layout of questions.
centerpanel.setLayout (new GridLayout (4,1));
// Each question will be created in a separate method.
// The cardlayout requires a label as second parameter.
centerpanel.add (firstQuestion (), "1");
centerpanel.add (secondQuestion(), "2");
centerpanel.add (thirdQuestion(), "3");
centerpanel.add (fourthQuestion(), "4");
// Add the center panel to the scroll pane and put it in the frame.
// A scrollpane for the center.
JScrollPane scrollpane = new JScrollPane (centerpanel);
cPane.add (scrollpane, BorderLayout.CENTER);
// ...
Not using it causes horizontal layout:
Designing a form with a menubar and dialog
Step 1 in creating the form: building the widgets
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
class NewFrame extends JFrame {
// Data.
JPanel centerpanel; // For the questions.
JScrollPane sc; // For placing the centerpanel.
JTextField lastnameTextF; // To get the lastname.
String lastname;
JTextField firstnameTextF; // Firstname.
String firstname;
JTextField networthTextF; // Net worth
String networth;
JTextArea addressTextA; // Address (TextArea)
String address;
JMenuBar mb; // The menubar.
// Constructor.
public NewFrame (int width, int height)
{
this.setTitle ("Snoot Club Membership Form");
this.setResizable (true);
this.setSize (width, height);
Container cPane = this.getContentPane();
// cPane.setLayout (new BorderLayout());
// First, a welcome message:
JLabel L = new JLabel ("Please fill out the following membership form:");
L.setFont (new Font ("Serif", Font.BOLD | Font.ITALIC, 15));
L.setForeground (Color.blue);
cPane.add (L, BorderLayout.NORTH);
// Now the center panel.
centerpanel = new JPanel ();
centerpanel.setLayout (new GridLayout (4,1));
// Each widget is created in a separate method.
centerpanel.add ( firstName() );
centerpanel.add ( lastName() );
centerpanel.add ( netWorth() );
centerpanel.add ( address () );
// Next, the scrollpane to contain the main panel.
sc = new JScrollPane (centerpanel);
cPane.add (sc, BorderLayout.CENTER);
// Create a menubar and add two menus.
mb = new JMenuBar ();
mb.add ( makeFileMenu() );
mb.add ( makeActionMenu() );
// Note how a menubar is added to a Frame.
this.setJMenuBar (mb);
// Finally, show the frame.
this.setVisible (true);
}
// No-parameter constructor.
public NewFrame ()
{
this (500, 300);
}
// Read in the first name.
JPanel firstName ()
{
JPanel subpanel = new JPanel ();
// First, a label before the textfield.
JLabel L = new JLabel ("First Name");
L.setFont (new Font ("SansSerif", Font.ITALIC, 20));
subpanel.add (L);
// Create and add the textfield.
firstnameTextF = new JTextField (20);
firstnameTextF.setForeground (Color.blue);
subpanel.add (firstnameTextF);
return subpanel;
}
// Get last name.
JPanel lastName ()
{
JPanel subpanel = new JPanel ();
// The "last name" label.
JLabel L = new JLabel ("Last Name");
L.setFont (new Font ("SansSerif", Font.ITALIC, 20));
subpanel.add (L);
lastnameTextF = new JTextField (20);
lastnameTextF.setForeground (Color.blue);
subpanel.add (lastnameTextF);
return subpanel;
}
// Get net worth.
JPanel netWorth ()
{
JPanel subpanel = new JPanel ();
JLabel L = new JLabel ("Net worth (in millions)");
L.setFont (new Font ("SansSerif", Font.ITALIC, 20));
subpanel.add (L);
networthTextF = new JTextField (10);
networthTextF.setForeground (Color.blue);
subpanel.add (networthTextF);
return subpanel;
}
// Get address via a TextArea.
JPanel address ()
{
JPanel subpanel = new JPanel ();
JLabel L = new JLabel ("Address");
L.setFont (new Font ("SansSerif", Font.ITALIC, 20));
subpanel.add (L);
addressTextA = new JTextArea (4, 30);
addressTextA.setForeground (Color.blue);
subpanel.add (addressTextA);
return subpanel;
}
// Create the File menu and associated listeners.
JMenu makeFileMenu ()
{
// Add a "File" menu with two items.
JMenu fileMenu = new JMenu ("File");
// "Load From File" menu item
JMenuItem loadFromFileMenuItem = new JMenuItem ("Load From File");
loadFromFileMenuItem.addActionListener (
new ActionListener () {
public void actionPerformed (ActionEvent a)
{
loadFromFile ();
}
}
);
fileMenu.add (loadFromFileMenuItem);
// "Quit" menu item
JMenuItem quitMenuItem = new JMenuItem ("Quit");
quitMenuItem.addActionListener (
new ActionListener () {
public void actionPerformed (ActionEvent a)
{
System.exit (0);
}
}
);
fileMenu.add (quitMenuItem);
return fileMenu;
}
// Create the Action Menu and its listeners.
JMenu makeActionMenu ()
{
// Add an "Action" menu with two items.
JMenu actionMenu = new JMenu ("Action");
// "Submit" menu item
JMenuItem submitMenuItem = new JMenuItem ("Submit");
submitMenuItem.addActionListener (
new ActionListener () {
public void actionPerformed (ActionEvent a)
{
submit ();
}
}
);
actionMenu.add (submitMenuItem);
// "Clear" menu item
JMenuItem clearMenuItem = new JMenuItem ("Clear");
clearMenuItem.addActionListener (
new ActionListener () {
public void actionPerformed (ActionEvent a)
{
// Clear all the fields.
firstname = ""; firstnameTextF.setText (firstname);
lastname = ""; lastnameTextF.setText (lastname);
networth = ""; networthTextF.setText (networth);
address = ""; addressTextA.setText (address);
}
}
);
actionMenu.add (clearMenuItem);
return actionMenu;
}
// Process data when ready.
void submit ()
{
System.out.println ("Submit");
}
// Use a file dialog.
void loadFromFile ()
{
System.out.println ("Load From File");
}
}
public class Form1 {
public static void main (String[] argv)
{
NewFrame nf = new NewFrame (500, 200);
}
}
This combination was placed in a panel.
firstname = ""; firstnameTextF.setText (firstname);
lastname = ""; lastnameTextF.setText (lastname);
networth = ""; networthTextF.setText (networth);
address = ""; addressTextA.setText (address);
this.setJMenuBar (mb);
// "Quit" menu item
JMenuItem quitMenuItem = new JMenuItem ("Quit");
quitMenuItem.addActionListener (
new ActionListener () {
public void actionPerformed (ActionEvent a)
{
System.exit (0);
}
}
);
fileMenu.add (quitMenuItem);
Step 2 in creating the form: working with files.
Properties info;
void submit ()
{
// Retrieve data from the widgets.
lastname = lastnameTextF.getText();
firstname = firstnameTextF.getText();
networth = networthTextF.getText();
address = addressTextA.getText();
// Create a file by concatenating firstname and lastname.
String filename = firstname + lastname;
if (filename.length() == 0) return;
// We will use a "Properties" instance to store data.
Properties p = new Properties ();
p.put ("firstname", firstname);
p.put ("lastname", lastname);
p.put ("networth", networth);
p.put ("address", address);
// Use the "save" feature of the Properties instance.
try {
FileOutputStream f = new FileOutputStream (filename);
p.store (f, "Member information");
}
catch (IOException e) {
System.out.println (e);
System.exit (0);
}
}
Properties p = new Properties ();
p.put ("firstname", firstname);
p.put ("lastname", lastname);
p.put ("networth", networth);
p.put ("address", address);
FileOutputStream f = new FileOutputStream (filename);
p.store (f, "Member information");
Once you've completed the above, see what happens when you
use the setHelpMenu() method of JMenuBar
instead of add() when adding the help menu.
Step 3 in creating the form: a file dialog.
void loadFromFile ()
{
// Create the FileDialog instance.
JFileChooser fc = new JFileChooser();
int returnCode = fc.showOpenDialog (null);
File file = fc.getSelectedFile();
info = new Properties ();
try {
// Load the properties file.
FileInputStream f = new FileInputStream (file);
info.load (f);
// Extract the info.
firstname = info.getProperty ("firstname");
firstnameTextF.setText (firstname);
lastname = info.getProperty ("lastname");
lastnameTextF.setText (lastname);
networth = info.getProperty ("networth");
networthTextF.setText (networth);
address = info.getProperty ("address");
addressTextA.setText (address);
}
catch (IOException e) {
System.out.println ("Couldn't load file");
System.exit (0);
}
}
int returnCode = fc.showOpenDialog (null);
FileInputStream f = new FileInputStream (filename);
info.load (f);
// ...
Step 4 in creating the form: an error dialog.
try {
FileInputStream f = new FileInputStream (filename);
// ...
}
catch (IOException e) {
System.out.println ("Couldn't load file");
System.exit (0);
}
void loadFromFile ()
{
// Create the FileDialog instance.
JFileChooser fc = new JFileChooser();
int returnCode = fc.showOpenDialog (null);
File file = fc.getSelectedFile();
info = new Properties ();
try {
FileInputStream f = new FileInputStream (file);
info.load (f);
firstname = info.getProperty ("firstname");
firstnameTextF.setText (firstname);
lastname = info.getProperty ("lastname");
lastnameTextF.setText (lastname);
networth = info.getProperty ("networth");
networthTextF.setText (networth);
address = info.getProperty ("address");
addressTextA.setText (address);
}
catch (IOException e) {
// Handle a file error gracefully with a dialog.
JOptionPane.showMessageDialog (this,
"File does not exist",
"Error dialog",
JOptionPane.INFORMATION_MESSAGE);
}
}
JOptionPane.showMessageDialog (this,
"File does not exist",
"Error dialog",
JOptionPane.INFORMATION_MESSAGE);
Step 5 in creating the form: a popup menu
(Along the way, we will learn how to set the scroll position).
class NewFrame extends JFrame {
// ...
JPopupMenu pm; // The popup menu.
// Constructor.
public NewFrame (int width, int height)
{
// ...
// A pop-up menu is handled a little different from the other menus.
makePopupMenu ();
// ...
}
// Methods like firstName() method are slightly modified:
JPanel firstName ()
{
JPanel subpanel = new JPanel ();
// First, a label before the textfield.
JLabel L = new JLabel ("First Name");
L.setFont (new Font ("SansSerif", Font.ITALIC, 20));
subpanel.add (L);
// Need to have each component listen for a Popup click.
L.addMouseListener (getMouseListener (L));
// Create and add the textfield.
firstnameTextF = new JTextField (20);
firstnameTextF.setForeground (Color.blue);
subpanel.add (firstnameTextF);
// Make the subpanel listen for mouseclicks too.
subpanel.addMouseListener (getMouseListener(subpanel));
return subpanel;
}
// ...
// Create a Listener for popup's.
MouseListener getMouseListener (Component c)
{
class PopupMouseListener extends MouseAdapter {
Component c;
public PopupMouseListener (Component c)
{
this.c = c;
}
public void mousePressed (MouseEvent m)
{
// We need this special check.
if (m.isPopupTrigger ())
pm.show (c, m.getX(), m.getY());
// The "show" method requires the component reference,
// which is why we store it in the variable c.
}
}
return new PopupMouseListener (c);
}
// Create the popup menu and its listeners.
void makePopupMenu ()
{
// Note: pm is a top-level variable, which we will need to access elsewhere.
pm = new JPopupMenu ();
// Move to "top"
JMenuItem topMenuItem = new JMenuItem ("Top");
topMenuItem.addActionListener (
new ActionListener () {
public void actionPerformed (ActionEvent a)
{
top ();
}
}
);
pm.add (topMenuItem);
// Move to "bottom"
JMenuItem bottomMenuItem = new JMenuItem ("Bottom");
bottomMenuItem.addActionListener (
new ActionListener () {
public void actionPerformed (ActionEvent a)
{
bottom ();
}
}
);
pm.add (bottomMenuItem);
}
// Handle the "go to top" event.
void top ()
{
// Get the viewport out of the JScrollPane.
JViewport vp = sc.getViewport();
// Set the new view.
vp.setViewPosition (new Point (0,0));
}
// Handle the "go to bottom" event.
void bottom ()
{
// Get the viewport out of the JScrollPane.
JViewport vp = sc.getViewport();
// Set the new view.
Dimension D = vp.getViewSize();
vp.setViewPosition (new Point (0,D.height));
}
}
pm = new JPopupMenu ();
JMenuItem topMenuItem = new JMenuItem ("Top");
topMenuItem.addActionListener (
new ActionListener () {
public void actionPerformed (ActionEvent a)
{
top ();
}
}
);
pm.add (topMenuItem);
JPanel firstName ()
{
JPanel subpanel = new JPanel ();
// ...
JLabel L = new JLabel ("First Name");
// ...
// Need to have each component listen for a Popup click.
L.addMouseListener (getMouseListener (L));
// ...
subpanel.addMouseListener (getMouseListener(subpanel));
return subpanel;
}
MouseListener getMouseListener (Component c)
{
class PopupMouseListener extends MouseAdapter {
Component c;
public PopupMouseListener (Component c)
{
this.c = c;
}
public void mousePressed (MouseEvent m)
{
// We need this special check.
if (m.isPopupTrigger ())
pm.show (c, m.getX(), m.getY());
}
}
return new PopupMouseListener (c);
}
pm.show (c, m.getX(), m.getY());
This method takes as parameters the component (e.g., label)
in which the menu pops up and the location.
JViewport vp = sc.getViewport();
// Set the new view.
vp.setViewPosition (new Point (0,0));
Sliders
For example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
import java.io.*;
class NewFrame extends JFrame {
// Data.
JSlider // One scrollbar for each color.
redSlider,
blueSlider,
greenSlider;
int // Intensity value for each color.
redValue = 0,
blueValue = 0,
greenValue = 0;
JPanel drawingArea; // To display the mixed color.
// Constructor.
public NewFrame (int width, int height)
{
this.setTitle ("RGB combination");
this.setResizable (true);
this.setSize (width, height);
Container cPane = this.getContentPane();
// cPane.setLayout (new BorderLayout());
// Three sliders and the JPanel will
// be added to a panel.
JPanel p = new JPanel ();
p.setLayout (new GridLayout (4,1));
// The canvas on which to display the result.
drawingArea = new JPanel ();
drawingArea.setBackground (Color.white);
p.add (drawingArea);
// A local Listener for the sliders
class ColorChangeListener implements ChangeListener {
public void stateChanged (ChangeEvent e)
{
adjust ();
}
}
// Red one.
redSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, 0);
redSlider.addChangeListener (new ColorChangeListener());
p.add (redSlider);
// Green one.
greenSlider = new JSlider (JSlider.HORIZONTAL, 0, 255, 0);
greenSlider.addChangeListener (new ColorChangeListener());
p.add (greenSlider);
// Blue one.
blueSlider = new JSlider (JSlider.HORIZONTAL, 0, 255, 0);
blueSlider.addChangeListener (new ColorChangeListener());
p.add (blueSlider);
cPane.add (p, BorderLayout.CENTER);
// A quit button for the application.
Button quitb = new Button ("Quit");
quitb.setBackground (Color.red);
quitb.setFont (new Font ("Serif", Font.PLAIN | Font.BOLD, 15));
quitb.addActionListener (
new ActionListener () {
public void actionPerformed (ActionEvent a)
{
System.exit (0);
}
}
);
cPane.add (quitb, BorderLayout.SOUTH);
// Finally, show the frame.
this.setVisible (true);
}
// No-parameter constructor.
public NewFrame ()
{
this (500, 300);
}
// Create the composite color.
public void adjust ()
{
// Get the new values.
redValue = redSlider.getValue();
greenValue = greenSlider.getValue ();
blueValue = blueSlider.getValue ();
// Set the color in each scrollbar.
redSlider.setBackground (new Color (redValue, 0, 0));
greenSlider.setBackground (new Color (0, greenValue, 0));
blueSlider.setBackground (new Color (0, 0, blueValue));
// Create the composite color.
Color newColor = new Color (redValue, greenValue, blueValue);
drawingArea.setBackground (newColor);
drawingArea.repaint ();
}
}
public class TestSlider {
public static void main (String[] argv)
{
NewFrame nf = new NewFrame (500, 300);
}
}
redSlider = new Scrollbar (Scrollbar.HORIZONTAL, 0, 255, 0);
Keyboard events
class NewFrame extends JFrame {
// ...
// Constructor.
public NewFrame (int width, int height)
{
// ...
// A KeyListener for the panel
drawingArea.addKeyListener ( getKeyListener() );
// A KeyListener for the red scrollbar.
redSlider.addKeyListener (getKeyListener());
// A KeyListener for the green scrollbar.
greenSlider.addKeyListener (getKeyListener());
// A KeyListener for the blue scrollbar.
blueSlider.addKeyListener (getKeyListener());
// ...
}
// ...
// Create a KeyListener to be used everywhere.
KeyListener getKeyListener ()
{
return new KeyAdapter () {
public void keyPressed (KeyEvent k)
{
if (k.getKeyCode() == KeyEvent.VK_Q)
// "q" for quit.
System.exit (0);
else if (k.getKeyCode() == KeyEvent.VK_LEFT) {
// Left arrow.
redSlider.setValue (Math.max (0, redValue-10));
adjust ();
}
else if (k.getKeyCode() == KeyEvent.VK_RIGHT) {
// Right arrow.
redSlider.setValue (Math.min (255, redValue+10));
adjust ();
}
}
};
}
}
interface KeyListener extends EventListener {
public void keyPressed (KeyEvent e);
public void keyReleased (KeyEvent e);
public void keyTyped (KeyEvent e);
}
Additional Swing topics