Java Swing just showing in top-left of output - why?

I have a colleague interested in using replit.com for a class (yay!), and asked me to run some code. In an ordinary Java replit, this:

import javax.swing.;
import java.awt.
;

class Example extends JFrame {
public static void main(String args) {
Example ex = new Example();
// ex.setLayout(new FlowLayout());
// ex.setPreferredSize(new Dimension(500,500));
ex.setVisible(true);
}
}

just produces a very small window at the top left of the output pane (see attached). I threw in the commented out statements for good measure (minus the //!) but it still produced the same. As you can tell, I don’t do much with Swing, but I’d like to be able to tell them why what they wrote didn’t work – and also direct them to the Swing-specific replit.

So, why is this happening? Is this expected behavior?

Thanks for any info,

Michael

1 Like

(I don’t know much Java.)
Using setSize instead of setPreferredSize seems to work better. This works fine:

import java.awt.*;
import javax.swing.*;

class Main extends JFrame {
	public static void main(String[] args) {
		Main ex = new Main();
		ex.setLayout(new FlowLayout());
		ex.setSize(new Dimension(500,500));
		ex.setVisible(true);
	}
}

Note that if you name the class Example, you will get an error since the program cannot find the Main class which it is set to find and run by default.

There is also a default Java Swing Repl which opens a JFrame fine as well.

2 Likes

Thanks so much, that did the trick!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.