java a1
unknown
plain_text
a year ago
16 kB
12
Indexable
package expensetracker;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.table.DefaultTableModel;
import java.util.HashMap;
public class ExpenseTracker {
// Store user data, monthly income, expenses, and allocation
private static HashMap<String, String> userAccounts = new HashMap<>();
private static HashMap<String, Double> monthlyIncome = new HashMap<>();
private static HashMap<String, HashMap<String, Double>> monthlyExpenses = new HashMap<>();
private static HashMap<String, HashMap<String, Double>> allocatedExpenses = new HashMap<>();
private static String currentUser = "";
public static void main(String[] args) {
SwingUtilities.invokeLater(ExpenseTracker::createSignUpScreen);
}
// Sign-Up & Sign-In Screen
private static void createSignUpScreen() {
JFrame frame = new JFrame("Expense Tracker - Sign Up / Sign In");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
JPanel panel = new JPanel(new GridLayout(5, 2));
JLabel usernameLabel = new JLabel("Username:");
JLabel passwordLabel = new JLabel("Password:");
JTextField usernameField = new JTextField();
JPasswordField passwordField = new JPasswordField();
JButton signUpButton = new JButton("Sign Up");
JButton signInButton = new JButton("Sign In");
JButton exitButton = new JButton("Exit");
panel.add(usernameLabel);
panel.add(usernameField);
panel.add(passwordLabel);
panel.add(passwordField);
panel.add(signUpButton);
panel.add(signInButton);
panel.add(exitButton);
frame.add(panel);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
signUpButton.addActionListener(e -> {
String username = usernameField.getText();
String password = new String(passwordField.getPassword());
if (userAccounts.containsKey(username)) {
JOptionPane.showMessageDialog(frame, "Username already exists.");
} else {
userAccounts.put(username, password);
JOptionPane.showMessageDialog(frame, "Sign-up successful!");
}
});
signInButton.addActionListener(e -> {
String username = usernameField.getText();
String password = new String(passwordField.getPassword());
if (userAccounts.containsKey(username) && userAccounts.get(username).equals(password)) {
currentUser = username;
frame.dispose();
createDashboard(); // Proceed to dashboard after sign-in
} else {
JOptionPane.showMessageDialog(frame, "Invalid credentials.");
}
});
exitButton.addActionListener(e -> System.exit(0)); // Exit the app
}
// Main Dashboard after logging in
private static void createDashboard() {
JFrame frame = new JFrame("Expense Tracker - Dashboard");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
JPanel panel = new JPanel(new BorderLayout());
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
JButton manageExpensesButton = new JButton("Manage Expenses");
JButton viewSummaryButton = new JButton("View Monthly Summary");
JButton exitButton = new JButton("Exit");
buttonPanel.add(manageExpensesButton);
buttonPanel.add(viewSummaryButton);
buttonPanel.add(exitButton);
panel.add(buttonPanel, BorderLayout.CENTER);
frame.add(panel);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
manageExpensesButton.addActionListener(e -> {
frame.dispose();
createMonthlyExpensePage(); // Open monthly expense page
});
viewSummaryButton.addActionListener(e -> {
frame.dispose();
viewMonthlySummary(); // View monthly summary
});
exitButton.addActionListener(e -> System.exit(0)); // Exit the app
}
// Page for Managing Expenses
private static void createMonthlyExpensePage() {
JFrame frame = new JFrame("Manage Expenses");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
JPanel panel = new JPanel(new BorderLayout());
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
JComboBox<String> monthSelector = new JComboBox<>(months);
JButton loadButton = new JButton("Load Month");
JButton backButton = new JButton("Back");
JButton exitButton = new JButton("Exit");
buttonPanel.add(monthSelector);
buttonPanel.add(loadButton);
buttonPanel.add(backButton);
buttonPanel.add(exitButton);
panel.add(buttonPanel, BorderLayout.NORTH);
frame.add(panel);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
loadButton.addActionListener(e -> {
String selectedMonth = (String) monthSelector.getSelectedItem();
frame.dispose();
openExpenseManagementForMonth(selectedMonth); // Open selected month page
});
backButton.addActionListener(e -> {
frame.dispose();
createDashboard(); // Go back to dashboard
});
exitButton.addActionListener(e -> System.exit(0)); // Exit the app
}
// Page for managing a specific month's expenses
private static void openExpenseManagementForMonth(String month) {
JFrame frame = new JFrame("Expense Management - " + month);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
JPanel mainPanel = new JPanel(new BorderLayout());
JPanel inputPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
JPanel tablePanel = new JPanel(new BorderLayout());
JLabel incomeLabel = new JLabel("Income: ");
JLabel expenseLabel = new JLabel("Expenses: ");
JLabel remainingLabel = new JLabel("Remaining: ");
JButton addIncomeButton = new JButton("Add Income");
JButton addExpenseButton = new JButton("Add Expense");
JButton addDailySpendingButton = new JButton("Add Daily Spending");
JButton backButton = new JButton("Back");
inputPanel.add(incomeLabel);
inputPanel.add(expenseLabel);
inputPanel.add(remainingLabel);
inputPanel.add(addIncomeButton);
inputPanel.add(addExpenseButton);
inputPanel.add(addDailySpendingButton);
inputPanel.add(backButton);
String[] columnNames = {"Category", "Allocated", "Spent", "Remaining"};
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
JTable expenseTable = new JTable(tableModel);
JScrollPane tableScrollPane = new JScrollPane(expenseTable);
tablePanel.add(tableScrollPane, BorderLayout.CENTER);
mainPanel.add(inputPanel, BorderLayout.NORTH);
mainPanel.add(tablePanel, BorderLayout.CENTER);
frame.add(mainPanel);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
// Add income button
addIncomeButton.addActionListener(e -> {
String incomeStr = JOptionPane.showInputDialog("Enter Income for " + month + ":");
try {
double income = Double.parseDouble(incomeStr);
monthlyIncome.put(month, income);
updateMonthSummary(month, incomeLabel, expenseLabel, remainingLabel);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(frame, "Invalid income amount.");
}
});
// Add expense button
addExpenseButton.addActionListener(e -> {
String category = JOptionPane.showInputDialog("Enter category:");
String allocatedStr = JOptionPane.showInputDialog("Enter allocated amount:");
try {
double allocated = Double.parseDouble(allocatedStr);
double totalIncome = monthlyIncome.getOrDefault(month, 0.0);
if (allocated > totalIncome) {
JOptionPane.showMessageDialog(frame, "Allocated amount exceeds total income. Please adjust.");
} else {
// If category already exists, update the existing allocation
HashMap<String, Double> monthAllocations = allocatedExpenses.computeIfAbsent(month, k -> new HashMap<>());
monthAllocations.put(category, monthAllocations.getOrDefault(category, 0.0) + allocated);
// Update the table with the new or updated allocated expenses
updateAllocatedInTable(month, category, allocated, tableModel);
updateMonthSummary(month, incomeLabel, expenseLabel, remainingLabel);
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(frame, "Invalid allocated amount.");
}
});
// Add daily spending button
addDailySpendingButton.addActionListener(e -> {
String category = JOptionPane.showInputDialog("Enter category:");
String spentStr = JOptionPane.showInputDialog("Enter daily spending amount:");
try {
double spent = Double.parseDouble(spentStr);
HashMap<String, Double> categorySpent = monthlyExpenses.computeIfAbsent(month, k -> new HashMap<>());
double existingSpent = categorySpent.getOrDefault(category, 0.0);
categorySpent.put(category, existingSpent + spent);
// Update the table with spent expenses
updateSpentInTable(month, category, spent, tableModel);
updateMonthSummary(month, incomeLabel, expenseLabel, remainingLabel);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(frame, "Invalid spending amount.");
}
});
// Back button
backButton.addActionListener(e -> {
frame.dispose();
createMonthlyExpensePage(); // Go back to manage expenses
});
}
// Update Month Summary after income/expense added
private static void updateMonthSummary(String month, JLabel incomeLabel, JLabel expenseLabel, JLabel remainingLabel) {
double totalIncome = monthlyIncome.getOrDefault(month, 0.0);
double totalExpense = monthlyExpenses.getOrDefault(month, new HashMap<>()).
values().stream().mapToDouble(Double::doubleValue).sum();
double allocatedAmount = allocatedExpenses.getOrDefault(month, new HashMap<>()).
values().stream().mapToDouble(Double::doubleValue).sum();
double remaining = totalIncome - allocatedAmount - totalExpense;
incomeLabel.setText("Income: " + totalIncome);
expenseLabel.setText("Expenses: " + totalExpense);
remainingLabel.setText("Remaining: " + remaining);
}
// Update spent amount in the table for a specific category
private static void updateSpentInTable(String month, String category, double spent, DefaultTableModel tableModel) {
for (int i = 0; i < tableModel.getRowCount(); i++) {
if (tableModel.getValueAt(i, 0).equals(category)) {
double allocated = (double) tableModel.getValueAt(i, 1);
double currentSpent = (double) tableModel.getValueAt(i, 2);
double remaining = allocated - (currentSpent + spent);
tableModel.setValueAt(currentSpent + spent, i, 2);
tableModel.setValueAt(remaining, i, 3);
break;
}
}
}
// Update allocated amount in the table for a specific category
private static void updateAllocatedInTable(String month, String category, double allocated, DefaultTableModel tableModel) {
boolean categoryExists = false;
for (int i = 0; i < tableModel.getRowCount(); i++) {
if (tableModel.getValueAt(i, 0).equals(category)) {
double currentAllocated = (double) tableModel.getValueAt(i, 1);
tableModel.setValueAt(currentAllocated + allocated, i, 1);
tableModel.setValueAt(currentAllocated + allocated - (double) tableModel.getValueAt(i, 2), i, 3);
categoryExists = true;
break;
}
}
if (!categoryExists) {
Object[] row = {category, allocated, 0.0, allocated};
tableModel.addRow(row);
}
}
// View Monthly Summary for all months
private static void viewMonthlySummary() {
JFrame frame = new JFrame("Monthly Summary");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
JPanel panel = new JPanel(new BorderLayout());
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
JComboBox<String> monthSelector = new JComboBox<>(new String[]{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"});
JButton loadButton = new JButton("Load Summary");
JButton backButton = new JButton("Back");
JButton exitButton = new JButton("Exit");
buttonPanel.add(monthSelector);
buttonPanel.add(loadButton);
buttonPanel.add(backButton);
buttonPanel.add(exitButton);
panel.add(buttonPanel, BorderLayout.NORTH);
frame.add(panel);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
loadButton.addActionListener(e -> {
String selectedMonth = (String) monthSelector.getSelectedItem();
openMonthlySummary(selectedMonth); // Open summary for the selected month
});
backButton.addActionListener(e -> {
frame.dispose();
createDashboard(); // Go back to dashboard
});
exitButton.addActionListener(e -> System.exit(0)); // Exit the app
}
// Display Monthly Summary (Table)
private static void openMonthlySummary(String month) {
JFrame frame = new JFrame("Monthly Summary - " + month);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
JPanel panel = new JPanel(new BorderLayout());
String[] columnNames = {"Category", "Allocated", "Spent", "Remaining"};
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
JTable table = new JTable(tableModel);
JScrollPane tableScrollPane = new JScrollPane(table);
panel.add(tableScrollPane, BorderLayout.CENTER);
HashMap<String, Double> expenses = allocatedExpenses.getOrDefault(month, new HashMap<>());
for (String category : expenses.keySet()) {
double allocated = expenses.get(category);
double spent = monthlyExpenses.getOrDefault(month, new HashMap<>()).getOrDefault(category, 0.0);
double remaining = allocated - spent;
tableModel.addRow(new Object[]{category, allocated, spent, remaining});
}
frame.add(panel);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}Editor is loading...
Leave a Comment