Multiple Windows

is setVisible(false) the best way to change windows?

Page 1 of 1

3 Replies - 5794 Views - Last Post: 16 June 2009 - 09:48 PM Rate Topic: -----

#1 pillpusher  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 48
  • Joined: 13-May 09

Multiple Windows

Posted 16 June 2009 - 09:16 PM

I have a small program that I want to expand and use multiple windows (frames) to perform multiple tasks. My original code only has one main view (below). The next Frame I design will have a totally different purpose and function. What is the best way to go from one frame to the next and back again? I found suggestions on another forum to just create all my Frames at once, and setVisible(false) on unused Frames and setVisible(true) on the Frame in use. This seems inefficient; it seems like you'd use up a lot of memory (especially with several Frames). Is there a better way? Should I dispose() of the unused Frame and instantiate a new one when I want to go back to it? Any other suggestions?

/*
 * Three40bView.java
 */


/**
 * The application's main frame.
 */
public class Three40bView extends FrameView {

	public boolean updateFinished = false;
	public String currentOS;
	public boolean isWindows;
	
	public Three40bView(SingleFrameApplication app) {
		super(app);

		initComponents();

		//determine Operating System
		currentOS = System.getProperty("os.name");
		if (currentOS.startsWith("Windows")) {
			isWindows = true;
		} else {
			isWindows = false;
		}

		// status bar initialization - message timeout, idle icon and busy animation, etc
		ResourceMap resourceMap = getResourceMap();
		int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
	messageTimer = new Timer(messageTimeout, new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				statusMessageLabel.setText("");
			}
		});
	messageTimer.setRepeats(false);
		int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
		for (int i = 0; i < busyIcons.length; i++) {
			busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
		}
		busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
				statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
			}
		}); 
		idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
		statusAnimationLabel.setIcon(idleIcon);
		progressBar.setVisible(false);

		// connecting action tasks to status bar via TaskMonitor
		TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
		taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
			public void propertyChange(java.beans.PropertyChangeEvent evt) {
				String propertyName = evt.getPropertyName();
				if ("started".equals(propertyName)) {
					if (!busyIconTimer.isRunning()) {
						statusAnimationLabel.setIcon(busyIcons[0]);
						busyIconIndex = 0;
						busyIconTimer.start();
					}
					progressBar.setVisible(true);
					progressBar.setIndeterminate(true);
				} else if ("done".equals(propertyName)) {
					busyIconTimer.stop();
					statusAnimationLabel.setIcon(idleIcon);
					progressBar.setVisible(false);
					progressBar.setValue(0);
				} else if ("message".equals(propertyName)) {
					String text = (String)(evt.getNewValue());
					statusMessageLabel.setText((text == null) ? "" : text);
					messageTimer.restart();
				} else if ("progress".equals(propertyName)) {
					int value = (Integer)(evt.getNewValue());
					progressBar.setVisible(true);
					progressBar.setIndeterminate(false);
					progressBar.setValue(value);
				}
			}
		});

		// tracking table selection
		masterTable.getSelectionModel().addListSelectionListener(
			new ListSelectionListener() {
				public void valueChanged(ListSelectionEvent e) {
					firePropertyChange("recordSelected", !isRecordSelected(), isRecordSelected());
				}
			});

		// tracking changes to save
		bindingGroup.addBindingListener(new AbstractBindingListener() {
			@Override
			public void targetChanged(Binding binding, PropertyStateEvent event) {
				// save action observes saveNeeded property
				setSaveNeeded(true);
			}
		});

		// have a transaction started
		entityManager.getTransaction().begin();

		Three40bView mainFrame = this;

		//Upon opening application, sort Table, refresh, save, and set focus in search window
		sortDB();
		setSaveNeeded(true);
		RefreshTask newRefresh = new RefreshTask(getApplication());
		newRefresh.doInBackground();
		searchTextField.requestFocus();
		searchTextField.selectAll();

	}

	public boolean isSaveNeeded() {
		return saveNeeded;
	}

	private void setSaveNeeded(boolean saveNeeded) {
		if (saveNeeded != this.saveNeeded) {
			this.saveNeeded = saveNeeded;
			firePropertyChange("saveNeeded", !saveNeeded, saveNeeded);
		}
	}

	public boolean isRecordSelected() {
		return masterTable.getSelectedRow() != -1;
	}
	

	@Action
	public void newRecord() {
		three40b.Drugs d = new three40b.Drugs();
		entityManager.persist(d);
		list.add(d);
		int row = list.size()-1;
		masterTable.setRowSelectionInterval(row, row);
		masterTable.scrollRectToVisible(masterTable.getCellRect(row, 0, true));
		setSaveNeeded(true);
		hospIdField.requestFocus();
	}

	@Action(enabledProperty = "recordSelected")
	public void deleteRecord() {
		int option = JOptionPane.showConfirmDialog(getComponent(), "Are you sure you want to \nDELETE the record? \nYou cannot undo this action.", "Confirm DELETE Record", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
		if (option == 0) {
			int[] selected = masterTable.getSelectedRows();
			List<three40b.Drugs> toRemove = new ArrayList<three40b.Drugs>(selected.length);
			for (int idx=0; idx<selected.length; idx++) {
				three40b.Drugs d = list.get(masterTable.convertRowIndexToModel(selected[idx]));
				toRemove.add(d);
				entityManager.remove(d);
			}
			list.removeAll(toRemove);
			setSaveNeeded(true);
			SaveTask saveAfterDelete = new SaveTask(getApplication());
			saveAfterDelete.doInBackground();
			searchTextField.requestFocus();
			searchTextField.selectAll();
		}
		else if (option != 0) {
			searchTextField.requestFocus();
			searchTextField.selectAll();
		}
	}
	

	@Action(enabledProperty = "saveNeeded")
	public Task save() {
		return new SaveTask(getApplication());
	}

	private class SaveTask extends Task {
		SaveTask(org.jdesktop.application.Application app) {
			super(app);
		}
		@Override protected Void doInBackground() {
			try {
				entityManager.getTransaction().commit();
				entityManager.getTransaction().begin();
			} catch (RollbackException rex) {
				rex.printStackTrace();
				entityManager.getTransaction().begin();
				List<three40b.Drugs> merged = new ArrayList<three40b.Drugs>(list.size());
				for (three40b.Drugs d : list) {
					merged.add(entityManager.merge(d));
				}
				list.clear();
				list.addAll(merged);
			}
			return null;
		}
		@Override protected void finished() {
			setSaveNeeded(false);
		}
	}

	/**
	 * An example action method showing how to create asynchronous tasks
	 * (running on background) and how to show their progress. Note the
	 * artificial 'Thread.sleep' calls making the task long enough to see the
	 * progress visualization - remove the sleeps for real application.
	 */

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

	private class RefreshTask extends Task {
		RefreshTask(org.jdesktop.application.Application app) {
			super(app);
		}
		@SuppressWarnings("unchecked")
		@Override protected Void doInBackground() {
			try {
				setProgress(0, 0, 4);
				setMessage("Rolling back the current changes...");
				setProgress(1, 0, 4);
				entityManager.getTransaction().rollback();
				//Thread.sleep(1000L); // remove for real app
				setProgress(2, 0, 4);

				setMessage("Starting a new transaction...");
				entityManager.getTransaction().begin();
				//Thread.sleep(500L); // remove for real app
				setProgress(3, 0, 4);

				setMessage("Fetching new data...");
				java.util.Collection data = query.getResultList();
				for (Object entity : data) {
					entityManager.refresh(entity);
				}
				//Thread.sleep(1300L); // remove for real app
				setProgress(4, 0, 4);

				Thread.sleep(150L); // remove for real app
				list.clear();
				list.addAll(data);
			} catch(InterruptedException ignore) { }
			return null;
		}
		@Override protected void finished() {
			setMessage("Done.");
			setSaveNeeded(false);
		}
	}

	@Action
	public void showAboutBox() {
		if (aboutBox == null) {
			JFrame mainFrame = Three40bApp.getApplication().getMainFrame();
			aboutBox = new Three40bAboutBox(mainFrame);
			aboutBox.setLocationRelativeTo(mainFrame);
		}
		Three40bApp.getApplication().show(aboutBox);
	}

	private void purchasedButtonActionPerformed(java.awt.event.ActionEvent evt) {												
		// Purchased button clicked
		// Subtract the quantity and save the current record
		if(isRecordSelected()) {
			int oldQuan = Integer.parseInt(quanField.getText());
			int quanToSubtract = Integer.parseInt(quanUpdateTextField.getText());
			int newQuan = oldQuan - quanToSubtract;
			String newQuanString = String.format("%d", newQuan);
			quanField.setText(newQuanString);
			quanUpdateTextField.setText("");
			saveAndRefresh();
		}
		else if (!isRecordSelected()) {
			JOptionPane.showMessageDialog(getComponent(), "You must select a record first.");
			quanUpdateTextField.requestFocus();
			quanUpdateTextField.selectAll();
		}
	}											   

	@SuppressWarnings("static-access")
	private void dispensedButtonActionPerformed(java.awt.event.ActionEvent evt) {												
		// Dispensed button clicked
		// Add the quantity and save the current record
		if(isRecordSelected()) {
			Calendar todaysDate = Calendar.getInstance();
			@SuppressWarnings("static-access")
			int currentMonth = 1 + todaysDate.get(todaysDate.MONTH);
			// January = 0 so we have to add 1 to the month value
			@SuppressWarnings("static-access")
			String todayString = todaysDate.get(todaysDate.YEAR) + "-";
			todayString += currentMonth + "-";
			todayString += todaysDate.get(todaysDate.DAY_OF_MONTH) + " ";
			todayString += todaysDate.get(todaysDate.HOUR_OF_DAY) + ":";
			todayString += todaysDate.get(todaysDate.MINUTE) + ":";
			todayString += todaysDate.get(todaysDate.SECOND);

			int oldQuan = Integer.parseInt(quanField.getText());
			int quanToAdd = Integer.parseInt(quanUpdateTextField.getText());
			int selectedID = Integer.parseInt(hospIdField.getText());

			String notes = JOptionPane.showInputDialog(getComponent(), "Please type a note stating who got these doses.");

			if(notes == null) {
				quanUpdateTextField.setText("");
				quanUpdateTextField.requestFocus();
				return;
			}
			// write to dispense Database
			Connection connection = null;
			Statement statement = null;
			ResultSet resultSet = null;
			try {
				Class.forName("com.mysql.jdbc.Driver");
				connection = DriverManager.getConnection("jdbc:mysql://localhost/three40b", "xxx", "xxx");
				statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

				String query2 = "INSERT INTO dispense (date, hosp_id, quan, notes) VALUES";
			query2 += "('" + todayString + "', '" + selectedID + "', '" + quanToAdd + "', '" + notes + "')";

			statement.execute(query2);
			
			}
			catch (SQLException sqlEx) {
				sqlEx.printStackTrace();
			}
			catch (ClassNotFoundException clnfEx) {
				clnfEx.printStackTrace();
			}
			finally {
				try {
					statement.close();
					connection.close();
				}
				catch (Exception exception) {
					exception.printStackTrace();
				}
			}//end try-catch-finally block

			int newQuan = oldQuan + quanToAdd;
			String newQuanString = String.format("%d", newQuan);
			quanField.setText(newQuanString);
			quanUpdateTextField.setText("");
			saveAndRefresh();
		}
		else if (!isRecordSelected()) {
			JOptionPane.showMessageDialog(getComponent(), "You must select a record first.");
			quanUpdateTextField.requestFocus();
			quanUpdateTextField.selectAll();
		}
	}											   

	private void uploadMenuItemActionPerformed(java.awt.event.ActionEvent evt) {											   
		fileToUpload = getFile().getAbsolutePath();
		
		if (fileToUpload != null) {
			Upload340BUsage uploadList = new Upload340BUsage();
			uploadList.setUserName("xxx");
			uploadList.setPassword("xxx");
			uploadList.setUpdateFileName(fileToUpload);
			uploadList.setToUndo(false);
			uploadList.setParentObject(this);
			try {
				uploadList.execute();
			}
			catch (NullPointerException npe) {
				JOptionPane.showMessageDialog(getComponent(), "File Not Found. Try again.");
			}
			catch (NoSuchElementException nsee) {
				JOptionPane.showMessageDialog(getComponent(), "That file is not a valid 340B text file");
				}
			catch (Exception e) {
				JOptionPane.showMessageDialog(getComponent(), e.toString());
			}
			finally {
				progressBar.setVisible(false);
				statusMessageLabel.setText("");
			}
		} else if (fileToUpload == null) {
			return;
		}
	}											  

	protected void saveAndRefresh() {
		//performed after file upload
		setSaveNeeded(true);
		SaveTask newSave = new SaveTask(getApplication());
		newSave.doInBackground();
		RefreshTask newRefresh = new RefreshTask(getApplication());
		newRefresh.doInBackground();
		searchTextField.requestFocus();
		searchTextField.selectAll();
	}

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

		int option = JOptionPane.showConfirmDialog(getComponent(), "Are you sure you want to \nUNDO the file upload?", "Confirm Undo File Update", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
		if(option == 0) {
			fileToUpload = getFile().getAbsolutePath();
			if (fileToUpload != null)  {
				Upload340BUsage uploadList = new Upload340BUsage();
				uploadList.setUserName("xxx");
				uploadList.setPassword("xxx");
				uploadList.setUpdateFileName(fileToUpload);
				uploadList.setToUndo(true);
				uploadList.setParentObject(this);
				try {
					uploadList.execute();
				}
				catch (NullPointerException npe) {
					JOptionPane.showMessageDialog(getComponent(), "File Not Found. Try again.");
				}
				catch (NoSuchElementException nsee) {
					JOptionPane.showMessageDialog(getComponent(), "That file is not a valid 340B text file");
					}
				catch (Exception e) {
					JOptionPane.showMessageDialog(getComponent(), e.toString());
				}
				finally {
					progressBar.setVisible(false);
					statusMessageLabel.setText("");
				}
			} else if (fileToUpload == null) {
				return;
			}
		}
	}											

	private void sortDB() {
			Connection connection = null;
			Statement statement = null;
			try {
				Class.forName("com.mysql.jdbc.Driver");
				connection = DriverManager.getConnection("jdbc:mysql://localhost/three40b", "xxx", "xxx");
				statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
				String querySort = "ALTER TABLE `drugs`  ORDER BY `description`";
				statement.execute(querySort);
			}
			catch (SQLException sqlEx) {
				sqlEx.printStackTrace();
			}
			catch (ClassNotFoundException clnfEx) {
				clnfEx.printStackTrace();
			}
			finally {
				try {
					statement.close();
					connection.close();
				}
				catch (Exception exception) {
					exception.printStackTrace();
				}
			}//end try-catch-finally block

		saveAndRefresh();
	}

	private void sortMenuItemActionPerformed(java.awt.event.ActionEvent evt) {											 
		sortDB();
			
	}											

	private void printMenuItemActionPerformed(java.awt.event.ActionEvent evt) {											  
		sortDB();
		setSaveNeeded(true);
		RefreshTask newRefresh = new RefreshTask(getApplication());
		newRefresh.doInBackground();
		searchTextField.requestFocus();
		searchTextField.selectAll();
		MessageFormat footer = new MessageFormat("Page {0}");
		try {
			boolean complete = masterTable.print(JTable.PrintMode.FIT_WIDTH, null, footer);
		} catch (PrinterException pe) {
			JOptionPane.showMessageDialog(getComponent(), "Printing Error \n\n" + pe);
		}

	}											 

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

			if (result == JFileChooser.APPROVE_OPTION) {
				fileName = fileChooser.getSelectedFile(); // get selected file
			}
			if (result == JFileChooser.CANCEL_OPTION) {
				fileName = null;
				return fileName;
			}
			// display error if invalid
			if ( ( fileName == null ) || ( fileName.getName().equals( "" ) ) )
			{
				JOptionPane.showMessageDialog( getComponent(), "Invalid File Name", "Invalid File Name", JOptionPane.ERROR_MESSAGE );
			} // end if
		
	  return fileName;
   } // end method getFile

	// Variables declaration - do not modify					 
	private javax.swing.JButton deleteButton;
	private javax.swing.JTextField descriptionField;
	private javax.swing.JLabel descriptionLabel;
	private javax.swing.JButton dispensedButton;
	private javax.persistence.EntityManager entityManager;
	private javax.swing.JTextField hospIdField;
	private javax.swing.JLabel hospIdLabel;
	private javax.swing.JLabel jLabel1;
	private javax.swing.JLabel jLabel2;
	private javax.swing.JPanel jPanel1;
	private javax.swing.JPanel jPanel2;
	private javax.swing.JPanel jPanel3;
	private javax.swing.JSeparator jSeparator1;
	private javax.swing.JSeparator jSeparator2;
	private java.util.List<three40b.Drugs> list;
	private javax.swing.JPanel mainPanel;
	private javax.swing.JScrollPane masterScrollPane;
	private javax.swing.JTable masterTable;
	private javax.swing.JMenuBar menuBar;
	private javax.swing.JButton newButton;
	private javax.swing.JMenuItem printMenuItem;
	protected javax.swing.JProgressBar progressBar;
	private javax.swing.JButton purchasedButton;
	private javax.swing.JTextField quanField;
	private javax.swing.JLabel quanLabel;
	private javax.swing.JTextField quanUpdateTextField;
	private javax.persistence.Query query;
	private javax.swing.JButton refreshButton;
	private three40b.RowSorterToStringConverter rowSorterToStringConverter1;
	private javax.swing.JButton saveButton;
	private javax.swing.JTextField searchTextField;
	private javax.swing.JMenuItem sortMenuItem;
	private javax.swing.JLabel statusAnimationLabel;
	protected javax.swing.JLabel statusMessageLabel;
	private javax.swing.JPanel statusPanel;
	private javax.swing.JMenuItem undoMenuItem;
	private javax.swing.JMenuItem uploadMenuItem;
	private org.jdesktop.beansbinding.BindingGroup bindingGroup;
	// End of variables declaration				   

	private final Timer messageTimer;
	private final Timer busyIconTimer;
	private final Icon idleIcon;
	private final Icon[] busyIcons = new Icon[15];
	private int busyIconIndex = 0;

	private JDialog aboutBox;

	private boolean saveNeeded;

	private String fileToUpload;
}



