2012-01-06 23 views
3

如果我的問題不是很具體,這是我正在嘗試做的。我有一個計算器,它有兩個JTextField,一個JLabel(「Answer =」)和一個JTextField作爲答案。用JButton添加文本到兩個文本框

我有一個JButtons(0到9)的數組,允許用戶點擊它們將數字添加到JTextField中,並將光標在其中激活......這是這裏的問題。我只能有兩個文本字段中的一個向其添加數字,或者兩者都添加相同的數字。

例如,如果我點擊一個按鈕並且addActionListener設置爲(new AddDigitsONE)它只會允許我將數字添加到第一個JTextField。即使我嘗試將遊標設置爲第二個JTextField並使用JButton添加數字,它也會跳回到第一個JTextField。

代碼添加Jbutton將數組到的JPanel JFrame中


// input is my JPanel set to BorderLayout.SOUTH 

for (int i = 0; i < button.length; i++) 
{ 
    text = Integer.toString(i); 
    button[i] = new JButton(); 
    button[i].setText(text); 
    input.add(button[i]); 
    button[i].addActionListener(new AddDigitsONE()); 
} 

代碼爲我的動作監聽:一是JTextField的

// firstNumber is my first JTextField 
// command is the button pressed (0-9) 
// command "<" is erasing one character at a time 

private class AddDigitsONE implements ActionListener 
{ 
    public void actionPerformed(ActionEvent e) 
    { 
     String text = firstNumber.getText(); 
     String command = ((JButton)(e.getSource())).getText(); 

     if (command == "<") 
     { 
      firstNumber.setText(text.substring(0,text.length()-1)); 
     } 

     else 
      firstNumber.setText(text.concat(command)); 
    } 
} 

代碼爲我的動作監聽:二JTextField的

private class AddDigitsTWO implements ActionListener 
{ 
    public void actionPerformed(ActionEvent e) 
    { 
     String text = secondNumber.getText(); 
     String command = ((JButton)(e.getSource())).getText(); 

     if (command == "<") 
     { 
      secondNumber.setText(text.substring(0,text.length()-1)); 
     } 

     else 
      secondNumber.setText(text.concat(command)); 
    } 
} 

有沒有辦法合併這兩個動作的聽衆和區分它們之間的文本字段中有光標激活(同時讓我輸入數字在兩個使用JButton的JTextFields中)?

+1

這似乎是一個非常尷尬的方式來製作一個計算器,至少對我來說。 – Max 2012-01-06 20:04:18

+0

@Max我知道。我正在研究一些製作計算器的更復雜的方法。防爆。有一個文本框顯示您的所有數字和操作......類似於一個真實的計算器。但是他們中的很多人都有點過頭了。 – Rob 2012-01-06 20:06:16

回答

4

而不是使用ActionListener,您可以將Action添加到按鈕。在這種情況下,您需要擴展TextAction,因爲它有一個方法可以讓您獲取最後一個焦點文本組件,以便您可以將該數字插入該組件。代碼會是這樣的:

class AddDigit extends TextAction 
{ 
    private String digit; 

    public AddDigit(String digit) 
    { 
     super(digit); 
     this.digit = digit; 
    } 

    public void actionPerformed(ActionEvent e) 
    { 
     JTextComponent component = getFocusedComponent(); 
     component.replaceSelection(digit); 
    } 
} 
+0

再一次非常感謝你!我很好奇組件如何知道將一個數字連接到前一個數字的末尾。我讀過[JTextComponent](http://docs.oracle.com/javase/6/docs/api/javax/swing/text/JTextComponent.html#replaceSelection%28java.lang.String%29),但是文檔讓我撓了腦袋......這會和構造函數有什麼關係嗎? – Rob 2012-01-06 22:46:29

+0

它代替當前插入位置處的文本。 – camickr 2012-01-07 02:20:13