简体   繁体   中英

Button only prints one number

I have a number pad for a calculator, when I push the button only one number appears on the JTextField , even thought I pressed the button twice. How do I allow the user to press a button more than once to make the numbers appear more than once on the JTextField . For example, if someone pressed the one key twice, 11 would appear. Here is my code for this portion and any help is appreciated, thanks!

@Override
public void actionPerformed(ActionEvent e) {
    if(e.getActionCommand().equals("1")){
        numField.setText("1");
    }
}

Get the old text and append the new one on it like this

@Override
public void actionPerformed(ActionEvent e) {
    if(e.getActionCommand().equals("1")){
        numField.setText(numField.getText() + "1");
    }
}

.setText is going to set whatever your thing is inside of that.

Suggestion: Have a global variable and add to it and setText to that global variable.

您在代码中所执行的操作是将文本设置为“ 1” ...看这行进行更改,如何想到一种制作方法,以便将其添加到已存在的字符串的末尾textField?

numField.setText("1");

"set" sets the field text. It doesn't add to the field text. Given the code above, it doesn't matter if you press the button twice or thirty times, the result will always be a single "1" in the field.

SAVE THE RESULT in a different variable, then display that variable.

StringBuilder accumulator = new StringBuilder();

@Override
public void actionPerformed(ActionEvent e) {
    accumulator.append( e.getActionCommand() );
    numField.setText( accumulator.toString() );
}

Not tested.

Another strategy to do this:

   final Set<String> actionSet = new HashSet<String>();
   actionSet.add("1");
   actionSet.add("2");
   actionSet.add("3");

   @Override
   public void actionPerformed(ActionEvent e) {
       if(actionSet.contains(e.getActionCommand())){
           numField.setText(numField.getText() + e.getActionCommand());
       }
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM