JavaでオートコンプリートJComboBoxを実装するにはどうすればよいですか?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;
public class AutoCompleteComboBoxTest extends JFrame {
private JComboBox comboBox;
public AutoCompleteComboBoxTest() {
setTitle("AutoCompleteComboBox");
String[] countries = new String[] {"india", "australia", "newzealand", "england", "germany",
"france", "ireland", "southafrica", "bangladesh", "holland", "america"};
comboBox = new AutoCompleteComboBox(countries);
add(comboBox, BorderLayout.NORTH);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String []args) {
new AutoCompleteComboBoxTest();
}
}
// Implementtion of AutoCompleteComboBox
class AutoCompleteComboBox extends JComboBox {
public int caretPos = 0;
public JTextField tfield = null;
public AutoCompleteComboBox(final Object countries[]) {
super(countries);
setEditor(new BasicComboBoxEditor());
setEditable(true);
}
public void setSelectedIndex(int index) {
super.setSelectedIndex(index);
tfield.setText(getItemAt(index).toString());
tfield.setSelectionEnd(caretPos + tfield.getText().length());
tfield.moveCaretPosition(caretPos);
}
public void setEditor(ComboBoxEditor editor) {
super.setEditor(editor);
if(editor.getEditorComponent() instanceof JTextField) {
tfield = (JTextField) editor.getEditorComponent();
tfield.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent ke) {
char key = ke.getKeyChar();
if (!(Character.isLetterOrDigit(key) || Character.isSpaceChar(key) )) return;
caretPos = tfield.getCaretPosition();
String text="";
try {
text = tfield.getText(0, caretPos);
} catch (javax.swing.text.BadLocationException e) {
e.printStackTrace();
}
for (int i=0; i < getItemCount(); i++) {
String element = (String) getItemAt(i);
if (element.startsWith(text)) {
setSelectedIndex(i);
return;
}
}
}
});
}
}
}
-
JavaでJToggleButtonを実装するにはどうすればよいですか?
JToggleButton JToggleButton AbstractButtonの拡張です また、オンに切り替えることができるボタンを表すために使用できます。 およびオフ 。 JToggleButtonの場合 を初めて押すと、押したままになり、2回押すと離すことができます。 JToggleButton ActionEventを生成します 押すたびに。 JToggleButton ItemEventを生成することもできます 、このイベントは、選択の概念をサポートするコンポーネントによって使用されます。 JToggleButtonの場合 を押すと選択されます。
-
JavaでJWindowを使用してスプラッシュ画面を実装するにはどうすればよいですか?
JWindow は、ユーザーのデスクトップのどこにでも表示できるコンテナです。 タイトルバーはありません 、ウィンドウ 管理 ボタン、 JFrameのようなものです。 JWindow JRootPaneが含まれています その唯一の子クラスとして。 contentPane JWindowの子の親になることができます 。 JFrameのように 、 JWindow は別のトップレベルのコンテナであり、装飾されていないJFrameとして機能します。 タイトルバー、ウィンドウメニューなどの機能はありません 、など。 JWindow スプラッシュ画面ウィンドウとして使用できます これ