How does the client wait for a server response - java

I have a simple server to client program that lets the server send text to the clients, There is no connection problems. However, I'm not sure what to put the while loop which updates the JLabel of the sent text. If I put while(true) I get an error saying no lines found.
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Client {
private static JLabel l = new JLabel();
public Client() {
JFrame f = new JFrame("Client");
JPanel p = new JPanel(null);
f.setSize(300, 150);
f.setLocationRelativeTo(null);
l.setSize(300, 20);
l.setLocation(0, 65);
p.add(l);
f.add(p);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) throws IOException {
new Client();
Socket socket = new Socket("localhost", 12000);
Scanner in = new Scanner(socket.getInputStream());
while(/* code goes here */) {
l.setText(in.nextLine());
}
}
}

private class PollingThread implements Runnable {
public void run() {
while (true) {
try {
l.setText(in.nextLine());
} catch (/* */) {
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
Log.d(TAG, "Thread interrupted");
}
}
}
Create a private nested class inside Client class.
Initiate the thread from Client class's main() method.
PollingThread mPollingThread = new PollingThread();
mPollingThread.start();

Related

How do I put a Server class on my website so my Client class can communicate with it from different computers?

I have a server client application working just how I want it locally. I need to get the server online so the client program can be used from different computers. Not sure how to do this. I have my own website that I thought I could just put the Server on in the background.
Is this possible or am I just looking at this the wrong way.
Server.java
package core;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
public class Server {
public static void main(String[] args) throws IOException {
ArrayList<ClientHandler> clients = new ArrayList<>();
ServerSocket serverSocket = null;
int clientNum = 1; // keeps track of how many clients were created
// 1. CREATE A NEW SERVERSOCKET
try {
serverSocket = new ServerSocket(4444); // provide MYSERVICE at port
// 4444
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
System.exit(-1);
}
// 2. LOOP FOREVER - SERVER IS ALWAYS WAITING TO PROVIDE SERVICE!
while (true) {
Socket clientSocket = null;
try {
// 2.1 WAIT FOR CLIENT TO TRY TO CONNECT TO SERVER
System.out.println("Waiting for client " + clientNum + " to connect!");
clientSocket = serverSocket.accept();
clientNum++;
ClientHandler c = new ClientHandler(clientSocket, clients);
clients.add(c);
// 2.2 SPAWN A THREAD TO HANDLE CLIENT REQUEST
Thread t = new Thread(c);
t.start();
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
// 2.3 GO BACK TO WAITING FOR OTHER CLIENTS
// (While the thread that was created handles the connected client's
// request)
} // end while loop
} // end of main method
} // end of class MyServer
class ClientHandler implements Runnable {
Socket s; // this is socket on the server side that connects to the CLIENT
ArrayList<ClientHandler> others;
Scanner in;
PrintWriter out;
ClientHandler(Socket s, ArrayList<ClientHandler> others) throws IOException {
this.s = s;
this.others = others;
in = new Scanner(s.getInputStream());
out = new PrintWriter(s.getOutputStream());
}
/*
* (non-Javadoc)
*
* #see java.lang.Runnable#run()
*/
public void run() {
// 1. USE THE SOCKET TO READ WHAT THE CLIENT IS SENDING
while (true) {
String clientMessage = in.nextLine();
// System.out.println(clientMessage);
new Thread(new Runnable() {
#Override
public void run() {
try (PrintWriter fileWriter = new PrintWriter(new FileOutputStream(new File("chat.txt"), true));) {
fileWriter.println(clientMessage);
fileWriter.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println(others.size());
for (ClientHandler c : others) {
// System.out.println(c.toString());
c.sendMessage(clientMessage);
}
}
}).start();
}
}
private void sendMessage(String str) {
out.println(str);
out.flush();
}
} // end of class ClientHandler
ClientSide.java
package core;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.BoxLayout;
import javax.swing.JTextArea;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
public class ClientSide extends JFrame {
private JPanel contentPane;
private JTextField textField;
private String name;
private JTextArea textArea;
private Thread serverListener;
private Socket socket;
private Scanner in;
private PrintWriter out;
// /**
// * Launch the application.
// */
// public static void main(String[] args) {
// EventQueue.invokeLater(new Runnable() {
// public void run() {
// try {
// ClientSide frame = new ClientSide();
// frame.setVisible(true);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// });
// }
/**
* Create the frame.
*
* #throws IOException
*/
public ClientSide(String myName) {
try {
socket = new Socket("localhost", 4444);
in = new Scanner(socket.getInputStream());
out = new PrintWriter(socket.getOutputStream());
} catch (IOException e1) {
e1.printStackTrace();
}
serverListener = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
String clientMessage = in.nextLine();
try {
System.out.println("Receiving before dec: " + clientMessage);
clientMessage = Crypto.decrypt(clientMessage, "key");
System.out.println("Receiving after dec: " + clientMessage);
addLine(clientMessage);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
serverListener.start();
name = myName;
setTitle("Client Side");
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(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
JPanel topPanel = new JPanel();
FlowLayout flowLayout = (FlowLayout) topPanel.getLayout();
flowLayout.setAlignment(FlowLayout.LEFT);
contentPane.add(topPanel);
textArea = new JTextArea();
textArea.setEditable(false);
textArea.setColumns(20);
textArea.setRows(7);
topPanel.add(textArea);
JPanel bottomPanel = new JPanel();
contentPane.add(bottomPanel);
bottomPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
JLabel lblMessage = new JLabel("Message");
bottomPanel.add(lblMessage);
textField = new JTextField();
bottomPanel.add(textField);
textField.setColumns(10);
JButton btnSend = new JButton("Send");
btnSend.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// send string/message to server
String clientMessage;
try {
clientMessage = Crypto.encrypt(name + ": > " + textField.getText(), "key");
System.out.println("Sending: " + clientMessage);
out.println(clientMessage);
out.flush();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
bottomPanel.add(btnSend);
}
public void addLine(String text) {
textArea.setText(textArea.getText() + text + "\n");
}
}
Provided your ClientSide class connects with your server applicztion on port 4444, you can do the following:
Package your client as jar file and run on each computer you want to distribute it to.
Ensure, each of those computers have JRE installed.
3 Package your Server module as jar file
You should own your server or have admin right. So you can install Java if not there.
Depending on OS, SSH skill might be required
Ensure PORT 4444 is enabled on your host server. firewall
Get the public IP address of your server and use it in your ClideSide code.

Text not showing up in Jframes in my GUI

So I've been working on this program off and on for a few days, its a basic client server chat room. I'm trying to have it so that when you launch the client, the gui that pops up has text inside of the portnumber, servername, and textbox JTextFields. Yesterday this was the case but I've changed things and now the gui appears without text in the text fields. That code is in the displaysettings method which runs at the beginning of the try catch block. Anyone know why it isn't working?
import java.net.*;
import java.util.*;
import java.io.*;
import java.awt.event.*;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class clienttry2 extends JFrame implements ActionListener {
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JButton send = new JButton("Send");
JButton connect = new JButton("Connect");
JLabel server = new JLabel("Server");
JLabel port = new JLabel("Port");
JButton disconnect = new JButton("Disconnect");
static JTextField servername = new JTextField(10);
static JTextField portnumber = new JTextField(10);
static JTextField textbox = new JTextField(40);
JTextArea chatbox = new JTextArea(20,45);
static Boolean isconnected = false;
static Boolean sending = false;
static Socket server1;
static ObjectInputStream in;
static ObjectOutputStream out;
public clienttry2(){
setTitle("Chat Room");
setLayout(new java.awt.FlowLayout());
setSize(600,500);
panel1.add(chatbox); //has all the chats
panel2.add(textbox); //area to type new messages into
panel2.add(send); send.addActionListener(this);//send button
panel3.add(server);
panel3.add(servername);
panel3.add(port);
panel3.add(portnumber);
panel3.add(connect); connect.addActionListener(this);
panel3.add(disconnect); disconnect.addActionListener(this); disconnect.setEnabled(false);
add(panel1);
add(panel2);
add(panel3);
}
public static void main(String[] args)throws Exception {
Client display = new Client();
display.setVisible(true);
try{
displaysettings();
connect();
setup();
String message;
message = (String) in.readObject();
System.out.println(message);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
private static void displaysettings() {
portnumber.setText("3333");
servername.setText("localhost");
textbox.setText("This is where you type your messages to send to others on the server!");
}
private static void connect() throws UnknownHostException, IOException {
server1 = new Socket("localhost", 3333);
}
private static void setup() throws IOException {
out = new ObjectOutputStream(server1.getOutputStream());
out.flush();
in = new ObjectInputStream(server1.getInputStream());
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==connect)
{
System.out.println("connected");
isconnected = true;
connect.setEnabled(false);
disconnect.setEnabled(true);
}
if(e.getSource()==send)
{
System.out.println("sending chat");
sending = true;
}
if(e.getSource()==disconnect)
{
try {
server1.close();
out.close();
isconnected = false;
connect.setEnabled(true);
disconnect.setEnabled(false);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
Swing components will not update unless told to. After you set the text, call:
textbox.repaint();
to force the GUI to update.

issue in sending the socket output to GUI

I wrote this simple multi threaded chatroom, and I am trying to send the client/server output to GUI to display it in chatroom text area but I get null pointer exception at the following line:
output.write(line + "\n");
here is the full code for GUI:
import java.awt.*;
import javax.swing.*;
import javax.swing.JTextField;
import javax.swing.JFrame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import javax.swing.JButton;
import java.io.Writer;
public class GUI {
private JFrame frame;
private JButton btnSend, btnConnect;
private JTextArea txtChat;
private JTextField fldText, fldName;
private JList clientList;
private DefaultListModel listModel;
private JScrollPane sc, scClients;
private JPanel jpS2All, jpS2Client, jpS2Text;
private String Name;
private JLabel lblErr;
private Writer output;
public GUI(String Name, Writer output) {
this.Name = Name;
this.output = output;
}
public GUI() {
}
class handler implements ActionListener, MouseListener {
handler(String Name) {
}
handler() {
}
#Override
public void actionPerformed(ActionEvent e) {
clients(); //it seems this line made the error because it creates the
listModel.addElement(Name);//gui and sends the output to textSend actionlistener
//to display it in gui
//while the output is empty, right?
//is there any way to handle this?
}
#Override
public void mouseClicked(MouseEvent e) {
fldName.setText("");
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
} //end of handler
class textSend implements ActionListener {
textSend(String Name, Writer output) {
}
#Override
public void actionPerformed(ActionEvent e) {
String line = fldText.getText();
try {
output.write(line + "\n"); // the null exception error shows the
output.flush(); // error source at this line!
} catch (IOException ioe) {
txtChat.append("Other party hung up!");
}
String contenet = Name + ":" + output;
txtChat.append(contenet);
fldText.setText("");
}
}//end of textSend
public void creatServer() {
frame = new JFrame("enter");
frame.setBounds(50, 50, 300, 200);
btnConnect = new JButton("connect");
lblErr = new JLabel();
lblErr.setText("");
frame.add(btnConnect, BorderLayout.EAST);
fldName = new JTextField();
fldName.setText("enter your name");
fldName.addMouseListener(new handler());
btnConnect.addActionListener(new handler(getName()));
frame.add(fldName, BorderLayout.CENTER);
frame.setVisible(true);
}
public void clients() { //to create the chatroom GUI
frame = new JFrame("friends");
frame.setBounds(100, 100, 400, 400);
jpS2All = new JPanel();
txtChat = new JTextArea();
txtChat.setRows(25);
txtChat.setColumns(25);
txtChat.setEditable(false);
sc = new JScrollPane(txtChat);
jpS2All.add(sc);
frame.add(jpS2All, BorderLayout.WEST);
jpS2Text = new JPanel();
////////////////////////
fldText = new JTextField();
fldText.setColumns(34);
fldText.setHorizontalAlignment(JTextField.RIGHT);
fldText.addActionListener(new textSend(getName(), output));
jpS2Text.add(fldText);
frame.add(jpS2Text, BorderLayout.SOUTH);
/////////
jpS2Client = new JPanel();
listModel = new DefaultListModel();
clientList = new JList(listModel);
clientList.setFixedCellHeight(14);
clientList.setFixedCellWidth(100);
scClients = new JScrollPane(clientList);
frame.add(jpS2Client.add(scClients), BorderLayout.EAST);
/////////
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.pack();
}//end of clients
public String getName() {
Name = fldName.getText();
return Name;
}
public void appendText(final String message) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
txtChat.append(message);
}
});
}
}
server code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class server {
public void start() throws IOException {
ServerSocket serverSocket = new ServerSocket(1234);
while (true) {
Socket socket = serverSocket.accept();
ClientThread t = new ClientThread(socket);
t.start();
}
}
public static void main(String[] args) throws IOException {
server server = new server();
server.start();
}
class ClientThread extends Thread {
Socket socket;
InputStream sInput;
OutputStream sOutput;
GUI gui = new GUI();
String Name;
ClientThread(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
try {
BufferedReader sInput
= new BufferedReader(new InputStreamReader(socket.getInputStream()));
Writer sOutput = new OutputStreamWriter(socket.getOutputStream());
Name = gui.getName();
gui = new GUI(Name, sOutput);
try {
String line;
while ((line = sInput.readLine()) != null) {
gui.appendText(line);
}
} catch (IOException ex) {
Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (IOException e) {
}
}
}
}
client side:
import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class client {
private Socket s;
private String Name;
private GUI gui;
private Writer output;
private BufferedReader input;
public void start() {
try {
s = new Socket("127.0.0.1", 1234);
} catch (IOException ex) {
}
try {
input = new BufferedReader(new InputStreamReader(s.getInputStream()));
output = new OutputStreamWriter(s.getOutputStream());
} catch (IOException eIO) {
}
Name = gui.getName();
new GUI(Name, output);
new ListenFromServer().start();
}
public static void main(String[] args) {
client cl = new client();
GUI gui = new GUI();
gui.creatServer();
}
class ListenFromServer extends Thread {
public void run() {
try {
String line;
while ((line = input.readLine()) != null) {
gui.appendText(line);
}
} catch (IOException ex) {
Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
I know my question is a bit cumbersome but I really appreciate to help me handle this issue!
I am looking at your code and it is obvious that output is null when you attempt output.write(line + "\n"); Therefore I went and looked for the possible path of execution that could leave output un-initialized. This is where debugging comes in very handy.
Here is your execution path:
In your main method of client you create a new GUI and then call gui.creatServer();
public static void main(String[] args) {
client cl = new client();
GUI gui = new GUI();
gui.creatServer();
}
output has not been assigned and is still null
in the creatServer(); method you have this line:
fldName.addMouseListener(new handler());
which the actionPerformed method of handler calls the clients(); method which has the line:
fldText.addActionListener(new textSend(getName(), output));
note output is still null
(now your textSend class doesn't even do anything inside the constructor but that aside even if it did you are still using the output variable from the GUI class)
you have the actionPerformed method in the textSend class that has the line:
output.write(line + "\n");
Without ever initializing output it is still null, which gives you the NullPointer
Please see What is a NullPointerException, and how do I fix it? as #markspace linked in the comments. In addition you should really learn how to debug small programs.
See the following links:
http://ericlippert.com/2014/03/05/how-to-debug-small-programs/
http://blogs.msdn.com/b/smallbasic/archive/2012/10/09/how-to-debug-small-basic-programs.aspx
Again in addition, consider using Anonymous classes to ease up on those lines of code, which also makes the code easier to debug and more readable.
One last thought, remember to use standard Naming Conventions for the language you are using. your code currently has a lot of incorrect lowercase classes and some uppercase methods/properties.
the error message shows that one of the variable used in the expression was null. This may be either output or line.
As chancea already mentioned, you are calling the GUI() constructor with no arguments, so the output field is not initialized. You should remove the constructor with no arguments when you have no way to initialize the output field in it and only leave the one with arguments.

how can i display components in GUI server without a connected client?

I have a tabbed Jframe named Version3 which implements Runnable. Into it i have 3 JPanels in different tabbs.Next to those tabs i have a textarea.
I want my GUI to listen for messages and display them in the textarea. I tried to make my GUI Version3 a server which listens all the time in case it receives any message from client.
java.awt.EventQueue.invokeLater(new Runnable(){
public void run(){
Version3 v=new Version3();
v.setVisible(true);
v.listenTo();
}
});
I made my GUI Version3 a server but when i run the program the components of the GUI doesn't show until it's connected to client.I just have a blank GUI window with no components. Any ideas how to display all my components on my GUI without a client connected?
I made my GUI Version3 a server but when i run the program the
components of the GUI doesn't show until it's connected to client.I
just have a blank GUI window with no components. Any ideas how to
display all my components on my GUI without a client connected?
I think it's more than likely that you're blocking the Event Dispatching Thread (a.k.a. EDT) while your class is trying to connect to the client. That's the reason why it works when you have connection but it doesn't when you haven't. The EDT is a single and special thread where Swing component creation and updates take place. If you have a heavy task running in the EDT then your GUI will freeze and Swing components won't be able to work (or even display).
Take a look to Concurrency in Swing trail to learn about concurrency in Swing.
Off-topic: please consider add your code in future questions. As #alex2410 suggested it's better if you include a SSCCE demonstrating your problem.
Server:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Server extends JPanel {
Socket socket;
final static int PORT = 2325;
PrintWriter pr;
public ServerSocket serverSocket;
JButton btn_sendHello;
int counter;
Thread thread;
public Server() {
counter = 0;
btn_sendHello = new JButton("Send hello");
btn_sendHello.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (pr != null) {
pr.println("Hello from server " + ++counter);
}
}
});
this.add(btn_sendHello);
try {
serverSocket = new ServerSocket(PORT);
thread = new Thread(waitingClient);
thread.start();
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
Runnable waitingClient = new Runnable() {
#Override
public void run() {
try {
socket = serverSocket.accept();
openStreams();
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
};
private void openStreams() {
if (socket != null) {
try {
pr = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.setTitle("Server");
frame.add(new Server());
frame.pack();
frame.setSize(250, 100);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
Client:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Client extends JPanel {
final static int PORT = 2325;
private Socket socket;
private BufferedReader fromServer;
private JTextField jtfield;
Thread threadReceive;
public Client() {
jtfield = new JTextField(12);
this.add(jtfield);
try {
socket = new Socket("localhost", PORT);
openStreams();
Thread thread = new Thread(receives);
thread.start();
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
Runnable receives = new Runnable() {
#Override
public void run() {
while (true) {
synchronized (this) {
if (socket != null) {
processServerInput();
}
}
}
}
};
private void openStreams() {
try {
if (socket != null) {
fromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void processServerInput() {
try {
String line = fromServer.readLine();
while (!(line.equals("Bye"))) {
jtfield.setText(line);
line = fromServer.readLine();
}
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
void closeStreams() {
try {
fromServer.close();
socket.close();
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.setTitle("Client");
frame.add(new Client());
frame.pack();
frame.setSize(250, 100);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}

Content in JFrame doesn't show when called from a specific method

The content in the JFrame WaitingFrame doesn't show up as expected. This is in essence what I am trying to do:
package org.brbcoffee.missinggui;
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Main {
public static KeynoteServer server;
public static void main(String[] args){
JFrame frame = new JFrame("SSCCE");
JButton btn = new JButton("Test");
btn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
connectToPhone();
}
});
frame.add(btn);
frame.pack();
frame.setVisible(true);
}
public static void connectToPhone(){
WaitingFrame wf = new WaitingFrame();
wf.setVisible(true);
server = new KeynoteServer();
if (server.setup()){
System.out.println("Server set up and connected");
} else {
System.out.println("Couldn't connect");
}
wf.dispose();
}
}
#SuppressWarnings("serial")
class WaitingFrame extends JFrame {
public WaitingFrame(){
setTitle("Waiting");
this.setLocationByPlatform(true);
JLabel label = new JLabel("Waiting for client..."); // This will never show
JPanel content = new JPanel();
content.add(label);
this.add(content);
pack();
}
}
class KeynoteServer{
private int port = 55555;
private ServerSocket server;
private Socket clientSocket;
public boolean setup() {
try {
server = new ServerSocket(55555);
server.setSoTimeout(10000);
clientSocket = server.accept();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
}
When setup() is called the WaitingFrame does indeed show up, but the contents are missing. I've tried different image formats, but it does work from other methods and classes, so that shouldn't matter. Does anyone know what's going on here?
Use SwingUtilities.invokeLater()/invokeAndWait() to show your frame because all the GUI should be updated from EDT.

Categories