I want to make this function less messy, I don't want individual if statements for every button but I can't figure out a correct solution. Anyone want to help?
public void actionPerformed( ActionEvent arg0 ) {
if(arg0.getSource()==buttons[0]){
txField.setText(txField.getText() + bText[0]);
}
if(arg0.getSource()==buttons[1]){
txField.setText(txField.getText() + bText[1]);
}
if(arg0.getSource()==buttons[2]){
txField.setText(txField.getText() + bText[2]);
}
if(arg0.getSource()==buttons[3]){
txField.setText(txField.getText() + bText[3]);
}
if(arg0.getSource()==buttons[4]){
txField.setText(txField.getText() + bText[4]);
}
if(arg0.getSource()==buttons[5]){
txField.setText(txField.getText() + bText[5]);
}
if(arg0.getSource()==buttons[6]){
txField.setText(txField.getText() + bText[6]);
}
if(arg0.getSource()==buttons[7]){
txField.setText(txField.getText() + bText[7]);
}
if(arg0.getSource()==buttons[8]){
txField.setText(txField.getText() + bText[8]);
}
if(arg0.getSource()==buttons[9]){
txField.setText(txField.getText() + bText[9]);
}
if(arg0.getSource()==buttons[10]){
txField.setText(txField.getText() + bText[10]);
}
}
What can I use to make this function shorter? A HashMap? For loop? Please assist. I want to have 20 buttons in total, I have only posted half of the function as the rest is redundant. bText is a string array with all necessary buttons for a calculator program. I.E 1, 2, 3, C, CE, etc.
Well, I don't know about Java but in a similar language you could do something like this,
for (int i = 0; i < button.length; i++)
{
if(arg0.getSource() == buttons[i])
{
txField.setText(txField.getText() + bText[i]);
break;
}
}