2012-10-25 47 views
1

我是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(); 
} 
+0

請詳細描述您的問題。你究竟做了什麼,你無法做到?你的代碼的哪一部分試圖做到這一點?假設我們沒有事先知道您的問題或您的代碼,特別是未顯示的代碼。 –

+0

幸運的是,人們能夠理解你的代碼,但下一次,請告訴我們更多。我不知道爲什麼你從來沒有回覆我上面的評論。 –

+0

對不起,下次我會更好地格式化我的代碼。我在文本框中的代碼格式有問題。雖然我的錯。感謝您的迴應! –

回答

3

我覺得你剛剛作出了一個非常小的錯誤,是忘記指定String.format()

佔位%s試試這個:

newStringLabel.setText(String.format("%s", newStr)); 
+0

哇,你是對的。男人,這在Eclipse中沒有顯示爲錯誤。感謝您關注細節。我會確保在下次發佈另一個問題之前這樣做。 –

2

設置標籤的文本時,您不需要String.format("", newStr)電話,你可以簡單地使用

newStringLabel.setText(newStr); 
+0

你說得對。謝謝你解釋了一切。我會磨練我的Eclipse環境的錯誤顯示並減少我的愚蠢錯誤。 –