如何将并发线程插入下面的java fx代码,以便图形用户界面(GUI)可以显示出价编号,单圈时间和圈数。
这是我的代码:
napfa_running_reader.java
package napfa_running_reader;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import com.thingmagic.*;
import java.util.Hashtable; // Added by Darren
import javafx.scene.layout.VBox;
/**
*
* @author pc
*/
public class Napfa_Running_Reader extends Application {
private static DbConnect db = new DbConnect();
private static Reader r = null;
private static String argv [] = null;
@Override
public void start(Stage primaryStage) {
TextArea ta = new TextArea();
ta.setEditable(false);
Button btn = new Button();
btn.setText("Stop Reader");
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
// System.out.println("Program Terminated!");
ta.appendText("Program Terminated!\n");
r.destroy();
//System.exit(0); //Kill whole program
}
});
VBox vb = new VBox();
vb.getChildren().addAll(ta, btn);
vb.setSpacing(10);
StackPane root = new StackPane();
root.getChildren().add(vb);
Scene scene = new Scene(root, 500, 500);
primaryStage.setTitle("NAPFA Lap Timing Monitor"); //Change the window title
primaryStage.setScene(scene);
primaryStage.show();
int nextarg = 0;
boolean trace = false;
int[] antennaList = null;
if (argv.length < 1) {
usage();
}
if (argv[nextarg].equals("-v")) {
trace = true;
nextarg++;
}
// Create Reader object, connecting to physical device
try {
TagReadData[] tagReads;
String readerURI = argv[nextarg];
nextarg++;
for (; nextarg < argv.length; nextarg++) {
String arg = argv[nextarg];
if (arg.equalsIgnoreCase("--ant")) {
if (antennaList != null) {
System.out.println("Duplicate argument: --ant specified more than once");
usage();
}
antennaList = parseAntennaList(argv, nextarg);
nextarg++;
} else {
System.out.println("Argument " + argv[nextarg] + " is not recognised");
usage();
}
}
readerURI = readerURI.substring(9);
r = Reader.create(readerURI);
if (trace) {
setTrace(r, new String[]{"on"});
}
r.connect();
if (Reader.Region.UNSPEC == (Reader.Region) r.paramGet("/reader/region/id")) {
Reader.Region[] supportedRegions = (Reader.Region[]) r.paramGet(TMConstants.TMR_PARAM_REGION_SUPPORTEDREGIONS);
if (supportedRegions.length < 1) {
throw new Exception("Reader doesn't support any regions");
} else {
r.paramSet("/reader/region/id", supportedRegions[0]);
}
}
String model = r.paramGet("/reader/version/model").toString();
if ((model.equalsIgnoreCase("M6e Micro") || model.equalsIgnoreCase("M6e Nano")) && antennaList == null) {
System.out.println("Module doesn't has antenna detection support, please provide antenna list");
r.destroy();
usage();
}
SimpleReadPlan plan = new SimpleReadPlan(antennaList, TagProtocol.GEN2, null, null, 1000);
r.paramSet(TMConstants.TMR_PARAM_READ_PLAN, plan);
Hashtable<String, Tag> ht = new Hashtable<String, Tag>();
while (true) {
// Read tags
tagReads = r.read(500);
// Print tag reads
for (TagReadData tr : tagReads) {
String tagID = tr.toString().substring(4, 28);
ta.appendText("Info Received: " + tr.toString() + "\n");
ta.appendText("Tag ID Found: " + tagID + "\n");
ta.appendText("Bid Number: " + db.getBidNo(tagID) + "\n");
long currentTime = System.currentTimeMillis();
if (!ht.containsKey(tagID)) {
ht.put(tagID, new Tag(currentTime));
} else {
long duration = currentTime - ht.get(tagID).getPrevTiming();
if ((duration / 1000) > 35 && ht.get(tagID).getNoOfLaps() < 6) {
ht.get(tagID).setPrevTime(currentTime);
ht.get(tagID).addTiming(duration + ht.get(tagID).getLatestLapTiming());
}
}
ta.appendText("No. of Laps: " + ht.get(tagID).getNoOfLaps() + "\n");
ta.appendText(ht.get(tagID).displayLapTimings() + "\n");
if (ht.get(tagID).getNoOfLaps() == 6 && !ht.get(tagID).isRunCompleted() && ht.containsKey(tagID)) {
ta.appendText(tagID + " Run Completed" + "\n");
db.updateLapTimings(ht.get(tagID), tagID);
ht.get(tagID).setRunCompleted();
}
}
}
} catch (ReaderException re) {
System.out.println("Reader Exception : " + re.getMessage());
} catch (Exception re) {
System.out.println("Exception : " + re.getMessage());
}
}
public void usage() {
System.out.printf("Usage: Please provide valid arguments, such as:\n"
+ " (URI: 'tmr:///COM1 --ant 1,2' or 'tmr://astra-2100d3/ --ant 1,2' "
+ "or 'tmr:///dev/ttyS0 --ant 1,2')\n\n");
System.exit(1);
}
public void setTrace(Reader r, String args[]) {
if (args[0].toLowerCase().equals("on")) {
r.addTransportListener(r.simpleTransportListener);
}
}
public int[] parseAntennaList(String[] args, int argPosition) {
int[] antennaList = null;
try {
String argument = args[argPosition + 1];
String[] antennas = argument.split(",");
int i = 0;
antennaList = new int[antennas.length];
for (String ant : antennas) {
antennaList[i] = Integer.parseInt(ant);
i++;
}
} catch (IndexOutOfBoundsException ex) {
System.out.println("Missing argument after " + args[argPosition]);
usage();
} catch (Exception ex) {
System.out.println("Invalid argument at position " + (argPosition + 1) + ". " + ex.getMessage());
usage();
}
return antennaList;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
argv = args;
launch(args);
}
}
Tag.java
package napfa_running_reader;
import java.util.ArrayList;
/**
*
* @author pc
*/
public class Tag {
private ArrayList<Long> timings;
private long prevTime;
private boolean runCompleted;
public Tag(long prevTime) {
this.timings = new ArrayList<Long>();
this.prevTime = prevTime;
this.runCompleted = false;
}
//Accessor Methods
public long getPrevTiming() {
return this.prevTime;
}
public int getNoOfLaps() {
return this.timings.size();
}
public long getLatestLapTiming() {
return (this.timings.size() == 0) ? 0L : this.timings.get(this.timings.size() - 1);
}
public boolean isRunCompleted()
{
return this.runCompleted;
}
public ArrayList<String> getTimings()
{
ArrayList <String> list_of_timings = new ArrayList<String>();
for(long timing : this.timings)
{
list_of_timings.add(getTimeString(timing));
}
return list_of_timings;
}
public String displayLapTimings() {
StringBuilder sb = new StringBuilder();
int count = 1;
for (long timing : this.timings) {
sb.append("Lap " + count + ":" + getTimeString(timing));
sb.append("\n");
count++;
}
return sb.toString();
}
//Mutator Methods
public void addTiming(long timing) {
this.timings.add(timing);
}
public void setPrevTime(long prevTime) {
this.prevTime = prevTime;
}
public void setRunCompleted()
{
this.runCompleted = true;
}
//Other Methods
private String getTimeString(long timing) {
long second = (timing / 1000) % 60;
long minute = (timing / (1000 * 60)) % 60;
long hour = (timing / (1000 * 60 * 60)) % 24;
String timeStr = String.format("%02d:%02d:%02d", hour, minute, second);
return timeStr;
}
}
DbConnect.java
package napfa_running_reader;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author pc
*/
import java.sql.PreparedStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class DbConnect {
private Connection conn = null;
private String driver = "com.mysql.jdbc.Driver";
private String url = "jdbc:mysql://localhost:3306/napfa_test_system";
private void openConn()
{
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, "root", "");
} catch (Exception e)
{
System.out.println(e.getMessage());
}
}
private void closeConn()
{
try {
conn.close();
} catch (Exception e)
{
System.out.println(e.getMessage());
}
}
public String getBidNo(String tagID)
{
String bidNo = "";
try{
openConn();
String query = "SELECT bid_number from bid_number_rfid_info_table WHERE rfid_number = ?";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, tagID);
ResultSet rs = stmt.executeQuery();
rs.next();
bidNo = rs.getString("bid_number");
closeConn();
} catch(Exception e) {
System.out.println(e.getMessage());
}
return bidNo;
}
public void updateLapTimings(Tag tagItem, String tagID)
{
try {
openConn();
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date();
String today = dateFormat.format(date);
ArrayList<String> list_of_timings = tagItem.getTimings();
String query = "UPDATE napfa_running_result_info_table SET lap1_time = ?, lap2_time = ?, lap3_time = ?, " +
"lap4_time = ?, lap5_time = ?, lap6_time = ?, rfid_number = ? WHERE created_date = ? AND bid_number = ?";
PreparedStatement stmt = conn.prepareStatement(query);
//Update Lap Timings
stmt.setString(1, list_of_timings.get(0));
stmt.setString(2, list_of_timings.get(1));
stmt.setString(3, list_of_timings.get(2));
stmt.setString(4, list_of_timings.get(3));
stmt.setString(5, list_of_timings.get(4));
stmt.setString(6, list_of_timings.get(5));
//Update rfid_number, created_date, bid_number
stmt.setString(7, tagID);
stmt.setString(8, today);
stmt.setString(9, getBidNo(tagID));
stmt.executeUpdate(query);
closeConn();
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
}