Java Instant Messenger-로그인 양식에서 시작할 때 클라이언트가 올바르게 작동하지 않음

mickm

저는 현재 인스턴트 메신저 앱을 코딩하고 있습니다. 제대로 작동하는 기본 클라이언트 / 서버 설정으로 시작했습니다. 그러나 Client () classLogin.java에서 시작 하면 (Server.java를 처음 실행 한 후) JFrame이 나타나지만 완전히 비어 있습니다. 즉, 대화 패널, 사용자 텍스트 입력 필드 등과 같은 요소가 존재하지 않습니다. 이것은 서버가 클라이언트가 연결되었음을 나타내지 만 클라이언트 양식에서 아무것도 입력 / 볼 수 없기 때문에 기이합니다.

서버를 시작하고 클라이언트를 직접 연결하면 (즉, Login.java에서 시작하지 않고) 클라이언트와 서버가 모두 완벽하게 작동하고 함께 대화 할 수 있습니다.

이상하게도 서버를 실행하지 않고 Login.java에서 Client.java를 실행하면 요소가 그대로 유지 된 상태로 창이 나타납니다 (하지만 서버에 연결되어 있지 않기 때문에 분명히 사용할 수 없습니다). 또한 Server.Java를 닫으면 Client.Java가 모든 요소를 ​​표시하는 것으로 되돌아 가지만 서버 연결 없이는 다시 사용할 수 없습니다.

어떤 도움이라도 대단히 감사합니다. 감사.

로그인. 자바 :

import java.awt.*;//contains layouts, buttons etc.
import java.awt.event.*; //contains actionListener, mouseListener etc.
import javax.swing.*; //allows GUI elements

public class Login extends JFrame implements ActionListener, KeyListener {
    private JLabel usernameLabel = new JLabel("Username/Email:");
    private JLabel userPasswordLabel = new JLabel("Password:");
    public JTextField usernameField = new JTextField();
    private JPasswordField userPasswordField = new JPasswordField();
    private JLabel status = new JLabel("Status: Not yet logged in.");
    private JButton loginButton = new JButton("Login");
    private JButton registerButton = new JButton("New User");

    public Login() {
        super("Please Enter Your Login Details...");//titlebar
        setVisible(true);
        setSize(400, 250);
        this.setLocationRelativeTo(null); //places frame in center of screen
        this.setResizable(false); //disables resizing of frame
        this.setLayout(null); //allows me to manually define layout of text fields etc.
        ImageIcon icon = new ImageIcon("bin/mm.png");
        JLabel label = new JLabel(icon);
        this.add(usernameLabel);
        this.add(userPasswordLabel);
        this.add(usernameField);
        this.add(userPasswordField);
        this.add(loginButton);
        this.add(registerButton);
        this.add(status);
        this.add(label);
        label.setBounds(0, 0, 400, 70);
        usernameLabel.setBounds(30, 90, 120, 30); //(10, 60, 120, 20);
        userPasswordLabel.setBounds(30, 115, 80, 30);//(10, 85, 80, 20);
        usernameField.setBounds(150, 90, 220, 30);
        userPasswordField.setBounds(150, 115, 220, 30);
        loginButton.setBounds(150, 160, 110, 25);
        registerButton.setBounds(260, 160, 110, 25);
        status.setBounds(30, 190, 280, 30);
        status.setForeground(new Color(50, 0, 255)); //sets text colour to blue
        loginButton.addActionListener(this);
        registerButton.addActionListener(this);
        registerButton.setEnabled(false);
        userPasswordField.addKeyListener(this);
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == loginButton) {
            String userName = usernameField.getText();
            String password = userPasswordField.getText();
            if (userName.equals("mick") && password.equals("mick")) {
                status.setText("Status: Logged in.");
                this.setVisible(false);
                new Client("127.0.0.1").startRunning();
            } else {
                status.setText("Status: Password or username is incorrect.");
                status.setForeground(new Color(255, 0, 0)); //changes text colour to red
            }
        }
    }
}

Client.java :

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Date; //timestamp functionality

import javax.swing.*;

