我需要让用户在单击按钮时更改文本颜色。当有选择时这很好 - 文本会改变它的颜色。However when selection length is 0, when I only have the caret, nothing will be changed, and that is perfectly normal.
但是,用户会期望他在按钮单击后在该位置键入的下一个字符会改变颜色,这不会发生。
尝试打开一个 MS Word 文档,输入一些文本,单击 RIGHT BEFORE 或 RIGHT AFTER A WORD。不要点击单词本身。现在更改文本的颜色 - 什么都不会发生(可见)。继续输入 - 输入文本的颜色是您将其更改为的颜色。
现在尝试对下面的程序做同样的事情,颜色不会改变。我怎样才能让它发生?
这是一个 SSCCE,为了您的方便,它只是普通的 Java 7,没有特殊的东西:
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
public class Main
{
public static void main(String[] args)
{
JFrame a = new JFrame("Test");
a.setSize(600, 900);
a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
a.getContentPane().setLayout(new BoxLayout(a.getContentPane(), BoxLayout.Y_AXIS));
final JTextPane b = new JTextPane();
b.addFocusListener(new FocusListener()
{
@Override
public void focusGained(FocusEvent arg0)
{
b.repaint();
}
@Override
public void focusLost(FocusEvent arg0)
{
b.repaint();
}
});
StyleContext context = new StyleContext();
final Style styleA = context.addStyle("A", null);
final Style styleB = context.addStyle("B", null);
StyleConstants.setForeground(styleA, Color.BLUE);
StyleConstants.setForeground(styleB, Color.RED);
try
{
b.getStyledDocument().insertString(0, "blablablablabla", styleA);
}
catch (BadLocationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
JButton c = new JButton("click me");
c.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
b.getStyledDocument().setCharacterAttributes(b.getSelectionStart(), b.getSelectionEnd() - b.getSelectionStart(), styleB, true);
b.grabFocus();
}
});
a.getContentPane().add(b);
a.getContentPane().add(c);
a.setVisible(true);
}
}