How to set the location of a JWindow below the textfield when the frame is being drag?
I am making an autocomplete project(just like Google). I have a jtextfield in my frame and whenever I type something to that field, a JWindow will appear below the textfield and that window is coming from another class.
Now the problem is how could I make the window always appear开发者_运维技巧 below the textfield whenever I drag the frame?
Any help would be much appreciated.. Thanks...
for manually set Locatio
n on the screen, you have to define something as private Point location;
and getLocation
from desired JComponent
, don't forget dealyed show for Show Top-Level Container into invokeLater();
for example
public void showWindow() {
window.setVisible(false);
location = myTextField.getLocationOnScreen();
int x = location.x;
int y = location.y;
window.setLocation(x - 20, y - 20);
Runnable doRun = new Runnable() {
@Override
public void run() {
window.setVisible(true);
}
};
SwingUtilities.invokeLater(doRun);
}
Use SwingUtilities.convertPointToScreen()/convertPointFromScreen()
pass JTextField's
position and get coordinates on screen for the JWindow
.
If I understood well, you're trying to do a JTextfield which propose a list of suggestions when the user enters some text.
I used this by the past: http://www.java2s.com/Code/Java/Swing-Components/AutocompleteComboBox.htm
It needs a bit of refactoring but your problem is what I said, it will help you solve it much more easily (and elegantly)!
To use the example:
Java2sAutoTextField textField = new Java2sAutoTextField(
Arrays.asList(new String[] {"Value 1","Value 2"}));
You should not use a JWindow for that but a JComboBox instead of the TextField. JWindow's are designed to be toplevel windows ...
精彩评论