-1

Im struggling to change this segment from requiring a server address hard coded to using

private static inetAddress host;

Here is the code

    import java.awt.*;
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.InetAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;

import javax.swing.*;

public class ChatClient extends JFrame {

    private JFrame chatFrame = new JFrame("Welcome To The Chat Room");
    private JFrame loginFrame;
    private JButton sendBtn, exitBtn;
    private JTextField typingArea;
    private JTextArea inRoom;
    private JTextArea chatBox;
    private JTextField loginInput;
    private static String username, entry;
    private static InetAddress host;

    public static ArrayList<String> usersList = new ArrayList<>();

    BufferedReader networkInput;
    PrintWriter networkOutput;

    public void loginDisplay() throws Exception {

        chatFrame.setVisible(false);
        loginFrame = new JFrame("Welcome User!");
        loginInput = new JTextField(15);

        JLabel usernameLabel = new JLabel("Pick a username:");
        JButton joinServer = new JButton("Enter Chat Server");

        joinServer.addActionListener(new loginBtnClick());
        JPanel loginPanel = new JPanel();


        loginPanel.add(usernameLabel);
        loginPanel.add(loginInput);

        loginFrame.add(BorderLayout.CENTER, loginPanel);
        loginFrame.add(BorderLayout.SOUTH, joinServer);
        loginFrame.setSize(300, 300);
        loginFrame.setVisible(true);

    }

    public void display() throws IOException {
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());

        JPanel southPanel = new JPanel();
        southPanel.setLayout(new GridBagLayout());

        typingArea = new JTextField(40);

        sendBtn = new JButton("Send Your Message");
        sendBtn.addActionListener(new sendBtnClick());

        chatBox = new JTextArea();
        chatBox.setEditable(false);
        chatBox.setLineWrap(true);

        inRoom = new JTextArea();
        inRoom.setEditable(false);
        inRoom.setLineWrap(false);
        inRoom.setSize(150, 300);

        inRoom.append("Users in Room: \n");

        mainPanel.add(new JScrollPane(chatBox));
        mainPanel.add(new JScrollPane(inRoom), BorderLayout.WEST);

        southPanel.add(typingArea);
        southPanel.add(sendBtn);

        mainPanel.add(BorderLayout.SOUTH, southPanel);
        chatFrame.add(mainPanel);
        chatFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        chatFrame.setSize(470, 350);
        chatFrame.setVisible(true);
        //chatFrame.setResizable(false);
    }

    //private String getServerAddress() {
    //  return "127.0.0.1";
    //}

    private class loginBtnClick implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            username = loginInput.getText();
            if (username.length() < 1) {
                System.out.println("Invalid Username");
                JOptionPane.showMessageDialog(null, "Invalid Username");
                //message to server and user error username

            } else {
                loginFrame.setVisible(false);
                networkOutput.println(loginInput.getText());
                try {
                    display();
                } catch (Exception e) {
                    System.out.println(e);
                    System.exit(1);
                }
            }

        }

    }

    private class sendBtnClick implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            if (typingArea.getText().length() < 1) {

            } else {
                networkOutput.println(typingArea.getText());
                typingArea.setText("");
            }
        }
    }

    public void run() throws IOException {

        //String serverAddress = getServerAddress();
        Socket socket = new Socket(host, 1237);
        networkInput = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        networkOutput = new PrintWriter(socket.getOutputStream(), true);

        while (true) {
            String line = networkInput.readLine();

            if (line.startsWith("NAMESENT  ")) {
                if (username != null) {
                    networkOutput.println(username);
                }
            } else if (line.startsWith("NAMEACCEPTED")) {

            } else if (line.startsWith("MESSAGE")) {
                chatBox.append(line.substring(8) + "\n");

            } else if (line.startsWith("LIST")) {
                if (!usersList.contains(line.substring(5))) {
                    usersList.add(line.substring(5));
                    inRoom.append(line.substring(5) + "\n");
                }
            } else if (line.startsWith("SPECMSG")) {
                if (line.substring(8).startsWith(username)) {
                    chatBox.append(line.substring(9 + username.length()));
                }
            } else if (line.startsWith("DISCONNECT")) {
                chatBox.append(line.substring(10) + " has disconnected.");
            }

        }

    }

    public static void main(String[] args) {

        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        ChatClient chat = new ChatClient();
        try {
            chat.loginDisplay();
            chat.run();

        } catch (Exception e) {
        }

    }

In the past i have had it as simple as this but i cant get it to be happy with it

private static void sendMessages() 
                            throws ClassNotFoundException {
    final int PORT = 1239;
    String entry;

    try {
        socket = new Socket(host, PORT);

EDIT

I want to get the top code to not say

socket = new Socket(ServerAddress, 1237)

i want it to say

socket = new Socket(host, PORT);

EDIT 2

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at ChatClient$loginBtnClick.actionPerformed(ChatClient.java:106)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$500(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
  • I don't understand your problem, could you please clarify what's wrong? – Nicolas Filotto Jun 09 '16 at 14:17
  • What is the question? – m0skit0 Jun 09 '16 at 14:17
  • What kind of errors? – Nicolas Filotto Jun 09 '16 at 14:21
  • This constructor exists https://docs.oracle.com/javase/7/docs/api/java/net/Socket.html#Socket(java.lang.String,%20int) so please be more accurate in your question – Nicolas Filotto Jun 09 '16 at 14:22
  • Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at ChatClient$loginBtnClick.actionPerformed(ChatClient.java:106) at javax.swing.AbstractButton.fireActionPerformed(Unknown Source) at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) – George Cawdron Jun 09 '16 at 14:22
  • add this in your question with the code of ChatClient – Nicolas Filotto Jun 09 '16 at 14:23
  • is there a way i can message you so i can state this more clearly? – George Cawdron Jun 09 '16 at 14:24
  • Why can't you just put the info in your question, to let people help you? – Nicolas Filotto Jun 09 '16 at 14:26
  • theres a time frame for editing questions isnt there? or is that only for this comment part down here. that was my worry i didnt want to run out of time editing, i do apologise – George Cawdron Jun 09 '16 at 14:27
  • no you can edit it as many times as you want – Nicolas Filotto Jun 09 '16 at 14:28
  • it must be the comments here with the time limit (im sure it has happened to me before) i have updated it now – George Cawdron Jun 09 '16 at 14:30
  • yes it is with the comment, you have a limited time to edit it but it is not applicable to questions hopefully some questions are edited even years later – Nicolas Filotto Jun 09 '16 at 14:31
  • that was asked by someone else not me, i understand how the null pointers work and the exceptions but sometimes you just cannot see where you need to put them. that is the case here it seems – George Cawdron Jun 09 '16 at 14:31
  • i have an error on an exact line that is not helped by the person killing my question, why does 106 have an error? where should the null pointer be? and i didnt want to dump my entire code because it causes issues with people stealing it which i have ran into – George Cawdron Jun 09 '16 at 14:38

1 Answers1

0

Java 7 documentation Socket Class says that it's possible to define a socket with

Socket(String host, int port)

Creates a stream socket and connects it to the specified port number on the named host.

Maybe you're problem is that the host OR the port at which you're connecting are down.

user2543740
  • 172
  • 1
  • 10