Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
尝试连接到串行端口时使用javax.swing.SwingWorker时出现问题_Java_Swing_User Interface_Serial Port_Xbee - Fatal编程技术网

尝试连接到串行端口时使用javax.swing.SwingWorker时出现问题

尝试连接到串行端口时使用javax.swing.SwingWorker时出现问题,java,swing,user-interface,serial-port,xbee,Java,Swing,User Interface,Serial Port,Xbee,我正在用Java开发一个应用程序,将从Xbee设备接收到的数据上传到在线数据库。功能就在那里,一切正常,但在开发GUI(使用WindowsPro Builder)时,一切都会变得糟糕。问题是,应用程序需要能够检测Xbee设备,如果没有连接,则等待它连接-无限期(或直到关闭)。我已经有了一种方法,可以检测串口是否是Xbee设备;正如我所说,除了我将其与GUI集成之外,其他一切都可以工作 我遇到的问题是创建一个GUI,它首先检测Xbee设备是否已连接,如果未连接,则显示一条消息,通知用户连接设备以继

我正在用Java开发一个应用程序,将从Xbee设备接收到的数据上传到在线数据库。功能就在那里,一切正常,但在开发GUI(使用WindowsPro Builder)时,一切都会变得糟糕。问题是,应用程序需要能够检测Xbee设备,如果没有连接,则等待它连接-无限期(或直到关闭)。我已经有了一种方法,可以检测串口是否是Xbee设备;正如我所说,除了我将其与GUI集成之外,其他一切都可以工作

我遇到的问题是创建一个GUI,它首先检测Xbee设备是否已连接,如果未连接,则显示一条消息,通知用户连接设备以继续。同时(在显示消息时),我需要调用扫描串行端口的方法。我在考虑线程,但我已经有一段时间没用了。请注意,该方法在应用程序启动时已经运行过一次,以便尝试和连接。我没有代码可以显示,因为我所做的只是显示基本的框架、按钮等(还没有事件)。我是Java GUI编程新手,有什么建议吗

更新:所以我试着实现MadProgrammer的建议,我相信在SwingWorker教程中它是可行的,但什么都没有发生。唯一需要运行的是设置GUI。接下来是代码:

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import javax.swing.SwingWorker;


