I'm new to Java GUI. I'm having a trouble visualizing bubble sort algorithm. I'm going to have to prompt a user to type an array of numbers, and sort that array using bubble sort.
I have the code in the link below, consisting of ActionListener class, which is triggered after user finishing to input their arrays. I got the program working, but the thing is, I cannot "View" the ongoing graphics. The graphics should display the ongoing sorting of rectangular bar, but all I see is the sorted result. Could anyone please help me on what I am doing wrong here?
` //The BubbleListener class will implement buttons chosen by player
private class BubbleListener implements ActionListener{
//Graphics g = frame.getGraphics();
public void actionPerformed(ActionEvent e) {
frame = new JFrame("Sorting Algorithm Visualiser");
frame.setSize(800, 800);
//g = frame.getGraphics();
bubbleLabel.setText("<html><b><div style='text-align: left'>Please input an array of numbers to be bubble-sorted separated by comma: </b></div></html");
textInput = new JTextField(15);
textInput.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
input = textInput.getText(); //receive input from text field
String[] splitArr=input.split(","); //
splitNum=new int[splitArr.length];
for (int i=0; i<splitArr.length; i++) {
System.out.print(splitNum[i]=Integer.parseInt(splitArr[i]));
System.out.print(' ');
}
System.out.println(input);
System.out.println("Testing input");
for(int i = 0;i<splitNum.length-1;i++){
g = frame.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(50, 200, 700, 700);
//Bubble sort algorithm
for(int j = 0;j<splitNum.length-i-1;j++){
if(splitNum[j]>splitNum[j+1]){
int temp = splitNum[j];
splitNum[j] = splitNum[j+1];
splitNum[j+1] = temp;
//splitNum[j+1]=(splitNum[j+1]+splitNum[j])-(splitNum[j]=splitNum[j+1]);
}
}
//Printing the array
for(int k = 0;k<splitNum.length;k++){
g.setColor(Color.BLACK) ;
g.fillRect(100+50*k,500-splitNum[k]*30,30,splitNum[k]*30);
g.drawString(""+splitNum[k],100+50 * k,530);
}
System.out.println(Arrays.toString(splitNum));
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
/*Set form properties*/
FlowLayout fl = new FlowLayout();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Shut down process
frame.setLayout(fl); //Set up flow layout
frame.setResizable(false); //Cannot change form size
//frame.pack();
frame.setLocationRelativeTo(null);//Center display
bubblePanel.add(bubbleLabel);
bubblePanel.add(textInput);
bubbleVal = textInput.getText();
String [] bubbleSplit = bubbleVal.split(",");
frame.getContentPane().add(bubblePanel);
frame.setVisible(true);
}
} `