您好,我正在玩Arduino:D
我有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 :(得分:0)
inputLine
无法解析,因为它是从scope访问的。在类级别范围内声明inputLine
而不是方法级范围来解决您的问题。 lblTxt
方法和searialEvent(...)
方法访问initialize()
,这样也必须属于班级范围。上下文中的简短示例:
... //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
}
}