JAVA two way communication between classes - java

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.

Related

this.dispose() is not working to close a JFrame

When I add:
this.dispose();
The window is not closing, what can I do?.
I use Eclipse with windowsBuilder.
I want to close the actual window to open another window.
My code:
public class Ventana_login extends JFrame {
/**
*
*/
private static final long serialVersionUID = -7948060398287723741L;
private JPanel contentPane;
private JTextField txtUsuario;
private JPasswordField txtContrasena;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Ventana_login frame = new Ventana_login();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Ventana_login() {
setTitle("Sistema Gestor de Eventos v1.0");
setResizable(false);
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);
JLabel lblBienvenidoAlSistema = new JLabel("Bienvenido");
lblBienvenidoAlSistema.setHorizontalAlignment(SwingConstants.CENTER);
lblBienvenidoAlSistema.setFont(new Font("Tahoma", Font.BOLD, 16));
lblBienvenidoAlSistema.setBounds(10, 11, 424, 14);
contentPane.add(lblBienvenidoAlSistema);
JLabel lblUsuario = new JLabel("Usuario");
lblUsuario.setHorizontalAlignment(SwingConstants.RIGHT);
lblUsuario.setBounds(96, 79, 70, 14);
contentPane.add(lblUsuario);
JLabel lblContrasena = new JLabel("Contrase\u00F1a");
lblContrasena.setHorizontalAlignment(SwingConstants.RIGHT);
lblContrasena.setBounds(96, 109, 70, 14);
contentPane.add(lblContrasena);
txtUsuario = new JTextField();
txtUsuario.setBounds(176, 76, 150, 20);
contentPane.add(txtUsuario);
txtUsuario.setColumns(10);
JButton btnIniciarSesion = new JButton("Iniciar Sesi\u00F3n");
btnIniciarSesion.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
Dato_login d_lgn = new Dato_login();
Logica_login l_lgn = new Logica_login();
d_lgn.setUsuario(txtUsuario.getText());
char[] contrasenaChar = txtContrasena.getPassword();
String contrasenaClean = new String(contrasenaChar);
d_lgn.setContrasena(contrasenaClean);
Dato_login d_lgn2 = l_lgn.login(d_lgn.getUsuario(), d_lgn.getContrasena());
if (Logica_login.resultado) {
Ventana_menu v_menu = new Ventana_menu();
v_menu.setVisible(true);
v_menu.setLocationRelativeTo(null);
Ventana_menu.lblPerfilActual.setText(d_lgn2.getPerfil());
Ventana_menu.lblApellidoActual.setText(d_lgn2.getApellido());
Ventana_menu.lblNombreActual.setText(d_lgn2.getNombre());
Ventana_menu.lblUsuarioActual.setText(d_lgn2.getUsuario());
if (Ventana_menu.lblPerfilActual.getText().equals("Portero")) {
Ventana_menu.btnMantenimiento_Eventos.setEnabled(false);
Ventana_menu.btnMantenimiento_Invitaciones.setEnabled(false);
Ventana_menu.btnMantenimiento_Invitados.setEnabled(false);
Ventana_menu.btnMantenimiento_Usuarios.setEnabled(false);
Ventana_menu.btnReportes.setEnabled(true);
} else {
Ventana_menu.btnMantenimiento_Eventos.setEnabled(true);
Ventana_menu.btnMantenimiento_Invitaciones.setEnabled(true);
Ventana_menu.btnMantenimiento_Invitados.setEnabled(true);
Ventana_menu.btnMantenimiento_Usuarios.setEnabled(true);
Ventana_menu.btnReportes.setEnabled(true);
}
this.dispose();
} else {
JOptionPane.showMessageDialog(contentPane, "Acceso Denegado", "Error", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Exception:\n" + e, "Error: Ventana_login", JOptionPane.ERROR_MESSAGE);
}
}
});
btnIniciarSesion.setBounds(176, 163, 150, 30);
contentPane.add(btnIniciarSesion);
I will assume by window you mean JFrame:
then do:
myJframe.dispatchEvent(new WindowEvent(myJframe, WindowEvent.WINDOW_CLOSING));

