TextField mit FloatValues

TimoTH

Mitglied
Hi !
Ich versuche gerade ein JTextField zu erstellen, welches nur Zahlen, bzw Kommanzahlen zulässt. Zusätzlich sit die anzahl der Vor- und Nachkommstellen noch begrenzt.
Versuchte es so zu lösen, das ich dem TextField ein eigenes PlainDocument zugewiesen habe. Doch hab ich noch massive Probleme.. Vielleicht kann mir ja jemand helfen?

*gruß*
Timo
Code:
import javax.swing.text.PlainDocument;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;

import java.text.DecimalFormat;
import javax.swing.JTextField;

import java.awt.event.KeyListener;

import java.awt.event.KeyEvent;



/**
 * Diese Klasse ist ein Dokument für Textfelder,welches nur Ziffern zulässt und die Eingabe auf
 * die übergebene Anzahl an Vor- und Nachkommastellen begrenzt.
 *
 */
public class FloatingPointValidation extends PlainDocument implements KeyListener{
    private int beforeSeparator;
    private int afterSeparator;
    final private char separator = '.';
    private JTextField field= null;
    private String pattern = null;
    private String pattern2 = null;
    /**
     *
     * @param before int anzahl der maximal möglichen Vorkommastellen
     * @param after int anzahl der maximal möglichen Nachkommastellen
     */
    public FloatingPointValidation(int before, int after,JTextField field) {
        super();
        field.addKeyListener(this);
        this.field = field;
        if (beforeSeparator < 0)
            beforeSeparator = 0;
        else
            beforeSeparator = before;
        if (afterSeparator < 0)
            afterSeparator = 0;
        else
            afterSeparator = after;
        
    }
    /**
     * Funktion überschreibt die Methode insertString von PlaintDocument
     * @param int offset: Position
     * @param String str: der String
     * @param AttributeSet attr: Attributset
     */
    public void insertString(int offset, String str, AttributeSet attr)
    throws BadLocationException {
        String subBefore = field.getText().substring(0,offset);
        String subAfter = field.getText().substring(offset,field.getText().length());
        String complete = subBefore+str+subAfter;
        
        //String complete2 = ""+Double.parseDouble(complete);
        
        //separator eingeben, bislang noch kein Separator vorhanden
        if((str.charAt(0) == this.separator) &&(complete.indexOf(this.separator)==-1)){
            String complete2 = ""+Double.parseDouble(complete);
        
        }
        
        
        
        
        
        
        
        
        
        
        
        
        
        if (str == null) return;
        //Zeichen ist kein Digit
        
        if (!Character.isDigit(str.charAt(str.length()-1))){
            //Zeichen ist kein separator
            if(str.charAt(str.length()-1) != this.separator){
                return;
            }
            if(str.charAt(str.length()-1) == this.separator){
                //nur ein separator erlaubt
                if(field.getText().indexOf(this.separator)!= -1){
                    return;
                }
                //Bis jetzt nur ein Separator Zeichen...
                format(offset,attr,str);
                
                
            }
        }
        //einzufügendes Zeichen ist eine Ziffer
        else{
            //bis jetzt kein Separator
            if(field.getText().indexOf(this.separator)== -1){
                
                if(complete.length()> this.beforeSeparator){
                    int caret = field.getCaretPosition();
                    if(caret == complete.length()-1){
                        super.insertString(offset,this.separator+str,attr);
                        return;
                    }
                    System.out.println(caret+", "+complete.length());
                    String toInsert = complete.substring(0,caret)+str+complete.substring(caret+2,complete.length());
                    super.replace(0,complete.length()-1,"",attr);
                    super.insertString(0,toInsert,attr);
                    if(caret< this.beforeSeparator)
                        field.setCaretPosition(caret+1);
                    
                }
                else{
                    if((Integer.parseInt(str)==0) &&(offset==0)){
                        super.insertString(offset,str+this.separator,attr);
                        return;
                    }
                    else{
                        super.insertString(offset,str,attr);
                        return;
                    }
                    
                }
                
            }
            //Sep vorhanden
            else{
                System.out.println("insert digigt, sep vorhanden");
                format(offset,attr,str);
            }
            
        }
        
        
        
    }
    
    private void format(int offset,AttributeSet attr,String str)throws BadLocationException{
        String complete = field.getText().substring(0,offset)+str+field.getText().substring(offset,field.getText().length());
        int sepIndex = complete.indexOf(this.separator);
        String subBefore = complete.substring(0,sepIndex);
        String subAfter = complete.substring(sepIndex+1,complete.length());
        System.out.println("complete:= "+complete+", before:= "+subBefore+", after:= "+subAfter);
        if(sepIndex ==0){
            System.out.println("1");
            if(subAfter.length()> this.afterSeparator){
                String toInsert = "0"+str+subAfter.substring(0,this.afterSeparator);
                int caret = field.getCaretPosition();
                super.replace(0,complete.length()-1,"",attr );
                super.insertString(0,toInsert,attr);
                if(caret< this.beforeSeparator)
                    field.setCaretPosition(caret+1);
                return;
            }
            else{
                String toInsert = "0"+str;
                super.insertString(offset,toInsert, attr);
                return;
            }
            
        }
        else if((subBefore.length() <= this.beforeSeparator) && (subAfter.length() <= this.afterSeparator)){
            System.out.println("2");
            int caret = field.getCaretPosition();
            if(complete.indexOf(this.separator)== complete.length()-1){
                System.out.println("15");
                
                super.insertString(offset,str+"0", attr);
                field.setCaretPosition(caret+1);
                return;
                
            }
            int count = 0;
            while (complete.indexOf("0")==0){
                complete= complete.substring(1,complete.length());
                count++;
            }
            //super.replace(0,complete.length()-1,"",attr );
            super.replace(0,complete.length()-1,"",attr );
            super.insertString(0,complete, attr);
            field.setCaretPosition(caret-count);
            return;
        }
        else if((subBefore.length() <= this.beforeSeparator) && (subAfter.length() > this.afterSeparator)){
            int caret = field.getCaretPosition();
            if(caret == complete.length()-1) return;
            else if(caret == complete.length()-2){
                String toInsert = complete.substring(0,caret)+str;
                super.replace(0,complete.length()-1,"",attr );
                super.insertString(0,toInsert,attr);
                return;
            }
            else{
                String toInsert = complete.substring(0,caret)+str+complete.substring(caret+2,complete.length());
                super.replace(0,complete.length()-1,"",attr );
                super.insertString(0,toInsert,attr);
                field.setCaretPosition(caret+1);
                
            }
        }
        else if((subBefore.length() > this.beforeSeparator) && (subAfter.length() <= this.afterSeparator)){
            System.out.println("4");
            int caret = field.getCaretPosition();
            System.out.println("caret:=" +caret+" sepIndex = "+sepIndex);
            if(caret == sepIndex-1){
                String toInsert= subBefore.substring(0,subBefore.length()-1) +separator + str+subAfter.substring(1,subAfter.length());
                super.replace(0,complete.length()-1,"",attr );
                super.insertString(0,toInsert,attr);
                field.setCaretPosition(caret+2);
                return;
            }
            else{
                String toInsert= complete.substring(0,caret)+ str+complete.substring(caret+2,complete.length());
                if(toInsert.startsWith("0")){
                    toInsert= toInsert.substring(1,toInsert.length());
                }
                super.replace(0,complete.length()-1,"",attr );
                super.insertString(0,toInsert,attr);
                field.setCaretPosition(caret+1);
                return;
            }
        }
        
    }
    
    public void keyPressed(java.awt.event.KeyEvent e) {
        
    }
    
    public void keyReleased(java.awt.event.KeyEvent e) {
        System.out.println("key released:= "+e.getKeyCode());
        if((e.getKeyCode() == KeyEvent.VK_BACK_SPACE) ||(e.getKeyCode()== KeyEvent.VK_DELETE)){
            try {
                checkText();
                
            } catch(BadLocationException ble) {
            }
        }
    }
    
    public void keyTyped(java.awt.event.KeyEvent e) {
    }
    private void checkText() throws BadLocationException{
        int caret = field.getCaretPosition();
        String text = field.getText();
        String toInsert = String.valueOf(Double.parseDouble(text));
        if(toInsert.lastIndexOf("0")== toInsert.length()-1){
            toInsert = toInsert.substring(0,toInsert.length()-2);
        }
        System.out.println(toInsert);
        super.replace(0,text.length(),"",null);
        super.insertString(0,toInsert,null);
        field.setCaretPosition(caret);
        return;
    }
    
    
    
    
    
}
 
Hi das sieht ziemlich kompliziert aus was du da versuchst.

So funktioniert es ganz gut:
Java:
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.util.Locale;

import javax.swing.JFrame;
import javax.swing.JTextField;

public class TestClass extends JFrame {

	public TestClass() {
		super( );
		init( );
	}

	/**
	 * 
	 */
	private void init() {
		this.setSize(500, 500);
		final JTextField field = new JTextField( );
		field.setMinimumSize(new Dimension(200, 50));
		field.setColumns(50);

		final NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
		final DecimalFormatSymbols symbols = DecimalFormatSymbols
				.getInstance(Locale.GERMAN);
		nf.setMaximumIntegerDigits(2);
		nf.setMaximumFractionDigits(2);

		field.addKeyListener(new KeyListener( ) {

			String validText = "";

			@Override
			public void keyPressed(KeyEvent event) {
			}

			@Override
			public void keyReleased(KeyEvent event) {
				String text = field.getText( );
				ParsePosition p = new ParsePosition(0);
				nf.parse(text, p);
				boolean valid = false;
				// check if everything was parsed
				if (p.getIndex( ) == text.length( )) {
					// get the index of the decimal separator
					int index = text.indexOf(String.valueOf(symbols
							.getDecimalSeparator( )));
					if (index != -1) {
						// split at separator in two parts
						String before = text.substring(0, index);
						String after = text.substring(index + 1);
						// check if length is not exceeded
						if (before.length( ) <= nf.getMaximumIntegerDigits( )
								&& after.length( ) <= nf
										.getMaximumFractionDigits( )) {
							valid = true;
						}

					}
					// only integer till here
					// check if the length of the non fractional part
					// is not exceeded
					else if (text.length( ) <= nf.getMaximumIntegerDigits( )) {
						valid = true;
					}

				}
				// set as valid text
				if (valid) {
					validText = text;
				}
				// reset to last known valid text
				else {
					field.setText(validText);
				}
			}

			@Override
			public void keyTyped(KeyEvent event) {

			}

		});
		field.setSize(200, 50);
		this.getContentPane( ).setLayout(new FlowLayout( ));
		this.getContentPane( ).add(field);
	}

	public static void main(String[] args) {
		new TestClass( ).setVisible(true);
	}

}
 
Zurück