javaswingjpanellayout-managerjtextfield

How to set size and location of JTextField?


I want to set location and size of my JTextField, how can I do it ? My code doesn't work.

public static void main(String[] args) {

    JTextField txt1;
    
    
    JFrame frame = new JFrame("Hangman");
    frame.setSize(1100, 600);
    frame.getContentPane().setLayout(new FlowLayout());
    frame.setResizable(false);
    frame.getContentPane().setBackground(Color.BLACK);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    txt1 = new JTextField(50);
    txt1.setSize(200, 199);
    txt1.setLocation(400, 200);
    frame.add(txt1);
    frame.setVisible(true);
}

txt1.setSize and txt1.setLocaiton doesn't work.

Output


Solution

  • Absolute positioning doesn't work with a layout manager.

    If you really need it, you will have to set null as a layout manager, i.e :

    frame.getContentPane().setLayout(null);