java 将数组列表添加到 Jlist

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11572051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 05:37:34  来源:igfitidea点击:

Adding arraylist to Jlist

javaswinguser-interfacejlistserversocket

提问by DrWooolie

I have an arraylist in my metod receiveArrayLists which i want to add to a JList. How can i do this?

我的方法 receiveArrayLists 中有一个数组列表,我想将其添加到 JList 中。我怎样才能做到这一点?

import java.awt.Dimension;
import java.awt.Scrollbar;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class GUI implements Runnable {

private Server server;
private JFrame frame = new JFrame();
private JTextField jtf = new JTextField();
private JList jl = new JList();
private JTextArea jl1 = new JTextArea();
private JScrollPane pane = new JScrollPane(jl);
private Socket socket;
private DataInputStream dis;
private ObjectInputStream ois = null;
private DataOutputStream dos;

public GUI() {

    socket = new Socket();
    InetSocketAddress ipPort = new InetSocketAddress("127.0.0.1", 4444);
    try {
        socket.connect(ipPort);
        dis = new DataInputStream(socket.getInputStream());
        dos = new DataOutputStream(socket.getOutputStream());
    } catch (Exception e) {
    }
    new Thread(this).start();


    frame.getContentPane().setLayout(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setBounds(50, 300, 420, 400);
    frame.setResizable(false);
    frame.setVisible(true);
    pane.add(jl);
    pane.add(jl1);
    jl1.setEditable(false);
    jtf.setBounds(50, 40, 150, 40);
    jl.setBounds(50, 90, 150, 200);
    jl1.setBounds(210, 90, 150, 200);


    jtf.addKeyListener(new KeyListener() {

        public void keyTyped(KeyEvent e) {
        }

        public void keyPressed(KeyEvent e) {
        }

        public void keyReleased(KeyEvent e) {
            if (dos != null) {
                if(jtf.getText().length() >0){
                try {
                    dos.writeUTF(jtf.getText());
                } catch (IOException ex) {
                    Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
                }
                }else{
                    jl1.setText("");
                }
            }

        }
    });
    frame.add(jtf);
    frame.add(jl);
    frame.add(jl1);

    frame.add(pane);
}

public void run() {
    String fromServer;
    try {
        while ((fromServer = dis.readUTF()) != null) {
            if (fromServer.equals("read")) {
                receiveArrayList();
            }
        }
    } catch (Exception e) {

    }
}

Here is my metod, as you can see, i try to use append which obviously wont work to add an arraylist to a JList

这是我的方法,如您所见,我尝试使用 append 显然无法将数组列表添加到 JList

public void receiveArrayList() {

    try {
        jl1.setText("");
        ois = new ObjectInputStream(socket.getInputStream());
        @SuppressWarnings("unchecked")
        ArrayList<String> a = (ArrayList<String>) (ois.readObject());
        for (int i = 0; i < a.size(); i++) {
            jl.append(a.get(i) + " \n");
        }
        dis = new DataInputStream(socket.getInputStream());
    } catch (ClassNotFoundException ex) {
        System.out.println(ex);
    } catch (IOException ex) {
        System.out.println(ex);
    }
}

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

}
}

回答by Hovercraft Full Of Eels

The simplest is to create a DefaultListModel object, iterate through the ArrayList in a for or foreach loop and add the items to the model via its addElement(...)method. Then set the JList's model to your model.

最简单的方法是创建一个 DefaultListModel 对象,在 for 或 foreach 循环中遍历 ArrayList 并通过其addElement(...)方法将项目添加到模型中。然后将 JList 的模型设置为您的模型。

More involved but satisfying is to create your own ListModel by extending AbstractListModel using your ArrayList as the model's nucleus.

更多涉及但令人满意的是通过使用您的 ArrayList 作为模型的核心扩展 AbstractListModel 来创建您自己的 ListModel。

回答by MadProgrammer

You need to make use the JList's list model. The simplest solution is to use DefaultListModel, but you could investigate implementation your own (based on the AbstractListModel)

您需要使用 JList 的列表模型。最简单的解决方案是使用DefaultListModel,但您可以调查自己的实现(基于AbstractListModel

If you don't want to keep any previous content when you receive the array list you could do the following:

如果您在收到数组列表时不想保留任何以前的内容,您可以执行以下操作:

public void receiveArrayList() {

    try {

        DefaultListModel model = new DefaultListModel();
        jl1.setText("");
        ois = new ObjectInputStream(socket.getInputStream());
        @SuppressWarnings("unchecked")
        ArrayList<String> a = (ArrayList<String>) (ois.readObject());
        for (int i = 0; i < a.size(); i++) {
            model.addElement(a.get(i)); // <-- Add item to model
        }
        dis = new DataInputStream(socket.getInputStream());

        jl.setModel(model); // <-- Set the model to make it visible

    } catch (ClassNotFoundException ex) {
        System.out.println(ex);
    } catch (IOException ex) {
        System.out.println(ex);
    }
}

If you want to keep the previous list, then you need to ensure that the original model is a DefaultListModel(in this example) or is compatible with the ListModelyou are using.

如果您想保留之前的列表,那么您需要确保原始模型是DefaultListModel(在本例中)或与ListModel您正在使用的兼容。

Basically, then you want to cast the model:

基本上,然后你想投射模型:

You may want to check out this tutorialfor more info. DefaultListModel model = jl.getModel();

您可能想查看本教程以获取更多信息。DefaultListModel 模型 = jl.getModel();

Obviously, you won't need to reapply it at the end ;)

显然,您不需要在最后重新应用它;)