调用函数JComboBox

时间:2015-04-18 03:45:37

标签: java swing serial-port jcombobox swingworker

我正在尝试使用JComboBox来收集蓝牙地址。

我已将JComboBox添加到GUI.java,但无法使其与Receiver.java文件一起使用,该文件具有检测蓝牙地址的代码。

如何将Reciever.java中检测到的蓝牙地址移至GUI.java并显示在JComboBox

我已使用此消息附加了这两个文件。

GUI.java

public class GUI {

    private JFrame f = new JFrame("Bluetooth Software v1.0");// added by me 
    private JPanel northPanel = new JPanel();
    private JPanel centerPanel = new JPanel();
    private JPanel southPanel = new JPanel();
    private JScrollPane statusScrollPane;
    private JTextArea statusTextArea;
    private JButton connectButton; 
    private JButton exitButton;
    private JButton simplekeyOnButton;
    private JButton simplekeyOffButton;
    private JComboBox comPortBox;
    private JComboBox blue_name;// added by me
    private JButton Read;

    ConnectionManager cm;
    GUI gui;
    Timer timer;

    public GUI(){
        System.out.println("I am in GUI Function\n");
        timer = new Timer();

        this.gui = this;

        this.connectButton = new JButton("Connect");
        this.exitButton = new JButton("Exit");
        this.simplekeyOnButton = new JButton("Button1");
        this.simplekeyOnButton.setEnabled(false);
        this.simplekeyOffButton = new JButton("Button2");
        this.simplekeyOffButton.setEnabled(false);
        this.statusScrollPane = new JScrollPane();
        this.statusTextArea = new JTextArea();
        this.comPortBox = new JComboBox();
        this.comPortBox.setModel(new DefaultComboBoxModel(new ListAvailablePorts().getPortArray()));

        this.blue_name = new JComboBox();// added by me

    //  this.blue_name.setModel(new DefaultComboBoxModel(new Receiver));// added by me

        this.northPanel.add(this.comPortBox);
        this.northPanel.add(this.blue_name);// added by me
        this.northPanel.add(this.connectButton);
        this.northPanel.add(this.exitButton);
        this.centerPanel.add(this.simplekeyOnButton);
        this.centerPanel.add(this.simplekeyOffButton);

        this.statusTextArea.setColumns(40);
        this.statusTextArea.setEditable(false);
        this.statusTextArea.setRows(10);
        this.statusScrollPane.setViewportView(this.statusTextArea);
        this.southPanel.add(this.statusScrollPane);

        this.connectButton.addActionListener(new connectButtonListener());
        this.exitButton.addActionListener(new exitButtonListener());
        this.simplekeyOnButton.addActionListener(new simplekeyOnButtonListener());
        this.simplekeyOffButton.addActionListener(new simplekeyOffButtonListener());

        this.f.getContentPane().setLayout(new BorderLayout());
        this.f.getContentPane().add(northPanel,BorderLayout.NORTH);
        this.f.getContentPane().add(centerPanel,BorderLayout.CENTER);
        this.f.getContentPane().add(southPanel,BorderLayout.SOUTH);
        this.f.addWindowListener(new ListenCloseWdw());
        this.f.setLocationRelativeTo(null);

    }

    private class ConnectTask extends TimerTask{

        public ConnectTask(){

        }

        @Override
        public void run() {
            statusTextArea.append("Error connecting to the device.\n" +
                    "Remove and insert again the USB dongle from the USB slot, restart the\n" +
                    " application and try again.");
        }
    }

    private class connectButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent arg0) {

            new SwingWorker<Void,String>(){

                protected Void doInBackground() throws Exception{

                    timer.schedule(new ConnectTask(),15000);

                    String portName = (String)comPortBox.getSelectedItem();
                    connectButton.setEnabled(false);
                    cm = new ConnectionManager(gui,portName);
                    cm.initializeDevice();

                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    if(cm == null){
                        statusTextArea.setText("Error, not connected");
                        return null;
                    }
                    cm.deviceDiscoveryReq();

                    return null;
                }

                public void done(){ 

                }

            }.execute();
        }
    };

    public class ListenCloseWdw extends WindowAdapter{
        public void windowClosing(WindowEvent e){
            System.exit(0);         
        }
    }

    private class simplekeyOnButtonListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent arg0) {

            new SwingWorker<Void,Void>(){

                @Override
                protected Void doInBackground() throws Exception {
                    statusTextArea.append("Key Notifications ON: ");
                    setEnabled(false);


                    if(cm == null){
                        statusTextArea.append("Not connected.\n");
                        return null;
                    }

                    cm.simpleKeysEnabler();

                    return null;
                }

                public void done(){
                    setEnabled(true);
                }

            }.execute();
        }
    }

    private class simplekeyOffButtonListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent arg0) {

            new SwingWorker<Void,Void>(){

                @Override
                protected Void doInBackground() throws Exception {
                    statusTextArea.append("Key Notifications OFF: ");
                    setEnabled(false);

                    if(cm == null){
                        statusTextArea.append("Not connected.\n");
                        return null;
                    }

                    cm.simpleKeysDisabler();

                    return null;
                }

                public void done(){
                    setEnabled(true);
//                  cm.stopDataStreamWriter();
                }
            }.execute();
        }
    }

    public void addressFound(){ // this is declaration 
        this.timer.cancel();
        this.statusTextArea.append("Device found\n");
        System.out.println("Device found\n");

        this.cm.establishLink();
    }

    public void isEstablished(boolean isEstablished){

        if(isEstablished){
            this.statusTextArea.append("Enabling Key Notifications start: \n");
            this.cm.simpleKeysEnabler();
            this.statusTextArea.append("Enabling Key Notifications end: \n");
        }
    }

    private class exitButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent arg0) {
            if(cm != null){
                new SwingWorker<Void,Void>(){
                    @Override
                    protected Void doInBackground() throws Exception {
                        cm.simpleKeysDisabler();
                        return null;
                    }

                    public void done(){
                        cm.terminateLink();
                    }

                }.execute();
            }
        }
    };

    public void appendText(boolean success){
        if(success){
            this.statusTextArea.append("Success\n");
            setEnabled(true);
        }
    }

    public void quitApplication(){
        System.exit(0);
    }

    public void launchFrame(){
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack(); //Adjusts panel to components for display
        f.setVisible(true);
    }

    public static void main(String[] args){
        GUI gui = new GUI();
        System.out.println("I am in main function \n");
        gui.launchFrame();
    }

    private void setEnabled(boolean enabled){
        connectButton.setEnabled(enabled);
        exitButton.setEnabled(enabled);
        simplekeyOnButton.setEnabled(enabled);
        simplekeyOffButton.setEnabled(enabled);
    }   
}

Receiver.java

public class Receiver implements Runnable {

    private SerialPort serialPort;
    private SerialPortConnection serialPortConnection;
    private ConnectionManager cm;
    private SerialReader reader;
    private boolean dataArrived = false;
    private int[] inputBuffer;
    private boolean go = true;
    private boolean addressFound = false;
    private boolean isStopped = false;

    ArrayList<String> blue_address = new ArrayList<String>();

    public Receiver(SerialPortConnection serialPortConnection, ConnectionManager cm)
    {
        this.serialPortConnection = serialPortConnection;
        this.serialPort = this.serialPortConnection.getSerialPort();
        this.cm = cm;
        this.cm.setReceiver(this);
    }

    public SerialPort getSerialPort(){
        return this.serialPort;
    }

    public void setReader(SerialReader reader){
        this.reader = reader;
    }


    public SerialReader getReader(){
        return this.reader;
    }

    /**
     * This method is called by the underlying SerialReader. If the given boolean is true, this method calls 
     * notiftAll() to wake up the current thread.
     * @param dataArrived boolean indicating whether data ha arrived.
     */
    public synchronized void notifyDataArrivedDataArrived(boolean dataArrived){
        this.dataArrived = dataArrived;
        if(dataArrived){
            notifyAll();
        }
    }
    /**
     * This method is called by the underlying receiver process to set the inputbuffer with received data.
     * @param dataList ArrayList holding received bytes.
     */
    public void setInputBuffer(ArrayList<Integer> dataList){

        int[] tmpInputBuffer = new int[dataList.size()];
        for(int i = 0; i<tmpInputBuffer.length; i++){
            tmpInputBuffer[i] = dataList.get(i);
        }
        this.inputBuffer = tmpInputBuffer;
    }

    public int[] getInputBuffer(){
        return this.inputBuffer;
    }

