每当我在搜索栏中输入一个字符时,我都必须再次手动单击搜索栏以保持焦点。
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.List;
import java.awt.event.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.List;
public class SearchTextField extends JTextField {
private JPopupMenu searchResultPopup;
private SearchPOI searchPOI;
public SearchTextField(SearchPOI searchPOI) {
this.searchPOI = searchPOI;
searchResultPopup = new JPopupMenu();
this.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if (!isNavigationKey(e)) {
updatePOIList();
}
}
});
searchResultPopup.addComponentListener(new ComponentAdapter() {
@Override
public void componentHidden(ComponentEvent e) {
SwingUtilities.invokeLater(() -> requestFocusInWindow());
}
});
}
private boolean isNavigationKey(KeyEvent e) {
return e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_DOWN
|| e.getKeyCode() == KeyEvent.VK_ENTER || e.getKeyCode() == KeyEvent.VK_ESCAPE;
}
private void updatePOIList() {
String searchText = getText();
List<PointOfInterest> pois;
if (searchText.isEmpty()) {
pois = searchPOI.getAllPOIs();
} else {
pois = searchPOI.searchForPOI(searchText);
}
searchResultPopup.removeAll();
for (PointOfInterest poi : pois) {
JMenuItem menuItem = new JMenuItem(poi.getName());
menuItem.addActionListener(e -> {
setText(poi.getName());
searchResultPopup.setVisible(false);
requestFocusInWindow(); // request focus after selecting an item
});
searchResultPopup.add(menuItem);
}
if (!pois.isEmpty()) {
searchResultPopup.show(this, 0, this.getHeight());
} else {
searchResultPopup.setVisible(false);
requestFocusInWindow(); // request focus after hiding the popup
}
}
}
我试过使用JCombobox,但不起作用,我也试过FocusListener。每当我尝试使用requestFocus时,搜索栏都会保持焦点,但弹出菜单不能正确更新。
2条答案
按热度按时间bq3bfh9z1#
我不确定你到底想实现什么样的行为,但根据我所收集的信息,我成功地使用了一个可编辑的JComboBox:
plupiseo2#
您可以在更新JPopMenu后尝试调用requestFocusInWindow()函数。