我正在学习Java,但被卡住了。我正在使用JTextField作为userInput。用户按下Enter后,我希望我的if语句为我打印“文本已更改”。我想设置2个吸气剂。首先是我的布尔值,第二个是包含用户答案的字符串。
import java.awt.*;
import java.awt.event.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class setTextField{
boolean gotChanged = false;
String userInput;
public void setTextField()
{
Font fieldFont = new Font("Arial", Font.PLAIN, 20);
JTextField test;
test = new JTextField("Input here...");
test.setBounds(widthPosition, 145, 220, 25);
test.setFont(fieldFont);
test.setBackground(Color.WHITE);
test.setForeground(Color.GRAY.brighter());
test.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
gotChanged = true;
userInput = test.getText();
}
});
if(gotChanged)
{
System.out.println("Your answer is " + test);
}
}
public boolean getInfo()
{
return gotChanged;
}
public String getInput()
{
return userInput;
}
}
答案 0 :(得分:2)
将Sysout
放入actionPerformed
方法中。您没有实现重新检查if(gotChanged)
的逻辑。