0

我这里有非常简单的 Java swing 代码,我没有看到框架中显示的按钮。有人可以帮助解决问题吗?

import javax.swing.*;

import java.awt.event.*;

public class HangmanGUI extends JFrame{

        JComboBox favoriteShows;
        JButton[] alphaButtons;
        String infoOnComponent = "";
        JButton button1;

        public static void main(String[] args){

            new HangmanGUI();

        }
        //constructor for Hangman
        /**
         * Instantiates a new hangman gui.
         */
        public HangmanGUI() {

            this.setSize(600,400);

            this.setLocationRelativeTo(null);

            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            this.setTitle("Play Hangman");

            JPanel thePanel = new JPanel();

            button1 = new JButton("Get Answer");

            thePanel.add(button1);

            this.setVisible(true);


        }

}
4

1 回答 1

4

你永远不会添加thePanel到框架中......

public HangmanGUI() {

    this.setSize(600,400);
    this.setLocationRelativeTo(null);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setTitle("Play Hangman");

    JPanel thePanel = new JPanel();
    button1 = new JButton("Get Answer");
    thePanel.add(button1);

    // This is very important ;)        
    add(thePanel);

    this.setVisible(true);

}

就个人而言,我会避免从JFrame这样的目录扩展。除了您没有向框架添加任何功能这一事实之外,它还将您与单个部署/使用联系起来。

我会从 a 之类的东西开始,JPanel然后从那里构建程序,将此面板添加到JFrame“主”条目类中的 create 实例中......恕我直言

于 2013-10-15T02:56:36.663 回答