Why isn't the Frame showing?

After implementing the Observer/Observable pattern, I can't really see why the Frame isn't showing when the code is executed.
I've looked over it a million times but can't figure it out.
I just want to know where I've gone wrong and how I can fix, so that the frame is showing.
Apologies for the code dump. Would be very grateful for the assistance.
public class MainGameFrame extends JFrame implements KeyListener,Observer {
private final JLabel lblPythonChallenge = DefaultComponentFactory
.getInstance().createTitle("Code Wars");
protected JTextArea textAreaEditable;
protected JTextArea textAreaQuestion;
protected JTextArea textAreaResult;
protected JTextArea textAreaScore;
protected PrintWriter output; // to write textArea stuff to file
private JTextArea textAreaPreview;
private JLabel lblPreview;
private ServerToClient model;
private Socket sock;
/**
* Create the application.
*/
public MainGameFrame() {
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
try {
sock = new Socket("127.0.0.1", 6789);
model = new ServerToClient(sock);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
initialize();
setVisible(true);
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
model.addObserver(this);
getContentPane().setBackground(new Color(153, 204, 102));
setForeground(Color.GREEN);
setBackground(Color.GREEN);
setTitle("Code Wars");
setBounds(100, 100, 762, 511);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
// TextArea 1
textAreaEditable = new JTextArea();
textAreaEditable.setBounds(10, 117, 353, 130);
getContentPane().add(textAreaEditable);
textAreaEditable.setTabSize(2); // fix tab size
// auto-indentation
textAreaEditable.registerKeyboardAction(new IndentNextLine(),
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),
JComponent.WHEN_FOCUSED);
// add KeyListener
textAreaEditable.addKeyListener(this);
// TextArea 2
textAreaQuestion = new JTextArea();
textAreaQuestion.setBackground(new Color(255, 255, 255));
textAreaQuestion.setBounds(10, 34, 353, 46);
getContentPane().add(textAreaQuestion);
// TextArea 3
textAreaResult = new JTextArea();
textAreaResult.setBounds(10, 357, 713, 104);
getContentPane().add(textAreaResult);
textAreaResult.setEditable(false);
// JTextPane textPane_1 = new JTextPane();
// textPane_1.setBounds(463, 158, 273, 269);
// frmPythonChallenge.getContentPane().add(textPane_1);
// component 4
JButton btnRunCode = new JButton("Run Code");
btnRunCode.setBounds(10, 258, 330, 31);
getContentPane().add(btnRunCode);
btnRunCode.addActionListener(new RunButtonListener());
// TextArea 4
textAreaScore = new JTextArea();
textAreaScore.setBounds(373, 34, 350, 46);
getContentPane().add(textAreaScore);
lblPythonChallenge.setBounds(23, -31, 143, 31);
getContentPane().add(lblPythonChallenge);
JLabel lblEnterCodeIn = DefaultComponentFactory.getInstance()
.createLabel("Enter code in the box below:");
lblEnterCodeIn.setForeground(new Color(0, 100, 0));
lblEnterCodeIn.setFont(new Font("Tahoma", Font.BOLD, 12));
lblEnterCodeIn.setBounds(10, 91, 209, 15);
getContentPane().add(lblEnterCodeIn);
JLabel lblQuestion = DefaultComponentFactory.getInstance().createLabel(
"Question:");
lblQuestion.setForeground(new Color(0, 100, 0));
lblQuestion.setFont(new Font("Tahoma", Font.BOLD, 12));
lblQuestion.setBounds(10, 9, 92, 14);
getContentPane().add(lblQuestion);
JLabel lblScores = DefaultComponentFactory.getInstance().createLabel(
"Scores:");
lblScores.setForeground(new Color(0, 100, 0));
lblScores.setFont(new Font("Tahoma", Font.BOLD, 12));
lblScores.setBounds(373, 9, 92, 14);
getContentPane().add(lblScores);
JLabel lblThisIsThe = DefaultComponentFactory.getInstance()
.createLabel("This is the result from your code!");
lblThisIsThe.setForeground(new Color(0, 100, 0));
lblThisIsThe.setFont(new Font("Tahoma", Font.BOLD, 12));
lblThisIsThe.setBounds(10, 328, 238, 15);
getContentPane().add(lblThisIsThe);
// TextArea 5
textAreaPreview = new JTextArea();
textAreaPreview.setBounds(373, 117, 350, 130);
textAreaPreview.setTabSize(2);
textAreaPreview.setEditable(false);
getContentPane().add(textAreaPreview);
lblPreview = DefaultComponentFactory.getInstance().createLabel(
"Preview");
lblPreview.setForeground(new Color(0, 128, 0));
lblPreview.setFont(new Font("Tahoma", Font.BOLD, 12));
lblPreview.setLabelFor(lblPreview);
lblPreview.setBounds(373, 84, 200, 31);
getContentPane().add(lblPreview);
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainGameFrame window = new MainGameFrame();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Change your main() method to this:
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainGameFrame window = new MainGameFrame();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
At the end of the initialize() method, add some code that will make MainGameFrame() visible:
this.setVisible(true);
I also suggest you use a Layout Manager to organize the components. Oracle has some great tutorials on how to use different layouts. How to Use Various Layout Managers

Two way communication between a GUI and a Server Client

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!

Two way communication between GUI and a Server Client

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);
}
}
}

