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

查看:27
本文介绍了如何从 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,而不是更新现有的.

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天全站免登陆