简体   繁体   中英

Java gui Jbutton

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);

    }
}

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.

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);

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM