Senin, 13 Juli 2026

JAVA MVC - 6 Array with Calculate SUM

 Since you mentioned "students data" but used item properties (item_id, name_item, sub_total), I designed this as a student-themed billing/fees table (e.g., tracking student tuition or itemized fees).

1. The Model (StudentItem.java)

This class represents a single data record.

Java
package com.example.mvc;

public class StudentItem {
    private String itemId;
    private String nameItem;
    private double subTotal;

    public StudentItem(String itemId, String nameItem, double subTotal) {
        this.itemId = itemId;
        this.nameItem = nameItem;
        this.subTotal = subTotal;
    }

    // Getters and Setters
    public String getItemId() { return itemId; }
    public void setItemId(String itemId) { this.itemId = itemId; }

    public String getNameItem() { return nameItem; }
    public void setNameItem(String nameItem) { this.nameItem = nameItem; }

    public double getSubTotal() { return subTotal; }
    public void setSubTotal(double subTotal) { this.subTotal = subTotal; }
}

2. The View (StudentView.java)

This builds the GUI using standard Swing components. You can easily replicate this layout in the NetBeans GUI Builder by dragging a JTable into a JScrollPane (Center) and a JLabel into a JPanel (South).

Java
package com.example.mvc;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;

public class StudentView extends JFrame {
    private JTable table;
    private DefaultTableModel tableModel;
    private JLabel statusBar;

    public StudentView() {
        setTitle("Student Items Management (MVC)");
        setSize(600, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // Setup Table
        String[] columns = {"Item ID", "Student / Item Name", "Sub Total"};
        tableModel = new DefaultTableModel(columns, 0);
        table = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(table);

        // Setup Status Bar
        statusBar = new JLabel(" Total Sum: $0.00", SwingConstants.LEFT);
        statusBar.setBorder(BorderFactory.createEtchedBorder());
        statusBar.setPreferredSize(new Dimension(this.getWidth(), 25));

        // Layout Layout
        setLayout(new BorderLayout());
        add(scrollPane, BorderLayout.CENTER);
        add(statusBar, BorderLayout.SOUTH);
    }

    public DefaultTableModel getTableModel() {
        return tableModel;
    }

    public void updateTotalStatus(double total) {
        statusBar.setText(String.format(" Total Sum: $%.2f", total));
    }
}

3. The Controller (StudentController.java)

The controller bridges the Model and the View. It populates the 10 sample student items, updates the table UI, and calculates the running sum for the status bar.

Java
package com.example.mvc;

import java.util.ArrayList;
import java.util.List;

public class StudentController {
    private List<StudentItem> modelList;
    private StudentView view;

    public StudentController(StudentView view) {
        this.view = view;
        this.modelList = new ArrayList<>();
        
        // Load the 10 sample student records
        loadSampleData();
        // Update the GUI components
        updateView();
    }

    private void loadSampleData() {
        modelList.add(new StudentItem("STU001", "Alex - Tuition Fees", 1200.50));
        modelList.add(new StudentItem("STU002", "Blake - Textbooks", 150.00));
        modelList.add(new StudentItem("STU003", "Charlie - Lab Equipment", 85.75));
        modelList.add(new StudentItem("STU004", "Diana - Parking Permit", 50.00));
        modelList.add(new StudentItem("STU005", "Ethan - Student Activity", 110.00));
        modelList.add(new StudentItem("STU006", "Fiona - Meal Plan", 500.25));
        modelList.add(new StudentItem("STU007", "George - Laptop Rental", 250.00));
        modelList.add(new StudentItem("STU008", "Hannah - Graduation Fee", 90.00));
        modelList.add(new StudentItem("STU009", "Ian - Sports Club", 65.00));
        modelList.add(new StudentItem("STU010", "Julia - Tech Services", 45.00));
    }

    public void updateView() {
        // Clear existing rows
        view.getTableModel().setRowCount(0);
        
        double totalSum = 0;

        // Populate table and calculate total sum
        for (StudentItem item : modelList) {
            Object[] rowData = { item.getItemId(), item.getNameItem(), item.getSubTotal() };
            view.getTableModel().addRow(rowData);
            totalSum += item.getSubTotal();
        }

        // Send sum total to view's status bar
        view.updateTotalStatus(totalSum);
    }
}

4. Application Entry Point (Main.java)

This ties everything together and runs the program.

Java
package com.example.mvc;

import javax.swing.SwingUtilities;

public class Main {
    public static void main(String[] args) {
        // Run Swing apps on the Event Dispatch Thread (EDT) for thread safety
        SwingUtilities.invokeLater(() -> {
            StudentView view = new StudentView();
            // Controller handles initializing and linking the data
            new StudentController(view);
            view.setVisible(true);
        });
    }
}

How to set this up in NetBeans:

JAVA MVC 5 Array

Here is a clean, modular Model-View-Controller (MVC) implementation in Java Swing.

To keep this easy to run and understand, this example is structured in a single file containing all components. However, when working in NetBeans, you would typically split these into separate files (Student.java, StudentView.java, StudentController.java, and Main.java) within the same package.

The MVC Architecture

  • Model (Student): Holds the data structure for a student.

  • View (StudentView): Handles the UI components (the Swing window, table, and buttons).

  • Controller (StudentController): Acts as the bridge, fetching the hardcoded array of 10 students and populating the View.

The Java Code



Java

Main.java
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package mvcstudentapp;


import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;

// ==========================================
// 1. THE MODEL
// ==========================================
class Student {
    private String studentId;
    private String name;
    private String classroom;

    public Student(String studentId, String name, String classroom) {
        this.studentId = studentId;
        this.name = name;
        this.classroom = classroom;
    }

    // Getters
    public String getStudentId() { return studentId; }
    public String getName() { return name; }
    public String getClassroom() { return classroom; }
}

// ==========================================
// 2. THE VIEW
// ==========================================
class StudentView extends JFrame {
    private JTable studentTable;
    private DefaultTableModel tableModel;
    private JButton loadButton;

    public StudentView() {
        // Window Setup
        setTitle("Student Directory (MVC Pattern)");
        setSize(500, 350);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout(10, 10));

        // Table Setup
        String[] columnNames = {"Student ID", "Name", "Classroom"};
        tableModel = new DefaultTableModel(columnNames, 0);
        studentTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(studentTable);
        add(scrollPane, BorderLayout.CENTER);

        // Controls Setup
        JPanel panelBottom = new JPanel(new FlowLayout(FlowLayout.CENTER));
        loadButton = new JButton("Load Student Data");
        panelBottom.add(loadButton);
        add(panelBottom, BorderLayout.SOUTH);
    }

    // Update the table with new data
    public void setTableData(List<Student> students) {
        tableModel.setRowCount(0); // Clear existing data
        for (Student student : students) {
            Object[] row = {
                student.getStudentId(), 
                student.getName(), 
                student.getClassroom()
            };
            tableModel.addRow(row);
        }
    }

    // Getter for the button to attach listener in Controller
    public JButton getLoadButton() {
        return loadButton;
    }
}

// ==========================================
// 3. THE CONTROLLER
// ==========================================
class StudentController {
    private StudentView view;
    private List<Student> studentList;

    public StudentController(StudentView view) {
        this.view = view;
        this.studentList = new ArrayList<>();
        
        // Initialize 10 sample student data points
        initializeSampleData();

        // Attach action listener to the View's button
        this.view.getLoadButton().addActionListener(e -> {
            view.setTableData(studentList);
        });
    }

    private void initializeSampleData() {
        studentList.add(new Student("STU001", "Alex Mercer", "12-A"));
        studentList.add(new Student("STU002", "Beatrice Vance", "12-B"));
        studentList.add(new Student("STU003", "Charles Xavier", "11-A"));
        studentList.add(new Student("STU004", "Diana Prince", "10-C"));
        studentList.add(new Student("STU005", "Ethan Hunt", "12-A"));
        studentList.add(new Student("STU006", "Fiona Gallagher", "11-B"));
        studentList.add(new Student("STU007", "Garrus Vakarian", "12-B"));
        studentList.add(new Student("STU008", "Hal Jordan", "10-A"));
        studentList.add(new Student("STU009", "Iris West", "11-C"));
        studentList.add(new Student("STU010", "Jack Sparrow", "10-B"));
    }
}

// ==========================================
// MAIN ENTRY POINT
// ==========================================
public class Main {
    public static void main(String[] args) {
        // Set Look and Feel to System Default for a cleaner UI
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ignored) {}

        SwingUtilities.invokeLater(() -> {
            StudentView view = new StudentView();
            // The Controller links the View and manages the data
            new StudentController(view);
            view.setVisible(true);
        });
    }
}

How to use this in NetBeans:

JAVA MVC 4 CRUD CSV File

java swing gui CRUD jtable sample model view controller book title and author database in one package and save as csv file

Gemini said

Here is a complete, lightweight Java Swing CRUD application implementing the Model-View-Controller (MVC) design pattern.

This implementation handles a database of books (Title and Author) and persists the data directly to a CSV file (books.csv). For simplicity and to meet your requirement, all classes are designed to sit within the same package.

Project Structure

Since everything is in one package (e.g., com.bookapp), you will create four files:

  1. Book.java (The Data Model)

  2. BookRepository.java (The CSV Database Handler)

  3. BookView.java (The Swing GUI View)

  4. BookController.java (The Controller / Main Entry)

1. The Model (Book.java)

This represents a single book entity.

Java
package com.bookapp;

public class Book {
    private String title;
    private String author;

    public Book(String title, String author) {
        this.title = title;
        this.author = author;
    }

    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }

    public String getAuthor() { return author; }
    public void setAuthor(String author) { this.author = author; }
}

2. The File Handler (BookRepository.java)

This class manages reading from and writing to the CSV file.

Java
package com.bookapp;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class BookRepository {
    private final String csvFile = "books.csv";

    // Load books from CSV
    public List<Book> loadBooks() {
        List<Book> books = new ArrayList<>();
        File file = new File(csvFile);
        
        if (!file.exists()) return books; // Return empty list if file doesn't exist yet

        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] data = line.split(",");
                if (data.length >= 2) {
                    // Escape commas if necessary, but keeping it simple here
                    books.add(new Book(data[0].trim(), data[1].trim()));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return books;
    }

    // Save books to CSV
    public void saveBooks(List<Book> books) {
        try (PrintWriter pw = new PrintWriter(new FileWriter(csvFile))) {
            for (Book book : books) {
                pw.println(book.getTitle() + "," + book.getAuthor());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3. The View (BookView.java)

This handles the GUI layout. It exposes UI components and data to the controller via methods so that it doesn't handle business logic itself.

Java
package com.bookapp;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionListener;

public class BookView extends JFrame {
    private JTextField txtTitle = new JTextField(15);
    private JTextField txtAuthor = new JTextField(15);
    private JButton btnCreate = new JButton("Add");
    private JButton btnUpdate = new JButton("Update");
    private JButton btnDelete = new JButton("Delete");
    private JButton btnClear = new JButton("Clear");
    
    private JTable table = new JTable();
    private DefaultTableModel tableModel = new DefaultTableModel(new Object[]{"Title", "Author"}, 0);

    public BookView() {
        setTitle("Book CRUD Manager (MVC)");
        setSize(600, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        table.setModel(tableModel);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        // Input Panel
        JPanel inputPanel = new JPanel(new GridLayout(2, 2, 5, 5));
        inputPanel.add(new JLabel("Title:"));
        inputPanel.add(txtTitle);
        inputPanel.add(new JLabel("Author:"));
        inputPanel.add(txtAuthor);

        // Buttons Panel
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(btnCreate);
        buttonPanel.add(btnUpdate);
        buttonPanel.add(btnDelete);
        buttonPanel.add(btnClear);

        // Top Area combining Inputs and Buttons
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        topPanel.add(inputPanel, BorderLayout.CENTER);
        topPanel.add(buttonPanel, BorderLayout.SOUTH);

        // Main Layout
        setLayout(new BorderLayout());
        add(topPanel, BorderLayout.NORTH);
        add(new JScrollPane(table), BorderLayout.CENTER);
    }

    // Getters and Helper Methods for Controller
    public String getBookTitle() { return txtTitle.getText().trim(); }
    public String getBookAuthor() { return txtAuthor.getText().trim(); }
    
    public void setInputs(String title, String author) {
        txtTitle.setText(title);
        txtAuthor.setText(author);
    }

    public int getSelectedRow() { return table.getSelectedRow(); }
    public DefaultTableModel getTableModel() { return tableModel; }
    public JTable getTable() { return table; }

    public void clearInputs() {
        txtTitle.setText("");
        txtAuthor.setText("");
        table.clearSelection();
    }

    // Listeners registrations
    public void addCreateListener(ActionListener l) { btnCreate.addActionListener(l); }
    public void addUpdateListener(ActionListener l) { btnUpdate.addActionListener(l); }
    public void addDeleteListener(ActionListener l) { btnDelete.addActionListener(l); }
    public void addClearListener(ActionListener l) { btnClear.addActionListener(l); }
}

4. The Controller & Main Application (BookController.java)

The brains of the operation. It syncs the BookRepository (Model/Data) with the BookView (UI) and handles all user interactions.

Java
package com.bookapp;

import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import java.util.List;

public class BookController {
    private BookView view;
    private BookRepository repository;
    private List<Book> bookList; // Runtime memory cache of our data

    public BookController(BookView view, BookRepository repository) {
        this.view = view;
        this.repository = repository;
        this.bookList = repository.loadBooks();

        // Populate View table initially
        updateTable();

        // Wire up listeners
        this.view.addCreateListener(e -> handleCreate());
        this.view.addUpdateListener(e -> handleUpdate());
        this.view.addDeleteListener(e -> handleDelete());
        this.view.addClearListener(e -> view.clearInputs());

        // Table row selection syncs back to input fields
        this.view.getTable().getSelectionModel().addListSelectionListener(e -> {
            int selectedRow = view.getSelectedRow();
            if (selectedRow != -1) {
                String title = view.getTableModel().getValueAt(selectedRow, 0).toString();
                String author = view.getTableModel().getValueAt(selectedRow, 1).toString();
                view.setInputs(title, author);
            }
        });
    }

    private void updateTable() {
        DefaultTableModel model = view.getTableModel();
        model.setRowCount(0); // Clear table view
        for (Book book : bookList) {
            model.addRow(new Object[]{book.getTitle(), book.getAuthor()});
        }
    }

    private void handleCreate() {
        String title = view.getBookTitle();
        String author = view.getBookAuthor();

        if (title.isEmpty() || author.isEmpty()) {
            JOptionPane.showMessageDialog(view, "Fields cannot be empty!");
            return;
        }

        bookList.add(new Book(title, author));
        repository.saveBooks(bookList);
        updateTable();
        view.clearInputs();
    }

    private void handleUpdate() {
        int selectedRow = view.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(view, "Select a book to update.");
            return;
        }

        String title = view.getBookTitle();
        String author = view.getBookAuthor();

        if (title.isEmpty() || author.isEmpty()) {
            JOptionPane.showMessageDialog(view, "Fields cannot be empty!");
            return;
        }

        // Update runtime list and save to CSV
        Book book = bookList.get(selectedRow);
        book.setTitle(title);
        book.setAuthor(author);
        
        repository.saveBooks(bookList);
        updateTable();
        view.clearInputs();
    }

    private void handleDelete() {
        int selectedRow = view.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(view, "Select a book to delete.");
            return;
        }

        bookList.remove(selectedRow);
        repository.saveBooks(bookList);
        updateTable();
        view.clearInputs();
    }

    // MAIN ENTRY POINT
    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(() -> {
            BookView view = new BookView();
            BookRepository repository = new BookRepository();
            new BookController(view, repository);
            view.setVisible(true);
        });
    }
}

How to Run it:

  1. Put all 4 files into a directory folder named com/bookapp (matching the package structure).