Gillky Gillky - 3 days ago 7
Java Question

Small chat program, access variables between files

at the moment I am creating a simple chat program that will allow you to communicate between a server. I am having an issue accessing the username variable when it is used in one file in another file. The user will enter his name, this is done in the ChatGUI file, then when he enters the chat room a EchoFrame is created, which is in the EchoFrame file. Also in the EchoFrame file, I want to append the username to the users message, and also announce when they connect to the chatroom and when they leave the chat room. I hope I was clear on explaining my issue, any other information needed please let me know!

EchoFrame

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

public class EchoFrame extends Frame{

EchoPanel ep;
Button sendMessage;

public EchoFrame(){

setSize(500,500);
setTitle("Echo Client");
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});

ep = new EchoPanel();
add(ep, BorderLayout.CENTER);




setVisible(true);
}

public static void main(String[] args){

EchoFrame ef = new EchoFrame();

}
}


class EchoPanel extends Panel implements ActionListener, Runnable{

TextField tf;
TextArea ta;
Button connect, disconnect;
Socket s;
BufferedReader br;
PrintWriter pw;
Thread t;
String fromServer;
String username;


public EchoPanel(){

setLayout(new BorderLayout());
tf = new TextField();
tf.setEditable(false);
tf.addActionListener(this);
add(tf, BorderLayout.NORTH);
ta = new TextArea();
ta.setEditable(false);
add(ta, BorderLayout.CENTER);
Panel buttonPanel = new Panel();
connect = new Button("Connect");
connect.addActionListener(this);
buttonPanel.add(connect);
disconnect = new Button("Disconnect");
disconnect.setEnabled(false);
disconnect.addActionListener(this);
buttonPanel.add(disconnect);
add(buttonPanel, BorderLayout.SOUTH);



}

public void actionPerformed(ActionEvent ae){

if(ae.getSource() == connect){
try{
s = new Socket("127.0.0.1", 8189);
ta.append(username + " has entered the chat room. \n");
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
pw = new PrintWriter(s.getOutputStream(), true);
}catch(UnknownHostException uhe){
System.out.println(uhe.getMessage());
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}

t = new Thread(this);
t.start();
tf.setEditable(true);
connect.setEnabled(false);
disconnect.setEnabled(true);
}else if(ae.getSource() == disconnect){
try{
pw.close();
br.close();
s.close();
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
t = null;
ta.append(username + " has disconnected from chat room. \n");
tf.setEditable(false);
connect.setEnabled(true);
disconnect.setEnabled(false);
}else if(ae.getSource() == tf){
String fromTf = tf.getText();
pw.println(fromTf);
tf.setText("");

}else{

//additional events
}
}

public void run (){
fromServer = "";
try{
while((fromServer = br.readLine()) != null){

ta.append(username + ":" + fromServer + "\n");
}
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
}

}


ChatGUI

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;




public class ChatGUI extends JFrame {

private int currentCard = 1;
private JPanel cardPanel;
private CardLayout cl;
JTextField usernameField;
String username;

public ChatGUI() {

setTitle("Chat Program");
setSize(500, 120);
cardPanel = new JPanel();

cl = new CardLayout();
cardPanel.setLayout(cl);

JPanel chooseUsername = new JPanel();
JLabel usernameLabel = new JLabel("Please enter your username:");

chooseUsername.add(usernameLabel);
cardPanel.add(chooseUsername, "Log in");

usernameField = new JTextField(15);


usernameField.setEditable(true);
add(usernameField, BorderLayout.CENTER);


JPanel buttonPanel = new JPanel();
JButton logInBtn = new JButton("Enter Chat Room");

buttonPanel.add(logInBtn);



logInBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
currentCard = 2;
cl.show(cardPanel, "" + (currentCard));

username = usernameField.getText(); //gets username
EchoFrame ef = new EchoFrame(); //creates message room

}
});


getContentPane().add(cardPanel, BorderLayout.NORTH);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
}
public static void main(String[] args) {
ChatGUI cl = new ChatGUI();
cl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cl.setVisible(true);
}
}


Chat Server

import java.io.*;
import java.net.*;
import java.util.*;

public class ChatServer{
Socket s;
ArrayList <ChatHandler>handlers;
public ChatServer(){
try{
ServerSocket ss = new ServerSocket(8189);
handlers = new ArrayList<ChatHandler>();
for(;;){
s = ss.accept();
new ChatHandler(s, handlers).start();
}
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
}
public static void main(String[] args){
ChatServer tes = new ChatServer();
}
}


Chat Handler

import java.io.*;
import java.net.*;
import java.util.*;

public class ChatHandler extends Thread{
Socket s;
BufferedReader br;
PrintWriter pw;
String temp;
ArrayList <ChatHandler>handlers;

public ChatHandler(Socket s, ArrayList <ChatHandler>handlers){
this.s = s;
this.handlers = handlers;
}


public void run(){
try{
handlers.add(this);
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
pw = new PrintWriter(s.getOutputStream(), true);
temp = "";
while((temp = br.readLine()) != null){
for (ChatHandler ch : handlers){
ch.pw.println(temp);
}
System.out.println(temp);
}
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}finally{
handlers.remove(this);
}
}
}

Answer

Make userName static and access it via ChatUI.userName. In actuality, userName shouldn't be in ChatUI. Alternatively, a more heavyweight option would be to get MySQL, set up a database, and connect to it via JDBC, if you're going to have more than one user.

Comments