I have to sort an array of 10 numbers using insertion sort and display them using rectangles (i.e. a bar graph). Each time the user hits “next” it will sort the next position in the array. The console confirms that my algorithm is working, and the rectangles will become bigger/smaller but will only overwrite themselves on top of another rectangle; the panel will not erase before drawing new rectangles. How can I fix this? Here are the important parts of my code:
public class graphTest extends JFrame {
int[] numbers = {31, 19, 76, 24, 94, 99, 21, 74, 40, 73};
private JButton action = new JButton("Next");
public graphTest(){
final ImagePanel p1 = new ImagePanel();
add(action, BorderLayout.SOUTH);
p1.add(new ImagePanel(), BorderLayout.CENTER);
add(p1,BorderLayout.CENTER);
action.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Code for insertion sort
p1.repaint();
//System.out.println testing array
}
});
}
class ImagePanel extends JPanel{
public void paintComponent (Graphics g){
super.paintComponents(g);
g.setColor(Color.black);
for(int i = 0; i < 10; i++)
g.drawRect(10*i+10,200-numbers[i],7,numbers[i]);
}
}
public static void main(String[] args) {
JFrame frame = new graphTest();
frame.setTitle("Hi");
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
I’ve made a quick workaround by just drawing a large fillRect before drawing the regular rectangles, but I would still like to learn how to properly redraw a JPanel.
In
ImagePanel.paintComponent( Graphics g ):you call
super.paintComponents(g)when what you really want issuper.paintComponent(g)