gpt4 book ai didi

java - 如何更改文本字段中的插入符号?

转载 作者:行者123 更新时间:2023-11-29 03:20:22 25 4
gpt4 key购买 nike

有没有办法将文本字段中闪烁的插入符号更改为另一个字符?我想把它从“|”改成到“>”。我所知道的就是改变颜色。

textField.setCaretColor(Color.WHITE);  

谢谢

最佳答案

基本上,您需要创建自己的 Caret 并绘制您想要的任何内容...

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());
}
}

}
}

这是基于这个 example

关于java - 如何更改文本字段中的插入符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24026774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com