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.
CodePudding user response:
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.add(textField);
frame.setSize(500,500);
frame.setLayout(null);
textField.setBounds(PositionX,PositionY,SizeX,SizeY);
textField.setVisible(true);
frame.setVisible(true);
}
}
Or you Can Use JInternalFrame And Implement The TextField In There.
EDIT: I have made corrections to the code thanks to the below comment
CodePudding user response:
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.