School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!
Welcome to Dream.In.Code
Become an Expert!

Join 340,158 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 4,058 people online right now. Registration is fast and FREE... Join Now!



Can I call a method from another window?

Can I call a method from another window? Rate Topic: -----

#1 pillpusher  Icon User is offline

  • New D.I.C Head
  • Pip
  • Group: Members
  • Posts: 33
  • Joined: 13-May 09


Dream Kudos: 0

Posted 31 May 2009 - 09:27 AM

I have a small database app created in Netbeans. The app has a main application window that is used for most all functionality. I want a second window to open so that a file can be chosen and processed, but then I want the second window to close. Before the second window closes, however I want to call a refresh() task which is a method from the first window. Can I do that? The refresh() task refreshes a JTable so that the table will reflect the changes that the uploaded file just made.

The second window is created from the main frame this way:

private void uploadMenuItemActionPerformed(java.awt.event.ActionEvent evt) {											   
			UpdateView updateWindow = new UpdateView(new javax.swing.JFrame());
	}


I want to use the refresh() method at the end of this method:

	private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {											
		String fileToUpload = fileNameTextField.getText();
		if (fileToUpload.isEmpty()) {
			JOptionPane.showMessageDialog(rootPane, "Enter a file name or click Browse");
		} else {
			try {
				boolean success = uploadFile.addUsageFile(fileToUpload, false, "xxx", "xxx");
				// add code later to print/display lines thad did not load
				finished = true;
			}
			catch (NullPointerException npe) {
				JOptionPane.showMessageDialog(rootPane, "File Not Found. Try again.");
			}
			catch (NoSuchElementException nsee) {
					JOptionPane.showMessageDialog(rootPane, "That file is not a valid 340B text file");
				}
			catch (Exception e) {
				JOptionPane.showMessageDialog(rootPane, e.toString());
			}
		}
		if(finished) {
			// I want to call the refresh() method here
			 this.dispose();
		}
	}


And the full code for the second window that opens and processes the text file is:

/*
 * UpdateView.java
 *
 * Created on May 26, 2009, 11:02:34 PM
 */

package three40b;

import java.io.File;
import java.util.*;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 *
 * @author Chad
 */
public class UpdateView extends javax.swing.JDialog {

	// creates new List340B object to use to update inventory
	List340B uploadFile = new List340B();
	public boolean finished = false;

