I try to make applet for array including operations of insertion/removal/search.
For insertion and removal, it's easy: once user click the 'insert' or 'remove' button, just update the array, and call repaint to redraw the array.
However search is different, it's an animation, once the search button is clicked, I want to start from the first element in the array to check the value by high-light that element. I had the code as below, but it only high light the element at the last step (when the element is found), it doesn't high light each elements as i expected, I'm not quite familiar with applet animation, anyone can help? Thanks.
// index for search.
private searchIndex = -1;
public boolean search(int number) {
boolean found = false;
for (int i = 0; i < arr.getSize(); i++) {
searchIndex = i;
repaint();
revalidate();
if (arr.getElement(i) == number) {
found = true;
break;
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return found;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2;
g2 = (Graphics2D) g;
g2.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int xPos = START_X, yPos = START_Y;
int width = CELL_WIDTH, height = CELL_HEIGHT;
Font font = new Font("Serif", Font.BOLD, 12);
g2.setFont(font);
// draw array
for(int i = 0; i < arr.getSize(); i++) {
int element = arr.getElement(i);
g2.setColor(Color.BLUE);
g2.drawString(Integer.toString(element), xPos + OFFSET - 5, yPos + OFFSET + 5);
g2.setColor(Color.BLACK);
g2.drawRect(xPos, yPos, width, height);
xPos += width;
}
// high light the cell
if (searchIndex > -1) {
xPos = START_X + (runSearch * CELL_WIDTH);
g2.setColor(Color.blue);
g2.fillRect(xPos, yPos, width, height);
g2.setColor(Color.white);
g2.drawString(Integer.toString(arr.getElement(searchIndex)), xPos + OFFSET - 5, yPos + OFFSET + 5);
}
}