The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.
|
 |
|
Dev Shed Forums
> Programming Languages
> Java Help
|
How to display text on JTextField from another class?
Discuss How to display text on JTextField from another class? in the Java Help forum on Dev Shed. How to display text on JTextField from another class? Java Help forum discussing all Java platforms - J2ME, J2SE and J2EE - as well as relevant standards, APIs and frameworks such as Swing, Servlets, JSPs, Applets, Struts, Spring, Hibernate, ANT, EJB, and other Java-related topics.
|
|
 |
|
|
|
|

Dev Shed Forums Sponsor:
|
|
|

November 21st, 2009, 01:58 AM
|
|
Registered User
|
|
Join Date: Sep 2009
Posts: 6
Time spent in forums: 1 h 26 m 6 sec
Reputation Power: 0
|
|
|
How to display text on JTextField from another class?
I'm trying to make a Server (command prompt) & Client (GUI based) program where I can type the name of a text file in my Client program. The Client will send the name of the text file to Server. Server will read the file name and read the content of that file. The Server will finally "should" display the text content of that file back to Client's JTextArea. I did all the steps above with the exception that my Server keeps displaying the content on its own command prompt instead of sending it back to Client's JTextArea. Any help?
Client
Code:
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Client extends JFrame
{
private JTextField enterField;
private JTextArea displayArea;
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private String chatServer;
private Socket client;
public static void main(String[] args)
{
Client application;
if(args.length == 0)
application = new Client("127.0.0.1");
else
application = new Client(args[0]);
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.runClient();
}
public Client(String host)
{
super("Client");
chatServer = host;
//set server to which this client connects
Container container = getContentPane();
enterField = new JTextField();
//create enterField and register listener
enterField.setEnabled(false);
enterField.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
//send message to server
{
sendData(event.getActionCommand());
}
});
// end call to addActionListener
container.add(enterField, BorderLayout.NORTH);
displayArea = new JTextArea();
container.add(new JScrollPane(displayArea), BorderLayout.CENTER);
setSize(500, 350);
setVisible(true); }
public void runClient()
//connect to server and process message from server
{
try
//connect to server, get streams, process connection
{
connectToServer();
//step 1 create socket to make connection
getStreams();
//step 2 get input and output stream
processConnection();
//step 3 process connection
closeConnection();
//step 4 close connection
}
//server close connection
catch(EOFException eofException)
{
System.out.println("Server terminated connection");
}
catch(IOException ioException)
{
ioException.printStackTrace();
}
}
private void getStreams() throws
IOException
//get stream to send and receive data
{
output = new ObjectOutputStream(client.getOutputStream());
//set up output stream for objects
output.flush();
input = new ObjectInputStream(client.getInputStream());
//set up input stream for objects
displayArea.append("\nGot Input & Output Stream\n");
}
private void connectToServer() throws IOException
//connect to server
{
displayArea.setText("Attempting connection\n");
client = new Socket(InetAddress.getByName(chatServer), 8189);
//create socket to make connection to server
displayArea.append("Connect to: " + client.getInetAddress().getHostName());
//display connection information
}
private void processConnection() throws IOException
//process connection with server
{
enterField.setEnabled(true);
//enable enterField so client user can send messages
do
//process message sent from server
{
try
//read message and display it {
message = (String) input.readObject();
displayArea.append("\n" + message);
displayArea.setCaretPosition(displayArea.getText().length());
}
catch(ClassNotFoundException classNotFoundException)
{
displayArea.append("\nUnknown object type received");
}
}while(!message.equals("TERMINATE"));
}//end method process connection
private void closeConnection() throws IOException
//close streams and socket
{
displayArea.append("\nClosing connection");
output.close();
input.close();
client.close();
}
private void sendData(String message)
//send message to server
{
try //send object to sever
{
output.writeObject("" + message);
output.flush();
displayArea.append("\n" + message);
}
catch(IOException ioException)
//process problems sending object
{
displayArea.append("\nError writing object");
}
}
}//end class Client
Server
Code:
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Server
{
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
private int counter = 1;
private String file1;
public static void main( String args[] )
// execute application
{
Server application = new Server();
application.runServer();
}
public Server()
{
}
// set up and run server
public void runServer()
{
try
// set up server to receive connections & process connections
{
server = new ServerSocket( 8189, 50 );
// Step 1: Create a ServerSocket.
while ( true )
{
waitForConnection();
// Step 2: Wait for a connection.
getStreams();
// Step 3: Get input and output streams.
processConnection();
// Step 4: Process connection.
closeConnection();
// Step 5: Close connection.
//++counter;
}
}
catch ( EOFException eofException )
// process EOFException when client closes connection
{
System.out.println( "Client terminated connection" );
}
catch ( IOException ioException )
// process problems with I/O
{
ioException.printStackTrace();
}
}
private void waitForConnection() throws IOException
// wait for connection to arrive, then display connection info
{
System.out.println( "Waiting for connection\n" );
connection = server.accept();
// allow server to accept a connection
System.out.println( "Connection " + counter + " received from: " + connection.getInetAddress().getHostName() );
}
private void getStreams() throws IOException
// get streams to send and receive data
{
output = new ObjectOutputStream( connection.getOutputStream() );
// set up output stream for objects
output.flush();
// flush output buffer to send header information
input = new ObjectInputStream( connection.getInputStream() );
// set up input stream for objects
}
// process connection with client
private void processConnection() throws IOException
{
String message = "SERVER>>> Connection successful, Please name the file";
// send connection successful message to client
output.writeObject( message );
output.flush();
do
{
// process messages sent from client
try
{
message = ( String ) input.readObject();
// read message and display it
File file1 = new File(message);
if(file1.exists() && file1.isFile())
{
BufferedReader in = new BufferedReader(new FileReader(file1));
//String myFile = "";
String line = in.readLine();
while(line != null)
{
//myFile += line + "\n";
line = in.readLine();
System.out.println("" + line);
}
in.close();
}
else
{
System.out.println("File does not exist");
}
}
catch ( ClassNotFoundException classNotFoundException )
// catch problems reading from client
{
System.out.println( "\nUnknown object type received" );
}
} while ( !message.equals( "TERMINATE" ) );
}
private void closeConnection() throws IOException
// close streams and socket
{
System.out.println( "\nUser terminated connection" );
output.close();
input.close();
connection.close();
}
private void sendData( String message )
// send message to client
{
try
// send object to client
{
output.writeObject( "SERVER>>> " + message );
output.flush();
//System.out.println( "\nSERVER>>>" + message );
}
catch ( IOException ioException )
// process problems sending object
{
System.out.println( "\nError writing object" );
}
}
} // end class Server
|

