简体   繁体   English

ActionListener调用while循环方法

[英]ActionListener invoke while loop method

I add a ActionListener which create a new chat JFrame that can send and receive message from the Server. 我添加了一个ActionListener,它创建了一个新的聊天JFrame,可以从服务器发送和接收消息。 this is the code in the ActionPerformed() method 这是ActionPerformed()方法中的代码

BananaChat chat = new BananaChat(name, password, IP, port, status);
    try {
        chat.chatting();
    } catch (Exception e) {
        showInfo("fail");
    }

so it create a new chat frame, if I didn't invoke the chat.chatting() method, I can send the message to Server normally, But cannot receive the message from server. 因此它创建了一个新的聊天框架,如果我不调用chat.chatting()方法,则可以正常地将消息发送到Server,但是无法从服务器接收消息。 So I have to invoke this method because I need to keeping listening the message from server if it does send the message. 因此,我必须调用此方法,因为如果它确实发送了消息,则需要继续监听来自服务器的消息。

here is the code of chatting() 这是chatting()的代码

String line = null;

    try {
        while ((line = in.readLine()) != null) {
            if (line.equals("your user name is already registered") || line.equals("user name doesn't exist") || line.equals("wrong password")) {
                showMessage(line);
                break;
            }

            showMessage(line);
        }

    } catch (IOException e) {
        showMessage("can not receive the message");
    }

It is the while loop. 这是while循环。 If I create my chat frame and invoke this method in the main method, it can work, but if I create the chat frame in ActionListener, it is stuck. 如果创建我的聊天框架并在main方法中调用此方法,则它可以工作,但是如果我在ActionListener中创建该聊天框架,则它会卡住。 it seems that the ActionListener cannot have a while Loop which doesn't end at all. 看来ActionListener不能有一个while循环,它根本不会结束。

I don't know how to solve it, is there a better way to create a new chat interface from the login interface? 我不知道如何解决,是否有更好的方法通过登录界面创建新的聊天界面?

As already suggested by kiheru , it is probably a good idea to run your chatting code in a background thread - for example using a SwingWorker (which is made especially for use with Swing GUIs). 正如kiheru所建议的那样 ,在后台线程中运行您的聊天代码可能是一个好主意-例如,使用SwingWorker (专门用于Swing GUI)。 With some guess work regarding the BananaChat class, a very simple (one directional) chat program could look like this: 在对BananaChat类进行一些猜测BananaChat ,一个非常简单的(单向)聊天程序可能如下所示:

A main class: 主类:

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;

public class Chat {
    private int nextPort = 80;

    public static void main(final String[] args) {
        new Chat().launchGui();
    }

    private void launchGui() {
        final JFrame frame = new JFrame("Stack Overflow: chat with multiple servers");
        frame.setBounds(100, 100, 800, 600);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        final JPanel panel = new JPanel();
        final JButton startChatButton = new JButton("Start a new chat");
        startChatButton.addActionListener(actionEvent -> {
            final BananaChat bananaChat = new BananaChat("user name", "password",
                "192.0.0.1", String.valueOf(nextPort), "???");
            nextPort++;
            bananaChat.startChatting();
        });
        panel.add(startChatButton);
        frame.getContentPane().add(panel);
        frame.setVisible(true);
    }
}

A BananaChat class: BananaChat类:

import java.util.List;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;

public class BananaChat extends JFrame {
    private final String userName;
    private final String password;
    private final String IP;
    private final String port;
    private final String status;
    private final Random dummyServerMessages;
    private final JTextArea messagesTextArea;

    public BananaChat(final String userName, final String password, final String IP,
                      final String port, final String status) {
        super("Chat with " + IP + ":" + port);
        this.userName = userName;
        this.password = password;
        this.IP = IP;
        this.port = port;
        this.status = status;
        dummyServerMessages = new Random(123456);
        messagesTextArea = new JTextArea();
        add(new JScrollPane(messagesTextArea));
        setBounds(1000, 100, 400, 200);
        setVisible(true);
    }

    public void startChatting() {
        final SwingWorker chatWorker = new SwingWorker<Void, String>() {
            @Override
            protected Void doInBackground() {
                while (!isCancelled()) {
                    final String message = getMessageFromServer();
                    publish(message + "\n");
                    pause(1000);
                }
                return null;
            }

            @Override
            protected void process(final List<String> messages) {
                messages.forEach(messagesTextArea::append);
            }
        };

        chatWorker.execute();
    }

    // Generate silly random messages. Can be replaced by a call to in.readLine().
    private String getMessageFromServer() {
        final String message;
        if (dummyServerMessages.nextInt(6) < 2)
            message = "Hello";
        else
            message = "Silence";
        return message + " from " + userName + "@" + IP + ":" + port;
    }

    private void pause(final int milliseconds) {
        try {
            Thread.sleep(milliseconds);
        } catch (final InterruptedException e) {
            e.printStackTrace();
        }
    }

    public String getPassword() {
        return password;
    }

    public String getStatus() {
        return status;
    }
}

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

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