I'm trying to implement a program where the client will send a fix message to the server side, and the UI I have for the server side will show up the FIX message on the text area.
However when I start the program, the textfields and all the labels will show, except the text area. And when I try send a message from the client side, everything works besides the text area.
code
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.awt.*; // using AWT containers and components
import java.awt.event.*; // using AWT events and listener interfaces
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class TcpServerCompareCSV extends Frame implements ActionListener , WindowListener {
private Label lblPort; // declare component Label
private TextField tfPort; // declare component TextField
private int port; // port number
private Label lblLocation; // declare component Label
private TextField tfLocation; // declare component TextField
private String fileLocation; // csv file location
private Button btnCount; // declare component Button //________________________________________________________________________________\\
private Label lblCSVLine; // declare component Label from csv file line, server side
private TextField tfCSVLine; // declare component TextField from csv file line, server side
private String CSVLine; // port number
private Label lblFIXMsg; // declare component Label from csv file line, server side
private JTextArea tfFIXMsg; // declare component TextField from csv file line, server side
private String FIXMsg; // port number
private JScrollPane jScrollPane1;//________________________________________________________________________________\\
/** WindowEvent handlers */
// Called back upon clicking close-window button
#Override
public void windowClosing(WindowEvent e) {
System.exit(0); // terminate the program
}
//constructor for frame
public TcpServerCompareCSV () {
setLayout(new FlowLayout());
// "this" Frame sets its layout to FlowLayout, which arranges the components
// from left-to-right, and flow to next row from top-to-bottom.
lblPort = new Label("Port"); // construct Label
add(lblPort); // "this" Frame adds Label
tfPort = new TextField("0", 40); // construct TextField
tfPort.setEditable(true); //edit text
add(tfPort); // "this" Frame adds tfCount
// tfPort.addActionListener(this); // for event-handling
lblLocation = new Label("CSV File Location"); // construct Label
add(lblLocation); // "this" Frame adds Label
tfLocation = new TextField("text", 40); // construct TextField
tfLocation.setEditable(true); //edit text
add(tfLocation); // "this" Frame adds tfCount
//________________________________________________________________________________\\
setTitle("compare"); // "this" Frame sets title
setSize(800,200); // "this" Frame sets initial window size
setVisible(true); // "this" Frame shows
lblCSVLine = new Label("CSV Line"); // construct Label
add(lblCSVLine); // "this" Frame adds Label
tfCSVLine = new TextField("text", 40); // construct TextField
tfCSVLine.setEditable(false); //edit text
add(tfCSVLine); // "this" Frame adds tfCount
lblFIXMsg = new Label("FIX message from client"); // construct Label
add(lblFIXMsg); // "this" Frame adds Label
tfFIXMsg = new JTextArea(); // construct TextField
tfFIXMsg.setColumns(20);
tfFIXMsg.setLineWrap(true);
tfFIXMsg.setRows(50);
tfFIXMsg.setWrapStyleWord(true);
tfFIXMsg.setEditable(false); //edit text
add(tfFIXMsg); // "this" Frame adds tfCount
jScrollPane1 = new JScrollPane(tfFIXMsg);
add(jScrollPane1);
btnCount = new Button("Enter"); // construct Button
add(btnCount); // "this" Frame adds Button
btnCount.addActionListener(this); // for event-handling
addWindowListener(this);
// "this" Frame fires WindowEvent its registered WindowEvent listener
// "this" Frame adds "this" object as a WindowEvent listener
}
/** ActionEvent handler - Called back when user clicks the button. */
#Override
public void actionPerformed(ActionEvent evt) {
// Get the String entered into the TextField tfPort, convert to int
port = Integer.parseInt(tfPort.getText());
fileLocation = tfLocation.getText();
String csvName = fileLocation;
/*
Scanner console = new Scanner(System.in);
System.out.println("Type in CSV file location: ");
//String csvName = console.nextLine();
String csvName = "C:\\Users\\I593458\\Downloads\\orders.csv";
*/
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
}
catch (IOException e)
{
System.err.println("Could not listen on port: 57635.");
System.exit(1);
}
Socket clientSocket = null;
System.out.println ("Waiting for connection.....");
try {
clientSocket = serverSocket.accept();
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
System.out.println ("Connection successful");
System.out.println ("Waiting for input.....");
PrintWriter out = null;
try {
out = new PrintWriter(clientSocket.getOutputStream(),
true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader in = null;
try {
in = new BufferedReader(
new InputStreamReader( clientSocket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String inputLine, outputLine;
try {
while ((inputLine = in.readLine()) != null)
{
System.out.println ("Server: " + inputLine);
tfFIXMsg.setText(inputLine);
if (inputLine.trim().equals("Bye.")) {
System.out.println("Exit program");
break;
}
Scanner input1 = new Scanner(new File(csvName));
Scanner input2 = new Scanner(new File(csvName));
Scanner input3 = new Scanner(new File(csvName));
Scanner input4 = new Scanner(new File(csvName));
String csvline = getCsvLineVal (getLocation34CSV(getTag34Value(Tag34Location(getTagCSV( parseFixMsg(inputLine ,inputLine))), getValueCSV( parseFixMsg(inputLine ,inputLine))), getVal34(input1, input2)), getCSVLine( input3, input4) );
outputLine = compareClientFixCSV( getTagCSV( parseFixMsg(inputLine ,inputLine)), getValueCSV(parseFixMsg(inputLine ,inputLine)), getCSVTag(csvline), getCSVValue(csvline));
out.println(outputLine);
tfCSVLine.setText(outputLine);
input1.close();
input2.close();
input3.close();
input4.close();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.close();
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You add the textArea to a JScrollPane, and then never do anything with the pane.
jScrollPane1 = new JScrollPane(tfFIXMsg);
You need add(jScrollPane1);
Related
package kebek;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
public class Kebek extends JFrame implements ActionListener {
String mainFileName; // the file name the user entered
String essay; // the data the user wrote in the text field
public Kebek() {
// set up the title of the frame
super("Kebek Text Editor");
//or setTitle("Kebek Text Editor");
//must be added to customize apeariance
this.setLookAndFeel();
// set the size of the frame - in px
this.setSize(500, 1000);
// or pack(); - this The pack() method sets the frame big enough
//to hold the preferred size of
//each component inside the frame (but no bigger)
// exits the program when x button is clicked
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Choose layout to give to our frame
FlowLayout flo = new FlowLayout();
// associate the manager with the container.
this.setLayout(flo);
// creating save button and adding it into layout
JButton saveButton = new JButton("Save");
// make save button listen for button clicks
saveButton.addActionListener(this);
JButton openButton = new JButton("Open");
openButton.addActionListener(this);
this.add(saveButton);
this.add(openButton);
// create text fields and add them to our layout
JLabel fileNameLabel = new JLabel("file name: ", JLabel.RIGHT);
JTextField fileNameText = new JTextField(20);
// create writing area
JTextArea editSpace = new JTextArea(40, 40);
String editSpaceText = editSpace.getText();
this.add(fileNameLabel);
this.add(fileNameText);
this.add(editSpace);
//
String fileNameStr = fileNameText.getText();
//
this.essay = editSpaceText;
this.mainFileName = fileNameStr;
// makes the frame visible
this.setVisible(true);
}
// needed for to customize our frame
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception exc) {
// do nothing
}
}
// save file method
public void saveFile() {
try {
// write the string on to a file
FileWriter writeFile = new FileWriter(this.mainFileName + ".txt");
BufferedWriter buffWrite = new BufferedWriter(writeFile);
buffWrite.write(this.essay);
buffWrite.close();
} catch (IOException ex) {
System.out
.println("There is an error with the" + this.mainFileName);
}
}
// action performed method - event handler
#Override
public void actionPerformed(ActionEvent event) {
// listen to what button is pressed
String cmd = event.getActionCommand();
this.saveFile();
// // if save button is pressed save file
// if (cmd.equals("save")) {
// System.out.println(" This is the result of cmd" + cmd);
//
// // if the open button is presses open file
// this.saveFile();
// } else if (cmd.equals("open")) {
//
// // else do nothing
// } else {
//
// }
}
public static void main(String[] argus) {
Kebek kebekframe = new Kebek();
}
}
What I want to do is when save button is pressed, a .txt file with a file name of the user's choice is created(string from fileNameStr). The file should contain the words they typed in the text field(editSpaceText) I provided. Also When i run this code, it does not give me an error. It is highly likely the problem is in my saveFile & actionPreformed methods.
You do not assign the contents of the JTextArea to the variable essay at a relevant point of time - you assign it in the constructor, but the JTextArea is likely empty.
There is no magical link between the JTextArea's text and the essay variable
The first thing you need to do is make the relevant components available to other parts of your class, by making them instance fields...
public class Kebek extends JFrame implements ActionListener {
private JTextArea editSpace;
private JTextField fileNameText;
public Kebek() {
//...
JLabel fileNameLabel = new JLabel("file name: ", JLabel.RIGHT);
fileNameText = new JTextField(20);
// create writing area
editSpace = new JTextArea(40, 40);
// pointless
//String editSpaceText = editSpace.getText();
this.add(fileNameLabel);
this.add(fileNameText);
this.add(editSpace);
// pointless
//String fileNameStr = fileNameText.getText();
// point less
//this.essay = editSpaceText;
//this.mainFileName = fileNameStr;
//...
}
Then, when you need the values of those components, you ask for them...
public void saveFile() {
String mainFileName = fileNameText.getText();
String essay = editSpace.getText();
try (BufferedWriter buffWrite = new BufferedWriter(new FileWriter(mainFileName + ".txt"))) {
// write the string on to a file
buffWrite.write(essay);
} catch (IOException ex) {
System.out
.println("There is an error with the" + mainFileName);
}
}
You should also have a look at the try-with-resources statement for a better way to manage your resources
Try using this..
File file=new File(this.mainFileName + ".txt");
if(file.exists()==false){
file.createNewFile();
}
FileWriter writeFile = new FileWriter(file);
BufferedWriter buffWrite = new BufferedWriter(writeFile);
I have a label that isn't updating in the same instance of the GUI.
If I click the jButton that should update the value on a jLabel ("testLabel" from block of code), I have to run the java program again to see the change appear. How can I get it to appear on button click in the same instance?
I know about invokelater and I've been playing with it trying to get it to update in real time, but with no luck. I've been stuck on this for awhile now so any help is appreciated.
With the block of code listed below I still have to run a new instance of the GUI to get the value to update.
Related code:
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MISControlPanel window = new MISControlPanel();
window.frame.setVisible(true);
// testLabel.setText(CN);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
JButton searchComputerButton = new JButton("Search");
searchComputerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String line;
BufferedWriter bw = null;
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(tempFile));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// String lineToRemove = "OU=Workstations";
String s = null;
Process p = null;
/*
* try { // p = Runtime.getRuntime().exec(
* "cmd /c start c:\\computerQuery.bat computerName"); } catch
* (IOException e1) { // TODO Auto-generated catch block
* e1.printStackTrace(); }
*/
try {
p = Runtime.getRuntime().exec("c:\\computerQuery.bat");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
StringBuffer sbuffer = new StringBuffer();
BufferedReader in = new BufferedReader(new InputStreamReader(p
.getInputStream()));
try {
while ((line = in.readLine()) != null) {
System.out.println(line);
// textArea.append(line);
String dn = "CN=FDCD111304,OU=Workstations,OU=SIM,OU=Accounts,DC=FL,DC=NET";
LdapName ldapName = new LdapName(dn);
String commonName = (String) ldapName.getRdn(
ldapName.size() - 1).getValue();
}
ComputerQuery.sendParam();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InvalidNameException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally
{
try {
fw.close();
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ComputerQuery.sendParam();
}
});
try (BufferedReader br = new BufferedReader(new FileReader(
"resultofbatch.txt"))) {
final Pattern PATTERN = Pattern.compile("CN=([^,]+).*");
try {
while ((sCurrentLine = br.readLine()) != null) {
String[] tokens = PATTERN.split(","); // This will return
// you a array,
// containing the
// string array
// splitted by what
// you write inside
// it.
// should be in your case the split, since they are
// seperated by ","
// System.out.println(sCurrentLine);
CN = sCurrentLine.split("CN=", -1)[1].split(",", -1)[0];
System.out.println(CN);
testLabel.setText(CN);
}
Full Class Code
http://pastebin.com/havyqMxP
Computer Query Class (Small Class)
http://pastebin.com/Q89BCjya
As promised... here is a simple example of fetching an URL content using swing worker to decouple the task of getting the contents (the long running task) from the task that update the swing components. This will show an example of how you should approach this issue...
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingWorker;
/* FrameDemo.java requires no other files. */
public class MainWindow extends JFrame {
private static final Logger LOOGER = Logger.getLogger(MainWindow.class.getName());
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private JLabel statusLabel = new JLabel("Status");
private JButton actionButton = new JButton("Push me");
public MainWindow() {
super("FrameDemo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
statusLabel = new JLabel("Status");
actionButton = new JButton("Push me");
statusLabel.setPreferredSize(new Dimension(400, 50));
actionButton.setPreferredSize(new Dimension(100, 50));
getContentPane().setLayout(new BorderLayout());
getContentPane().add(statusLabel, BorderLayout.NORTH);
getContentPane().add(actionButton, BorderLayout.CENTER);
actionButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// THIS METHOD IS INVOKED WITHIN THE EVENT DISPATCH THREAD!!.. SO IS CRUCIAL TO NOT PERFORM
// HERE LONG TIME RUNNING TASKS...
actionButton.setEnabled(false); // let's disable this button, in order to avoid invoking
// multiple times the same task and messing up the entire app...
UrlFechterSwingWorker urlFechterSwingWorker = new UrlFechterSwingWorker();
urlFechterSwingWorker.execute();
}
});
}
public void display() {
pack();
setVisible(true);
}
private class UrlFechterSwingWorker extends SwingWorker<String, String> {
#Override
public String doInBackground() { // this method is executed under a worker thread
BufferedReader in;
StringBuilder sb = new StringBuilder();
try {
URL url = new URL("http://www.stackoverflow.com");
in = new BufferedReader(new InputStreamReader(url.openStream()));
String line = in.readLine();
while (line != null) {
sb.append(line);
publish(line); // publish partial results....
line = in.readLine();
}
in.close();
} catch (Exception e) {
LOOGER.log(Level.SEVERE, "", e);
}
return sb.toString();
}
#Override
protected void process(List<String> readedLines) { // this method in the Event dispatch Thread
// do what you want to do with the readedLines....
statusLabel.setText("The doInBackground read... " + readedLines.size() + " lines");
}
#Override
public void done() { // this method in the Event dispatch Thread
// do what you want when the process finish
actionButton.setEnabled(true); // well.. at least i would like to enable the button again...
}
}
public static void main(String[] args) {
MainWindow mainWindow = new MainWindow();
mainWindow.display();
}
}
Here are more tips:
After you understand (more or less) how things are working in the above example.. you will have to implement a proper doInBackground method that perform all the LDAP stuff, for this you will have to make your mind to conceive a way of informing the progress to a end user... i mean, look my example, is very poor regarding progress advance.. all the thing that i am stating is that, we read "a number of lines" from a given url. You should think what is the best way to inform progress regarding your task.. there is no template for this except the understanding of the underlying domain model.
Have in mind that swing workers has two ways to inform about the progress.
One is using the publish and process method in conjunction. (Like the example above)
Other is to to modify internal properties (progress and state) inside the method doInBackground, and attach a PropertyChangeListener to the swing worker. This propertyChangeListener object has a method whose signature is public void propertyChange(PropertyChangeEvent evt) (a little more complex, on my point of view..)
Patience and good luck!
When my program reads from the randomaccessfile it will only find the first file or the file with the lowest account number ( this is a banking program )
After that I get the IO exception with a read error
private RandomAccessFile input; // Random Aecess File input Stream
private Record data;
public static JFrame frame = new JFrame();
public CredRead() // Constructor CredRead created
{
// open the file
try {
// declare the output stream object and associate it to file
// file.dat
input = new RandomAccessFile("UnionDB.dat", "rw");
}
catch (IOException e) {
// if an error occurs display a message on the screen
System.err.println("File not opened properly\n " + e.toString());
// the program terminates due to error
System.exit(1);
}
data = new Record();
setPreferredSize(new Dimension(650, 400));
frame.setSize(getPreferredSize()); // Frame Size
frame.setLocationRelativeTo(null);
frame.setLayout(new GridLayout(7, 2)); // Grid Layout set
/* GUI Components */
frame.add(new Label("Enter Account Number and click Enter"));
account_num = new TextField();
frame.add(account_num);
account_num.addActionListener(this);
frame.add(new Label("First Name"));
first_name = new TextField(20);
first_name.setEditable(false);
frame.add(first_name);
frame.add(new Label("Last Name"));
last_name = new TextField(20);
last_name.setEditable(false);
frame.add(last_name);
frame.add(new Label("Available Funds"));
balance = new TextField(20);
balance.setEditable(false);
frame.add(balance);
frame.add(new Label("Overdraft Limit"));
overdraft = new TextField(20);
overdraft.setEditable(false);
frame.add(overdraft);
enter = new Button("Enter");
enter.addActionListener(this);
frame.add(enter);
done = new Button("Click to Exit");
done.addActionListener(this);
frame.add(done);
setVisible(true); // GUI components set as visible to the program
}
public void readRecord() {
DecimalFormat twoDigits = new DecimalFormat("0.00");
try {
do {
data.read(input);
} while (data.getAccount() == 0);
input.seek(
(long) ( data.getAccount()-1 ) * Record.size());
data.write( input );
account_num.setText(String.valueOf(data.getAccount()));
first_name.setText(data.getFirstName());
last_name.setText(data.getLastName());
balance.setText(String.valueOf(twoDigits.format(data.getBalance())));
overdraft.setText(String.valueOf(twoDigits.format(data.getOverdraft())));
}// end try
catch (EOFException eof) {
closeFile();
}
catch (IOException e) {
// if an error occurs display a message on the screen
System.err.println("Error during read from file\n " + e.toString());
// the program terminates due to error
// System.exit(1);
}
}
private void closeFile() {
try {
input.close();
// System.exit(1);
} catch (IOException e) {
// if an error occurs display a message on the screen
System.err.println("Error closing file\n " + e.toString());
// System.exit(1);
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == enter)
readRecord();
else if (e.getSource() == done)
frame.dispose();
else
frame.add(new TextField(" Account Not Found on Database "));
closeFile();
}
public static void main(String args[]) {
new CredRead();
}
}
My guess is that
data.getAccount() != 0
and so your loop only executes once, because you did it in a do ... while();
Try adding some debugging into your code and make sure what data.getAccount() is equal to.
How do you get multiple inputs from the multiple textfields you have created?
I want one text field to get the port number, another to get file location.
So once the user enter the int and the string, I can use these inputs for the program.
I am new to this, so when I tried to implement this, I would enter the port number, and suddenly the UI seems to "freeze" and I can't enter the file location.
constructor for frame
public TcpServerCompareCSV () {
setLayout(new FlowLayout());
// "this" Frame sets its layout to FlowLayout, which arranges the components
// from left-to-right, and flow to next row from top-to-bottom.
lblPort = new Label("Port"); // construct Label
add(lblPort); // "this" Frame adds Label
tfPort = new TextField("0", 10); // construct TextField
tfPort.setEditable(true); //edit text
add(tfPort); // "this" Frame adds tfCount
tfPort.addActionListener(this); // for event-handling
lblLocation = new Label("CSV File Location"); // construct Label
add(lblLocation); // "this" Frame adds Label
tfLocation = new TextField("text", 40); // construct TextField
tfLocation.setEditable(true); //edit text
add(tfLocation); // "this" Frame adds tfCount
tfLocation.addActionListener(this);
setTitle("compare"); // "this" Frame sets title
setSize(250, 100); // "this" Frame sets initial window size
setVisible(true); // "this" Frame shows
addWindowListener(this);
// "this" Frame fires WindowEvent its registered WindowEvent listener
// "this" Frame adds "this" object as a WindowEvent listener
}
action event
/** ActionEvent handler - Called back when user clicks the button. */
#Override
public void actionPerformed(ActionEvent evt) {
// Get the String entered into the TextField tfPort, convert to int
port = Integer.parseInt(tfPort.getText());
fileLocation = tfLocation.getText();
String csvName = fileLocation;
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
}
catch (IOException e)
{
System.err.println("Could not listen on port: 57635.");
System.exit(1);
}
Socket clientSocket = null;
System.out.println ("Waiting for connection.....");
try {
clientSocket = serverSocket.accept();
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
System.out.println ("Connection successful");
System.out.println ("Waiting for input.....");
PrintWriter out = null;
try {
out = new PrintWriter(clientSocket.getOutputStream(),
true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader in = null;
try {
in = new BufferedReader(
new InputStreamReader( clientSocket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String inputLine, outputLine;
try {
while ((inputLine = in.readLine()) != null)
{
System.out.println ("Server: " + inputLine);
if (inputLine.trim().equals("Bye.")) {
System.out.println("Exit program");
break;
}
Scanner input1 = new Scanner(new File(csvName));
Scanner input2 = new Scanner(new File(csvName));
Scanner input3 = new Scanner(new File(csvName));
Scanner input4 = new Scanner(new File(csvName));
String csvline = getCsvLineVal (getLocation34CSV(getTag34Value(Tag34Location(getTagCSV( parseFixMsg(inputLine ,inputLine))), getValueCSV( parseFixMsg(inputLine ,inputLine))), getVal34(input1, input2)), getCSVLine( input3, input4) );
outputLine = compareClientFixCSV( getTagCSV( parseFixMsg(inputLine ,inputLine)), getValueCSV(parseFixMsg(inputLine ,inputLine)), getCSVTag(csvline), getCSVValue(csvline));
out.println(outputLine);
input1.close();
input2.close();
input3.close();
input4.close();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.close();
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
By adding the ActionListener to both text fields, if I remember correctly, they will fire the event as soon as you hit Return in one of them.
That will trigger your network code immediately.
You should only register the action for the button.
Moreover, as was already pointed out in a comment, you are executing network communications on the GUI thread, which is causing the freeze.
In the action implementation, you must spawn a separate thread to do the actual network communications to prevent the blocking. To find out how that works, look at the documentation for Runnable and the Executor framework.
Only call addActionListener(this); for your button, don't listen to actions on your textFields, because your actionPerformed method is being called when actions occur on your textfield (user hits enter). I'm guessing your doing this after the first field and that your action method is getting called by this and then waiting for the socket connection, as that is a blocking call, this would make your GUI unresponsive.
Are there any examples of a server and a client that use sockets, but that have send and get methods? I'm doing this networked battleship program, almost finished, but can't get the server and clients to work. I have made a chat program that only sends strings, but this time I need to send objects. I'm already frustrated, so is there any source code that already has this.
Here's the code for the client... how would you modify it to allow to send objects? Also I need to be listening for incoming objects and process them right away.
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SimpleChat extends JFrame {
private Socket communicationSocket = null;
private PrintWriter outStream = null;
private BufferedReader inStream = null;
private Boolean communicationContinue = true;
private String disconnectString = "disconnect764*#$1";
private JMenuItem disconnectItem;
private JTextField displayLabel;
private final Color colorValues[] = { Color.black, Color.blue, Color.red, Color.green };
// set up GUI
public SimpleChat() {
super("Simple Chat");
// set up File menu and its menu items
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic('F');
// set up Activate Server menu item
JMenuItem serverItem = new JMenuItem("Activate Server");
serverItem.setMnemonic('S');
fileMenu.add(serverItem);
serverItem.addActionListener(new ActionListener() { // anonymous inner class
// display message dialog when user selects About...
public void actionPerformed(ActionEvent event) {
setUpServer();
}
} // end anonymous inner class
); // end call to addActionListener
// set up Activate Client menu item
JMenuItem clientItem = new JMenuItem("Activate Client");
clientItem.setMnemonic('C');
fileMenu.add(clientItem);
clientItem.addActionListener(new ActionListener() { // anonymous inner class
// display message dialog when user selects About...
public void actionPerformed(ActionEvent event) {
setUpClient();
}
} // end anonymous inner class
); // end call to addActionListener
// set up Activate Client menu item
disconnectItem = new JMenuItem("Disconnect Client/Server");
disconnectItem.setMnemonic('D');
disconnectItem.setEnabled(false);
fileMenu.add(disconnectItem);
disconnectItem.addActionListener(new ActionListener() { // anonymous inner
// class
// display message dialog when user selects About...
public void actionPerformed(ActionEvent event) {
disconnectClientServer(true);
}
} // end anonymous inner class
); // end call to addActionListener
// set up About... menu item
JMenuItem aboutItem = new JMenuItem("About...");
aboutItem.setMnemonic('A');
fileMenu.add(aboutItem);
aboutItem.addActionListener(new ActionListener() { // anonymous inner class
// display message dialog when user selects About...
public void actionPerformed(ActionEvent event) {
JOptionPane.showMessageDialog(SimpleChat.this, "This is an example\nof using menus", "About",
JOptionPane.PLAIN_MESSAGE);
}
} // end anonymous inner class
); // end call to addActionListener
// set up Exit menu item
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.setMnemonic('x');
fileMenu.add(exitItem);
exitItem.addActionListener(new ActionListener() { // anonymous inner class
// terminate application when user clicks exitItem
public void actionPerformed(ActionEvent event) {
disconnectClientServer(true);
System.exit(0);
}
} // end anonymous inner class
); // end call to addActionListener
// create menu bar and attach it to MenuTest window
JMenuBar bar = new JMenuBar();
setJMenuBar(bar);
bar.add(fileMenu);
// set up label to display text
displayLabel = new JTextField("Sample Text", SwingConstants.CENTER);
displayLabel.setForeground(colorValues[0]);
displayLabel.setFont(new Font("Serif", Font.PLAIN, 72));
displayLabel.addActionListener(new ActionListener() { // anonymous inner
// class
// display message dialog when user selects About...
public void actionPerformed(ActionEvent event) {
sendData();
}
} // end anonymous inner class
); // end call to addActionListener
getContentPane().setBackground(Color.CYAN);
getContentPane().add(displayLabel, BorderLayout.CENTER);
setSize(500, 200);
setVisible(true);
} // end constructor
public static void main(String args[]) {
final SimpleChat application = new SimpleChat();
application.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
application.disconnectClientServer(true);
System.exit(0);
}
});
// application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
public void setCommunicationSocket(Socket sock) {
communicationSocket = sock;
communicationContinue = true;
disconnectItem.setEnabled(true);
}
public void setOutStream(PrintWriter out) {
outStream = out;
}
public void setInStream(BufferedReader in) {
inStream = in;
}
public void setUpServer() {
ServerThread st = new ServerThread(this);
st.start();
}
public void setUpClient() {
ClientThread st = new ClientThread(this);
st.start();
}
public void disconnectClientServer(Boolean sendMessage) {
if (communicationSocket == null)
return;
try {
// shut down socket read loop
communicationContinue = false;
disconnectItem.setEnabled(false);
// send notification to other end of socket
if (sendMessage == true)
outStream.println(disconnectString);
// sleep to let read loop shut down
Thread t = Thread.currentThread();
try {
t.sleep(500);
} catch (InterruptedException ie) {
return;
}
outStream.close();
inStream.close();
communicationSocket.close();
} catch (IOException e) {
System.err.println("Stream Read Failed.");
JOptionPane.showMessageDialog(SimpleChat.this, "Disconnection Failed", "SimpleChat", JOptionPane.PLAIN_MESSAGE);
return;
} finally {
communicationSocket = null;
}
}
public void sendData() {
if (communicationSocket != null) {
String data = displayLabel.getText();
outStream.println(data);
}
}
public void getData() {
String inputLine;
try {
while (communicationContinue == true) {
communicationSocket.setSoTimeout(100);
// System.out.println ("Waiting for Connection");
try {
while (((inputLine = inStream.readLine()) != null)) {
System.out.println("From socket: " + inputLine);
if (inputLine.equals(disconnectString)) {
disconnectClientServer(false);
return;
}
displayLabel.setText(inputLine);
}
} catch (SocketTimeoutException ste) {
// System.out.println ("Timeout Occurred");
}
} // end of while loop
System.out.println("communication is false");
} catch (IOException e) {
System.err.println("Stream Read Failed.");
JOptionPane.showMessageDialog(SimpleChat.this, "Input Stream read failed", "SimpleChat",
JOptionPane.PLAIN_MESSAGE);
return;
}
}
}
class ServerThread extends Thread {
private SimpleChat sc;
private JTextField display;
public ServerThread(SimpleChat scParam) {
sc = scParam;
}
public void run() {
ServerSocket connectionSocket = null;
try {
connectionSocket = new ServerSocket(10007);
} catch (IOException e) {
System.err.println("Could not listen on port: 10007.");
JOptionPane.showMessageDialog(sc, "Could not listen on port: 10007", "Server", JOptionPane.PLAIN_MESSAGE);
return;
}
JOptionPane.showMessageDialog(sc, "Server Socket is now activated", "Server", JOptionPane.PLAIN_MESSAGE);
Socket communicationSocket = null;
try {
communicationSocket = connectionSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
JOptionPane.showMessageDialog(sc, "Accept failed", "Server", JOptionPane.PLAIN_MESSAGE);
return;
}
JOptionPane.showMessageDialog(sc, "Comminucation is now activated", "Server", JOptionPane.PLAIN_MESSAGE);
try {
PrintWriter out = new PrintWriter(communicationSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(communicationSocket.getInputStream()));
sc.setCommunicationSocket(communicationSocket);
sc.setOutStream(out);
sc.setInStream(in);
connectionSocket.close();
sc.getData();
} catch (IOException e) {
System.err.println("Accept failed.");
JOptionPane.showMessageDialog(sc, "Creation of Input//Output Streams failed", "Server", JOptionPane.PLAIN_MESSAGE);
return;
}
}
}
class ClientThread extends Thread {
private SimpleChat sc;
public ClientThread(SimpleChat scParam) {
sc = scParam;
}
public void run() {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
String ipAddress = "127.0.0.1";
try {
echoSocket = new Socket(ipAddress, 10007);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + ipAddress);
JOptionPane.showMessageDialog(sc, "Don't know about host: " + ipAddress, "Client", JOptionPane.PLAIN_MESSAGE);
return;
} catch (IOException e) {
System.err.println("Couldn't get I/O for " + "the connection to: " + ipAddress);
JOptionPane.showMessageDialog(sc, "Couldn't get I/O for the connection to: " + ipAddress, "Client",
JOptionPane.PLAIN_MESSAGE);
return;
}
JOptionPane.showMessageDialog(sc, "Comminucation is now activated", "Client", JOptionPane.PLAIN_MESSAGE);
sc.setCommunicationSocket(echoSocket);
sc.setOutStream(out);
sc.setInStream(in);
sc.getData();
}
}
I suggest you read up on java serialization. There is an example here. Basically, there is built in serialization support. Your class needs to implement Serializable. Then you use ObjectOutputStream and ObjectInputStream to write object.
You would be well advised to use libraries that shield you from the error prone low level socket programming.
For C++ look to Boost (http://www.boost.com) or ACE (http://www.cs.wustl.edu/~schmidt/ACE.html)
For Java I only found a document that talks about the acceptor pattern http://www.hillside.net/plop/plop99/proceedings/Fernandez3/RACPattern.PDF
But I am sure there's an implementation out somewhere
Your on the right track. A chat program is a good place to start learning about sockets.
What you want is to use the ObjectOutputStream and ObjectInputStream classes. You simply have to wrap your input stream / output stream with these filters. ObjectOutputStream has a method writeObject(), and the ObjectInputStream has a corresponding readObject() method.
Most serialization examples show reading and writing objects to a file, but the same can be done using a socket stream. See http://www.acm.org/crossroads/xrds4-2/serial.html
I didn't bother to read through your piles and piles of code, but in general you can't directly send objects over the network. Network communication is just bits and bytes. If you want to send objects, you'll need to serialize them on the sending side, and de-serialize them on the receiving side. There are tons of methods of serializing, eg JSON, XML, or even Java's built-in serialization support (only recommended if both the client and server will always be Java).
You may find this code to be a decent starting point for making your own class. These are two classes I made to somewhat abstract the work needed for TCP and UDP socket protocols:
http://code.google.com/p/hivewars/source/browse/trunk/SocketData.java
http://code.google.com/p/hivewars/source/browse/trunk/UDPSocket.java
Quick dislaimer: These are kind of versions of a feature full class, I just added functionality as I needed it. However, it could help you start.