Reputation: 149
I have a program but I can't combine the textfield
and the button
in the same frame like in top textfield
and below that the button
:
Here is my source code:
import java.awt.*;
import javax.swing.*;
public class FirstGui extends JFrame
{
JTextField texts;
JButton button;
public FirstGui()
{
texts = new JTextField(15);
add(texts);
button = new JButton("Ok");
add(button);
}
public static void main(String args [])
{
FirstGui gui = new FirstGui();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(200,125);
gui.setVisible(true);
}
}
Upvotes: 0
Views: 275
Reputation: 209092
The default layout is BorderLayout
for JFrame
. When you add components to a BorderLayout
, if you don't specify their BorderLayout
position, like BorderLayout.SOUTH
, the component will automatically be add to BorderLayout.CENTER
. Bthe thing is though, each position can only have one component. So when you add texts
it gets added to the CENTER
. Then when you add button
, it gets added to the CENTER
but texts
gets kicked out. So to fix, you can do
add(texts, BorderLayout.NORTH);
add(button, BorderLayout.CENTER);
See Laying out Components Within a Container to learn more about layout managers.
UPDATE
import java.awt.*;
import javax.swing.*;
public class FirstGui extends JFrame {
JTextField texts;
JButton button;
public FirstGui() {
texts = new JTextField(15);
add(texts, BorderLayout.CENTER);
button = new JButton("Ok");
add(button, BorderLayout.SOUTH);
}
public static void main(String args[]) {
FirstGui gui = new FirstGui();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.pack();
gui.setVisible(true);
}
}
Upvotes: 2
Reputation: 8825
Add a layout like FlowLayout
:
public FirstGui()
{
setLayout(new FlowLayout());
texts = new JTextField(15);
add(texts);
button = new JButton("Ok");
add(button);
}
at the very beginning of your constructor, before anything else.
Upvotes: 2