• 0

[Java] Swing -- Closes immediately after opened


Question

Hi all,

Something strange is up with my app.

It's only two classes thus far. One has the bulk of the code and the other has a main method, which instantiates an object of type (the other class). In doing so, the constructor of the other class does appropriate operations as I'd like and then calls upon the display method.. but after it does that, the java swing window (JFrame) instantly closes.

Any ideas?

Here's the method that's supposed to do the displaying. it's not really what it's supposed to end up doing, but ... you get the idea (I hope) :p

 // (javax.swing.* was imported at the top of the class)
public void displayStats()
	{
		JFrame.setDefaultLookAndFeelDecorated(true);
		JFrame fr = new JFrame("Statistician - Results");

		fr.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		JLabel label = new JLabel("hiiiii");
		JComponent comp = new JTextArea();
		fr.getContentPane().add(label);
		fr.getContentPane().add(comp, 100);

		fr.setSize(100,300);
		fr.pack();
		fr.setVisible(true);
	}

Thanks,,

--dt

12 answers to this question

Recommended Posts

  • 0
  Wheazel said:

you forgot the specify the layout manager

frame.setLayout(new BorderLayout());

That didn't help; it still closes immediately. :(

Here's what I've got so far.

(java.awt.BorderLayout and javax.swing.* are both imported at the top of the class)

	public void displayStats()
	{
		JFrame.setDefaultLookAndFeelDecorated(true);
		JFrame fr = new JFrame("Statistician - Results");
		fr.setLayout(new BorderLayout());
		fr.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		JLabel label = new JLabel("hiiiii");
		JComponent comp = new JTextArea();
		fr.getContentPane().add(label);
		fr.getContentPane().add(comp, BorderLayout.CENTER);

		fr.setSize(100,300);
		fr.pack();
		fr.setVisible(true);
	}

Thanks,

dt

edit: Does it matter that I'm calling displayStats() from the class's constructor? Also, does it matter that the class whose main method instantiates an object of type (this class, which contains displayStats()) does not import swing?

  • 0
  DJ Trauma said:

Hmm, it compiles and runs perfect for me (in netbeans 5.0).

Did you import java.awt.* at the top of the class?

Which class?

Upon doing that in the class with the method whose code I displayed above, the same problem occurred.

:/ Thanks anyway though..

  • 0

Update. I made an observation. When I comment out the constructor, the JFrame pops up just fine. It's something in the constructor apparently, that breaks swing :(

public StatsCalc()
	{
		try {
			numItems = Integer.valueOf(JOptionPane.showInputDialog
					("How many items?"));
			data = new double[numItems];

			for (int i = 0; i < numItems; i++)
			{
				String st = JOptionPane.showInputDialog(
						"Enter item #" + (i+1) + ":");
				if (st == "")
					numItems--;
				else
					data[i] = Double.valueOf(st);
				if (st == null)
					throw new java.lang.NumberFormatException();
			}			
		} catch (java.lang.NumberFormatException e) {
			System.err.println("Invalide.");
		} finally {
			System.exit(0); 
		}
	}

I'm a noob at exceptions so if that has some kind of error could you kindly point it out? :) Please and thanks lol.

EDIT: I removed the exception handling and now it works without problems.

Why, though? Why can't I use exception handling AND swing like this? :confused:

Edited by dt
  • 0
  dt said:

Does it matter that I'm calling displayStats() from the class's constructor? Also, does it matter that the class whose main method instantiates an object of type (this class, which contains displayStats()) does not import swing?

erm i belive constructors are there to inialize variables not to call methods, however i have called the thread start method in a constructor b4, like thrd.start(). if your main method is in its own class which it should be (thats what i do), then it should matter... but only if you are putitng classes in seperate files e.g class1.java, class2.java but if they are all in one file then it shoudltn matter.

  kjordan2001 said:

You sure you want that finally { System.exit(0); }? It will execute no matter what happens and will terminate your program.

yeh i agree... i was thinking when i first started reading this i bet he has got a system.exit(0) in there somewhere, and its just recahing it and terminating.

hope that makes sense.

  • 0

Ohhh ok. Thanks for the help :)

I have a question then; how do I define what the app does after catching a certain type of exception? Is "finally" simply unnecessary then?

Also, with regards to swing, if I'd like to popup a JFrame with several JLabels, they seem to overlap one another so that only the last one initialized appears. How do I make them appear on different lines? Looking around online yielded some stuff about "BorderLayout"s and the like, but I don't really understand how they have to do with JFrames or how they can work together to arrange / position the components (e.g. JPanel or JLabel) in the JFrame. Can anyone direct me to some kind of comprehensive guide or something that can help me get this concept? Thanks a lot! :yes:

  • 0
  dt said:

Ohhh ok. Thanks for the help :)

I have a question then; how do I define what the app does after catching a certain type of exception? Is "finally" simply unnecessary then?

Also, with regards to swing, if I'd like to popup a JFrame with several JLabels, they seem to overlap one another so that only the last one initialized appears. How do I make them appear on different lines? Looking around online yielded some stuff about "BorderLayout"s and the like, but I don't really understand how they have to do with JFrames or how they can work together to arrange / position the components (e.g. JPanel or JLabel) in the JFrame. Can anyone direct me to some kind of comprehensive guide or something that can help me get this concept? Thanks a lot! :yes:

The finally block is mainly for cleanup. Say you wanted to close a file or something no matter what happened, you would put that in the finally block, otherwise you're likely to duplicate code (i.e. having a close in the try and a close in the catch).

JFrames don't handle the layout of the components. That's why you need to specify a layout type. The default layout if none is specified is a FlowLayout. This basically puts components on the same line until it can't fit any more and then puts the newest ones on the next line.

On the other hand, BorderLayout does it by putting a component in either N, S, E, W, or the center direction of the Frame. If you want to put one under another or next to each other, you might consider GridLayout.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Jeez 4 years and its still garbage at least W10 saw some usability improvements
    • WoW as primary game.  Thought bitcraft looks interesting and comes to EA shortly. 
    • I’m so glad to see the direction this political image thread has gone. 
    • Explorer patcher is a free alternative that also works great. I get that you use startisback it’s more for others that see this and are curious.
    • PeaZip 10.5.0 by Razvan Serea PeaZip is an open source file and archive manager. It's freeware and free of charge for any use. PeaZip can extract most of archive formats both from Windows and Unix worlds, ranging from mainstream 7Z, RAR, TAR and ZIP to experimental ones like PAQ/LPAQ family, currently the most powerful compressor available. Open and extract 200+ archive formats: 001, 7Z, ACE(*), ARC, ARJ, BZ2, CAB, DMG, GZ, ISO, LHA, PAQ, PEA, RAR, TAR, UDF, WIM, XZ, ZIP ZIPX - view full list of supported archive file formats for archiving and for extraction. PeaZip provides fast, high compression ratio multi-format archiving - view file compression and decompression benchmarks for more information. PeaZip is localized in 29 languages and is capable of handling all most popular archive formats (180+ file types), supporting a wide array of advanced file and archive management features (search, bookmarks, thumbnail viewer, find duplicate files and compute hash/checksum value, convert archive files...), especially focused on security (strong encryption, two factor authentication, encrypted password manager, secure file deletion...). PeaZip 10.5.0 release notes: PeaZip 10.5.0 brings a major update in the file manager, boosting archive browsing performances, improving archive editing, adding new functions to open file as archive from within archives, to prevent running a custom list of file extensions without confirmation, and to hide or show hidden files. On macOS all file browser styles and icon sizes are now available as on other platforms. On Windows it is now possible to explore NTFS Alternate Data Streams to gather additional information on files, including a dedicated tools to batch scan the input for Zone.Identifier (Mark of The Web) to detect files coming from remote systems. In addition, the option to include the Zone.Identifier metadata in archives is now enabled by default for all formats supporting it (RAR, WIM). Backend were updated to Pea 1.25. Full list of changes and fixes is available at https://peazip.github.io/changelog.html Download: PeaZip 64-bit | PeaZip Portable 64-bit | ~13.0 MB (Open Source) Download: PeaZip 32-bit | PeaZip Portable 32-bit View: PeaZip Home Page | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • One Month Later
      jezzzy earned a badge
      One Month Later
    • First Post
      CSpera earned a badge
      First Post
    • One Month Later
      MIR JOHNNY BLAZE earned a badge
      One Month Later
    • Apprentice
      Wireless wookie went up a rank
      Apprentice
    • Week One Done
      bukro earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      625
    2. 2
      ATLien_0
      280
    3. 3
      +FloatingFatMan
      179
    4. 4
      Michael Scrip
      149
    5. 5
      Steven P.
      118
  • Tell a friend

    Love Neowin? Tell a friend!