Reputation: 45
I'm just getting into creating GUIs in Java, and with this basic setup, I can't get anything to appear in my JFrame:
public class Main extends JFrame {
public static void main(String[] args) {
JFrame jframe = new JFrame();
jframe.setSize(400,400); // setting size
jframe.setVisible(true); // Allow it to appear
jframe.setTitle("Lab 7");
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Main init = new Main();
}
public Main() {
Container pane = getContentPane();
pane.setBackground(Color.BLUE);
pane.setLayout(new FlowLayout());
JButton add = new JButton("Add");
JButton close = new JButton("Close");
JTextArea area = new JTextArea();
JScrollPane scroll = new JScrollPane(area);
add.setBounds(70, 125, 80, 20);
close.setBounds(70, 115, 80, 20);
pane.add(add);
pane.add(close);
pane.add(scroll);
AddClick added = new AddClick();
add.addActionListener(added);
}
}
I also tried moving all the JFrame stuff into public Main() but it caused an infinite amount of windows opening and I had to end the program each time.
Upvotes: 0
Views: 38
Reputation: 10613
You're creating two separate JFrame
s: one is your Main
class, and the other is an unrelated JFrame
. Most of the customization, including adding components, happens to the Main
in its constructor. But you only ever set the other JFrame
to be visible.
Use your Main
instance as the JFrame
instead of creating another one, and the problem will be fixed.
public static void main(String[] args) {
JFrame jframe = new Main(); //Use an instance of Main as your JFrame
jframe.setSize(400,400); // setting size
jframe.setVisible(true); // Allow it to appear
jframe.setTitle("Lab 7");
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
Upvotes: 2