日期:2014-05-20  浏览次数:20714 次

求助一个关于Timer的问题
大家好,我就一个学生,现在正在做书后的一个编程练习,逻辑有问题,麻烦大家办看看,代码不长,谢谢!
import   java.awt.*;
import   java.awt.event.*;
import   javax.swing.*;
import   javax.swing.border.LineBorder;

public   class   H13_9   extends   JFrame   implements   ActionListener
{
Button[]   leftButtons=new   Button[8];
Button[]   rightButtons=new   Button[8];
JPanel[]   panels=new   JPanel[8];
ColorPanel[]   cp=new   ColorPanel[8];
Timer   timer=new   Timer(2000,this);
boolean   stub=true;
int   thisSta=1;
int   tarSta=1;

H13_9()
{
this.setLayout(new   GridLayout(8,1));
this.setTitle( "Exercise   13.9 ");
for(int   i=7;i> =0;i--)
{
timer.addActionListener(this);
timer.start();
panels[i]=new   JPanel();
cp[i]=new   ColorPanel();
panels[i].setLayout(new   BorderLayout());
leftButtons[i]=new   Button( "     F "+(i+1)+ "     ");
leftButtons[i].addActionListener(this);
panels[i].add(leftButtons[i],BorderLayout.WEST);
rightButtons[i]=new   Button( "     F "+(i+1)+ "     ");
rightButtons[i].setEnabled(!stub);
rightButtons[i].addActionListener(this);
panels[i].add(rightButtons[i],BorderLayout.EAST);
panels[i].add(cp[i]);
panels[i].setBorder(new   LineBorder(Color.BLACK,1));
this.add(panels[i]);
}
if(thisSta==tarSta)
{
timer.stop();
cp[tarSta-1].s= 'G ';
cp[tarSta-1].repaint();
}
}

public   void   actionPerformed(ActionEvent   e)
{
if(e.getSource()==timer)
{
if(thisSta==tarSta)
{
stub=!stub;
timer.stop();
for(int   i=0;i <8;i++)
{
leftButtons[i].setEnabled(stub);
rightButtons[i].setEnabled(!stub);
}
cp[tarSta-1].s= 'G ';
cp[tarSta-1].repaint();
}
else
{
cp[thisSta-1].s= 'N ';
cp[thisSta-1].repaint();
if(thisSta <tarSta)
{
cp[thisSta].s= 'R ';
cp[thisSta].repaint();
System.out.println(thisSta);
thisSta++;
}
else
{
cp[thisSta-2].s= 'R ';
cp[thisSta-2].repaint();
thisSta--;
}
}
}
else
{
for(int   i=0;i <=7;i++)
{
if(e.getSource()==leftButtons[i])
{
tarSta=i+1;
if(thisSta!=tarSta)
timer.start();
break;
}
if(e.getSource()==rightButtons[i])
{
tarSta=i+1;
if(thisSta!=tarSta)
timer.start();
break;
}
}
}
}

public   static   void   main(String[]   args)
{
H13_9   h13_9=new   H13_9();
h13_9.setSize(210,200);
h13_9.setVisible(true);
h13_9.setDefaultCloseOperation(3);
}
}

class   ColorPanel   extends   JPanel
{
char   s= 'N ';
public   void   paintComponent(Graphics   g)
{
super.paintComponent(g);
if(s== 'N ')
setBackground(Color.WHITE);
else   if(s== 'G ')
setBackground(Color.GREEN);
else   if(s== 'R ')
setBackground(Color.RED);
}
}

这是一个模拟电梯程序,先按左边的钮呼叫电梯,到达后按右边的钮去目标楼层,我这个Timer为什么一下子就走到了呢?而不是一步一步地到达?谢谢大家