JTextComponent 3
ナビゲーションに移動
検索に移動
JTextComponent 3
- ドキュメントの変更を感知
- キャレットの状態を感知
import java.awt.BorderLayout; import java.awt.Rectangle; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import javax.swing.event.CaretEvent; import javax.swing.event.CaretListener; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; /** * @see http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html */ public class JTextTest3 { private JFrame frame; private JTextArea txtArea; private JLabel changeStats; private CaretListenerLabel caretStats; private void createUI() { frame = new JFrame("TextTest3"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); caretStats = new CaretListenerLabel("caret:"); changeStats = new JLabel("change:"); JPanel statusPanel = new JPanel(new BorderLayout()); statusPanel.add(changeStats, BorderLayout.CENTER); statusPanel.add(caretStats, BorderLayout.SOUTH); txtArea = new JTextArea(10, 30); JPanel basePanel = new JPanel(new BorderLayout()); basePanel.add(new JScrollPane(txtArea), BorderLayout.CENTER); basePanel.add(statusPanel, BorderLayout.SOUTH); txtArea.getDocument().addDocumentListener( new MyDocumentListener()); txtArea.addCaretListener(caretStats); frame.getContentPane().add(basePanel); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater( new Runnable(){ public void run() { JTextTest3 jft = new JTextTest3(); jft.createUI(); } } ); } /** * ドキュメントの変更を感知 */ class MyDocumentListener implements DocumentListener { public void changedUpdate(DocumentEvent e) { changeStats.setText("chage:chage"); } public void insertUpdate(DocumentEvent e) { changeStats.setText("change:insert"); } public void removeUpdate(DocumentEvent e) { changeStats.setText("change:remove"); } } /** * キャレットの状態を感知 */ @SuppressWarnings("serial") class CaretListenerLabel extends JLabel implements CaretListener { public CaretListenerLabel(String label) { super(label); } public void caretUpdate(CaretEvent e) { try { int dot = e.getDot(); // モデル内の指定された位置を、ビュー座標系内の場所に変換 Rectangle rect = txtArea.modelToView(dot); caretStats.setText("caret: text pos=" + dot + " view location [" + rect.x + "," + rect.y + "]"); } catch (Exception ex) { ex.printStackTrace(); } } } }
© 2006 矢木浩人