1
这是我的功课。的JPanel没有出现正确,同时延长JFrame的
我的路线: GuessGame类:这个类包含创建JFrame对象的主函数,设置JFrame的大小,可见性和退出。
类GuessGameFrame:GuessGameFrame类扩展的JFrame。所以GuessGameFrame类具有在JFrame类中定义的所有变量和方法。
我不是100%肯定,我的问题是什么,但我相信的JPanel工作不正常
任何帮助将大大赞赏,如果我离开了什么重要的东西,请让我知道,我可以添加更多的细节。
主类:
public class GuessGame {
public static void main(String[] args){
GuessGameFrame localGuessGameFrame = new GuessGameFrame();
localGuessGameFrame.setVisible(true); //set visible
localGuessGameFrame.setSize(380,175); // set size 380 width 175 height
localGuessGameFrame.setDefaultCloseOperation(localGuessGameFrame.EXIT_ON_CLOSE); // needed to enable the red X button to close the program
}
}
扩展类:当执行输出窗口
import javax.swing.*;
import java.awt.*;
public class GuessGameFrame extends JFrame
{
private int lastDistance; // distance between last guess and number
private Color background; // background color of application
private JFrame f;
static JPanel p;
private JButton b1;
private JLabel l1;
private JLabel l2;
JTextField t1 = new JTextField(8);
private JLabel l3;
//declare constructor
public GuessGameFrame()
{
//create our JFrame
f = new JFrame("Guessing game");
//create our panel
p = new JPanel();
p.setBackground(Color.MAGENTA); // background color is magenta
//create our labels
l1 = new JLabel("I have a number between 1 and 1000.");
l2 = new JLabel("Can you guess my number? Enter your first Guess:.");
l3 = new JLabel("Guess result appears here.");
//create our button
b1 = new JButton("New Game");
//add button and label to panel
p.add(l1); // Adds label 1
p.add(l2); // adds label 2
p.add(t1); // adds textfield 1
p.add(l3); // adds label 3
p.add(b1); // adds button 1
//add panel to JFrame
f.add(p);
}
}
我希望它看起来像这样:
这个工作!你能解释它为什么起作用吗,也许关注'这个'一点。 – GeekyDewd
因为在你的代码中,GuessGameFrame是一个JFrame本身,它包含另一个JFrame f。您初始化为JFrame的F(不GuessGameFrame)用户界面,并在主类调用localGuessGameFrame.setVisible(真),所以它不会工作 – Jerry06
@ Jerry06:既'this'和'的getContentPane()'是多余的,但他们使它清楚你正在调用'GuessGameFrame'实例的方法。 – trashgod