user2327579
user2327579

Reputation: 499

Nothing showing in JFrame

I have this class for a [JFrame][1], but nothing is showing up. However, if I remove the setLayout the temp panel shows up, but if I add other components they do not show up.I've added the Panel now

public class GenerateQuestions extends JFrame {
    List<ButtonGroup> btngp;

    GenerateQuestions() {
    setSize(400, 400);
    btngp = new LinkedList<ButtonGroup>();

    String[] contents =
    {
        "Test1", "Test2", "Test3", "Test4"
    };
    SpringLayout z = new SpringLayout();
    setLayout(z); 
    JPanel temp = new JPanel(); 
    SpringLayout sl = new SpringLayout();
    temp.setLayout(sl);
    JLabel x = new JLabel("This is a test question generator for online assesment ");
    temp.add(x);
    sl.putConstraint(SpringLayout.NORTH, x, 5, SpringLayout.NORTH, temp);
    sl.putConstraint(SpringLayout.WEST, x, 5, SpringLayout.WEST, temp); 

    ButtonGroup btn = new ButtonGroup();
    int counterNorth = 15;
    int counterWest = 15;
    for (int i = 0; i < contents.length; i++) {
        JRadioButton t = new JRadioButton(contents[i]);
        btn.add(t);
        temp.add(t);
        sl.putConstraint(SpringLayout.NORTH, t, counterNorth, SpringLayout.NORTH, x);
        sl.putConstraint(SpringLayout.WEST, t, counterWest, SpringLayout.WEST, temp);
        if (i % 2 == 0) {
        counterWest += 75;
        } else {
        counterWest -= 75;
        counterNorth += 25;
        }
    }
    btngp.add(btn);
    z.putConstraint(SpringLayout.NORTH, temp, 10, SpringLayout.NORTH, this);
    z.putConstraint(SpringLayout.WEST, temp, 10, SpringLayout.WEST, this);
    setVisible(true);
    getContentPane().add(temp);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    }

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

Upvotes: 0

Views: 1506

Answers (2)

alex2410
alex2410

Reputation: 10994

You add all your components to temp panel, but you never add that panel to your JFrame. Add this line setContentPane(temp); before setVisible(true); and all will be work.

EDIT: If you want to add more that one panel to your JFrame use LayoutManager for example GridLayout :

    getContentPane().setLayout(new GridLayout(2,2));
    getContentPane().add(temp);
    getContentPane().add(new JLabel("test"));

or you can use BorderLayout like this getContentPane().setLayout(new BorderLayout()); it also helps you.

By default your getContentPane() panel has FlowLayout which can't display components with preferedSize(0,0) . If you want to use it you must to specify size of your components, for example : temp.setPreferredSize(new Dimension(100,100));

LayoutManager

GridLayout

BorderLayout

Upvotes: 2

kap
kap

Reputation: 1804

You should set the temp panel to be the content pane of the JFrame.

Add

setContentPane( temp );

before showing the frame with setVisible( true );.

Upvotes: 1

Related Questions