如何从ArrayList更新JComboBox内容? [英] How to update JComboBox content from ArrayList?

查看:83
本文介绍了如何从ArrayList更新JComboBox内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有基于ArrayList的JComboBox:

I have JComboBox based on ArrayList:

private ArrayList<String> klienci = new ArrayList<String>();
private JComboBox klienciLista;

然后将其添加到构造函数中:

and I add it in constructor:

klienciLista = new JComboBox(klienci.toArray());
klienciLista.setPrototypeDisplayValue("#############################");
panel.add(klienciLista); //JPanel panel

开始时,列表为空.客户端通过套接字在线程中获取新的ArrayList:

At the start List is empty. Client gets via socket new ArrayList in thread:

public void run() {
  try {
   host = InetAddress.getLocalHost().getHostName();
   socket = new Socket(host, SERVER_PORT);
   input = new ObjectInputStream(socket.getInputStream());
   output = new ObjectOutputStream(socket.getOutputStream());
   output.writeObject(nazwa);
  } catch (IOException e) {
   System.out.println(e);
   JOptionPane.showMessageDialog(null,
     "Polaczenie sieciowe dla klienta nie moze byc utworzone");
   setVisible(false);
   dispose(); // zwolnienie zasobów graficznych
      // okno graficzne nie zostanie utworzone
   return;
  }
  try {
   while (true) {
    container = new Object[2];
    container = (Object[]) input.readObject();
    String m = (String) container[0];
    setKlienci((ArrayList<String>) container[1]);
    klienciLista = new JComboBox(klienci.toArray());
    String pom = textArea.getText();
    textArea.setText(pom + ">>> " + m + "\n");
    klienciLista.revalidate();
    panel.revalidate();
    panel.repaint();

    if (m.equals("exit")) {
     input.close();
     output.close();
     socket.close();
     setVisible(false);
     dispose();
     break;
    }
   }
  } catch (Exception e) {
   System.out.println(e);
   JOptionPane.showMessageDialog(null,
     "Polaczenie sieciowe dla klienta zostalo przerwane");
   setVisible(false);
   dispose();
  }
 }

我想做的是在我的JComboBox klienciLista中填充可用客户端的新ArrayList,但这不会发生.连接后,服务器将发送arrayList,客户端将对其进行更新,但不会更新ComboBox.为什么会这样?

What I want to do is that my JComboBox klienciLista fill with new ArrayList of available clients, but that does not happen. After connecting, the server sends arrayList and client updates it but doesn't update ComboBox. Why is this?

推荐答案

这是因为您一直在循​​环中创建一个新的JComboBox,而不是更新现有的JComboBox.

It's because you keep creating a new JComboBox in your loop, instead of updating the existing one.

代替

while(true){
...
klienciLista = new JComboBox(klienci.toArray());
...
}

这样做:

while(true){
    ...
    klienciLista.removeAllItems();
    for(String s:klienci){
        klienciLista.addItem(s);
    }
    ...
}

或者最好,使用模型:

    klienciLista.setModel(new DefaultComboBoxModel(klienci.toArray()));

这篇关于如何从ArrayList更新JComboBox内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