1

我是 Java 事件、侦听器和处理程序的新手。我可以编写代码来创建按钮单击事件和工作结果。但是,我无法让 TextField 中的简单输入事件起作用。

请注意,我确实声明并调用了动作侦听器、输入处理程序,并定义了结果方法执行。(我导入了下面未显示的 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();
}
4

2 回答 2

3

我认为您只是犯了一个很小的错误,就是忘记%sString.format()

试试这个:

newStringLabel.setText(String.format("%s", newStr));
于 2012-10-25T22:19:59.367 回答
2

设置标签文本时不需要String.format("", newStr)调用,只需使用

newStringLabel.setText(newStr);
于 2012-10-25T22:22:28.650 回答