Passing a Variable Between Different Classes

Passing a socket from a dialogbox back to the mainframe

Page 1 of 1

1 Replies - 4658 Views - Last Post: 02 April 2009 - 03:24 PM Rate Topic: -----

#1 laguan  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 36
  • Joined: 12-March 09

Passing a Variable Between Different Classes

Posted 02 April 2009 - 03:19 PM

For the currnet project in my networking class I have to write a POP3 client to retrieve email messages.
I am using a JDialog to create the socket for communicating with the server, but am unsure how to pass it back to my JFrame after it successfully connects to the specified server and logs in in to an email account so that I can use it for checking mail and retrieving the messages.

This is the code for my JFrame

 import java.awt.*;
 import javax.swing.*;
 import java.lang.*;
 import java.awt.event.*;
 import javax.swing.event.*;
 import javax.swing.table.*;
 import java.io.*;
 
public class MyFrame extends JFrame
	implements ActionListener
{
	JButton				checkMailButton;
	JButton				logInButton;
	JButton				logOutButton;
	JButton				deleteEmailButton;
	JButton				readEmailButton;
	JPanel				buttonPanel;
	DefaultListModel	mailList;
	MailTable			mailTable;
	JTable				mailTableBox;
	JScrollPane			mailTablePane;
	MessageHeader		msgHeader;
	Communicator		communicator;

	public MyFrame() //constructor
	{
		Container cp;
		
		//setup buttons
		
		checkMailButton = new JButton("Check Mail");
		logInButton = new JButton("Login");
		logOutButton = new JButton("Logout");
		deleteEmailButton = new JButton("Delete");
		readEmailButton = new JButton("Read");
		
		checkMailButton.addActionListener(this);
		logInButton.addActionListener(this);
		logOutButton.addActionListener(this);
		deleteEmailButton.addActionListener(this);
		readEmailButton.addActionListener(this);
		
		checkMailButton.setActionCommand("CHECKMAIL");
		logInButton.setActionCommand("LOGIN");
		logOutButton.setActionCommand("LOGOUT");
		deleteEmailButton.setActionCommand("DELETE");
		readEmailButton.setActionCommand("READEMAIL");
		
		buttonPanel = new JPanel();
		
		buttonPanel.add(logInButton);
		buttonPanel.add(logOutButton);
		buttonPanel.add(checkMailButton);
		buttonPanel.add(readEmailButton);
		buttonPanel.add(deleteEmailButton);
		
		//end setup buttons
		
		//setup table
		
		mailList = new DefaultListModel();
		mailTable = new MailTable(mailList);//abastarct table model
		mailTableBox = new JTable(mailTable);
		mailTableBox.setColumnModel(mailTable.setTableColumns());
		mailTablePane = new JScrollPane(mailTableBox);
		
		
		//end setup table
		
		cp = getContentPane();
		
		cp.add(buttonPanel, BorderLayout.NORTH);
		cp.add(mailTablePane, BorderLayout.CENTER);
		setupMainFrame();
		
	}//end of MyFrame contructor
	
	void setupMainFrame()
	{
		Toolkit tk;
		Dimension d;
	
		tk = Toolkit.getDefaultToolkit();
		d = tk.getScreenSize();
		setSize(d.width/2, d.height/2);
		setLocation(d.width/4, d.height/4);
	
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	
		setTitle("POP3 Client");
	
		setVisible(true);
	}// end of setupMainFrame()
	
	public void actionPerformed(ActionEvent e)
	{
		int n;
		
		if(e.getActionCommand().equals("CHECKMAIL"))
		{
			for(n=1; n<4; n++)
			{
				try
				{
					//communicator.retrieveHeaders(msgHeader, n);
				}
				
				catch(IOException rmsgERR)
				{
					JOptionPane.showMessageDialog(this, "Error Logging In.\n" + 
						"Could not retrieve message header.","ERROR", JOptionPane.ERROR_MESSAGE);
				}
				mailList.addElement(msgHeader);
			}
		}
		
		else if(e.getActionCommand().equals("LOGIN"))
		{
			new LoginDialog(communicator);
		}
		
		else if(e.getActionCommand().equals("LOGOUT"))
		{
			
		}
		
		else if(e.getActionCommand().equals("DELETE"))
		{
			
		}
		
		else if(e.getActionCommand().equals("READEMAIL"))
		{
			new DisplayMessage();
		}
	}	
		
}



