JFrame组件之间的触发延迟
我想展示如何使用JFrame
直观地进行合并排序。 我想做的是让后续的JLabel
可见一段时间延迟。 我尝试了很多方法,但所有这些都出现在同一时刻,没有中间延迟。
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: // jLabel1.setVisible(false); jLabel2.setVisible(false); jLabel3.setVisible(false); jLabel4.setVisible(false); jLabel5.setVisible(false); jLabel6.setVisible(false); jLabel7.setVisible(false); final Timer t=new Timer((4000), null); final int delay=2000; final ActionListener taskPerformer = new ActionListener() { public void actionPerformed(ActionEvent evt) { jLabel1.setVisible(true); t.getDelay(); jLabel2.setVisible(true); t.setDelay(3000); jLabel3.setVisible(true); t.setDelay(2000); jLabel4.setVisible(true); t.setDelay(2000); jLabel5.setVisible(true); t.setDelay(2000); jLabel6.setVisible(true); t.setDelay(2000); } }; new Timer(delay, taskPerformer).start();
但是,当我点击按钮时,所有的标签出现在同一个momenet,虽然我一直拖延。
造成这种情况的原因有很多。 首先, javax.swing.Timer
不能以这种方式工作。 它在后台等待,直到给定的延迟过去,然后调用已注册的ActionListener
的actionPerformed
方法。
其次,如果它以这种方式工作,它将阻止事件调度线程,阻止它处理重绘请求。
我想你会发现如何使用Swing Timers 。
public class BlinkOut { public static void main(String[] args) { new BlinkOut(); } public BlinkOut() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { } JFrame frame = new JFrame("Test"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); frame.add(new TestPane()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public class TestPane extends JPanel { private JLabel[] labels; private int[] delays; private Timer timer; private int index; public TestPane() { setLayout(new GridLayout(0, 1)); labels = new JLabel[7]; for (int index = 0; index < 7; index++) { labels[index] = new JLabel("Label " + (index + 1)); add(labels[index]); } delays = new int[] {2000, 3000, 2000, 2000, 2000, 2000, 2000}; JButton hide = new JButton("Hide"); add(hide); hide.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("Click"); index = 0; labels[index].setVisible(false); timer.setDelay(delays[index]); timer.start(); } }); timer = new Timer(delays[0], new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("Tick"); timer.stop(); index++; if (index < 7) { labels[index].setVisible(false); timer.setDelay(delays[index]); timer.start(); } } }); timer.setRepeats(false); timer.setCoalesce(true); } } }
您需要更新计时器的动作侦听器中的图标,如此处所示。 您可以实现Icon
界面来渲染大小与元素比较值成比例的图标,如此处所示。
附录: 请你稍微具体一点吗?
您希望为某些初始随机顺序排序大小为N
的List
的中间步骤设置动画。 Number
子类实现Comparable
,因此compareTo()
已经完成。 每个具有Icon
的JLabel
GridLayout(1, 0)
可用于显示值。 DecRenderer
显示如何创建具有比例大小的图标; 你想要改变区间[0, N)
的高度。 GrayIcons
&Mad的示例显示了如何以某种顺序为图标的显示设置动画。