这个类叫做操作系统,我必须制作一个模拟时钟,在某个时间读取信息并用它做一些事情,但我只是在这里询问时钟部分。现在,我有4个按钮,分别是 run , tick , read 和 show status 。我有一个输入,一个输出和一个计时器文本字段。我有一个clockstarter
类,在程序启动时启动时钟并将其写入控制台。我应该有两个线程,所以当发生这种情况时,我可以点击“运行”并且计时器文本字段开始连续计数或如果没有点击运行,我可以手动添加时间与勾选。我需要帮助让它在文本字段中显示。
public class ClockStarter implements Runnable {
private Thread thread;
private int currentTime;
private javax.swing.JTextField time;
public ClockStarter(javax.swing.JTextField t){
System.out.println("Clock Starter Constructor");
currentTime = -1;
time = t;
thread = new Thread(this);
thread.start();
}
public void run(){
while(true){
incrementTime();
System.out.println("Clock Starter Current Time ");
time = ("" + getCurrentTime());// I need to fix this line
try{Thread.sleep(1000);} catch(Exception e){}
}
}
public void incrementTime(){
currentTime++;
}
public int getCurrentTime(){
return currentTime;
}
}
答案 0 :(得分:0)
不使用Thread.sleep()
,因为它会冻结您的Swing应用程序。
相反,您应该使用javax.swing.Timer
。
有关更多信息和示例,请参阅Java教程How to Use Swing Timers和Lesson: Concurrency in Swing。
请阅读Swing教程How to Use Text Fields:
文本字段是一种基本文本控件,使用户可以键入少量文本。当用户指示文本输入完成时(通常按Enter键),文本字段将触发操作事件。如果您需要从用户那里获得多行输入,请使用文本区域。
示例代码
/* TextDemo.java requires no other files. */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TextDemo extends JPanel implements ActionListener {
protected JTextField textField;
protected JTextArea textArea;
private final static String newline = "\n";
public TextDemo() {
super(new GridBagLayout());
textField = new JTextField(20);
textField.addActionListener(this);
textArea = new JTextArea(5, 20);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
//Add Components to this panel.
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
add(textField, c);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
add(scrollPane, c);
}
public void actionPerformed(ActionEvent evt) {
String text = textField.getText();
textArea.append(text + newline);
textField.selectAll();
//Make sure the new text is visible, even if there
//was a selection in the text area.
textArea.setCaretPosition(textArea.getDocument().getLength());
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("TextDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add contents to the window.
frame.add(new TextDemo());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}