改了下,能输入一个小数点了
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class Sum extends JFrame{
private JTextField num1,num2,result;
private JLabel operation;
private JButton add;
private Container container;
public Sum(){
super("两数相加");
container = getContentPane();
container.setLayout(new FlowLayout());
num1 = new JTextField(10);
num1.setDocument(new NumOnly());
num2 = new JTextField(10);
num2.setDocument(new NumOnly());
result = new JTextField(10);
result.setEditable(false);
operation = new JLabel("+");
add = new JButton("=");
add.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
if(num1.getText().equals("")||num2.getText().equals("")){
JOptionPane.showMessageDialog(container,"您必须输入两个数","提示",JOptionPane.INFORMATION_MESSAGE);
}
else{
float n1 = Float.valueOf(num1.getText());
float n2 = Float.valueOf(num2.getText());
result.setText(String.valueOf(n1+n2));
}
}
}
);
container.add(num1);
container.add(operation);
container.add(num2);
container.add(add);
container.add(result);
pack();
Dimension frameSize = getSize();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setLocation((screenSize.width-frameSize.width)/2,(screenSize.height-frameSize.height)/2);
setResizable(false);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[]){
Sum s = new Sum();
}
public class NumOnly extends PlainDocument{
private boolean dot = false;
public void insertString(int offs,String str,AttributeSet a) throws BadLocationException{
for(int i=0;i<str.length();i++){
if((str.charAt(i)<'0'||str.charAt(i)>'9') && dot){
return;
}
}
if(str.substring(0,1).equals("."))
dot = true;
super.insertString(offs,str,a);
}
}
}
[[it] 本帖最后由 freish 于 2008-4-27 22:21 编辑 [/it]]