Java, runing "textArea = new JTextArea()" taking too much time

Something strange happened to me. For some reason, it takes a long time(1.60900 seconds) till it runs the following line:
textArea = new JTextArea();
I declared textArea variable as globally.
This only happens in one window (Jframe). In others it does not happen.
public class FAQ extends JFrame
{
/*--------attributes--------*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JPanel panel;
private JScrollPane scrollPaneInput;
private JScrollPane scrollPaneQuestions;
private JPanel paneQuestions;
private JPanel paneSelectOrNewFAQ;
private JButton btnEditSelection;
private JButton btnNewFAQ;
public JTextArea textArea;
private JLabel lblQuestions;
public JList list;
private User user;
private FAQ currentWindow;
private int selectedFaq = 0;
private DatabaseManager DManager;
private Vector<FAQ_class> Faqs = new Vector<FAQ_class>();
private JButton btnNewButton;
/*--------methods--------*/
public FAQ(User _user,DatabaseManager DM)
{
setResizable(false);
DManager = DM;
addWindowStateListener(new WindowStateListener() {
public void windowStateChanged(WindowEvent arg0) {
}
});
addWindowListener(new WindowAdapter() {
#Override
public void windowClosed(WindowEvent arg0) {
Menu menu = new Menu(user,DManager);
menu.setVisible(true);
}
});
currentWindow = this;
user = _user;
addGui();
if(!user.rule.equals("patient"))
{
btnEditSelection.setEnabled(true);
btnNewFAQ.setEnabled(true);
}
loadFaqs();
}//end of FAQ
public void loadFaqs()
{
Faqs = DManager.getQuestionsList();
Vector<String> temp = new Vector<String>();
for(int i = 0 ; i < Faqs.size();i++)
{
temp.addElement(Faqs.get(i).question);
}
list.setListData(temp);
}
public void addGui()
{
setTitle("FAQ - Online medical help");
setIconImage(Toolkit.getDefaultToolkit().getImage(FAQ.class.getResource("/Images/question.png")));
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 708, 438);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new GridLayout(1, 0, 0, 0));
addPanel();
addPanes();
addButtons();
addGroupLayout();
addJTextArea();
}//end of addGui
public void addPanel()
{
panel = new JPanel();
panel.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.add(panel);
}//end of addPanel
public void addPanes()
{
scrollPaneInput = new JScrollPane();
scrollPaneInput.setBounds(327, 0, 365, 398);
paneQuestions = new JPanel();
paneQuestions.setBounds(0, 0, 317, 38);
paneQuestions.setBackground(new Color(154, 205, 50));
}//end of addScrollPanes
public void addButtons()
{
}//end of addButtons
public void addJTextArea()
{
textArea = new JTextArea();
textArea.setEditable(false);
textArea.setFont(new Font("Courier New", Font.PLAIN, 14));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setAlignmentX(Component.RIGHT_ALIGNMENT);
scrollPaneInput.setViewportView(textArea);
}//end of addJTextArea
public void addGroupLayout()
{
lblQuestions = new JLabel("Questions");
lblQuestions.setHorizontalAlignment(SwingConstants.CENTER);
lblQuestions.setBounds(0, 0, 317, 38);
lblQuestions.setForeground(new Color(255, 255, 255));
lblQuestions.setFont(new Font("Tahoma", Font.BOLD, 22));
panel.setLayout(null);
scrollPaneQuestions = new JScrollPane();
scrollPaneQuestions.setBounds(0, 37, 317, 318);
list = new JList();
list.setSelectionBackground(new Color(154, 205, 50));
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
try
{
for(int i = 0; i<Faqs.size();i++)
{
if(!list.isSelectionEmpty())
if(Faqs.get(i).question.equals(list.getSelectedValue().toString()))
{
textArea.setText(Faqs.get(i).answer);
selectedFaq = i;
break;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
scrollPaneQuestions.setViewportView(list);
panel.add(scrollPaneQuestions);
panel.add(paneQuestions);
paneQuestions.setLayout(null);
paneQuestions.add(lblQuestions);
panel.add(scrollPaneInput);
paneSelectOrNewFAQ = new JPanel();
paneSelectOrNewFAQ.setBounds(0, 348, 317, 50);
btnEditSelection = new JButton("Edit Selected");
btnEditSelection.setBounds(68, 11, 131, 40);
btnEditSelection.setEnabled(false);
btnEditSelection.addActionListener(new ActionListener() {
//open EditFAQ to edit FAQ
public void actionPerformed(ActionEvent e) {
if(!list.isSelectionEmpty())
{
EditFAQ faq = new EditFAQ(user,Faqs.get(selectedFaq),currentWindow,DManager);
faq.setVisible(true);
currentWindow.setEnabled(false);
}
else
{
JOptionPane.showMessageDialog(null,"You must select for the list first.");
}
}
});
btnEditSelection.setIcon(new ImageIcon(FAQ.class.getResource("/Images/tool.png")));
btnNewFAQ = new JButton("New FAQ");
btnNewFAQ.setBounds(203, 11, 114, 40);
btnNewFAQ.setEnabled(false);
btnNewFAQ.addActionListener(new ActionListener() {
//open EditFAQ to make new FAQ
public void actionPerformed(ActionEvent e) {
EditFAQ faq = new EditFAQ(user,null,currentWindow,DManager);
faq.setVisible(true);
currentWindow.setEnabled(false);
}
});
btnNewFAQ.setMinimumSize(new Dimension(95, 23));
btnNewFAQ.setMaximumSize(new Dimension(95, 23));
btnNewFAQ.setPreferredSize(new Dimension(95, 23));
btnNewFAQ.setIcon(new ImageIcon(FAQ.class.getResource("/Images/add.png")));
btnNewButton = new JButton("");
btnNewButton.setBounds(0, 10, 42, 41);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
btnNewButton.setIcon(new ImageIcon(FAQ.class.getResource("/Images/left.png")));
panel.add(paneSelectOrNewFAQ);
paneSelectOrNewFAQ.setLayout(null);
paneSelectOrNewFAQ.add(btnNewButton);
paneSelectOrNewFAQ.add(btnEditSelection);
paneSelectOrNewFAQ.add(btnNewFAQ);
}//end of addGroupLayout
}//end of class
Something strange happened to me. For some reason, it takes a long time(5 second~) till it runs the following line: Run this class and give me the result:
import java.text.DecimalFormat;
import java.text.NumberFormat;
import javax.swing.JTextArea;
public class JTextAreaRunningTime {
JTextArea textArea;
public JTextAreaRunningTime(){
long startTime = System.currentTimeMillis();
textArea = new JTextArea();
long endTime = System.currentTimeMillis();
NumberFormat nf = new DecimalFormat("#0.00000");
String totalTime = nf.format((endTime-startTime)/1000d);
System.out.println("Execution time is " + totalTime + " seconds");
}
public static void main (String...argW){
new JTextAreaRunningTime();
}
}

Categories