I am new to Java events, listeners and handlers. 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.
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.)
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()
Try this:
newStringLabel.setText(String.format("%s", newStr));
设置标签的文本时不需要String.format("", newStr)
调用,您只需使用
newStringLabel.setText(newStr);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.