Removal method works bindAutoCompletion () class TextFields library ControlsFX - java

I have in the text box that by choosing the combo box Binds respectively the text field with the specified data. The point is that after the first binding process, you can not remove the effect. I choose binding logins, this Binds me a text box with logins. Then I want Bind the e-mail, then I develop two lists, login and e-mail.
#FXML
public void setToSearch() {
if(comboSettingsSearch.getSelectionModel().getSelectedIndex() == 1)
TextFields.bindAutoCompletion(textSearchPerson, Database.loadLogins());
if(comboSettingsSearch.getSelectionModel().getSelectedIndex() == 5)
TextFields.bindAutoCompletion(textSearchPerson, Database.loadEmails());
}
enter image description here
Underneath logins, and on top of e-mail. Anyone know how to remove this effect?

If you do it like this,
#FXML
public void setToSearch() {
if(comboSettingsSearch.getSelectionModel().getSelectedIndex() == 1)
AutoCompletionBinding<String> acbLogin = TextFields.bindAutoCompletion(textSearchPerson, Database.loadLogins());
if(comboSettingsSearch.getSelectionModel().getSelectedIndex() == 5)
AutoCompletionBinding<String> acbEmail = TextFields.bindAutoCompletion(textSearchPerson, Database.loadEmails());
}
you can dispose the binding with
acbLogin.dispose();
acbEmail.dispose();
as far as I can tell from the HelloAutoComplete-example and the javadocs.

This is a late response to this post, however, I see that it apparently didn't work because it is not checked. It also didn't work for me but two weeks later I discovered why.
The proposed declaration and initialization above does not work if you include the type as part of the declaration. You need to remove the type from the declaration and then the .dispose() method will work.
This doesn't work:
AutoCompletionBinding<String> acbLogin = TextFields.bindAutoCompletion(textSearchPerson, Database.loadLogins());
This does:
AutoCompletionBinding acbLogin = TextFields.bindAutoCompletion(textSearchPerson, Database.loadLogins());

AutoCompletionBinding acb = TextFields.bindAutoCompletion(txtfield,arraylistobj);
acb=null;

Related

How to correct a display problem when inserting a row in a JavaFX grid?

