在JLabel中定时更新BMP图片(使用了Swing包中的timer),界面层实现的部分代码如下。。
如何把点击播放按钮中的响应事件迁移到模型层呢?或者不使用定时器,改用别的实现这个功能,可以吗?import java.awt.*;
import java.awt.event.*;
import java.io.File;import javax.swing.*;
public class TestBmp extends JFrame implements ActionListener { private static final long serialVersionUID = -6326060400269044196L;
private JButton [] jb;
File [] f;
JLabel jl;
//定时器及其相关设置参数
javax.swing.Timer timer;
int flag = 0,circletime = 40;
public TestBmp(File file){
String [] str ={"播放","暂停","停止","加速","减速"};
jb = new JButton[str.length];
this.setLayout(new FlowLayout());
for(int i = 0 ;i < str.length ; i++) {
jb[i] = new JButton(str[i]);
jb[i].addActionListener(this);
if(i>0) jb[i].setEnabled(false);
this.add(jb[i]);
}
f = file.listFiles();
//jl 用来显示BMP图片,其中BmpParse中的loadBitmap方法读取BMP图片
BmpParse bp = new BmpParse();
Image im = bp.loadBitmap(f[flag]);
jl = new JLabel(new ImageIcon(im));
this.add(jl);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}
public static void main(String[] args) {
new TestBmp(new File("D:/Love/Ours")); }
@Override
public void actionPerformed(ActionEvent e) {
Object obj = e.getSource();
if(obj==jb[0]) {
//??这里的代码多达30多行,能不能把它们迁移到模型层去呢?
//播放,首先使暂停停止加速减速等按钮启动
jb[1].setEnabled(true);
jb[2].setEnabled(true);
jb[3].setEnabled(true);
jb[4].setEnabled(true);
//更新JLabel中的图片,先创建定时器中的任务
ActionListener taskPerformer=new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
BmpParse bp = new BmpParse();
Image im = bp.loadBitmap(f[flag++]);
jl.setIcon(new ImageIcon(im));
//将BMP的头文件信息显示到一些JLabel中去
//……
//……
}
};
timer=new Timer(circletime,taskPerformer);
     timer.start();
} else if(obj==jb[1]){
//暂停
if(timer.isRunning()) timer.stop();
} else if(obj==jb[2]){
//停止,清零……
if(timer.isRunning()) timer.stop();
} else if(obj==jb[3]){
//加速,修改circletime
} else if(obj==jb[4]){
//减速 ,修改circletime
}
}
}

解决方案 »

  1.   

    可以把Timer的初始化从ActionListener中移至构造方法中,在相应ActionListener中只是进行Timer.start()方法的调用
      

  2.   

    恩,这是一个好思路。可是还停留在View层,我是想能不能直接把这些东西全部移到Model层里面。
    比如在BmpModel的这个类中有一个方法setPlay(),来响应播放按钮的事件。然后View层就很简洁://……
      BmpModel bm = new BmpModel();
      bm.setPlay("传递参数,比如JButton,JLabel等等");
    //