【发布时间】:2015-03-18 06:29:57
【问题描述】:
我正在开展一个项目,该项目涉及通过从物理卡读取字符串进行访问,以下代码简化了我程序的要点,但是当我尝试在用户滑动后暂停几秒钟时他的卡,出了点问题,行为不是我需要的,程序暂停,但颜色的窗格没有改变,标签也没有改变。
有什么建议吗?
这是代码:
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();
}
});
}
}
【问题讨论】:
-
不要在 EDT 上睡觉; 做见Concurrency in Swing.
-
是的,但不是你的做法。最好使用摆动计时器
-
this.setLayout(null);Java GUI 必须在不同的操作系统、屏幕尺寸、屏幕分辨率等上工作。因此,它们不利于像素完美布局。而是使用布局管理器,或 combinations of them 以及 white space 的布局填充和边框。 -
顺便说一句,如果您正在等待用户提供值,最好将
JFrame更改为模态JDialog or aJOptionPane`。这将“阻止”对 GUI 和下一个代码行的访问,直到对话框被关闭。 -
感谢大家提供有用的 cmets,它们对我来说非常重要。
标签: java multithreading swing thread-safety