Is This A Good Question/Topic? 0
  • +

Replies To: Multiple Windows

#2 Fuzzyness  Icon User is offline

  • Comp Sci Student
  • member icon

Reputation: 669
  • View blog
  • Posts: 2,438
  • Joined: 06-March 09

Re: Multiple Windows

Posted 16 June 2009 - 09:26 PM

I too have faced a problem with that in my previous Project of a database that consumed a Main Frame- Admin Frame - Guest Frame. What I ended up doing in the end, is having the admin Frame and Guest Frame take a MainFrame as a param, and setting visible to false in constructor, then setting it to true upon an exit. I have recently looked over an interface WindowListener. Some methods from it are:
windowActivated(WindowEvent);
windowClosed(WindowEvent);
windowDeactivated(WindowEvent);
windowOpened(WindowEvent);

and for a window Object, like a frame you can also use a method called setEnabled(false);

Hope this helps!

This post has been edited by Fuzzyness: 16 June 2009 - 09:34 PM

Was This Post Helpful? 0
  • +
  • -

#3 pillpusher  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 48
  • Joined: 13-May 09

Re: Multiple Windows

Posted 16 June 2009 - 09:45 PM

View PostFuzzyness, on 16 Jun, 2009 - 10:26 PM, said:

I have recently looked over an interface WindowListener. Some methods from it are:
windowActivated(WindowEvent);
windowClosed(WindowEvent);
windowDeactivated(WindowEvent);
windowOpened(WindowEvent);

and for a window Object, like a frame you can also use a method called setEnabled(false);


Thanks! I'll check these out. Do you know if setEnable(false) releases assets and frees memory, etc.? It just seems like there would be a better way to handle this. Maybe someone should create a class "FrameHandler" to efficiently handle multiple views without all the memory overhead.
Was This Post Helpful? 0
  • +
  • -

#4 Fuzzyness  Icon User is offline

  • Comp Sci Student
  • member icon

Reputation: 669
  • View blog
  • Posts: 2,438
  • Joined: 06-March 09

Re: Multiple Windows

Posted 16 June 2009 - 09:48 PM

I am not too positively sure on that one. I know a book I was looking at when I stumbled across it said that that disables the control for user input. I am not too sure you can really release memory. I suppose one thing you may be able to do is everytime you open anew frame, just dispose of the class you use to open the new frame, but when you close the frame you opened, make a new object of the previous frame and set it to visible? Hope I didnt lose you there. Maybe the great pbl here has a better solution to this.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1