[英]How to change the caret in a textfield?
有沒有辦法將文本字段中閃爍的插入符號更改為另一個字符? 我想將其從“ |”更改為 到“>”。 我只知道改變顏色。
textField.setCaretColor(Color.WHITE);
謝謝
基本上,您需要創建自己的Caret
並繪制所需的內容...
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.Rectangle;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.plaf.TextUI;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultCaret;
import javax.swing.text.Document;
import javax.swing.text.Element;
import javax.swing.text.JTextComponent;
import javax.swing.text.Position;
public class CaretExample {
public static void main(String[] args) {
new CaretExample();
}
public CaretExample() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JTextField field = new JTextField(10);
field.setCaret(new MyCaret());
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(field);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MyCaret extends DefaultCaret {
private String mark = "<";
public MyCaret() {
setBlinkRate(500);
}
@Override
protected synchronized void damage(Rectangle r) {
if (r == null) {
return;
}
JTextComponent comp = getComponent();
FontMetrics fm = comp.getFontMetrics(comp.getFont());
int textWidth = fm.stringWidth(">");
int textHeight = fm.getHeight();
x = r.x;
y = r.y;
width = textWidth;
height = textHeight;
repaint(); // calls getComponent().repaint(x, y, width, height)
}
@Override
public void paint(Graphics g) {
JTextComponent comp = getComponent();
if (comp == null) {
return;
}
int dot = getDot();
Rectangle r = null;
try {
r = comp.modelToView(dot);
} catch (BadLocationException e) {
return;
}
if (r == null) {
return;
}
if ((x != r.x) || (y != r.y)) {
repaint(); // erase previous location of caret
damage(r);
}
if (isVisible()) {
FontMetrics fm = comp.getFontMetrics(comp.getFont());
int textWidth = fm.stringWidth(">");
int textHeight = fm.getHeight();
g.setColor(comp.getCaretColor());
g.drawString(mark, x, y + fm.getAscent());
}
}
}
}
這是基於此示例
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.