2016-06-10 30 views
0

你好我有樂趣的Arduino:d顯示的serialEvent在JLabel的

而且我的serialEvent

public synchronized void serialEvent(SerialPortEvent oEvent) { 
    if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) { 
     try { 
      String inputLine = input.readLine(); 
      System.out.println(inputLine); 

     } catch (Exception e) { 
      System.err.println(e.toString()); 
     } 
    } 
} 

如何看起來應該像代碼以顯示在一個JLabel(的Java Swing)文本

lblText.setText(inputLine.toString()); 

但我有錯誤inputLine cannot be resolved

+0

這裏是代碼http://pastebin.com/qEhafEhp –

回答

0
  1. inputLine無法解析,因爲它正在被訪問出scope。在類級作用域而不是方法級作用域聲明inputLine以解決您的問題。
  2. 您在searialEvent(...)方法和initialize()方法中訪問lblTxt,因此也必須在類級範圍內。

在上下文中的小例子:

... //Imports and package declaration 

public class ArduinoGUI implements SerialPortEventListener { 

    private String inputLine; 
    private JLabel lblTxt; 

    ... //Other private variables, initialize2(), and close() 

    public synchronized void serialEvent(SerialPortEvent oEvent) { 
     if(oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) { 
      try { 
       inputLine = input.readLine(); //Don't forget to use the        
               //class-level scope variable here 
       System.out.println(inputLine); 
       lblTxt.setText(inputLine); //.toString() unnessesary since 
              //inputLine is a String 
     } catch (Exception e) { 
      System.err.println(e.toString()); 
     } 
    } 

    ... //Main method and constructor 

    private void initialize() { 
     ... //GUI stuff 
     lblTxt = new JLabel("txt"); //Don't forget to use the 
            //class-level scope variable here too 
     ... //Adding lblTxt to frame 
     lblTxt.setText(inputLine); //Again, .toString() unnessesary 
    } 
} 
+0

受到了很多的錯誤,爲什麼呢? http://pastebin.com/qE7pp3TP –

+0

line 92:window.frame.setVisible(true); –

+0

什麼樣的錯誤?我無法編譯你的代碼並找出來,因爲我沒有外部的.jar文件。 – MasterBlaster