Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 13 of 13

Thread: Thread syncronization JAVA GUI

  1. #1
    Junior Member
    Join Date
    Jan 2011
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Unhappy Thread syncronization JAVA GUI

    Hi there I have been having some thread synchronization issues lately, I am trying to write a client/server application which is supposed to transfer files from one computer to another using a given socket! The thing is I keep getting a Null pointer exception in oos.writeInt(selectedFiles.length) (client side), I don't really understand why that happens since I am initializing oos in run() and then making sure it doesn't go any further before knowing the number of files to transfer to the other side..... So I figured it must be a synchronization issue, I just don't know how to solve this....

    Server side code:

    package fileUpload;
     
    import java.awt.BorderLayout;
    import java.awt.EventQueue;
    import java.awt.Font;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.net.Socket;
    import java.net.SocketException;
     
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JProgressBar;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingConstants;
    import javax.swing.border.EmptyBorder;
     
    public class FileUpload_Server extends JFrame implements Runnable{
     
    	private JPanel contentPane;
    	private JTextField currentDownload;
    	private JProgressBar progressBar;
    	private JTextArea uploads;
    	private ObjectInputStream ois;
    	private ObjectOutputStream oos;
    	private Socket channel;
     
    	/**
    	 * Create the frame.
    	 */
    	public FileUpload_Server(Socket channel) {
     
    		this.channel=channel;
     
    		setResizable(false);
    		setTitle("Remote Administrator");
    		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    		setBounds(100, 100, 450, 300);
    		contentPane = new JPanel();
    		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    		setContentPane(contentPane);
    		contentPane.setLayout(null);
     
    		JLabel lblFileCurrentlyBeing = new JLabel("File currently being downloaded:");
    		lblFileCurrentlyBeing.setFont(new Font("Dialog", Font.BOLD, 10));
    		lblFileCurrentlyBeing.setBounds(12, 13, 196, 19);
    		contentPane.add(lblFileCurrentlyBeing);
     
    		currentDownload = new JTextField();
    		currentDownload.setEnabled(false);
    		currentDownload.setHorizontalAlignment(SwingConstants.CENTER);
    		currentDownload.setOpaque(false);
    		currentDownload.setEditable(false);
    		currentDownload.setBounds(226, 12, 196, 19);
    		contentPane.add(currentDownload);
    		currentDownload.setColumns(10);
     
    		progressBar = new JProgressBar();
    		progressBar.setEnabled(false);
    		progressBar.setBounds(12, 44, 410, 14);
    		contentPane.add(progressBar);
     
    		uploads = new JTextArea();
    		uploads.setEnabled(false);
    		uploads.setEditable(false);
    		uploads.setBounds(12, 96, 410, 155);
    		contentPane.add(uploads);
     
    		JLabel lblListOfDownloaded = new JLabel("List of downloaded files:");
    		lblListOfDownloaded.setBounds(12, 70, 196, 15);
    		contentPane.add(lblListOfDownloaded);
     
    		setVisible(true);
     
    	}
     
    	@Override
    	public void run() {
     
    		try {
    			ois = new ObjectInputStream(channel.getInputStream());
    		} catch (IOException e2) {
    			// TODO Auto-generated catch block
    			e2.printStackTrace();
    		}
     
    		try {
    			oos = new ObjectOutputStream(channel.getOutputStream());
    		} catch (IOException e2) {
    			// TODO Auto-generated catch block
    			e2.printStackTrace();
    		}
     
    		System.out.println("ois and oos initialized");
     
    		int howMany = 0;
    		try {
    			howMany = ois.readInt();
    		} catch (IOException e3) {
    			// TODO Auto-generated catch block
    			e3.printStackTrace();
    		}
     
    		File downloadDirectory = new File((new File(".")).getParentFile(),"Uploads");
     
    		downloadDirectory.mkdir();
     
    		for(int i=0; i<howMany; i++){
     
    		//Creating new file
     
    		String currentDownloadFileName = null;
    		try {
    			currentDownloadFileName = (String) ois.readObject();
    		} catch (IOException e3) {
    			// TODO Auto-generated catch block
    			e3.printStackTrace();
    		} catch (ClassNotFoundException e3) {
    			// TODO Auto-generated catch block
    			e3.printStackTrace();
    		}
     
    		File receivedFile = new File(downloadDirectory,currentDownloadFileName);
     
    		currentDownload.setText(currentDownloadFileName);
     
    		long length = 0;
    		try {
    			length = ois.readLong();
    		} catch (IOException e2) {
    			// TODO Auto-generated catch block
    			e2.printStackTrace();
    		}
     
    	    //Receiving its data
    		FileOutputStream wr = null;
    		try {
    			wr = new FileOutputStream(receivedFile);
    		} catch (FileNotFoundException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		}
    		byte[] outBuffer = null;
    		try {
    			outBuffer = new byte[channel.getReceiveBufferSize()];
    		} catch (SocketException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		}
     
    		int bytesReceivedNow = 0;
    		int bytesReceivedUntilNow = 0;
     
    		try {
    			while((bytesReceivedNow = ois.read(outBuffer))>0)
    			{
    				wr.write(outBuffer,0,bytesReceivedNow);
    				bytesReceivedUntilNow += bytesReceivedNow;
    				progressBar.setValue((int)(bytesReceivedUntilNow/length));
    			}
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
     
    		progressBar.setValue(100);
     
    		try {
    			wr.close();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
     
    		currentDownload.setText("");
     
    		uploads.append(receivedFile.getName()+"\n");
     
    		}
     
    		try {
    			channel.close();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
     
    	}
    }

    Client side code:

    package fileUpload;
     
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.net.Socket;
    import java.net.SocketException;
     
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JProgressBar;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingConstants;
    import javax.swing.border.EmptyBorder;
     
    public class FileUpload_Client extends JFrame implements ActionListener, Runnable{
     
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    	private JPanel contentPane;
    	private JTextField currentUpload;
    	private JProgressBar progressBar;
    	private JTextArea uploads;
    	private File[] selectedFiles;
    	private JButton upload;
    	private boolean selectionHasNotYetBeenMade=true;
    	private JLabel lblNewLabel;
    	private JLabel lblCurrentFilesProgress;
    	private Socket channel;
    	private ObjectInputStream ois;
    	private ObjectOutputStream oos;
     
    	/**
    	 * Create the frame.
    	 */
    	public FileUpload_Client(Socket channel) {
     
    		this.channel=channel;
     
    		setResizable(false);
    		setTitle("Remote Administrator");
    		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    		setBounds(100, 100, 450, 300);
    		contentPane = new JPanel();
    		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    		setContentPane(contentPane);
    		contentPane.setLayout(null);
     
    		JLabel lblPleaseUploadyourFiles = new JLabel("Please upload your files by clicking the button here:");
    		lblPleaseUploadyourFiles.setFont(new Font("Dialog", Font.BOLD, 10));
    		lblPleaseUploadyourFiles.setBounds(12, 12, 306, 15);
    		contentPane.add(lblPleaseUploadyourFiles);
     
    		upload = new JButton("Upload");
    		upload.addActionListener(this);
    		upload.setBounds(317, 9, 105, 19);
    		contentPane.add(upload);
     
    		JLabel lblFileCurrentlyBeing = new JLabel("File currently being uploaded:");
    		lblFileCurrentlyBeing.setFont(new Font("Dialog", Font.BOLD, 10));
    		lblFileCurrentlyBeing.setBounds(12, 32, 196, 15);
    		contentPane.add(lblFileCurrentlyBeing);
     
    		currentUpload = new JTextField();
    		currentUpload.setEnabled(false);
    		currentUpload.setHorizontalAlignment(SwingConstants.CENTER);
    		currentUpload.setOpaque(false);
    		currentUpload.setEditable(false);
    		currentUpload.setBounds(226, 32, 196, 14);
    		contentPane.add(currentUpload);
    		currentUpload.setColumns(10);
     
    		progressBar = new JProgressBar();
    		progressBar.setEnabled(false);
    		progressBar.setBounds(226, 59, 196, 15);
    		contentPane.add(progressBar);
     
    		uploads = new JTextArea();
    		uploads.setFont(new Font("Dialog", Font.PLAIN, 10));
    		uploads.setEnabled(false);
    		uploads.setEditable(false);
    		uploads.setBounds(12, 111, 410, 140);
    		contentPane.add(uploads);
     
    		lblNewLabel = new JLabel("List of uploaded files:");
    		lblNewLabel.setFont(new Font("Dialog", Font.BOLD, 10));
    		lblNewLabel.setBounds(12, 84, 161, 15);
    		contentPane.add(lblNewLabel);
     
    		lblCurrentFilesProgress = new JLabel("Current file's progress bar:");
    		lblCurrentFilesProgress.setFont(new Font("Dialog", Font.BOLD, 10));
    		lblCurrentFilesProgress.setBounds(12, 59, 196, 15);
    		contentPane.add(lblCurrentFilesProgress);
     
    		setVisible(true);
     
    	}
     
     
     
    	@Override
    	public void run() {
     
    		try {
    			ois = new ObjectInputStream(channel.getInputStream());
    		} catch (IOException e2) {
    			// TODO Auto-generated catch block
    			e2.printStackTrace();
    		}
     
    		try {
    			oos = new ObjectOutputStream(channel.getOutputStream());
    		} catch (IOException e2) {
    			// TODO Auto-generated catch block
    			e2.printStackTrace();
    		}
     
    		System.out.println("ois and oos initialized");
     
     
    		while(selectionHasNotYetBeenMade){	}
     
     
    		for(int i=0; i<selectedFiles.length; i++){
     
    		//Sending over file's name
    		try {
    			oos.writeObject((String)selectedFiles[i].getName());
    		} catch (IOException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		}
     
    		currentUpload.setText(selectedFiles[i].getName());
     
    		try {
    			oos.writeLong(selectedFiles[i].length());
    		} catch (IOException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		}
     
    		//Sending over its data
    		FileInputStream in = null;
    		try {
    			in = new FileInputStream(selectedFiles[i]);
    		} catch (FileNotFoundException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
     
    		byte[] buff = null;
    		try {
    			buff = new byte[channel.getSendBufferSize()];
    		} catch (SocketException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		}
     
    		int bytesReadNow = 0;
    		int bytesReadUntilNow = 0;
     
    		try {
    			while((bytesReadNow = in.read(buff))>0)
    			{
    				oos.write(buff,0,bytesReadNow);
    				oos.flush();
    				bytesReadUntilNow += bytesReadNow;
    				progressBar.setValue((int)(bytesReadUntilNow/selectedFiles[i].length()));
    			}
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
     
    		progressBar.setValue(100);
     
    		try {
    			in.close();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
     
    		currentUpload.setText("");
     
    		uploads.append(selectedFiles[i].getName()+"\n");
     
    		}
     
    		try {
    			channel.close();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
     
    	}
     
    	@Override
    	public void actionPerformed(ActionEvent e) {
     
    		JFileChooser files_chooser = new JFileChooser();
    		files_chooser.setMultiSelectionEnabled(true);
    		files_chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
     
    		if(files_chooser.showDialog(this, "Upload")== JFileChooser.APPROVE_OPTION){
    			selectedFiles=files_chooser.getSelectedFiles();
    			uploads.setEnabled(true);
    			currentUpload.setEnabled(true);
    			try {
    				oos.writeInt(selectedFiles.length);
    				oos.flush();
    			} catch (IOException e1) {
    				// TODO Auto-generated catch block
    				e1.printStackTrace();
    			}
    			selectionHasNotYetBeenMade=false;
    		}
     
    	}
    }

    The program just doesn't seem to get to the run() method... so that ois and oos can be initialized!

    Both classes are part of a larger project, that's why I just dispose the frames on close.


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,334
    Thanks
    181
    Thanked 830 Times in 773 Posts
    Blog Entries
    5

    Default Re: Thread syncronization JAVA GUI

    Please 1) post the full exception stack trace. 2) Post an SSCCE of the client and server

  3. #3
    Junior Member
    Join Date
    Jan 2011
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Thread syncronization JAVA GUI

    the server side just hangs (well that's normal, since it's waiting for the the number of files to be transferred)
    here's the the exception stack trace:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at fileUpload.FileUpload_Client.actionPerformed(FileU pload_Client.java:224)
    at javax.swing.AbstractButton.fireActionPerformed(Abs tractButton.java:1995)
    at javax.swing.AbstractButton$Handler.actionPerformed (AbstractButton.java:2318)
    at javax.swing.DefaultButtonModel.fireActionPerformed (DefaultButtonModel.java:387)
    at javax.swing.DefaultButtonModel.setPressed(DefaultB uttonModel.java:242)
    at javax.swing.plaf.basic.BasicButtonListener.mouseRe leased(BasicButtonListener.java:236)
    at java.awt.Component.processMouseEvent(Component.jav a:6288)
    at javax.swing.JComponent.processMouseEvent(JComponen t.java:3267)
    at java.awt.Component.processEvent(Component.java:605 3)
    at java.awt.Container.processEvent(Container.java:204 1)
    at java.awt.Component.dispatchEventImpl(Component.jav a:4651)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2099)
    at java.awt.Component.dispatchEvent(Component.java:44 81)
    at java.awt.LightweightDispatcher.retargetMouseEvent( Container.java:4577)
    at java.awt.LightweightDispatcher.processMouseEvent(C ontainer.java:4238)
    at java.awt.LightweightDispatcher.dispatchEvent(Conta iner.java:4168)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2085)
    at java.awt.Window.dispatchEventImpl(Window.java:2478 )
    at java.awt.Component.dispatchEvent(Component.java:44 81)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.j ava:643)
    at java.awt.EventQueue.access$000(EventQueue.java:84)
    at java.awt.EventQueue$1.run(EventQueue.java:602)
    at java.awt.EventQueue$1.run(EventQueue.java:600)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectio nPrivilege(AccessControlContext.java:87)
    at java.security.AccessControlContext$1.doIntersectio nPrivilege(AccessControlContext.java:98)
    at java.awt.EventQueue$2.run(EventQueue.java:616)
    at java.awt.EventQueue$2.run(EventQueue.java:614)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectio nPrivilege(AccessControlContext.java:87)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java: 613)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(E ventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThre ad.java:122)


    line 224 is: oos.writeInt(selectedFiles.length);

    Both threads are started this way (variables globally declared):

    fu = new FileUpload_Server(accepted);
    tfu = new Thread(fu);
    tfu.start();

    while(tfu.isAlive()){ }

    fu = new FileUpload_Client(fileUpload_channel);
    tfu = new Thread(fu);
    tfu.start();
    while(tfu.isAlive()){ }

    fileUpload_channel and accepted are two working sockets



    I just wrote everything that came to mind....

  4. #4
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,334
    Thanks
    181
    Thanked 830 Times in 773 Posts
    Blog Entries
    5

    Default Re: Thread syncronization JAVA GUI

    What is null on line 224? Add some println's in there to figure it out.

  5. #5
    Junior Member
    Join Date
    Jan 2011
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Thread syncronization JAVA GUI

    it's oos; I added the following lines of code before oos.writeInt(selectedFiles.length);
    if(oos==null) System.out.println("oos is null");
    else System.out.println("oos is not null");

    and it printed "oos is null"

    Isn't run() supposed to start automatically once you start the corresponding thread? (Sorry for all the starts)
    The thing is I am initializing both ois and oos in run(), so it must not be getting to it, not in time at least....

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,040
    Thanks
    52
    Thanked 2,280 Times in 2,251 Posts

    Default Re: Thread syncronization JAVA GUI

    Is there more than one variable named oos? Do you give one a value and use the other one at the NPE?

    This would be more direct: System.out.println("oos is " + oos);

    You have several debugging print outs that should show you what order the code was executed in.
    What do they show? You should post all the information you have about how the program is executing to help solve the problem.
    Last edited by Norm; December 1st, 2011 at 03:35 PM.

  7. #7
    Junior Member
    Join Date
    Jan 2011
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Thread syncronization JAVA GUI

    These two classes are part of a much larger project for my dissertation (for my bachelor's)..... Once the client's logged in, they can choose what to do amongst four possible choices: Remotely control the other computer, upload files to the server, download files from server and start a chat.
    I have already implemented the chat, and I've used there the same logic I am using here, and it works, it does get into run() smoothly, they are implemented pretty much the same way...... so I don't get why these two don't get into their respective run's!
    that's the only variable named oos is globally declared.....
    Last edited by lex25288; December 2nd, 2011 at 03:14 AM.

  8. #8
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re: Thread syncronization JAVA GUI

    and it printed "oos is null"
    If oos printed null, what else you expect
    oos.writeInt(selectedFiles.length);
    to do? Your output stream is null so what do you want to write with null?

    Note: I am not good in Networking though, but still a point of observation. Also, i want to get updated with this thread, so i posted here

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,040
    Thanks
    52
    Thanked 2,280 Times in 2,251 Posts

    Default Re: Thread syncronization JAVA GUI

    I don't get why these two don't get into their respective run's!
    What do the printlns outputs show you about the timing/sequencing of the events?
    Add more printlns to show when the methods are called and the variables given values.

  10. #10
    Junior Member
    Join Date
    Jan 2011
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Thread syncronization JAVA GUI

    Quote Originally Posted by Mr.777 View Post
    If oos printed null, what else you expect

    to do? Your output stream is null so what do you want to write with null?

    Note: I am not good in Networking though, but still a point of observation. Also, i want to get updated with this thread, so i posted here
    I finally figured it out!
    I managed to make it work by deleting the Upload Button and actionPerformed() and moved the code in it into run()....
    Then I replaced ObjectInputStream and ObjectOutputStream with DataInputStream and DataOutputStream respectively.... beats me but I don't really know why I couldn't get the variables initialized as object streams
    I needed the oos.writeInt(selectedFiles.length); because I needed to know how many files I was uploading to the server.....
    Anyway here's the code for the client:

    package fileUpload;
     
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.net.Socket;
    import java.net.SocketException;
     
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JProgressBar;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingConstants;
    import javax.swing.border.EmptyBorder;
     
    public class FileUpload_Client extends JFrame implements Runnable{
     
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    	private JPanel contentPane;
    	private JTextField currentUpload;
    	private JProgressBar progressBar;
    	private JTextArea uploads;
    	private File[] selectedFiles;
    	private JLabel lblNewLabel;
    	private JLabel lblCurrentFilesProgress;
    	private Socket channel;
    	private DataInputStream dis;
    	private DataOutputStream dos;
     
    	/**
    	 * Create the frame.
    	 */
    	public FileUpload_Client(Socket channel) {
     
    		this.channel=channel;
     
    		setResizable(false);
    		setTitle("Remote Administrator");
    		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    		setBounds(100, 100, 450, 300);
    		contentPane = new JPanel();
    		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    		setContentPane(contentPane);
    		contentPane.setLayout(null);
     
    		JLabel lblFileCurrentlyBeing = new JLabel("File currently being uploaded:");
    		lblFileCurrentlyBeing.setFont(new Font("Dialog", Font.BOLD, 10));
    		lblFileCurrentlyBeing.setBounds(12, 12, 196, 15);
    		contentPane.add(lblFileCurrentlyBeing);
     
    		currentUpload = new JTextField();
    		currentUpload.setEnabled(false);
    		currentUpload.setHorizontalAlignment(SwingConstants.CENTER);
    		currentUpload.setOpaque(false);
    		currentUpload.setEditable(false);
    		currentUpload.setBounds(226, 11, 196, 14);
    		contentPane.add(currentUpload);
    		currentUpload.setColumns(10);
     
    		progressBar = new JProgressBar();
    		progressBar.setEnabled(false);
    		progressBar.setBounds(226, 45, 196, 15);
    		contentPane.add(progressBar);
     
    		uploads = new JTextArea();
    		uploads.setFont(new Font("Dialog", Font.PLAIN, 10));
    		uploads.setEnabled(false);
    		uploads.setEditable(false);
    		uploads.setBounds(12, 99, 410, 152);
    		contentPane.add(uploads);
     
    		lblNewLabel = new JLabel("List of uploaded files:");
    		lblNewLabel.setFont(new Font("Dialog", Font.BOLD, 10));
    		lblNewLabel.setBounds(12, 72, 161, 15);
    		contentPane.add(lblNewLabel);
     
    		lblCurrentFilesProgress = new JLabel("Current file's progress bar:");
    		lblCurrentFilesProgress.setFont(new Font("Dialog", Font.BOLD, 10));
    		lblCurrentFilesProgress.setBounds(12, 45, 196, 15);
    		contentPane.add(lblCurrentFilesProgress);
     
    		setVisible(true);
     
    	}
     
     
     
    	@Override
    	public void run() {
     
    		try {
    			dis = new DataInputStream(channel.getInputStream());
    		} catch (IOException e2) {
    			// TODO Auto-generated catch block
    			e2.printStackTrace();
    		}
     
    		try {
    			dos = new DataOutputStream(channel.getOutputStream());
    		} catch (IOException e2) {
    			// TODO Auto-generated catch block
    			e2.printStackTrace();
    		}
     
    		System.out.println("dis and dos initialized");
     
    		int howMany;
     
    		JFileChooser files_chooser = new JFileChooser();
    		files_chooser.setMultiSelectionEnabled(true);
    		files_chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
     
    		if(files_chooser.showDialog(this, "Upload")== JFileChooser.APPROVE_OPTION){
    			selectedFiles=files_chooser.getSelectedFiles();
    			uploads.setEnabled(false);
    			currentUpload.setEnabled(true);
     
    			howMany=selectedFiles.length;
     
    		}
    		else howMany=0;
     
    		try {
    			dos.writeInt(howMany);
    			dos.flush();
    		} catch (IOException e2) {
    			// TODO Auto-generated catch block
    			e2.printStackTrace();
    		}
     
    		System.out.println("number of files to be transferred: "+howMany);
     
    		for(int i=0; i<howMany; i++){
     
    		//Sending over file's name
    		try {
    			dos.writeUTF(selectedFiles[i].getName());
    		} catch (IOException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		}
     
    		currentUpload.setText(selectedFiles[i].getName());
     
    		try {
    			dos.writeLong(selectedFiles[i].length());
    		} catch (IOException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		}
     
    		//Sending over its data
    		FileInputStream in = null;
    		try {
    			in = new FileInputStream(selectedFiles[i]);
    		} catch (FileNotFoundException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
     
    		byte[] buff = null;
    		try {
    			buff = new byte[channel.getSendBufferSize()];
    		} catch (SocketException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		}
     
    		int bytesReadNow = 0;
    		int bytesReadUntilNow = 0;
     
    		try {
    			while((bytesReadNow = in.read(buff))>0)
    			{
    				dos.write(buff,0,bytesReadNow);
    				dos.flush();
    				bytesReadUntilNow += bytesReadNow;
    				progressBar.setValue((int)(bytesReadUntilNow/selectedFiles[i].length()));
    			}
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
     
    		progressBar.setValue(100);
     
    		try {
    			in.close();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
     
    		currentUpload.setText("");
     
    		uploads.append(selectedFiles[i].getName()+"\n");
     
    		}
     
    		try {
    			channel.close();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
     
    	}
     
    }

    Server side:

    package fileUpload;
     
    import java.awt.Font;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.net.Socket;
    import java.net.SocketException;
     
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JProgressBar;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingConstants;
    import javax.swing.border.EmptyBorder;
     
    public class FileUpload_Server extends JFrame implements Runnable{
     
    	private JPanel contentPane;
    	private JTextField currentDownload;
    	private JProgressBar progressBar;
    	private JTextArea uploads;
    	private DataInputStream dis;
    	private DataOutputStream dos;
    	private Socket channel;
     
    	/**
    	 * Create the frame.
    	 */
    	public FileUpload_Server(Socket channel) {
     
    		this.channel=channel;
     
    		setResizable(false);
    		setTitle("Remote Administrator");
    		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    		setBounds(100, 100, 450, 300);
    		contentPane = new JPanel();
    		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    		setContentPane(contentPane);
    		contentPane.setLayout(null);
     
    		JLabel lblFileCurrentlyBeing = new JLabel("File currently being downloaded:");
    		lblFileCurrentlyBeing.setFont(new Font("Dialog", Font.BOLD, 10));
    		lblFileCurrentlyBeing.setBounds(12, 13, 196, 19);
    		contentPane.add(lblFileCurrentlyBeing);
     
    		currentDownload = new JTextField();
    		currentDownload.setEnabled(false);
    		currentDownload.setHorizontalAlignment(SwingConstants.CENTER);
    		currentDownload.setOpaque(false);
    		currentDownload.setEditable(false);
    		currentDownload.setBounds(226, 12, 196, 19);
    		contentPane.add(currentDownload);
    		currentDownload.setColumns(10);
     
    		progressBar = new JProgressBar();
    		progressBar.setEnabled(false);
    		progressBar.setBounds(12, 44, 410, 14);
    		contentPane.add(progressBar);
     
    		uploads = new JTextArea();
    		uploads.setEnabled(false);
    		uploads.setEditable(false);
    		uploads.setBounds(12, 96, 410, 155);
    		contentPane.add(uploads);
     
    		JLabel lblListOfDownloaded = new JLabel("List of downloaded files:");
    		lblListOfDownloaded.setBounds(12, 70, 196, 15);
    		contentPane.add(lblListOfDownloaded);
     
    		setVisible(true);
     
    	}
     
    	@Override
    	public void run() {
     
    		try {
    			dis = new DataInputStream(channel.getInputStream());
    		} catch (IOException e2) {
    			// TODO Auto-generated catch block
    			e2.printStackTrace();
    		}
     
    		try {
    			dos = new DataOutputStream(channel.getOutputStream());
    		} catch (IOException e2) {
    			// TODO Auto-generated catch block
    			e2.printStackTrace();
    		}
     
    		System.out.println("dis and dos initialized");
     
    		int howMany = 0;
    		try {
    			howMany = dis.readInt();
    		} catch (IOException e3) {
    			// TODO Auto-generated catch block
    			e3.printStackTrace();
    		}
     
    		System.out.println("number of files to be transferred: "+howMany);
     
    		File downloadDirectory = new File((new File(".")).getParentFile(),"Uploads");
     
    		downloadDirectory.mkdir();
     
    		for(int i=0; i<howMany; i++){
     
    		//Creating new file
     
    		String currentDownloadFileName = null;
    		try {
    			currentDownloadFileName = dis.readUTF();
    		} catch (IOException e3) {
    			// TODO Auto-generated catch block
    			e3.printStackTrace();
    		}
     
    		File receivedFile = new File(downloadDirectory,currentDownloadFileName);
     
    		currentDownload.setText(currentDownloadFileName);
     
    		long length = 0;
    		try {
    			length = dis.readLong();
    		} catch (IOException e2) {
    			// TODO Auto-generated catch block
    			e2.printStackTrace();
    		}
     
    	    //Receiving its data
    		FileOutputStream wr = null;
    		try {
    			wr = new FileOutputStream(receivedFile);
    		} catch (FileNotFoundException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		}
    		byte[] outBuffer = null;
    		try {
    			outBuffer = new byte[channel.getReceiveBufferSize()];
    		} catch (SocketException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		}
     
    		int bytesReceivedNow = 0;
    		int bytesReceivedUntilNow = 0;
     
    		try {
    			while((bytesReceivedNow = dis.read(outBuffer))>0)
    			{
    				wr.write(outBuffer,0,bytesReceivedNow);
    				bytesReceivedUntilNow += bytesReceivedNow;
    				progressBar.setValue((int)(bytesReceivedUntilNow/length));
    			}
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
     
    		progressBar.setValue(100);
     
    		try {
    			wr.close();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
     
    		currentDownload.setText("");
     
    		uploads.append(receivedFile.getName()+"\n");
     
    		}
     
    		try {
    			channel.close();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
     
    	}
    }

  11. #11
    Junior Member
    Join Date
    Jan 2011
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Thread syncronization JAVA GUI

    Quote Originally Posted by Eric2012 View Post
    Please 1) post the full exception stack trace. 2) Post an SSCCE of the client and server

    what?? I figured the problem out by myself, so I thought I'd post the corrected classes, should anyone need them

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,040
    Thanks
    52
    Thanked 2,280 Times in 2,251 Posts

    Default Re: Thread syncronization JAVA GUI

    Eric2012 is spamming the forum.

  13. #13
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,334
    Thanks
    181
    Thanked 830 Times in 773 Posts
    Blog Entries
    5

    Default Re: Thread syncronization JAVA GUI

    Quote Originally Posted by Norm View Post
    Eric2012 is spamming the forum.
    And Eric2012 has been banned. Thanks Norm.

Similar Threads

  1. java thread programing.
    By parisa in forum Member Introductions
    Replies: 1
    Last Post: July 26th, 2011, 01:38 PM
  2. The Java 7 Thread
    By KevinWorkman in forum The Cafe
    Replies: 4
    Last Post: July 8th, 2011, 11:56 AM
  3. Run Or Cancel Java Thread !
    By byrodi in forum The Cafe
    Replies: 11
    Last Post: November 3rd, 2010, 09:04 AM
  4. Java Thread error plz help me
    By ani1125ster in forum Member Introductions
    Replies: 1
    Last Post: July 12th, 2010, 10:07 AM
  5. Java Thread error plz help me
    By ani1125ster in forum What's Wrong With My Code?
    Replies: 1
    Last Post: July 12th, 2010, 10:07 AM

Tags for this Thread