Cannot recognize Japanese characters - java

I have a combo box in java which filters smoothly if alphanumeric is inputted. But if I input Japanese character, it does not work.
Here is a scenario to describe my filtering:
Combo box items are the following:
If user inputs letter K, the items are narrow down/filtered if the string is present in each of the items, so that
leaves it to this: it is working as expected.
However, if user inputs a Japanese character like "エ" once, it doubles the entry of the character automatically even pressing it once, so it does not work as expected like the filtering above.
Illustration if user inputs エ
Here is my current code:
JTextComponent editor = (JTextComponent) combo.getEditor().getEditorComponent();
editor.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent ke) {
combo.setPopupVisible(true);
}
});
editor.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent arg0) {
}
public void insertUpdate(DocumentEvent arg0) {
String item = combo.getEditor().getItem().toString().trim();
if (!item.equals(tempCmbString)) {
searchCmb();
}
}
public void removeUpdate(DocumentEvent arg0) {
String item = combo.getEditor().getItem().toString().trim();
if (!item.equals(tempCmbString)) {
searchCmb();
}
}
private void searchCmb() {
Runnable doSearchCmb = new Runnable() {
#Override
public void run() {
IElement[] foundList = null;
List list = new ArrayList(0);
String toFind = combo.getEditor().getItem().toString().trim();
if (toFind.length() == 0) {
int cmbItems = combo.getItems().length;
if (cmbItems != elements.length) {
combo.setItems(elements);
}
tempCmbString = "";
} else {
boolean isEqualToTempStr = !toFind.equals(tempCmbString);
if (isEqualToTempStr) {
combo.setItems(elements);
}
if (!toFind.equals(":")) {
for (int i = 1; i < elements.length; i++) {
if (toFind.length() > 0) {
String key = elements[i].getKey();
String fullName = elements[i].getName();
String name = "";
if (fullName.length() > 0 && fullName.indexOf(':') > 0) {
name = fullName.substring(0, fullName.indexOf(':'));
}
if (key.contains(toFind)) {
if (toFind.length() < 5 && toFind.length() > 0) {
if (toFind.equals(key.substring(0, toFind.length()))) {
list.add(elements[i]);
}
}
} else if (name.contains(toFind)) {
list.add(elements[i]);
} else if (fullName.contains(toFind)) {
list.add(elements[i]);
}
}
foundList = (IElement[]) list.toArray(new IElement[list.size()]);
}
if (list.size() > 0) {
if (isEqualToTempStr) {
combo.setItems(foundList);
}
} else {
combo.removeAllItems();
if (isEqualToTempStr) {
combo.setItems(elements);
}
list.add(new DIElement("", ""));
foundList = (IElement[]) list.toArray(new IElement[list.size()]);
if (isEqualToTempStr) {
combo.setItems(foundList);
}
}
if (isEqualToTempStr) {
combo.getEditor().setItem(toFind);
tempCmbString = toFind;
}
}
}
}
};
SwingUtilities.invokeLater(doSearchCmb);
}
});

Related

AVL tree in java

