I have a table declared like this in JavaFX:
#FXML private TableView tableEF;
How can I, for example when I press a button or change a value in a ComboBox, hide it completely from the GUI, and after I press another one or change again the value in the ComboBox, make it visible again?
Edit:
public class AllController {
private RaportPDF wrpdf;
#FXML private Pagination pagination1;
#FXML private Pagination pagination2;
#FXML private Pagination pagination3;
public void updateSarcina(Observable<Sarcina> observable)
{
SarcinaService service = (SarcinaService)observable;
smodel.setAll(service.getAllSarcinas());
}
public void updatePost(Observable<Post> observable)
{
PostService service = (PostService)observable;
pmodel.setAll(service.getAllPosts());
}
public void updateFisa(Observable<Elementfisa> observable)
{
FisaService service = (FisaService)observable;
fmodel.setAll(service.getAllFisa());
}
public Observer<Sarcina> getSarcinaObserver()
{
return new Observer<Sarcina>()
{
#Override
public void update(Observable<Sarcina> observable)
{
updateSarcina(observable);
}
};
}
public Observer<Post> getPostObserver()
{
return new Observer<Post>()
{
#Override
public void update(Observable<Post> observable)
{
updatePost(observable);
}
};
}
public Observer<Elementfisa> getFisaObserver()
{
return new Observer<Elementfisa>()
{
#Override
public void update(Observable<Elementfisa> observable)
{
updateFisa(observable);
}
};
}
#SuppressWarnings("rawtypes")
#FXML private TableView allTable;
#FXML private TableView<Post> tableP;
#FXML private TableView<Sarcina> tableS;
#FXML private TableView<Elementfisa> tableEF;
#FXML private TableColumn<Sarcina, String> sFirstColumn;
#FXML private TableColumn<Sarcina, String> sSecondColumn;
#FXML private TableColumn<Post, String> pFirstColumn;
#FXML private TableColumn<Post, String> pSecondColumn;
#FXML private TableColumn<Elementfisa, String> fFirstColumn;
#FXML private TableColumn<Elementfisa, String> fSecondColumn;
#FXML private ComboBox<String> ComboObject;
#FXML private Label firstLabel;
#FXML private Label secondLabel;
#FXML private Label thirdLabel;
#FXML private TextField firstTextField;
#FXML private TextField secondTextField;
#FXML private TextField thirdTextField;
#FXML private TextField filterTextField;
#FXML private RadioButton radioButtonFirst;
#FXML private RadioButton radioButtonSecond;
#FXML private Button addButton;
#FXML private Button updateButton;
#FXML private Button deleteButton;
#FXML private Button clearFieldsButton;
#FXML private Button raportButton;
#FXML private Pagination pagination ;
SarcinaService sservice;
PostService pservice;
FisaService fservice;
ObservableList<Sarcina> smodel;
ObservableList<Post> pmodel;
ObservableList<Elementfisa> fmodel;
private String currentComboBoxString;
private Boolean isSelectedFC;
private Boolean isSelectedSC;
ToggleGroup toggleRadioGroup = new ToggleGroup();
public AllController()
{
}
private int intValidate(String e)
{
for(int i = 0; i < e.length(); i++)
{
if(i == 0 && e.charAt(i) == '-')
{
if(e.length() == 1)
{
showErrorMessage("Numar invalid !");
return -1;
}
else continue;
}
if(Character.digit(e.charAt(i), 10) < 0)
{
showErrorMessage("Numar invalid !");
return -1;
}
}
return Integer.parseInt(e);
}
private void fillItemsOnTable(boolean justColumns)
{
ObservableList<Sarcina> localModel1 = null;
ObservableList<Post> localModel2 = null;
ObservableList<Elementfisa> localModel3 = null;
if (currentComboBoxString.equals("Sarcina"))
{
tableP.setVisible(false);
tableEF.setVisible(false);
tableS.setVisible(true);
tableS.getColumns().clear();
tableS.getColumns().add(sFirstColumn);
tableS.getColumns().add(sSecondColumn);
localModel1 = this.smodel;
}
else if (currentComboBoxString.equals("Post"))
{
tableP.setVisible(true);
tableEF.setVisible(false);
tableS.setVisible(false);
tableP.getColumns().clear();
tableP.getColumns().add(pFirstColumn);
tableP.getColumns().add(pSecondColumn);
localModel2 = this.pmodel;
}
else if (currentComboBoxString.equals("Fisa"))
{
tableP.setVisible(false);
tableEF.setVisible(true);
tableS.setVisible(false);
tableEF.getColumns().clear();
tableEF.getColumns().add(fFirstColumn);
tableEF.getColumns().add(fSecondColumn);
localModel3 = this.fmodel;
}
if (!justColumns)
{
if (localModel1!=null)
{
tableS.setItems(localModel1);
tableP.setVisible(false);
tableEF.setVisible(false);
tableS.setVisible(true);
}
else
if (localModel2!=null)
{
tableP.setItems(localModel2);
tableP.setVisible(true);
tableEF.setVisible(false);
tableS.setVisible(false);
}
else
{
tableEF.setItems(localModel3);
tableP.setVisible(false);
tableEF.setVisible(true);
tableS.setVisible(false);
}
}
}
#FXML public void handleRaport()
{
if (isSelectedFC)
{
ObservableList<Sarcina> model = FXCollections.observableArrayList(fservice.filterRapoarte());
ComboObject.setValue("Sarcina");
this.fillItemsOnTable(true);
tableS.setItems(model);
wrpdf.addPdf(model);
}
}
public void setService(SarcinaService sservice, PostService pservice, FisaService fservice)
{
this.sservice = sservice;
this.pservice = pservice;
this.fservice = fservice;
this.smodel = FXCollections.observableArrayList(sservice.getAllSarcinas());
this.pmodel = FXCollections.observableArrayList(pservice.getAllPosts());
this.fmodel = FXCollections.observableArrayList(fservice.getAllFisa());
this.fillItemsOnTable(false);
}
#FXML private void onActionComboBox(ActionEvent event)
{
String current = ComboObject.getSelectionModel().getSelectedItem();
if (current.compareTo(currentComboBoxString) != 0)
{
currentComboBoxString = current;
if (current.equals("Sarcina"))
{
secondLabel.setText("Desc: ");
radioButtonSecond.setText("By Desc");
thirdLabel.setVisible(false);
radioButtonFirst.setVisible(false);
thirdTextField.setVisible(false);
}
else if (current.equals("Post"))
{
secondLabel.setText("Name: ");
thirdLabel.setText("Type: ");
radioButtonFirst.setText("By Name");
radioButtonSecond.setText("By Type");
thirdLabel.setVisible(true);
radioButtonFirst.setVisible(true);
thirdTextField.setVisible(true);
}
else if (current.equals("Fisa"))
{
secondLabel.setText("Sarcina ID: ");
thirdLabel.setText("Post ID: ");
radioButtonFirst.setText("By Sarcina");
radioButtonSecond.setText("By Post");
thirdLabel.setVisible(true);
radioButtonFirst.setVisible(true);
thirdTextField.setVisible(true);
}
this.fillItemsOnTable(false);
}
}
#FXML private void initialize()
{
pagination1.setPageFactory(this::createPageP);
pagination2.setPageFactory(this::createPageS);
pagination3.setPageFactory(this::createPageEF);
ComboObject.getItems().addAll
(
"Sarcina",
"Post",
"Fisa"
);
currentComboBoxString = "Sarcina";
ComboObject.setValue("Sarcina");
thirdLabel.setVisible(false);
radioButtonFirst.setVisible(false);
thirdTextField.setVisible(false);
isSelectedFC = true;
isSelectedSC = false;
radioButtonFirst.setToggleGroup(toggleRadioGroup);
radioButtonSecond.setToggleGroup(toggleRadioGroup);
radioButtonFirst.setSelected(true);
if (currentComboBoxString.equals("Post"))
{
tableP.getSelectionModel().selectedItemProperty().addListener((obs, oldSelection, newSelection) -> {
if (newSelection != null)
{
if (currentComboBoxString.equals("Post"))
{
firstTextField.setText(((Post) newSelection).getId().toString());
secondTextField.setText(((Post) newSelection).getNume());
thirdTextField.setText(((Post) newSelection).getTip());
}
}
});
}
else
if (currentComboBoxString.equals("Sarcina"))
{
tableS.getSelectionModel().selectedItemProperty().addListener((obs, oldSelection, newSelection) -> {
if (newSelection != null)
{
if (currentComboBoxString.equals("Sarcina"))
{
firstTextField.setText(((Sarcina) newSelection).getId().toString());
secondTextField.setText(((Sarcina) newSelection).getDesc());
}
}
});
}
else
if (currentComboBoxString.equals("Fisa"))
{
tableEF.getSelectionModel().selectedItemProperty().addListener((obs, oldSelection, newSelection) -> {
if (newSelection != null)
{
if (currentComboBoxString.equals("Fisa"))
{
firstTextField.setText(((Elementfisa) newSelection).getId().toString());
secondTextField.setText(((Elementfisa) newSelection).getSarcina().getId().toString());
thirdTextField.setText(((Elementfisa) newSelection).getPost().getId().toString());
}
}
});
}
}
public int itemsPerPage()
{
return 1;
}
public int rowsPerPage()
{
return 7;
}
#SuppressWarnings("unchecked")
public VBox createPageS(int pageIndex)
{
int lastIndex = 0;
int displace = smodel.size() % rowsPerPage();
if (displace > 0) {
lastIndex = smodel.size() / rowsPerPage();
} else {
lastIndex = smodel.size() / rowsPerPage() - 1;
}
VBox box = new VBox(7);
int page = pageIndex * itemsPerPage();
for (int i = page; i < page + itemsPerPage(); i++) {
TableView<Sarcina> tableS = new TableView<Sarcina>();
sFirstColumn.setCellValueFactory(
new PropertyValueFactory<Sarcina, String>("Id"));
sFirstColumn.setMinWidth(20);
sSecondColumn.setCellValueFactory(
new PropertyValueFactory<Sarcina, String>("desc"));
sSecondColumn.setMinWidth(160);
tableS.getColumns().addAll(sFirstColumn, sSecondColumn);
if (lastIndex == pageIndex) {
tableS.setItems(FXCollections.observableArrayList(smodel.subList(pageIndex * rowsPerPage(), pageIndex * rowsPerPage() + displace)));
} else {
tableS.setItems(FXCollections.observableArrayList(smodel.subList(pageIndex * rowsPerPage(), pageIndex * rowsPerPage() + rowsPerPage())));
}
box.getChildren().add(tableS);
}
pagination2.setPageCount(smodel.size()/7+1);
return box;
}
#SuppressWarnings("unchecked")
public VBox createPageP(int pageIndex)
{
int lastIndex = 0;
int displace = pmodel.size() % rowsPerPage();
if (displace > 0) {
lastIndex = pmodel.size() / rowsPerPage();
} else {
lastIndex = pmodel.size() / rowsPerPage() - 1;
}
VBox box = new VBox(7);
int page = pageIndex * itemsPerPage();
for (int i = page; i < page + itemsPerPage(); i++) {
TableView<Post> tableP = new TableView<Post>();
pFirstColumn.setCellValueFactory(
new PropertyValueFactory<Post, String>("nume"));
pFirstColumn.setMinWidth(20);
pSecondColumn.setCellValueFactory(
new PropertyValueFactory<Post, String>("tip"));
pSecondColumn.setMinWidth(160);
tableP.getColumns().addAll(pFirstColumn, pSecondColumn);
if (lastIndex == pageIndex)
{
tableP.setItems(FXCollections.observableArrayList(pmodel.subList(pageIndex * rowsPerPage(), pageIndex * rowsPerPage() + displace)));
} else {
tableP.setItems(FXCollections.observableArrayList(pmodel.subList(pageIndex * rowsPerPage(), pageIndex * rowsPerPage() + rowsPerPage())));
}
pagination1.setPageCount(pmodel.size()/7+1);
box.getChildren().add(tableP);
}
return box;
}
public VBox createPageEF(int pageIndex)
{
int lastIndex = 0;
int displace = fmodel.size() % rowsPerPage();
if (displace > 0) {
lastIndex = fmodel.size() / rowsPerPage();
} else {
lastIndex = fmodel.size() / rowsPerPage() - 1;
}
VBox box = new VBox(7);
int page = pageIndex * itemsPerPage();
for (int i = page; i < page + itemsPerPage(); i++)
{
fFirstColumn.setCellValueFactory(new Callback<CellDataFeatures<Elementfisa, String>, ObservableValue<String>>()
{
public ObservableValue<String> call(CellDataFeatures<Elementfisa, String> p)
{
if (p.getValue() != null && p.getValue().getSarcina() != null)
{
return new SimpleStringProperty(p.getValue().getSarcina().getDesc());
} else
{
return new SimpleStringProperty("Empty");
}
}
});
fSecondColumn.setCellValueFactory(new Callback<CellDataFeatures<Elementfisa, String>, ObservableValue<String>>()
{
public ObservableValue<String> call(CellDataFeatures<Elementfisa, String> p)
{
if (p.getValue() != null && p.getValue().getPost() != null)
{
return new SimpleStringProperty(p.getValue().getPost().getNume());
} else
{
return new SimpleStringProperty("Empty");
}
}
});
fFirstColumn.setMinWidth(20);
fSecondColumn.setMinWidth(160);
if (lastIndex == pageIndex) {
tableEF.setItems(FXCollections.observableArrayList(fmodel.subList(pageIndex * rowsPerPage(), pageIndex * rowsPerPage() + displace)));
} else if (lastIndex == pageIndex && lastIndex!=0 && pageIndex!=0) {
tableEF.setItems(FXCollections.observableArrayList(fmodel.subList(pageIndex * rowsPerPage(), pageIndex * rowsPerPage() + rowsPerPage())));
}
pagination3.setPageCount(fmodel.size()/7+1);
box.getChildren().add(tableEF);
}
return box;
}
private void clearFields()
{
firstTextField.setText("");
secondTextField.setText("");
thirdTextField.setText("");
}
#FXML public void handleAdd()
{
String id = firstTextField.getText();
String first = secondTextField.getText();
String sec = thirdTextField.getText();
int vid = intValidate(id);
if (vid == -1)
return;
if (currentComboBoxString.equals("Sarcina"))
{
Sarcina s = new Sarcina(Integer.parseInt(id), first);
try {
if (sservice.findOne(s.getId()) == null)
{
sservice.save(s);
showMessage(Alert.AlertType.INFORMATION, "Salvare cu succes", "Sarcina a fost adaugat!");
clearFields();
}
else
showErrorMessage("Exista deja o sarcina cu acest id !");
}catch(ValidatorException e)
{
showErrorMessage(e.getMessage());
}
}
else if (currentComboBoxString.equals("Post"))
{
Post p = new Post(Integer.parseInt(id), first, sec);
try {
if (pservice.findOne(p.getId()) == null)
{
pservice.save(p);
showMessage(Alert.AlertType.INFORMATION, "Salvare cu succes", "Post-ul a fost adaugat!");
clearFields();
}
else
showErrorMessage("Exista deja un post cu acest id !");
}catch(ValidatorException e)
{
showErrorMessage(e.getMessage());
}
}
else if (currentComboBoxString.equals("Fisa"))
{
try {
Sarcina s = sservice.findOne(Integer.parseInt(first));
Post p = pservice.findOne(Integer.parseInt(sec));
if (s == null || p == null)
{
showErrorMessage("Id-ul sarcinii sau postului nu exista !");
return;
}
Elementfisa f = new Elementfisa(Integer.parseInt(id), p, s);
if (fservice.findOne(f.getId()) == null)
{
fservice.save(f);
showMessage(Alert.AlertType.INFORMATION, "Salvare cu succes", "Fisa a fost adaugat!");
clearFields();
}
else
showErrorMessage("Exista deja o fisa cu acest id !");
} catch (ValidatorException e)
{
showErrorMessage(e.getMessage());
}
}
}
#FXML public void handleUpdate()
{
String id = firstTextField.getText();
String first = secondTextField.getText();
String sec = thirdTextField.getText();
int vid = intValidate(id);
if (vid == -1)
return;
if (currentComboBoxString.equals("Sarcina"))
{
Sarcina s = new Sarcina(Integer.parseInt(id), first);
try {
Sarcina updated = sservice.update(s);
if (updated != null)
{
showMessage(Alert.AlertType.INFORMATION, "Actualizare cu succes", "Sarcina a fost actualizata!");
clearFields();
}
else
showErrorMessage("Eroare la actualizare !");
} catch (ValidatorException e)
{
showErrorMessage(e.getMessage());
}
}
else if (currentComboBoxString.equals("Post"))
{
Post p = new Post(Integer.parseInt(id), first, sec);
try {
Post updated = pservice.update(p);
if (updated != null)
{
showMessage(Alert.AlertType.INFORMATION, "Actualizare cu succes", "Postul a fost actualizat!");
clearFields();
}
else
showErrorMessage("Eroare la actualizare !");
} catch (ValidatorException e)
{
showErrorMessage(e.getMessage());
}
}
else if (currentComboBoxString.equals("Fisa"))
{
try {
Sarcina s = sservice.findOne(Integer.parseInt(first));
Post p = pservice.findOne(Integer.parseInt(sec));
if (s == null || p == null)
{
showErrorMessage("Id-ul sarcinii sau postului nu exista !");
return;
}
Elementfisa f = new Elementfisa(Integer.parseInt(id), p, s);
Elementfisa updated = fservice.update(f);
if (updated != null)
{
showMessage(Alert.AlertType.INFORMATION, "Actualizare cu succes", "Fisa a fost actualizata!");
clearFields();
}
else
showErrorMessage("Eroare la actualizare !");
}catch (ValidatorException e)
{
showErrorMessage(e.getMessage());
}
}
}
#FXML public void handleDelete()
{
if (currentComboBoxString.equals("Sarcina"))
{
Sarcina s = (Sarcina) tableS.getSelectionModel().getSelectedItem();
try
{
sservice.delete(s);
showMessage(Alert.AlertType.INFORMATION, "Stergere cu succes", "Sarcina a fost stersa !");
clearFields();
} catch (ValidatorException e) {
showErrorMessage(e.getMessage());
}
}
else if (currentComboBoxString.equals("Post"))
{
Post p = (Post) tableP.getSelectionModel().getSelectedItem();
try
{
pservice.delete(p);
showMessage(Alert.AlertType.INFORMATION, "Stergere cu succes", "Postul a fost sters !");
clearFields();
} catch (ValidatorException e)
{
showErrorMessage(e.getMessage());
}
}
else if (currentComboBoxString.equals("Fisa"))
{
Elementfisa f = (Elementfisa) tableEF.getSelectionModel().getSelectedItem();
try
{
fservice.delete(f);
showMessage(Alert.AlertType.INFORMATION, "Stergere cu succes", "Fisa a fost stersa !");
clearFields();
} catch (ValidatorException e)
{
showErrorMessage(e.getMessage());
}
}
}
#FXML public void handleClearFields()
{
clearFields();
}
#FXML public void handleToggleButton()
{
isSelectedFC = radioButtonFirst.isSelected();
isSelectedSC = radioButtonSecond.isSelected();
}
#FXML public void handleFilterColumn()
{
String what = filterTextField.getText();
try
{
if (currentComboBoxString.equals("Sarcina"))
{
if (what.equals(""))
{
tableS.setItems(smodel);
return;
}
if (isSelectedFC)
{
showErrorMessage("N/A for Sarcina !");
return;
}
else if (isSelectedSC)
{
ObservableList<Sarcina> model = FXCollections.observableArrayList(sservice.filterSarcinaDesc(what));
tableS.setItems(model);
}
}
else if (currentComboBoxString.equals("Post"))
{
if (what.equals(""))
{
tableP.setItems(pmodel);
return;
}
if (isSelectedFC)
{
ObservableList<Post> model = FXCollections.observableArrayList(pservice.filterPostNume(what));
tableP.setItems(model);
}
else if (isSelectedSC)
{
ObservableList<Post> model = FXCollections.observableArrayList(pservice.filterPostTip(what));
tableP.setItems(model);
}
}
else if (currentComboBoxString.equals("Fisa"))
{
if (what.equals(""))
{
ComboObject.setValue("Fisa");
tableS.setItems(smodel);
return;
}
int vid = intValidate(what);
if (vid == -1)
return;
if (isSelectedFC)
{
Sarcina s = sservice.findOne(Integer.parseInt(what));
ObservableList<Sarcina> model = FXCollections.observableArrayList(fservice.filterElementSarcina(s));
ComboObject.setValue("Sarcina");
this.fillItemsOnTable(true);
tableS.setItems(model);
}
else if (isSelectedSC)
{
Post p = pservice.findOne(Integer.parseInt(what));
ObservableList<Post> model = FXCollections.observableArrayList(fservice.filterElementPost(p));
ComboObject.setValue("Fisa");
this.fillItemsOnTable(true);
tableP.setItems(model);
}
}
}
catch(ValidatorException e)
{
showErrorMessage(e.getMessage());
}
}
static void showMessage(Alert.AlertType type, String header, String text)
{
Alert message=new Alert(type);
message.setHeaderText(header);
message.setContentText(text);
message.showAndWait();
}
static void showErrorMessage(String text)
{
Alert message=new Alert(Alert.AlertType.ERROR);
message.setTitle("Mesaj eroare");
message.setContentText(text);
message.showAndWait();
}
}
Edit2: The question "JavaFX - setVisible doesnt “hide” the element" isn't a solution because for him the setInvisible works, since it makes the vBox invisible, just doesn't move another one in it's place. Also I already tried the solution proposed there, nothing worked.
Also I noticed that the table Fisa (tableEF), hides itself when I change the value in the ComboBox.
private final BooleanProperty tableHidden;
public AllController()
{
this.tableHidden = new SimpleBooleanProperty(false);
this.tableEF.visibleProperty().bind(this.tableHiddenProperty());
this.tableEF.managedProperty().bind(this.tableHiddenProperty().not());
// ...
}
// Standard FX property setter/getter...
public void makeTableHidden()
{
this.setTableHidden(true);
// ...
}
Of course, you can choose not to have a property and directly set visibleProperty and managedProperty of the TableView, but I thought it is neater (personal opinion) to do it this way.
Edit
These are standard naming conventions for getters/setters of JavaFX properties (see Example 1).
The table's visibility is also one example of such property; its private property (which you cannot see) is called visible, its public version (which you can see) is visibleProperty, and its getter/setter are isVisible and setVisible respectively.
This is the extra piece of codes that you need to have (which I had assumed you had known how to generate one on your own).
public final BooleanProperty tableHiddenProperty()
{
return this.tableHidden;
}
public final boolean isTableHidden()
{
return this.tableHiddenProperty().get;
}
public final void setTableHidden(final boolean value)
{
this.tableHiddenProperty().set(value);
}
Related
I know my problem is trivilant and solution is on the surface, but I still can't deal with it and so need help. The problem is that TableView ListChangeListener in my code does not show updated changes. I have read many topics, manuals and examples before asked a question
Javafx: Detect ALL changes made to tableView including addition/deletion of table rows and cell edits on any table rows
Java ListChangeListener WasUpdated() doesn't work
https://docs.oracle.com/javase/8/javafx/api/javafx/collections/ListChangeListener.Change.html#wasUpdated--
http://java-buddy.blogspot.com/2014/11/example-of-listchangelistener-for.html
but still can't understand why my code does not work. I have added extractor but it's not helped me.
Here is a part of my code
public class mainTableOverviewController {
#FXML
private TableView<EmailData> emailTableView;
#FXML
private TableColumn<EmailData, String> emailNameColumn;
#FXML
private TableColumn<EmailData, String> emailLoginColumn;
#FXML
private TableColumn<EmailData, String> emailPasswordColumn;
#FXML
private TableColumn<EmailData, String> emailCommentsColumn;
#FXML
private Button handleDeletePerson;
private MainApp mainApp;
public mainTableOverviewController() {
}
#FXML
private void initialize() {
emailTableView.setEditable(true);
emailTableView.getSelectionModel().setCellSelectionEnabled(true);
emailTableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
Callback<TableColumn<EmailData, String>, TableCell<EmailData, String>> cellFactory =
new Callback<TableColumn<EmailData, String>, TableCell<EmailData, String>>() {
public TableCell call(TableColumn p) {
return new EditingCell();
}
};
emailNameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
emailNameColumn.setCellFactory(cellFactory);
emailNameColumn.setOnEditCommit(
t -> t.getTableView().getItems().get(
t.getTablePosition().getRow()).setName(t.getNewValue())
);
emailLoginColumn.setCellValueFactory(cellData -> cellData.getValue().loginProperty());
emailLoginColumn.setCellFactory(cellFactory);
emailLoginColumn.setOnEditCommit(
t -> t.getTableView().getItems().get(
t.getTablePosition().getRow()).setLogin(t.getNewValue())
);
emailPasswordColumn.setCellValueFactory(cellData -> cellData.getValue().passwordProperty());
emailPasswordColumn.setCellFactory(cellFactory);
emailPasswordColumn.setOnEditCommit(
t -> t.getTableView().getItems().get(
t.getTablePosition().getRow()).setPassword(t.getNewValue())
);
emailCommentsColumn.setPrefWidth(120);
emailCommentsColumn.setCellValueFactory(cellData -> cellData.getValue().commentsProperty());
emailCommentsColumn.setCellFactory(cellFactory);
emailCommentsColumn.setOnEditCommit(
t -> t.getTableView().getItems().get(
t.getTablePosition().getRow()).setComments(t.getNewValue())
);
emailData.addListener((Change<? extends EmailData> c) -> {
while (c.next()) {
if (c.wasAdded()) {
System.out.println("Added:");
c.getAddedSubList().forEach(System.out::println);
System.out.println();
}
if (c.wasRemoved()) {
System.out.println("Removed:");
c.getRemoved().forEach(System.out::println);
System.out.println();
}
if (c.wasUpdated()) {
System.out.println("Updated:");
emailData.subList(c.getFrom(), c.getTo()).forEach(System.out::println);
System.out.println();
}
}
});
emailTableView.getColumns().setAll(emailNameColumn, emailLoginColumn, emailPasswordColumn, emailCommentsColumn, actionCol);
}
}
#FXML
private void handleDeletePerson() {
int selectedIndex = emailTableView.getSelectionModel().getSelectedIndex();
if (selectedIndex >= 0) {
deletedDataList.add(emailTableView.getItems().get(selectedIndex));
emailTableView.getItems().remove(selectedIndex);
menuItemDisable.set(false);
} else {
nothingSelected();
}
}
class EditingCell extends TableCell<EmailData, String> {
TextField textField;
EditingCell() {
}
#Override
public void startEdit() {
if (!isEmpty()) {
super.startEdit();
if (textField == null) {
createTextField();
}
setGraphic(textField);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
Platform.runLater(new Runnable() {
#Override
public void run() {
textField.requestFocus();
textField.selectAll();
}
});
}
}
#Override
public void cancelEdit() {
super.cancelEdit();
setText((String) getItem());
setGraphic(null);
}
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
if (textField != null) {
textField.setText(getString());
}
setGraphic(textField);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
} else {
emailTableView.getColumns().get(0).setVisible(false);
emailTableView.getColumns().get(0).setVisible(true);
setText(getString());
setContentDisplay(ContentDisplay.TEXT_ONLY);
}
}
}
private void createTextField() {
textField = new TextField(getString());
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap()
* 2);
textField.focusedProperty().addListener(
new ChangeListener<Boolean>() {
#Override
public void changed(
ObservableValue<? extends Boolean> arg0,
Boolean arg1, Boolean arg2) {
if (!arg2) {
commitEdit(textField.getText());
}
}
});
textField.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent t) {
if (t.getCode() == KeyCode.ENTER) {
commitEdit(textField.getText());
} else if (t.getCode() == KeyCode.ESCAPE) {
cancelEdit();
} else if (t.getCode() == KeyCode.TAB) {
commitEdit(textField.getText());
TableColumn nextColumn = getNextColumn(!t.isShiftDown());
if (nextColumn != null) {
getTableView().edit(getTableRow().getIndex(),
nextColumn);
}
}
}
});
}
private String getString() {
return getItem() == null ? "" : getItem();
}
private TableColumn<EmailData, ?> getNextColumn(boolean forward) {
List<TableColumn<EmailData, ?>> columns = new ArrayList<>();
for (TableColumn<EmailData, ?> column : getTableView().getColumns()) {
columns.addAll(getLeaves(column));
}
// There is no other column that supports editing.
if (columns.size() < 2) {
return null;
}
int nextIndex = columns.indexOf(getTableColumn());
if (forward) {
nextIndex++;
if (nextIndex > columns.size() - 1) {
nextIndex = 0;
}
} else {
nextIndex--;
if (nextIndex < 0) {
nextIndex = columns.size() - 1;
}
}
return columns.get(nextIndex);
}
private List<TableColumn<EmailData, ?>> getLeaves(
TableColumn<EmailData, ?> root) {
List<TableColumn<EmailData, ?>> columns = new ArrayList<>();
if (root.getColumns().isEmpty()) {
if (root.isEditable()) {
columns.add(root);
}
return columns;
} else {
for (TableColumn<EmailData, ?> column : root.getColumns()) {
columns.addAll(getLeaves(column));
}
return columns;
}
}
}
}
And the Class where list declaration are:
public class MainApp extends Application {
public static ObservableList<EmailData> backupList = FXCollections.observableArrayList();
public static ObservableList<EmailData> emailData = FXCollections.observableArrayList(ed ->
new Observable[]{
ed.nameProperty(),
ed.loginProperty(),
ed.passwordProperty(),
ed.commentsProperty()
});
private BorderPane rootLayout;
public MainApp() {
}
public static void readCryptedData(String s) {
try {
switch (s) {
case "initData":
emailData = readDataFromStream(decryptFileBytes(libraryPath, salt, nonce));
break;
default:
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
launch(args);
}
public static ObservableList<EmailData> getEmailData() {
return emailData;
}
#Override
public void start(Stage primaryStage) {
MainApp.primaryStage = primaryStage;
MainApp.primaryStage.setResizable(false);
MainApp.primaryStage.getIcons().add(new Image(imageFile.toURI().toString()));
initRootLayout();
try {
showFirstView();
} catch (IOException e) {
e.printStackTrace();
}
}
private void initRootLayout() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource("/fxml/RootLayout.fxml"));
rootLayout = loader.load();
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
primaryStage.show();
menuItemDisable.set(true);
} catch (IOException e) {
e.printStackTrace();
}
}
public Stage getPrimaryStage() {
return primaryStage;
}
#Override
public void stop() {
if (emailData.size() != 0) {
saveDataToFile();
}
}
}
I will much appreciated for any help.
After looking for comments and minuses to my question, I saw that I need to search a problem in my code by myself. Hope somebody will find this question and answer usefull.
The problem was in my read method readDataFromStream(). Before reading topics mentioned above I used such way declaration of ObservableList
public static ObservableList<EmailData> emailData = FXCollections.observableArrayList();
And my readDataFromStream looked like:
public static ObservableList<EmailData> readDataFromStream(byte[] bytes) {
ObservableList<EmailData> emailData = FXCollections.observableArrayList();
try {
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis);
List<EmailData> list = (List<EmailData>) ois.readObject();
emailData = FXCollections.observableList(list);
bis.close();
ois.close();
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
return emailData;
}
And then I have read that I need create the list with an extractor. And I changed ObservableList declaration to:
ObservableList<EmailData> emailData = FXCollections.observableArrayList(ed ->
new Observable[]{
ed.nameProperty(),
ed.loginProperty(),
ed.passwordProperty(),
ed.commentsProperty()
});
but my readDataFromStream() method remained the same. Now I changed it to:
public static ObservableList<EmailData> readDataFromStream(byte[] bytes) {
ObservableList<EmailData> emailData = FXCollections.observableArrayList(ed ->
new Observable[]{
ed.nameProperty(),
ed.loginProperty(),
ed.passwordProperty(),
ed.commentsProperty()
});
try {
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis);
List<EmailData> list = (List<EmailData>) ois.readObject();
emailData = FXCollections.observableList(
list,
(EmailData tp) -> new Observable[]{tp.nameProperty(), tp.passwordProperty(),
tp.loginProperty(), tp.commentsProperty()});
bis.close();
ois.close();
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
return emailData;
}
and wasUpdated() method of ListChangeListener.Change now works like a charm.
Hope it will help newbies like me.
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
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
I am making an autocomplete application and the list of my words are coming from my database. I have a textfield and now I want to make a suggestion list that will appear below the field everytime I type something. Could you give me some hint or idea how to do it? Thanks in advance.
Much better if you use JCombobox but if you are using Jtextfield, I would rather suggest to you to use Jlist and put in JWindow since you are using textfield, thats what I've tried in my Dictionary application.
EDIT :
public class MainMenu extends JPanel
{
private final Connection connection;
private final Application application;
private JTextField word = new JTextField(10);
private final JButton translate = new JButton();
private final JComboBox translators = new JComboBox();
private final JButton search = new JButton();
private JList speechPartAndDefinitionWidget;
private final DefaultListModel speechPartAndDefinitionWidgetModel = new DefaultListModel();
private Translator translator;
private Suggestor suggestor;
private DefaultListModel translatedWidgetModel;
private JList translatedWidget;
private final DefaultListModel suggestionWidgetModel = new DefaultListModel();
private final JList suggestionWidget = new JList(suggestionWidgetModel);
private JavaWindow javaWindow = new JavaWindow(suggestionWidget);
public MainMenu(Application application, Connection connection)
{
word.getDocument().addDocumentListener(new DocumentListener()
{
public void insertUpdate(DocumentEvent e)
{
try
{
onWordUpdated(word.getText());
}
catch (ClassNotFoundException e1)
{
e1.printStackTrace();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
public void removeUpdate(DocumentEvent e)
{
try
{
onWordUpdated(word.getText());
}
catch (ClassNotFoundException e1)
{
e1.printStackTrace();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
public void changedUpdate(DocumentEvent e)
{
try
{
onWordUpdated(word.getText());
}
catch (ClassNotFoundException e1)
{
e1.printStackTrace();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
});
this.application = application;
this.connection = connection;
translators.setFocusable(false);
word.grabFocus();
word.requestFocus();
word.setFocusable(true);
search.setText("<html><b><u>S</u>earch</b></html>");
translate.setText("<html><b><u>T</u>ranslate</b></html>");
translators.addItem(new EnglishBisayaTranslator(connection));
setToolTipText("English-Bisaya");
translators.addItem(new BisayaEnglishTranslator(connection));
setToolTipText("Bisaya-English");
setLayout(new BorderLayout());
JPanel formX = new JPanel();
formX.setLayout(new BorderLayout());
JPanel header = new JPanel();
header.setLayout(new GridBagLayout());
header.add(translators);
header.add(word);
header.add(search);
header.add(translate);
translators.setBorder(BorderFactory.createEtchedBorder(1));
translators.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10));
word.setBorder(BorderFactory.createEtchedBorder());
word.setBorder(BorderFactory.createLineBorder(Color.gray, 1));
word.setFont(new Font("Garamond", Font.BOLD, 17));
suggestionWidget.setFont(new Font("Calibri", Font.BOLD, 17));
header.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 8));
formX.add(BorderLayout.PAGE_START, header);
formX.setBorder(BorderFactory.createEmptyBorder(10, 15, 10, 10));
add(header, BorderLayout.NORTH);
speechPartAndDefinitionWidget = new JList(speechPartAndDefinitionWidgetModel);
speechPartAndDefinitionWidget.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
speechPartAndDefinitionWidget.addListSelectionListener(new ListSelectionListener()
{
public void valueChanged(ListSelectionEvent ev)
{
onDefinitionSelected(ev);
}
});
JPanel formBottom = new JPanel();
formBottom.setLayout(new GridBagLayout());
add(formBottom, BorderLayout.CENTER);
Component up = new JScrollPane(speechPartAndDefinitionWidget);
formBottom.setBorder(BorderFactory.createEmptyBorder(20, 10, 10, 10)); speechPartAndDefinitionWidget.setBorder(BorderFactory.createLineBorder(Color.black,1));
JPanel down = new JPanel();
down.setLayout(new BorderLayout());
down.setBorder(BorderFactory.createLineBorder(Color.black, 1));
down.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
down.add(translatedWidget = new JList(translatedWidgetModel = new DefaultListModel()));
add(down, BorderLayout.CENTER);
translatedWidget.setBorder(BorderFactory.createLineBorder(Color.black, 1));
translatedWidget.setFont(new Font("Calibri",Font.BOLD, 17));
speechPartAndDefinitionWidget.setFont(new Font("Calibri", Font.BOLD, 17));
add(BorderLayout.CENTER, new JSplitPane(JSplitPane.VERTICAL_SPLIT, up, down));
word.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
{
hideSuggestionWindowToBack();
}
else if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
int selectedIndex = suggestionWidget.getSelectedIndex();
if (selectedIndex == -1)
{
onSearchClick();
}
else
{
onSuggestionSelected(selectedIndex);
}
}
}
public void keyReleased(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
hideSuggestionWindowToBack();
onSearchClick();
}
}
});
translators.addActionListener(new
ActionListener()
{
public void actionPerformed
(ActionEvent e)
{
onTranslatorsClick();
}
}
);
word.addKeyListener(new
KeyAdapter()
{
public void keyPressed
(KeyEvent
e)
{
if (suggestionWidgetModel.isEmpty())
{
return;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN)
{
final Point location = word.getLocationOnScreen();
javaWindow.setLocation(location.x, location.y + word.getHeight());
showSuggestionWindowToBack();
int currentSelectedItemIndex = suggestionWidget.getSelectedIndex();
if (currentSelectedItemIndex == -1 || currentSelectedItemIndex == suggestionWidgetModel.size() - 1)
{
suggestionWidget.setSelectedIndex(0);
}
else if (currentSelectedItemIndex < suggestionWidgetModel.size() - 1)
{
suggestionWidget.setSelectedIndex(currentSelectedItemIndex + 1);
}
}
else if (e.getKeyCode() == KeyEvent.VK_UP)
{
int currentSelectedItemIndex = suggestionWidget.getSelectedIndex();
if (currentSelectedItemIndex == -1 || currentSelectedItemIndex == suggestionWidgetModel.size() + 1)
{
suggestionWidget.setSelectedIndex(0);
}
else if (currentSelectedItemIndex < suggestionWidgetModel.size() + 1)
{
suggestionWidget.setSelectedIndex(currentSelectedItemIndex - 1);
}
}
}
}
);
suggestionWidget.addMouseListener(new MouseAdapter()
{
#Override
public void mousePressed(MouseEvent e)
{
int selectedIndex = suggestionWidget.getSelectedIndex();
if (e.getClickCount() == 2)
{
if (selectedIndex < -1)
{
onSearchClick();
}
else
{
onSuggestionSelected(selectedIndex);
hideSuggestionWindowToBack();
}
}
}
public void mouseReleased(MouseEvent e)
{
if (e.getClickCount() == 2)
{
{
hideSuggestionWindowToBack();
}
}
}
});
speechPartAndDefinitionWidget.addKeyListener(new
KeyAdapter()
{
#Override
public void keyPressed
(KeyEvent
e)
{
if (speechPartAndDefinitionWidgetModel.isEmpty())
{
return;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN)
{
int currentSelectedItemIndex = speechPartAndDefinitionWidget.getSelectedIndex();
if (currentSelectedItemIndex == -1 || currentSelectedItemIndex == speechPartAndDefinitionWidgetModel.size() - 1)
{
speechPartAndDefinitionWidget.setSelectedIndex(0);
}
else if (currentSelectedItemIndex < speechPartAndDefinitionWidgetModel.size() - 1)
{
speechPartAndDefinitionWidget.setSelectedIndex(currentSelectedItemIndex + 1);
onTranslate();
}
}
else if (e.getKeyCode() == KeyEvent.VK_UP)
{
int currentSelectedItemIndex = speechPartAndDefinitionWidget.getSelectedIndex();
if (currentSelectedItemIndex == -1 || currentSelectedItemIndex == speechPartAndDefinitionWidgetModel.size() + 1)
{
speechPartAndDefinitionWidget.setSelectedIndex(0);
}
else if (currentSelectedItemIndex < speechPartAndDefinitionWidgetModel.size() + 1)
{
speechPartAndDefinitionWidget.setSelectedIndex(currentSelectedItemIndex - 1);
}
}
}
}
);
speechPartAndDefinitionWidget.addMouseMotionListener(new MouseMotionAdapter()
{
#Override
public void mouseMoved(MouseEvent e)
{
final int x = e.getX();
final int y = e.getY();
final Rectangle cellBounds = speechPartAndDefinitionWidget.getCellBounds(0, speechPartAndDefinitionWidget.getModel().getSize() - 1);
if (cellBounds != null && cellBounds.contains(x, y))
{
speechPartAndDefinitionWidget.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
else
{
speechPartAndDefinitionWidget.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
}
}
);
speechPartAndDefinitionWidget.setCellRenderer(new
DefaultListCellRenderer()
{
#Override
public Component getListCellRendererComponent
(JList
list, Object
value, int index,
boolean isSelected,
boolean cellHasFocus)
{
final String speechPart = ((DefinitionUiModel) value).getPart().getFriendlyName();
final String definition = ((DefinitionUiModel) value).getDefinition().toString();
Color bg = null;
Color fg = null;
final JLabel renderer = new JLabel(
"<html><font color=red>" + speechPart + "</font>) => <font color=black>" + definition + "</font></html>");
if (renderer.isEnabled())
{
if (isSelected)
{
renderer.setText("<html><font color=gray>" + speechPart + "</font><font color=blue><u><b>" + definition + "</b></u></font></html>");
renderer.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
JList.DropLocation dropLocation = list.getDropLocation();
if (dropLocation != null
&& !dropLocation.isInsert()
&& dropLocation.getIndex() == index)
{
bg = DefaultLookup.getColor(this, ui, "List.dropCellBackground");
fg = DefaultLookup.getColor(this, ui, "List.dropCellForeground");
isSelected = true;
}
if (isSelected)
{
renderer.setBackground(bg == null ? list.getSelectionBackground() : bg);
renderer.setForeground(fg == null ? list.getSelectionForeground() : fg);
}
Border border = null;
if (cellHasFocus)
{
if (isSelected)
{
border = DefaultLookup.getBorder(this, ui, "List.focusSelectedCellHighlightBorder");
}
if (border == null)
{
border = DefaultLookup.getBorder(this, ui, "List.focusCellHighlightBorder");
}
}
else
{
}
}
return renderer;
}
}
);
translatedWidget.setForeground(Color.black);
translate.addActionListener(new
ActionListener()
{
public void actionPerformed
(ActionEvent
e)
{
onTranslate();
}
}
);
search.setToolTipText("find");
search.addActionListener(new
ActionListener()
{
public void actionPerformed
(ActionEvent
e)
{
onSearchClick();
}
}
);
translators.setSelectedIndex(0);
suggestionWidget.setBorder(BorderFactory.createLineBorder(Color.gray, 1));
onTranslatorsClick();
}
private void onSuggestionSelected(int selectedIndex)
{
String hold = (String) suggestionWidgetModel.getElementAt(selectedIndex);
word.setText(hold);
hideSuggestionWindowToBack();
suggestionWidgetModel.clear();
if (javaWindow == null)
{
javaWindow.dispose();
javaWindow = null;
}
}
public void onWordUpdated(final String toComplete) throws ClassNotFoundException, SQLException
{
new Thread(new Runnable()
{
public void run()
{
try
{
final List<Suggestion> suggestions = suggestor.getSuggestions(toComplete);
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
speechPartAndDefinitionWidgetModel.clear();
translatedWidgetModel.clear();
suggestionWidgetModel.clear();
try
{
for (Suggestion suggestion : suggestions)
{
suggestionWidgetModel.addElement(suggestion.getCaption());
}
if (!suggestions.isEmpty())
{
suggestionWidget.setSelectedIndex(0);
if (javaWindow == null)
{
javaWindow = new JavaWindow(suggestionWidget);
}
else
{
final Point location = word.getLocationOnScreen();
javaWindow.setLocation(location.x, location.y + word.getHeight());
}
showSuggestionWindowToBack();
}
else
{
hideSuggestionWindowToBack();
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
}
});
}
catch (SQLException e)
{
onSqlError(e);
}
}
}
, "onWordUpdated").
start();
}
private void onTranslate()
{
try
{
translatedWidgetModel.clear();
String lookupWord = word.getText();
if (lookupWord != null)
{
Collection<String> bisayaWords = this.translator.translateSimple(lookupWord);
for (String bisayaWord : bisayaWords)
{
translatedWidgetModel.addElement(bisayaWord.toUpperCase());
}
}
}
catch (SQLException ex)
{
onSqlError(ex);
}
}
private void onSqlError(SQLException ex)
{
JOptionPane.showMessageDialog(null, "SQL Error! :" + ex.getMessage());
}
private void onDefinitionSelected(ListSelectionEvent ev)
{
if (!ev.getValueIsAdjusting())
{
int selectedIndex = speechPartAndDefinitionWidget.getSelectedIndex();
if (selectedIndex != -1)
{
final DefinitionUiModel definitionUiModel = (DefinitionUiModel) speechPartAndDefinitionWidgetModel.get(selectedIndex);
translate(definitionUiModel.getDefinition());
}
}
}
private void translate(Definition definition)
{
try
{
translatedWidgetModel.clear();
Map<String, String> map = new HashMap<String, String>();
int definitionId = definition.getId();
String definitionName = definition.getValue();
int nameId = translator.getFromDictionary().getNameIdForDefinitionId(definitionId);
if (nameId > -1)
{
final Collection<String> translation = translator.translateSimple(nameId);
for (String transWord : translation)
{
map.put(transWord, definitionName);
for (Map.Entry<String, String> entry : map.entrySet())
{
String myValue = entry.getKey().toUpperCase() + " -- " + entry.getValue();
translatedWidgetModel.addElement(myValue);
}
}
}
}
catch (SQLException ex)
{
onSqlError(ex);
}
}
private void onSearchClick()
{
search.setEnabled(true);
hideSuggestionWindowToBack();
speechPartAndDefinitionWidgetModel.clear();
translatedWidgetModel.clear();
try
{
final String lookupWord = word.getText();
if (lookupWord != null)
{
final Dictionary fromDictionary = translator.getFromDictionary();
final WordDefinitions definitions = fromDictionary.getWordDefinitions(lookupWord);
final Iterator<Map.Entry<SpeechPart, List<Definition>>> items = definitions.iterator();
while (items.hasNext())
{
final Map.Entry<SpeechPart, List<Definition>> item = items.next();
for (Definition definition : item.getValue())
{
speechPartAndDefinitionWidgetModel.addElement(new DefinitionUiModel(item.getKey(), definition));
}
}
}
}
catch (SQLException ex)
{
onSqlError(ex);
}
}
private void onTranslatorsClick()
{
translator = (Translator) translators.getSelectedItem();
suggestor = new Suggestor(translator.getFromDictionary(), 10);
word.setEnabled(true);
application.setTitle(translator.toString());
translators.setToolTipText("tooltip : " + translator.toString());
speechPartAndDefinitionWidgetModel.clear();
}
private void hideSuggestionWindowToBack()
{
if (javaWindow == null)
{
return;
}
javaWindow.setVisible(false);
javaWindow.toBack();
}
private void showSuggestionWindowToBack()
{
if (javaWindow == null)
{
return;
}
javaWindow.setVisible(true);
javaWindow.toFront();
}
}
The algorithm (that I know of) behind the suggestions list is: Longest common substring problem. The problem is quite easy if you have stored the strings in the database in the form of a trie. Then the list of suggestions for the current prefix will be all those strings that start with the currently entered string. You will understand what I mean if you look at the Trie data structure.
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 ..