我在使用Netbeans的JAVA中出现文本字段自动计算问题
我的问题是我是否要在“文本字段”中输入数值以进行自动加法,然后在“文本字段”中输入数值至(票价,税金和comm%),在那里我将进入字段自动计算,以便获得结果单击“提交”按钮之前,在“文本字段”(Comm)和“成本价格”中选择这些数值。
try { String sql = "insert into ticketing (Date,LPO,PassName,Route,AirlineCode,TicketNum,SellingPrice, Contact, Officer,Fare,Tax,comm%,comm,CostPrice,System,Remart)" + "values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");
pst = conn.prepareStatement(sql);
//pst.setInt(1, Integer.parseInt(id.getText()));
pst.setString(1, Date.getText());
pst.setString(2, LPO.getText());
pst.setString(3, PassName.getText());
pst.setString(4, Route.getText());
pst.setString(5, AirCode.getText());
pst.setString(6, TikNum.getText());
pst.setString(7, SellPrice.getText());
String Conta;
Conta = Cont.getSelectedItem().toString();
pst.setString (8,Conta);
String Officer;
Officer = Offic.getSelectedItem().toString();
pst.setString (9,Officer);
pst.setString(10, Fare.getText());
pst.setString(11, Tax.getText());
pst.setString(12, commper.getText());
pst.setString(13, comm.getText());
pst.setString(14, CostPrice.getText());
String Sys;
Sys = System.getSelectedItem().toString();
pst.setString (15,Sys);
pst.setString(16, Remark.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "insertion successful");
conn.close();
}catch (SQLException e){
JOptionPane.showMessageDialog(null, e);
}
怎么做。
谢谢...........
答案 0 :(得分:0)
我不得不使用DocumentFilter
来解决问题,我只是在共享我的代码,这可能会在将来对某人有所帮助,也有些人会寻找知识
DocumentFilter df = new DocumentFilter() {
@Override
public void insertString(DocumentFilter.FilterBypass fb, int i, String string, AttributeSet as) throws BadLocationException {
if (isDigit(string)) {
super.insertString(fb, i, string, as);
calcAndSetTotal();
}
}
@Override
public void remove(DocumentFilter.FilterBypass fb, int i, int i1) throws BadLocationException {
super.remove(fb, i, i1);
calcAndSetTotal();
}
@Override
public void replace(DocumentFilter.FilterBypass fb, int i, int i1, String string, AttributeSet as) throws BadLocationException {
if (isDigit(string)) {
super.replace(fb, i, i1, string, as);
calcAndSetTotal();
}
}
private boolean isDigit(String string) {
for (int n = 0; n < string.length(); n++) {
char c = string.charAt(n);//get a single character of the string
//System.out.println(c);
if (!Character.isDigit(c)) {//if its an alphabetic character or white space
return false;
}
}
return true;
}
void calcAndSetTotal() {
int sum = 0;
int fr = 0;
int pc = 0;
int tax = 0;
int total = 0;
if (!Fare.getText().isEmpty()) {
fr= Integer.parseInt(Fare.getText());//we must add this
}
if (!Tax.getText().isEmpty()) {
tax= Integer.parseInt(Tax.getText());//we must add this
}
if (!commper.getText().isEmpty()) {
pc= Integer.parseInt(commper.getText());//we must subtract this
}
sum =(int) (fr *(pc*0.01));
total = (int) (fr + tax - sum);
comm.setText(String.valueOf(sum));
CostPrice.setText(String.valueOf(total));
}
};