November 21st, 2009, 02:07 AM
|
 |
<?PHP user_title("gimp"); ?>
|
|
Join Date: Jan 2005
Location: Internet
|
|
|
If you properly format tabbing we'll be able to read your code a lot easier. As it stands I don't think many people will want to dig through it...
__________________
Chat Server Project & Tutorial | WiFi-remote-control sailboat (building) | Joke Thread
“Rational thinkers deplore the excesses of democracy; it abuses the individual and elevates the mob. The death of Socrates was its finest fruit.”
Use XXX in a comment to flag something that is bogus but works. Use FIXME to flag something that is bogus and broken. Use TODO to leave yourself reminders. Calling a program finished before all these points are checked off is lazy.
-Partial Credit: Sun
If I ask you to redescribe your problem, it's because when you describe issues in detail, you often get a *click* and you suddenly know the solutions.
Ches Koblents
|

November 21st, 2009, 02:09 AM
|
|
Registered User
|
|
Join Date: Sep 2009
Posts: 6
Time spent in forums: 1 h 26 m 6 sec
Reputation Power: 0
|
|
Quote: | Originally Posted by gimp If you properly format tabbing we'll be able to read your code a lot easier. As it stands I don't think many people will want to dig through it... |
How do I format TAB? When I press Tab, the cursor keeps moving to other window.
|

November 21st, 2009, 04:53 AM
|
|
|
Quote: | Originally Posted by Jaru How do I format TAB? When I press Tab, the cursor keeps moving to other window. |
Copy the code into a text editor, add the tab spaces and paste it back into the submission box.
|

November 21st, 2009, 06:14 AM
|
 |
Lord of the Dance
|
|
|
|
Quote: | Originally Posted by Jaru How do I format TAB? When I press Tab, the cursor keeps moving to other window. |
Where from did you copy the code first time? isn't the code formatted that place?
|

November 21st, 2009, 08:52 AM
|
|
Contributing User
|
|
Join Date: Oct 2004
Location: the Netherlands
|
|
|
As it is now (as far as I can read it all) the server prints the file contents to the console through the System.out stream; I don't think you want that.
Another (more important?) thing is that the server should be able to read the file from its own file system; what are you going to do if this is not so? (e.g. the client runs from your home while the server runs at my place).
kind regards,
Jos
|
Developer Shed Advertisers and Affiliates
| Thread Tools |
Search this Thread |
|
|
|
| Display Modes |
Rate This Thread |
Linear Mode
|
|
Posting Rules
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
|
|
|
|
|