How to limit user of only insert number into textfield?

959 views Asked by At

This is my Sales.java

package assignment2;

import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class Sales implements ActionListener{

private String paymentmethod[] = {"Visa","Master"};

private String first = "Crunchy Combo 1 - RM19.70";
private String second = "Crunchy Combo 2 - RM26.90";
private String third = "Hot Variety Box - RM28.28";
private String fourth = "Hot Power Meal 1 - RM22.90";
private String fifth = "Hot Power Meal 2 - RM53.90";

private double price1 = 19.70;
private double price2 = 26.90;
private double price3 = 28.28;
private double price4 = 22.90;
private double price5 = 53.90;
private double total = 0.0;

private JRadioButton crunchy1 = new JRadioButton("Crunchy Combo 1 - RM 19.70",true);
private JRadioButton crunchy2 = new JRadioButton("Crunchy Combo 2 - RM 26.90");
private JRadioButton hotvariety = new JRadioButton("Hot Variety Box - RM 28.28");
private JRadioButton hotpower1 = new JRadioButton("Hot Power Meal 1 - RM 22.90");
private JRadioButton hotpower2 = new JRadioButton("Hot Power Meal 2 - RM 53.90");
private ButtonGroup gp = new ButtonGroup();

private JLabel item = new JLabel("Select Item");    
private JLabel quantity = new JLabel("Quantity: ");
private JLabel payment = new JLabel("Payment Method: ");
private JLabel creditCard = new JLabel("Credit Card number: ");
/*item.setHorizontalAlignment(JLabel.LEFT);
quantity.setHorizontalAlignment(JLabel.LEFT);
payment.setHorizontalAlignment(JLabel.LEFT);
creditcard.setHorizontalAlignment(JLabel.LEFT);*/

private JTextField quantitytext = new JTextField("1",10);
private JTextField creditCardtext = new JTextField("1",10);
private JTextArea commenttext = new JTextArea();

private JComboBox combo = new JComboBox(paymentmethod);

private JButton done = new JButton("DONE!");

public void createGUI(){

    JFrame frame = new JFrame("Point of Sales");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new FlowLayout());
    frame.setBounds(100,100,500,400);

    gp.add(crunchy1);
    gp.add(crunchy2);
    gp.add(hotvariety);
    gp.add(hotpower1);
    gp.add(hotpower2);

    JPanel all = new JPanel();
    all.setLayout(new GridLayout(0,1));

    JPanel panelItem = new JPanel();
    panelItem.setLayout(new FlowLayout());

    JPanel panelOption = new JPanel();
    panelOption.setLayout(new GridLayout(4,2));

    JPanel panelSales = new JPanel();
    panelSales.setLayout(new GridLayout(4,2));

    JPanel panelTextArea = new JPanel();
    panelTextArea.setSize(500, 50);

    combo.setSelectedIndex(1);

    done.addActionListener(this);
    commenttext.setEditable(false);

    frame.add(all);
    all.add(panelItem);
    all.add(panelSales);
    all.add(panelTextArea);

    panelOption.add(crunchy1);
    panelOption.add(crunchy2);
    panelOption.add(hotvariety);
    panelOption.add(hotpower1);
    panelOption.add(hotpower2);

    panelItem.add(item,BorderLayout.WEST);
    panelItem.add(panelOption,BorderLayout.EAST);

    panelSales.add(quantity);
    panelSales.add(quantitytext);
    panelSales.add(payment);
    panelSales.add(combo);
    panelSales.add(creditCard);
    panelSales.add(creditCardtext);
    panelSales.add(done);

    panelTextArea.add(commenttext);

    frame.pack();
    frame.setVisible(true);
}

public static void main(String args[]){
    Sales sale = new Sales();
    sale.createGUI();
}

@Override
public void actionPerformed(ActionEvent arg0) {
    // TODO Auto-generated method stub
    if(arg0.getSource()==done)
    { 
        if(crunchy1.isSelected())
        { 
            total=price1*Double.parseDouble(quantitytext.getText());
            Object d=combo.getSelectedItem(); 
            String h=d.toString();
            commenttext.setText("Selected Item and Price per Unit:" + first + "\nQuantity: "+ quantitytext.getText() + "\nThe amount is RM" + total + " Charged to "+ h +" "+ creditCardtext.getText());
        }

        else if(crunchy2.isSelected())
        { 
            total=price2*Double.parseDouble(quantitytext.getText());
            Object d=combo.getSelectedItem(); 
            String h=d.toString();
            commenttext.setText("Selected Item and Price per Unit:" + second + "\nQuantity: "+ quantitytext.getText() + "\nThe amount is RM" + total + " Charged to "+ h +" "+ creditCardtext.getText());
        }

        else if(hotvariety.isSelected())
        { 
            total=price3*Double.parseDouble(quantitytext.getText());
            Object d=combo.getSelectedItem(); 
            String h=d.toString();
            commenttext.setText("Selected Item and Price per Unit:" + third + "\nQuantity: "+ quantitytext.getText() + "\nThe amount is RM" + total + " Charged to "+ h +" "+ creditCardtext.getText());
        }

        else if(hotpower1.isSelected())
        { 
            total=price4*Double.parseDouble(quantitytext.getText());
            Object d=combo.getSelectedItem(); 
            String h=d.toString();
            commenttext.setText("Selected Item and Price per Unit:" + fourth + "\nQuantity: "+ quantitytext.getText() + "\nThe amount is RM" + total + " Charged to "+ h +" "+ creditCardtext.getText());
        }

        else if(hotpower2.isSelected())
        { 
            total=price5*Double.parseDouble(quantitytext.getText());
            Object d=combo.getSelectedItem(); 
            String h=d.toString();
            commenttext.setText("Selected Item and Price per Unit:" + fifth + "\nQuantity: "+ quantitytext.getText() + "\nThe amount is RM" + total + " Charged to "+ h +" "+ creditCardtext.getText());
        }
    }
}

}

The TextField involved is

private JTextField quantitytext = new JTextField("1",10);
private JTextField creditCardtext = new JTextField("1",10);

How should I write the try and catch() function to limit user input? Since quantity of item and credit card number only can accept intergers. Your help here is really appreciated~

1

There are 1 answers

5
nachokk On

You are looking for DocumentFilter. Here you have official tutorial how to implement it. Implementing a documentFilter . Your document have to extends from AbstractDocument by default Swing text components use AbstractDocument subclasses for their documents.

myTextField.getDocument().setDocumentFilter( new MyDocumentFilter() )

class MyDocumentFilter extends DocumentFilter {

@Override
public void insertString(DocumentFilter.FilterBypass fb,
                int offset,
                String string,
                AttributeSet attr)
                  throws BadLocationException{

          //your business logic here
          // Example : if it's a number super.insertString(..) else do nothing.
       }

}

Also you can use JFormattedTextfield. How to use formatted textfields.