2012-01-06 48 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