2016-03-25 49 views
-2
public class Game extends JFrame implements ActionListener{ 

Drawing object=new Drawing(); 
Timer t=new Timer(1,this); 
int score; 
ArrayList<Enemy> bombs=new ArrayList<Enemy>(); 

public Game() 
{ 
    t.start(); 

    setDefaultCloseOperation(EXIT_ON_CLOSE); 
    setSize(700,600); 
    setVisible(true); 
    add(object); 
    add(new JLabel("Hello")); 
    validate(); 
    createBombs(); 
} 

为什么我无法同时添加JLabel和对象。只有其中一个出现。 (JLabel)。添加多个对象

+0

你得到的错误是什么?我们可以看到添加功能吗? –

+0

什么样的对象是绘图?你是否能够在任何其他控件上显示它?我最好的猜测是绘制得到添加没有任何问题,但它实际上并没有绘制的东西,所以它似乎没有被添加。 –

+0

你知道JFrame的默认布局管理器是什么吗? – FredK

回答

2

JFrame具有BorderLayout作为默认值。在BorderLayoutadd方法将给定的组件添加到CENTER位置。

所以:

add(object); 
add(new JLabel("Hello")); 

与这些线路要添加两个项目到CENTER位置。例如,如果您将标签添加到SOUTH的位置,您的object将可见。

add(object); 
add(new JLabel("Hello"), BorderLayout.SOUTH); 

编辑:

由于@camickr说,你必须调用后setVisible(true)添加所有的组件。看看下面的代码。

public class Game extends JFrame implements ActionListener { 

    Drawing object = new Drawing(); 
    Timer t = new Timer(1, this); 
    int score; 
    ArrayList<Enemy> bombs = new ArrayList<Enemy>(); 

    public Game() { 
     t.start(); 

     setDefaultCloseOperation(EXIT_ON_CLOSE); 
     setSize(700, 600); 
     add(object); 
     add(new JLabel("Hello")); 
     validate(); 
     createBombs(); 

     setVisible(true); 
    } 
} 
+0

非常感谢。我也尝试过,但也添加BorderLayout.NORTH到我不应该有的对象。 –

+1

(1+)。 @Satti博士,尽管您应该使用BorderLayout.PAGE_END,但这是正确的解决方案。但是,在使框架可见之前,您还应该将组件添加到框架。 – camickr

+0

没有必要验证()。基本代码应该是frame.add(...),frame.pack(),frame.setVisible(true)。 – camickr