Showing posts with label java. Show all posts
Restrict a java text field length
There are many different way to do this. You might write your own once you figure out what has to be done exactly. But I came up with this. Additionally I wanted the input to be numeric as well. So below is what I came up with.private class NumericAndLengthFilter extends DocumentFilter { /** * Number of characters allowed. */ private int length = 0; /** * Restricts the number of charcacters can be entered by given length. * @param length Number of characters allowed. */ public NumericAndLengthFilter(int length) { this.length = length; } @Override public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException { if (isNumeric(string)) { if (this.length> 0 && fb.getDocument().getLength() + string. length() > this.length) { return; } super.insertString(fb, offset, string, attr); } } @Override public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { if (isNumeric(text)) { if (this.length> 0 && fb.getDocument().getLength() + text. length() > this.length) { return; } super.insertString(fb, offset, text, attrs); } } /** * This method tests whether given text can be represented as number. * This method can be enhanced further for specific needs. * @param text Input text. * @return {@code true} if given string can be converted to number; otherwise returns {@code false}. */ private boolean isNumeric(String text) { if (text == null || text.trim().equals("")) { return false; } for (int iCount = 0; iCount < text.length(); iCount++) { if (!Character.isDigit(text.charAt(iCount))) { return false; } } return true; } } }
Restricting a Java Text field to just a range of integers
This time I came across a slightly different way than extending the documentfilter. That is I will write my own plain document here.class IntegerRangeDocument extends PlainDocument { int minimum, maximum; int currentValue = 0; public IntegerRangeDocument(int minimum, int maximum) { this.minimum = minimum; this.maximum = maximum; } public int getValue() { return currentValue; } public void insertString(int offset, String string, AttributeSet attributes) throws BadLocationException { if (string == null) { return; } else { String newValue; int length = getLength(); if (length == 0) { newValue = string; } else { String currentContent = getText(0, length); StringBuffer currentBuffer = new StringBuffer(currentContent); currentBuffer.insert(offset, string); newValue = currentBuffer.toString(); } try { currentValue = checkInput(newValue); super.insertString(offset, string, attributes); } catch (Exception exception) { Toolkit.getDefaultToolkit().beep(); } } } public void remove(int offset, int length) throws BadLocationException { int currentLength = getLength(); String currentContent = getText(0, currentLength); String before = currentContent.substring(0, offset); String after = currentContent.substring(length + offset, currentLength); String newValue = before + after; try { currentValue = checkInput(newValue); super.remove(offset, length); } catch (Exception exception) { Toolkit.getDefaultToolkit().beep(); } } public int checkInput(String proposedValue) throws NumberFormatException { int newValue = 0; if (proposedValue.length()> 0) { newValue = Integer.parseInt(proposedValue); } if ((minimum <= newValue) && (newValue <= maximum)) { return newValue; } else { throw new NumberFormatException(); } } }Now you can attach your text field with this plain document as below to achieve our requirement.
Document rangeOne = new IntegerRangeDocument(0, 255); JTextField textFieldOne = new JTextField(); textFieldOne.setDocument(rangeOne);
Restricting a Java Text field to alphabet
This is slightly opposite to what we have seen in one of the previous postsPlease use the below DocumentFilter for the same.
class MyDocFilter extends DocumentFilter { private static final String REMOVE_REGEX = "\\d"; private boolean filter = true; public boolean isFilter() { return filter; } public void setFilter(boolean filter) { this.filter = filter; } @Override public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException { if (filter) { text = text.replaceAll(REMOVE_REGEX, ""); } super.insertString(fb, offset, text, attr); } @Override public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { if (filter) { text = text.replaceAll(REMOVE_REGEX, ""); } super.replace(fb, offset, length, text, attrs); } }
Restricting a Java Text field to Integers
I have read a lot for this and the best way I found to do this is by extending the DocumentFilter class and using this new DocumentFilterclass MyIntFilter extends DocumentFilter { @Override public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException { Document doc = fb.getDocument(); StringBuilder sb = new StringBuilder(); sb.append(doc.getText(0, doc.getLength())); sb.insert(offset, string); if (test(sb.toString())) { super.insertString(fb, offset, string, attr); } else { // warn the user and don't allow the insert } } private boolean test(String text) { try { Integer.parseInt(text); return true; } catch (NumberFormatException e) { return false; } } @Override public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { Document doc = fb.getDocument(); StringBuilder sb = new StringBuilder(); sb.append(doc.getText(0, doc.getLength())); sb.replace(offset, offset + length, text); if (test(sb.toString())) { super.replace(fb, offset, length, text, attrs); } else { // warn the user and don't allow the insert } } @Override public void remove(FilterBypass fb, int offset, int length) throws BadLocationException { Document doc = fb.getDocument(); StringBuilder sb = new StringBuilder(); sb.append(doc.getText(0, doc.getLength())); sb.delete(offset, offset + length); if (test(sb.toString())) { super.remove(fb, offset, length); } else { // warn the user and don't allow the insert } } }Now after this use this filter with your JtextField like below:
PlainDocument doc = (PlainDocument) textField.getDocument(); doc.setDocumentFilter(new MyIntFilter());
A new addition to this blog - Java
I recently started working on Java and so from now on I would like to share all the interesting things that I have come across about this beautiful programming language. So I am starting a new tag by name JAVA in this blog which will direct all the posts related to java. Happy coding to myself and all.Difference between Java and c++
- C++ supports pointers whereas Java does not support pointers. But when many programmers questioned how you can work without pointers, the promoters began saying "Restricted pointers.” So we can say java supports Restricted pointers.
- At compilation time Java Source code converts into byte code .The interpreter execute this byte code at run time and gives output .Java is interpreted for the most part and hence platform independent. C++ run and compile using compiler which converts source code into machine level languages so c++ is plate from dependents
- Java is platform independent language but c++ is depends upon operating system machine etc. C++ source can be platform independent (and can work on a lot more, especially embedeed, platforms), although the generated objects are generally platofrom dependent but there is clang for
llvm
which doesn't have this restriction. - Java uses compiler and interpreter both and in c++ their is only compiler
- C++ supports operator overloading multiple inheritance but java does not.
- C++ is more nearer to hardware then Java
- Everything (except fundamental types) is an object in Java (Single root hierarchy as everything gets derived from
java.lang.Object
). - Java does is a similar to C++ but not have all the complicated aspects of C++ (ex: Pointers, templates, unions, operator overloading, structures etc..) Java does not support conditional compile (
#ifdef/#ifndef
type). - Thread support is built-in Java but not in C++. C++11, the most recent iteration of the C++ programming language does have Thread support though.
- Internet support is built-in Java but not in C++. However c++ has support for socket programming which can be used.
- Java does not support header file, include library files just like C++ .Java use import to include different Classes and methods.
- Java does not support default arguments like C++.
- There is no scope resolution operator
::
in Java. It has.
using which we can qualify classes with the namespace they came from. - There is no
goto
statement in Java. - Exception and Auto Garbage Collector handling in Java is different because there are no destructors into Java.
- Java has method overloading, but no operator overloading just like c++.
- The String class does use the + and += operators to concatenate strings and String expressions use automatic type conversion,
- Java is pass-by-value.
- Java does not support unsigned integer.
Subscribe to:
Posts (Atom)