[英]JTextField ActionListener in GridBagLayout
I am having troubles adding an actionlistener to my JTextField. 我在向JTextField添加actionlistener时遇到了麻烦。 I need to get the text entered from the user into a string so i can work with it.
我需要将用户输入的文本转换为字符串,以便我可以使用它。
Can anyone tell me what im doing wrong or how i should do it. 任何人都可以告诉我我做错了什么或我应该怎么做。
Here is the code: 这是代码:
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
JFrame frame = new JFrame("Value Bet");
frame.setVisible(true);
frame.setSize(500,300);
GridBagLayout layout = new GridBagLayout();
frame.setLayout(layout);
GridBagConstraints c = new GridBagConstraints();
JLabel label;
JTextField tf;
if (shouldFill) {
//natural height, maximum width
c.fill = GridBagConstraints.HORIZONTAL;
}
if (shouldWeightX) {
c.weightx = 0.5;
}
...
tf = new JTextField();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 2;
frame.add(tf, c);
tf.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String chance1 = tf.getText();
}
});
...
Why are you using ActionListener
instead of KeyListener
? 为什么使用
ActionListener
而不是KeyListener
?
You should use KeyListener or: 您应该使用KeyListener或:
tf.getDocument().addDocumentListener(documentListener);
public void actionPerformed(ActionEvent e)
{
// Look Ma, a one-liner!
String chance1 = JOptionPane.showInputDialog(someComponent, "Value Bet");
}
Look further into the overloaded methods to tweak the look, for robustness add a null
check, and consider using a spinner instead of the text field (BNI). 进一步研究重载方法以调整外观,为鲁棒性添加
null
检查,并考虑使用微调器而不是文本字段(BNI)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.