public class ConnectionWorker extends SwingWorker<Boolean, String> {

private ConnectionListener callBack;
private Xbee xbee = new Xbee();
private QboComm comm;

public ConnectionWorker(ConnectionListener listener, QboComm comm) {
    this.callBack = listener;
    this.comm = comm;
}


protected void process(List<String> chunks) {
    String msg = chunks.get(chunks.size() - 1);
    if (msg.equals("WAITING")) {
        comm.publishError();
    }
}

protected Boolean doInBackground() throws Exception {
    boolean isConnected = false;
    this.xbee = QboComm.xbee;
    ArrayList<String> list = new ArrayList<String>();
    if(!isConnected){
        publish("WAITING");
        while(!isConnected){
            list = xbee.getSerialPorts();
            for(String s : list){
                isConnected = xbee.connect(s);
                if(isConnected){
                    publish("DONE");
                    break;
                }
            }
        }
    }
    return isConnected;
}


protected void done() {
    boolean check;
    try {
        check = get();
        if (check) {
            comm.removeError();
            callBack.connectionEstablished();
        } else {
            callBack.connectionFailed();
        }
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
}  
}
import java.util.ArrayList;
导入java.util.List;
导入java.util.concurrent.ExecutionException;
导入javax.swing.SwingWorker;
公共类ConnectionWorker扩展SwingWorker{
私有连接侦听器回调;
私有Xbee Xbee=新Xbee();
私人QboComm通信;
公共连接工作程序(连接侦听器侦听器,QboComm comm){
this.callBack=listener;
this.comm=comm;
}
受保护的无效进程(列表块){
String msg=chunks.get(chunks.size()-1);
如果(消息等于(“等待”)){
comm.publishError();
}
}
受保护的布尔值doInBackground()引发异常{
布尔值未连接=假;
this.xbee=QboComm.xbee;
ArrayList=新建ArrayList();
如果(!未连接){
发布(“等待”);
当(!断开连接){
list=xbee.getSerialPorts();
用于(字符串s:列表){
isConnected=xbee.connect;
如果(未连接){
发布(“完成”);
打破
}
}
}
}
返回不连接;
}
受保护的void done(){
布尔检查;
试一试{
check=get();
如果(检查){
命令删除错误();
callBack.connectionEstablished();
}否则{
callBack.connectionFailed();
}
}捕获(中断异常|执行异常e){
e、 printStackTrace();
}
}  
}

导入java.awt.EventQueue;
公共类QboComm{
专用JFrame frmQboCommunicator;
公共静态Xbee Xbee=新Xbee();
私有内部框架内部框架;
私人JLabel LBL连接;
/**
*启动应用程序。
*/
公共静态void main(字符串[]args){
invokeLater(新的Runnable(){
公开募捐{
QboComm窗口=新的QboComm();
window.frmQboCommunicator.setVisible(true);
ConnectionListener回调=新建ConnectionListener(){
公共无效连接已建立(){
试一试{
ArrayList=新建ArrayList();
list=xbee.fetch();
DBConnector db=DBConnector.getConnector();
if(db.connect()){
用于(字符串s:列表){
db.upload(s.substring(0,5),s.substring(5));
}
}
db.disconnect();
xbee.printDBList();
}捕获(例外e){
e、 printStackTrace();
} 
}
公共无效连接失败(){
//实施
}
};
新建ConnectionWorker(回调,窗口).execute();
}
});
}
/**
*创建应用程序。
*/
公共QboComm(){
初始化();
}
/**
*初始化框架的内容。
*/
私有void初始化(){
frmQboCommunicator=newjframe();
frmQboCommunicator.setTitle(“Qbo通信器”);
frmQboCommunicator.getContentPane().setBackground(新颜色(165,42,42));
frmQboCommunicator.getContentPane().setForeground(新颜色(211211211211211));
frmQboCommunicator.setBounds(100100450300);
frmQboCommunicator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmQboCommunicator.getContentPane().setLayout(null);
/**
*连接错误弹出窗口
*/
this.internalFrame=new JInternalFrame(“连接错误”);
内部框架顺序(新线条边框(新颜色(153180209),3));
内框立根(103,46,227,157);
frmQboCommunicator.getContentPane().add(internalFrame);
internalFrame.getContentPane().setLayout(null);
JTextPane txtpnAQboCommunicator=新JTextPane();
txtpnAQboCommunicator.setText(“Qbo通讯器未连接。请连接Qbo通讯器以继续。”);
txtpnAQboCommunicator.setEditable(false);
txtpnAQboCommunicator.setBounds(0,0,211,128);
internalFrame.getContentPane().add(txtpnAQboCommunicator);
internalFrame.setVisible(假);
/**
*应用程序名称
*/
JLabel lblQboCommunicator=DefaultComponentFactory.getInstance().createTitle(“QBO通信器”);
lblQboCommunicator.set前台(新颜色(255、255、255));
lblQboCommunicator.setBackground(新颜色(255、255、240));
lblQboCommunicator.setHorizontalAlignment(SwingConstants.CENTER);
lblQboCommunicator.setBo
import java.awt.EventQueue;


public class QboComm {

private JFrame frmQboCommunicator;
public static Xbee xbee = new Xbee();
private JInternalFrame internalFrame;
private JLabel lblConnected;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            QboComm window = new QboComm();
            window.frmQboCommunicator.setVisible(true);
            ConnectionListener callback = new ConnectionListener() {
                public void connectionEstablished() {
                    try {
                        ArrayList<String> list = new ArrayList<String>();
                        list = xbee.fetch();
                        DBConnector db = DBConnector.getConnector();
                        if(db.connect()){
                            for(String s : list){
                                db.upload(s.substring(0, 5), s.substring(5));
                            }
                        }
                        db.disconnect();
                        xbee.printDBList();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } 
                }
                public void connectionFailed() {
                    //IMPLEMENT
                }
            };
            new ConnectionWorker(callback, window).execute();
        }
    });
}

/**
 * Create the application.
 */
