If my question wasn't very specific, here is what I am trying to do. I have a calculator that has two JTextFields, a JLabel ("Answer = "), and a JTextField for the answer.
I have an array of JButtons (0 through 9) that allow the user to click on them to add the number to the JTextField with the cursor active in it... which is the problem here. I can only have one of the two textfields add numbers to them or both add the same numbers to each other.
For example, if I click on a button and the addActionListener
is set to (new AddDigitsONE)
it will only allow me to add numbers to the first JTextField. It will jump back to the first JTextField even after I try to set the cursor to the second JTextField and add numbers to it using the JButtons.
Code for adding the array of JButtons to the JPanel in the 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());
}
Code for my action listener: First 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));
}
}
Code for my action listener: Second 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));
}
}
Is there a way to merge both action listeners and differentiate between which text field has the cursor active in it (while allowing me to enter numbers in both JTextFields using the JButtons)?
Instead of using an ActionListener you can add an Action to the button. In this case you will want to extend TextAction because it has a method that allows you to get the last focused text component so you can insert the digit into that component. The code would be something like:
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 );
}
}