JFrame上的所有组件都没有显示

时间:2014-05-16 01:20:32

标签: java swing

当我尝试将这些组件添加到JFrame上时,我正在创建一个刽子手游戏并想要框架上的3个不同组件,绞架的图片,试图猜到的单词以及lettters的按钮在我想要它们的地方添加,但是这个词出现在左侧并且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 个答案:

答案 0 :(得分:2)

在您构建了用户界面后调用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.packframe.setLocationByPlatform(true)