I've got a problem where I'm adding a JTextField to a JPanel and it appears centered horizontally and adjacent to the top border instead of at the coordinates I set with setBounds().
My code has a class that creates a JFrame and calls a new Jpanel like this:
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();
}
}
The JPanel is coded like this:
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);
}