JTextField 没有出现在 JFrame 中

JTextField not appearing in JFrame

我创建了一个在屏幕上的随机位置生成图像 (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();
    }
}

Window:

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()" 方法中,您不需要一直将框添加到面板。您只需添加一次框。然后你可以简单地改变它的位置。

您不应该使用静态变量。变量应该是 class.

的实例变量