I need to make the vaadin 14 textfield which can accept only numbers.The criterias for the textfield are as follows
1.The textfield must only accept numbers nothing else as I want to use that textfield as a mobile number field.
2.validate in such a way that if users tries to enter the alphabets nothing must be reflected in the textfield.Only numbers must be allowed to be entered in the textfield.
3.Any warning or errors must not be shown in the UI as we are specially making textfield for the mobile number.
Things I have tried is binders but that allows to enter the alphabets later on after the focus lost event they validate and provide the error message I dont want that behaviour.
Also tried vaadin number field but that allows character 'e'
Just simple and straight forward I am looking for the textfield which takes input only numbers.If user tries to input alphabets nothing must be reflected in the textfield.
Server-side
There are number of options you can do, the first one is the server side validator already mentioned in the answer by Alim Ă–zdemir:
binder.forField(textFieldForNumber)
.withValidator(new RegexpValidator("Only 1-9 allowed","\\d*"))
.bind(YourEntity::getNo, YourEntity::setNo);
Client-side
There is also possibility do the same checking and input filtering on client side using textField.setPattern(..) method, e.g.:
textFieldForNumber.setPattern("\\d*");
Furthermore it is possible to prevent input not matching the pattern alltogether by
textFieldForNumber.setPreventInvalidInput(true);
Alternate widget: NumberField
Third alternative is to use the NumberField component.
You could do a validation on the field with the binder like
binder.forField(textFieldForNumber)
.withValidator(new RegexpValidator("Only 1-9 allowed","\\d*"))
.bind(YourEntity::getNo, YourEntity::setNo);
I found the solution for my answer I extracted the source code for the Integer text field In Vaadin new beta version
The code goes as follows
#Tag("vaadin-integer-field")
#HtmlImport("frontend://bower_components/vaadin-text-field/src/vaadin-integer-field.html")
#JsModule("#vaadin/vaadin-text-field/src/vaadin-integer-field.js")
public class BigIntegerField extends AbstractNumberField<BigIntegerField, BigInteger> {
private static final SerializableFunction<String, BigInteger> PARSER = valueFormClient -> {
if (valueFormClient == null || valueFormClient.isEmpty()) {
return null;
}
try {
return new BigInteger(valueFormClient);
} catch (NumberFormatException e) {
return null;
}
};
private static final SerializableFunction<BigInteger, String> FORMATTER = valueFromModel -> valueFromModel == null
? ""
: valueFromModel.toString();
/**
* Constructs an empty {#code IntegerField}.
*/
public BigIntegerField() {
super(PARSER, FORMATTER, Double.MIN_VALUE, Double.MAX_VALUE);
// super(PARSER, FORMATTER, new BigInteger(String.valueOf(Integer.MIN_VALUE)), new BigInteger(String.valueOf(Integer.MAX_VALUE)));
}
/**
* Constructs an empty {#code IntegerField} with the given label.
*
* #param label
* the text to set as the label
*/
public BigIntegerField(String label) {
this();
setLabel(label);
}
/**
* Constructs an empty {#code IntegerField} with the given label and
* placeholder text.
*
* #param label
* the text to set as the label
* #param placeholder
* the placeholder text to set
*/
public BigIntegerField(String label, String placeholder) {
this(label);
setPlaceholder(placeholder);
}
/**
* Constructs an empty {#code IntegerField} with a value change listener.
*
* #param listener
* the value change listener
*
* #see #addValueChangeListener(ValueChangeListener)
*/
public BigIntegerField(
ValueChangeListener<? super ComponentValueChangeEvent<BigIntegerField, BigInteger>> listener) {
this();
addValueChangeListener(listener);
}
/**
* Constructs an empty {#code IntegerField} with a value change listener and
* a label.
*
* #param label
* the text to set as the label
* #param listener
* the value change listener
*
* #see #setLabel(String)
* #see #addValueChangeListener(ValueChangeListener)
*/
public BigIntegerField(String label,
ValueChangeListener<? super ComponentValueChangeEvent<BigIntegerField, BigInteger>> listener) {
this(label);
addValueChangeListener(listener);
}
/**
* Constructs a {#code IntegerField} with a value change listener, a label
* and an initial value.
*
* #param label
* the text to set as the label
* #param initialValue
* the initial value
* #param listener
* the value change listener
*
* #see #setLabel(String)
* #see #setValue(Object)
* #see #addValueChangeListener(ValueChangeListener)
*/
public BigIntegerField(String label, BigInteger initialValue,
ValueChangeListener<? super ComponentValueChangeEvent<BigIntegerField, BigInteger>> listener) {
this(label);
setValue(initialValue);
addValueChangeListener(listener);
}
/**
* Sets the minimum value of the field. Entering a value which is smaller
* than {#code min} invalidates the field.
*
* #param min
* the min value to set
*/
public void setMin(int min) {
super.setMin(min);
}
/**
* Gets the minimum allowed value of the field.
*
* #return the min property of the field
* #see #setMin(int)
*/
public int getMin() {
return (int) getMinDouble();
}
/**
* Sets the maximum value of the field. Entering a value which is greater
* than {#code max} invalidates the field.
*
* #param max
* the max value to set
*/
public void setMax(int max) {
super.setMax(max);
}
/**
* Gets the maximum allowed value of the field.
*
* #return the max property of the field
* #see #setMax(int)
*/
public int getMax() {
return (int) getMaxDouble();
}
/**
* Sets the allowed number intervals of the field. This specifies how much
* the value will be increased/decreased when clicking on the
* {#link #setHasControls(boolean) control buttons}. It is also used to
* invalidate the field, if the value doesn't align with the specified step
* and {#link #setMin(int) min} (if specified by user).
*
* #param step
* the new step to set
* #throws IllegalArgumentException
* if the argument is less or equal to zero.
*/
public void setStep(int step) {
if (step <= 0) {
throw new IllegalArgumentException("The step cannot be less or equal to zero.");
}
super.setStep(step);
}
/**
* Gets the allowed number intervals of the field.
*
* #return the step property of the field
* #see #setStep(int)
*/
public int getStep() {
return (int) getStepDouble();
}
}
This Actually solved my problem regarding the Mobile number inputs.
Related
I am making a text editor, And i want to make it when the user type a article then if the user select a specific word then change it's color the color will be changed and also if the user select the same word but in another place this word's color only will be changed
As indicated in this picture:
because of all of my search results was that i change only a word's color even if it repeated it will be also colored
I am trying in JtextPane, I have searched in "Oracle Java Docs" for the JtextPane methodes but i didn't found anything
It is necessary to use JTextPane.
Just use new FindManager(yourTextPane, Color.RED);.
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import java.awt.Color;
import java.util.ArrayList;
/**
* #author Swimer
*/
public class FindManager {
/**
* Constructor
* #param pane Swing text pane
* #param selection The color to apply to characters similar to selection
*/
public FindManager(JTextPane pane, Color selection) {
Style selected = pane.getStyledDocument().addStyle("selection-text", null);
Style defaultStyle = pane.getStyledDocument().addStyle("default", null);
StyleConstants.setForeground(selected, selection);
pane.addCaretListener(e -> {
Runnable doHighlight = () -> {
try {
String selectedText = pane.getSelectedText();
String text = pane.getStyledDocument().getText(0, pane.getStyledDocument().getLength());
if (selectedText != null && selectedText.length() > 0) {
for (Integer string : getStrings(text, selectedText, pane.getSelectionStart())) {
pane.getStyledDocument().setCharacterAttributes(string, selectedText.length(), selected, true);
}
}else{
pane.getStyledDocument().setCharacterAttributes(0, text.length(), defaultStyle, true);
}
} catch (Exception exception) {
exception.printStackTrace();
}
};
SwingUtilities.invokeLater(doHighlight);
});
}
/**
* Get positions of similar words
* #param text The string to look for
* #param toFind What to look for
* #param ignore What to ignore
* #return List of similar word positions
*/
public static ArrayList<Integer> getStrings(String text, String toFind, int ignore){
ArrayList<Integer> out = new ArrayList<>();
int index = text.indexOf(toFind);
while (index >= 0 && index != ignore) {
out.add(index);
index = text.indexOf(toFind, index+toFind.length());
}
return out;
}
}
My goal is to make anyGivenWord in a JTextArea "actionable". For example, when you hover the mouse over anyGivenWord, a tooltip appears, but not when you hover the mouse over any other word in the JTextArea. Since you can't do this directly to my knowledge, I was thinking of placing a component over where every anyGivenWord appears in the JTextArea, and have it re-position itself when the JTextArea's size changes, so that clicking on what appears to be anyGivenWord is actually clicking on the component(resulting in some listener being triggered). To do this, I would need to know at what point(x,y) that word occurs, so I can place the component at that point.
I was thinking I could search through the JTextArea and select instances of anyGivenWord, and then getSelectionStart() and getSelectionEnd(), but I think the int those methods return is the index of the first/last letter selected, as in, its position in the string returned by getText(). What I need is the x/y coordinates. Is this possible?
If not...any suggestions for more elegant ways to do what I'm trying to do?
You can use any JTextComponent and with a few methods (provided below) you can gather several different items from your text like:
The Character located under the current mouse pointer location;
The Word located under the current mouse pointer location;
The Selected Text located under the current mouse pointer location
(if selected);
The Highlighted Text located under the current mouse pointer location
(if you're into highlighting within the text as well);
Is the text under mouse pointer Selected?;
Is the text under mouse pointer Highlighted?.
As #camickr has already so generously pointed out, the key here is the use of the JTextComponent.viewToModel() method (I believe all Swing Text components contain this method) in order to acquire the text index location in relation to where the current mouse pointer is located within the component.
Here are some methods to play with:
/**
* This method will return either boolean true or false if the text contained
* under the current mouse pointer location within a JTextComponent is Selected
* or not. If the text under the mouse is found to be Selected then boolean
* true is returned. If the text under the mouse pointer is NOT found to be
* Selected then boolean false is returned.<br><br>
*
* This method is not to be confused with the getHighlightedUnderMouse() method.
* Highlighted text and Selected text are two completely different things.
* Highlighted Text can be text which is Highlighted (generally with a specific
* color) and can be in many different locations throughout the entire document
* whereas Selected Text is generally done by dragging the mouse over a document
* location while holding the left mouse button making the text SELECTED.<br><br>
*
* This method is generally run within a JTextComponent MouseMove Event but can be
* run from any JTextComponent Mouse event which will provide the current mouse
* coordinates within the supplied JTextComponent Object.
*
* #param textComp (JTextComponent) The JTextComponent object to work on. This
* can be the component variable name for either a JTextField, JTextArea,
* JFormattedField, JPasswordField, JTextPane, and JEditorPane.<br>
*
* #param textAreaMouseXLocation (Integer) The current X Location of the mouse
* pointer. This value can be acquired from the JTextComponent's MouseMove event like
* this <code>int x = evt.getX();</code> where evt is the <b>java.awt.event.MouseEvent</b>
* parameter variable.<br>
*
* #param textAreaMouseYLocation (Integer) The current Y Location of the mouse
* pointer. This value can be acquired from the JTextComponent's MouseMove event like
* this <code>int y = evt.getY();</code> where evt is the <b>java.awt.event.MouseEvent</b>
* parameter variable.<br>
*
* #return (Boolean) True if the text under the current mouse pointer location
* within the supplied JTextComponent is Selected and false if it is not.
*/
public static boolean isSelectededUnderMouse(JTextComponent textComp, int textAreaMouseXLocation,
int textAreaMouseYLocation) {
boolean isSelected = false;
if (textComp.getText().isEmpty()) { return false; }
Point pt = new Point(textAreaMouseXLocation, textAreaMouseYLocation);
int pos = textComp.viewToModel(pt);
int start = textComp.getSelectionStart();
int end = textComp.getSelectionEnd();
if (pos >= start && pos <= end) {
isSelected = true;
}
return isSelected;
}
/**
* This method will return either boolean true or false if the text contained
* under the current mouse pointer location within a JTextComponent is Highlighted
* or not. If the text under the mouse is found to be Highlighted then boolean
* true is returned. If the text under the mouse pointer is not found to be
* highlighted then boolean false is returned.<br><br>
*
* This method is not to be confused with the getSelectedUnderMouse() method.
* Highlighted text and Selected text are two completely different things.
* Highlighted Text can be text which is Highlighted (generally with a specific
* color) and can be in many different locations throughout the entire document
* whereas Selected Text is generally done by dragging the mouse over a document
* location while holding the left mouse button making the text SELECTED.<br><br>
*
* This method is generally run within a JTextComponent's MouseMove Event but can be
* run from any JTextComponent's Mouse event which will provide the current mouse
* coordinates within the supplied JTextArea Object.
*
* #param textComp (JTextComponent) The JTextComponent object to work on. This
* can be the component variable name for either a JTextField, JTextArea,
* JFormattedField, JPasswordField, JTextPane, and JEditorPane.<br>
*
* #param textAreaMouseXLocation (Integer) The current X Location of the mouse
* pointer. This value can be acquired from the JTextComponent's MouseMove event like
* this <code>int x = evt.getX();</code> where evt is the <b>java.awt.event.MouseEvent</b>
* parameter variable.<br>
*
* #param textAreaMouseYLocation (Integer) The current Y Location of the mouse
* pointer. This value can be acquired from the JTextComponent's MouseMove event like
* this <code>int y = evt.getY();</code> where evt is the <b>java.awt.event.MouseEvent</b>
* parameter variable.<br>
*
* #return (Boolean) True if the text under the current mouse pointer location
* within the supplied JTextComponent is Highlighted and false if it is not.
*/
public static boolean isHighlightededUnderMouse(JTextComponent textComp, int textAreaMouseXLocation,
int textAreaMouseYLocation) {
boolean isHighlighted = false;
if (textComp.getText().isEmpty()) { return false; }
Point pt = new Point(textAreaMouseXLocation, textAreaMouseYLocation);
int pos = textComp.viewToModel(pt);
Highlighter.Highlight[] allHighlights = textComp.getHighlighter().getHighlights();
String strg = "";
for (int i = 0; i < allHighlights.length; i++) {
int start = (int)allHighlights[i].getStartOffset();
int end = (int)allHighlights[i].getEndOffset();
if (pos >= start && pos <= end) {
isHighlighted = true;
break;
}
}
return isHighlighted;
}
/**
* This method will return the "Selected" text contained under the mouse pointer
* location within a JTextComonent.<br><br>
*
* This method is not to be confused with the getHighlightedUnderMouse() method.
* Highlighted text and Selected text are two completely different things.
* Highlighted Text can be text which is Highlighted (generally with a specific
* color) and can be in many different locations throughout the entire document
* whereas Selected Text is generally done by dragging the mouse over a document
* location while holding the left mouse button making the text SELECTED.<br><br>
*
* This method is generally run within a Text Component's MouseMove Event but can be
* run from any Text Component's Mouse event which will provide the current mouse
* coordinates within the supplied Text Component Object.
*
* #param textComp (JTextComponent) The JTextComponent object to work on. This
* can be the component variable name for either a JTextField, JTextArea,
* JFormattedField, JPasswordField, JTextPane, and JEditorPane.<br>
*
* #param textAreaMouseXLocation (Integer) The current X Location of the mouse
* pointer. This value can be acquired from the Text Component's MouseMove event like
* this <code>int x = evt.getX();</code> where evt is the <b>java.awt.event.MouseEvent</b>
* parameter variable.<br>
*
* #param textAreaMouseYLocation (Integer) The current Y Location of the mouse
* pointer. This value can be acquired from the Text Component's MouseMove event like
* this <code>int y = evt.getY();</code> where evt is the <b>java.awt.event.MouseEvent</b>
* parameter variable.<br>
*
* #return (String) The current selected string located under the current mouse
* location.
*/
public static String getSelectededUnderMouse(JTextComponent textComp, int textAreaMouseXLocation,
int textAreaMouseYLocation) {
String selectedText = "";
if (textComp.getText().isEmpty()) { return selectedText; }
Point pt = new Point(textAreaMouseXLocation, textAreaMouseYLocation);
int pos = textComp.viewToModel(pt);
int start = textComp.getSelectionStart();
int end = textComp.getSelectionEnd();
int selectedLength = (end - start);
if (pos >= start && pos <= end) {
try {
selectedText = textComp.getText(start, selectedLength);
}
catch (BadLocationException ex) {
// Ignore!!!
}
}
return selectedText;
}
/**
* This method will return the "Highlighted" text contained under the mouse pointer
* location within a JTextComponent.<br><br>
*
* This method is not to be confused with the getSelectedUnderMouse() method.
* Highlighted text and Selected text are two completely different things.
* Highlighted Text can be text which is Highlighted (generally with a specific
* color) and can be in many different locations throughout the entire document
* whereas Selected Text is generally done by dragging the mouse over a document
* location while holding the left mouse button making the text SELECTED.<br><br>
*
* This method is generally run within a JTextComponent MouseMove Event but can be
* run from any JTextComponent Mouse event which will provide the current mouse
* coordinates within the supplied JTextComponent Object.
*
* #param textComp (JTextComponent) The JTextComponent object to work on. This
* can be the component variable name for either a JTextField, JTextArea,
* JFormattedField, JPasswordField, JTextPane, and JEditorPane.<br>
*
* #param textAreaMouseXLocation (Integer) The current X Location of the mouse
* pointer. This value can be acquired from the JTextComponent's MouseMove event like
* this <code>int x = evt.getX();</code> where evt is the <b>java.awt.event.MouseEvent</b>
* parameter variable.<br>
*
* #param textAreaMouseYLocation (Integer) The current Y Location of the mouse
* pointer. This value can be acquired from the JTextComponent's MouseMove event like
* this <code>int y = evt.getY();</code> where evt is the <b>java.awt.event.MouseEvent</b>
* parameter variable.<br>
*
* #return (String) The current highlighted string located under the current mouse
* location.
*/
public static String getHighlightededUnderMouse(JTextComponent textComp, int textAreaMouseXLocation,
int textAreaMouseYLocation) {
if (textComp.getText().isEmpty()) { return ""; }
Point pnt = new Point(textAreaMouseXLocation, textAreaMouseYLocation);
int pos = textComp.viewToModel(pnt);
String highlightedText = "";
Highlighter.Highlight[] allHighlights = textComp.getHighlighter().getHighlights();
if (allHighlights.length > 0) {
for (int i = 0; i < allHighlights.length; i++) {
int start = (int)allHighlights[i].getStartOffset();
int end = (int)allHighlights[i].getEndOffset();
int hlStringLength = (end-start);
if (pos >= start && pos <= end) {
try {
highlightedText = textComp.getText(start, hlStringLength);
break;
}
catch (BadLocationException ex) {
// Ignore!!!
}
}
}
}
return highlightedText;
}
/**
* This method would normally be called within a JTextComponent's MouseMove Event.
*
* #param textComp (JTextComponent) The JTextComponent object to work on. This
* can be the component variable name for either a JTextField, JTextArea,
* JFormattedField, JPasswordField, JTextPane, and JEditorPane.<br>
*
* #param textAreaMouseXLocation (Integer) The current X Location of the mouse
* pointer. This value can be acquired from the JTextComponent's MouseMove event like
* this <code>int x = evt.getX();</code> where evt is the <b>java.awt.event.MouseEvent</b>
* parameter variable.<br>
*
* #param textAreaMouseYLocation (Integer) The current Y Location of the mouse
* pointer. This value can be acquired from the JTextComponent's MouseMove event like
* this <code>int y = evt.getY();</code> where evt is the <b>java.awt.event.MouseEvent</b>
* parameter variable.<br>
*
* #return (String) The current character located under the current mouse
* location.
*/
public static String getCharUnderMouse(JTextComponent textComp, int textAreaMouseXLocation,
int textAreaMouseYLocation) {
String character = "";
Point pt = new Point(textAreaMouseXLocation, textAreaMouseYLocation);
int pos = textComp.viewToModel(pt);
try {
character = textComp.getDocument().getText(pos, 1);
}
catch (BadLocationException ex) {
// Ignore!!
}
return character;
}
/**
* This method would normally be called within a JTextComponent's MouseMove Event.
*
* #param textComp (JTextArea) The JTextComponent object to work on. This
* can be the component variable name for either a JTextField, JTextArea,
* JFormattedField, JPasswordField, JTextPane, and JEditorPane.<br>
*
* #param textAreaMouseXLocation (Integer) The current X Location of the mouse
* pointer. This value can be acquired from the JTextComponent's MouseMove event like
* this <code>int x = evt.getX();</code> where evt is the <b>java.awt.event.MouseEvent</b>
* parameter variable.<br>
*
* #param textAreaMouseYLocation (Integer) The current Y Location of the mouse
* pointer. This value can be acquired from the JTextComponent's MouseMove event like
* this <code>int y = evt.getY();<code> where evt is the <b>java.awt.event.MouseEvent</b>
* parameter variable.<br>
*
* #return (String) The current Word located under the current mouse location.
*/
public static String getWordUnderMouse(JTextComponent textComp, int textAreaMouseXLocation,
int textAreaMouseYLocation) {
Point pt = new Point(textAreaMouseXLocation, textAreaMouseYLocation);
int pos = textComp.viewToModel(pt);
String word = "";
try {
Document doc = textComp.getDocument();
if( pos > 0 && (pos >= doc.getLength() || Character.isWhitespace( doc.getText( pos, 1 ).charAt( 0 ) )) ) {
// if the next character is a white space then use
// the word on the left side..
pos--;
}
// get the word from current position
final int begOffs = Utilities.getWordStart(textComp, pos);
final int endOffs = Utilities.getWordEnd(textComp, pos);
word = textComp.getText( begOffs, endOffs - begOffs );
}
catch( BadLocationException ex ) {
// Ignore this exception!!!
}
return word;
}
You can use a JEditorPane with HTML and add Hyperlinks to any given word. Read the section from the Swing tutorial on How to Use Editor Panes for the basics to get you started.
You can then add a HyperlinkListener to respond to events when the word is clicked. Read the JEditorPane API for an example of using a HyperlinkListener.
For example, when you hover the mouse over anyGivenWord, a tooltip appears,
If you don't want to use Hyperlinks then you could control the tooltip text by overriding the getToolTipText(...) method. This method receives the MouseEvent so you can get the mouse location. You can then use the viewToModel(...) method of the JTextArea to get the offset of the mouse into the Document. Then check out the Utilities. class which will help you get the start/end offsets of the word so you can use the getText(...) method to extract the word at the current mouse location.
I have the sample code below, and I'm having problems understanding it. So I'd like two ask 2 questions:
Why does JFormattedTextField have a "value" (getValue(), setValue()) and a JTextField does not?
In the propertyChange() method, why is it sufficient to write:
amount = ((Number)amountField.getValue()).doubleValue();
to update the amount so that it is displayed the right way, but for the paymentField I have to call the setValue() method?
Sample:
/*
* Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle or the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
import java.text.*;
/**
* FormattedTextFieldDemo.java requires no other files.
*
* It implements a mortgage calculator that uses four
* JFormattedTextFields.
*/
public class FormattedTextFieldDemo extends JPanel
implements PropertyChangeListener {
//Values for the fields
private double amount = 100000;
private double rate = 7.5; //7.5%
private int numPeriods = 30;
//Labels to identify the fields
private JLabel amountLabel;
private JLabel rateLabel;
private JLabel numPeriodsLabel;
private JLabel paymentLabel;
//Strings for the labels
private static String amountString = "Loan Amount: ";
private static String rateString = "APR (%): ";
private static String numPeriodsString = "Years: ";
private static String paymentString = "Monthly Payment: ";
//Fields for data entry
private JFormattedTextField amountField;
private JFormattedTextField rateField;
private JFormattedTextField numPeriodsField;
private JFormattedTextField paymentField;
//Formats to format and parse numbers
private NumberFormat amountFormat;
private NumberFormat percentFormat;
private NumberFormat paymentFormat;
public FormattedTextFieldDemo() {
super(new BorderLayout());
setUpFormats();
double payment = computePayment(amount,
rate,
numPeriods);
//Create the labels.
amountLabel = new JLabel(amountString);
rateLabel = new JLabel(rateString);
numPeriodsLabel = new JLabel(numPeriodsString);
paymentLabel = new JLabel(paymentString);
//Create the text fields and set them up.
amountField = new JFormattedTextField(amountFormat);
amountField.setValue(new Double(amount));
amountField.setColumns(10);
amountField.addPropertyChangeListener("value", this);
rateField = new JFormattedTextField(percentFormat);
rateField.setValue(new Double(rate));
rateField.setColumns(10);
rateField.addPropertyChangeListener("value", this);
numPeriodsField = new JFormattedTextField();
numPeriodsField.setValue(new Integer(numPeriods));
numPeriodsField.setColumns(10);
numPeriodsField.addPropertyChangeListener("value", this);
paymentField = new JFormattedTextField(paymentFormat);
paymentField.setValue(new Double(payment));
paymentField.setColumns(10);
paymentField.setEditable(false);
paymentField.setForeground(Color.red);
//Tell accessibility tools about label/textfield pairs.
amountLabel.setLabelFor(amountField);
rateLabel.setLabelFor(rateField);
numPeriodsLabel.setLabelFor(numPeriodsField);
paymentLabel.setLabelFor(paymentField);
//Lay out the labels in a panel.
JPanel labelPane = new JPanel(new GridLayout(0,1));
labelPane.add(amountLabel);
labelPane.add(rateLabel);
labelPane.add(numPeriodsLabel);
labelPane.add(paymentLabel);
//Layout the text fields in a panel.
JPanel fieldPane = new JPanel(new GridLayout(0,1));
fieldPane.add(amountField);
fieldPane.add(rateField);
fieldPane.add(numPeriodsField);
fieldPane.add(paymentField);
//Put the panels in this panel, labels on left,
//text fields on right.
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
add(labelPane, BorderLayout.CENTER);
add(fieldPane, BorderLayout.LINE_END);
}
/** Called when a field's "value" property changes. */
public void propertyChange(PropertyChangeEvent e) {
Object source = e.getSource();
if (source == amountField) {
amount = ((Number)amountField.getValue()).doubleValue();
} else if (source == rateField) {
rate = ((Number)rateField.getValue()).doubleValue();
} else if (source == numPeriodsField) {
numPeriods = ((Number)numPeriodsField.getValue()).intValue();
}
double payment = computePayment(amount, rate, numPeriods);
paymentField.setValue(new Double(payment));
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("FormattedTextFieldDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add contents to the window.
frame.add(new FormattedTextFieldDemo());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//Turn off metal's use of bold fonts
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}
});
}
//Compute the monthly payment based on the loan amount,
//APR, and length of loan.
double computePayment(double loanAmt, double rate, int numPeriods) {
double I, partial1, denominator, answer;
numPeriods *= 12; //get number of months
if (rate > 0.01) {
I = rate / 100.0 / 12.0; //get monthly rate from annual
partial1 = Math.pow((1 + I), (0.0 - numPeriods));
denominator = (1 - partial1) / I;
} else { //rate ~= 0
denominator = numPeriods;
}
answer = (-1 * loanAmt) / denominator;
return answer;
}
//Create and set up number formats. These objects also
//parse numbers input by user.
private void setUpFormats() {
amountFormat = NumberFormat.getNumberInstance();
percentFormat = NumberFormat.getNumberInstance();
percentFormat.setMinimumFractionDigits(3);
paymentFormat = NumberFormat.getCurrencyInstance();
}
}
"Why has a JFormattedTextField an "value" (getValue(), setValue()) and a jTextField not?"
The text attributes of both JTextField and JFormattedTextField are the actual text you see displayed by each. But JFormattedTextField isn't just displaying some text that you give it. It, with the help of a Formatter that you provided, translates between some Object--in this case a Number--and the convenient human-readable text representation you see on the screen. The object whose value you're displaying is the "value" of the JFormattedTextField, how it looks on the screen is the "text". A regular JTextField, on the other hand, just shows whatever text you tell it to show and returns whatever the you type into it, so there's no need for a separate value attribute because it would always be identical to the "text".
"Why is it sufficient to write "amount = ((Number)amountField.getValue()).doubleValue();" to update the amount so that is is displayed the right way but for the paymentField i have to call the setValue-Methode?"
You're not writing
amount = ((Number)amountField.getValue()).doubleValue();
to update amountField, you're doing it to find out what to user typed into amountField. amountField is updating itself in response to user input because that's what JFormattedTextFields do.
Now, having learned what the user typed into amountField, you recalculate the payment amount and tell the paymentField to show the new payment by calling its setValue method.
I'm wondering if you had any ideas about resizing an image in word doc, I'm using docx4j. I've got the image showing but it is too big and I've tried everything to resize it. I've tried compressing with ImageWriter/ImageWriteParam param and the method SaveAsJPEGTiles with not much luck. It either just doesn't show up in the word doc or it is still too large. I really need it to be .5"X.5". I never know what to put in for the width and height.
Thank you.
Use the cx parameter to set the width!
/**
* Create a <wp:inline> element suitable for this image,
* which can be _embedded_ in w:p/w:r/w:drawing.
* #param filenameHint Any text, for example the original filename
* #param altText Like HTML's alt text
* #param id1 An id unique in the document
* #param id2 Another id unique in the document
* #param cx Image width in twip
* #param link true if this is to be linked not embedded
* None of these things seem to be exposed in Word 2007's
* user interface, but Word won't open the document if
* any of the attributes these go in (except # desc) aren't present!
* #throws Exception
*/
public Inline createImageInline(String filenameHint, String altText,
int id1, int id2, long cx, boolean link) throws Exception
I am implementing a widget board for controlling numerous widgets (extending JComponents) which must implement several featrues: resizable, draggable, closeable etc...
Null (or absolute) layout came to my mind because all other native Layout managers do not support the desired features (dragging a component and placing it on a specific position). But as we all know, using absolute manager is not even not recommended, but also forbidden in Netbeans RCP. So I am trying to implement my own layout manager which would be as close to absolute layout as possible and provide some additional features.
Here is the code of my layout prototype
public class WidgetLayout implements LayoutManager, java.io.Serializable {
private boolean usePreferredSize;
/**
* Convenience constructor
*/
public WidgetLayout() {
this(true);
}
/**
* Create a DragLayout and indicate how the component size is determined.
*
* #param usePreferred size see setPreferredSize() for values.
*/
public WidgetLayout(boolean usePreferredSize) {
setUsePreferredSize(usePreferredSize);
}
/**
* Set the use preferred size property
*
* #param usePreferredSize when true, use the preferred size of the
* component in layout calculations. When false, use the size of the
* component, unless the size is 0, in which case use the preferred size as
* a default.
*/
public void setUsePreferredSize(boolean usePreferredSize) {
this.usePreferredSize = usePreferredSize;
}
/**
* Get the use Preferred Size property
*
* #return the use preferred size property
*/
public boolean isUsePreferredSize() {
return usePreferredSize;
}
/**
* Adds the specified component with the specified name to the layout.
*
* #param name the name of the component
* #param comp the component to be added
*/
#Override
public void addLayoutComponent(String name, Component comp) {
}
/**
* Removes the specified component from the layout.
*
* #param comp the component to be removed
*/
#Override
public void removeLayoutComponent(Component component) {
}
/**
* Determine the preferred size on the Container
*
* #param parent the container in which to do the layout
* #return the preferred dimensions to lay out the subcomponents of the
* specified container
*/
#Override
public Dimension preferredLayoutSize(Container parent) {
synchronized (parent.getTreeLock()) {
return getLayoutSize(parent);
}
}
/**
* Determine the minimum size on the Container
*
* #param target the container in which to do the layout
* #return the minimum dimensions needed to lay out the subcomponents of the
* specified container
*/
#Override
public Dimension minimumLayoutSize(Container parent) {
synchronized (parent.getTreeLock()) {
return preferredLayoutSize(parent);
}
}
/**
* Lays out the specified container using this layout.
*
* #param target the container in which to do the layout
*/
#Override
public void layoutContainer(Container parent) {
}
/*
* The calculation for minimum/preferred size is the same.
*
* #param parent the container in which to do the layout
*/
private Dimension getLayoutSize(Container parent) {
Insets parentInsets = parent.getInsets();
int x = parentInsets.left;
int y = parentInsets.top;
int width = 0;
int height = 0;
// Get extreme values of the components on the container.
// The x/y values represent the starting point relative to the
// top/left of the container. The width/height values represent
// the bottom/right value within the container.
for (Component component : parent.getComponents()) {
if (component.isVisible()) {
Point p = component.getLocation();
Dimension d = component.getSize();
x = Math.min(x, p.x);
y = Math.min(y, p.y);
width = Math.max(width, p.x + d.width);
height = Math.max(height, p.y + d.height);
}
}
Dimension d = new Dimension(width, height);
return d;
}
/**
* Returns the string representation of this column layout's values.
*
* #return a string representation of this layout
*/
#Override
public String toString() {
return "["
+ getClass().getName()
+ "]";
}
}
It sort of works, but I have a problem with other components in my RCP application that surrounds this one.
There is a JPanel with this layout inside a TopComponent. return parent.getParent().getParent().getSize(); ensures that this panel has the same size as the topComponent istself (it is the only component there, it works as a canvas or a board). But when I want to increase size of the Explorer, for example, I cant. I can only make the board with my layout bigger, but not smaller. I think I know the reason (the panel with my layout has set preferred size as high as possible) but I am not sure how to correct this. Any tips?
EDIT: what I need is for this layout to has the same size as the TopComponent but the TopComponent should have the ability to increase and decrease its size...
EDIT2: Problem solved. I based some of the functions on DragLayout and now it behaves as an AbsoluteLayout but does not move other components when its size changes (unless the whole component above it changes size) - see the code above.
Also, the trick is to place the component implementing this layout inside some layout which does not force newly created components on the middle of the container, so I put this one into a GridLayout(1, 1), which fill the whole component by default :-)
Solved - see question EDIT. I will leave the question here, perhaps someone could make use of it when implementing absolute layout-like layout manager...