2016-09-17 57 views
0

我创建了一个游戏,在屏幕上的随机位置产生一个图像(JLabel)。点击后,图像会在不同的随机位置产生。我现在计划在屏幕上也有文字。我正在使用JTextField进行此操作。问题是JTextField msg未出现,尽管它使用与JLabel box相同的方法添加。有人可以解释为什么它不会在JFrame中产卵吗?JTextField没有出现在JFrame中

BoxGame:

import java.awt.event.MouseAdapter; 
import java.awt.event.MouseEvent; 
import java.util.Random; 

import javax.swing.ImageIcon; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JTextField; 

@SuppressWarnings("serial") 
public class BoxGame02 extends JFrame { 

    static JLabel box  = new JLabel(); 
    static JTextField msg = new JTextField(); 

    static int min   = 2; 
    static int max   = 350; 

    static Random random = new Random(); 
    static int rand1  = min + random.nextInt(max - min + 1); 
    static int rand2  = min + random.nextInt(max - min + 1); 
    static int randMessage = 1 + random.nextInt(10 - 1 + 1); 

    public BoxGame02() { 
     super("Click the Box!"); 
     setLayout(null); 

     ImageIcon icon = new ImageIcon("C:/Users/btayl/JavaProjects/Java Game Development/Box Game/BoxGame02/Images/face.png"); 
     box.setIcon(icon); 
     box.setSize(50,50); 

     box.setLocation(rand1, rand2); 
     add(box); 

     msg.setText("Text on Screen"); 
     msg.setLocation(10, 200); 
     add(msg); 

     box.setName("box"); 
     BoxListener clickBox = new BoxListener(); 

     box.addMouseListener(clickBox); 

    } 

    class BoxListener extends MouseAdapter { 

     public void mouseClicked(MouseEvent e) { 
      JLabel l = (JLabel) e.getSource(); 

      if(l.getName().equals("box")) 
       moveBox(); 
     } 
    } 
    public void moveBox() { 
     System.out.println("Testing!"); 

     rand1   = min + random.nextInt(max - min + 1); 
     rand2   = min + random.nextInt(max - min + 1); 
     randMessage  = 1 + random.nextInt(10 - 1 + 1); 

     box.setLocation(rand1, rand2); 
     add(box); 

     revalidate(); 
     repaint(); 
    } 
} 

窗口:

public class Window { 
    public static void main(String[] args) { 

     BoxGame02 frame = new BoxGame02(); 
     frame.setSize(400, 400); 
     frame.setLocationRelativeTo(null); 
     frame.setResizable(false); 
     frame.setVisible(true); 
    } 
} 
+0

你知道'setLayout(null)'是做什么的吗?尝试使用布局管理器来查看是否有更改... – nbro

+0

我将它设置为空,以便我可以设置确切的坐标。我知道这不是构建程序的最佳方法,但我认为在这种情况下它可以正常工作。 – SputnicK

+0

'在这种情况下,它工作正常。“ - 以及如果标签的随机位置与文本字段重叠?您需要创建单独的面板。例如,您可以将文本字段添加到框架的PAGE_START。然后,您创建一个单独的面板并将该面板添加到框架的中心。然后,您将标签添加到第二个面板。现在标签的随机位置将不会与文本字段重叠。 – camickr

回答

3

JTextField的MSG没有出现尽管它使用相同的方法,选择JLabel盒被添加。

不,您没有使用与标签相同的方法。再次仔细查看你的代码。

您在JLabel上使用了哪些方法?

现在比较用于JTextField的方法,看看有什么不同。

在你的“moveBox()”方法中,你不需要继续添加框到面板。您只添加一个框。然后你可以简单地改变它的位置。

你不应该使用静态变量。变量应该是类的实例变量。

+0

我试图在moveBox()和mouseClicked()方法中添加'msg',它仍然不起作用。你能否提供更详细的解释? – SputnicK

+0

@SputnicK,你说的代码是一样的。所以告诉我,你在“box”变量上调用了什么方法,以及你在“msg”变量上调用了哪些方法。如果您想使用空布局,则需要管理每个组件上的相同属性。这是使用布局管理器的另一个原因。 – camickr

+0

哦,我没有设置大小......韦尔普我是个白痴。感谢您的帮助:) – SputnicK