Reputation:
I'm trying to make a swing version of the Hello World!!! program in a GUI. But I keep on getting an error like I mentioned in the title. Here is my code:
import javax.swing.*;
public class HelloFrame
{
public static void main(String[] args)
{
new HelloFrame();
}
public HelloFrame()
{
this.setSize(200, 100);
this.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
this.setTitle("Hello World!");
this.setVisible(true);
}
}
Errors are in:
this.setSize(200, 100);
this.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
this.setTitle("Hello World!");
this.setVisible(true);
I would really appreciate some answers. Thanks!
EDIT 1: Oh yeah! I forgot to mention I'm using java.
Upvotes: 0
Views: 1613
Reputation: 205835
In your example, HelloFrame
implicitly extends Object
. As a result, this
refers to an Object
, which has no JFrame
methods. Instead, let HelloFrame
contain a JFrame
, as shown below. Also,
I've added a JLabel
to give the frame something to display after pack()
is invoked.
Swing GUI objects should be constructed and manipulated only on the event dispatch thread.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
/** @see https://stackoverflow.com/a/32016671/230513 */
public class HelloFrame {
private void display() {
JFrame f = new JFrame("HelloFrame");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Hello World!");
f.add(new JLabel("Hello World! Hello World!"), JLabel.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new HelloFrame()::display);
}
}
Upvotes: 3