0

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

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Guido
  • 1
  • 1
  • I found that if I add ``` this.addLayout(null); ``` the JTextField appears in the desired position but I don't understand why – Guido Aug 12 '21 at 18:09
  • 1
    Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). **But** for this type of game, I'd go directly to custom painting - where layouts are irrelevant. – Andrew Thompson Aug 16 '21 at 08:05
  • 1
    **Other Tips:** 1) `this.setSize(SCREEN_HEIGHT,SCREEN_HEIGHT);` That's the wrong size. Presumably the `SpaceInvadersPanel` needs to be that size, so the frame will need to be larger to account for the window chrome (which changes according the OS, among other things. 2) `new Font("Verdana", Font.BOLD, 20)` Don't presume a `Font` exists. 3) `this.setVisible(true);` that should be last, after *all* components are added. 4) `SpaceInvadersFrame extends JFrame` There is no need or case to extend here. Just use a plain instance. – Andrew Thompson Aug 16 '21 at 08:11

0 Answers0