-2

I want to sort these coloured bars using different algorithms.

Image1.

I have created a JFrame and added eight buttons and one JPanel. In the panel I have created a bar chart of an array. I want to sort this bar chart visually by using different sorting algorithms like bubble sort, selection sort, merge sort etc by clicking on buttons and showing each algorithm and step. But I'm finding trouble in visualizing these algorithms.

Here is my code:

public class VisuofSortTech { 
//Declarations....
private final JLabel lbl = new JLabel();
private JTextField jtf = new JTextField(10);
private JPanel pnl = new JPanel();

private final JButton bbl= new JButton("Bubble Sort");
private final JButton ins= new JButton("Insertion Sort");
private final JButton mrg= new JButton("Merge Sort");
private final JButton slc= new JButton("Selection Sort");
private final JButton qck= new JButton("Quick Sort");
private final JButton rdx= new JButton("Radix Sort");
private final JButton heap= new JButton("Heap Sort");
private final JButton stp= new JButton("Stupid Sort");
private final JButton go = new JButton("Create");

String[] parts;
int[] arr1;
BarChart chart = new BarChart();
Random rand = new Random();

//Main method....
public static void main(String[] args) {
    VisuofSortTech visuOfSortTech = new VisuofSortTech();
    System.out.println("Visual :" + visuOfSortTech);

}


// Bars
public class BarChart extends Canvas
        {
            private final Map<Color, Integer> bars =
            new LinkedHashMap<>();

        public void addBar(Color color, int value)
            {
                bars.put(color, value);
                repaint();
            }
       //
        @Override
        public void paint(Graphics g)
        {
        // determine longest bar
            int max = Integer.MIN_VALUE;
            for (int value : bars.values())
            {
                max = Math.max(max, value);
            }        

        // paint bars
        int width = (getWidth() / bars.size()) - 2;
        int x = 1;
        for (Color color : bars.keySet())
        {
            int value = bars.get(color);
            int height = (int) ((getHeight()-5) * ((double)value / max));
            g.setColor(color);
            g.fill3DRect(x, getHeight() - height, width, height , true);
            g.setColor(Color.white);
            g.drawRect(x, getHeight() - height, width, height);

            x += (width + 2);
        }
        }   

}

// Constructor........
public VisuofSortTech(){
    JFrame frame = new JFrame("DSA Project");
    frame.getContentPane().setLayout(null);

    // Label
    lbl.setText("Visualization of Sorting Algorithms");
    lbl.setFont(new Font("SansSerif", 3, 36));
    lbl.setForeground(Color.red);
    lbl.setBackground(new Color(150,235,210,100));
    lbl.setFocusable(true);
    lbl.setBounds(10,10, 620, 60);
    lbl.setMinimumSize(new Dimension(200,200));
    lbl.setOpaque(true);
    lbl.setBorder(BorderFactory.createLineBorder(Color.white, 3, true));
    frame.add(lbl);


    // Buttons
    bbl.setBounds(50, 100, 115, 35);
    bbl.setForeground(Color.magenta);
    bbl.setBackground(Color.white);
    bbl.setBorder(BorderFactory.createDashedBorder(Color.GREEN, 5, 2, 0, true));
    bbl.setBorderPainted(true);
    frame.add(bbl);


    ins.setBounds(50, 150, 115, 35);
    ins.setForeground(Color.magenta);
    ins.setBackground(Color.white);
    ins.setBorder(BorderFactory.createDashedBorder(Color.GREEN, 5, 2, 0, true));
    ins.setBorderPainted(true);
    frame.add(ins);


    mrg.setBounds(50, 200, 115, 35);
    mrg.setForeground(Color.magenta);
    mrg.setBackground(Color.white);
    mrg.setBorder(BorderFactory.createDashedBorder(Color.GREEN, 5, 2, 0, true));
    mrg.setBorderPainted(true);
    frame.add(mrg);


    qck.setBounds(50, 250, 115, 35);
    qck.setForeground(Color.magenta);
    qck.setBackground(Color.white);
    qck.setBorder(BorderFactory.createDashedBorder(Color.GREEN, 5, 2, 0, true));
    qck.setBorderPainted(true);
    frame.add(qck);


    slc.setBounds(50, 300, 115, 35);
    slc.setForeground(Color.magenta);
    slc.setBackground(Color.white);
    slc.setBorder(BorderFactory.createDashedBorder(Color.GREEN, 5, 2, 0, true));
    slc.setBorderPainted(true);
    frame.add(slc);


    rdx.setBounds(50, 350, 115, 35);
    rdx.setForeground(Color.magenta);
    rdx.setBackground(Color.white);
    rdx.setBorder(BorderFactory.createDashedBorder(Color.GREEN, 5, 2, 0, true));
    rdx.setBorderPainted(true);
    frame.add(rdx);


    heap.setBounds(50, 400, 115, 35);
    heap.setForeground(Color.magenta);
    heap.setBackground(Color.white);
    heap.setBorder(BorderFactory.createDashedBorder(Color.GREEN, 5, 2, 0, true));
    heap.setBorderPainted(true);
    frame.add(heap);


    stp.setBounds(50, 450, 115, 35);
    stp.setForeground(Color.magenta);
    stp.setBackground(Color.white);
    stp.setBorder(BorderFactory.createDashedBorder(Color.GREEN, 5, 2, 0, true));
    stp.setBorderPainted(true);
    frame.add(stp);


    go.setBounds(755, 600, 100, 30);
    go.setForeground(Color.magenta);
    go.setBackground(Color.white);
    go.setBorder(BorderFactory.createDashedBorder(Color.GREEN, 5, 2, 0, true));
    go.setBorderPainted(true);
    frame.add(go);


    // Textfield

    jtf.setBounds(550, 600, 200, 30);
    jtf.setBorder(BorderFactory.createLineBorder(Color.GREEN, 2, true));
    frame.add(jtf);



    // Panel

    pnl.setBorder(BorderFactory.createTitledBorder(new LineBorder(Color.white, 4, true), "Sorting Pane"));
    pnl.setBounds(342, 100, 682, 384);
    pnl.setLayout(new BorderLayout());
    pnl.setBackground(new Color(255,255,255,150));
    frame.add(pnl);


    // Color arrays
    int l= 20;
    int[] clr1= new int[l];
    int[] clr2= new int[l];
    int[] clr3= new int[l];

    // red color
    for(int i=0; i < l ;i++){
        int r= rand.nextInt(255);
        clr1[i]= r;
    }

    // green color
    for(int i=0; i < l ;i++){
        int g= rand.nextInt(255);
        clr2[i]= g;
    }

    // blue color
    for(int i=0; i < l ;i++){
        int b= rand.nextInt(255);
        clr3[i]= b;
    }

    // Array
    go.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt){
            pnl.setVisible(false);
            String str = jtf.getText();
            parts = str.split(",");
            arr1 =new int[parts.length];

            for(int i=0 ; i<parts.length; i++){
                arr1[i]=Integer.parseInt(parts[i]);
            }



    for(int i=0; i <arr1.length; i++){
    chart.addBar(new Color(clr1[i] , clr2[i] ,clr3[i]) ,arr1[i]);
    }
    pnl.add(chart);
    pnl.setVisible(true);
        }
    });


    // Bubble sort
    bbl.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt)  {
            pnl.remove(chart);
            pnl.setVisible(false);
            //Thread t = new Thread();
           int loop=arr1.length-1;
        for(int i=0; i<loop; i++){
            for(int j=0; j<loop-i;j++)
            {
                boolean exp = arr1[j]>arr1[j+1];
                if(exp)
                {
                    int temp=arr1[j];
                    arr1[j]=arr1[j+1];
                    arr1[j+1]=temp;
                    System.out.print(exp + ",");

                try{
                    Thread.sleep(250);
                }
                catch(Exception e){
                    System.out.println("Thread is not working " + e);

                }
                System.out.print(temp + ",");
                }
            }
        }
        for(int i=0; i <arr1.length; i++){
            chart.addBar(new Color(clr1[i] , clr2[i] ,clr3[i]) ,arr1[i]);
        }

        pnl.add(chart);
        pnl.setVisible(true);

    }
});


    // Frame
    Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setBackground(new Color(167,167,247));
    frame.setPreferredSize(new Dimension(screensize.width,screensize.height));
    frame.pack();
    frame.setResizable(true);
    frame.setVisible(true);

}   
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Farhan
  • 13
  • 5
  • You need to explain what your trouble is. What do you expect to happen? What happens instead? Do you get errors? The code is a good start, but it's not enough as a problem description. – RealSkeptic Dec 24 '18 at 17:09
  • Welcome to Stack Overflow! Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, _a specific problem or error_ and _the shortest code necessary_ to reproduce it **in the question itself**. Questions without a clear problem statement are not useful to other readers. See: [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). – Joe C Dec 24 '18 at 17:21
  • When I enter the values of the array in JTextField and click on create button, it creates bars of different heights and colours in JPanel. Now I want to sort these bars visually by using different algorithms. I mean I want to animate every comparison of sorting. – Farhan Dec 24 '18 at 17:33

1 Answers1

2

You cannot use Thread.sleep() in Swing’s Event Dispatching Thread. That doesn’t slow down the program to allow you to see what happens; rather it prevents the UI from responding to anything, including repaint requests, so nothing happens, and time is wasted for no benefit.

Use a Swing Timer or (better) a SwingWorker to perform the sorting, in steps, and publish() the interm partial sort results for display.

AJNeufeld
  • 8,526
  • 1
  • 25
  • 44