reformat
[nikiroo-utils.git] / src / be / nikiroo / fanfix_swing / gui / SearchBar.java
... / ...
CommitLineData
1
2package be.nikiroo.fanfix_swing.gui;
3
4import java.awt.BorderLayout;
5import java.awt.event.ActionEvent;
6import java.awt.event.ActionListener;
7import java.awt.event.KeyAdapter;
8import java.awt.event.KeyEvent;
9
10import javax.swing.JButton;
11import javax.swing.JTextField;
12import javax.swing.SwingUtilities;
13
14import be.nikiroo.fanfix_swing.gui.utils.ListenerPanel;
15import be.nikiroo.fanfix_swing.gui.utils.UiHelper;
16import be.nikiroo.fanfix_swing.images.IconGenerator;
17import be.nikiroo.fanfix_swing.images.IconGenerator.Icon;
18import be.nikiroo.fanfix_swing.images.IconGenerator.Size;
19
20/**
21 * A generic search/filter bar.
22 *
23 * @author niki
24 */
25public class SearchBar extends ListenerPanel {
26 static private final long serialVersionUID = 1L;
27
28 private JButton search;
29 private JTextField text;
30 private JButton clear;
31
32 private boolean realTime;
33
34 /**
35 * Create a new {@link SearchBar}.
36 */
37 public SearchBar() {
38 setLayout(new BorderLayout());
39
40 search = new JButton(IconGenerator.get(Icon.search, Size.x16));
41 UiHelper.setButtonPressed(search, realTime);
42 search.addActionListener(new ActionListener() {
43 @Override
44 public void actionPerformed(ActionEvent e) {
45 realTime = !realTime;
46 UiHelper.setButtonPressed(search, realTime);
47 text.requestFocus();
48
49 if (realTime) {
50 fireActionPerformed(getText());
51 }
52 }
53 });
54
55 text = new JTextField();
56 text.addKeyListener(new KeyAdapter() {
57 @Override
58 public void keyTyped(final KeyEvent e) {
59 super.keyTyped(e);
60 SwingUtilities.invokeLater(new Runnable() {
61 @Override
62 public void run() {
63 boolean empty = (text.getText().isEmpty());
64 clear.setVisible(!empty);
65
66 if (realTime) {
67 fireActionPerformed(getText());
68 }
69 }
70 });
71 }
72 });
73 text.addActionListener(new ActionListener() {
74 @Override
75 public void actionPerformed(ActionEvent e) {
76 if (!realTime) {
77 fireActionPerformed(getText());
78 }
79 }
80 });
81
82 clear = new JButton(IconGenerator.get(Icon.clear, Size.x16));
83 clear.setBackground(text.getBackground());
84 clear.setVisible(false);
85 clear.addActionListener(new ActionListener() {
86 @Override
87 public void actionPerformed(ActionEvent e) {
88 text.setText("");
89 clear.setVisible(false);
90 text.requestFocus();
91
92 fireActionPerformed(getText());
93 }
94 });
95
96 add(search, BorderLayout.WEST);
97 add(text, BorderLayout.CENTER);
98 add(clear, BorderLayout.EAST);
99 }
100
101 /**
102 * Return the current text displayed by this {@link SearchBar}.
103 *
104 * @return the text
105 */
106 public String getText() {
107 return text.getText();
108 }
109}