gpt4 book ai didi

java - JFrame 中没有显示任何内容

转载 作者:行者123 更新时间:2023-12-01 23:27:00 25 4
gpt4 key购买 nike

我有一个 [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();
}
}

最佳答案

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

编辑:如果您想向 JFrame 添加多个面板,请使用 LayoutManager 例如 GridLayout :

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

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

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

LayoutManager

GridLayout

BorderLayout

关于java - JFrame 中没有显示任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19837769/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com