我的方法接收数组列表中有一个数组列表,我想将它添加到 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) {
}
}
这是我的方法,如您所见,我尝试使用 append 显然无法将 arraylist 添加到 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();
}
}