In the Swing Layout Manager tutorial
The FlowLayout class puts components in a row, the size of which depends on their size. If the horizontal space in the container is too small to fit all the components on one line, the FlowLayout class uses several lines. If the container is larger than necessary for a number of components, the default row is horizontally inside the container
So, you need to adjust the preferred size of the text field, preferably using the setColumns
method.
Please note that if you want your text field to cover the entire width, you can use a different layout and then FlowLayout
for the above reason
For example, the following code gives a nice JTextField
, but I hardcoded the number of columns
import javax.swing.JFrame; import javax.swing.JTextField; import java.awt.Container; import java.awt.EventQueue; import java.awt.FlowLayout; public class TextFieldWithFlowLayout { public static void main( String[] args ) { EventQueue.invokeLater( new Runnable() { @Override public void run() { JFrame console = new JFrame("ArchiveConsole"); Container base = console.getContentPane(); base.setLayout(new FlowLayout( FlowLayout.CENTER, 5,5)); JTextField tf = new JTextField(); tf.setColumns( 20 ); base.add(tf); console.pack(); console.setVisible(true); } } ); } }
Robin source share