Application Deployment
JAR Files
Java applications are typically distributed as JAR (Java Archive) files, which are essentially ZIP files containing compiled class files and other resources. JAR files allow for easy packaging and distribution of Java applications, including GUI programs that can be executed by double-clicking the file.
JAR files can contain:
Compiled class files Resource files such as images and sounds Configuraton files Other supporting files
The jar command is used to create and manipulate JAR files. The basic syntax is: jar {ctxu} [vfm0Me] [jar-file] [manifest-file] [entry-point] [-C dir] files ...
To run a JAR file, use: java -jar MyProgram.jar
Resources
Java applications often need to access additional resources like images, sound files, or text files. These resources can be packaged within the JAR file and accessed using getResource() and getResourceAsStream() methods.
Application Preferences Storage
Java provides mechanisms for storing application prefreences:
Properties files for simple key-value storage Preferences API for system-wide or user-specific settings
Java Web Start
Java Web Start allows applications to be deployed over the web and launched through a browser. It uses the JNLP (Java Network Launching Protocol) to define how applications are downloaded and executed.
GUI Programming Exercises
Resource Loading Example
This example demonstrates loading resources from within a JAR file:
package resource_demo;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
public class ResourceDemo {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame frame = new ResourceDemoFrame();
frame.setTitle("Resource Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
class ResourceDemoFrame extends JFrame {
private static final int DEFAULT_WIDTH = 400;
private static final int DEFAULT_HEIGHT = 400;
public ResourceDemoFrame() {
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// Load an image resource
URL imageURL = getClass().getResource("logo.png");
Image icon = new ImageIcon(imageURL).getImage();
setIconImage(icon);
// Load text resource
JTextArea textArea = new JTextArea();
InputStream stream = getClass().getResourceAsStream("description.txt");
try (Scanner in = new Scanner(stream, "UTF-8")) {
while (in.hasNextLine()) {
textArea.append(in.nextLine() + "\n");
}
}
add(textArea);
}
}
Preferences Storage Example
This example shows how to use the Preferences API to store application settings:
package preferences_demo;
import java.awt.*;
import java.util.prefs.*;
import javax.swing.*;
public class PreferencesDemo {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
PreferencesFrame frame = new PreferencesFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
class PreferencesFrame extends JFrame {
private static final int DEFAULT_WIDTH = 400;
private static final int DEFAULT_HEIGHT = 300;
private Preferences prefs = Preferences.userNodeForPackage(getClass());
public PreferencesFrame() {
int width = prefs.getInt("width", DEFAULT_WIDTH);
int height = prefs.getInt("height", DEFAULT_HEIGHT);
int x = prefs.getInt("x", 0);
int y = prefs.getInt("y", 0);
setBounds(x, y, width, height);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
prefs.putInt("width", getWidth());
prefs.putInt("height", getHeight());
prefs.putInt("x", getX());
prefs.putInt("y", getY());
}
});
}
}
Calculator Application with Web Start
This example demonstrates a calculator application that can be deployed using Java Web Start:
package webstart_calc;
import java.awt.*;
import javax.swing.*;
public class CalculatorApp {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
CalculatorFrame frame = new CalculatorFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
class CalculatorFrame extends JFrame {
private CalculatorPanel panel;
public CalculatorFrame() {
setTitle("Calculator");
panel = new CalculatorPanel();
add(panel);
pack();
}
}
class CalculatorPanel extends JPanel {
private JTextArea display;
private JPanel buttonPanel;
private double result;
private String operator;
private boolean start;
public CalculatorPanel() {
setLayout(new BorderLayout());
display = new JTextArea(5, 20);
display.setEditable(false);
add(new JScrollPane(display), BorderLayout.NORTH);
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4));
String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+"
};
for (String text : buttons) {
addButton(text);
}
add(buttonPanel, BorderLayout.CENTER);
}
private void addButton(String text) {
JButton button = new JButton(text);
button.addActionListener(e -> processCommand(text));
buttonPanel.add(button);
}
private void processCommand(String command) {
if (command.equals("=")) {
calculate();
operator = "";
} else {
display.append(command);
}
}
private void calculate() {
String text = display.getText();
if (text.isEmpty()) return;
try {
double value = Double.parseDouble(text);
if (operator.equals("+")) result += value;
else if (operator.equals("-")) result -= value;
else if (operator.equals("*")) result *= value;
else if (operator.equals("/")) result /= value;
else result = value;
display.setText(String.valueOf(result));
} catch (NumberFormatException e) {
display.setText("Error");
}
}
}
ID Card Information System
This example demonstrates a GUI application for managing ID card information:
package id_card_system;
import java.awt.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
public class IDCardSystem {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
IDCardFrame frame = new IDCardFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
class IDCardFrame extends JFrame {
private JTextArea displayArea;
private JTextField searchField;
private JButton searchButton;
private ArrayList<Person> people;
public IDCardFrame() {
setTitle("ID Card Information System");
setSize(800, 600);
people = loadPeopleData();
displayArea = new JTextArea();
displayArea.setEditable(false);
add(new JScrollPane(displayArea), BorderLayout.CENTER);
JPanel searchPanel = new JPanel();
searchField = new JTextField(20);
searchButton = new JButton("Search");
searchButton.addActionListener(e -> searchPeople());
searchPanel.add(new JLabel("Search by ID or Name:"));
searchPanel.add(searchField);
searchPanel.add(searchButton);
add(searchPanel, BorderLayout.SOUTH);
}
private ArrayList<Person> loadPeopleData() {
ArrayList<Person> list = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader("id_cards.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.split(",");
Person p = new Person(parts[0], parts[1], Integer.parseInt(parts[2]), parts[3], parts[4]);
list.add(p);
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
private void searchPeople() {
String query = searchField.getText().trim();
displayArea.setText("");
for (Person p : people) {
if (p.getName().contains(query) || p.getId().contains(query)) {
displayArea.append(p.toString() + "\n");
}
}
}
}
class Person {
private String name;
private String id;
private int age;
private String gender;
private String location;
public Person(String name, String id, int age, String gender, String location) {
this.name = name;
this.id = id;
this.age = age;
this.gender = gender;
this.location = location;
}
// Getters and setters...
@Override
public String toString() {
return String.format("Name: %s, ID: %s, Age: %d, Gender: %s, Location: %s",
name, id, age, gender, location);
}
}
Math Quiz Application
This example demonstrates a math quiz application for elementary students:
package math_quiz;
import java.awt.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
public class MathQuiz {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
QuizFrame frame = new QuizFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
class QuizFrame extends JFrame {
private JTextArea questionArea;
private JTextField answerField;
private JButton submitButton;
private JLabel scoreLabel;
private int currentQuestion;
private int score;
private ArrayList<Question> questions;
public QuizFrame() {
setTitle("Math Quiz");
setSize(500, 400);
questions = generateQuestions();
currentQuestion = 0;
score = 0;
questionArea = new JTextArea();
questionArea.setEditable(false);
add(new JScrollPane(questionArea), BorderLayout.CENTER);
JPanel inputPanel = new JPanel();
answerField = new JTextField(10);
submitButton = new JButton("Submit");
submitButton.addActionListener(e -> checkAnswer());
inputPanel.add(new JLabel("Answer:"));
inputPanel.add(answerField);
inputPanel.add(submitButton);
add(inputPanel, BorderLayout.SOUTH);
scoreLabel = new JLabel("Score: 0");
add(scoreLabel, BorderLayout.NORTH);
showNextQuestion();
}
private ArrayList<Question> generateQuestions() {
ArrayList<Question> list = new ArrayList<>();
Random rand = new Random();
for (int i = 0; i < 10; i++) {
int a = rand.nextInt(100);
int b = rand.nextInt(100);
String operator = getRandomOperator();
int answer = calculateAnswer(a, b, operator);
list.add(new Question(a, b, operator, answer));
}
return list;
}
private String getRandomOperator() {
String[] ops = {"+", "-", "*", "/"};
return ops[new Random().nextInt(ops.length)];
}
private int calculateAnswer(int a, int b, String operator) {
switch (operator) {
case "+": return a + b;
case "-": return a - b;
case "*": return a * b;
case "/": return a / b;
default: return 0;
}
}
private void showNextQuestion() {
if (currentQuestion < questions.size()) {
Question q = questions.get(currentQuestion);
questionArea.setText(String.format("Question %d: %d %s %d = ?",
currentQuestion + 1, q.getA(), q.getOperator(), q.getB()));
answerField.setText("");
} else {
questionArea.setText("Quiz complete! Final score: " + score + "/10");
submitButton.setEnabled(false);
saveResults();
}
}
private void checkAnswer() {
try {
int answer = Integer.parseInt(answerField.getText());
Question q = questions.get(currentQuestion);
if (answer == q.getAnswer()) {
score++;
scoreLabel.setText("Score: " + score);
}
currentQuestion++;
showNextQuestion();
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this, "Please enter a valid number");
}
}
private void saveResults() {
try (PrintWriter out = new PrintWriter("quiz_results.txt")) {
out.println("Math Quiz Results");
out.println("Date: " + new Date());
out.println("Final Score: " + score + "/10");
for (int i = 0; i < questions.size(); i++) {
Question q = questions.get(i);
out.printf("Q%d: %d %s %d = %d (Your answer: %s)%n",
i + 1, q.getA(), q.getOperator(), q.getB(), q.getAnswer(),
i < currentQuestion ? answerField.getText() : "Not answered");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Question {
private int a;
private int b;
private String operator;
private int answer;
public Question(int a, int b, String operator, int answer) {
this.a = a;
this.b = b;
this.operator = operator;
this.answer = answer;
}
// Getters...
}