我正在尝试将接收到的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 的图像。它正在使用正确的数据打印垃圾值: