Text not showing up in Jframes in my GUI - java

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.

Related

Game with server and multiple client, make sure only one game object is created

I'm trying to write a poker server and client program, I create the game in the server class and my client class takes the output and displays them. However, when ever i do this, there seem to be two game objects created, the first player gets the input that is consistent with the object that is shown in the console, the second player always displays cards that are not shown in the sysout method, and I can not seem to find where I created the second game object.
server class:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashSet;
public class PokerServer {
/**
* The port that the server listens on.
*/
private static final int PORT = 9050;
// keeps track of all the names
private static ArrayList<String> names = new ArrayList<String>();
// broadcast messages
private static ArrayList<PrintWriter> writers = new ArrayList<PrintWriter>();
private boolean bothPlayersConnected = false;
/**
* The appplication main method, which just listens on a port and spawns
* handler threads.
*/
public static void main(String[] args) throws Exception {
System.out.println("The poker server is running.");
ServerSocket listener = new ServerSocket(PORT);
try {
while (true) {
new GameThread(listener.accept()).start();
}
} finally {
listener.close();
}
}
private static class GameThread extends Thread {
private String name;
private Socket socket;
private BufferedReader in;
private PrintWriter out;
private Game game;
public GameThread(Socket socket) {
this.socket = socket;
}
/**
* Services this thread's client by repeatedly requesting a screen name
* until a unique one has been submitted, then acknowledges the name and
* registers the output stream for the client in a global set, then
* repeatedly gets inputs and broadcasts them.
*/
public void run() {
try {
System.out.println("get to this part");
// Create character streams for the socket.
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
// get the name of the player
out.println("SUBMITNAME");
name = in.readLine();
names.add(name);
while(names.size()<2){
out.println("MESSAGE waiting for opponent to connect");
}
// Now that a successful name has been chosen, add the
// socket's print writer to the set of all writers so
// this client can receive broadcast messages.
// out.println("NAMEACCEPTED");
// writers.add(out);
game = new Game(names.get(0), names.get(1), 1000);
game.dealToPlayers();
out.println(names.get(0) + game.getPlayer1().getHand()[0].transferStr());
out.println(names.get(0) + game.getPlayer1().getHand()[1].transferStr());
out.println(names.get(1) + game.getPlayer2().getHand()[0].transferStr());
out.println(names.get(1) + game.getPlayer2().getHand()[1].transferStr());
// Accept messages from this client and broadcast them.
// Ignore other clients that cannot be broadcasted to.
while (true) {
String input = in.readLine();
if (input == null) {
return;
} else if (input.startsWith(names.get(0))) {
}
for (PrintWriter writer : writers) {
writer.println("MESSAGE " + name + ": " + input);
}
}
} catch (IOException e) {
System.out.println(e);
} finally {
// This client is going down! Remove its name and its print
// writer from the sets, and close its socket.
if (name != null) {
names.remove(name);
}
if (out != null) {
writers.remove(out);
}
try {
socket.close();
} catch (IOException e) {
}
}
}
}
}
Client class
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class PokerClient {
BufferedReader in;
PrintWriter out;
String playerName = "Poker";
JFrame frame = new JFrame(playerName);
JPanel playerHandPanel, controlPanel, bottomPanel, topPanel, messageBoard;
JButton check, fold;
JTextField textField = new JTextField(10);
JLabel firstLine = new JLabel("");
String serverAddress = "localhost";
Card playerHand1, playerHand2;
public PokerClient() {
// Layout GUI
frame.setSize(1100, 700);
frame.setResizable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
playerHandPanel = new JPanel(new GridLayout(1, 0));
playerHandPanel.setPreferredSize(new Dimension(600, 300));
playerHandPanel.setVisible(true);
topPanel = new JPanel(new GridLayout(1, 0));
topPanel.setPreferredSize(new Dimension(900, 300));
topPanel.setVisible(true);
messageBoard = new JPanel(new GridLayout(0, 1));
messageBoard.add(firstLine);
controlPanel = new JPanel();
controlPanel.setPreferredSize(new Dimension(600, 40));
controlPanel.setVisible(true);
topPanel.add(messageBoard);
check = new JButton("Check");
check.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
out.println(playerName+"CHECK");
}
});
fold = new JButton("fold");
fold.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
out.println(playerName+"FOLD");
}
});
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(isInt(textField.getText())){
out.println(textField.getText());
textField.setText("");
} else{
JFrame frame = new JFrame("Not a number");
frame.setSize(600, 70);
frame.setLocation(400, 250);
frame.setResizable(false);
JLabel label = new JLabel("You must enter a number in order to raise");
frame.add(label);
frame.setVisible(true);
frame.toFront();
frame.repaint();
textField.setText("");
}
}
});
controlPanel.add(check);
controlPanel.add(fold);
controlPanel.add(new JLabel(" Raise:"));
controlPanel.add(textField);
bottomPanel = new JPanel();
bottomPanel.add(controlPanel, BorderLayout.SOUTH);
bottomPanel.add(playerHandPanel, BorderLayout.NORTH);
frame.add(topPanel, BorderLayout.NORTH);
frame.add(bottomPanel, BorderLayout.SOUTH);
//frame.add(firstLine, "SOUTH");
frame.setVisible(true);
}
private static boolean isInt(String s)
{
try
{ int i = Integer.parseInt(s); return true; }
catch(NumberFormatException er)
{ return false; }
}
/**
* Prompt for and return the desired screen name.
*/
private String getName() {
return JOptionPane.showInputDialog(
frame,
"Choose a screen name:",
"Screen name selection",
JOptionPane.PLAIN_MESSAGE);
}
private Card constructCard(String line){
int seperator = line.indexOf('/');
int cardNum = Integer.parseInt(line.substring(0, seperator));
Card card;
if(line.substring(seperator+1).startsWith("S")){
card = new Card(cardNum, Suit.SPADE);
} else if(line.substring(seperator+1).startsWith("C")){
card = new Card(cardNum, Suit.CLUB);
} else if(line.substring(seperator+1).startsWith("D")){
card = new Card(cardNum, Suit.DIAMOND);
} else{
card = new Card(cardNum, Suit.HEART);
}
System.out.println(card.toString());
return card;
}
/**
* Connects to the server then enters the processing loop.
*/
private void run() throws IOException {
Socket socket = new Socket(serverAddress, 9050);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
// Process all messages from server, according to the protocol.
while (true) {
String line = in.readLine();
System.out.println(line);
if (line.startsWith("SUBMITNAME")) {
String name = getName();
playerName = name;
out.println(name);
frame.setTitle(playerName);
} else if (line.startsWith(playerName)) {
playerHandPanel.add(new CardComponent(constructCard(line.substring(playerName.length()))));
playerHandPanel.revalidate();
playerHandPanel.repaint();
} else if(line.startsWith("CARD")){
topPanel.add(new CardComponent(constructCard(line.substring(4))));
topPanel.revalidate();
topPanel.repaint();
} else if(line.startsWith("MESSAGE")){
firstLine.setText(line.substring(7));
}
}
}
public static void main(String[] args) throws Exception {
PokerClient client = new PokerClient();
client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
client.frame.setVisible(true);
client.run();
}
}

I am doing a multiclient chat sever program in java. But I am not able to run it. Here is my code for multi client server

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;
import javax.swing.*;
/* The code is able to run single client but not multiple client. When I run this program with my client class it is able to handle only one client. While I run multiple threads it lost its communication with the first thread. I don't know why. */
public class MultipleChatClient extends JFrame{
Vector<HandleAClient> clients = new Vector<HandleAClient>();
JButton btnSend = null;
JButton btnExit = null;
JTextArea taMessages = null;
JTextField tfInput = null;
BufferedReader br = null;
PrintWriter pw = null;
ServerSocket server = null;
Socket socket = null;
int clientNumber = 0;
public MultipleChatClient(){
this.Interface(); /* creates GUI */
try{
server = new ServerSocket(8900);
while(true){
socket = server.accept();
HandleAClient task = new HandleAClient(socket); /* add every client to vector */
clients.add(task);
new Thread(task).start();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
public class HandleAClient implements Runnable{ /* multithreaded class to handle multiclients */
private Socket socket;
public HandleAClient(Socket socket){
clientNumber++;
this.socket = socket;
}
public void run(){
try{
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(), true);
while(true){
String line = br.readLine();
taMessages.append("Client Number " + clientNumber + " said: ");
taMessages.append(line + "\n");
}
}
catch(IOException ex){
ex.printStackTrace();
}
catch(Exception e){
taMessages.append("Connection Lost");
}
}
public void sendMessage() {
pw.println(tfInput.getText());
}
}
public void Interface(){ /* to build GUI */
setLayout(new BorderLayout());
btnSend = new JButton("Send");
btnExit = new JButton("Exit");
taMessages = new JTextArea();
taMessages.setRows(10);
taMessages.setColumns(50);
taMessages.setEditable(false);
tfInput = new JTextField(50);
JPanel but = new JPanel(new GridLayout(2,1,5,10));
but.add(btnSend);
but.add(btnExit);
JScrollPane sp = new JScrollPane(taMessages, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
add(sp,"Ce`enter code here`nter");
JPanel bp = new JPanel(new BorderLayout());
bp.add(tfInput, BorderLayout.CENTER);
bp.add(but, BorderLayout.EAST);
add(bp, BorderLayout.SOUTH);
btnSend.addActionListener(new buttonListner());
//btnSend.addKeyListener(new buttonListner());
btnExit.addActionListener(new buttonListner());
setSize(600,600);
setTitle("Server");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
//pack();
}
public class buttonListner implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btnExit){
System.exit(1);
}
else{
taMessages.append("You Said: ");
taMessages.append(tfInput.getText() + "\n");
for(HandleAClient c: clients){
c.sendMessage();
}
tfInput.setText(null);
}
}
}
public static void main(String[] args) {
new MultipleChatClient();
}
}
You have to use Multi-threading. Create a new Thread for each client connected to the server.
I have already posted some of the samples in the same context.
Please have a look at below posts. It might help you to understand it.
Java Server with Multiclient communication.
Multiple clients access the server concurrently

