[英]JTextField is updating String data along with junk
我正在嘗試將接收到的ByteBuffer
數據(轉換為String
)更新為JTextField
,但是即使在修剪字符串之后,文本字段也將打印輸出數據以及垃圾值。
但是在輸出控制台中,它正在打印適當的數據,當涉及GUI中的文本字段時,它正在打印垃圾數據以及適當的數據。
import org.usb4java.LibUsb;
import org.usb4java.LibUsbException;
public class UsbRead
{
static final byte IN_ENDPOINT1 = (byte) 0x82;
static final int TIMEOUT = 100;
static final byte INTERFACE = 1;
static final byte interfaceNum = 1;
static String s=new String();
static String dd=new String();
public static String read(DeviceHandle handle)
{
try{
System.out.println("-----read-----");
ByteBuffer buffer = BufferUtils.allocateByteBuffer(30);
IntBuffer transferred = BufferUtils.allocateIntBuffer();
System.out.println("capacity-->"+buffer.capacity());
int result=LibUsb.bulkTransfer(handle, IN_ENDPOINT1, buffer,
transferred, TIMEOUT);
if (result != LibUsb.SUCCESS)
{
throw new LibUsbException("Unable to read data", result);
}
else
{
System.out.println("---------------------------read----------");
System.out.println(transferred.get() + "-------- bytes read from device");
s="";
s = StandardCharsets.UTF_8.decode(buffer).toString();
System.out.println("s--"+s);
s.trim();
WisePanel4.textField_1.setText(s);
dd=s;
System.out.println("received data ->"+dd);
}
return dd;
}
catch(Exception e)
{
System.out.println("-*----read time out");
}
return dd;
}
}
輸出->
---------------------------read----------
20-------- bytes read from device
s--192.168.1.108
received data ->192.168.1.108
請檢查GUI的圖像。 它正在使用適當的數據打印垃圾值:
您很可能會收到C字符串作為響應。 因此,字符串以NUL('\\ 0')字符終止。 嘗試使用以下方法獲取值:
s = s.substring(0, s.indexOf('\0'));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.