简体   繁体   中英

JTextField not appearing on top of JFrame

How do I get a textbox to appear on this JFrame? Also is it good practice to build everything on top of the JFrame itself? Or is it better to overlay a JPanel and build everything on top of that?

Thanks in advance!

public class GUI {

    private static JFrame frame = new JFrame("FrameDemo");

    public GUI() {

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        BufferedImage myImage = null;
        try {
            myImage = ImageIO.read(new File("C:/Users/Desktop/background.jpg"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 

        frame.setContentPane(new ImageFrame(myImage));

        JTextField field = new JTextField(10);
        frame.add(field, BorderLayout.SOUTH);

        Dimension dimension = new Dimension(); 
        dimension.setSize(950, 800);
        frame.setSize(dimension);

        frame.setVisible(true);
    }

}

You have replaced the default content pane with you own content pane. I would guess your content pane does not use a layout manager so the text field is never displayed.

Try something like:

//frame.setContentPane(new ImageFrame(myImage));
ImageFrame content = new ImageFrame(myImage));
content.setLayout( new BorderLayout() );
frame.setContentPane(content);

Now you text field should be added to the south of your image panel.

Also is it good practice to build everything on top of the JFrame itself? Or is it better to overlay a JPanel and build everything on top of that?

The content pane of a JFrame is a JPanel, so it doesn't really matter what you do since your will be using a panel either way. The key is to manage the layout manager of your content pane.

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