[英]How can I stop the JTextField from taking up my whole JFrame?
我編寫了代碼來創建一個包含游戲的 JFrame,但我需要添加一個 TextField。 到目前為止,我已經能夠添加整個字段,但它占用了整個幀。 看其他例子我有點困惑,所以我想我會問是否有人可以用我的代碼向我提示正確的方向。
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();
}
}
VS 與 JTextField:
我希望文本框只占據屏幕中間某處的一小部分。
我最終通過使用在游戲開始時出現的 JOptionPane 解決了這個問題。
如果其他閱讀者有類似的問題但不想使用選項窗格,您可以改為為 window 設置布局,並以不相互重疊的方式向其中添加組件。
你試過textField.setBounds();
?
示例用法:
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);
}
}
或者您可以使用 JInternalFrame 並在其中實現 TextField。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.