下面列出了怎么用javax.swing.text.DefaultCaret的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Creates new form FrmTextEditor
*/
public FrmTextEditor() {
initComponents();
DefaultCaret caret = (DefaultCaret) this.jTextArea_Output.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
BufferedImage image = null;
try {
image = ImageIO.read(this.getClass().getResource("/images/snake.png"));
this.setIconImage(image);
} catch (Exception e) {
}
this.setScriptLanguage(_scriptLanguage);
addNewTextEditor("New file");
this._splitPanelSize = this.jSplitPane1.getBounds().getSize();
this.setSize(600, 600);
//this.jSplitPane1.setDividerLocation(0.6);
this.jSplitPane1.setDividerLocation(5);
//this.jScrollPane1.invalidate();
}
public SwingTextAreaWrapper(JTextArea textArea) {
this.textArea = textArea;
textArea.setEditable(true);
textArea.setFont(FONT);
final DefaultCaret caret = (DefaultCaret) textArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
node = new SwingNode();
JScrollPane sp = new JScrollPane(textArea);
textArea.setComponentPopupMenu(popupMenu);
node.setContent(sp);
popupMenu.add(saveToFileMenu);
}
@Override public void updateUI() {
super.updateUI();
setOpaque(false);
Caret caret = new DefaultCaret() {
// [UnsynchronizedOverridesSynchronized]
// Unsynchronized method damage overrides synchronized method in DefaultCaret
@SuppressWarnings("PMD.AvoidSynchronizedAtMethodLevel")
@Override protected synchronized void damage(Rectangle r) {
if (Objects.nonNull(r)) {
JTextComponent c = getComponent();
x = 0;
y = r.y;
width = c.getSize().width;
height = r.height;
c.repaint();
}
}
};
// caret.setBlinkRate(getCaret().getBlinkRate());
caret.setBlinkRate(UIManager.getInt("TextArea.caretBlinkRate"));
setCaret(caret);
}
public LogPanel() {
textArea.setLineWrap(true);
textArea.setEditable(false);
textArea.setWrapStyleWord(true);
DefaultCaret caret = (DefaultCaret) textArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(textArea);
setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);
textArea.addPopupMenu();
}
/**
* Creates a new password field.
*/
public MaterialPasswordField() {
setBorder(null);
setFont(getFont().deriveFont(16f)); //use default font, Roboto's bullet doesn't work on some platforms (i.e. Mac)
floatingLabel.setText("");
setOpaque(false);
setBackground(MaterialColor.TRANSPARENT);
setCaret(new DefaultCaret() {
@Override
protected synchronized void damage(Rectangle r) {
MaterialPasswordField.this.repaint(); //fix caret not being removed completely
}
});
getCaret().setBlinkRate(500);
}
public AbstractCodeArea(ContentPanel contentPanel) {
this.contentPanel = contentPanel;
this.node = contentPanel.getNode();
setMarkOccurrences(true);
setEditable(false);
setCodeFoldingEnabled(false);
loadSettings();
Caret caret = getCaret();
if (caret instanceof DefaultCaret) {
((DefaultCaret) caret).setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
}
caret.setVisible(true);
registerWordHighlighter();
}
private void initComponents() {
DefaultCaret caret = (DefaultCaret) statusTextArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
setAutoscrolls(true);
setPreferredSize(new Dimension(183, 115));
statusTextArea.setEditable(false);
statusTextArea.setColumns(20);
statusTextArea.setFont(new Font("Monospaced", 0, 11)); // NOI18N
statusTextArea.setLineWrap(true);
statusTextArea.setRows(5);
statusTextArea.setWrapStyleWord(true);
setViewportView(statusTextArea);
}
/**
* Displays the notification.
*
* @param notification The notification
*/
private void publish(UserNotification notification) {
DefaultCaret caret = (DefaultCaret) textArea.getCaret();
if (autoScroll) {
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
textArea.setCaretPosition(textArea.getDocument().getLength());
}
else {
caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
}
textArea.append(format(notification));
textArea.append("\n");
checkLength();
}
@Override
protected void initOutput() {
output = new MASColorTextPane(Color.black);
output.setEditable(false);
((DefaultCaret)output.getCaret()).setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
if (isTabbed()) {
tabPane.add(" all", new JScrollPane(output));
} else {
pcenter.add(BorderLayout.CENTER, new JScrollPane(output));
}
}
private MainPanel() {
super(new BorderLayout());
((DefaultCaret) textArea0.getCaret()).setUpdatePolicy(DefaultCaret.UPDATE_WHEN_ON_EDT); // default
((DefaultCaret) textArea1.getCaret()).setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
((DefaultCaret) textArea2.getCaret()).setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
JPanel p = new JPanel(new GridLayout(1, 0));
p.add(makeTitledPanel("UPDATE_WHEN_ON_EDT", new JScrollPane(textArea0)));
p.add(makeTitledPanel("ALWAYS_UPDATE", new JScrollPane(textArea1)));
p.add(makeTitledPanel("NEVER_UPDATE", new JScrollPane(textArea2)));
IntStream.range(0, 10).mapToObj(Integer::toString).forEach(this::test);
start.addActionListener(e -> startTest());
stop.setEnabled(false);
stop.addActionListener(e -> {
// TEST: timer.stop();
// TEST: thread = null;
if (Objects.nonNull(worker)) {
worker.cancel(true);
worker = null;
}
});
Box box = Box.createHorizontalBox();
box.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
box.add(Box.createHorizontalGlue());
box.add(check);
box.add(Box.createHorizontalStrut(5));
box.add(start);
box.add(Box.createHorizontalStrut(5));
box.add(stop);
add(p);
add(box, BorderLayout.SOUTH);
setPreferredSize(new Dimension(320, 240));
}
@Override
public void preferencesChanged(Map<String, String> preferences) {
DefaultCaret caret = (DefaultCaret)textArea.getCaret();
int updatePolicy = caret.getUpdatePolicy();
caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
decompile(preferences);
caret.setUpdatePolicy(updatePolicy);
super.preferencesChanged(preferences);
}
public static void main(String[] args) throws Exception {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
JTextArea jta = new JTextArea();
DefaultCaret dc = new DefaultCaret();
jta.setCaret(dc);
dc.deinstall(jta);
dc.mouseClicked(new MouseEvent(jta, MouseEvent.MOUSE_CLICKED, 0, 0, 0, 0, 0, false));
}
});
}
public static void main(String[] args) throws Exception {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
JTextArea jta = new JTextArea();
DefaultCaret dc = new DefaultCaret();
jta.setCaret(dc);
dc.deinstall(jta);
dc.mouseClicked(new MouseEvent(jta, MouseEvent.MOUSE_CLICKED, 0, 0, 0, 0, 0, false));
}
});
}
/**
* Sets the {@code SKIP_CLICK_COUNT} client property on the component
* if it is an instance of {@code JTextComponent} with a
* {@code DefaultCaret}. This property, used for text components acting
* as editors in a table or tree, tells {@code DefaultCaret} how many
* clicks to skip before starting selection.
*/
public static void setSkipClickCount(Component comp, int count) {
if (comp instanceof JTextComponent
&& ((JTextComponent) comp).getCaret() instanceof DefaultCaret) {
((JTextComponent) comp).putClientProperty(SKIP_CLICK_COUNT, count);
}
}
public static void main(String[] args) throws Exception {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
JTextArea jta = new JTextArea();
DefaultCaret dc = new DefaultCaret();
jta.setCaret(dc);
dc.deinstall(jta);
dc.mouseClicked(new MouseEvent(jta, MouseEvent.MOUSE_CLICKED, 0, 0, 0, 0, 0, false));
}
});
}
/**
* Initial settings
*/
protected void init()
{
// "support for SSL"
String handlerPkgs = System.getProperty("java.protocol.handler.pkgs");
if ((handlerPkgs != null) && !(handlerPkgs.isEmpty())) {
handlerPkgs = handlerPkgs + "|com.sun.net.ssl.internal.www.protocol";
} else {
handlerPkgs = "com.sun.net.ssl.internal.www.protocol";
}
System.setProperty("java.protocol.handler.pkgs", handlerPkgs);
java.security.Security
.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
// Create custom EditorKit if needed
if (swingBoxEditorKit == null) {
swingBoxEditorKit = new SwingBoxEditorKit();
}
setEditable(false);
setContentType("text/html");
activateTooltip(true);
Caret caret = getCaret();
if (caret instanceof DefaultCaret)
((DefaultCaret) caret).setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
}
/**
* Sets the {@code SKIP_CLICK_COUNT} client property on the component
* if it is an instance of {@code JTextComponent} with a
* {@code DefaultCaret}. This property, used for text components acting
* as editors in a table or tree, tells {@code DefaultCaret} how many
* clicks to skip before starting selection.
*/
public static void setSkipClickCount(Component comp, int count) {
if (comp instanceof JTextComponent
&& ((JTextComponent) comp).getCaret() instanceof DefaultCaret) {
((JTextComponent) comp).putClientProperty(SKIP_CLICK_COUNT, count);
}
}
@Override protected void paintComponent(Graphics g) {
super.paintComponent(g);
Caret c = getCaret();
if (c instanceof DefaultCaret) {
Graphics2D g2 = (Graphics2D) g.create();
Insets i = getInsets();
// int y = g2.getFontMetrics().getHeight() * getLineAtCaret(this) + i.top;
DefaultCaret caret = (DefaultCaret) c;
int y = caret.y + caret.height - 1;
g2.setPaint(LINE_COLOR);
g2.drawLine(i.left, y, getSize().width - i.left - i.right, y);
g2.dispose();
}
}
public ConsoleTab()
{
this.setLayout(_layout);
_cons.fill = GridBagConstraints.BOTH;
_cons.weightx = 1;
_cons.weighty = 1;
_cons.insets = new Insets(5,5,5,5);
_textPane = new JTextArea();
_textPane.setEditable(false);
DefaultCaret caret = (DefaultCaret)_textPane.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
this.add(new JScrollPane(_textPane,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED),_cons);
}
/**
* Sets the {@code SKIP_CLICK_COUNT} client property on the component
* if it is an instance of {@code JTextComponent} with a
* {@code DefaultCaret}. This property, used for text components acting
* as editors in a table or tree, tells {@code DefaultCaret} how many
* clicks to skip before starting selection.
*/
public static void setSkipClickCount(Component comp, int count) {
if (comp instanceof JTextComponent
&& ((JTextComponent) comp).getCaret() instanceof DefaultCaret) {
((JTextComponent) comp).putClientProperty(SKIP_CLICK_COUNT, count);
}
}
@Override protected void paintComponent(Graphics g) {
Caret c = getCaret();
if (c instanceof DefaultCaret) {
Graphics2D g2 = (Graphics2D) g.create();
Insets i = getInsets();
DefaultCaret caret = (DefaultCaret) c;
int h = caret.height;
int y = caret.y;
g2.setPaint(LINE_COLOR);
g2.fillRect(i.left, y, getSize().width - i.left - i.right, h);
g2.dispose();
}
super.paintComponent(g);
}
private MainPanel() {
super(new BorderLayout());
JTextField field1 = new JTextField("0987654321");
field1.setSelectedTextColor(Color.RED);
field1.setSelectionColor(Color.GREEN);
HighlightPainter selectionPainter = new DefaultHighlightPainter(Color.WHITE) {
@Override public Shape paintLayer(Graphics g, int offs0, int offs1, Shape bounds, JTextComponent c, View view) {
Shape s = super.paintLayer(g, offs0, offs1, bounds, c, view);
if (s instanceof Rectangle) {
Rectangle r = (Rectangle) s;
g.setColor(Color.ORANGE);
g.fillRect(r.x, r.y + r.height - 2, r.width, 2);
}
return s;
}
};
Caret caret = new DefaultCaret() {
@Override protected HighlightPainter getSelectionPainter() {
return selectionPainter;
}
};
JTextField field2 = new JTextField("123465789735");
caret.setBlinkRate(field2.getCaret().getBlinkRate());
field2.setSelectedTextColor(Color.RED);
field2.setCaret(caret);
Box box = Box.createVerticalBox();
box.add(makeTitledPanel("Default", new JTextField("12345")));
box.add(Box.createVerticalStrut(10));
box.add(makeTitledPanel("JTextComponent#setSelectionColor(...)", field1));
box.add(Box.createVerticalStrut(10));
box.add(makeTitledPanel("JTextComponent#setCaret(...)", field2));
box.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
add(box, BorderLayout.NORTH);
setPreferredSize(new Dimension(320, 240));
}
public static void main(String[] args) {
DefaultCaret caret = new DefaultCaret();
for (int i = 0; i < 10; i++) {
boolean active = (i % 2 == 0);
caret.setVisible(active);
if (caret.isActive() != active) {
throw new RuntimeException("caret.isActive() does not equal: " + active);
}
}
}
protected void initOutput() {
output = new JTextArea();
output.setEditable(false);
((DefaultCaret)output.getCaret()).setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
if (isTabbed) {
tabPane.add("common", new JScrollPane(output));
} else {
pcenter.add(BorderLayout.CENTER, new JScrollPane(output));
}
}
private void jCheckBoxLogActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxLogActionPerformed
DefaultCaret caret = (DefaultCaret) jTextArea1.getCaret();
if (jCheckBoxLog.isSelected()) {
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
jTextArea1.setCaretPosition(jTextArea1.getDocument().getLength());
jScrollPaneLog.setViewportView(jTextArea1);
}
else caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
}
@Override
public void setText(byte[] message) {
caret = (DefaultCaret) editor.getCaret();
caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
if (message != null) {
editor.setText(helpers.bytesToString(message));
}
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
searchIndex = -1;
}
protected void restoreLegacyCaret(Caret caret) {
if (caret instanceof DefaultCaret) {
((DefaultCaret)caret).setDot(getOffset(dotOffsetAndBias), getBias(dotOffsetAndBias));
} else {
caret.setDot(getOffset(dotOffsetAndBias));
}
}
private void setupTextPane(final JTextPane textPane, String comment) {
if( UIUtils.isNimbus() ) {
textPane.setUI( new BasicTextPaneUI() );
}
textPane.setText(comment);
Caret caret = textPane.getCaret();
if (caret instanceof DefaultCaret) {
((DefaultCaret)caret).setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
}
// attachments
if (!attachmentIds.isEmpty()) {
AttachmentHyperlinkSupport.Attachement a = AttachmentHyperlinkSupport.findAttachment(comment, attachmentIds);
if (a != null) {
String attachmentId = a.id;
if (attachmentId != null) {
int index = attachmentIds.indexOf(attachmentId);
if (index != -1) {
BugzillaIssue.Attachment attachment = attachments.get(index);
AttachmentLink attachmentLink = new AttachmentLink(attachment);
HyperlinkSupport.getInstance().registerLink(textPane, new int[] {a.idx1, a.idx2}, attachmentLink);
} else {
Bugzilla.LOG.log(Level.WARNING, "couldn''t find attachment id in: {0}", comment); // NOI18N
}
}
}
}
// pop-ups
textPane.setComponentPopupMenu(commentsPopup);
textPane.setBackground(blueBackground);
textPane.setBorder(BorderFactory.createEmptyBorder(3,3,3,3));
textPane.setEditable(false);
textPane.getAccessibleContext().setAccessibleName(NbBundle.getMessage(CommentsPanel.class, "CommentsPanel.textPane.AccessibleContext.accessibleName")); // NOI18N
textPane.getAccessibleContext().setAccessibleDescription(NbBundle.getMessage(CommentsPanel.class, "CommentsPanel.textPane.AccessibleContext.accessibleDescription")); // NOI18N
}
public ResultSetTableCellEditor(final JTextField textField) {
super(textField);
delegate = new EditorDelegate() {
@Override
public void setValue(Object value) {
val = value;
textField.setText((value != null) ? value.toString() : "");
}
@Override
public boolean isCellEditable(EventObject evt) {
if (evt instanceof MouseEvent) {
return ((MouseEvent) evt).getClickCount() >= 2;
}
return true;
}
@Override
public Object getCellEditorValue() {
String txtVal = textField.getText();
if (val == null && txtVal.equals("")) {
return null;
} else {
return txtVal;
}
}
};
textField.addActionListener(delegate);
// #204176 - workarround for MacOS L&F
textField.setCaret(new DefaultCaret());
}
public static void main(String[] args) {
DefaultCaret caret = new DefaultCaret();
for (int i = 0; i < 10; i++) {
boolean active = (i % 2 == 0);
caret.setVisible(active);
if (caret.isActive() != active) {
throw new RuntimeException("caret.isActive() does not equal: " + active);
}
}
}