Display connected client in jtextarea

I want to be able to detect any connected clients and display them on my JTextArea.
Here is my server code
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
public class serveur extends Thread {
final static int port = 9632;
private Socket socket;
private JTextArea clien;
private String res;
public static void main(String[] args) {
// window
final int windowX = 640; //pixels
final int windowY = 500; //pixels
final FlowLayout LAYOUT_STYLE = new FlowLayout();
JFrame window = new JFrame("admin");
window.setSize(windowX, windowY);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel liste = new JLabel("Clients connectés ");
JTextArea clien = new JTextArea(20,50);
clien.setEditable(false);
JButton captureButton = new JButton("Capture d'écran");
JButton partageButton = new JButton("Partage d'écran");
JButton envoiButton = new JButton("Envoi de fichier");
JButton lancementButton = new JButton("Lancement d'une application");
JButton redémarrageButton = new JButton("Redémarrage de la machine");
JButton infoButton = new JButton("Plus d'information");
Container c = window.getContentPane();
c.setLayout(LAYOUT_STYLE);
c.add(captureButton);
c.add(partageButton);
c.add(envoiButton);
c.add(redémarrageButton);
c.add(infoButton);
c.add(lancementButton);
c.add(liste);
c.add(clien);
c.add(new JSeparator(SwingConstants.VERTICAL));
window.setVisible(true);
//serveur
try{
ServerSocket socketServeur = new ServerSocket(port);
System.out.println("Lancement du serveur");
while (true) {
Socket socketClient = socketServeur.accept();
serveur t = new serveur(socketClient);
t.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
//socketServeur.setOption("reuseAddress", true);
public serveur(Socket socket) {
this.socket = socket;
}
public void traitements() {
try {
clien.append(socket.getInetAddress().getHostName());
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
traitements();
}
}
And the client code :
import java.net.*;
import java.io.*;
public class client {
final static int port = 9632;
public static void main(String[] args) {
Socket socket;
try {
socket = new Socket(InetAddress.getLocalHost(), port);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I guess the problem is with the correct placement of this line
clien.append(socket.getInetAddress().getHostName());
Any suggestions
in the traitements () just before client.append you need to add the folowing code :
BufferedReader brBufferedReader1 = new BufferedReader(new InputStreamReader(connection.getInputStream()));
Client.append(brBufferedReader1.readLine());

Chat program freezes JFrame

I'm writing a simply chat client and am moving it over to a nice GUI. The constructor for the server side (client side is android) contains a list that's in the JFrame, and the first part of the server runs, but then the entire frame locks up. Does anyone see the issue? Sorry for the relatively disorganized, not cleanly commented code...
Server:
import java.awt.List;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
public class ChatServer {
private final int CHAT_PORT = 4453;
ServerSocket sSocket;
Socket cSocket;
PrintWriter pWriter;
BufferedReader bReader;
InetAddress localAddr;
List messageList;
public ChatServer(List entList)
{
messageList = entList;
}
public synchronized void run()
{
messageList.add("Chat Server Starting...");
try {
localAddr = InetAddress.getLocalHost();
} catch (UnknownHostException e1) {
messageList.add("InnetAddress error");
}
while(true)
{
try {
sSocket = new ServerSocket(CHAT_PORT);
sSocket.setReuseAddress(true);
messageList.add("Server has IP:" + localAddr.getHostAddress());
messageList.add("Server has hostname:" + localAddr.getHostName());
messageList.add("Server has port:" + CHAT_PORT);
} catch (IOException e) {
//ERRORS
if(cSocket.isConnected())
{
messageList.add("User disconnected\n");
try {
cSocket.close();
} catch (IOException e1) {
messageList.add("Error closing client socket");
}
}
else
{
messageList.add("ERROR CREATING SOCKET\n");
}
}
try {
cSocket = sSocket.accept();
cSocket.setReuseAddress(true);
messageList.add("INFO: socket connected");
} catch (IOException e) {
messageList.add("Client Socket Error");
System.exit(-1);
}
try {
pWriter = new PrintWriter(cSocket.getOutputStream(), true);
messageList.add("INFO: Print writer opened");
} catch (IOException e) {
messageList.add("PrintWriter error");
}
try {
bReader = new BufferedReader(new InputStreamReader(cSocket.getInputStream()));
messageList.add("INFO: buffered reader opened");
} catch (IOException e) {
messageList.add("BufferedReader error");
}
String inputLine;
try {
while((inputLine = bReader.readLine()) != null)
{
messageList.add(inputLine);
if(inputLine.equals("close"))
{
close();
}
}
} catch (IOException e) {
messageList.add("Buffered Reader error");
}
}
}
public synchronized void close()
{
messageList.add("****Server closing****");
try {
sSocket.close();
} catch (IOException e) {
messageList.add("Error closing server socket");
}
try {
cSocket.close();
} catch (IOException e) {
messageList.add("Error closing client socket");
}
pWriter.close();
try {
bReader.close();
} catch (IOException e) {
messageList.add("Error closing buffered reader");
}
messageList.add("****It's been fun, but I've got to go.****\n****Server has shut down.****");
System.exit(0);
}
}
GUI:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.List;
import java.awt.Toolkit;
#SuppressWarnings("serial")
public class ClientGUI extends JFrame {
private JPanel contentPane;
private JTextField txtEnterTextHere;
private JMenuBar menuBar;
private List messageList;
private JMenu mnOptions;
private JMenu mnHelp;
private JMenuItem mntmStartServer;
private JMenuItem mntmStopServer;
private JMenuItem mntmConnectionInfo;
private JMenuItem mntmEmailDeveloper;
private static String userName;
private ChatServer cServer;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ClientGUI frame = new ClientGUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ClientGUI() {
setTitle("Ben's Chat Client");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmExit = new JMenuItem("Exit");
mntmExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showConfirmDialog(null, "Are you sure you want to exit?");
}
});
mnFile.add(mntmExit);
mnOptions = new JMenu("Options");
menuBar.add(mnOptions);
mntmStartServer = new JMenuItem("Start Server");
mntmStartServer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ChatServer cServer = new ChatServer(messageList);
cServer.run();
}
});
mnOptions.add(mntmStartServer);
mntmStopServer = new JMenuItem("Stop Server");
mnOptions.add(mntmStopServer);
mntmConnectionInfo = new JMenuItem("Connection Info");
mnOptions.add(mntmConnectionInfo);
mnHelp = new JMenu("Help");
menuBar.add(mnHelp);
mntmEmailDeveloper = new JMenuItem("Email Developer");
mnHelp.add(mntmEmailDeveloper);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
txtEnterTextHere = new JTextField();
txtEnterTextHere.setBounds(10, 220, 334, 20);
txtEnterTextHere.setText("Enter text here...");
contentPane.add(txtEnterTextHere);
txtEnterTextHere.setColumns(10);
JButton btnSend = new JButton("Send");
btnSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
messageList.add(userName + ": " + txtEnterTextHere.getText().toString());
}
});
messageList = new List();
btnSend.setBounds(349, 219, 85, 23);
contentPane.add(btnSend);
messageList.setBounds(10, 10, 424, 204);
contentPane.add(messageList);
}
public static String getUsername()
{
return userName;
}
public static void setUsername(String entName)
{
userName = entName;
}
}
Thanks!
It looks like you're starting the server on the Swing thread (see: The Event Dispatch Thread). As soon as you call cServer.run(); in the ActionListener, you are blocking the EDT from doing anything else (such as updating your JFrame and responding to events). Start your server in a background thread instead:
new Thread(new Runnable()
{
#Override
public void run()
{
// start your server
}
}).start();

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