The program that I am writing simulates a road charging system which reads several lines of inputs, each one representing a different command until I reach the EOF (\n).
This commands simulate a road charging system, where the input reads as follows:
PASS 44AB55 I -> where the first word is the command the program receives, the second word is the number plate of the car (44AB55) and the second is the status of the car (Regular or Irregular).
There are three types of commands:
“PASS 00AA00 R” – Increments the number of times that the car has passed in the system and marks its status has Regular or Irreguar. If the car isnt still in the database, it inserts the car as Regular and starts the counter with one passage.
“UNFLAG 00AA00” – Flags the car as Regular if it exists in the database. If the car doesnt exist in the database ignores the command.
“STATUS 00AA00” – Retrieves the status of the car (Regular or Irregular) and the number of passages of the car in the system. If it the car doesnt exist in the database, prints a "NO RECORD" message.
To solve this problem, I am using AVL trees and using the following code:
import java.util.ArrayList;
import java.util.Scanner;
public class TP2_probB {
static No raiz = null;
static double numRotacoes = 0;
static double numAtravessos = 0;
public static class No {
private String matricula;
private int porticos;
private boolean estadoRegular;
private No pai;
private No filhoEsq;
private No filhoDir;
private int balanco;
public No(String matricula, int porticos, boolean estadoRegular) {
this.matricula = matricula;
this.porticos = porticos;
this.estadoRegular = estadoRegular;
this.pai = null;
this.filhoDir = null;
this.filhoEsq = null;
this.balanco = 0;
}
public void setEstadoRegular(boolean estadoRegular) {
this.estadoRegular = estadoRegular;
}
public void setPai(No pai) {
this.pai = pai;
}
public void setFilhoEsq(No filhoEsq) {
this.filhoEsq = filhoEsq;
}
public void setFilhoDir(No filhoDir) {
this.filhoDir = filhoDir;
}
public void atribuiNoEsq(No noEsq) {
this.filhoEsq = noEsq;
}
public void atribuiNoDir(No noDir) {
this.filhoDir = noDir;
}
public void atribuiPai(No noPai) {
this.pai = noPai;
}
public void aumentaPortico() {
porticos++;
}
public String getMatricula() {
return matricula;
}
public boolean isEstadoRegular() {
return estadoRegular;
}
public No getPai() {
return pai;
}
public No getFilhoEsq() {
return filhoEsq;
}
public No getFilhoDir() {
return filhoDir;
}
#Override
public String toString() {
String estado;
if (estadoRegular == true) {
estado = "R";
} else {
estado = "I";
}
return matricula + " " + porticos + " " + estado;
}
}
public static No duplaRotacaoFilhoEsq(No k3)
{
k3.filhoEsq = rotacaoFilhoDir(k3);
return rotacaoFilhoEsq(k3);
}
public static No duplaRotacaoFilhoDir(No k3)
{
k3.filhoDir = rotacaoFilhoEsq(k3);
return rotacaoFilhoDir(k3);
}
public static No rotacaoFilhoDir(No k1) {
No k2 = k1.filhoDir;
k2.pai=k1.pai;
k1.filhoDir = k2.filhoEsq;
if(k1.filhoDir!=null)
{
k1.filhoDir.pai=k1;
}
k2.filhoEsq = k1;
k1.pai=k2;
if(k2.pai!=null)
{
if(k2.pai.filhoDir==k1)
{
k2.pai.filhoDir = k2;
}
else if(k2.pai.filhoEsq==k1)
{
k2.pai.filhoEsq = k2;
}
}
balanco(k2);
balanco(k1);
return k2;
}
public static No rotacaoFilhoEsq(No k1) {
No k2 = k1.filhoEsq;
k2.pai=k1.pai;
k1.filhoEsq = k2.filhoDir;
if(k1.filhoEsq!=null)
{
k1.filhoEsq.pai=k1;
}
k2.filhoDir = k1;
k1.pai=k2;
if(k2.pai!=null)
{
if(k2.pai.filhoDir==k1)
{
k2.pai.filhoDir = k2;
}
else if(k2.pai.filhoEsq==k1)
{
k2.pai.filhoEsq = k2;
}
}
balanco(k2);
balanco(k1);
return k2;
}
public static int pesagem(No aux)
{
if(aux==null)
{
return -1;
}
if(aux.filhoEsq == null && aux.filhoDir == null)
{
return 0;
}
else if ((aux.filhoEsq == null))
{
return (pesagem(aux.filhoDir) + 1);
}
else if ((aux.filhoDir == null))
{
return (pesagem(aux.filhoEsq) + 1);
}
else
return (Math.max(pesagem(aux.filhoEsq), pesagem(aux.filhoDir)) + 1);
}
public static void balanco(No tmp)
{
tmp.balanco = pesagem(tmp.filhoDir)-pesagem(tmp.filhoEsq);
}
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String linha;
String[] aux;
ArrayList<String> output = new ArrayList<String>();
int x = 0;
while (true) {
linha = input.nextLine();
if (linha.isEmpty())
{
break;
}
else
{
aux = linha.split(" ");
if (aux[0].compareTo("PASS") == 0) {
No novo;
if (aux[2].compareTo("R") == 0) {
novo = new No(aux[1], 1, true);
} else {
novo = new No(aux[1], 1, false);
}
if (raiz == null) {
raiz = novo;
balanco(raiz);
} else {
procuraNo(novo);
}
} else if (aux[0].compareTo("UNFLAG") == 0) {
if (raiz != null) {
No no = new No(aux[1], 0, false);
mudaEstado(no);
}
} else if (aux[0].compareTo("STATUS") == 0) {
if (raiz == null) {
output.add(aux[1] + " NO RECORD");
} else {
No no = new No(aux[1], 0, false);
output.add(procuraRegisto(no));
}
}
}
}
for (int i = 0; i < output.size(); i++) {
System.out.println(output.get(i));
}
System.out.println("Número de Rotações: "+numRotacoes+"\nNúmero de atravessias: "+numAtravessos);
}
public static void procuraNo(No novo) {
No aux = raiz;
while (true) {
if (aux.getMatricula().compareTo(novo.getMatricula()) == 0) {
aux.aumentaPortico();
aux.setEstadoRegular(novo.isEstadoRegular());
equilibra(aux);
break;
} else if (aux.getMatricula().compareTo(novo.getMatricula()) < 0) {
if (aux.getFilhoDir() == null) {
novo.setPai(aux);
aux.setFilhoDir(novo);
aux=aux.filhoDir;
equilibra(aux);
break;
} else {
aux = aux.getFilhoDir();
numAtravessos++;
}
} else if (aux.getMatricula().compareTo(novo.getMatricula()) > 0) {
if (aux.getFilhoEsq() == null) {
novo.setPai(aux);
aux.setFilhoEsq(novo);
aux=aux.filhoEsq;
equilibra(aux);
break;
} else {
aux = aux.getFilhoEsq();
numAtravessos++;
}
}
}
}
public static void equilibra(No tmp) {
balanco(tmp);
int balanco = tmp.balanco;
System.out.println(balanco);
if(balanco==-2)
{
if(pesagem(tmp.filhoEsq.filhoEsq)>=pesagem(tmp.filhoEsq.filhoDir))
{
tmp = rotacaoFilhoEsq(tmp);
numRotacoes++;
System.out.println("Rodou");
}
else
{
tmp = duplaRotacaoFilhoDir(tmp);
numRotacoes++;
System.out.println("Rodou");
}
}
else if(balanco==2)
{
if(pesagem(tmp.filhoDir.filhoDir)>=pesagem(tmp.filhoDir.filhoEsq))
{
tmp = rotacaoFilhoDir(tmp);
numRotacoes++;
System.out.println("Rodou");
}
else
{
tmp = duplaRotacaoFilhoEsq(tmp);
numRotacoes++;
System.out.println("Rodou");
}
}
if(tmp.pai!=null)
{
equilibra(tmp.pai);
}
else
{
raiz = tmp;
}
}
public static void mudaEstado(No novo) {
No aux = raiz;
while (true) {
if (aux.getMatricula().compareTo(novo.getMatricula()) == 0) {
aux.setEstadoRegular(true);
break;
} else if (aux.getMatricula().compareTo(novo.getMatricula()) < 0) {
if (aux.getFilhoDir() == null) {
break;
} else {
aux = aux.getFilhoDir();
numAtravessos++;
}
} else if (aux.getMatricula().compareTo(novo.getMatricula()) > 0) {
if (aux.getFilhoEsq() == null) {
break;
} else {
aux = aux.getFilhoEsq();
numAtravessos++;
}
}
}
}
public static String procuraRegisto(No novo) {
No aux = raiz;
while (true) {
if (aux.getMatricula().compareTo(novo.getMatricula()) == 0) {
return aux.toString();
} else if (aux.getMatricula().compareTo(novo.getMatricula()) < 0) {
if (aux.getFilhoDir() == null) {
return (novo.getMatricula() + " NO RECORD");
} else {
aux = aux.getFilhoDir();
numAtravessos++;
}
} else if (aux.getMatricula().compareTo(novo.getMatricula()) > 0) {
if (aux.getFilhoEsq() == null) {
return (novo.getMatricula() + " NO RECORD");
} else {
aux = aux.getFilhoEsq();
numAtravessos++;
}
}
}
}
}
The problem is that I am getting a stack overflow error:
Exception in thread "main" java.lang.StackOverflowError
at TP2_probB.pesagem(TP2_probB.java:174)
at TP2_probB.pesagem(TP2_probB.java:177)
at TP2_probB.pesagem(TP2_probB.java:177)
at TP2_probB.pesagem(TP2_probB.java:177)
(...)
at TP2_probB.pesagem(TP2_probB.java:177)
Here is a link with two files with inputs used to test the program:
https://drive.google.com/folderview?id=0B3OUu_zQ9xlGfjZHRlp6QkRkREc3dU82QmpSSWNMRlBuTUJmWTN5Ny1LaDhDN3M2WkVjYVk&usp=sharing

How can we do undo and redo functionality for a swt texteditor

I have created a swt textbox and trying to do undo and redo functionality but when i press "ctrl+z" the listener itself is not working .so how can we do undo and redo operations.the code to implement undo and redo is as follows
private static class CTabItemControl extends Composite {
private static class UndoRedoStack<T> {
private Stack<T> undo;
private Stack<T> redo;
public UndoRedoStack() {
undo = new Stack<T>();
redo = new Stack<T>();
}
public void pushUndo(T delta) {
undo.add(delta);
}
public void pushRedo(T delta) {
redo.add(delta);
}
public T popUndo() {
T res = undo.pop();
return res;
}
public T popRedo() {
T res = redo.pop();
return res;
}
public T peekUndo() {
T res = undo.peek();
return res;
}
public void clearRedo() {
redo.clear();
}
public void clearUndo() {
undo.clear();
}
public boolean hasUndo() {
return !undo.isEmpty();
}
public boolean hasRedo() {
return !redo.isEmpty();
}
}
//private StyledText editor;
private UndoRedoStack<ExtendedModifyEvent> stack;
private boolean isUndo;
private boolean isRedo;
public CTabItemControl(Composite parentComposite,final CTabItem tabitem){
super(parentComposite, SWT.NONE);
setLayout(new GridLayout(1, false));
editor = new StyledText(this, SWT.MULTI | SWT.V_SCROLL);
editor.setLayoutData(new GridData(GridData.FILL_BOTH));
editor.setFont(new Font(Display.getDefault(),"Cambria", 10, SWT.NORMAL));
editor.addListener(SWT.KeyDown, new Listener(){
public void handleEvent(Event event) {
event.doit = true;
if(!tabitem.getText().contains("*"))
{
tabitem.setText('*'+tabitem.getText());
System.out.println("inserted *");
}
}
});
editor.addExtendedModifyListener(new ExtendedModifyListener(){
//editor.addKeyListener(this);
public void modifyText(ExtendedModifyEvent event) {
if (isUndo) {
stack.pushRedo(event);
} else { // is Redo or a normal user action
stack.pushUndo(event);
if (!isRedo) {
stack.clearRedo();
}
}
}
});
editor.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
// Listen to CTRL+Z for Undo, to CTRL+Y or CTRL+SHIFT+Z for Redo
boolean isCtrl = (e.stateMask & SWT.CTRL) > 0;
boolean isAlt = (e.stateMask & SWT.ALT) > 0;
if (isCtrl && !isAlt) {
boolean isShift = (e.stateMask & SWT.SHIFT) > 0;
if (!isShift && e.keyCode == 'z') {
{
System.out.println("call undo");
undo();
}
} else if (!isShift && e.keyCode == 'y' || isShift
&& e.keyCode == 'z') {
redo();
}
}
if(e.stateMask == SWT.CTRL && e.keyCode == 'a'){
editor.selectAll();
}
}
public void keyReleased(KeyEvent e) {
// ignore
}
});
//this.editor = editor;
stack = new UndoRedoStack<ExtendedModifyEvent>();
}
private void revertEvent(ExtendedModifyEvent event) {
System.out.println("calling revertevent");
editor.replaceTextRange(event.start, event.length, event.replacedText);
// (causes the modifyText() listener method to be called)
editor.setSelectionRange(event.start, event.replacedText.length());
}
private void undo() {
System.out.println("calling undo");
if (stack.hasUndo()) {
isUndo = true;
revertEvent(stack.popUndo());
isUndo = false;
}
}
private void redo() {
if (stack.hasRedo()) {
isRedo = true;
revertEvent(stack.popRedo());
isRedo = false;
}
}
public void clearUndoRedo() {
stack.clearUndo();
stack.clearRedo();
}
public boolean hasUndo() {
return stack.hasUndo();
}
public String peekUndo() {
return stack.peekUndo().toString();
}
}
When you press Ctrl + Z or Ctrl + Y, you get 2 key events, one for Ctrl and one for another key. So it is better to check for the character of the second event
e.character == 0x1a
for Ctr + Z, and
e.character == 0x19
for Ctrl + Y

