JTextFieldでコードアシストもどき 2008/09/10

Javaです。Swingです。そしてJTextFieldです。

JFaceでコードアシストをためしてみていい感じだったので、今度は、swingでできないかとチャレンジ。



まず、getKeymapでKeyStrokeの登録。"ctrl SPACE"で行う。
Actionで、textFiledでイベントが発生した場所から、実際のポップアップを表示を特定します。
で、ここではた悩む。とりあえず、API調べてみて、よさげなものをみつけて試してみました。
getCaretPositionを使って現在のビームの位置をもとめます。さらに、modelToViewメソッドを使ってキャレット位置からViewの座標に変換(※この説明が正しいかいささか自信ないですがとりあえずうまくいったようなので)この値を使ってポップアップが表示される位置をもとめます。

modelToViewはRectangleを返します。

ポップアップメニューを使ってコードアシストもどきを表現して選択されたら、そのアクションでtextFieldのほうに値を挿入します。

次はJTextPaneで試してみましょうか。

import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeListener;

import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.text.BadLocationException;

public class TestKeyStroke {

public static void main(String[] args) {

JFrame frame = new JFrame();
JTextField textField = new JTextField();
textField.getKeymap().addActionForKeyStroke(
KeyStroke.getKeyStroke("ctrl SPACE"), new Action() {

public void addPropertyChangeListener(
PropertyChangeListener listener) {

}

public Object getValue(String key) {
return null;
}
public boolean isEnabled() {
// !!!!!!!!
return true;
}

public void putValue(String key, Object value) {

}

public void removePropertyChangeListener(
PropertyChangeListener listener) {
}

public void setEnabled(boolean b) {
}

/**
* イベントが発生したコンポーネントでJWindowを表示してみる
*/
public void actionPerformed(ActionEvent e) {
System.out.println(e.getSource());
final JTextField textField = (JTextField) e.getSource();
final int p = textField.getCaretPosition();
Rectangle rectangle;
try {
rectangle = textField.modelToView(p);

JPopupMenu popupMenu = new JPopupMenu();

ActionListener actionListener = new ActionListener() {

public void actionPerformed(ActionEvent e) {
try {
textField.getDocument().insertString(p,
e.getActionCommand(), null);
} catch (BadLocationException e1) {
e1.printStackTrace();
}

}

};
System.out.println(rectangle);
popupMenu.add("テストです").addActionListener(
actionListener);
popupMenu.add("0_0!").addActionListener(
actionListener);
popupMenu.add("^_^!").addActionListener(
actionListener);
popupMenu.add("o_o!").addActionListener(
actionListener);
popupMenu.show(textField, rectangle.x, rectangle.y
+ rectangle.height);
} catch (BadLocationException e1) {
e1.printStackTrace();
}

}
});

frame.getContentPane().add(textField);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setAlwaysOnTop(true);
frame.setVisible(true);

}
}

: