0

I'm working on a Java program to simulate the Shortest Job First (SJF) preemptive algorithm and then visualize the execution using a Gantt chart. I have the algorithm logic implemented, but I'm struggling with drawing the Gantt chart. Can someone help me with this?

Expected Result: I expect the Gantt chart to display the execution timeline of each process, with labels indicating the process IDs and bars representing their execution durations.

Question:

How can I efficiently draw a Gantt chart in Java to visualize the execution of processes in the SJF preemptive algorithm? Are there any libraries or built-in functions that can simplify this process? Should I consider using a different data structure or approach to represent the Gantt chart data? Any help or suggestions would be greatly appreciated! Thank you.

Example chart I want to implement this shape using java GUI

I have an algorithm which is supposed to calculate and simulate this operations

import java.util.ArrayList;

public class ProcessManagement {

    private static ArrayList<Process> processArray = new ArrayList<>();


    // -----------Delete Process-----------------
    public static int deleteProcess(int id)
    {
        for(int i = 0; i < processArray.size(); i++)
        {
            if(processArray.get(i).getID() == id)
            {
                processArray.remove(i);
                return 1; // Process deleted successfully
            }
        }
        return -1;   // Process not found
    }

    //-------------Get all the processes-------------
    public static ArrayList<Process> getAllProcesses()
    {
        return processArray;
    }

    //---------------Add Process---------------------

    public static void addProcess(double burst, double arrival)
    {
        ProcessManagement.getAllProcesses().add(new Process(arrival, burst));
    }

    //----------------Serve all the processes--------------------------

    public static void serve()
    {
        ArrayList<Process> processes = getAllProcesses();
        ArrayList<Process> readyProcesses = new ArrayList<>();

        int servedProcesses = 0;
        double currentSecond = 0;

        while(servedProcesses < processes.size())
        {   
            // Add all the processes that have arrived in readyProcesses Array
            for(Process process : processes)
            {
                if(process.getArrivalTime() <= currentSecond && !readyProcesses.contains(process) && process.getBurstTime() > 0)
                {
                    readyProcesses.add(process);
                }
            }

            if(!readyProcesses.isEmpty())
            {
                Process shortestProcess = readyProcesses.get(0);
                for(Process process : readyProcesses)
                {
                    if(process.getBurstTime() < shortestProcess.getBurstTime())
                    {
                        shortestProcess = process;
                    }
                }

                for(Process p : processArray)
                {
                    if(p.getID() == shortestProcess.getID())
                    {
                        if(p.getStartTime() == -1)
                        {
                            p.setStartTime(currentSecond);
                        }
                    }
                }
                shortestProcess.setBurstTime(shortestProcess.getBurstTime() - 1);

                if(shortestProcess.getBurstTime() <= 0)
                {
                    for(Process p : processArray)
                    {
                        if(p.getID() == shortestProcess.getID())
                        {
                            p.setCompletionTime(currentSecond + 1);
                        }
                    }
                    readyProcesses.remove(shortestProcess);
                    servedProcesses++;
                }
            }
            currentSecond++;
        }
    }

    // Waiting time function
    public static double waitingTime(int id)
    {
        for(Process p : processArray)
        {
            if(p.getID() == id)
                return (turnaroundtime(id) - p.getOriginalBurstTime());
        }
        return -1; // process not found
    }


    // Turnaround time function
    public static double turnaroundtime(int id)
    {
        for(Process p : processArray){
            if(p.getID() == id)
            {
                return p.getCompletionTime() - p.getArrivalTime();
            }
        }
        return -1; // process not found
    }


    // Response Time function
    public static double responseTime(int id)
    {
        for(Process p : processArray)
        {
            if(p.getID() == id)
            {
                return p.getStartTime() - p.getArrivalTime();
            }
        }
        return -1;
    }

    //=================================================================
        //Rania Task 

        // Average waiting Time Function

        public static double calculateAverageWaiting(){
            ArrayList<Process> processes = getAllProcesses();
            double totalWaitingTime=0;

            for(Process process : processes){
                totalWaitingTime += process.getWaitingTime();
            }

            return totalWaitingTime / processes.size();
        }

        // Average Turnaround Time Function

        public static double calculateAverageTurnaroundTime(){
            ArrayList<Process> processes = getAllProcesses();
            double totalTurnaroundTime=0;
            for(Process process : processes){
                totalTurnaroundTime += process.getTurnaroundTime();
            }
            return  totalTurnaroundTime / processes.size();
        }

        // Average Response Time Function

        public static double calculateAverageResponseTime(){
            ArrayList<Process> processes = getAllProcesses();
            double totalResponseTime=0;
            for(Process process : processes){
                totalResponseTime += process.getResponseTime();
            }
            return  totalResponseTime / processes.size();
        }


        //==========================================================
        public static void Calculation(){
            ArrayList<Process>  ProcessList = getAllProcesses();

            for(Process  p : ProcessList) {
                p.setResponseTime(responseTime(p.getID()));
                p.setTurnaroundTime(turnaroundtime(p.getID()));
                p.setWaitingTime(waitingTime(p.getID()));
            }
        }
    //================================================================

}

I have also tried this code to draw the gantt chart but it works when only two processes are done

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class GanttChart extends JFrame {

        private List<Process> Processes;

        public GanttChart(List<Process> processes) {
                setTitle("Gantt Chart ");
                setSize(800, 300);
                setDefaultCloseOperation(EXIT_ON_CLOSE);
                Processes = new ArrayList<>();
                for (Process process : processes) {
                        Processes.add(process) ;
                }


                JPanel ganttPanel = new JPanel() {
                        @Override
                        protected void paintComponent(Graphics g) {
                                super.paintComponent(g);
                                drawGanttChart(g);
                        }
                };

                getContentPane().add(ganttPanel);

        }

        private void drawGanttChart(Graphics g) {
                Random rand = new Random();
                double startingIndex = Double.MAX_VALUE;
                double endOfLine = 0;
                double [] time  = new double[Processes.size()] ;

                // Find the earliest arrival time and the total completion time
                for (Process process :Processes) {

                        if (process.getArrivalTime() < startingIndex) {
                                startingIndex = process.getArrivalTime();
                        }
                        double completionTime = process.getArrivalTime() + process.getBurstTime(); // Calculate completion time dynamically

                        if (completionTime > endOfLine) {
                                endOfLine = completionTime;
                                System.out.println(completionTime);
                        }


                }

                // Draw tasks
                for (Process process : Processes) {
                        Color taskColor = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
                        g.setColor(taskColor);

                        int rectangleWidth = (int) (process.getBurstTime() * 700 / endOfLine); // Scale the width based on the total completion time
                        int rectangleHeight = 30; // Example height of the rectangle
                        int rectangleX = (int) (process.getArrivalTime() * (700 / endOfLine)) + 50; // Calculate x-coordinate based on process arrival time
                        int rectangleY = 50; // Y-coordinate of the rectangle
                        g.fillRect(rectangleX, rectangleY, rectangleWidth, rectangleHeight); // Draw the rectangle
                        g.setColor(Color.BLACK);

                        // Draw process ID text aligned with the corresponding process rectangle
                        int textX = rectangleX + rectangleWidth / 2 - 5; // Center the text horizontally
                        int textY = 40; // Y-coordinate of the text
                        g.drawString(Integer.toString(process.getID()), textX, textY); // Draw the process ID text
                }

                // Draw time axis
                g.setColor(Color.BLACK);
                int startX = (int) (startingIndex * (700 / endOfLine)) + 50;
                g.drawLine(startX, 100, 750, 100);
                for (int i = (int) startingIndex; i <= (int) endOfLine; i += 1) {
                        int x = 50 + i * (700 / (int) endOfLine);
                        g.drawLine(x, 100, x, 90);
                        g.drawString(Integer.toString(i), x - 5, 120);
                }
        }



}
1

0