StackOverFlowError when looping through options

I'm working on an exercise and I'm running into something. The following code gives me a stackoverflow error, but I have no idea why because my code should stop.
class Options {
private int amount;
private ArrayList<Integer> pieces;
public void execute() {
pieces = new ArrayList<Integer>();
pieces.add(5);
pieces.add(2);
pieces.add(3);
amount = pieces.size();
combinations(new StringBuilder());
}
public void combinations(StringBuilder current) {
if(current.length() == pieces.size()) {
System.out.println(current.toString());
return;
}
for(int i = 0; i < amount; i++) {
current.append(pieces.get(i));
combinations(current);
}
}
}
It only prints the first output (555).
Thanks.
Add a return to end your recursion
public void combinations(StringBuilder current) {
if(current.length() == pieces.size()) {
System.out.println(current.toString());
return; // <-- like so.
}
for(int i = 0; i < amount; i++) {
current.append(pieces.get(i));
combinations(current);
}
}
or put the loop in an else like
public void combinations(StringBuilder current) {
if(current.length() == pieces.size()) {
System.out.println(current.toString());
} else {
for(int i = 0; i < amount; i++) {
current.append(pieces.get(i));
combinations(current);
}
}
}
Edit
static class Options {
private List<Integer> pieces;
public void execute() {
pieces = new ArrayList<>();
pieces.add(5);
pieces.add(2);
pieces.add(3);
combinations(new StringBuilder());
}
public void combinations(StringBuilder current) {
if (current.length() == pieces.size()) {
System.out.println(current.toString());
} else {
for (int i = current.length(); i < pieces.size(); i++) {
current.append(pieces.get(i));
combinations(current);
}
}
}
}
public static void main(String[] args) {
Options o = new Options();
o.execute();
System.out.println(o.pieces);
}
Output is
523
[5, 2, 3]

