简体   繁体   中英

How can I stop the JTextField from taking up my whole JFrame?

I have code written to create a JFrame which holds a game, but I need to add a TextField. So far I have been able to add the whole field but it takes up the entire frame. I'm a bit confused looking at other examples, so I thought I would ask if anyone could prompt me in the right direction a bit with my code.

public class Window extends Canvas {

    @Serial
    private static final long serialVersionUID = -5360723068750368974L;

    public Window( int width, int height, String title, Game game){
        JFrame frame = new JFrame(title);

        JTextField username = new JTextField(10);



        //Sets minimum maximum and default window size as the same, so the window is always the same size
        frame.setPreferredSize(new Dimension(width, height));
        frame.setMaximumSize(new Dimension(width, height));
        frame.setMinimumSize(new Dimension(width, height));

        //Allows the x button on the window to close the program
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Prevents the window from being resizable
        frame.setResizable(false);
        //Location of the window is not relative to anything
        frame.setLocationRelativeTo(null);
        //Tells the frame what it will contain
        frame.add(game);
        frame.add(username);
        //Makes the frame visible
        frame.setVisible(true);
        //calls game start method
        game.start();
    }
}

The output for the code without the JTextField: 标准游戏窗口

VS with the JTextField:

文本域

I want the text box to only take up a small portion of the screen somewhere in the middle.

I solved this issue in the end by using a JOptionPane instead which appears at the start of the game.

If anyone else reading has a similar issue but does not want to use an option pane, you can instead set a layout for your window and add components to it in a way that they do not overlap eachother.

Have You Tried textField.setBounds(); ?

Usage With Example:

import javax.swing.*;
import java.awt.*;

public class Main{
    public static void main(String[] args)
    {
        int PositionX = 0,PositionY = 0,SizeX = 450,SizeY = 450;
        JFrame frame = new JFrame("Game");
        JTextField textField = new JTextField();
        frame.setVisible(true);
        frame.add(textField);
        frame.setSize(500,500);
        textField.setBounds(PositionX,PositionY,SizeX,SizeY);
        textField.setVisible(true);
    }
}

Or you Can Use JInternalFrame And Implement The TextField In There.

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