Adding a JPanel to a JFrame in Netbeans
Solution 1
Your problem:
Your MyPanel
instance is not added to the main frame.
Solution:
Add your MyPanel
instance to the main frame's content pane.
Something like:
JFrame f = new JFrame();
MyPanel jPanel1 = new MyPanel();
f.getContentPane().add(jPanel1 );
f.pack();
f.setVisible(true);
Solution 2
Above answers are correct - you need to actually add this MyPanel
to the contentPane of the Frame.
Additionally you should probably use Swing instead of plain AWT. The code would look like this:
SwingUtilities.invokeLater(new Runnable() {
@Override //annotation if you are using Java >= 1.5
public void run() {
JFrame f = new JFrame();
MyPanel jPanel1 = new MyPanel();
f.getContentPane().add(jPanel1);
f.pack();
f.setVisible(true);
}
});
xyz
Updated on November 19, 2020Comments
-
xyz over 3 years
I created
JFrame
class in Netbeans and using generator I have addjPanel
. I have also class, which extendsJPanel
. Now i want to create object of this class, and add him on the place where is my Panel inJFrame
, but I can't find the right way, because all what I'm trying give no resultspublic static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { Frame f = new Frame(); jPanel1 = new MyPanel(); f.pack(); f.setVisible(true); } });
Ok, so maybe I will show more precise example what am I talking about:
first File:
class MyPanel extends javax.swing.JPanel { public MyPanel() { initComponents(); } }
Another file, with Frame:
public class Frame extends javax.swing.JFrame { public Frame() { initComponents(); } public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { Frame f = new Frame(); MyPanel p = new MyPanel(); jPanel1 = p; } }); } private javax.swing.JButton jButton1; private javax.swing.JPanel jPanel1;
And I want to set on the place of jPanel1 - object MyPanel