Can someone please help me how to set the width of a JTextField at runtime? I want my text field to be resized on runtime. It will ask the user for the length, then the input will change the width of the text field.
if(selectedComponent instanceof javax.swing.JTextField){
javax.swing.JTextField txtField = (javax.swing.JTextField) selectedComponent;
//txtField.setColumns(numInput); //tried this but it doesn't work
//txtField.setPreferredSize(new Dimension(numInput, txtField.getHeight())); //also this
//txtField.setBounds(txtField.getX(), txtField.getY(), numInput, txtField.getHeight());
//and this
txtField.revalidate();
}
I am using null layout for this, since I’m on edit mode.
You simply need to use
jTextFieldObject.setColumns(int columnSize). This will let you increase it’s size at runtime. The reason why you couldn’t do it at your end is thenullLayout. That is one of the main reasons why the use ofnull Layout/Absolute Positioningis discouraged. Here is a small example for trying your hands on :For absolute positioning you need to call
setSize()on theJTextFieldin order to attain the result, though you should always keep in mind the reason why this approach is discouraged, as given in the Java Doc’s first paragraph: