How to get all packages from an Eclipse Plug-in? - eclipse

// Eclipse PDE 2022-09
// JDK17
// I get the ClassLoader of org.eclipse.swt
ClassLoader classLoader = ......
// Try to get all packages from it
Package packages[] = classLoader.getDefinedPackages() ;
for ( Package pkg : packages ) {
println( pkg ) ;
}
// But some packages are missing from the results, like "org.eclipse.swt.awt".
In this scenario, how can I get all the packages ?

This is my way getAllClassName( SWTBundle ) ;
public record Package( String packageName , List<String> classes , Bundle bundle ){
public Class<?> loadClass(String className) throws ClassNotFoundException {
if( !classes.contains(className) ) {
throw new ClassNotFoundException("not found " + className) ;
}
return bundle.loadClass( packageName + "." + className ) ;
}
#Override
public int hashCode() {
return Objects.hash(packageName);
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Package other = (Package) obj;
return Objects.equals(packageName, other.packageName);
}
}
public Stream<Package> getAllClassName(Bundle bundle) throws BundleException {
BundleWiring bundleWiring = bundle.adapt(BundleWiring.class) ;
if( bundleWiring == null ) {
throw new BundleException( "BundleWiring is null" ) ;
}
Collection<String> resources = bundleWiring.listResources("/", "*.class", BundleWiring.LISTRESOURCES_RECURSE);
List<Package> packageList = new ArrayList<>();
for (String resource : resources) {
String className = FilenameUtils.getBaseName( resource ) ;
String packageName = FilenameUtils.getPathNoEndSeparator( resource ).replace('/','.') ;
int index = packageList.indexOf(new Package(packageName,null,null)) ;
ArrayList<String> classes = null ;
if( index == -1 ) {
classes = new ArrayList<>() ;
packageList.add( new Package(packageName,classes,bundle) ) ;
}else {
classes = (ArrayList<String>)packageList.get(index).classes ;
}
classes.add( className ) ;
}
return packageList.stream().sorted( (a,b) -> a.packageName.compareTo(b.packageName) ) ;
}

Related

AutoCompleteTextField list does not always scroll to top?

The AutoCompleteTextField seems to work exactly as intended until I start backspacing in the TextField. I am not sure what the difference is, but if I type in something like "123 M" then I get values that start with "123 M". If I backspace and delete the M leaving "123 " in the field, the list changes, but it does not scroll to the top of the list.
I should note that everything works fine on the simulator and that I am experiencing this behavior when running a debug build on my iPhone.
EDIT: So this does not only seem to happen when backspacing. This image shows the results I have when typing in an address key by key. In any of the pictures where the list isn't viewable or is clipped, I am able to drag down on the list to get it to then display properly. I have not tried this on an Android device.
EDIT2:
public class CodenameOneTest {
private Form current;
private Resources theme;
private WaitingClass w;
private String[] properties = {"1 MAIN STREET", "123 E MAIN STREET", "12 EASTER ROAD", "24 MAIN STREET"};
public void init(Object context) {
theme = UIManager.initFirstTheme("/theme");
// Enable Toolbar on all Forms by default
Toolbar.setGlobalToolbar(true);
}
public void start() {
if(current != null) {
current.show();
return;
}
Form form = new Form("AutoCompleteTextField");
form.setLayout(new BorderLayout());
final DefaultListModel<String> options = new DefaultListModel<>();
AutoCompleteTextField ac = new AutoCompleteTextField(options) {
protected boolean filter(String text) {
if(text.length() == 0) {
options.removeAll();
return false;
}
String[] l = searchLocations(text);
if(l == null || l.length == 0) {
return false;
}
options.removeAll();
for(String s : l) {
options.addItem(s);
}
return true;
};
};
Container container = new Container(BoxLayout.y());
container.setScrollableY(true); // If you comment this out then the field works fine
container.add(ac);
form.addComponent(BorderLayout.CENTER, container);
form.show();
}
String[] searchLocations(String text) {
try {
if(text.length() > 0) {
if(w != null) {
w.actionPerformed(null);
}
w = new WaitingClass();
String[] properties = getProperties(text);
if(Display.getInstance().isEdt()) {
Display.getInstance().invokeAndBlock(w);
}
else {
w.run();
}
return properties;
}
}
catch(Exception e) {
Log.e(e);
}
return null;
}
private String[] getProperties(String text) {
List<String> returnList = new ArrayList<>();
List<String> propertyList = Arrays.asList(properties);
for(String property : propertyList) {
if(property.startsWith(text)) {
returnList.add(property);
}
}
w.actionPerformed(null);
return returnList.toArray(new String[returnList.size()]);
}
class WaitingClass implements Runnable, ActionListener<ActionEvent> {
private boolean finishedWaiting;
public void run() {
while(!finishedWaiting) {
try {
Thread.sleep(30);
}
catch(InterruptedException ex) {
ex.printStackTrace();
}
}
}
public void actionPerformed(ActionEvent e) {
finishedWaiting = true;
return;
}
}
public void stop() {
current = Display.getInstance().getCurrent();
if(current instanceof Dialog) {
((Dialog)current).dispose();
current = Display.getInstance().getCurrent();
}
}
public void destroy() {
}
}
I used this code on an iPhone 4s:
public void start() {
if(current != null){
current.show();
return;
}
Form hi = new Form("AutoComplete", new BorderLayout());
if(apiKey == null) {
hi.add(new SpanLabel("This demo requires a valid google API key to be set in the constant apiKey, "
+ "you can get this key for the webservice (not the native key) by following the instructions here: "
+ "https://developers.google.com/places/web-service/get-api-key"));
hi.getToolbar().addCommandToRightBar("Get Key", null, e -> Display.getInstance().execute("https://developers.google.com/places/web-service/get-api-key"));
hi.show();
return;
}
Container box = new Container(new BoxLayout(BoxLayout.Y_AXIS));
box.setScrollableY(true);
for(int iter = 0 ; iter < 30 ; iter++) {
box.add(createAutoComplete());
}
hi.add(BorderLayout.CENTER, box);
hi.show();
}
private AutoCompleteTextField createAutoComplete() {
final DefaultListModel<String> options = new DefaultListModel<>();
AutoCompleteTextField ac = new AutoCompleteTextField(options) {
#Override
protected boolean filter(String text) {
if(text.length() == 0) {
return false;
}
String[] l = searchLocations(text);
if(l == null || l.length == 0) {
return false;
}
options.removeAll();
for(String s : l) {
options.addItem(s);
}
return true;
}
};
ac.setMinimumElementsShownInPopup(5);
return ac;
}
String[] searchLocations(String text) {
try {
if(text.length() > 0) {
ConnectionRequest r = new ConnectionRequest();
r.setPost(false);
r.setUrl("https://maps.googleapis.com/maps/api/place/autocomplete/json");
r.addArgument("key", apiKey);
r.addArgument("input", text);
NetworkManager.getInstance().addToQueueAndWait(r);
Map<String,Object> result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(r.getResponseData()), "UTF-8"));
String[] res = Result.fromContent(result).getAsStringArray("//description");
return res;
}
} catch(Exception err) {
Log.e(err);
}
return null;
}
I was able to create this issue but not the issue you describe.

How to use antlr4 in Eclipse?

Since Antlr4 is new version of Antlr and this is the first time I use it. I have downloaded the Antlr4 plugin from eclipse marketplace.
I made new ANTLR 4 project and I got Hello.g4
Afterward I saw this small grammar:
/**
* Define a grammar called Hello
*/
grammar Hello;
r : 'hello' ID ; // match keyword hello followed by an identifier
ID : [a-z]+ ; // match lower-case identifiers
WS : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines
Once it was saved, It was build and I saw it from the Antlr console, I wanted to test the program but I didn't know how, and I didn't know how to make a new file that can be compiled by the new grammar?
Thanks in advance for any help.
You need to create an instance of the generated parser in order to run it.
Create a Java project J next to your ANTLR project A.
Create a linked folder in project J referencing the
generated-sources/antlr4 folder from A, and make this linked folder a source
folder. Compile errors should appear.
Add the antlr4 jar to the build path of project J. This should remove the compile errors.
Write a main program in J which creates an instance of the generated
parser and feeds it with text. You can take the TestRig from the
ANTLR documentation, pasted below for convenience.
The TestRig must be invoked by passing the grammar name (Hello, in your example) and the starting rule (r).
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.DefaultErrorStrategy;
import org.antlr.v4.runtime.DiagnosticErrorListener;
import org.antlr.v4.runtime.InputMismatchException;
import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.Parser;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.TokenStream;
import org.antlr.v4.runtime.atn.PredictionMode;
import javax.print.PrintException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/** Run a lexer/parser combo, optionally printing tree string or generating
* postscript file. Optionally taking input file.
*
* $ java org.antlr.v4.runtime.misc.TestRig GrammarName startRuleName
* [-tree]
* [-tokens] [-gui] [-ps file.ps]
* [-trace]
* [-diagnostics]
* [-SLL]
* [input-filename(s)]
*/
public class Test {
public static final String LEXER_START_RULE_NAME = "tokens";
protected String grammarName;
protected String startRuleName;
protected final List<String> inputFiles = new ArrayList<String>();
protected boolean printTree = false;
protected boolean gui = false;
protected String psFile = null;
protected boolean showTokens = false;
protected boolean trace = false;
protected boolean diagnostics = false;
protected String encoding = null;
protected boolean SLL = false;
public Test(String[] args) throws Exception {
if ( args.length < 2 ) {
System.err.println("java org.antlr.v4.runtime.misc.TestRig GrammarName startRuleName\n" +
" [-tokens] [-tree] [-gui] [-ps file.ps] [-encoding encodingname]\n" +
" [-trace] [-diagnostics] [-SLL]\n"+
" [input-filename(s)]");
System.err.println("Use startRuleName='tokens' if GrammarName is a lexer grammar.");
System.err.println("Omitting input-filename makes rig read from stdin.");
return;
}
int i=0;
grammarName = args[i];
i++;
startRuleName = args[i];
i++;
while ( i<args.length ) {
String arg = args[i];
i++;
if ( arg.charAt(0)!='-' ) { // input file name
inputFiles.add(arg);
continue;
}
if ( arg.equals("-tree") ) {
printTree = true;
}
if ( arg.equals("-gui") ) {
gui = true;
}
if ( arg.equals("-tokens") ) {
showTokens = true;
}
else if ( arg.equals("-trace") ) {
trace = true;
}
else if ( arg.equals("-SLL") ) {
SLL = true;
}
else if ( arg.equals("-diagnostics") ) {
diagnostics = true;
}
else if ( arg.equals("-encoding") ) {
if ( i>=args.length ) {
System.err.println("missing encoding on -encoding");
return;
}
encoding = args[i];
i++;
}
else if ( arg.equals("-ps") ) {
if ( i>=args.length ) {
System.err.println("missing filename on -ps");
return;
}
psFile = args[i];
i++;
}
}
}
public static void main(String[] args) throws Exception {
Test test = new Test(args);
if(args.length >= 2) {
test.process();
}
}
public void process() throws Exception {
//System.out.println("exec "+grammarName+" "+startRuleName);
String lexerName = grammarName+"Lexer";
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Class<? extends Lexer> lexerClass = null;
try {
lexerClass = cl.loadClass(lexerName).asSubclass(Lexer.class);
}
catch (java.lang.ClassNotFoundException cnfe) {
System.err.println("1: Can't load "+lexerName+" as lexer or parser");
return;
}
Constructor<? extends Lexer> lexerCtor = lexerClass.getConstructor(CharStream.class);
Lexer lexer = lexerCtor.newInstance((CharStream)null);
Class<? extends Parser> parserClass = null;
Parser parser = null;
if ( !startRuleName.equals(LEXER_START_RULE_NAME) ) {
String parserName = grammarName+"Parser";
parserClass = cl.loadClass(parserName).asSubclass(Parser.class);
if ( parserClass==null ) {
System.err.println("Can't load "+parserName);
}
Constructor<? extends Parser> parserCtor = parserClass.getConstructor(TokenStream.class);
parser = parserCtor.newInstance((TokenStream)null);
}
if ( inputFiles.size()==0 ) {
InputStream is = System.in;
Reader r;
if ( encoding!=null ) {
r = new InputStreamReader(is, encoding);
}
else {
r = new InputStreamReader(is);
}
process(lexer, parserClass, parser, is, r);
return;
}
for (String inputFile : inputFiles) {
InputStream is = System.in;
if ( inputFile!=null ) {
is = new FileInputStream(inputFile);
}
Reader r;
if ( encoding!=null ) {
r = new InputStreamReader(is, encoding);
}
else {
r = new InputStreamReader(is);
}
if ( inputFiles.size()>1 ) {
System.err.println(inputFile);
}
process(lexer, parserClass, parser, is, r);
}
}
protected void process(Lexer lexer, Class<? extends Parser> parserClass, Parser parser, InputStream is, Reader r) throws IOException, IllegalAccessException, InvocationTargetException, PrintException {
try {
ANTLRInputStream input = new ANTLRInputStream(r);
lexer.setInputStream(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
tokens.fill();
if ( showTokens ) {
for (Object tok : tokens.getTokens()) {
System.out.println(tok);
}
}
if ( startRuleName.equals(LEXER_START_RULE_NAME) ) return;
if ( diagnostics ) {
parser.addErrorListener(new DiagnosticErrorListener());
parser.getInterpreter().setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION);
}
if ( printTree || gui || psFile!=null ) {
parser.setBuildParseTree(true);
}
if ( SLL ) { // overrides diagnostics
parser.getInterpreter().setPredictionMode(PredictionMode.SLL);
}
parser.setTokenStream(tokens);
parser.setTrace(trace);
//parser.setErrorHandler(new BailErrorStrategy());
try {
Method startRule = parserClass.getMethod(startRuleName);
ParserRuleContext tree = (ParserRuleContext)startRule.invoke(parser, (Object[])null);
if ( printTree ) {
System.out.println(tree.toStringTree(parser));
}
if ( gui ) {
tree.inspect(parser);
}
if ( psFile!=null ) {
tree.save(parser, psFile); // Generate postscript
}
}
catch (NoSuchMethodException nsme) {
System.err.println("No method for rule "+startRuleName+" or it has arguments");
}
}
finally {
if ( r!=null ) r.close();
if ( is!=null ) is.close();
}
}
#SuppressWarnings("unused")
private static class BailErrorStrategy extends DefaultErrorStrategy {
/** Instead of recovering from exception e, rethrow it wrapped
* in a generic RuntimeException so it is not caught by the
* rule function catches. Exception e is the "cause" of the
* RuntimeException.
*/
#Override
public void recover(Parser recognizer, RecognitionException e) {
throw new RuntimeException(e);
}
/** Make sure we don't attempt to recover inline; if the parser
* successfully recovers, it won't throw an exception.
*/
#Override
public Token recoverInline(Parser recognizer)
throws RecognitionException
{
throw new RuntimeException(new InputMismatchException(recognizer));
}
/** Make sure we don't attempt to recover from problems in subrules. */
#Override
public void sync(Parser recognizer) { }
}
}
'Hope this helps!
Create a new ANTLR 4 Project
Convert the project to faceted form
Add Java project facet
Optionally you can add package names to be generated in the header of the grammar file
Use target/generated-sources/antlr4 as source folder
Edit and save the grammar file to re-generate everything
The antlr4 generated sources should now be packaged and imported as usual inside your project.

