繁体   English   中英

JList未显示在jframe中

[英]JList not showing in jframe

我在聊天客户端上工作(我没有成功)。 我正在制作一个在线名单,但不会显示。 下面是代码

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

/**
 * A simple Swing-based client for the chat server.  Graphically
 * it is a frame with a text field for entering messages and a
 * textarea to see the whole dialog.
 *
 * The client follows the Chat Protocol which is as follows.
 * When the server sends "SUBMITNAME" the client replies with the
 * desired screen name.  The server will keep sending "SUBMITNAME"
 * requests as long as the client submits screen names that are
 * already in use.  When the server sends a line beginning
 * with "NAMEACCEPTED" the client is now allowed to start
 * sending the server arbitrary strings to be broadcast to all
 * chatters connected to the server.  When the server sends a
 * line beginning with "MESSAGE " then all characters following
 * this string should be displayed in its message area.
 */
public class ChatClient {
    List<String> names = new ArrayList<String>();
    BufferedReader in;
    PrintWriter out;
    JFrame frame = new JFrame("Chatter");

    JTextArea messageArea = new JTextArea(8, 40);
JTextField textField = new JTextField(40);
JList listDisplay = new JList();

/**
 * Constructs the client by laying out the GUI and registering a
 * listener with the textfield so that pressing Return in the
 * listener sends the textfield contents to the server.  Note
 * however that the textfield is initially NOT editable, and
 * only becomes editable AFTER the client receives the NAMEACCEPTED
 * message from the server.
 */
public ChatClient() {

    // Layout GUI
    names.add("Online People");
    listDisplay.equals(names);

    textField.setEditable(false);
    messageArea.setEditable(false);
    frame.getContentPane().add(listDisplay, "East");
    frame.getContentPane().add(textField, "South");
    frame.getContentPane().add(new JScrollPane(messageArea), "North");

    frame.pack();
    // Add Listeners
    textField.addActionListener(new ActionListener() {
        /**
         * Responds to pressing the enter key in the textfield by sending
         * the contents of the text field to the server.    Then clear
         * the text area in preparation for the next message.
         */
        public void actionPerformed(ActionEvent e) {
            out.println(textField.getText());
            textField.setText("");
        }
    });
}

/**
 * Prompt for and return the address of the server.
 */
private String getServerAddress() {
    return JOptionPane.showInputDialog(
        frame,
        "Enter IP Address of the Server:",
        "Welcome to the Chatter",
        JOptionPane.QUESTION_MESSAGE);
}

/**
 * Prompt for and return the desired screen name.
 */
String getName() {
    String name = JOptionPane.showInputDialog(
            frame,
            "Choose a screen name:",
            "Screen name selection",
            JOptionPane.PLAIN_MESSAGE);
    return name;
}

/**
 * Connects to the server then enters the processing loop.
 */
private void run() throws IOException {

    // Make connection and initialize streams
    String serverAddress = getServerAddress();
    @SuppressWarnings("resource")
    Socket socket = new Socket(serverAddress, 25565);
    in = new BufferedReader(new InputStreamReader(
        socket.getInputStream()));
    out = new PrintWriter(socket.getOutputStream(), true);
    String name = getName();

    // Process all messages from server, according to the protocol.
    while (true) {
        String line = in.readLine();
        if (line.startsWith("SUBMITNAME")) {

            out.println(name);
        } else if (line.equals("NAMEACCEPTED " + name)){
            textField.setEditable(true);
            names.add(name);
            listDisplay.equals(names);
        }

        else if (line.startsWith("NAMEACCEPTED ")) {
            line.replaceAll("NAMEACCEPTED ", "");
            names.add(name);
            listDisplay.equals(names);
        } 

        else if (line.startsWith("MESSAGE")) {
            messageArea.append(line.substring(8) + "\n");
                 messageArea.setCaretPosition(messageArea.getDocument().getLength());
        } else if (line.startsWith("KICK " + name) ){
            JOptionPane.showMessageDialog(null, "YOU HAVE BEEN KICKED \nRestart the program to join again", "KICK", JOptionPane.WARNING_MESSAGE);
            textField.setEditable(false);
        } else if (line.startsWith("SILENT")){
            textField.setEditable(false);
        }
    }

}

/**
 * Runs the client as an application with a closeable frame.
 */
public static void main(String[] args) throws Exception {
    ChatClient client = new ChatClient();
    client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    client.frame.setVisible(true);
    client.run();
}
}

该守则仍然需要工作。 有谁知道为什么它的列表没有出现?

names.add("Online People");
listDisplay.equals(names);

上面的代码什么都不做。 您将字符串添加到列表。 但是您永远不要将List的内容添加到JList equals(..)方法用于比较对象,以查看一个对象是否等于另一个对象。

当您添加到JList您将数据添加到ListModel中的JList 最简单的方法是创建DefaultListModel并将模型添加到JList。 然后,您可以将数据直接添加到模型中(不需要List ):

DefaultListModel model = new DefaultListModel();
model.addElement("Online People");
JList list = new JList( model );

然后,在添加新人员时,只需在DefaultListModel上调用addElement(...)方法。

阅读Swing教程中有关如何使用列表的部分,了解一个有效的示例。 ListDemo的“雇用”按钮显示了如何添加项目。 还要注意教程中的示例如何将JList to a添加JList to a JScrollPane`,以便在添加更多用户时出现滚动条。

frame.getContentPane().add(listDisplay, "East");

不要使用魔术变量。 人们不知道“东方”是什么意思。 该API将具有可用作约束的变量。 例如:

frame.getContentPane().add(listDisplay, BorderLayout.EAST);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM