java设置按钮点击效果,要在java中设置单击按钮的延迟?

I have a save button in a JFrame ;on clicking save the 'save' text sets to 'saving....'; I need to set that text as 'saved' after a delay of 10 seconds.How is it possible in java?

Please help...

try {

Thread.sleep(4000);

} catch (InterruptedException e) {

e.printStackTrace();

}

This is what i did...but this wont shows as 'saving' during that delayed time.

解决方案

If you want to provide the user with visual feedback that something is going on (and maybe give some hint about the progress) then go for JProgressBar and SwingWorker (more details).

If on the other hand you want to have a situation, when user clicks the button and the task is supposed to run in the background (while the user does other things), then I would use the following approach:

button.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

button.setEnabled(false); // change text if you want

new SwingWorker() {

@Override

protected Void doInBackground() throws Exception {

// Do the calculations

// Wait if you want

Thread.sleep(1000);

// Dont touch the UI

return null;

}

@Override

protected void done() {

try {

get();

} catch (Exception ignore) {

} finally {

button.setEnabled(true); // restore the text if needed

}

}

}.execute();

}

});

Finally, the initial solution that was using the Swing specific timer:

final JButton button = new JButton("Save");

button.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

// Take somehow care of multiple clicks

button.setText("Saving...");

final Timer t = new Timer(10000, new ActionListener() {

@Override

public void actionPerformed(ActionEvent evt) {

button.setText("Saved");

}

});

t.setRepeats(false);

t.start();

}

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值