• 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

    • Finally the tasteless sound is replaced with the good old pleasant sounding one.
    • Surface Pro 11 and Laptop 7 get big firmware updates that fix shutdowns, black screens, more by Taras Buria Microsoft has released major firmware updates for some of its ARM-powered Copilot+ PCs. The Surface Pro 11 and the Surface Laptop 7 can now download the June 2025 firmware updates. These updates address a wide range of issues, including abrupt shutdowns when playing Netflix, black screen flashes, bugs with the Slim Pen haptics in OneNote, incorrect battery indication on the taskbar, and various performance improvements. Here are the changelogs for both devices: Surface Pro 11 Surface Laptop 7 Reliability: Improves system stability and reduces the frequency of unexpected shutdowns or the occurrence of a black screen while watching Netflix. Mitigates the issue that could cause screen flashing or a blank display during power state transitions. Improves the touch experience by resolving an issue where touch functionality could be lost after the device remained in Sleep mode for an extended period. Addresses an issue with Slim Pen losing haptic or Side button functionality in Microsoft OneNote. Resolved an issue where the battery icon incorrectly displayed the device as plugged in after waking from Sleep mode, even when it was not connected to a power source. ​ Performance and usability: Resolves the issue that caused authentication failures while using Windows Hello when waking from Sleep mode. Improves camera stability by reducing unexpected crashes and addressing issues, including freezing in video calls when HDR is enabled, errors when launching the Camera app or taking photos, and problems switching between front and rear cameras in some apps. Mitigates an issue where the Settings app could crash when setting up Fingerprint recognition. Interoperability: Resolves connectivity issues that caused the device to lose wired network access or fail to detect external monitors when connected via USB-C. Reliability: Improves overall stability, reducing occurrences of unexpected crashes and error screens. Reduces the occurrence of crashes during audio streaming sessions. Minimizes display timeout events and reduces the frequency of recovery cycles. Resolves an issue that caused the screen to remain black when resuming from Sleep mode. Performance and usability: Addresses an intermittent audio disruption experienced during video playback with Bluetooth headsets. Resolves a problem that caused Teams audio to drop during transitions between Bluetooth and built-in speakers. Addresses a startup issue that prevented USB Type-A devices from being recognized on the first boot. Interoperability: Resolves an issue introduced in the April 2025 release that prevented Thunderbolt 4 monitors from functioning when connected to the host device. You can get these updates by heading to Settings > Windows Update. Like Windows updates, Surface firmware releases are cumulative, which means a single download contains every update released so far. While the latest firmware updates for the Surface Pro 11 and the Surface Laptop 7 do not contain any known issues, keep in mind that firmware is not uninstallable, so back up important data to keep it safe before updating. You can find release notes for the Surface Pro 11 here and the Surface Laptop 7 here. Note that these updates are only available for Snapdragon-based versions, not those with Intel processors.
    • Here’s some history of this nonsense for people with short memories. https://www.neowin.net/amp/windows-next-hate-is-nothing-new/
    • 7 worked because vista cleared the way for it. Hardware manufacturers stopped making the “vista capable” machines, the updated secure drivers were released, and the issue with software manufacturers making everything with admin privileges was sorted. Vista took the reputational damage to do what was necessary so that 7 could be beloved.
    • You don’t remember the people who swore they were going to stay on 98se/2k because of windows xp’s “fisher price” interface/bloat.
  • Recent Achievements

    • One Month Later
      Jdoe25 earned a badge
      One Month Later
    • Explorer
      Legend20 went up a rank
      Explorer
    • 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
  • Popular Contributors

    1. 1
      +primortal
      617
    2. 2
      ATLien_0
      277
    3. 3
      +FloatingFatMan
      178
    4. 4
      Michael Scrip
      151
    5. 5
      Steven P.
      117
  • Tell a friend

    Love Neowin? Tell a friend!