user1106130
user1106130

Reputation: 301

Java ComboBox Association with arraylist

Please help me on the following code guys, I am trying to return arraylist elements(searched ports) from a method in class SearchPort. This would then be used in the corresponding class Communication, where the method returnArray() would be called to extract strings to be used for Jcombox options. But how do I go about doing it? Please help.

public class SearchPort {

    CommPortIdentifier portIdentifier;

    ArrayList <String> portFound ;

    public void listPorts() {
        portFound = new ArrayList();
        //Enumeration holds all port objects
        Enumeration<CommPortIdentifier> portEnum = CommPortIdentifier.getPortIdentifiers();
        while ( portEnum.hasMoreElements() ) //while Enumeration contains more port objects 
        {
            portIdentifier = portEnum.nextElement(); //switches through each port
            portFound.add(portIdentifier.getName());           
        } 
     }

     public String returnArray(){

          listPorts();
          for(int i = 0; i < portFound.size(); i++){
              System.out.println(portFound.get(i));

          }
          return portFound;
      }    

  public static void main(String[] args){
      SearchPort run = new SearchPort();
      run.listPorts();
  }

}

public class Communication {

JLabel jLabel1;
JPanel jPanel1;
    JComboBox Connections;

    public Communication() {
        JFrame commFrame = new JFrame("gec");
        commFrame.pack();
        commFrame.setVisible(true);
        commFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    commFrame.setSize(300,300); 

    jLabel1 = new JLabel();
    jPanel1 = new JPanel();

    jLabel1.setText("GEC");
        Font font = new Font("Calibri", Font.BOLD, 14);
        SearchPort port = new SearchPort();
        String [] portStrings = { port.returnArray()}; //add found ports into array
        Connections = new JComboBox(portStrings); 
        Connections.addItemListener(null);
    jLabel1.setFont(font);
    jPanel1.add(jLabel1, BorderLayout.EAST);
        jPanel1.add(Connections, BorderLayout.CENTER);        
       /*Add Contents to the Frame*/ 
        commFrame.add(jPanel1); 
    }

    public static void main(String args[]) {       
        Communication GUI = new Communication();            
    }

}//end class

Upvotes: 0

Views: 1954

Answers (1)

mKorbel
mKorbel

Reputation: 109813

1) you have three choices how to add Items to the JCombobox, by implement

2) all updates to the already visible Swing GUI must be done on Event Dispatch Thread

3) initialization for Swing GUI main method would be from Event Dispatch Thread

4) methods

commFrame.pack();
commFrame.setVisible(true);

should be last code lines in the Communication class

Upvotes: 1

Related Questions