public QboComm() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frmQboCommunicator = new JFrame();
    frmQboCommunicator.setTitle("Qbo Communicator");
    frmQboCommunicator.getContentPane().setBackground(new Color(165, 42, 42));
    frmQboCommunicator.getContentPane().setForeground(new Color(211, 211, 211));
    frmQboCommunicator.setBounds(100, 100, 450, 300);
    frmQboCommunicator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frmQboCommunicator.getContentPane().setLayout(null);

    /**
     * Connection Error Pop-up
     */
    this.internalFrame = new JInternalFrame("Connection Error");
    internalFrame.setBorder(new LineBorder(new Color(153, 180, 209), 3));
    internalFrame.setBounds(103, 46, 227, 157);
    frmQboCommunicator.getContentPane().add(internalFrame);
    internalFrame.getContentPane().setLayout(null);
    JTextPane txtpnAQboCommunicator = new JTextPane();
    txtpnAQboCommunicator.setText("A Qbo Communicator is not connected. Please connect a Qbo Communicator to continue.");
    txtpnAQboCommunicator.setEditable(false);
    txtpnAQboCommunicator.setBounds(0, 0, 211, 128);
    internalFrame.getContentPane().add(txtpnAQboCommunicator);
    internalFrame.setVisible(false);

    /**
     * Application Name
     */
    JLabel lblQboCommunicator = DefaultComponentFactory.getInstance().createTitle("QBO COMMUNICATOR");
    lblQboCommunicator.setForeground(new Color(255, 255, 255));
    lblQboCommunicator.setBackground(new Color(255, 255, 240));
    lblQboCommunicator.setHorizontalAlignment(SwingConstants.CENTER);
    lblQboCommunicator.setBounds(144, 0, 146, 14);
    frmQboCommunicator.getContentPane().add(lblQboCommunicator);

    /**
     * Connected label, displayed when connected to Xbee device
     */
    this.lblConnected = DefaultComponentFactory.getInstance().createLabel("CONNECTED");
    lblConnected.setForeground(new Color(255, 255, 255));
    lblConnected.setFont(new Font("Tahoma", Font.BOLD, 14));
    lblConnected.setHorizontalAlignment(SwingConstants.CENTER);
    lblConnected.setBounds(144, 25, 146, 14);
    frmQboCommunicator.getContentPane().add(lblConnected);

    /**
     * Scroll Panel that displays uploaded data
     */

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    scrollPane.setBounds(53, 65, 344, 131);
    frmQboCommunicator.getContentPane().add(scrollPane);

    JPanel panel = new JPanel();
    panel.setBorder(new LineBorder(new Color(255, 255, 255)));
    panel.setBackground(new Color(165, 42, 42));
    scrollPane.setViewportView(panel);

    /**
     * Progress Bar
     */
    JProgressBar progressBar = new JProgressBar();
    progressBar.setStringPainted(true);
    progressBar.setFont(new Font("Tahoma", Font.BOLD, 12));
    progressBar.setBackground(new Color(255, 255, 255));
    progressBar.setForeground(new Color(255, 140, 0));
    progressBar.setBounds(53, 214, 344, 25);
    frmQboCommunicator.getContentPane().add(progressBar);
}

public void publishError(){
    this.internalFrame.setVisible(true);
    this.lblConnected.setText("DISCONNECTED");
}

public void removeError(){
    this.internalFrame.setVisible(false);
    this.lblConnected.setText("CONNECTED");
}
}
public synchronized guardedJoy() {
    // This guard only loops once for each special event, which may not
    // be the event we're waiting for.
    while(!joy) {
        try {
            wait();
        } catch (InterruptedException e) {}
    }
    System.out.println("Joy and efficiency have been achieved!");
}
public synchronized notifyJoy() {
    joy = true;
    notifyAll();
}
import java.awt.EventQueue;
import java.util.List;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class WaitForSwingWorker {

    public static void main(String[] args) {
        new WaitForSwingWorker();
    }

    public WaitForSwingWorker() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                ConnectionListener callback = new ConnectionListener() {

                    @Override
                    public void connectionEstablished() {
                        // Continue running the app
                    }

                    @Override
                    public void connectionFailed() {
                        // Show error message :(
                    }
                };

                new ConnectionWorker(callback).execute();

                // Execution will continue here...

            }
        });
    }

    public interface ConnectionListener {
        public void connectionEstablished();
        // If possible, you should provide a message as to why...
        public void connectionFailed();
    }

    public class ConnectionWorker extends SwingWorker<Void, String> {

        private ConnectionListener callBack;

        public ConnectionWorker(ConnectionListener listener) {
            callBack = listener;
        }

        @Override
        protected void process(List<String> chunks) {
            // Back in the EDT...
            String msg = chunks.get(chunks.size() - 1);
            if (msg.equals("WAITING")) {
                // Show waiting for connection message...
            }
        }

        @Override
        protected Void doInBackground() throws Exception {
            // Within our own thread
            // Establish connection...
            if (!isConnected) {
                publish("WAITING");
                // Wait for incoming connection, this can block...
            }
            return null;
        }

        @Override
        protected void done() {
            // Back in the EDT
            if (isConnected) {
                // Show failed to connect message?
                callBack.connectionEstablished();
            } else {
                callBack.connectionFailed();
            }
        }

    }

}