Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何限制用户只在文本字段中插入数字?_Java_Swing_User Interface_Jtextfield_Limits - Fatal编程技术网

Java 如何限制用户只在文本字段中插入数字?

Java 如何限制用户只在文本字段中插入数字?,java,swing,user-interface,jtextfield,limits,Java,Swing,User Interface,Jtextfield,Limits,这是我的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;

这是我的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());
        }
    }
}

}
涉及的文本字段是

private JTextField quantitytext = new JTextField("1",10);
private JTextField creditCardtext = new JTextField("1",10);
如何编写try and catch()函数来限制用户输入? 由于商品数量和信用卡号只能接受整数。
非常感谢您的帮助~

您正在寻找DocumentFilter。这里有如何实现它的官方教程。 . 您的文档必须从
AbstractDocument
扩展。默认情况下,Swing text组件使用AbstractDocument子类作为其文档

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.
       }

}

还可以使用JFormattedTextfield

如果您使用的是扩展了
AbstractDocument
的文档,那么当我扩展AbstractDocument时,您可以使用
DocumentFilter
,它说我需要为类销售实现一个构造函数,否则就是错误的。您可以使用扩展了
AbstractDocument
PlainDocument
,默认情况下,swing文本组件使用的是扩展
AbstractDocument
I的内容,正如您在这里所说的那样,使用DocumentFilter,我不确定要编写什么的业务逻辑。我把它作为我的业务登录名,但error@Override public void insertString(DocumentFilter.FilterBypass fb,int offset,String String,AttributeSet attr)抛出了BadLocationException{if(Double.parseDouble(quantitytext.getText()){commenttext.setText(“您只能在整数中输入数量!”);}@Nick您遇到了什么问题?使用
fb.getDocument().getText(..)
str
来解析整数。您是parsingDouble,它与整数不同。根据我的说明,这个简单的应用要求是,对于textfield
quantitytext
creditcardtext
只能接收数字。。到目前为止,我还不确定DocumentFilter是如何工作的,
fb.getDocument().getText(…)
getDocument()我收到的错误是getDocument无法解决或不是field@Nick你读过oracle教程吗?这是直截了当的,我正在使用Keylistener来解决它,感谢oracle教程。因为我真的不知道我需要扩展
AbstractDocument
DocumentFilter