신입생 데이터 포트에 문자열을 수신 할 때까지 출력 포트에 데이터 문자열을 출력 한 다음 다른 조치를 취해야합니다. 현재 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);
}
}