RMS stored values are not permanently available in J2ME emulator

I have code to stored the value using RMS in J2ME. It's working fine on emulator. So, my first problem is
When i restart the emulator all the stored values are deleted.
Stored values are showing in the emulator, but not in the Mobile, in which i am testing my application.
I am using NetBeans for developing my J2ME application.
===UPDATED===
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.rms.*;
public class TryNew extends MIDlet implements CommandListener, ItemCommandListener {
private RecordStore record;
private StringItem registered;
static final String REC_STORE = "SORT";
//Button existUser;
Display display = null;
private Ticker ticker;
Form form = null;
Form form1 = null;
TextField tb, tb1, tb2, tb3;
ChoiceGroup operator = null;
String str = null;
Command backCommand = new Command("Back", Command.BACK, 0);
Command loginCommand = new Command("Login", Command.OK, 2);
Command saveCommand = new Command("Save New", Command.OK, 1);
Command sendCommand = new Command("Send", Command.OK, 2);
Command selectCommand = new Command("Select", Command.OK, 0);
Command exitCommand = new Command("Exit", Command.STOP, 3);
private ValidateLogin ValidateLogin;
public TryNew() {
}
public void startApp() throws MIDletStateChangeException {
display = Display.getDisplay(this);
form = new Form("Login");
registered = new StringItem("", "Registered ?", StringItem.BUTTON);
form1 = new Form("Home");
tb = new TextField("Login Id: ", "", 10, TextField.PHONENUMBER);//TextField.PHONENUMBER
tb1 = new TextField("Password: ", "", 30, TextField.PASSWORD);
operator = new ChoiceGroup("Select Website", Choice.POPUP, new String[]{"Game", "Joke", "SMS"}, null);
form.append(tb);
form.append(tb1);
form.append(operator);
form.append(registered);
registered.setDefaultCommand(selectCommand);
registered.setItemCommandListener(this);
form.addCommand(saveCommand);
ticker = new Ticker("Welcome Screen");
form.addCommand(loginCommand);
form.addCommand(selectCommand);
form.addCommand(exitCommand);
// existUser = new StringItem(null, "Registered ?");
// form.append(existUser);
form.setCommandListener(this);
form1.addCommand(exitCommand);
form1.addCommand(sendCommand);
form1.setCommandListener(this);
form.setTicker(ticker);
display.setCurrent(form);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
void showMessage(String message, Displayable displayable) {
Alert alert = new Alert("");
alert.setTitle("Error");
alert.setString(message);
alert.setType(AlertType.ERROR);
alert.setTimeout(5000);
display.setCurrent(alert, displayable);
}
public void commandAction(Command c, Displayable d) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
} else if (c == backCommand) {
display.setCurrent(form);
} else if (c == loginCommand) {
ValidateLogin = new ValidateLogin(this);
ValidateLogin.start();
ValidateLogin.validateLogin(tb.getString(), tb1.getString(), operator.getString(operator.getSelectedIndex()));
} else if (c == saveCommand) {
openRecord();
writeRecord(tb.getString(), tb1.getString(), operator.getString(operator.getSelectedIndex()));
closeRecord();
showAlert("Login Credential Saved Successfully !!");
}
}
////==============================================================================/////
/// Record Management
public void openRecord() {
try {
record = RecordStore.openRecordStore(REC_STORE, true);
} catch (Exception e) {
db(e.toString());
}
}
public void closeRecord() {
try {
record.closeRecordStore();
} catch (Exception e) {
db(e.toString());
}
}
public void deleteRecord() {
if (RecordStore.listRecordStores() != null) {
try {
RecordStore.deleteRecordStore(REC_STORE);
} catch (Exception e) {
db(e.toString());
}
}
}
public void writeRecord(String login_id, String pwd, String operator_name) {
String credential = login_id + "," + pwd + "," + operator_name;
byte[] rec = credential.getBytes();
try {
if (login_id.length() > 10 || login_id.length() < 10) {
showAlert("Please Enter valid Login Id");
} else if (pwd.length() < 1) {
showAlert("Please Password !!");
} else {
record.addRecord(rec, 0, rec.length);
}
} catch (Exception e) {
db(e.toString());
}
}
private void showAlert(String err) {
Alert a = new Alert("");
a.setString(err);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
}
public void readRecord() {
try {
if (record.getNumRecords() > 0) {
Comparator comp = new Comparator();
RecordEnumeration re = record.enumerateRecords(null, comp, false);
while (re.hasNextElement()) {
String str = new String(re.nextRecord());
showAlert(str);
}
}
} catch (Exception e) {
db(e.toString());
}
}
private void db(String error) {
System.err.println("Exception: " + error);
}
public void commandAction(Command c, Item item) {
if (c == selectCommand && item == registered) {
openRecord();
readRecord();
closeRecord();
}
}
class Comparator implements RecordComparator {
public int compare(byte[] rec1, byte[] rec2) {
String str1 = new String(rec1);
String str2 = new String(rec2);
int result = str1.compareTo(str2);
if (result == 0) {
return RecordComparator.EQUIVALENT;
} else if (result < 0) {
return RecordComparator.PRECEDES;
} else {
return RecordComparator.FOLLOWS;
}
}
}
class ValidateLogin implements Runnable {
TryNew midlet;
private Display display;
String login_id;
String pwd;
String operator_name;
public ValidateLogin(TryNew midlet) {
this.midlet = midlet;
display = Display.getDisplay(midlet);
}
public void start() {
Thread t = new Thread(this);
t.start();
}
public void run() {
if (login_id.length() > 10 || login_id.length() < 10) {
showAlert("Please Enter valid Login Id");
} else if (pwd.length() < 1) {
showAlert("Please Password !!");
} else {
showHome();
}
}
/* This method takes input from user like text and pass
to servlet */
public void validateLogin(String login_id, String pwd, String operator_name) {
this.login_id = login_id;
this.pwd = pwd;
this.operator_name = operator_name;
}
/* Display Error On screen*/
private void showAlert(String err) {
Alert a = new Alert("");
a.setString(err);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
}
private void showHome() {
tb2 = new TextField("To: ", "", 30, TextField.PHONENUMBER);
tb3 = new TextField("Message: ", "", 300, TextField.ANY);
form1.append(tb2);
form1.append(tb3);
form1.addCommand(loginCommand);
//display.setCurrent(tb3);
display.setCurrent(form1);
}
};
}
This is what i got, when i click the Manage Emulator
You need to fix the storage_root of your app in WTK,
Whenever you start your enulator it would refer to same storage_root, by default it creates different data files for each session

