2014-11-18 3 views
0

Я начал работать с графическим интерфейсом, первое, что я хотел сделать, это увидеть, какие последовательные порты активны/подключены. Это выполняется функцией listSerialPorts(). Я хотел бы поместить эту информацию в ComboBox. Но, похоже, он не знает переменную comboBox, когда я пытаюсь использовать ее в функции. Каков наилучший способ заполнения combobox из моей функции?Добавление строки в comboBox

Для combobox: я просто перетащил & опустил его. Таким образом, весь этот другой код был сгенерирован автоматически. Имеет ли значение, где я поставил функцию (до/после main)? КПП. У меня нет большого опыта работы с java.

public class gui_v1 { 

    private JFrame frame; 

    /** 
    * Launch the application. 
    */ 

    /** My input */ 
    public static String[] listSerialPorts() { 
     Enumeration ports = CommPortIdentifier.getPortIdentifiers(); 
     ArrayList portList = new ArrayList(); 
     String portArray[] = null; 
     while (ports.hasMoreElements()) { 
      CommPortIdentifier port = (CommPortIdentifier) ports.nextElement(); 
      if (port.getPortType() == CommPortIdentifier.PORT_SERIAL) { 
       portList.add(port.getName()); 
      } 
     } 
     portArray = (String[]) portList.toArray(new String[0]); 
     return portArray; 
    } 

    public static void main(String[] args) { 
     EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       try { 
        gui_v1 window = new gui_v1(); 
        window.frame.setVisible(true); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 

      } 
     }); 
    } 

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

    /** 
    * Initialize the contents of the frame. 
    */ 
    public void initialize() { 
     frame = new JFrame(); 
     frame.setBounds(100, 100, 450, 300); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.getContentPane().setLayout(null); 

     JComboBox comboBox = new JComboBox(); 
     comboBox.setBounds(36, 49, 53, 20); 
     frame.getContentPane().add(comboBox); 

    } 
} 

ответ

0

В коде вы объявляете comboBox как переменную, локальную для метода initialize(). Это делает его видимым только в методе, в котором объявлен comboBox.

Чтобы сделать переменную доступной в любом месте, вы можете объявить ее как статический член класса.

public class gui_v1 
{ 
    private JFrame frame; 
    public static JComboBox comboBox; 

    /** 
    * Launch the application. 
    */ 
    /** 
    * My input 
    */ 
    public static String[] listSerialPorts() 
    { 
     Enumeration ports = CommPortIdentifier.getPortIdentifiers(); 
     ArrayList portList = new ArrayList(); 
     String portArray[] = null; 
     while (ports.hasMoreElements()) 
     { 
      CommPortIdentifier port = (CommPortIdentifier) ports.nextElement(); 
      if (port.getPortType() == CommPortIdentifier.PORT_SERIAL) 
      { 
       portList.add(port.getName()); 
      } 
     } 
     portArray = (String[]) portList.toArray(new String[0]); 
     return portArray; 
    } 

    public static void main(String[] args) 
    { 
     EventQueue.invokeLater(new Runnable() 
     { 
      public void run() 
      { 
       try 
       { 
        gui_v1 window = new gui_v1(); 
        window.frame.setVisible(true); 
       } 
       catch (Exception e) 
       { 
        e.printStackTrace(); 
       } 

      } 
     }); 
    } 

    /** 
    * Create the application. 
    */ 
    public gui_v1() 
    { 
     initialize(); 
     //comboBox is accessible from here too 
     comboBox.setBounds(36, 49, 53, 20); 
    } 

    /** 
    * Initialize the contents of the frame. 
    */ 
    public void initialize() 
    { 
     frame = new JFrame(); 
     frame.setBounds(100, 100, 450, 300); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.getContentPane().setLayout(null); 

     //This uses a static member comboBox, initializes it with a value. 
     //See declaration of member above : public static ComboBox comboBox 
     comboBox = new JComboBox(); 

     comboBox.setBounds(36, 49, 53, 20); 
     frame.getContentPane().add(comboBox); 

    } 
} 
Смежные вопросы