我有一個框架,當我在tester2框架上單擊確定按鈕時,應該看到tester1框架,並且當單擊showbumber按鈕時,應該在我的標籤中顯示一個隨機數。JButton和JLabel不顯示在JDialog上並且睡眠不起作用
但我看不到這個生成的數字,而我使用睡眠方法!
感謝您的幫助。
public class tester2 extends JFrame implements ActionListener {
public tester2() {
setTitle("Hello");
setLayout(new FlowLayout());
JButton okButton = new JButton("Ok");
okButton.addActionListener(this);
add(okButton);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(40, 50, 300, 400);
}
@Override
public void actionPerformed(ActionEvent e) {
tester1 tester1 = new tester1(tester2.this);
tester1.setVisible(true);
}
public static void main(String[] args) {
new tester2().setVisible(true);
}
}
測試儀1:
public class tester1 extends JDialog implements ActionListener {
JLabel lbl1;
JButton showButton;
public tester1(JFrame owner) {
super(owner, "tester1", true);
showButton = new JButton("Show Number");
showButton.addActionListener(this);
lbl1 = new JLabel(" ");
this.add(showButton);
this.add(lbl1);
this.setBounds(40, 50, 300, 400);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == showButton) {
GenerateNumber();
tester1.this.dispose();
}
}
public void GenerateNumber() {
Random rnd1 = new Random();
try {
Thread.sleep(1000);
lbl1.setText(String.valueOf(rnd1.nextInt(100)));
} catch (InterruptedException inrptdEx) {
}
}
}
您要處理你的框架,在標籤設置文本之後。爲什麼?它不會讓你看到你設定的文字。同時遵循[命名約定](http://www.oracle.com/technetwork/java/codeconv-138413.html),同時在java中進行編碼。 – 2013-02-19 09:53:02
在EDT內睡覺將阻止Swing執行任何重繪。而不是使用Thread.sleep,請使用javax.swing.Timer – MadProgrammer 2013-02-19 10:00:52
看看我的帖子,看看我的答案 – 2013-02-19 10:30:18