I want to insert a new JavaFX bean in a grid using an "insert" button. Everything is fine, except for a display problem. After insertion, a "ghost selection" is displayed lower in the grid, as shown in this screenshot. In this example, a fourth section bean was added and selected as requested. But a fake selection appears 10 lines under the last real bean, where no bean is set for this row.
Has anyone experienced this kind of behavior? Any clue how get rid of this ghost selection? Here is what the code for the insert button looks like:
#FXML
private Button insert;
...
insert.setOnAction(event -> {
JfxBean newBean = createBean();
tableView.getItems().add(newBean);
int index = tableView.getItems().indexOf(newBean);
tableView.getSelectionModel().clearSelection();
tableView.requestFocus();
tableView.scrollTo(index);
tableView.getSelectionModel().focus(index);
tableView.getSelectionModel().select(index);
};
According to javaFX-8 documentation, SelectionModel.java does not expose any focus() method. FocusModel.java does instead. Therefore JVM will fail to compile your presented code.
Below is a possible solution:
insert.setOnAction(event -> {
JfxBean newBean = createBean();
tableView.getItems().add(newBean);
int index = tableView.getItems().indexOf(newBean);
tableView.getSelectionModel().clearSelection();
tableView.requestFocus();
tableView.scrollTo(index);
// below line is the amendment
tableView.getFocusModel().focus(index);
tableView.getSelectionModel().select(index);
};
Finally, adding tableView.refresh() corrected this weird behavior. No more ghost selection.

Selenium made a sendKeys for two fields instead of one for some reason

I made a pretty simple selenium test, where I want to open web page, clear field value, start entering text for this field, select first value from the hint drop down.
Web site is aviasales.com (I just found some site with a lot of controls, this is not an advertisement)
I did
DriverFactory.getDriver().findElement(By.id("flights-origin-prepop-whitelabel_en")).clear();
and it was working perfectly, I also checked via console that this is the only one object on a page like:
document.getElementById('flights-origin-prepop-whitelabel_en')
So, in next line I'm sending value:
DriverFactory.getDriver().findElement(By.id("flights-origin-prepop-whitelabel_en")).sendKeys("LAX");
but it send LAX value for both "flights-origin-prepop-whitelabel_en" and "flights-destination-prepop-whitelabel_en" for some reason, then i tried
DriverFactory.getDriver().findElement(By.id("//input[#id='flights-destination-prepop-whitelabel_en'][#placeholder='Destination']")).sendKeys(destinationAirport);
but I got the same result:
What could be a reason and how to fix this?
Thank you!
Yep... there's some weird behavior going on there. The site is copying whatever is entered into the first field into the second for reason I don't understand. I gave up trying to understand it and found a way around it.
Whenever I write code that I know I'm going to reuse, I put them into functions. Here's the script code
driver.navigate().to(url);
setOrigin("LAX");
setDestination("DFW");
...and since you are likely to use these repeatedly, the support functions.
public static void setOrigin(String origin)
{
WebElement e = driver.findElement(By.id("flights-origin-prepop-whitelabel_en"));
e.click();
e.clear();
e.sendKeys(origin);
e.sendKeys(Keys.TAB);
}
public static void setDestination(String dest)
{
WebElement e = driver.findElement(By.id("flights-destination-prepop-whitelabel_en"));
e.click();
e.clear();
e.sendKeys(dest);
e.sendKeys(Keys.TAB);
}
You can see the functions but basically I click in the field, clear the text (because usually there's something already in there), send the text, and then press to move out of the field and choose the default (first choice).
The reason of your issue is the ORIGIN and DESTINATION inputbox binded keyboard event which used to supply an autocomplete list according to your typed characters.
The binded keyborad event breaks the normal sendKeys() functionality. I met similar case in my projects and questions on StackOverFlow.
I tried input 'GSO' into DESTINATION by sendKeys('GSO'), but I get 'GGSSOO' on page after the sendKeys() complete.
To resolve your problem, we can't use sendKeys(), we have to use executeScript() to set the value by javascript in backgroud. But executeScript() won't fire keyborad event so you won't get the autocomplete list. So we need find out a way to fire keyborady event after set value by javascript.
Below code snippet worked on chrome when i tested on aviasales.com:
private void inputAirport(WebElement targetEle, String city) {
String script = "arguments[0].value = arguments[1]";
// set value by javascript in background
((JavascriptExecutor) driver).executeScript(script, targetEle, city + "6");
// wait 1s
Thread.sleep(1000);
// press backspace key to delete the last character to fire keyborad event
targetEle.sendKeys(Keys.BACK_SPACE);
// wait 2s to wait autocomplete list pop-up
Thread.sleep(2000);
// choose the first item of autocomplete list
driver.findElement(By.cssSelector("ul.mewtwo-autocomplete-list > li:nth-child(1)")).click();
}
public void inputOrigin(String city) {
WebElement target = driver.findElement(By.id("flights-origin-prepop-whitelabel_en"));
return inputAirport(target, city);
}
public void inputDestination(String city) {
WebElement target = driver.findElement(By.id("flights-origin-prepopflights-destination-prepop-whitelabel_en"));
return inputAirport(target, city);
}

JInput Multiple Controllers?

i'm somewhat new to jinput and java in general and was wondering, what's the easiest way to set up multiple xbox 360 controllers (particularly 4) with jinput? currently, i'm currently going off of theuzo007's tutorial on jinput with controllers, and have a basic working controller setup going on. it would be fantastic if i could set what controller moves certain entities around. (i'm using my friend's homemade library, just so you know.)
screenshot -
http://imgur.com/a/1Ocu5
top one is the main block of code, last one is the header (sorry for putting them in the wrong order, imgur does that sometimes!)
if anyone could help me out, that would be great, thanks!
edit: if there's no possible way to do it, if anyone could try to reccomend a new library to me, that would be cool.
There is a possible way
That tutorial is pretty good. Furthermore, I think you can do the 4 controllers stuff by copy-pasting some code inside the zip theuzo007 provides you and a bit more. By the way, that page that you liked says that there is a better version of that tutorial where you can download an also better version of his code -> theuzo007's JInput tutorial V2
Once you download the code you can see that in JoystickTest.java there is a method called searchForControllers() that you can put (With the corresponding private ArrayList<Controller> foundControllers; as field) in a class called ControllerChecker or some cooler name. Make them all static and you will get something like this:
public class ControllerChecker {
private static ArrayList<Controller> foundControllers = null;
/**
* Just used for checking all available controllers.
*/
private static void searchForControllers() {
Controller[] controllers = ControllerEnvironment.getDefaultEnvironment().getControllers();
for(int i = 0; i < controllers.length; i++){
Controller controller = controllers[i];
if (
controller.getType() == Controller.Type.STICK ||
controller.getType() == Controller.Type.GAMEPAD ||
controller.getType() == Controller.Type.WHEEL ||
controller.getType() == Controller.Type.FINGERSTICK
)
{
// Add new controller to the list of all controllers.
foundControllers.add(controller);
// Add new controller to the list on the window.
window.addControllerName(controller.getName() + " - " + controller.getType().toString() + " type");
}
}
}
/**
* Returns null if there is no controller available. Otherwise, it retrieves the last controller in the list by removing it.
*/
public static Controller getController() {
if(foundControllers == null) {
foundControllers = new ArrayList<Controller>();
searchForControllers();
}
return foundControllers.size() == 0 ? null : foundControllers.remove(foundControllers.size() - 1);
}
}
You would use the static method getController() to make the players have a different controller, checking if the returned controller is null, meaning that there is no available controller. Also you can change my code and check for controllers everytime you ask for one, but you have to check if the controller is already in use.
I hope this helps you in your purpose. This solution just checks for all available controllers and returns then in the last order it found them (maybe using a Stack is more efficient). But probably you will want more functionality like being able to tell the program to select a specific controller by pressing a button, maybe in a screen that says "Please, connect your controller and press any key/button". This can be achieve easily if you understand theuzo007's code (the JoystickTest.java has a lot of useful lines!).
Also you can make some mechanism to detect unpluged controllers and just by plugging in them again the system recognize it. Maybe there is some controller id, I haven't found it yet.
Finally, there is more code here.

Alternatives for switch statement

I am developing an Wicket application. But my question is not really Wicket related. In that app I have a horizontal menu. This menu is created by few links. On clicking the link you will be navigated to some page. Now based on the page you are currently viewing the css class attribute of the link of the menu will be changed to "selected". This is the description of the problem.
Now I am solving this problem by using a integer value. The value is saved in the session and it is updated when any one link has been clicked. Based on that saved value, which link will be "selected", will be determined at runtime.
I am implementing this in following way:
//On link click I set a number in session
public void onClick() {
session.setValue(1);// or 2 or 3
}
When the menu is created I switch between the value and modify the css class, as follows:
switch(session.getValue){
case 1: add css to home;
case 2: add css to profile;
// and so on.
}
I was wondering that is this the only right way to do it? Or there some other better techniques or design patterns exist which can help me to achieve this in better way?
Store the menu items in an array (or an ArrayList):
items[0] = home
items[1] = profile
And use the index of the array as menu identifier. When you receive the selected menu itentifier, retrieve the corresponding item with
items[selectedItem]
You could also use a Map if the identifiers are not numbers, or don't go from 0 to N.
For a start, use an enum or static constants instead of magic numbers (1, 2, 3).
The Visitor Pattern is commonly used to avoid this sort of switching. You might not want to implement the full pattern in your case, but it's worth knowning. JB Nizet's answer may be more practical in your situation.
See https://en.wikipedia.org/wiki/Visitor_pattern
These SO questions might give you some ideas, too
Java visitor pattern instead of instanceof switch
Java Enums - Switch statements vs Visitor Pattern on Enums - Performance benefits?
I have implemented it using EnumMap and an Enum type as its key. I have defined an Enum:
public enum NavigationStatus {
HOME,
PROFILE;
}
In session I set the value of the current navigation as:
private NavigationStatus activeUserNavigationStatus;
public NavigationStatus getActiveUserNavigationStatus() {
return activeUserNavigationStatus;
}
public void setActiveUserNavigationStatus(NavigationStatus activeUserNavigationStatus) {
this.activeUserNavigationStatus = activeUserNavigationStatus;
}
Primarily I set it to: setActiveUserNavigationStatus(NavigationStatus.HOME);
Now where the menu is building I created an EnumMap:
EnumMap<NavigationStatus, Component[]> menuMap = new EnumMap<NavigationStatus, Component[]>(NavigationStatus.class);
And added elements to it, as:
menuMap.put(NavigationStatus.HOME, new Component[] { homeContainer, home });
And also on click methods of the links I set the status value:
public void onClick() {
session.setActiveUserNavigationStatus(NavigationStatus.PROFILE);
}
Last of all I checked the current value from the session and set the css class accordingly:
Component[] menuComponents = menuMap.get(getSession().getActiveUserNavigationStatus());
menuComponents[0].add(new AttributeAppender("class", new Model<Serializable>(" active")));
menuComponents[1].add(new AttributeAppender("class", new Model<Serializable>(" active")));
This is without switch statement and combines the idea of JB Nizet's ArrayList index and Oli Charlesworth's Enum.
Thank you.

altering JFileChooser behaviour : preventing "choose" on enter in file path JTextField

Greetings to Swing Pros, here's a good (I hope) question for you.
The below are the task requirements and possible solutions I see. I would like someone having had such a hardcore experience to share some thoughts about this.
This does not require coding or anything like that, I just need general advice as to which approach is more reliable regarding the fact I need to work with private symbols which reside in sun.swing and/or javax.swing.plaf packages.
The task is to modify/alter JFileChooser behaviour (just a little bit, actually).
when the user presses enter in the file name JTextField, and the field contains a path to a dir, don't "select" the dir, but switch to it instead. Yes, the dialog is configured to accept directories, but we need to accept only clicks on the "Open" button, and (possibly) double-clicks in the file listing table.
prevent user from selecting a dir/file with more than 1GB data via hitting enter in the file name text field
Here're couple of general solution options:
a. listen on the property-based changes that JFileChooser provides (which AFAICS are triggered after-the-fact and won't provide the degree of control we need here).
b. tinker with the javax.swing.plaf.basic.BasicFileChooserUI (via refrection, breaking the private-level encapsulation) and alter the reference to
private Action approveSelectionAction = new ApproveSelectionAction();
so that our custom action does the extra checks for 1 and 2. This approach links with plaf package and may fail in case this action is somehow overridden in some class below this UI class.
c. traverse the JFileChooser component hierarchy, find the JTextField (which apparently should occur only once in the component tree), decorate all the action listeners hanging on that JTextField with our custom checks. My debugging session shows that this JTextField is some anonymous subclass of JTextField living in the sun.swing.FilePane.
This approach seems to be more OO-friendly, but there's a chance that for some OS this text field is absent, or some other JTextField is also present in the hierarchy.
Well, it seems that public JFileChooser API would not suffice to achieve that behaviour, while the other two options are either deep magic or unportable (long-term), or even both.
So, the question is: which approach would you choose and why?
Regarding option2, you don't need to use reflection to customize the accept Action. You can just override the approveSelection() method. Something like:
JFileChooser chooser = new JFileChooser( new File(".") )
{
public void approveSelection()
{
if (getSelectedFile().exists())
{
System.out.println("duplicate");
return;
}
else
super.approveSelection();
}
};
I recently encountered the same requirement, i.e., pressing Enter in the JTextField of a JFileChooser should cause the displayed dialog to traverse a directory instead of returning from the dialog. Only clicking on the Open button should cause the final selection.
The solution was fairly simple (at least for my application) and has two components to it (Pardon the messed up formatting. I'm new to this forum and I'm not sure why the code is not displaying correctly).
1 - Register an AWTListener to keep track of the last event type generated by the user
class MyChooser extends JFileChooser implements java.awt.AWTEventListener {
...
MyChooser(){
Toolkit.getDefaultToolkit().addAWTEventListener(this,
AWTEvent.MOUSE_EVENT_MASK + AWTEvent.KEY_EVENT_MASK);
...
}
int lastEventId;
public void eventDispatched(AWTEvent e) {
lastEventId=e.getID();
}
}
2 - Override the approveSelection() method of JFileChooser and check whether the approval request is a result of a mouse event (likely caused by the user clicking on the Open button) or a key event caused by the user pressing Enter. The 'lastEventId' variable provides access to this information. My own approveSelection then looks as follows:
public void approveSelection() {
File f=getSelectedFile();
if (f.exists() && isTraversable(f) && lastEventId ==
KeyEvent.KEY_PRESSED) {
setCurrentDirectory(f);
return;
}
super.approveSelection(); }

Categories