2

我正在编写一个 Swing 应用程序,我有一个朋友读了很多圣经。这个应用程序有文本或段落搜索。

但我的朋友只能看到大字体对比色。我更改了textFieldwith的插入符号的颜色setCaretColor,用户在其中输入要搜索的文本。

插入符号显示为具有相同字体高度的矩形,但宽度很小,我认为我的朋友看不到。

有没有办法改变插入符号的宽度以显示更大?

4

3 回答 3

4

您是否从网上流传的 Oreilly Swing 书中看到了这个例子?看来您可以自定义插入符号很多。

http://www.java2s.com/Code/Java/Swing-JFC/Fanciercustomcaretclass.htm

于 2012-04-25T15:54:50.507 回答
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();
            }
        });
    }
}
于 2012-04-25T16:44:57.270 回答
3

可能这可以帮助 http://java-sl.com/tip_overwrite_mode.html

于 2012-04-25T16:02:56.983 回答