Reputation: 420
I am trying to add a JButton to a JPanel that I create as a class, like so:
public class Popup extends Main {
public Popup() {
JPanel popup = new JPanel();
JButton button = new JButton("SUPER COOL BUTTON");
popup.add(button);
popup.setPreferredSize(new Dimension(50,50));
}
}
Main.java:
private void createFrame() {
JFrame frame = new JFrame("TEAM PROJECT");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(new Popup(), BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
When I do this, the frame creates but has nothing in it. Similar code works when trying to draw on the panel using paintComponent
, so is the problem that you can't add SwingComponents
this way?
What can I do to get the JPanel
created in Popup
to be added to the frame created in Main
?
Upvotes: 0
Views: 38
Reputation: 324207
Why would you extend Main (as that appears to be the class where you create the JFrame)?
If you want to add a button to a panel then extend JPanel and add your button to your class (which is a JPanel already so there is no need to create another JPanel):
public class Popup extends JPanel {
public Popup() {
//JPanel popup = new JPanel();
JButton button = new JButton("SUPER COOL BUTTON");
add( button );
//popup.add(button);
//popup.setPreferredSize(new Dimension(50,50));
}
}
Upvotes: 2