Java Reference
In-Depth Information
final JTextField dot = new JTextField();
dot.setEditable(false);
JPanel dotPanel = new JPanel(new BorderLayout());
dotPanel.add(new JLabel("Dot: "), BorderLayout.WEST);
dotPanel.add(dot, BorderLayout.CENTER);
frame.add(dotPanel, BorderLayout.NORTH);
final JTextField mark = new JTextField();
mark.setEditable(false);
JPanel markPanel = new JPanel(new BorderLayout());
markPanel.add(new JLabel("Mark: "), BorderLayout.WEST);
markPanel.add(mark, BorderLayout.CENTER);
frame.add(markPanel, BorderLayout.SOUTH);
CaretListener listener = new CaretListener() {
public void caretUpdate(CaretEvent caretEvent) {
dot.setText(Integer.toString(caretEvent.getDot()));
mark.setText(Integer.toString(caretEvent.getMark()));
}
};
textArea.addCaretListener(listener);
frame.setSize(250, 150);
frame.setVisible(true);
}
};
EventQueue.invokeLater(runner);
}
}
NavigationFilter Class
Similar to the way you can limit input to the text component's document by associating
a DocumentFilter with a Document , you can limit where the caret can go by associating a
NavigationFilter with a JTextComponent . The class has three methods:
public void setDot(NavigationFilter.FilterBypass fb, int dot, Position.Bias bias)
public void moveDot(NavigationFilter.FilterBypass fb, int dot, Position.Bias bias)
public int getNextVisualPositionFrom(JTextComponent text, int pos,
Position.Bias bias, int direction, Position.Bias[] biasRet)
To limit movement, you would typically override the first two, leaving the default imple-
mentation of the latter. For instance, Listing 15-11 shows a program that has a reserved area
(say, the title of a report) at the beginning of the JTextArea . If you try to set or move the caret
(dot) to the reserved area, the filter rejects the change and moves the caret to after the area.
Search WWH ::




Custom Search