我这里有非常简单的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);
}
}
答案 0 :(得分: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
目录扩展。除了您没有向框架添加任何功能之外,它还会将您绑定到单个部署/使用。
我会从类似JPanel
的东西开始,然后从那里构建程序,将此面板添加到“main”条目类中的JFrame
创建实例...恕我直言