You are on page 1of 22

SESSION 10

OTHER ADVANCED FEATURES OF SWING

Learning Objectives

In this session, students will learn to:

⮚ Explain about the Swing Timer

⮚ Explain the usage of the Timer Class

⮚ Outline the Practical usage of Timers with examples

⮚ Define and explain Key Bindings

⮚ Illustrate the different steps for creating a Manifest File

This session explores the advanced features of Swing Timer, usage, and its
practical implementation of Timers, along with Key Bindings and demonstrate
the various steps involved in creating a Manifest FIle

10.1 Swing Timers

Swing Timers are a feature in the Swing library that allow user to schedule a
task to be performed repeatedly after a specified delay. They are
implemented using the Timer class in Java, which is part of the javax.swing
package. Swing Timers are useful for creating animations, updating displays,
and performing other periodic tasks in a Swing application.
10.1.1 Timer Class:

The Timer class in Java is used to schedule a task to be performed after a


specified delay. It is part of the javax.swing package and is used
extensively in Swing applications. The Timer class has two constructors:

Timer(int delay, ActionListener listener)


Timer(int delay, ActionListener listener, int initialDelay)

The first constructor creates a Timer that fires an ActionEvent after the
specified delay. The second constructor creates a Timer that fires an
ActionEvent after the specified delay, but also has an initial delay before the
first event is fired. This can be useful for delaying the start of the Timer.

The Timer class has several useful methods:

start() - Starts the Timer.


stop() - Stops the Timer.
setDelay(int delay) - Sets the delay between events.
setInitialDelay(int delay) - Sets the initial delay before the first event is fired.
addActionListener(ActionListener listener) - Adds an ActionListener to the
Timer.

Following Code Snippet 1 shows creating a Timer object with an initial delay
of 1000 milliseconds (1 second) and an ActionListener that prints a message.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class SwingTimerExample {


private static final int TIMER_DELAY = 1000; // 1 second
private int count;
private Timer timer;
private JLabel label;
public SwingTimerExample() {
count = 0;
label = new JLabel("Count: " + count);
timer = new Timer(TIMER_DELAY, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
count++;
label.setText("Count: " + count);
}
});
}

public void start() {


timer.start();
}

public void stop() {


timer.stop();
}

public void reset() {


count = 0;
label.setText("Count: " + count);
}

public JPanel createPanel() {


JPanel panel = new JPanel();
panel.add(label);
JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
start();
}
});
panel.add(startButton);
JButton stopButton = new JButton("Stop");
stopButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
stop();
}
});
panel.add(stopButton);
JButton resetButton = new JButton("Reset");
resetButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
reset();
}
});
panel.add(resetButton);
return panel;
}

public static void main(String[] args) {


SwingTimerExample example = new SwingTimerExample();
JFrame frame = new JFrame("Swing Timer Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(example.createPanel());
frame.pack();
frame.setVisible(true);
}
}

Figure 10.1: Output of Creating a Timer object


Code Snippet 1 creates a swing timer that updates a count variable every
second, and displays the count in a label. It also provides methods to start,
stop, and reset the timer. The createPanel() method returns a JPanel that
contains the label and buttons to control the timer. The main method creates
an instance of the SwingTimerExample class, creates a JFrame to display the
panel, and sets the content pane of the frame to the panel.

10.1.2 Practical Usage of Timer in Java

The Timer class is useful in a variety of scenarios, such as creating animations,


updating a UI component periodically, or running background tasks at
regular intervals.

Following Code Snippet shows a practical example of using timers in Java.

Code Snippet 2 shows how to create a countdown timer

import javax.swing.*;
import java.awt.event.*;

