是否可以在 Swing 应用程序中间创建暂停? [英] Is it possible to create a pause in the middle of Swing application?
问题描述
我正在处理一个涉及通过从物理卡读取字符串进行访问的项目,以下代码简化了我的程序的要点,但是当我尝试在用户滑动后暂停几秒钟时他的卡,出了点问题,行为不是我所需要的,程序暂停,但颜色的窗格没有改变,标签也没有改变.
I'm working on a project that involves access by reading a String from a physical card, the following code simplifies the main point of my program, however when I try to make a pause for a few seconds after an user has swipe his card, something goes wrong and the behavior is not what I need, the program pauses but the color's pane doesn't change nor the label.
有什么建议吗?
这是代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class B2 extends JFrame implements ActionListener {
JLabel lbl;
JButton btn;
JTextField jtf;
String password = "123";
public B2() {
super("");
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setLayout(null);
this.setVisible(true);
setBounds(0,0,480, 250);
getContentPane().setBackground(Color.cyan);
btn = new JButton("OK");
lbl = new JLabel("Enter your password");
jtf = new JTextField(25);
btn.addActionListener(this);
lbl.setBounds(50, 100, 200, 25);
btn.setBounds(150, 180, 110, 25);
jtf.setBounds(20, 180, 110, 25);
getContentPane().add(btn);
getContentPane().add(lbl);
getContentPane().add(jtf);
}
public void actionPerformed(ActionEvent e) {
if(jtf.getText().equals(password)) {
getContentPane().setBackground(Color.green);
lbl.setText("Welcome");
} else {
getContentPane().setBackground(Color.red);
lbl.setText("Access Denied");
}
try {
Thread.sleep(3000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
getContentPane().setBackground(Color.cyan);
lbl.setText("Enter your password");
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
B2 frame = new B2();
}
});
}
}
推荐答案
使用 Thread.sleep()
可以防止 Swing 在暂停完成之前执行重绘.所以它会改变颜色并同时改变它,你不会看到效果.
Using Thread.sleep()
prevents Swing from doing a repaint until the pause has finished. So it will change the color and change it back at the same time and you won't see the effect.
尝试使用 Timer
代替.将此添加到您的代码中,它将起作用:
Try to use a Timer
instead. Add this to your code and it will work:
if(jtf.getText().equals(password)) {
getContentPane().setBackground(Color.green);
lbl.setText("Welcome");
} else {
getContentPane().setBackground(Color.red);
lbl.setText("Access Denied");
}
Timer timer = new Timer(3000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
getContentPane().setBackground(Color.cyan);
lbl.setText("Enter your password");
}
});
timer.setRepeats(false);
timer.start();
这篇关于是否可以在 Swing 应用程序中间创建暂停?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!