我是Java事件,偵聽器和處理程序的新手。我可以編寫代碼來創建一個按鈕點擊事件和一個工作結果。但是,我無法在TextField中使用簡單的輸入事件來工作。Java輸入事件不會激活處理程序
注意我聲明並調用動作偵聽器,輸入處理程序並定義生成的方法執行。 (我進口的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();
}
請詳細描述您的問題。你究竟做了什麼,你無法做到?你的代碼的哪一部分試圖做到這一點?假設我們沒有事先知道您的問題或您的代碼,特別是未顯示的代碼。 –
幸運的是,人們能夠理解你的代碼,但下一次,請告訴我們更多。我不知道爲什麼你從來沒有回覆我上面的評論。 –
對不起,下次我會更好地格式化我的代碼。我在文本框中的代碼格式有問題。雖然我的錯。感謝您的迴應! –