find matching 'begin' - 'end' and highlight them

I am a newbie in developing a DSL in Xtext. I would like to add a feature of highlighting the matching start and end of a code block. In my language every function must start with 'begin' and end with 'end' and same with if conditions and loops. I need to highlight the matching/corresponding 'end' when the cursor is on the 'begin'. for example below, I need to highlight the corresponding first 'end' when the cursor is on the second 'begin':
function X
begin
if a>b
begin
a=b;
end
end
Any help with that please?
Thanks
i dont think the support for that is very good. if you can live with a minor solution you could try the following
The Grammar
Model:
greetings+=Greeting*;
Greeting:
'if' name=ID 'endif';
In the UiModule
#Override
public ICharacterPairMatcher bindICharacterPairMatcher() {
return new MyDslCharacterPairMatcher(new char[] { '(', ')', '{', '}', '[', ']' });
}
with
public class MyDslCharacterPairMatcher extends DefaultCharacterPairMatcher {
public MyDslCharacterPairMatcher(char[] chars) {
super(chars);
}
#Override
public IRegion match(IDocument document, int offset, int length) {
if (document instanceof IXtextDocument) {
IXtextDocument xtextDocument = (IXtextDocument)document;
IRegion result = xtextDocument.readOnly(new IUnitOfWork<IRegion, XtextResource>() {
#Override
public IRegion exec(XtextResource state) throws Exception {
MyDslGrammarAccess ga = state.getResourceServiceProvider().get(MyDslGrammarAccess.class);
ICompositeNode root = state.getParseResult().getRootNode();
ILeafNode matchNode = NodeModelUtils.findLeafNodeAtOffset(root, offset);
EObject object = NodeModelUtils.findActualSemanticObjectFor(matchNode);
if (object instanceof Greeting) {
Greeting g = (Greeting)object;
if (matchNode.getGrammarElement() == ga.getGreetingAccess().getIfKeyword_0()) {
ICompositeNode objectNode = NodeModelUtils.findActualNodeFor(object);
for (INode n : objectNode.getAsTreeIterable()) {
if (n.getGrammarElement() != null && n.getGrammarElement() == ga.getGreetingAccess().getEndifKeyword_2()) {
return new Region(n.getOffset(), n.getLength());
}
}
}
if (matchNode.getGrammarElement() == ga.getGreetingAccess().getEndifKeyword_2()) {
ICompositeNode objectNode = NodeModelUtils.findActualNodeFor(object);
for (INode n : objectNode.getAsTreeIterable()) {
if (n.getGrammarElement() != null && n.getGrammarElement() == ga.getGreetingAccess().getIfKeyword_0()) {
return new Region(n.getOffset(), n.getLength());
}
}
}
}
return null;
}
});
if (result != null) {
return result;
}
}
return super.match(document, offset, length);
}
}
Unfortunately JFace only Highlight a single Character.
if you want more i think you have to hook into IOccurrenceComputer
(you have to have mark occurences on then)
package org.xtext.example.mydsl1.ui;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.xtext.nodemodel.ICompositeNode;
import org.eclipse.xtext.nodemodel.ILeafNode;
import org.eclipse.xtext.nodemodel.INode;
import org.eclipse.xtext.nodemodel.util.NodeModelUtils;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.ui.editor.XtextEditor;
import org.eclipse.xtext.ui.editor.model.IXtextDocument;
import org.eclipse.xtext.ui.editor.occurrences.DefaultOccurrenceComputer;
import org.eclipse.xtext.util.CancelIndicator;
import org.eclipse.xtext.util.TextRegion;
import org.eclipse.xtext.util.concurrent.CancelableUnitOfWork;
import org.xtext.example.mydsl1.myDsl.Greeting;
import org.xtext.example.mydsl1.services.MyDslGrammarAccess;
public class MyDslOccurrenceComputer extends DefaultOccurrenceComputer {
#Override
public Map<Annotation, Position> createAnnotationMap(XtextEditor editor,
ITextSelection selection, SubMonitor monitor) {
final IXtextDocument document = editor.getDocument();
if (document != null) {
Map<Annotation, Position> result = document.readOnly(new CancelableUnitOfWork<Map<Annotation, Position>, XtextResource>() {
#Override
public Map<Annotation, Position> exec(XtextResource state,
final CancelIndicator cancelIndicator) throws Exception {
MyDslGrammarAccess ga = state.getResourceServiceProvider()
.get(MyDslGrammarAccess.class);
ICompositeNode root = state.getParseResult().getRootNode();
ILeafNode matchNode = NodeModelUtils.findLeafNodeAtOffset(
root, selection.getOffset());
EObject object = NodeModelUtils
.findActualSemanticObjectFor(matchNode);
if (object instanceof Greeting) {
Greeting g = (Greeting) object;
if (matchNode.getGrammarElement() == ga
.getGreetingAccess().getIfKeyword_0()) {
ICompositeNode objectNode = NodeModelUtils
.findActualNodeFor(object);
for (INode n : objectNode.getAsTreeIterable()) {
if (n.getGrammarElement() != null
&& n.getGrammarElement() == ga
.getGreetingAccess()
.getEndifKeyword_3()) {
Map<Annotation, Position> result = new HashMap<>();
addOccurrenceAnnotation(
DECLARATION_ANNOTATION_TYPE,
document,
new TextRegion(matchNode
.getOffset(), matchNode
.getLength()), result);
addOccurrenceAnnotation(
OCCURRENCE_ANNOTATION_TYPE,
document,
new TextRegion(n.getOffset(), n
.getLength()), result);
return result;
}
}
}
if (matchNode.getGrammarElement() == ga
.getGreetingAccess().getEndifKeyword_3()) {
ICompositeNode objectNode = NodeModelUtils
.findActualNodeFor(object);
for (INode n : objectNode.getAsTreeIterable()) {
if (n.getGrammarElement() != null
&& n.getGrammarElement() == ga
.getGreetingAccess()
.getIfKeyword_0()) {
Map<Annotation, Position> result = new HashMap<>();
addOccurrenceAnnotation(
DECLARATION_ANNOTATION_TYPE,
document,
new TextRegion(matchNode
.getOffset(), matchNode
.getLength()), result);
addOccurrenceAnnotation(
OCCURRENCE_ANNOTATION_TYPE,
document,
new TextRegion(n.getOffset(), n
.getLength()), result);
return result;
}
}
}
}
return null;
}
});
if (result != null) {
return result;
}
}
return super.createAnnotationMap(editor, selection, monitor);
}
}

LoadException with FXML created with Scene Builder 2.0

I got a problem that i absolutly cant solve on my own because i have just started using JAVA FX. I get a nasty javafx.fxml.LoadException: , but i have done exactly like a guide (http://docs.oracle.com/javafx/scenebuilder/1/get_started/jsbpub-get_started.htm), but i cant get my Main to run. This is the console:
ant -f P:\\FXML\\IssueTrackingLite jfxsa-run
init:
deps-jar:
Created dir: P:\FXML\IssueTrackingLite\build
Updating property file: P:\FXML\IssueTrackingLite\build\built-jar.properties
Created dir: P:\FXML\IssueTrackingLite\build\classes
Created dir: P:\FXML\IssueTrackingLite\build\empty
Created dir: P:\FXML\IssueTrackingLite\build\generated-sources\ap-source-output
Compiling 6 source files to P:\FXML\IssueTrackingLite\build\classes
warning: [options] bootstrap class path not set in conjunction with -source 1.6
1 warning
Copying 4 files to P:\FXML\IssueTrackingLite\build\classes
compile:
Detected JavaFX Ant API version 1.3
Launching <fx:jar> task from C:\Program Files\Java\jdk1.8.0\jre\..\lib\ant-javafx.jar
Warning: From JDK7u25 the Codebase manifest attribute should be used to restrict JAR repurposing.
Please set manifest.custom.codebase property to override the current default non-secure value '*'.
Launching <fx:deploy> task from C:\Program Files\Java\jdk1.8.0\jre\..\lib\ant-javafx.jar
jfx-deployment-script:
jfx-deployment:
jar:
Copying 12 files to P:\FXML\IssueTrackingLite\dist\run910302418
jfx-project-run:
Executing P:\FXML\IssueTrackingLite\dist\run910302418\IssueTrackingLite.jar using platform C:\Program Files\Java\jdk1.8.0\jre/bin/java
before ........!
IssueTrackingLiteController.initialize
août 11, 2014 12:24:01 PM issuetrackinglite.Main start
GRAVE: null
javafx.fxml.LoadException:
file:/P:/FXML/IssueTrackingLite/dist/run910302418/IssueTrackingLite.jar!/issuetrackinglite/IssueTrackingLite.fxml
at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2617)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2595)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3230)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3191)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3164)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3140)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3120)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3113)
at issuetrackinglite.Main.start(Main.java:55)
at com.sun.javafx.application.LauncherImpl$8.run(LauncherImpl.java:837)
at com.sun.javafx.application.PlatformImpl$7.run(PlatformImpl.java:335)
at com.sun.javafx.application.PlatformImpl$6$1.run(PlatformImpl.java:301)
at com.sun.javafx.application.PlatformImpl$6$1.run(PlatformImpl.java:298)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl$6.run(PlatformImpl.java:298)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$300(WinApplication.java:39)
at com.sun.glass.ui.win.WinApplication$4$1.run(WinApplication.java:112)
at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.NullPointerException
at issuetrackinglite.IssueTrackingLiteController.configureTable(IssueTrackingLiteController.java:481)
at issuetrackinglite.IssueTrackingLiteController.initialize(IssueTrackingLiteController.java:119)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
... 19 more
BUILD STOPPED (total time: 50 minutes 46 seconds)
What does it mean and how can I fix it?
the main class:
package issuetrackinglite;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
public class Main extends Application {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Application.launch(Main.class, (java.lang.String[])null);
}
#Override
public void start(Stage primaryStage) {
try {
System.out.println(" before ........!");
AnchorPane page = (AnchorPane) FXMLLoader.load(Main.class.getResource("/issuetrackinglite/IssueTrackingLite.fxml"));
System.out.println(" after .............!");
Scene scene = new Scene(page);
primaryStage.setScene(scene);
primaryStage.setTitle("Issue Tracking Lite Sample");
primaryStage.show();
} catch (Exception ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
my FXML file is in the same path as Main class.
the class Controller:
package issuetrackinglite;
public class IssueTrackingLiteController implements Initializable {
#FXML
Button newIssue;
#FXML
Button deleteIssue;
#FXML
Button saveIssue;
TableView<ObservableIssue> table;
#FXML
TableColumn<ObservableIssue, String> colName;
#FXML
TableColumn<ObservableIssue, IssueStatus> colStatus;
#FXML
TableColumn<ObservableIssue, String> colSynopsis;
#FXML
ListView<String> list;
#FXML
TextField synopsis;
private String displayedBugId; // the id of the bug displayed in the details section.
private String displayedBugProject; // the name of the project of the bug displayed in the detailed section.
#FXML
Label displayedIssueLabel; // the displayedIssueLabel will contain a concatenation of the
// the project name and the bug id.
#FXML
AnchorPane details;
#FXML
TextArea descriptionValue;
ObservableList<String> projectsView = FXCollections.observableArrayList();
TrackingService model = null;
private TextField statusValue = new TextField();
final ObservableList<ObservableIssue> tableContent = FXCollections.observableArrayList();
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rsrcs) {
assert colName != null : "fx:id=\"colName\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert colStatus != null : "fx:id=\"colStatus\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert colSynopsis != null : "fx:id=\"colSynopsis\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert deleteIssue != null : "fx:id=\"deleteIssue\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert descriptionValue != null : "fx:id=\"descriptionValue\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert details != null : "fx:id=\"details\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert displayedIssueLabel != null : "fx:id=\"displayedIssueLabel\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert newIssue != null : "fx:id=\"newIssue\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert saveIssue != null : "fx:id=\"saveIssue\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert synopsis != null : "fx:id=\"synopsis\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert table != null : "fx:id=\"table\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert list != null : "fx:id=\"list\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
System.out.println(this.getClass().getSimpleName() + ".initialize");
configureButtons();
configureDetails();
configureTable();
connectToService();
if (list != null) {
list.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
list.getSelectionModel().selectedItemProperty().addListener(projectItemSelected);
displayedProjectNames.addListener(projectNamesListener);
}
}
/**
* Called when the NewIssue button is fired.
*
* #param event the action event.
*/
#FXML
public void newIssueFired(ActionEvent event) {
final String selectedProject = getSelectedProject();
if (model != null && selectedProject != null) {
ObservableIssue issue = model.createIssueFor(selectedProject);
if (table != null) {
// Select the newly created issue.
table.getSelectionModel().clearSelection();
table.getSelectionModel().select(issue);
}
}
}
/**
* Called when the DeleteIssue button is fired.
*
* #param event the action event.
*/
#FXML
public void deleteIssueFired(ActionEvent event) {
final String selectedProject = getSelectedProject();
if (model != null && selectedProject != null && table != null) {
// We create a copy of the current selection: we can't delete
// issue while looping over the live selection, since
// deleting selected issues will modify the selection.
final List<?> selectedIssue = new ArrayList<Object>(table.getSelectionModel().getSelectedItems());
for (Object o : selectedIssue) {
if (o instanceof ObservableIssue) {
model.deleteIssue(((ObservableIssue) o).getId());
}
}
table.getSelectionModel().clearSelection();
}
}
/**
* Called when the SaveIssue button is fired.
*
* #param event the action event.
*/
#FXML
public void saveIssueFired(ActionEvent event) {
final ObservableIssue ref = getSelectedIssue();
final Issue edited = new DetailsData();
SaveState saveState = computeSaveState(edited, ref);
if (saveState == SaveState.UNSAVED) {
model.saveIssue(ref.getId(), edited.getStatus(),
edited.getSynopsis(), edited.getDescription());
}
// We refresh the content of the table because synopsis and/or description
// are likely to have been modified by the user.
int selectedRowIndex = table.getSelectionModel().getSelectedIndex();
table.getItems().clear();
displayedIssues = model.getIssueIds(getSelectedProject());
for (String id : displayedIssues) {
final ObservableIssue issue = model.getIssue(id);
table.getItems().add(issue);
}
table.getSelectionModel().select(selectedRowIndex);
updateSaveIssueButtonState();
}
private void configureButtons() {
if (newIssue != null) {
newIssue.setDisable(true);
}
if (saveIssue != null) {
saveIssue.setDisable(true);
}
if (deleteIssue != null) {
deleteIssue.setDisable(true);
}
}
// An observable list of project names obtained from the model.
// This is a live list, and we will react to its changes by removing
// and adding project names to/from our list widget.
private ObservableList<String> displayedProjectNames;
// The list of Issue IDs relevant to the selected project. Can be null
// if no project is selected. This list is obtained from the model.
// This is a live list, and we will react to its changes by removing
// and adding Issue objects to/from our table widget.
private ObservableList<String> displayedIssues;
// This listener will listen to changes in the displayedProjectNames list,
// and update our list widget in consequence.
private final ListChangeListener<String> projectNamesListener = new ListChangeListener<String>() {
#Override
public void onChanged(Change<? extends String> c) {
if (projectsView == null) {
return;
}
while (c.next()) {
if (c.wasAdded() || c.wasReplaced()) {
for (String p : c.getAddedSubList()) {
projectsView.add(p);
}
}
if (c.wasRemoved() || c.wasReplaced()) {
for (String p : c.getRemoved()) {
projectsView.remove(p);
}
}
}
FXCollections.sort(projectsView);
}
};
// This listener will listen to changes in the displayedIssues list,
// and update our table widget in consequence.
private final ListChangeListener<String> projectIssuesListener = new ListChangeListener<String>() {
#Override
public void onChanged(Change<? extends String> c) {
if (table == null) {
return;
}
while (c.next()) {
if (c.wasAdded() || c.wasReplaced()) {
for (String p : c.getAddedSubList()) {
table.getItems().add(model.getIssue(p));
}
}
if (c.wasRemoved() || c.wasReplaced()) {
for (String p : c.getRemoved()) {
ObservableIssue removed = null;
// Issue already removed:
// we can't use model.getIssue(issueId) to get it.
// we need to loop over the table content instead.
// Then we need to remove it - but outside of the for loop
// to avoid ConcurrentModificationExceptions.
for (ObservableIssue t : table.getItems()) {
if (t.getId().equals(p)) {
removed = t;
break;
}
}
if (removed != null) {
table.getItems().remove(removed);
}
}
}
}
}
};
// Connect to the model, get the project's names list, and listen to
// its changes. Initializes the list widget with retrieved project names.
private void connectToService() {
if (model == null) {
model = new TrackingServiceStub();
displayedProjectNames = model.getProjectNames();
}
projectsView.clear();
List<String> sortedProjects = new ArrayList<String>(displayedProjectNames);
Collections.sort(sortedProjects);
projectsView.addAll(sortedProjects);
list.setItems(projectsView);
}
// This listener listen to changes in the table widget selection and
// update the DeleteIssue button state accordingly.
private final ListChangeListener<ObservableIssue> tableSelectionChanged =
new ListChangeListener<ObservableIssue>() {
#Override
public void onChanged(Change<? extends ObservableIssue> c) {
updateDeleteIssueButtonState();
updateBugDetails();
updateSaveIssueButtonState();
}
};
private static String nonNull(String s) {
return s == null ? "" : s;
}
private void updateBugDetails() {
final ObservableIssue selectedIssue = getSelectedIssue();
if (details != null && selectedIssue != null) {
if (displayedIssueLabel != null) {
displayedBugId = selectedIssue.getId();
displayedBugProject = selectedIssue.getProjectName();
displayedIssueLabel.setText( displayedBugId + " / " + displayedBugProject );
}
if (synopsis != null) {
synopsis.setText(nonNull(selectedIssue.getSynopsis()));
}
if (statusValue != null) {
statusValue.setText(selectedIssue.getStatus().toString());
}
if (descriptionValue != null) {
descriptionValue.selectAll();
descriptionValue.cut();
descriptionValue.setText(selectedIssue.getDescription());
}
} else {
displayedIssueLabel.setText("");
displayedBugId = null;
displayedBugProject = null;
}
if (details != null) {
details.setVisible(selectedIssue != null);
}
}
private boolean isVoid(Object o) {
if (o instanceof String) {
return isEmpty((String) o);
} else {
return o == null;
}
}
private boolean isEmpty(String s) {
return s == null || s.trim().isEmpty();
}
private boolean equal(Object o1, Object o2) {
if (isVoid(o1)) {
return isVoid(o2);
}
return o1.equals(o2);
}
private static enum SaveState {
INVALID, UNSAVED, UNCHANGED
}
private final class DetailsData implements Issue {
#Override
public String getId() {
if (displayedBugId == null || isEmpty(displayedIssueLabel.getText())) {
return null;
}
return displayedBugId;
}
#Override
public IssueStatus getStatus() {
if (statusValue == null || isEmpty(statusValue.getText())) {
return null;
}
return IssueStatus.valueOf(statusValue.getText().trim());
}
#Override
public String getProjectName() {
if (displayedBugProject == null || isEmpty(displayedIssueLabel.getText())) {
return null;
}
return displayedBugProject;
}
#Override
public String getSynopsis() {
if (synopsis == null || isEmpty(synopsis.getText())) {
return "";
}
return synopsis.getText();
}
#Override
public String getDescription() {
if (descriptionValue == null || isEmpty(descriptionValue.getText())) {
return "";
}
return descriptionValue.getText();
}
}
private SaveState computeSaveState(Issue edited, Issue issue) {
try {
// These fields are not editable - so if they differ they are invalid
// and we cannot save.
if (!equal(edited.getId(), issue.getId())) {
return SaveState.INVALID;
}
if (!equal(edited.getProjectName(), issue.getProjectName())) {
return SaveState.INVALID;
}
// If these fields differ, the issue needs saving.
if (!equal(edited.getStatus(), issue.getStatus())) {
return SaveState.UNSAVED;
}
if (!equal(edited.getSynopsis(), issue.getSynopsis())) {
return SaveState.UNSAVED;
}
if (!equal(edited.getDescription(), issue.getDescription())) {
return SaveState.UNSAVED;
}
} catch (Exception x) {
// If there's an exception, some fields are invalid.
return SaveState.INVALID;
}
// No field is invalid, no field needs saving.
return SaveState.UNCHANGED;
}
private void updateDeleteIssueButtonState() {
boolean disable = true;
if (deleteIssue != null && table != null) {
final boolean nothingSelected = table.getSelectionModel().getSelectedItems().isEmpty();
disable = nothingSelected;
}
if (deleteIssue != null) {
deleteIssue.setDisable(disable);
}
}
private void updateSaveIssueButtonState() {
boolean disable = true;
if (saveIssue != null && table != null) {
final boolean nothingSelected = table.getSelectionModel().getSelectedItems().isEmpty();
disable = nothingSelected;
}
if (disable == false) {
disable = computeSaveState(new DetailsData(), getSelectedIssue()) != SaveState.UNSAVED;
}
if (saveIssue != null) {
saveIssue.setDisable(disable);
}
}
// Configure the table widget: set up its column, and register the
// selection changed listener.
private void configureTable() {
colName.setCellValueFactory(new PropertyValueFactory<ObservableIssue, String>("id"));
colSynopsis.setCellValueFactory(new PropertyValueFactory<ObservableIssue, String>("synopsis"));
colStatus.setCellValueFactory(new PropertyValueFactory<ObservableIssue, IssueStatus>("status"));
// In order to limit the amount of setup in Getting Started we set the width
// of the 3 columns programmatically but one can do it from SceneBuilder.
colName.setPrefWidth(75);
colStatus.setPrefWidth(75);
colSynopsis.setPrefWidth(443);
colName.setMinWidth(75);
colStatus.setMinWidth(75);
colSynopsis.setMinWidth(443);
colName.setMaxWidth(750);
colStatus.setMaxWidth(750);
colSynopsis.setMaxWidth(4430);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
table.setItems(tableContent);
assert table.getItems() == tableContent;
final ObservableList<ObservableIssue> tableSelection = table.getSelectionModel().getSelectedItems();
tableSelection.addListener(tableSelectionChanged);
}
/**
* Return the name of the project currently selected, or null if no project
* is currently selected.
*
*/
public String getSelectedProject() {
if (model != null && list != null) {
final ObservableList<String> selectedProjectItem = list.getSelectionModel().getSelectedItems();
final String selectedProject = selectedProjectItem.get(0);
return selectedProject;
}
return null;
}
public ObservableIssue getSelectedIssue() {
if (model != null && table != null) {
List<ObservableIssue> selectedIssues = table.getSelectionModel().getSelectedItems();
if (selectedIssues.size() == 1) {
final ObservableIssue selectedIssue = selectedIssues.get(0);
return selectedIssue;
}
}
return null;
}
/**
* Listen to changes in the list selection, and updates the table widget and
* DeleteIssue and NewIssue buttons accordingly.
*/
private final ChangeListener<String> projectItemSelected = new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
projectUnselected(oldValue);
projectSelected(newValue);
}
};
// Called when a project is unselected.
private void projectUnselected(String oldProjectName) {
if (oldProjectName != null) {
displayedIssues.removeListener(projectIssuesListener);
displayedIssues = null;
table.getSelectionModel().clearSelection();
table.getItems().clear();
if (newIssue != null) {
newIssue.setDisable(true);
}
if (deleteIssue != null) {
deleteIssue.setDisable(true);
}
}
}
// Called when a project is selected.
private void projectSelected(String newProjectName) {
if (newProjectName != null) {
table.getItems().clear();
displayedIssues = model.getIssueIds(newProjectName);
for (String id : displayedIssues) {
final ObservableIssue issue = model.getIssue(id);
table.getItems().add(issue);
}
displayedIssues.addListener(projectIssuesListener);
if (newIssue != null) {
newIssue.setDisable(false);
}
updateDeleteIssueButtonState();
updateSaveIssueButtonState();
}
}
private void configureDetails() {
if (details != null) {
details.setVisible(false);
}
if (details != null) {
details.addEventFilter(EventType.ROOT, new EventHandler<Event>() {
#Override
public void handle(Event event) {
if (event.getEventType() == MouseEvent.MOUSE_RELEASED
|| event.getEventType() == KeyEvent.KEY_RELEASED) {
updateSaveIssueButtonState();
}
}
});
}
}
}

Solution for Numeric Text Field in GWT

I need a text field very similar in behavior to Gxt's NumberField. Unfortunately I am not using Gxt in my application and GWT 2.0 does not have a Numeric text field implementation as yet.
So that currently leaves me with an option to simulate a NumberField by filtering out non-numeric keystrokes using a keyboardHandler.
Is this the the best way to approach the problem? Does anyone here have a better solution/approach in mind?
Thanks in advance :)
Here you can find the code that I use in one of my classes. The features are much more limited that those of GXT, but should put you in the proper track.
It's a really basic widget, but does what I need to.
public class ValueTextBox extends TextBox {
private int min = 0;
private int max = 100;
private boolean minConstrained = true;
private boolean maxConstrained = true;
private int minDigits = 1;
private int step = 1;
private KeyUpHandler keyUpHandler = new KeyUpHandler() {
#Override
public void onKeyUp(KeyUpEvent event) {
if (isReadOnly() || !isEnabled()) {
return;
}
int keyCode = event.getNativeEvent().getKeyCode();
boolean processed = false;
switch (keyCode) {
case KeyCodes.KEY_LEFT:
case KeyCodes.KEY_RIGHT:
case KeyCodes.KEY_BACKSPACE:
case KeyCodes.KEY_DELETE:
case KeyCodes.KEY_TAB:
if (getText().isEmpty()) {
setValue(formatValue(min));
}
return;
case KeyCodes.KEY_UP:
if (step != 0) {
increaseValue();
processed = true;
}
break;
case KeyCodes.KEY_DOWN:
if (step != 0) {
decreaseValue();
processed = true;
}
break;
}
if (processed) {
cancelKey();
}
}
};
private KeyPressHandler keyPressHandler = new KeyPressHandler() {
#Override
public void onKeyPress(KeyPressEvent event) {
if (isReadOnly() || !isEnabled()) {
return;
}
int keyCode = event.getNativeEvent().getKeyCode();
switch (keyCode) {
case KeyCodes.KEY_LEFT:
case KeyCodes.KEY_RIGHT:
case KeyCodes.KEY_BACKSPACE:
case KeyCodes.KEY_DELETE:
case KeyCodes.KEY_TAB:
case KeyCodes.KEY_UP:
case KeyCodes.KEY_DOWN:
return;
}
int index = getCursorPos();
String previousText = getText();
String newText;
if (getSelectionLength() > 0) {
newText = previousText.substring(0, getCursorPos())
+ event.getCharCode()
+ previousText.substring(getCursorPos()
+ getSelectionLength(), previousText.length());
} else {
newText = previousText.substring(0, index)
+ event.getCharCode()
+ previousText.substring(index, previousText.length());
}
cancelKey();
setValue(newText, true);
}
};
public ValueTextBox(int value) {
this(value, 0, 100);
}
public ValueTextBox(int value, int min, int max) {
this(value, min, max, true);
}
public ValueTextBox(int value, int min, int max, boolean constrained) {
this(value, min, max, constrained, constrained);
}
public ValueTextBox(int value, int min, int max, boolean minConstrained,
boolean maxConstrained) {
super();
addKeyPressHandler(keyPressHandler);
addKeyUpHandler(keyUpHandler);
this.min = min;
this.max = max;
this.minConstrained = minConstrained;
this.maxConstrained = maxConstrained;
setValue(formatValue(value), false);
setTextAlignment(TextBoxBase.ALIGN_CENTER);
setStyleName(Resources.INSTANCE.css().fwFormEntry());
}
public void setMinDigits(int minDigits) {
if (minDigits > 0) {
this.minDigits = minDigits;
String value = getText();
long newValue = parseValue(value);
setText(formatValue(newValue));
}
}
public void setSteps(int step) {
this.step = step;
}
protected void increaseValue() {
if (step != 0) {
String value = getText();
long newValue = parseValue(value);
newValue += step;
if (maxConstrained && (newValue > max)) {
return;
}
setValue(formatValue(newValue));
}
}
protected void decreaseValue() {
if (step != 0) {
String value = getText();
long newValue = parseValue(value);
newValue -= step;
if (minConstrained && (newValue < min)) {
return;
}
setValue(formatValue(newValue));
}
}
/**
* #param value
* the value to format
* #return the formatted value
*/
protected String formatValue(long value) {
String newValue = String.valueOf(value);
if (minDigits > newValue.length()) {
String leading = StringUtils.repeat("0", (minDigits - newValue
.length()));
newValue = leading + newValue;
}
return newValue;
}
#Override
public void setValue(String value) {
setValue(value, false);
}
#Override
public void setValue(String value, boolean fireEvents) {
try {
long newValue = parseValue(value);
if ((maxConstrained && (newValue > max))
|| (minConstrained && (newValue < min))) {
return;
}
String prevText = getValue();
super.setText(formatValue(newValue));
if (fireEvents) {
ValueChangeEvent.fireIfNotEqual(this, getValue(), prevText);
}
} catch (Exception ex) {
// Do Nothing
System.out.println(ex.getMessage());
}
}
/**
* #param value
* the value to parse
* #return the parsed value
*/
protected long parseValue(String value) {
return Long.valueOf(value);
}
}
Update: The code is available in https://github.com/ctasada/GWT-Eureka
Here is a simple KeyPressHandler to allow the user to input decimal numbers;
public void onKeyPress(KeyPressEvent event){
TextBox sender = (TextBox)event.getSource();
if (sender.isReadOnly() || !sender.isEnabled()) {
return;
}
Character charCode = event.getCharCode();
int unicodeCharCode = event.getUnicodeCharCode();
// allow digits, '.' and non-characters
if (!(Character.isDigit(charCode) || charCode == '.' || unicodeCharCode == 0)){
sender.cancelKey();
}
}
Don't know when these classes were added to GWT, but they work fine for me without any extra code:
com.google.gwt.user.client.ui.DoubleBox
com.google.gwt.user.client.ui.IntegerBox
com.google.gwt.user.client.ui.LongBox
For more advanced validation you may want to overwrite their base class ValueBox with some custom Parser...
Here is my implementation of NumberField. Very similar in functionality to Carlos's version, but with additional support for decimal input and non-numeric key filtering.
public class NumberBox extends TextBox
{
private boolean isDecimal = false;
public NumberBox( )
{
}
public boolean isDecimal( )
{
return isDecimal;
}
public void setDecimal( boolean isDecimal )
{
this.isDecimal = isDecimal;
}
public Integer getIntegerValue( )
{
return ( StringUtil.isEmpty( getSanitizedValue( ) ) ) ? null : Integer.parseInt( getSanitizedValue( ) );
}
#Override
protected void initialize( )
{
super.initialize( );
addStyleName( "number" );
this.addKeyPressHandler( new KeyPressHandler( )
{
public void onKeyPress( KeyPressEvent event )
{
if ( !isEnabled( ) || isReadOnly( ) )
return;
int keyCode = event.getNativeEvent( ).getKeyCode( );
// allow special keys
if ( ( keyCode == KeyCodes.KEY_BACKSPACE )
|| ( keyCode == KeyCodes.KEY_DELETE )
|| ( keyCode == KeyCodes.KEY_ENTER ) || ( keyCode == KeyCodes.KEY_ESCAPE ) || ( keyCode == KeyCodes.KEY_RIGHT )
|| ( keyCode == KeyCodes.KEY_LEFT ) || ( keyCode == KeyCodes.KEY_TAB ) )
return;
// check for decimal '.'
if ( isDecimal( ) && '.' == (char)keyCode && !getValue( ).contains( "." ) )
return;
// filter out non-digits
if ( Character.isDigit( charCode ) )
return;
cancelKey( );
}
} );
}
}
PS: Superclass TextBox is a custom class extending GWT TextBox with some additional application specific features. The method initialize() is basically invoked inside the TextBox constructor, and getSanitizedValue does some basic sanity checks with trimming.
Carlos Tasada answer works, but contains a bug: you should add event.isShiftKeyDown() check in onKeyPress handler before switch/case block. It will pass some symbols like '(' otherwise.
Based on Julian Downes answer you can do this:
text.addKeyPressHandler(new KeyPressHandler() {
#Override
public void onKeyPress(KeyPressEvent event) {
TextBox sender = (TextBox) event.getSource();
if (sender.isReadOnly() || !sender.isEnabled()) {
return;
}
if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER){
return;
}
Character charCode = event.getCharCode();
try{
Double.parseDouble(sender.getText().concat(charCode.toString()));
}
catch(Exception e){
sender.cancelKey();
}
}
});