• 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

    • The so called tri-fold phone is not a phone just like today's so called smartphones are not phones. They are computing camera devices with the ability to make and receive phone calls. For many the phone app is among the least used apps on these so called smartphones.
    • Backpack Hero and Figment are free to claim on the Epic Games Store by Pulasthi Ariyasinghe The Epic Games Store has just refreshed its weekly giveaways promotion, and there are two games up for grabs this time. Replacing the Sable freebie from last week, Backpack Hero and Figment have now landed for all PC gamers to claim. As always, you have seven days to add the latest indie game permanently to your Epic Games Store library. From the double giveaway, Backpack Hero comes in from indie developer Jaspel, offering a unique inventory management roguelike experience. Aside from collecting items to maximize the potential of a run, like with other roguelikes, here, your placement of the item in the backpack also matters. Each run offers randomly generated dungeons, enemies, and loot to grab. Next, Figment lands from Bedtime Digital Games. This isometric perspective action adventure game takes place in a surreal landscape with hand-drawn artwork, and everything is taking place inside a mind. You take the role of Dusty, the former voice of courage in the mind. The musical adventure involves trying to return Dusty to his old self while also helping the mind beat back its nightmares and restoring its original purpose. The Figment and Backpack Hero giveaways on the Epic Games Store are now active, and they will last until July 10. When not on sale, both games come in at $19.99 to purchase, but PC gamers can add the duo to their library for no cost during the seven-day timeframe. When the giveaways refresh next week, Epic Games plans on giving away two more games: the next musical adventure, Figment 2: Creed Valley, as well as the classic arcade-inspired shoot’em up Sky Racket.
    • Isn’t your Google Wallet full of your personal information tied to your identity?
  • Recent Achievements

    • Week One Done
      Devesh Beri earned a badge
      Week One Done
    • Week One Done
      956400 earned a badge
      Week One Done
    • First Post
      loose_observer earned a badge
      First Post
    • Week One Done
      BeeJay_Balu earned a badge
      Week One Done
    • Week One Done
      filminutz earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      451
    2. 2
      ATLien_0
      158
    3. 3
      +FloatingFatMan
      153
    4. 4
      Nick H.
      65
    5. 5
      +thexfile
      62
  • Tell a friend

    Love Neowin? Tell a friend!