I'm trying to send a certain string when a button is pressed in my GUI. My Client class is currently running to keep taking string commands from the command line and send them to the server where they will be processed and a response will be returned.
How can I now send the data through my GUI and move the results back to my GUI?
E.g. I have a button called "pickup" which, when clicked will send the string "PICKUP" to the server, through the Client class.
Likewise, the response from the server would be either "SUCCESS" or "FAIL" which would be printed through the Thread "serverResponse" in my Client class and this needs to somehow be sent to an arbitrary method in the playerGUI class as a parameter.
Thanks for any help, sorry for not using the conventional class/method/field naming styles!
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class playerGUI {
private JFrame frame = new JFrame();
private JPanel displayPanel;
private JTextPane hostTextPane;
private JTextPane portTextPane;
private static Client newclient;
public static void main(String[] args) {
playerGUI GUI = new playerGUI();
GUI.frame.setVisible(true);
newclient = new Client(GUI);
}
/**
* Create the application.
*/
public playerGUI() {
frame.getContentPane().setBackground(new Color(255, 255, 255));
frame.getContentPane().setLayout(null);
frame.setBounds(100, 100, 500, 630);
frame.setUndecorated(false); // REMOVES MENU BAR
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel humanGameWindow = new JPanel();
humanGameWindow.setLayout(null);
humanGameWindow.setBackground(Color.LIGHT_GRAY);
humanGameWindow.setBounds(0, 0, 500, 630);
humanGameWindow.setVisible(false);
JButton pickup = new JButton("Pickup");
pickup.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//I WANT TO SEND THE STRING "PICKUP" TO WHERE THE STARS ARE IN Client.class
}
});
pickup.setBackground(new Color(100, 149, 237));
pickup.setBounds(40, 555, 100, 40);
displayPanel = new JPanel();
displayPanel.setBounds(48, 89, 400, 400);
displayPanel.setLayout(new GridLayout(5, 5));
displayPanel.setPreferredSize(new Dimension((int) (400), (int) (400)));
for (int i = 1; i < 26; i++) {
displayPanel.add(new JLabel("Label " + i));
}
JButton Look = new JButton("Look");
Look.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
Look.setBackground(new Color(100, 149, 237));
Look.setBounds(40, 514, 100, 40);
humanGameWindow.add(Look);
humanGameWindow.add(pickup);
humanGameWindow.add(displayPanel);
final JPanel mainMenu = new JPanel();
mainMenu.setLayout(null);
mainMenu.setBackground(Color.DARK_GRAY);
mainMenu.setBounds(0, 0, 500, 630);
mainMenu.setVisible(true);
JLabel mainMenuTitle = new JLabel("DUNGEON OF DOOM!!");
mainMenuTitle.setForeground(new Color(100, 149, 237));
mainMenuTitle.setFont(new Font("Moire", Font.BOLD, 28));
mainMenuTitle.setBounds(50, 13, 380, 50);
JButton mainMenuQuit = new JButton("Quit");
mainMenuQuit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
mainMenuQuit.setBackground(new Color(100, 149, 237));
mainMenuQuit.setBounds(220, 345, 70, 55);
JButton playGameHuman = new JButton("Play Game Human");
playGameHuman.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mainMenu.setVisible(false);
humanGameWindow.setVisible(true);
}
});
playGameHuman.setBackground(new Color(100, 149, 237));
playGameHuman.setBounds(50, 345, 150, 55);
mainMenu.add(mainMenuTitle);
mainMenu.add(mainMenuQuit);
mainMenu.add(playGameHuman);
frame.getContentPane().add(humanGameWindow);
frame.getContentPane().add(mainMenu);
frame.setVisible(true);
}
}
This is the Client class, the thread is where I want to send the response to the GUI class to process and display a specific output. The asterisks is where I want to send the text from button presses in the GUI class (there are other buttons I have deleted the code for easier reading!).
import java.net.*;
import java.io.*;
public class Client{
public Client(playerGUI GUI){
try{
final Socket sock = new Socket("localhost",4444);
final DataInputStream in = new DataInputStream(sock.getInputStream());
final PrintStream out = new PrintStream(sock.getOutputStream());
DataInputStream inputLine = new DataInputStream(new BufferedInputStream(System.in));
final Thread serverResponse = new Thread(){
public void run(){
System.out.println("DUNGEON OF DOOM HAS STARTED");
if(sock != null){
if(in != null){
try{
String response;
while((response = in.readLine()) != null){
//I WANT TO SEND "response" TO THE GUI CLASS
System.out.println(response);
}
}catch(UnknownHostException uhe){
System.err.println("Unknown host1: " + uhe);
}catch(IOException ioe){
System.err.println("IOException1: " + ioe);
}catch(NullPointerException npe){
System.err.println("Null Pointer1: " + npe);
}
}
}
}
};
serverResponse.start();
if(sock != null){
if(out != null){
try{
while(true){
String sending = *************************
//String sending = inputLine.readLine();
out.println(sending);
if(sending.equals("QUIT")) break;
}
}catch(UnknownHostException uhe2){
System.err.println("Unknown host2: " + uhe2);
}catch(IOException ioe2){
System.err.println("IOException2: " + ioe2);
}catch(NullPointerException npe2){
System.err.println("Null Pointer2: " + npe2);
}
}
}
out.close();
in.close();
sock.close();
}catch(UnknownHostException uhe3){
System.err.println("Unknown host3: " + uhe3);
}catch(IOException ioe3){
System.err.println("IOException3: " + ioe3);
}catch(NullPointerException npe3){
System.err.println("Null Pointer3: " + npe3);
}
}
}
You probaly should read that and then ask questions: Tutorial
To pass data from GUI to client thread, use LinkedBlockingQueue. To send the response to the GUI, use SwingUtilities.invokeLater.
You are mixing server and client side code as shown below. Client-Server application doesn't work in this way.
public static void main(String[] args) {
playerGUI GUI = new playerGUI();
GUI.frame.setVisible(true);
newclient = new Client(GUI);
}
In the final both the classes will live in separate JVM on separate Machine.
It might work on single machine but What will happen if server is running on one system and multiple clients are trying to communicate from different systems?
I have already posted some samples, please have a look at Client-Server Communication. I have described it step by step just follow the thread to find other samples as well.
Please let me know if still you have any issue!
Related
I'm trying to link my login class to my Laptop class but when I try to run the program it's only display "login successful" and when I press ok it's appeared as a blank frame. can someone tell me why? I already try to mess around with the button action performed but still display blank frame as result.
login class
import java.awt.*;
import java.io.*;
import javax.swing.*;
public class login extends JFrame{
JFrame frame = new JFrame();
JButton btnLogin;
JTextField fieldPass, fieldUser;
JLabel lblUser, lblPass;
String filePath="password.txt";
String filePathUser="userrname.txt";
String password="";
String username="";
BufferedWriter bw=null;
BufferedWriter bw2=null;
FileWriter fw=null;
FileWriter fw2=null;
File textFile=new File(filePath);
File textFileUser=new File(filePathUser);
Boolean login=false;
public login() {
function();
}
private void readFile() throws FileNotFoundException{
String user="";
String pass="";
boolean passFound=false;
boolean userFound=false;
BufferedReader passReader=null;
BufferedReader userReader=null;
password=fieldPass.getText();
username=fieldUser.getText();
boolean notFound=false;
try{
passReader=new BufferedReader(new FileReader("D:\\sementara buat ngoding\\password.txt"));
userReader=new BufferedReader(new FileReader("D:\\sementara buat ngoding\\username.txt"));
do{
user=userReader.readLine();
if (username.equalsIgnoreCase(user)) {
userFound=true;
}
pass=passReader.readLine();
if (password.equalsIgnoreCase(pass)) {
passFound=true;
}
if (pass==null||user==null) {
notFound=true;
}
}while(!userFound&&!passFound&&!notFound);
if (userFound&&passFound) {
login=true;
}
}
catch(IOException ex){
}
finally{
try{
if (passReader!=null) {
passReader.close();
}
if (userReader!=null) {
userReader.close();
}
}
catch(IOException ioe){
JOptionPane.showMessageDialog(null, "close error");
}
}
}
#SuppressWarnings("unchecked")
private void function() {
btnLogin = new JButton();
fieldPass = new JTextField();
fieldUser = new JTextField();
lblUser = new JLabel();
lblPass = new JLabel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btnLogin.setText("LOGIN");
btnLogin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLoginActionPerformed(evt);
}
});
fieldPass.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fieldPassActionPerformed(evt);
}
});
lblUser.setText("USERNAME:");
lblPass.setText("PASSWORD:");
}
private void fieldPassActionPerformed(java.awt.event.ActionEvent evt) {
}
private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {
try{
readFile();
if (login==true) {
JOptionPane.showMessageDialog(null, "login Success");
Laptop lapcl = new Laptop();
lapcl.setVisible(true);
}
else{
JOptionPane.showMessageDialog(null, "Login Failed");
}
}
catch(IOException ioe){
}
}
public static void main(String args[]) {
login LOG = new login();
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setSize(500, 200);
panel.setBackground(Color.decode("#a020f0"));
LOG.lblUser.setBounds(72, 30, 100, 30);
LOG.lblUser.setBackground(Color.decode("#a020f0"));
LOG.lblUser.setFont(new Font("Arial",Font.BOLD,14));
LOG.fieldUser.setBounds(202, 30, 200, 30);
LOG.lblPass.setBounds(72, 60, 100, 30);
LOG.lblPass.setBackground(Color.decode("#a020f0"));
LOG.lblPass.setFont(new Font("Arial",Font.BOLD,14));
LOG.fieldPass.setBounds(202, 60, 200, 30);
LOG.btnLogin.setBounds(302, 100, 100, 30);
LOG.btnLogin.setFont(new Font("Arial",(Font.BOLD),12));
LOG.btnLogin.setBackground(Color.decode("#7d26cd"));
frame.setSize(500, 200);
frame.setVisible(true);
frame.add(LOG.lblUser);
frame.add(LOG.fieldPass);
frame.add(LOG.lblPass);
frame.add(LOG.fieldUser);
frame.add(LOG.btnLogin);
frame.add(panel);
}
}
Laptop class
import java.awt.*;
import java.io.*;
import javax.swing.*;
public class Laptop extends JFrame{
JFrame frame = new JFrame();
JButton btnLaptop, btnTrans, btnHist;
public Laptop(){
function();
}
private void function() {
btnLaptop = new JButton();
btnTrans = new JButton();
btnHist = new JButton();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btnLaptop.setText("Laptop Data");
btnTrans.setText("Transaction");
btnHist.setText("Transaction History");
}
public static void main(String[] args) {
Laptop LAP = new Laptop();
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setSize(900, 600);
panel.setBackground(Color.decode("#a020f0"));
LAP.btnLaptop.setBounds(20, 20, 120, 30);
LAP.btnLaptop.setFont(new Font("Arial",(Font.BOLD),15));
LAP.btnLaptop.setBackground(Color.decode("#7d26cd"));
LAP.btnTrans.setBounds(160, 20, 120, 30);
LAP.btnTrans.setFont(new Font("Arial",(Font.BOLD),15));
LAP.btnTrans.setBackground(Color.decode("#7d26cd"));
LAP.btnHist.setBounds(300, 20, 120, 30);
LAP.btnHist.setFont(new Font("Arial",(Font.BOLD),15));
LAP.btnHist.setBackground(Color.decode("#7d26cd"));
frame.setVisible(true);
frame.setSize(900, 600);
frame.add(LAP.btnLaptop);
frame.add(LAP.btnTrans);
frame.add(LAP.btnHist);
frame.add(panel);
}
}
You are running login.class file. So main function of Laptop class never called.
You can do the things into btnLoginActionPerformed the things you have done into the main method of Laptop class.
So your btnLoginActionPerformed method of login class will be like this.....
private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {
try{
readFile();
if (login==true) {
JOptionPane.showMessageDialog(null, "login Success");
Laptop LAP = new Laptop();
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setSize(900, 600);
panel.setBackground(Color.decode("#a020f0"));
LAP.btnLaptop.setBounds(20, 20, 120, 30);
LAP.btnLaptop.setFont(new Font("Arial",(Font.BOLD),15));
LAP.btnLaptop.setBackground(Color.decode("#7d26cd"));
LAP.btnTrans.setBounds(160, 20, 120, 30);
LAP.btnTrans.setFont(new Font("Arial",(Font.BOLD),15));
LAP.btnTrans.setBackground(Color.decode("#7d26cd"));
LAP.btnHist.setBounds(300, 20, 120, 30);
LAP.btnHist.setFont(new Font("Arial",(Font.BOLD),15));
LAP.btnHist.setBackground(Color.decode("#7d26cd"));
frame.setVisible(true);
frame.setSize(900, 600);
frame.add(LAP.btnLaptop);
frame.add(LAP.btnTrans);
frame.add(LAP.btnHist);
frame.add(panel);
}
else{
JOptionPane.showMessageDialog(null, "Login Failed");
}
}
catch(IOException ioe){
}
}
you can also remove the main method of Laptop class. because it is useless.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am trying to make a text based adventure that runs in a jframe but when i run the program i get a NullPointer error on line 97 (first time i append console in the game method) and I have no idea how to fix it. I am relatively new to java so its probably something simple that I just don't know.
my code is here
package window;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Gui extends JFrame {
public JPanel contentPane;
public static JTextField input;
public static JButton send;
public static JTextArea console;
public static JTextArea invintory;
public static JTextArea stats;
static String i = "";
/**
* Launch the application.
*/
/**
* Create the frame.
*/
public Gui() {
//variables
int Gold = 20;
int Health = 100;
int MaxHealth = 100;
//variables end
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JTextArea console = new JTextArea();
console.setBounds(10, 11, 281, 214);
contentPane.add(console);
input = new JTextField();
input.setBounds(10, 236, 281, 20);
contentPane.add(input);
input.setColumns(10);
JTextArea stats = new JTextArea();
stats.setBounds(301, 11, 123, 53);
contentPane.add(stats);
JTextArea invintory = new JTextArea();
invintory.setBounds(301, 75, 128, 137);
contentPane.add(invintory);
JButton send = new JButton("Send");
send.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String i = input.getText();
input.setText("");
stats.setText("");
stats.append("Health: " + Health + "/" + MaxHealth + "\n");
stats.append("Gold: " + Gold);
}
});
send.setBounds(301, 224, 128, 32);
contentPane.add(send);
stats.append("Health: " + Health + "/" + MaxHealth + "\n");
stats.append("Gold: " + Gold);
}
public static void game (JButton send, JTextArea console, JTextArea stats, JTextArea invintory, JTextField input, String i) {
//start
//START
//START
//START
//START
while (true) {
console.append("You wake up open feild, with vast amounts of wheet in every direction");
console.append("There is a path going in either direction what do you want to do");
console.append("\t1. Go left.");
console.append("\t2. Go right.");
while (i == "") {
}
if (i == "1") {
console.append("1");
break;
}
else if (i == "2") {
console.append("2");
break;
}
}
//END
//END
//END
//END
}
public static void main(String[] args) {
try {
Gui frame = new Gui();
frame.setVisible(true);
Gui.game(send, console, stats, invintory, input, i);
} catch (Exception e) {
e.printStackTrace();
}
}
}
In your global variable console is null
public static JTextArea console;
You initialized it in Gui method
JTextArea console = new JTextArea();
So here in Gui method your global console variable is not initialized, This creates a local variable console under Gui method.
To initialize global variable in Gui method you need to initialize this way
console = new JTextArea();
You did this mistake to all variables so edit your code this way
public Gui() {
//variables
int Gold = 20;
int Health = 100;
int MaxHealth = 100;
//variables end
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
console = new JTextArea();
console.setBounds(10, 11, 281, 214);
contentPane.add(console);
input = new JTextField();
input.setBounds(10, 236, 281, 20);
contentPane.add(input);
input.setColumns(10);
stats = new JTextArea();
stats.setBounds(301, 11, 123, 53);
contentPane.add(stats);
invintory = new JTextArea();
invintory.setBounds(301, 75, 128, 137);
contentPane.add(invintory);
send = new JButton("Send");
send.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String i = input.getText();
input.setText("");
stats.setText("");
stats.append("Health: " + Health + "/" + MaxHealth + "\n");
stats.append("Gold: " + Gold);
}
});
send.setBounds(301, 224, 128, 32);
contentPane.add(send);
stats.append("Health: " + Health + "/" + MaxHealth + "\n");
stats.append("Gold: " + Gold);
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am currently trying to develop a simple local area network chat feature for the company. But I'm stuck at this point where the run method never get executed in client which previously working fine. It started not working after I restructure the constructor to be able to dispose and visible frame on system tray icon double click. Please let me know where I'm go wrong. I send you the code where it was previously working and current now where it's not working. I can also send the server interface source and other code if needed.
Before structuring (ChatClient.java)
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import sun.audio.*;
import java.awt.BorderLayout;
public class ChatClient extends Thread implements ActionListener, KeyListener {
String lineSeparator = System.getProperty("line.separator");
JFrame frame;
JPanel mainPanel;
JLabel label_1, label_2, label_3, label_4, label_5, charCnt;
JMenuBar menuBar;
JMenu tool, help;
JMenuItem save, log, exit, about, information;
JTextField field_2;
JTextArea area_1, area_2;
JCheckBox cb1;
JButton button_1, button_2, button_3, button_4, button_5, button_6, button_7;
JScrollPane scroll, scroll2;
Icon send = new ImageIcon("Resources/Image/send.gif");
Icon sv = new ImageIcon("Resources/Image/save.png");
Icon lg = new ImageIcon("Resources/Image/logoff.gif");
Icon ext = new ImageIcon("Resources/Image/exit.png");
Icon About = new ImageIcon("Resources/Image/about.png");
Icon clear = new ImageIcon("Resources/Image/clear.png");
Icon info = new ImageIcon("Resources/Image/help.png");
Font small = new Font("Sans Serif", Font.ITALIC, 9);
String strg[] = new String[10];
int arr, ctr2 = 0;
int charMax = 150;
boolean ignoreInput = false;
JList list;
DefaultListModel listModel;
Color background = new Color(241, 243, 248);
Color color = new Color(255, 255, 255);
Socket client;
String messageToAll, name;
BufferedReader fromServer;
PrintStream toServer;
Login login;
time2 obj2 = new time2(this);
Thread thr = new Thread(this);
#SuppressWarnings({"CallToThreadStartDuringObjectConstruction", "ResultOfObjectAllocationIgnored"})
ChatClient(String name, String IP, Login login) {
super(name);
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
}
Image bd = Toolkit.getDefaultToolkit().getImage("Resources/Image/client.png");
this.name = name;
this.login = login;
frame = new JFrame("Client - " + name);
frame.setIconImage(bd);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel();
menuBar = new JMenuBar();
tool = new JMenu("Tools");
help = new JMenu("Help");
save = new JMenuItem("Save");
log = new JMenuItem("Login as..");
exit = new JMenuItem("Exit");
about = new JMenuItem("About");
information = new JMenuItem("Information");
label_1 = new JLabel("Online Users");
label_3 = new JLabel("Messages: ");
label_4 = new JLabel("Public Message");
label_5 = new JLabel("");
charCnt = new JLabel("");
field_2 = new JTextField(29);
field_2.setToolTipText("Date & Time");
field_2.setEditable(false);
field_2.setFocusable(false);
cb1 = new JCheckBox("private");
cb1.setToolTipText("Private message");
area_1 = new JTextArea(20, 10);
area_1.setFont(login.notify);
area_1.setLineWrap(true);
area_1.setEditable(false);
area_2 = new JTextArea(1, 10);
area_2.setLineWrap(true);
area_2.setToolTipText("type your message here..");
scroll = new JScrollPane(area_1);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll2 = new JScrollPane(area_2);
mainPanel.setLayout(new BorderLayout());
listModel = new DefaultListModel();
list = new JList(listModel);
list.setToolTipText("Client available");
button_1 = new JButton("SEND");
button_1.setToolTipText("send message");
frame.getContentPane().add(mainPanel);
mainPanel.add(menuBar);
mainPanel.add(charCnt);
mainPanel.add(label_1);
mainPanel.add(label_3);
mainPanel.add(label_4);
mainPanel.add(label_5);
mainPanel.add(field_2);
mainPanel.add(scroll);
mainPanel.add(scroll2);
mainPanel.add(list);
mainPanel.add(button_1);
mainPanel.add(cb1);
cb1.setFont(login.notify);
button_1.setIcon(send);
mainPanel.setLayout(null);
menuBar.setBounds(0, 0, 600, 25);
//Users
label_1.setBounds(455, 5, 150, 20);
//Messages Box
//label_2.setBounds(245, 317, 150, 20);
//Messages
//label_3.setBounds(5, 335, 90, 25);
//Public Messages
label_4.setBounds(140, 5, 300, 20);
//time
label_5.setBounds(485, 297, 100, 25);
//Characters count
charCnt.setBounds(80, 360, 150, 15);
charCnt.setFont(small);
scroll.setBounds(5, 30, 390, 300);
scroll2.setBounds(5, 335, 450, 35);
list.setBounds(400, 30, 185, 260);
field_2.setBounds(479, 300, 110, 25);
cb1.setBounds(398, 300, 70, 20);
//button
button_1.setBounds(490, 336, 95, 27);
frame.setSize(600, 400);
frame.setResizable(false);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
button_1.addActionListener(this);
button_1.addKeyListener(this);
button_1.setMnemonic(KeyEvent.VK_ENTER);
area_2.addKeyListener(this);
field_2.addKeyListener(this);
list.addKeyListener(this);
cb1.addActionListener(this);
cb1.addKeyListener(this);
cb1.setMnemonic(KeyEvent.VK_P);
try {
client = new Socket(IP, 1001);
toServer = new PrintStream(client.getOutputStream());
fromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));
toServer.println("##" + name);
thr.start();
} catch (IOException e) {
area_1.setText("no server detected!");
JOptionPane.showMessageDialog(null, " No server running! " + lineSeparator + "Sorry, You've to log out.... ");
this.frame.dispose();
System.exit(0);
}
area_2.requestFocus();
obj2.start();
}
#SuppressWarnings("ResultOfObjectAllocationIgnored")
public static void main(String arg[]) {
new Login();
}
public void run() {
while (thr != null) {
try {createAndShowUI(); >>this code here executed properly.
} catch (IOException | HeadlessException e) {
JOptionPane.showMessageDialog(null, "Server has Closed!" + lineSeparator + "Sorry, you've to log out");
System.exit(0);
}
}
After restructuring (ChatClient.java)
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import sun.audio.*;
import java.awt.BorderLayout;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public final class ChatClient extends Thread implements ActionListener, KeyListener {
String lineSeparator = System.getProperty("line.separator");
JPanel mainPanel;
JLabel label_1, label_2, label_3, label_4, label_5, charCnt;
JMenuBar menuBar;
JMenu tool, help;
JMenuItem save, log, exit, about, information;
JTextField field_2;
JTextArea area_2;
JTextPane chatPane;
JCheckBox cb1;
JButton button_1, button_2, button_3, button_4, button_5, button_6, button_7;
JScrollPane scroll, scroll2, scroll3;
Icon send = new ImageIcon("Resources/Image/send.gif");
Icon sv = new ImageIcon("Resources/Image/save.png");
Icon lg = new ImageIcon("Resources/Image/logoff.gif");
Icon ext = new ImageIcon("Resources/Image/exit.png");
Icon About = new ImageIcon("Resources/Image/about.png");
Icon clear = new ImageIcon("Resources/Image/clear.png");
Icon info = new ImageIcon("Resources/Image/help.png");
Font small = new Font("Sans Serif", Font.ITALIC, 9);
Font prv = new Font("Helvetica", Font.ITALIC, 14);
String strg[] = new String[10];
int arr, ctr2 = 0;
int charMax = 150;
boolean ignoreInput = false;
JList list;
DefaultListModel listModel;
Color background = new Color(241, 243, 248);
Color color = new Color(255, 255, 255);
Socket client;
String messageToAll, name;
BufferedReader fromServer;
PrintStream toServer;
Login login;
time2 obj2 = new time2(this);
Thread thr = new Thread(this);
/**
*
* #param name
* #param IP
* #param login
*/
#SuppressWarnings({"CallToThreadStartDuringObjectConstruction", "ResultOfObjectAllocationIgnored"})
public ChatClient(String name, String IP, Login login) {
super(name);
try {
createAndShowUI(name);
createAndShowGUI(name);
client = new Socket(IP, 1001);
toServer = new PrintStream(client.getOutputStream());
fromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));
toServer.println("##" + name);
} catch (IOException e) {
chatPane.setText("no server detected!");
JOptionPane.showMessageDialog(null, " No server running! " + lineSeparator + "Sorry, You've to log out.... ");
System.exit(0);
}
}
public ChatClient() {
// defaultItem1.addActionListener(exitListener);
// defaultItem2.addActionListener(restoreListener);
// this.login = login;
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
}
mainPanel = new JPanel();
menuBar = new JMenuBar();
tool = new JMenu("Tools");
help = new JMenu("Help");
save = new JMenuItem("Save");
log = new JMenuItem("Login as..");
exit = new JMenuItem("Exit");
about = new JMenuItem("About");
information = new JMenuItem("Information");
label_1 = new JLabel("Online Users");
label_3 = new JLabel("Messages: ");
label_4 = new JLabel("Public Message");
label_5 = new JLabel("");
charCnt = new JLabel("");
field_2 = new JTextField(29);
field_2.setToolTipText("Date & Time");
field_2.setEditable(false);
field_2.setFocusable(false);
cb1 = new JCheckBox("private");
cb1.setToolTipText("Private message");
chatPane = new JTextPane();
area_2 = new JTextArea(1, 10);
area_2.setLineWrap(true);
area_2.setToolTipText("type your message here..");
listModel = new DefaultListModel();
list = new JList(listModel);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setToolTipText("Client available");
list.setVisibleRowCount(5);
scroll = new JScrollPane(chatPane);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll2 = new JScrollPane(area_2);
scroll2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scroll2.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll3 = new JScrollPane(list);
scroll3.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scroll3.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
mainPanel.setLayout(new BorderLayout());
button_1 = new JButton("SEND");
button_1.setToolTipText("send message");
mainPanel.add(charCnt);
mainPanel.add(label_1);
mainPanel.add(label_3);
mainPanel.add(label_4);
mainPanel.add(label_5);
mainPanel.add(field_2);
mainPanel.add(scroll);
mainPanel.add(scroll2);
mainPanel.add(scroll3);
mainPanel.add(button_1);
mainPanel.add(cb1);
cb1.setFont(prv);
button_1.setIcon(send);
mainPanel.setLayout(null);
menuBar.setBounds(0, 0, 600, 25);
//Users
label_1.setBounds(455, 5, 150, 20);
//Messages Box
//label_2.setBounds(245, 317, 150, 20);
//Messages
//label_3.setBounds(5, 335, 90, 25);
//Public Messages
label_4.setBounds(140, 5, 300, 20);
//time
label_5.setBounds(485, 297, 100, 25);
//Characters count
charCnt.setBounds(380, 358, 120, 15);
charCnt.setFont(small);
scroll.setBounds(5, 25, 390, 300);
//chatPane.setFocusable(false);
chatPane.setEditable(false);
scroll2.setBounds(5, 325, 485, 48);
scroll3.setBounds(400, 30, 185, 260);
field_2.setBounds(477, 300, 112, 25);
cb1.setBounds(398, 300, 70, 20);
button_1.setBounds(490, 326, 100, 30);
button_1.addActionListener(this);
button_1.addKeyListener(this);
button_1.setMnemonic(KeyEvent.VK_ENTER);
area_2.addKeyListener(this);
field_2.addKeyListener(this);
list.addKeyListener(this);
cb1.addActionListener(this);
cb1.addKeyListener(this);
cb1.setMnemonic(KeyEvent.VK_P);
try {
thr.start();
} catch (Exception e) {
}
area_2.requestFocus(true);
obj2.start();
}
#SuppressWarnings("ResultOfObjectAllocationIgnored")
public static void main(String arg[]) {
new Login();
}
public void run() {
while (thr != null) {
try {
createAndShowUI(); >> this code never run to
Login.java
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
final class Login {
JFrame frame;
JPanel panel;
JLabel label_1, label_2, label_3, label_4;
JTextField field_1, field_2;
JPasswordField pass;
JButton button_1, button_2;
Font Default = new Font("Comic Sans MS", Font.PLAIN, 12);
Font notify = new Font("Comic Sans MS", Font.BOLD, 12);
Font small = new Font("Sans Serif", Font.ITALIC, 3);
//String IP;
Socket client;
InetAddress ipaddr;
String hostname;
PrintStream toServer;
ChatClient clientObj;
public String gethostString(){
try {
ipaddr = InetAddress.getLocalHost();
hostname = ipaddr.getHostName();
}
catch (UnknownHostException e) {
}
return hostname;
}
#SuppressWarnings("CallToPrintStackTrace")
Login() {
String IP = "192.168.10.88";
try {
ipaddr = InetAddress.getLocalHost();
hostname = ipaddr.getHostName();
clientObj = new ChatClient(gethostString(), IP, this);
// clientObj.createAndShowGUI(hostname);
// clientObj.createAndShowUI();
} catch (UnknownHostException e) {
e.printStackTrace();
}
Image bd = Toolkit.getDefaultToolkit().getImage("Image/login.png");
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
}
}
}
This is my method createAndShowUI.
public void createAndShowUI(String name) {
this.name = name;
JFrame frame;
frame = new JFrame("Client - " + name);
Image bd = Toolkit.getDefaultToolkit().getImage("Resources/Image/client.png");
frame.setIconImage(bd);
frame.getContentPane().add(new ChatClient().mainPanel); >> I call the constructor here to draw the frame.
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.setSize(600, 400);
frame.setResizable(false);
// frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public JComponent getComponent() {
return mainPanel;
}
Any help would be very much appreciated. Cheers!
You created a second no-argument constructor, and nobody is invoking that second constructor. However, you moved the code that starts the thread into that second constructor, so now the thread is not being started anymore().
Perhaps you want to call this method public void init() { instead of public ChatClient() {, and then you call init(); at the end of the first constructor that has 3 arguments.
I'm trying to send a certain string when a button is pressed in my GUI. My Client class is currently running to keep taking string commands from the command line and send them to the server where they will be processed and a response will be returned.
How can I now send the data through my GUI and move the results back to my GUI?
E.g. I have a button called "pickup" which, when clicked will send the string "PICKUP" to the server, through the Client class.
Likewise, the response from the server would be either "SUCCESS" or "FAIL" which would be printed through the Thread "serverResponse" in my Client class and this needs to somehow be sent to an arbitrary method in the playerGUI class as a parameter.
Thanks for any help, sorry for not using the conventional class/method/field naming styles!
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class playerGUI {
private JFrame frame = new JFrame();
private JPanel displayPanel;
private JTextPane hostTextPane;
private JTextPane portTextPane;
private static Client newclient;
public static void main(String[] args) {
playerGUI GUI = new playerGUI();
GUI.frame.setVisible(true);
newclient = new Client(GUI);
}
/**
* Create the application.
*/
public playerGUI() {
frame.getContentPane().setBackground(new Color(255, 255, 255));
frame.getContentPane().setLayout(null);
frame.setBounds(100, 100, 500, 630);
frame.setUndecorated(false); // REMOVES MENU BAR
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel humanGameWindow = new JPanel();
humanGameWindow.setLayout(null);
humanGameWindow.setBackground(Color.LIGHT_GRAY);
humanGameWindow.setBounds(0, 0, 500, 630);
humanGameWindow.setVisible(false);
JButton pickup = new JButton("Pickup");
pickup.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//I WANT TO SEND THE STRING "PICKUP" TO WHERE THE STARS ARE IN Client.class
}
});
pickup.setBackground(new Color(100, 149, 237));
pickup.setBounds(40, 555, 100, 40);
displayPanel = new JPanel();
displayPanel.setBounds(48, 89, 400, 400);
displayPanel.setLayout(new GridLayout(5, 5));
displayPanel.setPreferredSize(new Dimension((int) (400), (int) (400)));
for (int i = 1; i < 26; i++) {
displayPanel.add(new JLabel("Label " + i));
}
JButton Look = new JButton("Look");
Look.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
Look.setBackground(new Color(100, 149, 237));
Look.setBounds(40, 514, 100, 40);
humanGameWindow.add(Look);
humanGameWindow.add(pickup);
humanGameWindow.add(displayPanel);
final JPanel mainMenu = new JPanel();
mainMenu.setLayout(null);
mainMenu.setBackground(Color.DARK_GRAY);
mainMenu.setBounds(0, 0, 500, 630);
mainMenu.setVisible(true);
JLabel mainMenuTitle = new JLabel("DUNGEON OF DOOM!!");
mainMenuTitle.setForeground(new Color(100, 149, 237));
mainMenuTitle.setFont(new Font("Moire", Font.BOLD, 28));
mainMenuTitle.setBounds(50, 13, 380, 50);
JButton mainMenuQuit = new JButton("Quit");
mainMenuQuit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
mainMenuQuit.setBackground(new Color(100, 149, 237));
mainMenuQuit.setBounds(220, 345, 70, 55);
JButton playGameHuman = new JButton("Play Game Human");
playGameHuman.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mainMenu.setVisible(false);
humanGameWindow.setVisible(true);
}
});
playGameHuman.setBackground(new Color(100, 149, 237));
playGameHuman.setBounds(50, 345, 150, 55);
mainMenu.add(mainMenuTitle);
mainMenu.add(mainMenuQuit);
mainMenu.add(playGameHuman);
frame.getContentPane().add(humanGameWindow);
frame.getContentPane().add(mainMenu);
frame.setVisible(true);
}
}
This is the Client class, the thread is where I want to send the response to the GUI class to process and display a specific output. The asterisks is where I want to send the text from button presses in the GUI class (there are other buttons I have deleted the code for easier reading!).
import java.net.*;
import java.io.*;
public class Client{
public Client(playerGUI GUI){
try{
final Socket sock = new Socket("localhost",4444);
final DataInputStream in = new DataInputStream(sock.getInputStream());
final PrintStream out = new PrintStream(sock.getOutputStream());
DataInputStream inputLine = new DataInputStream(new BufferedInputStream(System.in));
final Thread serverResponse = new Thread(){
public void run(){
System.out.println("DUNGEON OF DOOM HAS STARTED");
if(sock != null){
if(in != null){
try{
String response;
while((response = in.readLine()) != null){
//I WANT TO SEND "response" TO THE GUI CLASS
System.out.println(response);
}
}catch(UnknownHostException uhe){
System.err.println("Unknown host1: " + uhe);
}catch(IOException ioe){
System.err.println("IOException1: " + ioe);
}catch(NullPointerException npe){
System.err.println("Null Pointer1: " + npe);
}
}
}
}
};
serverResponse.start();
if(sock != null){
if(out != null){
try{
while(true){
String sending = *************************
//String sending = inputLine.readLine();
out.println(sending);
if(sending.equals("QUIT")) break;
}
}catch(UnknownHostException uhe2){
System.err.println("Unknown host2: " + uhe2);
}catch(IOException ioe2){
System.err.println("IOException2: " + ioe2);
}catch(NullPointerException npe2){
System.err.println("Null Pointer2: " + npe2);
}
}
}
out.close();
in.close();
sock.close();
}catch(UnknownHostException uhe3){
System.err.println("Unknown host3: " + uhe3);
}catch(IOException ioe3){
System.err.println("IOException3: " + ioe3);
}catch(NullPointerException npe3){
System.err.println("Null Pointer3: " + npe3);
}
}
}
I want to be able to create an instance of my Client class in my GUI and then pass GUI.this as a parameter for the Client constructor but I'm not sure exactly how to do that. I know I'm missing something obvious! I want to be able to call methods on the other from either class. Obviously I have commented code out because I don't know how or what I am supposed to do to achieve this two way communication without merging the classes! I want to be able to do stuff like send a command through the Client from the GUI class when the "Up" button is clicked on the GUI etc. Thanks for the help in advance.
Client class:
public class Client{
//static playerGUI GUI;
public static void main(String[] args) {
//GUI = new playerGUI();
//GUI.getFrame().setVisible(true);
//Client cli = new Client("localhost",4444);
}
public Client(playerGUI GUI){
try{
final Socket sock = new Socket("localhost",4444);
final DataInputStream in = new DataInputStream(sock.getInputStream());
final PrintStream out = new PrintStream(sock.getOutputStream());
DataInputStream inputLine = new DataInputStream(new BufferedInputStream(System.in));
final Thread serverResponse = new Thread(){
public void run(){
System.out.println("DUNGEON OF DOOM HAS STARTED");
if(sock != null){
if(in != null){
try{
String response;
while((response = in.readLine()) != null){
//GUI.processgrid(response);
//send to GUI to process output!
System.out.println(response);
}
}catch(UnknownHostException uhe){
System.err.println("Unknown host1: " + uhe);
}catch(IOException ioe){
System.err.println("IOException1: " + ioe);
}catch(NullPointerException npe){
System.err.println("Null Pointer1: " + npe);
}
}
}
}
};
serverResponse.start();
if(sock != null){
if(out != null){
try{
while(true){
//inputbuttons!
String sending = inputLine.readLine();
out.println(sending);
if(sending.equals("QUIT")) break;
}
}catch(UnknownHostException uhe2){
System.err.println("Unknown host2: " + uhe2);
}catch(IOException ioe2){
System.err.println("IOException2: " + ioe2);
}catch(NullPointerException npe2){
System.err.println("Null Pointer2: " + npe2);
}
}
}
out.close();
in.close();
sock.close();
}catch(UnknownHostException uhe3){
System.err.println("Unknown host3: " + uhe3);
}catch(IOException ioe3){
System.err.println("IOException3: " + ioe3);
}catch(NullPointerException npe3){
System.err.println("Null Pointer3: " + npe3);
}
}
}
GUI Class:
public class playerGUI {
private JFrame Frame = new JFrame();
private JPanel displayPanel;
private JTextPane hostTextPane;
private JTextPane portTextPane;
private playerGUI GUI;
public static void main(String[] args) {
playerGUI GUI = new playerGUI();
GUI.Frame.setVisible(true);
Client newclient = new Client(this.playerGUI);
}
/**
* Create the application.
*/
public playerGUI() {
Frame.getContentPane().setBackground(new Color(255, 255, 255));
Frame.getContentPane().setLayout(null);
Frame.setBounds(100, 100, 500, 630);
Frame.setUndecorated(false); // REMOVES MENU BAR
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// ############################################################################################################################################################################
final JPanel humanGameWindow = new JPanel();
humanGameWindow.setLayout(null);
humanGameWindow.setBackground(Color.LIGHT_GRAY);
humanGameWindow.setBounds(0, 0, 500, 600);
humanGameWindow.setVisible(false);
JLabel gameTitle = new JLabel("DUNGEON OF DOOM!!");
gameTitle.setForeground(new Color(100, 149, 237));
gameTitle.setFont(new Font("Moire", Font.BOLD, 28));
gameTitle.setBounds(92, 5, 380, 50);
JButton up = new JButton("Up");
up.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// ######################
}
});
up.setBackground(new Color(100, 149, 237));
up.setBounds(274, 514, 100, 40);
JButton down = new JButton("Down");
down.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// ######################
}
});
down.setBackground(new Color(100, 149, 237));
down.setBounds(274, 555, 100, 40);
JButton left = new JButton("Left");
left.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// ######################
}
});
left.setBackground(new Color(100, 149, 237));
left.setBounds(173, 535, 100, 40);
JButton right = new JButton("Right");
right.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// ######################
}
});
right.setBackground(new Color(100, 149, 237));
right.setBounds(375, 535, 100, 40);
JButton pickup = new JButton("Pickup");
pickup.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// ######################
}
});
pickup.setBackground(new Color(100, 149, 237));
pickup.setBounds(40, 555, 100, 40);
JButton Exit = new JButton("Exit");
Exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
Exit.setBackground(new Color(100, 149, 237));
Exit.setBounds(427, 17, 70, 40);
displayPanel = new JPanel();
displayPanel.setBounds(48, 89, 400, 400);
displayPanel.setLayout(new GridLayout(5, 5));
displayPanel.setPreferredSize(new Dimension((int) (400), (int) (400)));
for (int i = 1; i < 26; i++) {
displayPanel.add(new JLabel("Label " + i));
}
humanGameWindow.add(gameTitle);
humanGameWindow.add(up);
humanGameWindow.add(down);
humanGameWindow.add(left);
humanGameWindow.add(right);
humanGameWindow.add(pickup);
humanGameWindow.add(Exit);
humanGameWindow.add(displayPanel);
final JPanel mainMenu = new JPanel();
mainMenu.setLayout(null);
mainMenu.setBackground(Color.LIGHT_GRAY);
mainMenu.setBounds(0, 0, 500, 600);
mainMenu.setVisible(true);
JLabel mainMenuTitle = new JLabel("DUNGEON OF DOOM!!");
mainMenuTitle.setForeground(new Color(100, 149, 237));
mainMenuTitle.setFont(new Font("Moire", Font.BOLD, 28));
mainMenuTitle.setBounds(50, 13, 380, 50);
hostTextPane = new JTextPane();
hostTextPane.setToolTipText("Enter the host name");
hostTextPane.setBackground(new Color(192, 192, 192));
hostTextPane.setBounds(50, 100, 234, 30);
hostTextPane.setFont(new Font("Moire", Font.BOLD, 19));
portTextPane = new JTextPane();
portTextPane.setToolTipText("Enter the port");
portTextPane.setBackground(new Color(192, 192, 192));
portTextPane.setBounds(50, 175, 234, 30);
portTextPane.setFont(new Font("Moire", Font.BOLD, 19));
JButton playGameHuman = new JButton("Play Game Human");
playGameHuman.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mainMenu.setVisible(false);
humanGameWindow.setVisible(true);
//not sure if i need to be creating the Client here?
/*
* if (!(hostTextPane.getText().equals("")) &&
* !(portTextPane.getText().equals(""))) { try { Client cli =
* new Client(hostTextPane.getText(), Integer
* .parseInt(portTextPane.getText())); } catch (Exception e1) {
* System.out.println("Error."); } } else {
* JOptionPane.showMessageDialog(null,
* "Do not leave hostname or port no. blank."); }
*/
}
});
playGameHuman.setBackground(new Color(100, 149, 237));
playGameHuman.setBounds(50, 345, 150, 55);
mainMenu.add(mainMenuTitle);
mainMenu.add(mainMenuQuit);
mainMenu.add(playGameHuman);
mainMenu.add(hostTextPane);
mainMenu.add(portTextPane);
getFrame().getContentPane().add(humanGameWindow);
getFrame().getContentPane().add(mainMenu);
getFrame().setVisible(true);
}
}
public static void main(String[] args) {
playerGUI GUI = new playerGUI();
GUI.Frame.setVisible(true);
Client newclient = new Client(GUI);
}
main is a static method, which means it is run in a static context (ie, not "as" any instantiated object). This means you can't access this in main because there is no this to access. You need to access playerGUI with just playerGUI or playerGUI.playerGUI in your Client.main method. Also, you need to set the field playerGUI.playerGUI to static.
Instead of this:
Client newclient = new Client(this.playerGUI);
you need this:
Client newclient = new Client(GUI);
Notice that as main is static there is no this defined.
Also consider changing the names of your class and variables to follow Java naming conventions:
playerGUI should be PlayerGUI
GUI should be gui or whatever you feel like but starting with lowercase
Also do you notice that you are not using that field called GUI? You are only using the variable GUI. So it may be adding up to the confusion.