-1

Panel and button are added in the frame but not appearing in the frame output.

import javax.swing.*;
import java.awt.*;
public class frameeg
{

    public static void main(String s[])
    {
        JFrame frame = new JFrame("Frame eq");
        JPanel panel = new JPanel();               //panel not working
        panel.setLayout(new FlowLayout());
        JLabel label = new JLabel("JFrame by example");
        JButton button = new JButton();
        button.setText("Button");
        panel.add(label);
        panel.add(button);
        frame.add(panel);
        frame.setLayout(null);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(200,300);
    }
}
Jeff Learman
  • 2,914
  • 1
  • 22
  • 31
  • 1
    Just two suggestion without testing the code... frame.setLayout(null); can be the cause? frame.Show() or similar is not called. – Alex 75 Nov 14 '19 at 16:50
  • Welcome to StackOverflow! I edited the title for clarity and brevity, and I formatted the code. When pasting code, paste it in, select it, and click the `{}` widget to render it as code. That shifts it right 4 spaces. Avoid excess indents on the left of all the code. – Jeff Learman Nov 14 '19 at 17:06
  • 1
    @Alex75, you should NOT be using the show() method. Read the API for more information. The code IS using the setVisible(true) method which is the correct method to use. However your point about the null layout is correct. – camickr Nov 14 '19 at 19:20

1 Answers1

0

You decided to use null-layout which requires you to specify the bounds (setBounds(...)) of all the elements inside, otherwise it will display them with a width = 0 and height = 0.

But you shouldn't be using null-layout, as it's evil and will cause some funny / strange / hard-to solve issues like this one when running your program in different PLAFs / screen sizes / resolutions / etc.

For this I recommend you to remove this line:

frame.setLayout(null);

Replace this line:

frame.setSize(200,300);

For this one:

frame.pack();

And move this line at the very end of the main method:

frame.setVisible(true);

And don't forget to place you program on the EDT (as shown in the linked answer)

Frakcool
  • 10,915
  • 9
  • 50
  • 89