[英]Java Enter Event Does Not Activate Handler
I am new to Java events, listeners and handlers. 我是Java事件,侦听器和处理程序的新手。 I can write code to create a button click event and a working result. 我可以编写代码来创建按钮单击事件和工作结果。 However, I cannot get a simple enter event within a TextField to work. 但是,我无法在TextField中获得一个简单的enter事件来工作。
Notice I do declare and call action listeners, input handlers, and define a resulting method execution. 注意,我确实声明并调用了动作侦听器,输入处理程序,并定义了结果执行方法。 (I import java.awt and javax.swing libraries not shown below.) (我导入了未在下面显示的java.awt和javax.swing库。)
public convertStringToCapitalLetters() {
setTitle("Convert String to All Capital Letters");
Container c = getContentPane();
c.setLayout(new GridLayout(2, 2));
inputLabel = new JLabel("Enter String: ", SwingConstants.LEFT);
stringTextField = new JTextField(50);
outputLabel = new JLabel("Capitalized String: ", SwingConstants.LEFT);
newStringLabel = new JLabel("", SwingConstants.RIGHT);
c.add(inputLabel);
c.add(stringTextField);
c.add(outputLabel);
c.add(newStringLabel);
inputHandler = new InputHandler();
stringTextField.addActionListener(inputHandler);
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
private class InputHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
String str, newStr;
str = stringTextField.getText();
newStr = str.toUpperCase();
newStringLabel.setText(String.format("", newStr));
}
}
public static void main(String[] args) {
convertStringToCapitalLetters capitalConv = new convertStringToCapitalLetters();
}
I think you just made a very small mistake which is to forget to specify the placeholder %s
in String.format()
我认为您犯了一个非常小的错误,那就是忘记在String.format()
指定占位符%s
Try this: 尝试这个:
newStringLabel.setText(String.format("%s", newStr));
设置标签的文本时不需要String.format("", newStr)
调用,您只需使用
newStringLabel.setText(newStr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.