nt.UI/src/nt/UI/control/JSearchBar.java

112 lines
2.9 KiB
Java

package nt.UI.control;
import java.awt.Dimension;
import java.awt.Font;
import java.io.File;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JWindow;
import nt.UI.control.interfaces.DefaultSearchBarFinder;
import nt.UI.control.interfaces.SearchBarFinder;
public class JSearchBar extends JSearchTextField{
private static final long serialVersionUID = 1L;
protected static final File SYMBOLS_FILE = null;
protected SearchBarFinder finder;
protected SearchDropDown dropDown;
protected boolean completionActive = false;
protected String lastEntered = "";
private final JSearchBarController controller;
public JSearchBar() {
this(new DefaultSearchBarFinder());
}
public JSearchBar(SearchBarFinder finder) {
this.finder = finder;
this.dropDown = new SearchDropDown();
setFont(new Font("LigatureSymbols", Font.PLAIN, 13));
this.controller = new JSearchBarController(this);
controller.setDefaultState();
}
@Override
public void setVisible(boolean b) {
super.setVisible(b);
txtSearch.setText("\uE116 search");
txtSearch.setHorizontalAlignment(JTextField.CENTER);
}
protected void doCompletion() {
System.out.println("completion");
String[] tokens = this.finder.getSearchResults(txtSearch.getText());
if(tokens.length > 1) {
this.dropDown.putItems(tokens);
if(!this.dropDown.isVisible()) {
this.dropDown.setVisible(true);
}
}else {
if(this.dropDown.isVisible()) {
this.dropDown.setVisible(false);
}
}
}
protected void startCompletion() {
this.completionActive = true;
this.dropDown.setVisible(true);
}
protected void stopCompletion() {
this.completionActive = false;
this.dropDown.setVisible(false);
}
protected class SearchDropDown extends JWindow{
private static final long serialVersionUID = 1L;
private static final int ROW_COUNT = 5;
protected DefaultListModel<String> data = new DefaultListModel<>();
protected JList<String> list = new JList<>(data);
protected JScrollPane scrollPane = new JScrollPane(list);
public SearchDropDown() {
this.list.setVisibleRowCount(ROW_COUNT);
setAlwaysOnTop(true);
add(this.scrollPane);
}
public void putItems(String[] tokens) {
this.data.clear();
for(String token : tokens) {
this.data.addElement(token);
}
positionMenu();
}
public void positionMenu() {
JSearchBar parent = JSearchBar.this;
if(parent.isShowing()) {
if (this.list.getFixedCellHeight() < 0) {
this.list.setFixedCellHeight(this.getFontMetrics(this.getFont()).getHeight() + 2);
}
int x, y, width, height;
Dimension dim = parent.getSize();
x = parent.getLocationOnScreen().x;
y = parent.getLocationOnScreen().y + dim.height;
width = dim.width;
height = this.list.getFixedCellHeight() * ROW_COUNT;
setSize(new Dimension(width, height));
setLocation(x, y);
}
}
}
}