使用图形从用户那里获取输入
Get an input from the user using graphics
我正在编写我的第一款游戏,我想将用户的名字添加到高分排行榜中。从用户那里获取输入的最佳方式是什么?除了使用 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);
}
然后你只需要在你的构造函数的某处添加一个keylistener。
addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
text+=e.getKeyChar();
//you might not need this is you are rendering constantly
repaint();
}
});
我正在编写我的第一款游戏,我想将用户的名字添加到高分排行榜中。从用户那里获取输入的最佳方式是什么?除了使用 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);
}
然后你只需要在你的构造函数的某处添加一个keylistener。
addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
text+=e.getKeyChar();
//you might not need this is you are rendering constantly
repaint();
}
});