    @Override
    public synchronized void run() {

        SerialReader serialReader = new SerialReader(this.serialPort,this); 
        new Thread(serialReader).start();

        while(go){

            if(!this.dataArrived){
                try {
                    System.out.println("I am in while(go)\n");
                    this.wait();
                } 

                catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // if the program has been stopped by the user:
            if(!go){
                break;
            }
            System.out.println("Receiver - interrupted");
            processInputBuffer(getInputBuffer());

            // Finished processing the data: 
            this.dataArrived = false;
        }
    }

    private boolean handleInput(int[] buffer){

        if(buffer.length<3){
            return false;
        }

        int lengthOfPacket = buffer[2];

        if(buffer.length!= lengthOfPacket+3){

            int newPacketIndex = -1;

            for(int i = 2; i < buffer.length-1; i++){

                if(buffer[i] == 0x04 && buffer[i+1] == 0xff ){
                    //found new packet
                    newPacketIndex = i;
                    break;
                }
            }

            if(newPacketIndex != -1){

                int[] firstPacket = new int[newPacketIndex];
                int[] secondPacket = new int[buffer.length-newPacketIndex];


                for(int i = 0; i < newPacketIndex; i++){

                    firstPacket[i] = buffer[i];
                }
                for(int i = newPacketIndex; i < buffer.length; i++){

                    secondPacket[i-newPacketIndex] = buffer[i];

                }
//              System.out.println("Process the first packet. Length: "+firstPacket.length);
                processInputBuffer(firstPacket);
//              System.out.println("And the second... Length: "+secondPacket.length);
                processInputBuffer(secondPacket);
                return true;
            }
            else{
                System.out.println("SOP not found");
            }
        }

        return false;
    }

    private void processInputBuffer(int[] buffer)
    {
        Enumeration<CommPortIdentifier> blue_address = CommPortIdentifier.getPortIdentifiers();
        //Search for multiple messages on one "line"

        if(handleInput(buffer))
        {
            //If found. Stop processing. The splitting method
            //will initiate processing of each message separately

            return;
        }
        System.out.println("I am in process Input buffer and I am about to call printInput \n");
        printInput(buffer);

        if(Arrays.equals(buffer, Constants.terminateResponse)){
            this.cm.linkTerminated();
        }

            if(addressFound )
                {
                System.out.println("I am in address found, Receiver.java \n");
                if(Arrays.equals(buffer, Constants.writeAttributeResponse)){
                    return;
                }

                else if(Arrays.equals(buffer, Constants.establishResponse)){
                    System.out.println("establish success.");
                    this.cm.isEstablished(true);
                    return;
                }

                else if(Arrays.equals(buffer, Constants.terminateResponse)){
                    this.cm.isEstablished(false);
                    return;
                }

                else if(Arrays.equals(buffer, Constants.writeAttributeSuccess)){
                    if(isStopped){
                        isStopped = false;
                        return;
                    }
                    else{
                        this.cm.writeSuccess(true);
                    }
                }
            }
            else{

                if(buffer.length<3) return;

                //If buffer contains Write Attribute responses

                if(Arrays.equals(buffer, Constants.writeAttributeResponse)){
                    return;
                }

                if(Constants.addressMessageFound(buffer))

                {
                    int[] addressBuffer = new int[6];
                    addressFound = true;
                    System.out.println("Receiver - Address found!");
                    for(int i = 0; i < addressBuffer.length; i++)
                    {
                        addressBuffer[i] = buffer[9+i];
                        System.out.print(Integer.toHexString(addressBuffer[i])+" \n");
                    }
                    /*addressBuffer[0] = 160; //A0
                    addressBuffer[1] = 195;
                    addressBuffer[2] = 215;
                    addressBuffer[3] = 8;
                    addressBuffer[4] = 3;
                    addressBuffer[5] = 96;*/

                    addressBuffer[0] = 88;//58
                    addressBuffer[1] =118;
                    addressBuffer[2] = 109;
                    addressBuffer[3] = 76;
                    addressBuffer[4] = 153;
                    addressBuffer[5] = 180;
                    Constants.setAddress(addressBuffer);
                    this.cm.setAddressBuffer(addressBuffer);
                }
            }
    }       

    public void setIsStopped(boolean isStopped)
    {
        this.isStopped = isStopped;
    }

    private void printInput(int[]inputBuffer){
        String input = "";
        for(int i = 0; i < inputBuffer.length-1; i++){
            input+= Integer.toHexString(inputBuffer[i])+" ";
        //  System.out.println("I am in Receiver printInput: \n" + input);
        }
        input += Integer.toHexString(inputBuffer[inputBuffer.length-1]);
        System.out.println("I am in Receiver");
        System.out.println("RX: \n"+input);         
    }

    public void isAddressFound(boolean addressFound){
        this.addressFound = addressFound;
    }    
}

0 个答案:

没有答案