This is my code for my class that creates the socket and output/input streams and has all my read write methods.

 import java.util.*;
 import java.awt.*;
 import javax.swing.*;
 import java.lang.*;
 import java.awt.event.*;
 import javax.swing.event.*;
 import java.net.*;
 import java.io.*;
 
public class Communicator 
{
	Socket				socket;
	BufferedReader		myReader;
	DataOutputStream	myWriter;
	String				serverName;
	String				sResponse;
	int					msgNumber;
	MessageHeader		msgHeader;
	StringTokenizer		dfST; //string tokenizer for date and from lines
	StringTokenizer		sST; //string tokenizer for subject line
	
	public Communicator(String sName) throws IOException
	{
		serverName = sName;
		//myReader = aReader;
		//myWriter = aDos;
		
		socket = new Socket(serverName, 110);
		socket.setSoTimeout(1000);
		
		myReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		myWriter = new DataOutputStream(socket.getOutputStream()); 
		
		sResponse = myReader.readLine();
		System.out.println("Server:" + sResponse);
		
		
		
	}//end of Communicator constructor
	
	public synchronized void  retrieveHeaders(MessageHeader mHeader, int msgNum) throws IOException
	{
		msgNumber = msgNum;
		msgHeader = mHeader;
		
		myWriter.writeBytes("RETR" + " " + msgNumber + "\n");
		sResponse = myReader.readLine();
		
		if(sResponse.startsWith("+OK+"))
		{
			getDate(msgHeader);
			sResponse = myReader.readLine();
			getFrom(msgHeader);
			sResponse = myReader.readLine();
			getSubject(msgHeader);
			msgHeader.size = 1;
			while(!sResponse.startsWith("."))
			{
				myReader.readLine();
			}
		}//end of +OK response actions
		
		else
			System.out.println("ARF");
			
	}//end of retrieveHeaders
	
	public void getDate(MessageHeader mHeader) throws IOException
	{
		dfST = new StringTokenizer(sResponse,":<");
		
		while(!sResponse.startsWith("Date"))
		{
			sResponse = myReader.readLine();
		}
			
		while(dfST.hasMoreTokens())
		{
			try
			{	
				sResponse = dfST.nextToken();
			}
			
			catch(Exception e)
			{
				System.out.println("Bad shit happend");
			}
		}	
			
		msgHeader.date = sResponse;
			
	}
	
	public void getFrom(MessageHeader mHeader) throws IOException
	{
		dfST = new StringTokenizer(sResponse,":<");
		
		while(!sResponse.startsWith("From"))
		{ 
			sResponse = myReader.readLine();
		}
			while(dfST.hasMoreTokens())
			{
				try
				{	
					sResponse = dfST.nextToken();
				}
				catch(Exception e)
				{
					System.out.println("Bad stuff happend");
				}
			}	
		
		msgHeader.from = sResponse;
	}
	
	public void getSubject(MessageHeader mHeader) throws IOException
	{
		sST = new StringTokenizer(sResponse,":");
		
		while(!sResponse.startsWith("Subject"))
		{
			sResponse = myReader.readLine();
		}
			
		while(sST.hasMoreTokens())
		{
			try
			{
				sResponse = sST.nextToken();
			}
				
			catch(Exception e)
			{
				System.out.println("stuff happend.");
			}
		}
		
		msgHeader.subject = sResponse;
	}
   
	public synchronized void login(String uName, String pWord) throws IOException
	{
		String userName;
		String passWord;
		
		userName = uName;
		passWord = pWord;
		
		
		System.out.println("Server:" + sResponse);
		myWriter.writeBytes("USER" + " " + userName + "\n");
		System.out.println("Client: USER" + " " + userName);
		sResponse = myReader.readLine();
		System.out.println("Server:" + sResponse);
		
		if(sResponse.startsWith("+OK"))
		{
			myWriter.writeBytes("PASS" + " " + passWord+ "\n");
			System.out.println("Client: PASS" + " " + passWord);
			sResponse = myReader.readLine();
			
			System.out.println("Server:" + sResponse);
			
			if(sResponse.startsWith("+OK"))
			{
				myReader.readLine();
				System.out.println("Server:" + sResponse);
			}
			
			else
				throw new IOException();
		}
		
		else
			throw new IOException();
	}
	
}//end of class



and here is the code for my Login JDialog box

 import java.awt.*;
 import javax.swing.*;
 import java.lang.*;
 import java.awt.event.*;
 import javax.swing.event.*;
 import java.io.*;
 
public class LoginDialog extends JDialog
					implements ActionListener
{
	JLabel			nameLabel;
	JLabel			pWordLabel;
	JLabel			serverLabel;
	JTextField		nameTF;
	JPasswordField	pWordTF;
	JTextField		serverTF;
	JButton			loginButton;
	JButton			cancelButton;
	JPanel			buttonPanel;
	JPanel			labelTFPanel;
	String			serverName;
	String			userName;
	String			passWord;
	Communicator	communicator;
	
	public LoginDialog(Communicator aComm)//constructor
	{
		communicator = aComm;
		Container cp;
		
		nameLabel = new JLabel("User Name:");
		pWordLabel = new JLabel("Password:");
		serverLabel = new JLabel("Server:");
		
		nameTF = new JTextField(20);
		pWordTF = new JPasswordField(20);
		serverTF = new JTextField(20);
		
		loginButton = new JButton("Login");
		cancelButton = new JButton("Cancel");
		
		loginButton.setActionCommand("LOGIN");
		cancelButton.setActionCommand("CANCEL");
		
		loginButton.addActionListener(this);
		cancelButton.addActionListener(this);
		
		buttonPanel = new JPanel();
		labelTFPanel = new JPanel(new GridLayout(3,3));
		
		nameTF.setText("laguan@gmx.com");
		pWordTF.setText("llama");
		serverTF.setText("pop.gmx.com");
		
		labelTFPanel.add(nameLabel);
		labelTFPanel.add(nameTF);
		labelTFPanel.add(pWordLabel);
		labelTFPanel.add(pWordTF);
		labelTFPanel.add(serverLabel);
		labelTFPanel.add(serverTF);
		
		buttonPanel.add(loginButton);
		buttonPanel.add(cancelButton);
		
		cp = getContentPane();
		cp.add(labelTFPanel, BorderLayout.CENTER);
		cp.add(buttonPanel, BorderLayout.SOUTH);
		setupLoginDialog();
		
	}//end of constructor
	
void setupLoginDialog()
	{
		Toolkit tk;
		Dimension d;

		tk = Toolkit.getDefaultToolkit();
		d = tk.getScreenSize();								
		setSize(d.width/3, d.height/4);				 	
		setLocation(d.width/4, d.height/4);
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);	
		setTitle("Login");
		setVisible(true);
		setModalityType(Dialog.DEFAULT_MODALITY_TYPE);
	}		   //end of setupDialog()

	
public void actionPerformed(ActionEvent e)
{
	boolean loginOK;
	
	loginOK = false;
	
	if(e.getActionCommand().equals("LOGIN"))
	{
		userName = nameTF.getText().trim();
		passWord = pWordTF.getText().trim();
		serverName = serverTF.getText().trim();
		
		try
		{
			communicator = new Communicator(serverName);
		}
		catch(IOException sErr)
		{
			JOptionPane.showMessageDialog(this, "Error Connecting to " + serverName + ".\n " + 
				"Invalid server name or server is offline.","CONNECTION ERROR", JOptionPane.ERROR_MESSAGE);
		}
		
		try
		{
			communicator.login(userName, passWord);
		}
		
		catch(IOException loginErr)
		{
			JOptionPane.showMessageDialog(this, "Error Logging In.\n" + 
				"Username or password is invalid.","LOGIN ERROR", JOptionPane.ERROR_MESSAGE);
		}
	
		if(loginOK)
		{
			Window window = SwingUtilities.windowForComponent( (Component)e.getSource() );
			WindowEvent windowClosing = new WindowEvent(window, WindowEvent.WINDOW_CLOSING);
			Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(windowClosing);
		}
	}
	
	else if (e.getActionCommand().equals("CANCEL"))
	{
		Window window = SwingUtilities.windowForComponent( (Component)e.getSource() );
		WindowEvent windowClosing = new WindowEvent(window, WindowEvent.WINDOW_CLOSING);
		Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(windowClosing);

	}
}
}



I am getting my Communicator class that makes the socket and streams to the Login dailog by passing it as an argument in its constructor, but it doesn't pass itself back out when the Login dialog closes.

Is This A Good Question/Topic? 0
  • +

Replies To: Passing a Variable Between Different Classes

#2 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8325
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Passing a Variable Between Different Classes

Posted 02 April 2009 - 03:24 PM

You will do

communicator = new Communicator(... somewhere

then just use communicator.socket
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1