gpt4 book ai didi

java - 为什么这个简单的 Java Swing 代码中没有显示按钮?

转载 作者:行者123 更新时间:2023-12-01 18:42:29 25 4
gpt4 key购买 nike

我这里有非常简单的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);


}

}

最佳答案

您永远不会将 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 之类的东西开始,并从那里构建程序,将此面板添加到在“主”入口类中创建的 JFrame 实例中...恕我直言

关于java - 为什么这个简单的 Java Swing 代码中没有显示按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19372549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com