gpt4 book ai didi

java - JTextField 未出现在 JFrame 中

转载 作者:行者123 更新时间:2023-12-01 21:18:18 24 4
gpt4 key购买 nike

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

盒子游戏:

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);
}
}

最佳答案

the JTextField msg is not appearing despite it being added using the same method as the JLabel box.

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

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

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

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

您不应该使用静态变量。这些变量应该是类的实例变量。

关于java - JTextField 未出现在 JFrame 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39552708/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com