0
我是新來的Java 我有數據輸出端口的輸出字符串的要求內停止循環,直到我收到的數據端口上的繩子,然後採取其他行動。 撇開COM端口的問題,就目前而言,我想流簡單地使用按鈕來啓動然後停止模擬數據,和我慘遭失敗。 這是我創建的代碼。我想開始輸出到文本區域,直到我按下停止按鈕。我怎麼可以就一個JFrame
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextArea;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.concurrent.TimeUnit;
public class WriteToWindow extends JFrame {
private JPanel contentPane;
private final static String newline = "\n";
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WriteToWindow frame = new WriteToWindow();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public WriteToWindow() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
// try adding final
final JTextArea textArea = new JTextArea();
textArea.setRows(10);
textArea.setBounds(27, 23, 377, 142);
contentPane.add(textArea);
JButton btnStart = new JButton("Start");
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// start writing to the text area
int i = 1;
textArea.append("You clicked start" + newline);
do {
textArea.append("Iteration " + Integer.toString(i) + newline);
i++;
// wait a second
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (true);// forever
}
});
btnStart.setBounds(25, 188, 89, 23);
contentPane.add(btnStart);
JButton btnStop = new JButton("Stop");
btnStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//stop writing data to the text area
textArea.append("You clicked stop" + newline);
}
});
btnStop.setBounds(151, 188, 89, 23);
contentPane.add(btnStop);
}
}