	/** Creates new form UpdateView */
	public UpdateView(java.awt.Frame parent) {
		//constructor to create window
		super(parent);
		initComponents();
		this.setVisible(true);
	}

	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	private void initComponents() {

		jDialog1 = new javax.swing.JDialog();
		jDialog2 = new javax.swing.JDialog();
		jPanel1 = new javax.swing.JPanel();
		exitButton = new javax.swing.JButton();
		startButton = new javax.swing.JButton();
		undoButton = new javax.swing.JButton();
		fileNameTextField = new javax.swing.JTextField();
		browseButton = new javax.swing.JButton();

		jDialog1.setName("jDialog1"); // NOI18N

		javax.swing.GroupLayout jDialog1Layout = new javax.swing.GroupLayout(jDialog1.getContentPane());
		jDialog1.getContentPane().setLayout(jDialog1Layout);
		jDialog1Layout.setHorizontalGroup(
			jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
			.addGap(0, 400, Short.MAX_VALUE)
		);
		jDialog1Layout.setVerticalGroup(
			jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
			.addGap(0, 300, Short.MAX_VALUE)
		);

		jDialog2.setName("jDialog2"); // NOI18N

		javax.swing.GroupLayout jDialog2Layout = new javax.swing.GroupLayout(jDialog2.getContentPane());
		jDialog2.getContentPane().setLayout(jDialog2Layout);
		jDialog2Layout.setHorizontalGroup(
			jDialog2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
			.addGap(0, 400, Short.MAX_VALUE)
		);
		jDialog2Layout.setVerticalGroup(
			jDialog2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
			.addGap(0, 300, Short.MAX_VALUE)
		);

		setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
		org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(three40b.Three40bApp.class).getContext().getResourceMap(UpdateView.class);
		setTitle(resourceMap.getString("Upload.title")); // NOI18N
		setName("Upload"); // NOI18N

		jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel1.border.title"))); // NOI18N
		jPanel1.setName("jPanel1"); // NOI18N

		exitButton.setText(resourceMap.getString("exitButton.text")); // NOI18N
		exitButton.setName("exitButton"); // NOI18N
		exitButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				exitButtonActionPerformed(evt);
			}
		});

		startButton.setText(resourceMap.getString("startButton.text")); // NOI18N
		startButton.setName("startButton"); // NOI18N
		startButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				startButtonActionPerformed(evt);
			}
		});

		undoButton.setText(resourceMap.getString("undoButton.text")); // NOI18N
		undoButton.setName("undoButton"); // NOI18N
		undoButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				undoButtonActionPerformed(evt);
			}
		});

		javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
		jPanel1.setLayout(jPanel1Layout);
		jPanel1Layout.setHorizontalGroup(
			jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
			.addGroup(jPanel1Layout.createSequentialGroup()
				.addContainerGap()
				.addComponent(startButton)
				.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
				.addComponent(exitButton, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
				.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
				.addComponent(undoButton)
				.addContainerGap(52, Short.MAX_VALUE))
		);

		jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {exitButton, startButton, undoButton});

		jPanel1Layout.setVerticalGroup(
			jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
			.addGroup(jPanel1Layout.createSequentialGroup()
				.addContainerGap()
				.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
					.addComponent(startButton)
					.addComponent(exitButton)
					.addComponent(undoButton))
				.addContainerGap(18, Short.MAX_VALUE))
		);

		fileNameTextField.setText(resourceMap.getString("fileNameTextField.text")); // NOI18N
		fileNameTextField.setName("fileNameTextField"); // NOI18N

		browseButton.setText(resourceMap.getString("browseButton.text")); // NOI18N
		browseButton.setName("browseButton"); // NOI18N
		browseButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				browseButtonActionPerformed(evt);
			}
		});

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(
			layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
			.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
			.addGroup(layout.createSequentialGroup()
				.addGap(6, 6, 6)
				.addComponent(fileNameTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 496, Short.MAX_VALUE)
				.addContainerGap())
			.addGroup(layout.createSequentialGroup()
				.addContainerGap()
				.addComponent(browseButton)
				.addContainerGap(390, Short.MAX_VALUE))
		);
		layout.setVerticalGroup(
			layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
			.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
				.addContainerGap()
				.addComponent(fileNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
				.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
				.addComponent(browseButton)
				.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
				.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
				.addContainerGap())
		);

		pack();
	}// </editor-fold>

	private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {											
		String fileToUpload = fileNameTextField.getText();
		if (fileToUpload.isEmpty()) {
			JOptionPane.showMessageDialog(rootPane, "Enter a file name or click Browse");
		} else {
			try {
				boolean success = uploadFile.addUsageFile(fileToUpload, false, "xxx", "xxx");
				// add code later to print/display lines thad did not load
				finished = true;
			}
			catch (NullPointerException npe) {
				JOptionPane.showMessageDialog(rootPane, "File Not Found. Try again.");
			}
			catch (NoSuchElementException nsee) {
					JOptionPane.showMessageDialog(rootPane, "That file is not a valid 340B text file");
				}
			catch (Exception e) {
				JOptionPane.showMessageDialog(rootPane, e.toString());
			}
		}
		if(finished) {
			// I want to call the refresh() method here
			 this.dispose();
		}
	}										   

	private void undoButtonActionPerformed(java.awt.event.ActionEvent evt) {										   

		String fileToUpload = fileNameTextField.getText();
		if (!fileToUpload.isEmpty()) {
			int option = JOptionPane.showConfirmDialog(rootPane, "Are you sure you want to REVERSE the file?", "Confirm Undo File Update", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
			if(option == 0) {
				try {
					boolean success = uploadFile.addUsageFile(fileToUpload, true, "xxx", "xxx");
					// add code later to print/display lines thad did not load
					finished = true;
				}
				catch (NullPointerException npe) {
					JOptionPane.showMessageDialog(rootPane, "File Not Found. Try again.");
				}
				catch (NoSuchElementException nsee) {
					JOptionPane.showMessageDialog(rootPane, "That file is not a valid 340B text file");
				}
				catch (Exception e) {
					JOptionPane.showMessageDialog(rootPane, e.toString());
				}
			} else {
				JOptionPane.showMessageDialog(rootPane, "Enter a file name or click Browse");
			}
		}
		if(finished) {
			// I want to call the refresh() method here
			this.dispose();
		}
	}										  

	private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {											 
		File fileToUpdate = getFile();
		String path = fileToUpdate.getAbsolutePath();
		fileNameTextField.setText(path);
		startButton.requestFocus();
	}											

	private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {										   
		this.dispose();
	}										  

	private File getFile() {
	  // display file dialog, so user can choose file to open
	FileNameExtensionFilter textFilter = new FileNameExtensionFilter("Text File", "txt", "TXT");
	  JFileChooser fileChooser = new JFileChooser();
	  fileChooser.setFileSelectionMode(
		 JFileChooser.FILES_ONLY );
		fileChooser.setFileFilter(textFilter);

	  int result = fileChooser.showOpenDialog( this );

	  // if user clicked Cancel button on dialog, return
	  if ( result == JFileChooser.CANCEL_OPTION )
		 this.dispose();

	  File fileName = fileChooser.getSelectedFile(); // get selected file

	  // display error if invalid
	  if ( ( fileName == null ) || ( fileName.getName().equals( "" ) ) )
	  {
		 JOptionPane.showMessageDialog( this, "Invalid File Name",
			"Invalid File Name", JOptionPane.ERROR_MESSAGE );
		 this.dispose();
	  } // end if

	  return fileName;
   } // end method getFile

	// Variables declaration - do not modify
	private javax.swing.JButton browseButton;
	private javax.swing.JButton exitButton;
	private javax.swing.JTextField fileNameTextField;
	private javax.swing.JDialog jDialog1;
	private javax.swing.JDialog jDialog2;
	private javax.swing.JPanel jPanel1;
	private javax.swing.JButton startButton;
	private javax.swing.JButton undoButton;
	// End of variables declaration

}


