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 ..
Related
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);
}
});
For some obscene reason this works when reward = "DIAMOND" and amount = 10
public ItemStack giveReward() {
return new ItemStack(Material.matchMaterial(reward), amount);
}
p.getInventory().addItem(o.giveReward()); //gives the player 10 DIAMONDS
but when reward = "ACACIA_DOOR" and amount = 1 the same method gives the player NOTHING and no error is thrown. I have no clue why. Also
System.out.println(Material.getMaterial("ACACIA_DOOR"))
prints ACACIA_DOOR so shouldn't my above code work?
here's the rest of the code:
//imports omitted
public class ObjectivesRPG extends JavaPlugin implements Listener {
//TODO
//add view command
//implement rewards and requirements
//test for completeness
//future - allow ops to modify player data
public static void main(String args[]) {
Objective o = new Objective("Spider", 1, 3, "DIAMOND", 1);
Material m = Material.getMaterial("ACACIA_DOOR");
System.out.println(m);
//meta.setDisplayName(ChatColor.GOLD + "Excaliber");
//meta.setLore(Arrays.asList(ChatColor.AQUA + "The legendary sword", ChatColor.GREEN + "Wow"));
//sword.setItemMeta(meta);
//System.out.println(o.getName());
/*
System.out.println(Material.DIAMOND_SWORD);
ItemStack stack = new ItemStack(Material.DIAMOND_SWORD, 1);
ItemMeta meta = stack.getItemMeta();
stack.setItemMeta(meta);*/
}
private ArrayList<Objective> objectives = null;
private HashMap<String, ArrayList<Objective>> loadedPlayerData = null;
#SuppressWarnings("unchecked")
#Override
public void onEnable() {
System.out.println("ObjectivesRPG loaded");
loadedPlayerData = new HashMap<>();
File dir = getDataFolder();
if (!dir.exists()) {
Bukkit.getConsoleSender().sendMessage(ChatColor.YELLOW + "[ObjectivesRPG] Could not find data directory, creating it");
if (!dir.mkdir()) {
System.out.println("Error: Could not create data directory");
}
}
objectives = (ArrayList<Objective>) load(new File(getDataFolder(), "objectives.dat"));
if (objectives == null) {
objectives = new ArrayList<>();
}
getServer().getPluginManager().registerEvents(this, this); // ParamListener,
// ParamPlugin
}
#Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String args[]) {
if (label.equalsIgnoreCase("objectives")) {
if (sender instanceof Player) {
Player p = (Player) sender;
if(args.length == 0) {
for(Objective o: loadedPlayerData.get(p.getName())) {
p.sendMessage(o.getName() + " " + o.getTillComplete() + " ");
}
}
if (args.length > 0) {
if (args[0].equals("create")) {
if (!p.isOp()) {
p.sendMessage(ChatColor.RED + "You must be op to use this command");
} else if (args.length == 6) {
Objective objective = new Objective(args[1] ,Integer.parseInt(args[2]), Integer.parseInt(args[3]), args[4], Integer.parseInt(args[5]));
objectives.add(objective);
save(objectives, new File(getDataFolder(), "objectives.dat"));
} else {
p.sendMessage(ChatColor.RED + "Error: Bad arguments.");
}
}
}
}
}
return true;
}
public void onDisable() {
save(objectives, new File(getDataFolder(), "objectives.dat"));
}
public void save(Object o, File f) {
try {
if (!f.exists()) {
f.createNewFile();
}
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(f));
os.writeObject(o);
Bukkit.getConsoleSender().sendMessage("[ObjectivesRPG] Saved objective");
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public Object load(File f) {
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
Object result = ois.readObject();
ois.close();
return result;
} catch (Exception e) {
return null;
}
}
#EventHandler
private void checkKills(EntityDeathEvent e) {
Entity killed = e.getEntity();
Entity killer = e.getEntity().getKiller();
if(killer instanceof Player) {
Player p = (Player) killer;
for(Objective o: loadedPlayerData.get(p.getName())) {
if(o.isComplete()) {
continue;
}
if(!o.isComplete() && (o.getRequirement() == Requirement.kill_Spiders && killed instanceof Spider ||
o.getRequirement() == Requirement.kill_Zombies && killed instanceof Zombie) ||
o.getRequirement() == Requirement.kill_Skeletons && killed instanceof Skeleton
) {
o.setTillComplete(o.getTillComplete() - 1);
if(o.getTillComplete() == 0) {
p.sendMessage(ChatColor.GREEN + "Congragulations! You completed objective " + o.getName() + "! Here is your reward!");
p.getInventory().addItem(o.giveReward());
o.setComplete(true);
}
}
}
}
}
#EventHandler
private void onQuit(PlayerQuitEvent event) {
Player player = event.getPlayer();
File f = new File(getDataFolder(), player.getName());
save(loadedPlayerData.get(player.getName()), f);
loadedPlayerData.remove(player.getName());
}
#EventHandler
private void onJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
File f = new File(getDataFolder(), player.getName());
ArrayList<Objective> playerObjectives = null;
try {
if(!f.exists()) {
f.createNewFile();
Bukkit.getConsoleSender().sendMessage("[ObjectivesRPG] Could not find " + player.getName() + "'s objective data, creating it");
playerObjectives = new ArrayList<>();
for(Objective objective: objectives) {
playerObjectives.add(objective);
}
player.sendMessage(ChatColor.GREEN + "You have new objective(s) to complete! Type /objectives to view them.");
save(playerObjectives, f);
} else {
playerObjectives = (ArrayList<Objective>) load(f);
System.out.println(objectives.size() + " " + playerObjectives.size());
//If server objective list is larger than playerObjectives new objectives must be added to player list
if(objectives.size() > playerObjectives.size()) {
player.sendMessage(ChatColor.GREEN + "You have new objective(s) to complete! Type /objectives to view them.");
for(int i = 0; i < objectives.size(); i++) {
boolean objectiveAdded = false;
for(int j = 0; j < playerObjectives.size(); j++) {
if(objectives.get(i).getName().equals(playerObjectives.get(j).getName())) {
objectiveAdded = true;
//break;
}
}
if(!objectiveAdded) {
playerObjectives.add(objectives.get(i));
}
}
save(playerObjectives, f);
}
}
loadedPlayerData.put(player.getName(), playerObjectives);
} catch(Exception e) {
e.printStackTrace();
}
}
}
public class Objective implements Serializable {
private static final long serialVersionUID = -2018456670240873538L;
private static ArrayList<Requirement> requirements = new ArrayList<>();
private String name;
private Requirement requirement;
private String reward;
private int amount;
private int tillComplete;
private boolean complete;
public Objective(String name, int requirementIndex, int tillComplete, String reward, int amount) {
if(requirements.isEmpty()) {
requirements.add(Requirement.kill_Skeletons);
requirements.add(Requirement.kill_Spiders);
requirements.add(Requirement.kill_Zombies);
}
this.name = name;
this.requirement = requirements.get(requirementIndex);
this.tillComplete = tillComplete;
this.reward = reward;
this.amount = amount;
complete = false;
}
public ItemStack giveReward() {
return new ItemStack(Material.matchMaterial(reward), amount);
}
public String getName() {
return name;
}
public Object getRequirement() {
return requirement;
}
public static ArrayList<Requirement> getRequirements() {
return requirements;
}
public static void setRequirements(ArrayList<Requirement> requirements) {
Objective.requirements = requirements;
}
public int getTillComplete() {
return tillComplete;
}
public void setTillComplete(int tillComplete) {
this.tillComplete = tillComplete;
}
public void setName(String name) {
this.name = name;
}
public void setRequirement(Requirement requirement) {
this.requirement = requirement;
}
public void setReward(String reward) {
this.reward = reward;
}
public void setComplete(boolean complete) {
this.complete = complete;
}
public String getReward() {
return reward;
}
public boolean isComplete() {
return complete;
}
}
This has tripped people up more than once. Doors are two-component items. ACACIA_DOOR represents the top-part of the door, while ACACIA_DOOR_ITEM represents the bottom-part and also the item id. Use ACACIA_DOOR_ITEM when creating an ItemStack.
Tip: If you are unsure about an item id, launch Minecraft in creative mode and enable Advanced Tooltips by pressing F3+H. The real item id will be displayed in the tool tip as you hover over items in the creative inventory. For example, hovering over an Acacia Door would display
Acacia Door (#0430)
Use this information to lookup the appropriate Material enum in org.bukkit.Material, which in this case would be ACACIA_DOOR_ITEM.
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);
}
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
Im pretty new to Java and to thread-programming especially. This code is mostly out of a pretty old book (2001) with samples and examples for a search-engine.
But its just not working
Now i don't know if i am making a mistake or if the author made it or if there are incompatibilities with different versions of java...i really have no clue! The oddest thing about it is that it works 1 out of 100 times ...
After hours of debugging i would appreciate any help!
SearchEngine.java:
import java.util.Vector;
import parsing.SourceElement;
import parsing.WebParserWrapper;
import query.Filter;
public class SearchEngine implements Runnable {
private Vector linkHistory = new Vector();
private int currentLink;
private String beginAt = null;
private SearchHandler searchHandler = null;
private boolean searchInProgress = false;
private boolean stopPending = false;
boolean firstTime = true;
public boolean searchInProgress() {
return searchInProgress;
}
public boolean stopPending() {
return stopPending;
}
#SuppressWarnings("unchecked")
public void followLinks(String url) {
if (stopPending)
return;
try {
boolean drillDown = false;
WebParserWrapper webParser = new WebParserWrapper();
Vector sortedElements = webParser.getElements(url, "", "WITHGET");
Vector contentElements = Filter.getFilteredElements(sortedElements, Filter.CONTENT, "matches", "*");
for (int i = 0; i < contentElements.size(); i++) {
SourceElement thisElement = (SourceElement) contentElements.elementAt(i);
String thisKey = (String) thisElement.getKey();
String thisContent = (String) thisElement.getContent();
boolean goodHit = searchHandler.handleElement(url, thisKey, thisContent);
if (goodHit) {
drillDown = true;
}
}
System.out.println(url + " -- DrillDown " + ((drillDown) ? "positive" : "negative"));
if (drillDown) {
Vector linkElements = Filter.getFilteredElements(sortedElements, Filter.KEY, "matches",
"*a[*].#href[*]");
for (int i = 0; i < linkElements.size(); i++) {
SourceElement thisElement = (SourceElement) linkElements.elementAt(i);
String thisContent = (String) thisElement.getContent();
if (!linkHistory.contains(thisContent)) {
linkHistory.add(thisContent);
System.out.println("Collected: " + thisContent);
}
}
}
}
catch (Exception e) {}
if (currentLink < linkHistory.size()) {
String nextLink = (String) linkHistory.elementAt(currentLink++);
if (nextLink != null) {
followLinks(nextLink);
}
}
}
public boolean startSearch(String url, SearchHandler searchHandler) {
if (searchInProgress)
return false;
beginAt = url;
this.searchHandler = searchHandler;
this.linkHistory = new Vector();
this.currentLink = 0;
Thread searchThread = new Thread(this);
searchThread.start();
return true;
}
public void stopSearch() {
stopPending = true;
}
#Override
public void run() {
searchInProgress = true;
followLinks(beginAt);
searchInProgress = false;
stopPending = false;
}
}
SimpleSearcher.java
import java.util.Enumeration;
import java.util.Hashtable;
public class SimpleSearcher implements SearchHandler {
private SearchEngine searchEngine;
private String keyword;
private String startURL;
private Hashtable hits = new Hashtable();
public boolean handleElement(String url, String key, String content) {
boolean goodHit = false;
int keywordCount = 0;
int pos = -1;
while ((pos = content.toLowerCase().indexOf(keyword, pos + 1)) >= 0){
keywordCount++;
}
if (keywordCount > 0) {
Integer count = (Integer) hits.get(url);
if (count == null){
hits.put(url, new Integer(1));
}
else {
hits.remove(url);
hits.put(url, new Integer(count.intValue() + keywordCount));
}
goodHit = true;
}
if (hits.size() >= 3)
searchEngine.stopSearch();
return goodHit;
}
public Hashtable search(String startURL, String keyword) {
searchEngine = new SearchEngine();
this.startURL = startURL;
this.keyword = keyword;
searchEngine.startSearch(startURL, this);
try {Thread.sleep(1000);}catch (Exception e){e.printStackTrace();}
while (searchEngine.searchInProgress());
return this.hits;
}
public static void main(String[] args) {
SimpleSearcher searcher = new SimpleSearcher();
String url = "http://www.nzz.ch/";
String compareWord = "der";
Hashtable hits = searcher.search(url, compareWord);
System.out.println("URLs=" + hits.size());
for (Enumeration keys = hits.keys(); keys.hasMoreElements();) {
String thisKey = (String) keys.nextElement();
int thisCount = ((Integer) hits.get(thisKey)).intValue();
System.out.println(thisCount + " hits at " + thisKey);
}
}
}
SearchHandler.java
public interface SearchHandler {
public boolean handleElement(String url, String key, String content);
}