0

I'm trying to make a calculator program, and I want to only allow numbers to be typed, but I don't know how to do that, will you please tell me how. I haven't found anything elsewhere. Here is my source code:

import javax.swing.*;
import java.awt.*;

public class Sect1 extends JTextArea{
    public static final Dimension ss = Toolkit.getDefaultToolkit().getScreenSize();

    public Sect1(){
        this.setBounds(ss.width / 4, ss.height / 5, 100, 100);
        this.setLineWrap(true);
        this.setWrapStyleWord(true);
    }
}
  • 3
    Aside: never call `setBounds()` It's always going to be wrong. Use a layout manager please. – markspace Mar 02 '21 at 00:36
  • You basically have to intercept the inputs made to the JTextArea, and then silently reject them if it's not a number. – Benjamin M Mar 02 '21 at 00:39
  • 1
    For numbers only, look into [JFormattedTextField](https://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html) or a [document filter](https://docs.oracle.com/javase/tutorial/uiswing/components/generaltext.html#filter) – markspace Mar 02 '21 at 00:39
  • 1
    Why are you typing numbers into a JTextArea. Usually a calculator has button that allows you to enter numbers. Then you either 1) click on the button or 2) press the number displayed on the button. See: https://stackoverflow.com/questions/33739623/how-to-add-a-shortcut-key-for-a-jbutton-in-java/33739732#33739732 for an example of this approach. – camickr Mar 02 '21 at 02:17

1 Answers1

1

As commented above, have a look at the JFormattedTextField, or DocumentFilter classes. These will allow you to (more simply) control the inputs for your jTextField.

Another option to consider is creating a method like below:

public static boolean isNumber(String input){
    try{
        Integer.parseInt(input);
    }
    catch(Exception e){
        return false;
    }
    return true;
}

All that this code tries to do is parse the input as an integer and return if it is able to do that (and hence if the data is an integer). Calling this method with jTextField.getText() as the input using an eventListener will let you know if the data in the field is an integer or not while you are typing. See this for more on the last part.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Lain
  • 53
  • 7