我创建了一个游戏,在屏幕上的随机位置产生一个图像(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);
}
}
你知道'setLayout(null)'是做什么的吗?尝试使用布局管理器来查看是否有更改... – nbro
我将它设置为空,以便我可以设置确切的坐标。我知道这不是构建程序的最佳方法,但我认为在这种情况下它可以正常工作。 – SputnicK
'在这种情况下,它工作正常。“ - 以及如果标签的随机位置与文本字段重叠?您需要创建单独的面板。例如,您可以将文本字段添加到框架的PAGE_START。然后,您创建一个单独的面板并将该面板添加到框架的中心。然后,您将标签添加到第二个面板。现在标签的随机位置将不会与文本字段重叠。 – camickr