我正在编写一个Swing应用程序,我有一个朋友读了很多圣经。这个应用程序按文本或段落搜索。
但我的朋友只能看到大字体和对比色。我使用textField
更改setCaretColor
的插入符号颜色,用户输入要搜索的文本。
插入符号显示为具有相同 hight 字体的矩形,但宽度很少,我认为我的朋友看不到。
有没有办法更改插入符号的宽度以显示更大?
答案 0 :(得分:4)
你是否看过Oreilly Swing书中的这个例子,它漂浮在互联网上?您似乎可以自定义插入符号。
http://www.java2s.com/Code/Java/Swing-JFC/Fanciercustomcaretclass.htm
答案 1 :(得分:4)
我可以通过三种方式重现Caret
和JTextComponents
中的选择
import java.awt.Color;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.DefaultCaret;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
public class TextFieldExample extends JFrame {
private static final long serialVersionUID = 1L;
public TextFieldExample() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JPanel panel = new JPanel();
JTextField tfield = new JTextField(10);
tfield.setText("default text");
final JTextField tfield2 = new JTextField(10);
tfield2.setText("default text");
tfield2.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent fe) {
tfield2.setCaretPosition(tfield2.getDocument().getLength());
}
public void focusLost(FocusEvent fe) {
}
});
JTextField tfield3 = new JTextField(10);
tfield3.setText("default text");
tfield3.setCaret(new HighlightCaret());
panel.add(tfield);
panel.add(tfield2);
panel.add(tfield3);
add(panel);
pack();
setVisible(true);
}
class HighlightCaret extends DefaultCaret {
private final Highlighter.HighlightPainter unfocusedPainter =
new DefaultHighlighter.DefaultHighlightPainter(new Color(230, 230, 210));
private static final long serialVersionUID = 1L;
private boolean isFocused;
@Override
protected Highlighter.HighlightPainter getSelectionPainter() {
return isFocused ? super.getSelectionPainter() : unfocusedPainter;
}
@Override
public void setSelectionVisible(boolean hasFocus) {
if (hasFocus != isFocused) {
isFocused = hasFocus;
super.setSelectionVisible(false);
super.setSelectionVisible(true);
}
}
}
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TextFieldExample textFieldExample = new TextFieldExample();
}
});
}
}
答案 2 :(得分:3)