0

我有一个 [JFrame][1] 的课程,但没有显示任何内容。但是,如果我删除 setLayout 临时面板会显示,但如果我添加其他组件,它们不会显示。我现在添加了面板

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();
    }
}
4

2 回答 2

2

您将所有组件添加到temp面板,但您从未将该面板添加到您的JFrame. setContentPane(temp);在此之前添加此行setVisible(true);,一切都会正常工作。

编辑:如果您想添加更多的面板供您JFrame使用LayoutManager,例如GridLayout

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

或者你可以 BorderLayout像这样使用getContentPane().setLayout(new BorderLayout());它也可以帮助你。

默认情况下,您的getContentPane()面板FlowLayout无法显示带有 preferedSize(0,0) 的组件。如果您想使用它,您必须指定组件的大小,例如:temp.setPreferredSize(new Dimension(100,100));

布局管理器

网格布局

边框布局

于 2013-11-07T14:03:38.760 回答
1

您应该将临时面板设置为 JFrame 的内容面板。

添加

setContentPane( temp );

在显示框架之前setVisible( true );

于 2013-11-07T14:06:02.693 回答