JFrame 中的所有组件均未显示
Posted
技术标签:
【中文标题】JFrame 中的所有组件均未显示【英文标题】:All Components on JFrame arent showing 【发布时间】:2015-07-10 15:01:23 【问题描述】:我正在创建一个刽子手游戏,并希望框架上有 3 个不同的组件、绞刑架的图片、试图猜测的单词和字母的按钮,当我尝试将这些组件添加到 JFrame 上时被添加到我想要它们的地方,但是单词出现在左侧并且 HangmanGallows(扩展 JPanel)甚至没有显示,我如何让 HangmanGallows 和单词在绝对中心并排显示?
public void createGUI()
frame = new JFrame("Hangman");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
selectedWord = new WordBank().getWord(); // initializes 'selectedWord' to a random word selected from WordBank class
System.out.println(selectedWord);
displayWord();
displayCharacterChoices();
// end method
public void displayWord()
String word = "";
for (int i = 0; i < selectedWord.length(); i++)
word += "_ ";
// end for loop
HangmanGallows pic = new HangmanGallows();
JLabel actualWord = new JLabel(word);
actualWord.setFont(new Font(Font.DIALOG, Font.BOLD, 40));
frame.getContentPane().add(BorderLayout.EAST, pic);
frame.getContentPane().add(BorderLayout.CENTER, actualWord);
// end method
public void displayCharacterChoices()
String[] array = "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z";
charactersPanel = new JPanel();
CharacterButtonListener but = new CharacterButtonListener();
JPanel panelOne = new JPanel();
JPanel panelTwo = new JPanel();
JButton temp;
for (int i = 0; i < array.length / 2; i++)
temp = new JButton(array[i]);
temp.addActionListener(but);
temp.setText(array[i]);
panelOne.add(temp);
// end for loop
for (int i = array.length / 2; i < array.length; i++)
temp = new JButton(array[i]);
temp.addActionListener(but);
temp.setText(array[i]);
panelTwo.add(temp);
// end for loop
charactersPanel.setLayout(new BoxLayout(charactersPanel, BoxLayout.Y_AXIS));
charactersPanel.add(panelOne);
charactersPanel.add(panelTwo);
frame.add(BorderLayout.SOUTH, charactersPanel);
// end method
【问题讨论】:
【参考方案1】:构建 UI 后致电 setVisible(true)
例如...
public void createGUI()
frame = new JFrame("Hangman");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setVisible(true);
selectedWord = new WordBank().getWord(); // initializes 'selectedWord' to a random word selected from WordBank class
System.out.println(selectedWord);
displayWord();
displayCharacterChoices();
frame.setVisible(true);
// end method
您还可以找到frame.pack
和frame.setLocationByPlatform(true)
的一些用途
【讨论】:
以上是关于JFrame 中的所有组件均未显示的主要内容,如果未能解决你的问题,请参考以下文章