You can set the layout manager to null(cont.setLayout(null);), but this is generally bad practice.
You can see the complete FlowLayout version of this program at Example - Kilometers to Miles - Complete. Below is a comparison of the layout section of the FlowLayout constructor with the equivalent null layout constructor.
| FlowLayout | Null Layout |
|---|---|
//... Content panel, layout, add components
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
content.add(new JLabel("Kilometers"));
content.add(m_kilometersTf);
content.add(m_convertBtn);
content.add(new JLabel("Miles"));
content.add(m_milesTf);
this.setContentPane(content);
this.pack();
|
//... Create labels.
JLabel kmLabel = new JLabel("Kilometers");//Note 1
JLabel miLabel = new JLabel("Miles");
//... Set the positions of components.
kmLabel.setBounds(5, 10, 62, 16); //Note 2
m_kilometersTf.setBounds(72, 8, 114, 20);
m_convertBtn.setBounds(191, 5, 78, 26);
miLabel.setBounds(274, 10, 30, 16);
m_milesTf.setBounds(309, 8, 114, 20);
//... Content panel, layout, add components
JPanel content = new JPanel();
content.setLayout(null); //Note 3
content.add(kmLabel);
content.add(m_kilometersTf);
content.add(m_convertBtn);
content.add(miLabel);
content.add(m_milesTf);
this.setContentPane(content);
this.setSize(436, 63); //Note 4
NotesNote 1: Labels must be in variables to set their bounds. Note 2: How will you compute these coordinates? Note 3: Set the layout manager to null. Note 4: Explicitly set the size of the window. |