GWT Suggest TextArea widget

Did anyone see Suggest or AutoComplete TextArea GWT Widget? It doesn't have to be completely the same as SuggestBox. I'm just wondering about something being out there already before I dive into developing it myself.
There is a GWT library here there is also a demo here
You also might want to check out the multi-value auto-completer from Spiffy UI. This is a newer version of the auto-completer mentioned by z00bs and part of this reusable framework.
http://www.zackgrossbart.com/hackito/gwt-rest-auto/ might be what you're looking for.
A long time ago in a project far, far away, i wrote the class that could be helpful:
public class SuggestTextArea extends TextArea {
private SuggestingPopupPanel suggestingPanel;
private SuggestTextArea textArea = this;
public SuggestTextArea(List<String> keywords) {
super();
suggestingPanel = new SuggestingPopupPanel(keywords, "suggestion");
this.getElement().setAttribute("spellcheck", "false");
this.addKeyPressHandler(new KeyPressHandler() {
public void onKeyPress(KeyPressEvent event) {
int charCode = event.getNativeEvent().getKeyCode();
if (suggestingPanel.suggestingNow) {
if (charCode == KeyCodes.KEY_ENTER || charCode == KeyCodes.KEY_TAB || event.getCharCode() == ' ') {
event.preventDefault();
suggestingPanel.insertCurrentKeyword();
return;
}
if (charCode == KeyCodes.KEY_DOWN) {
event.preventDefault();
suggestingPanel.panel.next();
return;
}
if (charCode == KeyCodes.KEY_UP) {
event.preventDefault();
suggestingPanel.panel.prev();
return;
}
} else {
// Позиции естественно посчитаны не совсем верно
int posX = textArea.getAbsoluteLeft();
int posY = textArea.getAbsoluteTop() + 20 * getCurrentLines();
suggestingPanel.setPopupPosition(posX, posY);
}
// Не предполагаем при удалении или смещении курсора
if (charCode == KeyCodes.KEY_BACKSPACE || charCode == KeyCodes.KEY_LEFT || charCode == KeyCodes.KEY_RIGHT) {
suggestingPanel.stopSuggesting();
return;
}
// События с нажатым Ctrl не обрабатываем (ну почти)
if(event.isControlKeyDown()){
if(event.getCharCode() == 'v' || event.getCharCode() == 'V'){
suggestingPanel.stopSuggesting();
}
return;
}
suggest(event.getCharCode());
}
});
}
private int getCurrentLines() {
// считает неверно если изменить размеры text area
return (this.getText().length() / this.getCharacterWidth()) + 1;
}
// Добавляет указаные символы после курсора
private void insertCharacters(String insertion) {
String text = this.getText();
int cursorPos = this.getCursorPos();
String res = text.substring(0, cursorPos) + insertion + text.substring(cursorPos);
setText(res);
setCursorPos(cursorPos + insertion.length());
suggestingPanel.stopSuggesting();
}
private void suggest(char c) {
// Отсекаем текст за курсором
int cursorPos = this.getCursorPos();
String text;
text = this.getText().substring(0, cursorPos) + (c == 0 ? "" : c);
if (text.length() == 0) {
this.suggestingPanel.setVisible(false);
return;
}
// получем вводимые символы
String keys = "";
RegExp pattern = RegExp.compile("\\b(\\w+)$", "gmi");
for (MatchResult result = pattern.exec(text); result != null; result = pattern.exec(text)) {
keys = result.getGroup(1);
}
if (!keys.equals("")) {
suggestingPanel.showMatches(keys);
}
}
// Панель для отображения предположений
class SuggestingPopupPanel extends PopupPanel {
private boolean suggestingNow = false;
private String suggestStyleName;
private List<String> keywords;
private Suggestions panel;
private List<String> currentSuggestions;
private String lastKeys;
public SuggestingPopupPanel(List<String> keywords, String suggestStyleName) {
super(true, false); // autohide, not modal
this.keywords = keywords;
this.suggestStyleName = suggestStyleName;
setVisible(false);
}
public void insertCurrentKeyword() {
insertCharacters(this.getKeywordEnd() + " ");
}
public String getKeywordEnd() {
return currentSuggestions.get(panel.current).substring(lastKeys.length());
}
public String getKeywordEnd(int index) {
return currentSuggestions.get(index).substring(lastKeys.length());
}
public void showMatches(String keys) {
lastKeys = keys;
// Получаем совпадения
List<String> suggestions = new LinkedList<String>();
RegExp pattern = RegExp.compile("\\b(" + keys + ")", "gmi");
for (String keyword : keywords) {
for (MatchResult result = pattern.exec(keyword); result != null; result = pattern.exec(keyword)) {
suggestions.add(keyword);
}
}
currentSuggestions = suggestions;
if (suggestions.isEmpty()) {
this.setVisible(false);
suggestingNow = false;
} else {
suggestingNow = true;
ArrayList<HTML> htmlList = new ArrayList<HTML>();
for (String suggestion : suggestions) {
String htmlText = HtmlHelper.getHtmlText(suggestion + "\n");
htmlText = applyStyle(htmlText, keys);
htmlList.add(new HTML(htmlText));
}
panel = new Suggestions(htmlList);
this.setWidget(panel);
this.setVisible(true);
this.show();
}
}
public void stopSuggesting(){
suggestingNow = false;
this.setVisible(false);
}
private String applyStyle(String text, String keys) {
String regex = "\\b" + keys.toLowerCase();
return text.replaceAll(regex, "<span class=\"" + suggestStyleName + "\">" + keys + "</span>");
}
// Отображает варианты
class Suggestions extends VerticalPanel {
String choosingName = "htmlFocus";
List<HTML> variants;
int current;
public Suggestions(final ArrayList<HTML> variants) {
if (variants.isEmpty()) {
return;
}
this.variants = variants;
current = 0;
variants.get(current).addStyleName(choosingName);
for (final HTML html : variants) {
html.addStyleName("suggestVariant");
// При нажатии дополняем соответсвующие символы
html.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
textArea.insertCharacters(getKeywordEnd(variants.indexOf(html)) + " ");
stopSuggesting();
}
});
this.add(html);
}
}
public void prev() {
int prev = current - 1;
if (prev < 0) {
prev = variants.size() - 1;
}
variants.get(current).removeStyleName(choosingName);
variants.get(prev).addStyleName(choosingName);
current = prev;
}
public void next() {
int next = current + 1;
if (next == variants.size()) {
next = 0;
}
variants.get(current).removeStyleName(choosingName);
variants.get(next).addStyleName(choosingName);
current = next;
}
}
}
}
Excuse me for bad formatting and russian comments, but you should get the main idea.
Have you tried passing a TextArea to the SuggestBox's constructor? (given that TextArea extends TextBoxBase)
This is my current favourite solution of this: http://jdramaix.github.com/gwtchosen/
i think u can use the "comboBox" to that. with hide the arrow and make the field editable ..

Categories