2014-03-25 20 views
0

这个程序是在桂的数学考试。当我运行gui时,标题“此测试包含...”出现。当我添加更多标签并运行程序时,这些框架是空的。有人能帮助我吗?另一件事,我想一个接一个地增加更多的数学问题。例如练习1,练习2,练习3等等,我也不知道该怎么做。在这个程序中,当我添加更多标签时,所有准备好的标签都不显示。

public class University { 
    public static void main (String [] args) { 
     MathTest mt = new MathTest(); 
     mt.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     mt.setSize(320, 700); 
     mt.setVisible(true); 
    } 
} 

public class MathTest extends JFrame { 
    public MathTest() { 
     super("Persistent University- Math Test"); 

     JLabel info = new JLabel(" This test consists of 10 exercises.", SwingConstants.CENTER); 
     info.setVerticalAlignment(SwingConstants.TOP); 
     add(info); 

     JLabel exone = new JLabel("Exercise 1: How much is 1 added to 1?"); 
     JLabel ansone = new JLabel("Your answer, please"); 
     JTextField stu = new JTextField(4); //this for the student to type the answer 
     add(exone); 
     add(ansone); 
     add(stu); 
+2

的代码将更具可读性,如果它是正确的缩进。 – Hyperboreus

+0

你的代码不会编译,因为它在课程结束之前突然结束。是否有任何标签(exone,ansone,stu)至少显示一次,或者您是否遇到新项目? –

+0

我麻烦的是,当我添加新的标签,我运行程序的框架是空的。没有任何东西显示在框架上。 –

回答

0

确保您的标签变量名称未被添加到基础面板两次。例如:

JLabel info = new JLabel(); 
add(info); 
info = new JLabel(); 
add(info); 

不会添加两个JLable。每调用一次add(),您都需要一个新的对象参考。

请使用pack()后,当然,你叫setVisible()之前。

另外,如果你清楚你的面板,调用getContentPane().removeAll()让你不离开那些JComponents挥之不去。

2

的默认布局管理为JFrameBorderLayout

一个BorderLayout默认只允许一个单一组分占据各自的是5个可用的位置。

在供给没有限制,对于BorderLayout默认位置(或限制)是CENTER,这意味着你有效去除您添加的最后一个组件时,您添加下一个(技术上不正确的,但效果是足够接近出现是一回事)

看看How to Use BorderLayout的详细信息和Laying Out Components Within a Container可能的解决办法...

相关问题