junxi junxi - 2 months ago 8
Java Question

My GUI does not print anything at all

MyFrame(){
String titel = "Rezept";
JLabel label = new JLabel(titel);
JButton abutton = new JButton("Abbrechen");
JButton sbutton = new JButton("Speichern");

JPanel jp1 = new JPanel();
jp1.setLayout(new FlowLayout(FlowLayout.CENTER));
jp1.add(label);

JPanel jp2 = new JPanel();
jp2.setLayout(new GridLayout(1,2));
jp2.add(abutton);
jp2.add(sbutton);

setLayout(new BorderLayout());
setSize(300,500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
add(jp1, BorderLayout.NORTH);
add(jp2, BorderLayout.SOUTH);
}

public static void main(String[]args){
new MyFrame();
}


I just don't get it. When I run this GUI it doesn't print out anything at all.

I only get an empty frame. What am I doing wrong here?

(Code is in "MyFrame extends JFrame" class)

Answer

you will never see anything if you call the method setVisible(true); before adding the JPanels...

change the order to something like:

add(jp1, BorderLayout.NORTH);
add(jp2, BorderLayout.SOUTH);
setVisible(true);

after that you should see something like

enter image description here