public class CountdownTimer {


private static final int DELAY = 1000; // 1 second
private int remainingSeconds;
private Timer timer;
private JLabel label;

public CountdownTimer(int seconds) {


remainingSeconds = seconds;
label = new JLabel("Time remaining: " + remainingSeconds + " seconds");
timer = new Timer(DELAY, new ActionListener() {
public void actionPerformed
(ActionEvent e) {
remainingSeconds--;
label.setText("Time remaining: " + remainingSeconds + " seconds");
if (remainingSeconds == 0) {
timer.stop();
JOptionPane.showMessageDialog(null, "Time's up!");
}
}
});
}
public void start() {
timer.start();
}

public static void main(String[] args) {


int seconds = Integer.parseInt(JOptionPane.showInputDialog("Enter the
countdown time in seconds:"));
CountdownTimer countdown = new CountdownTimer(seconds);
JFrame frame = new JFrame("Countdown Timer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(countdown.label);
frame.pack();
frame.setVisible(true);
countdown.start();
}
}

Figure 10.2: Output for Creating a countdown timer

Code Snippet 2 creates a CountdownTimer class that takes an integer value


representing the number of seconds to count down from. The class has a
JLabel instance variable that displays the remaining time, a Timer instance
variable that generates action events every second, and a start() method
that starts the timer.

In the constructor, the JLabel and Timer objects are created, and the Timer's
ActionListener updates the label text and stops the timer when the remaining
time reaches 0.
Code Snippet 3 shows practical usage of timer for Bouncing a Ball

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class BouncingBallExample extends JPanel implements ActionListener {


private int x = 0;
private int y = 0;
private int xVelocity = 1;
private int yVelocity = 1;

public BouncingBallExample() {
Timer timer = new Timer(5, this);
timer.start();
}

public void paintComponent(Graphics g) {


super.paintComponent(g);
g.fillOval(x, y, 20, 20);
}

public void actionPerformed(ActionEvent e) {


x += xVelocity;
y += yVelocity;

if (x < 0 || x > getWidth() - 20) {


xVelocity = -xVelocity;
}
if (y < 0 || y > getHeight() - 20) {
yVelocity = -yVelocity;
}
repaint();
}

public static void main(String[] args) {


JFrame frame = new JFrame("Bouncing Ball Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.add(new BouncingBallExample());
frame.setVisible(true);
}
}

Figure 10.3: Output for Bouncing a Ball


Code Snippet 3 creates a BouncingBall class that extends JPanel to draw a
bouncing ball animation. The class has an x and y position variables that
represent the current position of the ball, dx and dy variables that represent
the direction of movement in the x and y direction, and a Timer instance
variable that generates action events every 10 milliseconds.

In the constructor, the x, y, dx, and dy variables are initialized, and the Timer's
ActionListener updates the x and y position of the ball and changes the
direction of movement if the ball hits the edge of its parent container. The
repaint() method is called to update the display.

In the paintComponent() method, the ball is drawn as a red oval using the
current x and y position and the BALL_SIZE constant.

In the main method, a JFrame is created and a BouncingBall object is added


to it. The frame is made visible on the screen, and the animation begins.
Code Snippet 4 shows practical usage of timer for updating a Progress Bar

import javax.swing.*;
import java.awt.event.*;

public class ProgressBarExample extends JFrame {


private JProgressBar progressBar;
private Timer timer;

public ProgressBarExample() {
// Set up the frame
setTitle("Progress Bar Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 100);

// Create the progress bar


progressBar = new JProgressBar(0, 100);
progressBar.setValue(0);
progressBar.setStringPainted(true);
add(progressBar);

// Set up the timer


timer = new Timer(100, new ActionListener() {
public void actionPerformed(ActionEvent e) {
int value = progressBar.getValue();
if (value < 100) {
value++;
progressBar.setValue(value);
} else {
timer.stop();
}
}
});

// Start the timer


timer.start();
}

public static void main(String[] args) {


ProgressBarExample example = new ProgressBarExample();
example.setVisible(true);
}
}

Figure 10.4: Output for updating a Progress Bar

Code Snippet 4 creates a progress bar that can display a specific string at certain
progress values. The setProgressString(String progressString) method sets the string
that is displayed on the progress bar, and the updateProgress(int progress) method
updates the progress bar and label with the specified progress value (between 0 and 100).
The createPanel() method returns a JPanel that contains the progress bar and label.

The main method creates an instance of the StringProgressBarExample class, creates

a JFrame to display the panel, and sets the content pane of the frame to the panel. It

also demonstrates an example usage of the setProgressString() method by setting

a progress string at specific progress values. In this example, the progress string is

set to "Starting..." at 10% progress, "Halfway there!" at 50% progress, "Almost done..."

at 90% progress, and "Complete!" at 100% progress.

10.2 Key Bindings


Key bindings provide a way for developers to map keyboard input to specific
actions in their application. This allows users to quickly interact with the
application using keyboard shortcuts instead of using the mouse or
navigating through menus. There are two key components of key bindings:
the InputMap and the ActionMap.

Code Snippet 5 shows how Key Bindings can be implemented


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class KeyBindingsExample extends JFrame {
public KeyBindingsExample() {
super("Key Bindings Example");
JPanel panel = new JPanel();
JButton button = new JButton("Save");
InputMap inputMap =
panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap actionMap = panel.getActionMap();
KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_S,
InputEvent.CTRL_DOWN_MASK);
inputMap.put(keyStroke, "saveAction");
actionMap.put("saveAction", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Save button clicked!");
}
});
panel.add(button);
getContentPane().add(panel);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new KeyBindingsExample();
}
}

Figure 10.5:Output for Key Binding

In Code snippet 5 we create a JPanel with a JButton and a JLabel that will
display the output of our action. We define a key binding that maps the "Ctrl
+ S" key combination to an action that sets the text of the label to "Save
button clicked!"
10.2.1 InputMap
The InputMap maps a key or key combination and an input event. This event
can be triggered by the user pressing the key or key combination or by some
other action, such as a timer firing. In addition, the InputMap class provides
methods for adding, removing, and looking up key bindings.

For example, to map the "Ctrl + S" key combination to the "Save" action in an
application, you could use the following code:

InputMap inputMap =
myComponent.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_S,
InputEvent.CTRL_DOWN_MASK);
inputMap.put(keyStroke, "saveAction");

It retrieves the InputMap for a JComponent and adds a mapping between


the "Ctrl + S" key combination and the string "saveAction". The string is a key
that will be used to look up the action in the ActionMap.

Code Snippet 6 shows the practical implementation of an InputMap

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class InputMapExample extends JFrame {


public InputMapExample() {
super("InputMap Example");

JPanel panel = new JPanel();


JButton button = new JButton("Save");

InputMap inputMap =
panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);

KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_S,


InputEvent.CTRL_DOWN_MASK);
inputMap.put(keyStroke, "saveAction");

panel.add(button);
getContentPane().add(panel);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public static void main(String[] args) {


new InputMapExample();
}
}

Figure 10.6: Output for InputMap

In Code Snippet 6 we create a JPanel with a JButton and define a key


binding that maps the "Ctrl + S" key combination to an action. The InputMap
is retrieved from the panel using the getInputMap() method, and the put()
method is used to associate the key stroke with a string identifier "saveAction".

10.2.2 ActionMap
The ActionMap is a mapping between a key and an action. Action is
typically an object that implements the Action interface, which defines a
method for performing the action. The ActionMap class provides methods for
adding and looking up actions.

For example, to map the "saveAction" key to a SaveAction object, you could
use the following code:

ActionMap actionMap = myComponent.getActionMap();


actionMap.put("saveAction", new SaveAction());
It retrieves the ActionMap for a JComponent and adds a mapping between
the "saveAction" key and a new instance of the SaveAction class. When the
"Ctrl + S" key combination is pressed, the SaveAction object will be invoked.

Code Snippet 7 demonstrates the practical usage of an ActionMap

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ActionMapExample extends JFrame {


private JLabel outputLabel;

public ActionMapExample() {
super("ActionMap Example");

JPanel panel = new JPanel();


JButton button = new JButton("Save");

outputLabel = new JLabel("No action performed yet");


panel.add(outputLabel);

ActionMap actionMap = panel.getActionMap();

actionMap.put("saveAction", new AbstractAction() {


@Override
public void actionPerformed(ActionEvent e) {
outputLabel.setText("Save button clicked!");
}
});

button.setActionCommand("saveAction");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
Action action = actionMap.get(actionCommand);
action.actionPerformed(e);
}
});

panel.add(button);
getContentPane().add(panel);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public static void main(String[] args) {


new ActionMapExample();
}
}

Figure 10.7: Output for ActionMap


In Code Snippet 7 we create a JPanel with a JButton and a JLabel that will
display the output of our action. We define an action that sets the text of the
label to "Save button clicked!" when invoked.

The ActionMap is retrieved from the panel using the getActionMap() method,
and the put() method is used to associate the string identifier "saveAction"
with the action.

The setActionCommand() method is used to set the action command of the


button to "saveAction", which allows us to retrieve the action from the
ActionMap when the button is clicked.

We then define an ActionListener that retrieves the action command from


the ActionEvent, retrieves the corresponding action from the ActionMap, and
invokes the actionPerformed() method on the action.

When the "Save" button is clicked, the actionPerformed() method of the


action is invoked, which sets the text of the label to "Save button clicked!".
10.3 How to Create an Executable Jar File?
Creating an executable JAR file in Java is a common way of distributing Java
applications. It allows you to package all the necessary classes and resources
into a single file, which can be easily distributed and executed on any
platform that has Java installed.

10.3.1 Manifest File


A manifest file is a special file that contains metadata about the JAR file. It is
located in the META-INF directory of the JAR file and is named
MANIFEST.MF. The manifest file is used to specify various attributes such as
the main class, classpath, and other information about the JAR file.

An example of a manifest file

Manifest-Version: 1.0
Main-Class: com.example.Main
Class-Path: lib/library1.jar lib/library2.jar

The manifest file contains the following attributes:


Manifest-Version: specifies the version of the manifest file format.
Main-Class: specifies the fully qualified name of the main class that will be
executed when the JAR file is launched. In this example, the main class is
com.example.Main.
Class-Path: specifies the classpath for the JAR file. In this example, the JAR file
depends on library1.jar and library2.jar, which are located in the lib directory
relative to the JAR file.

Steps to create an executable JAR file:


⮚ Create a directory to contain your project files.

⮚ Write the code for your application.

⮚ Create a manifest file named MANIFEST.MF with the required attributes, and
place it in the META-INF directory.
⮚ Compile your application code using the javac command.

⮚ Create a JAR file using the jar command, including the -cvmf options to specify
the manifest file and the main class.

⮚ Test the JAR file by executing it using the java command.

An example command to create an executable JAR file:

java -jar myapp.jar

MANIFEST.MF is the manifest file, myapp.jar is the name of the output JAR file,
and *.class specifies all the class files to be included in the JAR file.

Once the JAR file is created, it can be executed using the java -jar
command, like this:

10.4 Summary

⮚ In Java Swing, the Timer class is a useful tool for creating animations and other
time-based events

⮚ The Timer class generates action events at specified intervals, which can be used
to update the display of a Swing component, change the state of an object, or
perform other actions.

⮚ The practical usage of the Timer class in Java Swing includes creating animations,
such as bouncing balls or moving components, as well as updating the display of
a Swing component at regular intervals.

⮚ The Timer class is a versatile and powerful tool for creating time-based events
and animations in Java Swing, and is an essential component in many Java GUI
applications.
⮚ Key bindings in Java Swing allow you to associate actions with keyboard events,
such as pressing a key or a key combination.

⮚ There are two important maps used in key bindings: InputMap and ActionMap.
The InputMap maps KeyStroke objects to a unique string identifier, while the
ActionMap maps the string identifier to an Action object.

⮚ By combining these maps, you can create key bindings that trigger specific
actions in your application.

⮚ The manifest file is a special file that contains metadata about the JAR file, such
as the main class and classpath.

⮚ The manifest file is located in the META-INF directory of the JAR file and is named
MANIFEST.MF.

⮚ Once the manifest file is created, you can use the jar command to create an
executable JAR file, which can be launched using the java -jar command.

10.5 Test Your Knowledge

1. The package contains the Swing Timer class is ….


A. java.util
B. java.time
C. javax.swing
D. java.awt

2. Identify a valid constructor for a Swing Timer


A. Timer(int delay, ActionListener listener)
B. Timer(int delay, ActionListener listener, boolean repeat)
C. Timer(int delay, int repeats, ActionListener listener)
D. Timer(int delay, int repeats, ActionListener listener, boolean start)

3. Swing Timer is a …..


A. A class used to measure elapsed time
B. A class used to create animations and timed events
C. A class used to handle keyboard events
D. A class used to handle mouse events

4. A Swing Timer can be created by ….


A. By calling the constructor of the Timer class
B. By calling the static method createTimer() of the Timer class
C. By calling the static method getInstance() of the Timer class
D. By calling the static method newTimer() of the Timer class

5. A Swing Timer triggers events by …


A. By calling the start() method of the Timer class
B. By calling the actionPerformed() method of the ActionListener interface
C. By calling the actionPerformed() method of the Timer class
D. By calling the run() method of the Timer class

Answers to Test Your Knowledge

1. javax.swing
2. Timer(int delay, ActionListener listener)
3. A class used to create animations and timed events
4. By calling the constructor of the Timer class
5. By calling the actionPerformed() method of the Timer class

References:
https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html#:~:text=A
%20Swing%20timer%20(an%20instance,timer%20facility%20in%20the%20java.

https://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html

http://www.java2s.com/Tutorial/Java/0240__Swing/SwingTimers.htm

https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html
https://forums.oracle.com/ords/r/apexds/community/q?question=key-
bindings-swing-timer-7060

https://www.developer.com/java/java-jar-manifest-file/#:~:text=In%20the
%20Java%20programming%20language,to%20attributes%20of%20security
%20properties.

https://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html

You might also like