A suggested solution is seen below. It is important to add the components in the correct order.
At right is the display for the program. Observe how the components have been laid out in the frame.
FlowLayout is like a firehose that squirts out the components onto the frame in the same order in which they are added by the program. It starts in the top left, goes across the frame until it hits the right edge, then starts another left to right sweep far enough down to avoid the first row of components (this is called "raster order".) It also centers components within their row.
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TextEg2 extends JFrame { JTextField text; JLabel lbl ; public TextEg2() { text = new JTextField( 15 ) ; lbl = new JLabel ( "Enter Your Name:" ); getContentPane().setLayout( new FlowLayout() ); getContentPane().add( lbl ); getContentPane().add( text ); setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE ); } public static void main ( String[] args ) { TextEg2 teg = new TextEg2() ; teg.setSize ( 300, 100 ); teg.setVisible( true ); } }
Run the program.
Type text into the field.
Correct it using the backspace and delete keys.
All of these functions comes along for free when you
construct a JTextField
object.
Click and drag on the left edge of the frame to widen it.
Observe what happens to the GUI components.