Agent Smith Agent Smith - 2 months ago 16
Java Question

Frame shows nothing, neither does it show any error

so after solving my first error due to the help of Hovercraft I finally started coding and getting stuff ready for my actual project. However, when I tried to add the label it now just shows me nothing at all, I mean if I remove the label and add any other stuff such as a button or so, it would show me the button but the moment I add the jlabel to the code it just gives me a complete blank screen no matter what the property of the label be. The code of the project is as follow:

Main Frame:

public class Parking_Mania {

public static void main(String []args)throws Exception
{
new GameFrame("Paking Mania");
}
}


Game Frame:

public class GameFrame extends JFrame{

File info=new File("information.txt");

public GameFrame(String name) throws IOException
{
if(!info.exists())
{
info.createNewFile();
}
this.setTitle(name);
this.setSize(640,510);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setVisible(true);

Frames frame=new Frames();
this.add(frame);
frame.panel.show(frame, "opening");

}
}


Panel Class that handles changing different panels:

public class Frames extends JPanel{

CardLayout panel= new CardLayout();

public Frames()
{
this.setLayout(panel);
Opening op=new Opening(this);
//nxtframe nf= new nxtframe(this);
this.add(op, "opening");
//this.add(nf, "nt");
}

}


Finally the panel which should be showing itself on the frame:

public class Opening extends JPanel{


private Frames f;
private JLabel bg=new JLabel();
//private JLabel helpframe=new JLabel();
private JButton play=new JButton();
/*private JButton help=new JButton();
private JButton helpclose=new JButton();
private ImageIcon background;*/

public Opening(final Frames f){

this.f=f;
this.setBackground(Color.BLACK);
//this.add(bg);
this.add(play);
//bg.setIcon(new ImageIcon(getClass().getResource("/bg.jpg")));

}
}

Answer Source

Components should be added to the frame before the frame is made visible.

Start with the working examples found in the Swing tutorial. The tutorial covers all the basics of Swing.

I would especially start with the tutorial on How to Use CardLayout for the first demo code to understand and modify.

The tutorial will show you how to better structure your code so that you don't keep extending panels, just to add components to a panel.