I'd recommend using the setBounds
method instead of the setLocation
JTextField tf = new JTextField(10);
Dimension d = tf.getPreferredSize();
tf.setBounds(x, y, d.width, d.height);
Of course, if you're using a null Layout manager, you also need to take care of your preferredSize
. Here's an example that incorporates all the major aspects:
import java.awt.*;
import javax.swing.*;
public class TestProject extends JPanel{
public TestProject(){
super(null);
JTextField tf = new JTextField(10);
add(tf);
Dimension d = tf.getPreferredSize();
tf.setBounds(10, 20, d.width, d.height);
}
@Override
public Dimension getPreferredSize(){
//Hard coded preferred size - but you'd probably want
//to calculate it based on the panel's content
return new Dimension(500, 300);
}
public static void main(String args[])
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setContentPane(new TestProject());
frame.pack();
frame.setVisible(true);
}
});
}
}