首页 > 解决方案 > 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);
            
    }

标签: javaswingjframejtextfieldsetbounds

解决方案


推荐阅读