【发布时间】:2015-04-17 06:03:39
【问题描述】:
我对编程世界还是很陌生,并且最近注意到,每当我告诉程序在代码之间在之间闲置几秒钟时,它会在开始时休眠然后继续通过剩余的代码。
我尝试了各种方法,例如 thread.sleep() 或 Timers,但我从来没有得到我想要的。
这是一个例子:
public void Console(){
Console.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Console.setSize(500, 500);
Console.setLocationRelativeTo(null);
Console.setResizable(false);
Console.setVisible(true);
Console.setTitle("Console");
JPanel contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
Console.setContentPane(contentPane);
contentPane.setLayout(null);
contentPane.setBackground(new Color(47, 79, 79));
cinput.setBounds(10, 442, 353, 20);
contentPane.add(cinput);
cinput.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
in();
cinput.requestFocus();
}
});
cinput.setColumns(10);
cinput.requestFocus();
JButton Enter = new JButton("Enter");
Enter.setBounds(373, 439, 111, 23);
contentPane.add(Enter);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 10, 474, 421);
contentPane.add(scrollPane);
cmd.setEditable(false);
cmd.setFont(new Font("Courier New", Font.PLAIN, 18));
cmd.setForeground(Color.GREEN);
cmd.setText("CONSOLE\n");
cmd.setBackground(Color.BLACK);
cmd.setLineWrap(true);
cmd.setWrapStyleWord(true);
scrollPane.setViewportView(cmd);
Enter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
in();
cinput.requestFocus();
}
});
}
private void addText(JTextArea textArea, String text) {
String input = textArea.getText();
String output = input + text;
textArea.setText(output);
}
private void in()
{
String input = cinput.getText();
cinput.setText("");
String text;
text = input;
addText(cmd, "> " + text + "\n");
if(text.equals("start"))
{
addText(cmd, "1");
// SLEEP HERE
Thread.sleep(1000);
// -------------------
addText(cmd, "2");
}
else if(text.equals("exit"))
{
Console.dispose();
}
}
它应该看起来像这样:
在这个非常基本的“控制台”中,每当我在文本框中键入“开始”并按 Enter 键时,我希望首先出现数字“1”,然后在 1000 毫秒后出现数字“2”,但它不会出现” !
有没有办法让程序在语句之间休眠而不是总是在函数的开头休眠?
提前致谢
【问题讨论】:
标签: java multithreading swing sleep thread-sleep