• 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

    • Apple still has two unannounced features for iOS 26 by Hamid Ganji Apple held its WWDC25 event this month to unveil a slew of AI features and its new design for operating systems, known as Liquid Glass. While iOS 26 currently has no shortage of features, the iPhone maker might still have some features under wraps that didn’t make a debut at this month’s WWDC. Bloomberg’s Mark Gurman writes in his weekly Power On newsletter that Apple didn’t announce two iOS 26 features at the WWDC event. The first feature is a live translation of conversations via AirPods, and the latter is the ability to sync your wireless network login information across devices at a hotel or gym. Even though these features were already tipped to arrive in iOS 26, Apple held them from the event, presumably because they’re still not ready to ship. Apple appears to have learned from its experience with Apple Intelligence and aims to break the habit of unveiling new features before they are ready for release. The Live Translation on iOS 26 is currently integrated with popular apps like Messages, FaceTime, and Phone to help users break language barriers and communicate in different languages. The feature is now under development for AirPods, allowing users to hear real-time speech translations. Moreover, the WiFi syncing feature allows you to sync your sign-in information across your entire Apple ecosystem, enabling you to connect to a public WiFi network with ease. This would eliminate the need to sign into a WiFi network separately on each device. While these features haven’t arrived in iOS 26 yet, they’re more likely to be released later this year, in October or December.
    • Intel Level L4 cache has been around for a long time, so AMD Zen 3D Cache is a copy of Intel L4 cache that was introduced with Broadwell i7-5775c, which had 128mb of Level L4 cache. Secondly, Zen 6 is not faster in single-threaded performance than 13900k/14900k. 285k is something new Intel is trying, basically showing us that chiplet design does not work for gaming, just like AMD design does not work for gaming. Throwing more cores at it and having L4 cache won't fix the issue, and that is frame dip and stuttering caused by a very stupid design decision to keep the memory controller outside the compute tile. Might as well put a memory controller by bringing back a south bridge chip. lol
    • Just like AMD Zen, it is not going to work for gaming despite 3D Cache. Frame dip and stuttering are giving, which renders 14900KS the greatest gaming CPU ever released.
    • LG continues to manufacture and sell Windows laptops
  • Recent Achievements

    • Community Regular
      Primey_ went up a rank
      Community Regular
    • Reacting Well
      Gromvar earned a badge
      Reacting Well
    • Dedicated
      BreakingBenjamin earned a badge
      Dedicated
    • Week One Done
      Hartej earned a badge
      Week One Done
    • One Year In
      TsunadeMama earned a badge
      One Year In
  • Popular Contributors

    1. 1
      +primortal
      519
    2. 2
      +FloatingFatMan
      181
    3. 3
      ATLien_0
      166
    4. 4
      Skyfrog
      100
    5. 5
      Som
      97
  • Tell a friend

    Love Neowin? Tell a friend!