请帮助我以下代码,我试图从类SearchPort
中的方法返回arraylist元素(搜索端口)。然后,这将在相应的类Communication中使用,其中将调用方法returnArray()
以提取要用于Jcombox
选项的字符串。但是我该怎么做呢?请帮忙。
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
答案 0 :(得分:1)
1)您有三种选择如何通过工具
将项目添加到JCombobox 上完成对已经可见的Swing GUI的所有更新3)Swing GUI main方法的初始化将来自Event Dispatch Thread
4)方法
commFrame.pack();
commFrame.setVisible(true);
应该是Communication class