2014-01-20 89 views
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); 
    } 
} 

回答

1

這種做法是行不通的,因爲它阻止事件調度線程,阻止它處理它可能提出的任何新的事件,其中包括repaint事件。這基本上會掛起你的程序。

相反,你需要在循環的執行關閉加載到某種背景Thread的。

儘管您當然可以使用Thread,但您應該負責確保不違反Swing的單線程本質,即確保在事件分派的上下文中執行任何UI更新線。

爲此,我建議使用SwingWorker,因爲它可以讓你做後臺工作(獨立Thread),同時提供易於使用的功能同步更新回EDT

看看Concurrency in SwingSwingWorker特別是...