我使用了Windowbuilder / SwingDesigner / Jframe。 我有以下课程:
public class Tag {
String name ="";
long startTime;
long endTime;
long result;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getStartTime() {
return startTime;
}
public void setStartTime(long startTime) {
this.startTime = startTime;
}
public long getEndTime() {
return endTime;
}
public void setEndTime(long endTime) {
this.endTime = endTime;
}
public long getResult() {
return result;
}
public void setResult(long result) {
this.result = result;
}
}
在“class”之后我使用Tag并更改信息:
public class Runtracker extends JFrame
{
private static Tag[] tags;
void connect ( String portName ) throws Exception
{
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);
while(true){
byte[] buffer = new byte[1024];
InputStream in = serialPort.getInputStream();
if(in.read(buffer) > 0);
{
for(int i=0; i < tags.length; i++)
{
String compare;
compare = in.toString();
if(tags[i].getName().equals(compare)){
tags[i].setEndTime(System.currentTimeMillis());
tags[i].setResult(tags[i].getEndTime() - tags[i].getStartTime());
//Here is the second update of my label, cause now i get the endtime and result
}
}
(new Thread(new SerialReader(in))).start();
}
}
}
else
{
System.out.println("Error: Only serial ports are handled by this example.");
}
}
}
public static class SerialReader implements Runnable
{
InputStream in;
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 )
{
String x = (new String(buffer,0,len));
try
{
Thread.sleep(1000);
} catch( Exception e)
{
System.out.println("Sleep error");
}
tags[tags.length+1].setName(x);
tags[tags.length+1].setStartTime(System.currentTimeMillis());
//here i have to create the label and fill the name and starttime in it
}
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Runtracker frame = new Runtracker();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
我用评论标记标记了这些地方,应该在哪里创建或更改标签。
输出应该是: 名称starttime endtime结果(endtime-starttime) 我的想法是:
LabelName.setText(tags[tags.length+1].getName + tags[tags.length+1].getStartTime());
但它不会更新上层状态,我们必须添加结束时间和结果。