我的代码存在问题,似乎JComboBox会随时出现并消失。我有JComboBox何时工作的实例,然后关闭并重新启动程序会导致它再次停止工作。发生了什么事?
class FutoshikiGUI extends JFrame {
JPanel main = new JPanel();
public FutoshikiGUI() {
super("Futoshiki");
//setup standard GUI parameters
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setResizable(false);
setSize(600,600);
add(main);
//initialise other GUI components
initPanel();
}
private void initPanel() {
//prepare main panel
main.setLayout(new GridBagLayout());
main.setBackground(Color.decode("#FFFFFF"));
//create and prepare title
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
JLabel title = new JLabel("Futoshiki");
title.setFont(new Font("Tahoma", Font.PLAIN, 20));
main.add(title, gbc);
//create and prepare combobox
gbc.gridy = 1;
String[] diff = {"Easy", "Med", "Hard"};
JComboBox difficulty = new JComboBox(diff);
difficulty.setSelectedIndex(0);
main.add(difficulty);
}
答案 0 :(得分:3)
只有将所有组件添加到setVisible(true)
后,才应致电JFrame
。
另外,请在add(main)
之后致电initPanel()
,以确保JPanel
也准备就绪:
public FutoshikiGUI() {
super("Futoshiki");
//setup standard GUI parameters
setDefaultCloseOperation(EXIT_ON_CLOSE);
//initialise other GUI components
initPanel();
add(main);
setResizable(false);
setSize(600,600);
setVisible(true);
}