【发布时间】:2014-01-03 08:28:40
【问题描述】:
这是来自 RXTX 串行通信程序的示例代码的一部分。 我想知道如何提取我创建的用于存储输出的字符串变量,以便我可以在另一个类中使用它。输出显示在控制台上,但我想在 JTextfield 中显示它,我无法提取它。我已经完成了 GUI 部分。 首先我将展示主要部分:
public class MainSerialGui {
public static void main(String[] args) {
SerialGui vimal = new SerialGui ();
vimal.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
vimal.setSize(250, 200);
vimal.setVisible(true);
}
}
这是图形用户界面部分
public class SerialGui extends JFrame { //inherit all the stuff from JFrame and let us create a window
private JTextField item1;
private JButton readButton;
public SerialGui (){
setLayout(new FlowLayout());
item1 = new JTextField("Display Output");
add(item1);
readButton = new JButton("Read Data");
add(readButton);
thehandler handler = new thehandler();
readButton.addActionListener(handler);
}
private class thehandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
if(event.getSource() == readButton){
String portName = "COM4";
try{
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if ( portIdentifier.isCurrentlyOwned() )
{
System.out.println("Error: Port is currently in use");
}
else
{
CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);
if ( commPort instanceof SerialPort )
{
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(57600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE); // Setting port parameters
InputStream in = serialPort.getInputStream();
OutputStream out = serialPort.getOutputStream();
(new Thread(new SerialReader(in))).start();
SerialReader comm = new SerialReader(null);
item1.setText(comm.str);
}
}
}
catch (Exception e){
e.printStackTrace();
System.out.println("Only serial ports please");
}
}
}
}
}
这是一个单独的类,用于从通信端口读取数据。
public class SerialReader implements Runnable {
InputStream in;
public String str;
public SerialReader ( InputStream in )
{
this.in = in;
}
public void run ()
{
byte[] buffer = new byte[1024];
int len = -1;
try
{
while ( ( len = this.in.read(buffer)) > -1 )
{
str = new String(buffer,0,len); // I would like to take this String
System.out.print(str); // and use it to display in a
} // Jtextfield
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
这是我最初提取它以显示在文本字段中的方式,但结果显示为空。我将 str 声明为公共字符串,以便它在 GUI 类中可见。正在读取的数据可以显示在控制台中,但文本字段中没有变化。是因为它甚至在输出存储在 str 之前就取值还是因为“null”参数? 我无法用任何其他论点代替它。
SerialReader comm = new SerialReader(null);
item1.setText(comm.str);
http://rxtx.qbang.org/wiki/index.php/Two_way_communcation_with_the_serial_port
【问题讨论】:
-
如需更好的帮助,请尽快发帖SSCCE
-
“我想获取这个字符串并用它在 Jtextfield 中显示” -
textField.setText(str);有什么问题? -
你在做什么有什么问题?
-
嗨..对于我的问题缺少信息,我深表歉意。我已经更新了我的帖子,也尝试过使用 setText(str) 但它只显示 null。
标签: java swing serial-port jtextfield event-dispatch-thread