public class Client extends JFrame { //inherits from JFrame
        //1. Creating instance variables
    private JTextField userText; //where user inputs text
    private JTextArea chatWindow; //where messages are displayed
    private String fullTimeStamp = new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date());
    //fullTimeStamp - MM = months; mm = minutes; HH = 24-hour cloc
    private ObjectOutputStream output; //output from Client to Server
    private ObjectInputStream input; //messages received from Server
    private String message = "";
    private String serverIP;
    private Socket connection;

    //2. Constructor (GUI)
    public Client(String host) { //host=IP address of server
        super("Mick's Instant Messenger [CLIENT]");
        serverIP = host; //placed here to allow access to private String ServerIP
        userText = new JTextField();
        userText.setEditable(false);
        userText.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        sendMessage(event.getActionCommand()); //For this to work, must build sendData Method
                        userText.setText(""); //resets userText back to blank, after message has been sent to allow new message(s)
                    }
                }
        );
        add(userText, BorderLayout.SOUTH);
        chatWindow = new JTextArea();
        add(new JScrollPane(chatWindow), BorderLayout.CENTER); //allows you to scroll up and down when text outgrows chatWindow
        chatWindow.setLineWrap(true); //wraps lines when they outgrow the panel width
        chatWindow.setWrapStyleWord(true); //ensures that above line wrap occurs at word end
        setSize(400, 320);
        this.setLocationRelativeTo(null); //places frame in center of screen
        setVisible(true);
    }

    //3. startRunning method
    public void startRunning() {
        try {
            connectToServer(); //unlike Server, no need to wait for connections. This connects to one specific Server.
            setupStreams();
            whileChatting();
        } catch (EOFException eofException) {
            //Display timestamp for disconnection
            showMessage("\n\n" + fullTimeStamp);
            showMessage("\nConnection terminated by CLIENT! ");
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } finally {
            closeCrap();
        }
    }

    //4. Connect to Server
    void connectToServer() throws IOException {
        showMessage(" \n Attempting connection to SERVER... \n");
        connection = new Socket(InetAddress.getByName(serverIP), 6789);//Server IP can be added later
        showMessage(" Connected to: " + connection.getInetAddress().getHostName()); //displays IP Address of Server
    }

    //5. Setup streams to send and receive messages
    private void setupStreams() throws IOException {
        output = new ObjectOutputStream(connection.getOutputStream());
        output.flush();
        input = new ObjectInputStream(connection.getInputStream());
        showMessage("\n Streams are now setup! \n");
    }

    //6. While chatting method
    private void whileChatting() throws IOException {
        //Display timestamp for connection
        showMessage("\n" + fullTimeStamp);
        ableToType(true);
        String timeStamp = new java.text.SimpleDateFormat("HH:mm:ss").format(new Date());//timestamp
        do {
            try {
                message = (String) input.readObject(); //read input, treat as String, store in message variable
                showMessage("\n" + message);
            } catch (ClassNotFoundException classNotfoundException) {
                showMessage("\n I don't know that object type");
            }
            //***broken by timestamp?***    
        } while (!message.equalsIgnoreCase("SERVER " + "[" + timeStamp + "]" + ": " + "END")); //Conversation happens until Server inputs 'End'

    }

    //7. Close the streams and sockets
    private void closeCrap() {
        showMessage("\n\nClosing streams and sockets...");
        ableToType(false);//disable typing feature when closing streams and sockets
        try {
            output.close();
            input.close();
            connection.close();
        } catch (IOException ioException) {
            ioException.printStackTrace(); //show error messages or exceptions
        }
    }

    //8. Send Messages to Server
    private void sendMessage(String message) {
        try {
            String timeStamp = new java.text.SimpleDateFormat("HH:mm:ss").format(new Date());//timestamp
            output.writeObject("CLIENT" + " [" + timeStamp + "]" + ": " + message);
            output.flush();
            showMessage("\nCLIENT" + " [" + timeStamp + "]" + ": " + message);
        } catch (IOException ioexception) {
            chatWindow.append("\n Error: Message not sent!");
        }
    }

    //9.change/update chatWindow
    private void showMessage(final String m) {
        SwingUtilities.invokeLater(
                new Runnable() {
                    public void run() {
                        chatWindow.setEditable(false); //disallows text editing in chatWindow
                        chatWindow.append(m); //appends text, which was passed in from above
                    }
                }
        );
    }

    //10. Lets user type
    private void ableToType(final boolean tof) {
        SwingUtilities.invokeLater(
                new Runnable() {
                    public void run() {
                        userText.setEditable(tof); //passes in 'true'
                    }
                }
        );
    }
}
user2880020

이것을 교체

new Client("127.0.0.1").startRunning();

으로

Thread t1 = new Thread(new Runnable() {
    public void run(){
        Client client = new Client("127.0.0.1");
        client.startRunning();
    }
});  
t1.start();

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

IE의 양식 내에서 확인란 이미지 스타일이 올바르게 작동하지 않음

분류에서Dev

backbone.js에서 여러 경로가 올바르게 작동하지 않음

분류에서Dev

For 루프가 매크로 버튼에 할당되었을 때 올바르게 작동하지 않습니까?

분류에서Dev

Python Selenium : Microsoftonline 로그인이 올바르게 작동하지 않음

분류에서Dev

Java If-else 함수가 올바르게 작동하지 않음

분류에서Dev

Java If-else 함수가 올바르게 작동하지 않음

분류에서Dev

Selenium Webdriver-내부에 변수를 삽입 할 때 driver.get ()이 올바르게 작동하지 않음

분류에서Dev

양식 제출이 jquery에서 올바르게 작동하지 않습니다.

분류에서Dev

작업 표시 줄에서 최대화 할 때 Chrome이 올바르게 표시되지 않음

분류에서Dev

.select ()가 Chrome에서 올바르게 작동하지 않음

분류에서Dev

Drools가 Spring Boot에서 올바르게 작동하지 않음

분류에서Dev

사용자가 PHP에서 로그인 양식을 통해 로그인 한 후 데이터가 올바르게 표시되지 않음

분류에서Dev

기본 태그가 올바르게 작동하지 않음

분류에서Dev

Ansible : delegate_to 그룹이 올바르게 작동하지 않음

분류에서Dev

날짜 형식이 올바르게 작동하지 않음

분류에서Dev

DHCP3- 서버가 올바르게 작동하지 않음

분류에서Dev

CSS 애니메이션에서 SVG 클리핑 경로가 올바르게 작동하지 않음

분류에서Dev

PHP에서 시간을 확인할 때 정규식이 작동하지 않음

분류에서Dev

PHP에서 시간을 확인할 때 정규식이 작동하지 않음

분류에서Dev

C / C ++ 프로그램이 Raspberry Pi에서 올바르게 작동하지 않음

분류에서Dev

개체에 동적으로 메서드를 추가하는 것이 올바르게 작동하지 않음 (setattr)

분류에서Dev

www. AWS Route-53에서 S3 엔드 포인트로 올바르게 작동하지 않음

분류에서Dev

새 언어로 전환 할 때 Return 키가 올바르게 작동하지 않습니다.

분류에서Dev

Instagram에 게시 할 때 캡션이 작동하지 않음

분류에서Dev

Java에서 파일이 올바르게 작동하지 않습니다.

분류에서Dev

SQL Server에서 업데이트 할 때 문자 인코딩이 올바르게 업데이트되지 않음

분류에서Dev

SetConsoleCursorPosition이 C에서 올바르게 작동하지 않음 : 문자가 임의의 위치에 인쇄 됨

분류에서Dev

응용 프로그램이 올바르게 작동하지 않음 C #

분류에서Dev

Avro Java 직렬화가 올바르게 작동하지 않는 json으로

Related 관련 기사

  1. 1

    IE의 양식 내에서 확인란 이미지 스타일이 올바르게 작동하지 않음

  2. 2

    backbone.js에서 여러 경로가 올바르게 작동하지 않음

  3. 3

    For 루프가 매크로 버튼에 할당되었을 때 올바르게 작동하지 않습니까?

  4. 4

    Python Selenium : Microsoftonline 로그인이 올바르게 작동하지 않음

  5. 5

    Java If-else 함수가 올바르게 작동하지 않음

  6. 6

    Java If-else 함수가 올바르게 작동하지 않음

  7. 7

    Selenium Webdriver-내부에 변수를 삽입 할 때 driver.get ()이 올바르게 작동하지 않음

  8. 8

    양식 제출이 jquery에서 올바르게 작동하지 않습니다.

  9. 9

    작업 표시 줄에서 최대화 할 때 Chrome이 올바르게 표시되지 않음

  10. 10

    .select ()가 Chrome에서 올바르게 작동하지 않음

  11. 11

    Drools가 Spring Boot에서 올바르게 작동하지 않음

  12. 12

    사용자가 PHP에서 로그인 양식을 통해 로그인 한 후 데이터가 올바르게 표시되지 않음

  13. 13

    기본 태그가 올바르게 작동하지 않음

  14. 14

    Ansible : delegate_to 그룹이 올바르게 작동하지 않음

  15. 15

    날짜 형식이 올바르게 작동하지 않음

  16. 16

    DHCP3- 서버가 올바르게 작동하지 않음

  17. 17

    CSS 애니메이션에서 SVG 클리핑 경로가 올바르게 작동하지 않음

  18. 18

    PHP에서 시간을 확인할 때 정규식이 작동하지 않음

  19. 19

    PHP에서 시간을 확인할 때 정규식이 작동하지 않음

  20. 20

    C / C ++ 프로그램이 Raspberry Pi에서 올바르게 작동하지 않음

  21. 21

    개체에 동적으로 메서드를 추가하는 것이 올바르게 작동하지 않음 (setattr)

  22. 22

    www. AWS Route-53에서 S3 엔드 포인트로 올바르게 작동하지 않음

  23. 23

    새 언어로 전환 할 때 Return 키가 올바르게 작동하지 않습니다.

  24. 24

    Instagram에 게시 할 때 캡션이 작동하지 않음

  25. 25

    Java에서 파일이 올바르게 작동하지 않습니다.

  26. 26

    SQL Server에서 업데이트 할 때 문자 인코딩이 올바르게 업데이트되지 않음

  27. 27

    SetConsoleCursorPosition이 C에서 올바르게 작동하지 않음 : 문자가 임의의 위치에 인쇄 됨

  28. 28

    응용 프로그램이 올바르게 작동하지 않음 C #

  29. 29

    Avro Java 직렬화가 올바르게 작동하지 않는 json으로

뜨겁다태그

보관