The refresh task contained in the main window class is below:

 public Task refresh() {
	   return new RefreshTask(getApplication());
	}

	private class RefreshTask extends Task {
		RefreshTask(org.jdesktop.application.Application app) {
			super(app);
		}

		protected Void doInBackground() {
			try {
				setProgress(0, 0, 4);
				setMessage("Rolling back the current changes...");
				setProgress(1, 0, 4);
				entityManager.getTransaction().rollback();
				setProgress(2, 0, 4);

				setMessage("Starting a new transaction...");
				entityManager.getTransaction().begin();
				setProgress(3, 0, 4);

				setMessage("Fetching new data...");
				java.util.Collection data = query.getResultList();
				for (Object entity : data) {
					entityManager.refresh(entity);
				}
				setProgress(4, 0, 4);

				Thread.sleep(150L);
				list.clear();
				list.addAll(data);
			} catch(InterruptedException ignore) { }
			return null;
		}
		protected void finished() {
			setMessage("Done.");
			setSaveNeeded(false);
		}
	}


The answer is probably something very obvious, but thanks for any help.

This post has been edited by pillpusher: 31 May 2009 - 09:31 AM

Was This Post Helpful? 0
  • +
  • -


#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • Icon
  • View blog
  • Group: Mentors
  • Posts: 7,676
  • Joined: 18-April 07


Dream Kudos: 0

Expert In: C/C++, Java, VB, VB.NET, C#, PHP, Web Development, HTML & CSS, Javascript

Posted 31 May 2009 - 10:32 AM

Well assuming you are passing the first window into the UpdateView constructor as its parent and then storing that reference inside of UpdateView (create a member variable for it) then when you want to call anything from the first window you will just need to call it using your parent variable....

Example...

From first window you launch your second window like so...

// Notice here we use "this" instead of creating a new window.
// Thus we are passing the first window to the second.

UpdateView updateWindow = new UpdateView(this);


// Now in UpdateView class, create a variable to hold our parent
JFrame p;

// In the UpdateView constructor....
public UpdateView(java.awt.Frame parent) {
        //constructor to create window
        super(parent);

        // Set our variable to the parent
        p = parent;

        initComponents();
        this.setVisible(true);
}

// Later down in the code before we close up, we can call refresh back on the parent form...

p.refresh();



This is one way you could do it. Another way would to be to import the owner class in and make sure that the refresh method is public.

Your choice. Enjoy!

"At DIC we be window linking code ninjas... we use to be windows cleaners too, but we are afraid of heights" :snap:
Was This Post Helpful? 0
  • +
  • -

#3 pillpusher  Icon User is offline

  • New D.I.C Head
  • Pip
  • Group: Members
  • Posts: 33
  • Joined: 13-May 09


Dream Kudos: 0

Posted 31 May 2009 - 03:12 PM

I'm still having trouble. I tried to pass the parent into the new window, but my parent window extends FrameView and my second window extends JDialog. So I get a compilation error that there is no valid constructor.

I also tried to import my parent class (and the method is already public), but I'm getting a compilation error "can't find symbol: method refresh()"

I think FrameView is a NetBeans Class; I can't find the Javadoc in the API. I'm going to look on the NetBeans site a while. (I'm beginning to see the problem with using NetBeans to create my GUI !!!)

Can I use multithreading? If I code a button in the first window to create the new window then wait(), then I can notifyall() in the second window when I'm finished, disopose() the second window, then when control returns to the first window, call my refresh function (still under the same button action listener code). Would that work? If you think it will, I've gotta read up on multithreading before I can try it.
Was This Post Helpful? 0
  • +
  • -

#4 pillpusher  Icon User is offline

  • New D.I.C Head
  • Pip
  • Group: Members
  • Posts: 33
  • Joined: 13-May 09


Dream Kudos: 0

Posted 01 June 2009 - 12:41 PM

SOLVED!!!

I didn't really solve this problem. I finally put all of the relevant code from the "UpdateView" class in my main window class, so now I can process my file and then call my refresh() method. Still, if anyone knows how to call the method of a "parent" window from a "child" window where the Component type is different, please let me know.
Was This Post Helpful? 0
  • +
  • -

#5 pillpusher  Icon User is offline

  • New D.I.C Head
  • Pip
  • Group: Members
  • Posts: 33
  • Joined: 13-May 09


Dream Kudos: 0

Posted 08 June 2009 - 07:48 PM

SOLVED!!! (for real this time; no hacks)

In case anyone cares, I finally figured out how to call a method from a second window. Here's what I did:

My main window is a class I created called Three40bView. I created an instance variable and a "set method" in my second window like this:

private Three40bView parentObject = null; 
...
public void setParentObject(Three40bView objectIn) {
		  parentObject = objectIn;
}


Now when I am ready to instantiate the object for my "second window," I do this:

UpdateView secondWindow = new UpdateView();
secondwindow.setParentObject(this); 


Then in my second window, I can call my method this way:

 parentObject.methodFromFirstWindow(); 


Hope this helps someone else.
Was This Post Helpful? 1



Fast Reply

  

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users



Live Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month