java - JTextField 未出现在 setBounds 坐标处
问题描述
我遇到了一个问题,我将一个 JTextField 添加到一个 JPanel 并且它水平居中并与顶部边框相邻,而不是在我使用 setBounds() 设置的坐标处。
我的代码有一个类,它创建一个 JFrame 并像这样调用一个新的 Jpanel:
public class SpaceInvadersFrame extends JFrame {
static final int SCREEN_WIDTH = 600;
static final int SCREEN_HEIGHT = 600;
SpaceInvadersFrame() throws IOException, InterruptedException {
this.setSize(SCREEN_HEIGHT,SCREEN_HEIGHT);
this.setTitle("Space Invaders");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setVisible(true);
this.setLocationRelativeTo(null);
this.add(new SpaceInvadersPanel(SCREEN_WIDTH, SCREEN_HEIGHT));
this.pack();
}
}
JPanel 的编码如下:
public class SpaceInvadersPanel extends JPanel implements ActionListener {
JTextField playerInput;
SpaceInvadersPanel(int SCREEN_WIDTH, int SCREEN_HEIGHT) throws IOException, InterruptedException {
this.setPreferredSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT));
this.setBackground(Color.white);
this.setFocusable(true);
playerInput = new JTextField("prova2");
playerInput.setBounds(100, 300, 100, 30);
playerInput.setBackground(Color.black);
playerInput.setForeground(Color.white);
playerInput.setFont(new Font("Verdana", Font.BOLD, 20));
playerInput.setVisible(true);
this.add(playerInput);
}
解决方案
推荐阅读
- linux - 为文件夹中的每个文件运行一个命令 - LINUX
- amazon-s3 - 如何将大量数据从 AWS S3 自动备份到 Microsoft Azure
- python - 删除不属于城市名称字典文本文件的关键字
- spring - 君特 | main 中的自动装配组件为空
- python - 如何将一串句子重新格式化为每行一个句子 Python
- bash - 如何读取文件下的特定键值条目,主题由括号划分?
- django - DRF - 序列化多个模型
- laravel - 在一个文件中定义我所有的枚举 Laravel 5.7
- jms - 向(虚拟)主题发送消息时过滤目的地
- java - 是否可以将引用类型传递给需要动态引用类型的对象实例?