gpt4 book ai didi

java - 使用图形从用户那里获取输入

转载 作者:行者123 更新时间:2023-12-01 09:46:27 25 4
gpt4 key购买 nike

我正在编写我的第一个游戏,我想将用户的名字添加到高分图表中。获取用户输入的最佳方式是什么?除非使用 JOption。

无需说明我正在连续绘制我的游戏。也许我可以使用 JTextField?

最佳答案

假设您将游戏渲染到 JComponent 上,是的,您可以将 JTextField 添加到渲染器组件上。或者,如果您想自定义所有内容的外观,您可以呈现自己的文本字段。

要执行自定义渲染器:

在代码中的某个位置存储文本输入框的位置。

Rectangle r = new Rectangle(200,200,250,30);
String text = "";

在您的渲染代码中:

public void paintComponent(Graphics g){
g.setColor(Color.blue);
g.fillRect(r.x, r.y, r.width, r.height);
g.setColor(Color.black);
// You can play with this code to center the text
g.drawString(text, r.x, r.y+r.height);
}

然后您只需在构造函数中的某个位置添加一个按键监听器即可。

addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
text+=e.getKeyChar();

//you might not need this is you are rendering constantly
repaint();
}
});

关于java - 使用图形从用户那里获取输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37977143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com