Results 1 to 2 of 2
  1. #1
    FezKazi is offline Member
    Join Date
    Feb 2009
    Posts
    6
    Rep Power
    0

    Post JFrame created but window contents not showing, othr threads keep waiting on the user

    JFrame created but window contents not showing, othr threads keep waiting on the user input thatll never happn?
    this is all Java (1.6) code
    This window is created when I create a Win_TF_Layout myInputWindow = new Win_TF_Layout("Enter First and Last Name");

    However, the contents of the window DONT show... and therefore my other threads keep waiting on user input that will never happen because the user cant input anything!!

    also, i dont know why, but in eclipse, in debug mode the pointer always stops at the Win_TF_Layout contructor, and i cant figure out why!! resuming, or stepping into or over the contructor works fine, without errors, but why does it stop in the first place?

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    
    import javax.swing.*;
    
    
    public class Win_TF_Layout extends JFrame implements WindowListener,Runnable{
    	/**
    *
    */
    	private static final long serialVersionUID = -2014883727455286095L;
    	private static String newline;
    	private static String space;
    	//static Win_TF_Layout frame = new Win_TF_Layout("Window With Text Fields in my layout");
    	protected Win_TF_Layout frame;
    	protected JTextArea display;
    	protected JComponent myPanel;
    	protected String FirstName;
    	protected String LastName;
    	protected JTextField firstName;
    	protected JTextField lastName;
    	protected Boolean quit;
    
    	protected String tName;
    	protected Thread t;
    
    	public Win_TF_Layout(String name) {
    		//System.out.println("HELLO");
    		super(name);
    		frame = this;
    		try {
    			//UIManager.setLookAndFeel("com.sun.java.swing.plaf. windows.WindowsLookAndFeel");
    			//UIManager.setLookAndFeel("com.sun.java.swing.plaf. gtk.GTKLookAndFeel");
    			UIManager.setLookAndFeel("javax.swing.plaf.metal.M etalLookAndFeel");
    		} catch (UnsupportedLookAndFeelException ex) {
    			ex.printStackTrace();
    		} catch (IllegalAccessException ex) {
    			ex.printStackTrace();
    		} catch (InstantiationException ex) {
    			ex.printStackTrace();
    		} catch (ClassNotFoundException ex) {
    			ex.printStackTrace();
    		}
    		/* Turn off metal's use of bold fonts */
    		UIManager.put("swing.boldMetal", Boolean.FALSE);
    
    		tName = name;
    		t = new Thread (this, tName);
    		t.setPriority(Thread.MAX_PRIORITY);
    
    		FirstName = null;
    		LastName = null;
    		quit = false;
    		space = " ";
    		newline = System.getProperty("line.separator");
    
    		t.start();
    	}
    
    	/**
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    */
    
    	private void createAndShowGUI() {
    		//Create and set up the window.
    		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_C LOSE);
    
    		//set up grid bad layout
    		//Create the fields and set them up
    		firstName = new JTextField(20);
    		JLabel firstNameLabel = new JLabel("First Name:");
    		firstNameLabel.setDisplayedMnemonic('N');
    		firstNameLabel.setLabelFor(firstNameLabel);
    		lastName = new JTextField(20);
    		JLabel lastNameLabel = new JLabel("Last Name:");
    		lastNameLabel.setDisplayedMnemonic('N');
    		lastNameLabel.setLabelFor(lastNameLabel);
    
    		display = new JTextArea(5,20);
    		display.setEditable(false);
    		JScrollPane scrollPane = new JScrollPane(display);
    		scrollPane.setPreferredSize(new Dimension(400, 200));
    
    		// JTextField areaCode = new JTextField(3);
    		// JLabel phoneLabel = new JLabel("Phone:");
    		// phoneLabel.setDisplayedMnemonic('P');
    		// phoneLabel.setLabelFor(areaCode);
    		// JTextField prefix = new JTextField(3);
    		// JTextField number = new JTextField(3);
    		// JTextField email = new JTextField(20);
    		// JLabel emailLabel = new JLabel("Email:");
    		// emailLabel.setDisplayedMnemonic('E');
    		// emailLabel.setLabelFor(email);
    		JButton okButton = new JButton("OK");
    		okButton.setPreferredSize(new Dimension(100,
    		(int) okButton.getPreferredSize().getHeight()));
    		okButton.addActionListener(new ActionListener() {
    			@Override
    			public void actionPerformed(ActionEvent arg0) {
    				//SUBMIT DATA
    				FirstName = firstName.getText();
    				LastName = lastName.getText();
    				//System.out.println("Name entered was:\t" + FirstName + "\t" + LastName );
    				quit = true;
    				frame.dispose();
    				//this.notifyAll();
    			}
    		});
    		JButton cancelButton = new JButton("Cancel");
    		cancelButton.addActionListener(new ActionListener(){
    			@Override
    			public void actionPerformed(ActionEvent arg0) {
    				quit = true;
    				frame.dispose();
    			}
    		});
    		cancelButton.setPreferredSize(new Dimension(100,
    		(int) cancelButton.getPreferredSize().getHeight()));
    
    		JPanel panel = new JPanel(new GridBagLayout());
    		panel.setBorder(BorderFactory.createEmptyBorder(4, 10, 10, 10));
    
    		GridBagConstraints gbc = new GridBagConstraints();
    		gbc.anchor = GridBagConstraints.WEST;
    		gbc.fill = GridBagConstraints.HORIZONTAL;
    		gbc.insets = new Insets(6, 6, 0, 0);
    		gbc.gridx = GridBagConstraints.RELATIVE;
    		gbc.gridy = 0;
    
    		panel.add(firstNameLabel, gbc);
    		gbc.gridwidth = GridBagConstraints.REMAINDER;
    		panel.add(firstName, gbc);
    
    		gbc.gridy++;
    		gbc.gridwidth = 1;
    
    		panel.add(lastNameLabel, gbc);
    		gbc.gridwidth = GridBagConstraints.REMAINDER;
    		panel.add(lastName, gbc);
    
    		gbc.gridy++;
    		gbc.gridwidth = 2;
    
    		panel.add(scrollPane, gbc);
    		gbc.gridwidth = GridBagConstraints.REMAINDER;
    
    
    		// panel.add(phoneLabel, gbc);
    		// panel.add(areaCode, gbc);
    		// panel.add(prefix, gbc);
    		// panel.add(number, gbc);
    		//
    		// gbc.gridy++;
    		// panel.add(emailLabel, gbc);
    		// gbc.gridwidth = GridBagConstraints.REMAINDER;
    		// gbc.weightx = 1;
    		// panel.add(email, gbc);
    
    		JPanel buttonPanel = new JPanel(new GridBagLayout());
    		gbc.gridwidth = 1;
    		gbc.gridy = 0;
    		buttonPanel.add(okButton, gbc);
    		buttonPanel.add(cancelButton, gbc);
    
    		panel.add(buttonPanel,
    		new GridBagConstraints(1, 3, 4, 1, 0, 0,
    		GridBagConstraints.EAST, GridBagConstraints.NONE,
    		new Insets(0, 0, 0, 0), 0, 0));
    
    		panel.add(Box.createGlue(),
    		new GridBagConstraints(0, 4, 4, 1, 0, 1,
    		GridBagConstraints.EAST, GridBagConstraints.NONE,
    		new Insets(0, 0, 0, 0), 0, 0));
    
    		//Set up the content pane.
    		//myPanel = buildGridBagLayout();
    		panel.setOpaque(true); //content panes must be opaque
    		frame.setContentPane(panel);
    		addWindowListener(this);
    
    		//Display the window.
    		//frame.setSize( 300, 250 );
    		frame.pack();
    		frame.setVisible(true);
    		System.out.println("Win_TF_Layout GUI method is finishing up");
    	}
    
    	public void windowClosing(WindowEvent e) {
    		displayMessage("WindowListener method called: windowClosing.");
    		//A pause so user can see the message before
    		//the window actually closes.
    		ActionListener task = new ActionListener() {
    			boolean alreadyDisposed = false;
    			public void actionPerformed(ActionEvent e) {
    				if (frame.isDisplayable()) {
    					alreadyDisposed = true;
    					frame.dispose();
    				}
    			}
    		};
    		Timer timer = new Timer(500, task); //fire every half second
    		timer.setInitialDelay(2000); //first delay 2 seconds
    		timer.setRepeats(false);
    		timer.start();
    		quit = true;
    		frame.dispose();
    	}
    
    	public void windowClosed(WindowEvent e) {
    		//This will only be seen on standard output.
    		displayMessage("WindowListener method called: Input window closed.");
    	}
    
    	public void windowOpened(WindowEvent e) {
    		// displayMessage("WindowListener method called: windowOpened.");
    	}
    
    	public void windowIconified(WindowEvent e) {
    		// displayMessage("WindowListener method called: windowIconified.");
    	}
    
    	public void windowDeiconified(WindowEvent e) {
    		// displayMessage("WindowListener method called: windowDeiconified.");
    	}
    
    	public void windowActivated(WindowEvent e) {
    		// displayMessage("WindowListener method called: windowActivated.");
    	}
    
    	public void windowDeactivated(WindowEvent e) {
    		// displayMessage("WindowListener method called: windowDeactivated.");
    	}
    
    	public void windowGainedFocus(WindowEvent e) {
    		// displayMessage("WindowFocusListener method called: windowGainedFocus.");
    	}
    
    	public void windowLostFocus(WindowEvent e) {
    		// displayMessage("WindowFocusListener method called: windowLostFocus.");
    	}
    
    	public void windowStateChanged(WindowEvent e) {
    		// displayStateMessage(
    		// "WindowStateListener method called: windowStateChanged.", e);
    	}
    
    	private void displayMessage(String msg) {
    		display.append(msg + newline);
    		System.out.println(msg);
    	}
    
    	private void displayStateMessage(String prefix, WindowEvent e) {
    		int state = e.getNewState();
    		int oldState = e.getOldState();
    		String msg = prefix
    		+ newline + space
    		+ "New state: "
    		+ convertStateToString(state)
    		+ newline + space
    		+ "Old state: "
    		+ convertStateToString(oldState);
    		displayMessage(msg);
    	}
    
    	private String convertStateToString(int state) {
    		if (state == Frame.NORMAL) {
    			return "NORMAL";
    		}
    		String strState = " ";
    		if ((state & Frame.ICONIFIED) != 0) {
    			strState += "ICONIFIED";
    		}
    		//MAXIMIZED_BOTH is a concatenation of two bits, so
    		//we need to test for an exact match.
    		if ((state & Frame.MAXIMIZED_BOTH) == Frame.MAXIMIZED_BOTH) {
    			strState += "MAXIMIZED_BOTH";
    		} else {
    			if ((state & Frame.MAXIMIZED_VERT) != 0) {
    				strState += "MAXIMIZED_VERT";
    			}
    			if ((state & Frame.MAXIMIZED_HORIZ) != 0) {
    				strState += "MAXIMIZED_HORIZ";
    			}
    		}
    		if (" ".equals(strState)){
    			strState = "UNKNOWN";
    		}
    		return strState.trim();
    	}
    
    	public boolean quit(){
    		return quit;
    	}
    	/**
    * Returns the First Name and Last Name that should have been input correctly
    * @return null if the data was not input, else return a String array with First, then Last name.
    */
    	public String[] getNamesInput () {
    		if ( FirstName == null || LastName == null )
    		return null;
    		else {
    			String[] names = new String[2];
    			names[0] = FirstName;
    			names[1] = LastName;
    			return names;
    		}
    	}
    
    	@Override
    	public void run() {
    		//Schedule a job for the event dispatch thread:
    		//creating and showing this application's GUI.
    		// javax.swing.SwingUtilities.invokeLater(new Runnable() {
    		// public void run() {
    		// createAndShowGUI();
    		// }
    		// });
    		createAndShowGUI();
    		System.out.println("Win_TF_Layout GUI created");
    		frame.dispose();
    
    		while (!quit) {
    			try {
    
    				System.out.println(Thread.currentThread().getName( ) + " priority: " + Thread.currentThread().getPriority());
    				Thread.currentThread().setPriority(Thread.MAX_PRIO RITY);
    				System.out.println(Thread.currentThread().getName( ) + " is sleeping!");
    				Thread.sleep(1000);
    			} catch (InterruptedException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}
    	}
    }
    Last edited by FezKazi; 02-20-2009 at 01:18 PM.

  2. #2
    Steve11235's Avatar
    Steve11235 is offline Senior Member
    Join Date
    Dec 2008
    Posts
    1,046
    Rep Power
    7

    Default

    First, I suggest using OO design principles on even the most trivial applications. Cramming all this code into one class makes it very difficult to follow. At a minimum, create a controller and a view class. The controller should instantiate the view and start the GUI. The view should only create the components and have minimal code for accessing them, such as getting and setting component text. Event handling is a matter of personal style, since they couple the view and controller no matter what you do, but I prefer to let the controller listen to the views events, unless the event *only* updates the view.

    As far as your code, why are you creating a thread? Once you start the EDT, the main thread remains available, if you really need it. However, most GUI apps allow the main thread to terminate, leaving *only* the EDT. GUI events are handled on the EDT. The only reason to have worker threads is if you have a *long* running operation started by a GUI event, and you want the GUI to remain responsive while the operation runs.

    Setting a thread to max priority will just make your GUI less responsive, if it does anything at all. Generally, leave thread priorities alone.

    You have comments about running the GUI on the EDT, but you never mention EventQueue, must less invokeLater(). This is not essential, but it is good practice.

    If the debugger is stopping, it is generally because it encountered an exception. Debugging with threads is more complicated, so you need to put a break point at the entry point of each thread. Click on the thread to step through it, if the debugger doesn't switch over by itself.

    So, debug your program, starting in the main. Watch out for points where control will switch to a different thread. Watch what is happening. Look at the output on the console.

Similar Threads

  1. Calling a JFrame window from a command line program.
    By new_2_java in forum New To Java
    Replies: 7
    Last Post: 11-09-2008, 03:40 AM
  2. Once again: waiting in a thread loop.
    By willemjav in forum Threads and Synchronization
    Replies: 115
    Last Post: 09-22-2008, 01:35 PM
  3. Detecting user movement of a JFrame
    By dklett in forum AWT / Swing
    Replies: 4
    Last Post: 08-27-2008, 07:01 AM
  4. waiting for a file
    By Fleur in forum New To Java
    Replies: 2
    Last Post: 06-23-2008, 08:18 PM
  5. How to close an open JFrame window from a jsp page?
    By kasisaiganesh in forum JavaServer Pages (JSP) and JSTL
    Replies: 1
    Last Post: 05-27-2008, 06:29 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •