如何制作applet动画?

我尝试为数组制作applet,包括插入/删除/搜索操作。

对于插入和删除,很容易:一旦用户单击“插入”或“删除”按钮,只需更新数组,然后调用重绘以重绘数组。
但是搜索是不同的,它是一个动画,一旦点击搜索按钮,我想从数组中的第一个元素开始,通过高光那个元素来检查值。 我有下面的代码,但它只是高亮了最后一步的元素(当找到元素时),它没有像我期望的那样高亮每个元素,我对applet动画不是很熟悉,任何人都可以救命? 谢谢。

// 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  -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); } } 

因为Thread.sleep()导致EDT进入hibernate状态,这意味着在循环结束之前GUI不能重新绘制。 相反,你应该使用Swing Timer来安排动画。

阅读Swing教程 。 从“并发”部分开始(了解EDT的工作原理)和“如何使用计时器”。