【问题标题】:How to set Color for selected Text in java? [closed]如何在java中为选定的文本设置颜色? [关闭]
【发布时间】:2015-05-03 13:13:24
【问题描述】:

请任何人帮助仅设置所选文本的颜色...我已经创建了一个简单的文本编辑器...但是,我无法为所选文本内容设置颜色...一旦,我选择了颜色它将影响整个文本区域而不是选定区域。

请帮助任何人,

提前致谢。

for Example : 

现在我只选择 Kumar..所以,将只选择所选文本的颜色..但是,我的问题是也更改未选择文本的颜色..

怎么解决??????

【问题讨论】:

  • 你有没有尝试过?能给点代码吗?
  • 你能提供一些代码,和...钱吗?
  • 在 JTextComponent 的文档中查找方法 setSelectedTextColorsetSelectionColor
  • 颜色颜色 = JColorChooser.showDialog(null, "选择一种颜色", Color.blue);此代码仅我现在正在使用...它将返回选定的颜色..现在,我只想为选定的文本设置此颜色..请帮助我
  • 代码,代码,代码总是关于它,如果您尝试过任何事情,请不要只提供纯文本。

标签: java swing selection jtextarea


【解决方案1】:

你用什么组件来显示你的文本? 如果是 JTextArea,那就不可能了。 您需要一个允许不同样式的组件。例如 JTextPane 中的 StyledDocument。 欲了解更多信息,请参阅How to Use Editor Panes and Text Panes

【讨论】:

  • +1 获取教程链接,但如果您查看Text Component Features 部分,还有一个更好的示例。
【解决方案2】:

你可以试试下一个:

public static void main(String[] args) {

    final JFrame frame = new JFrame("Selected Color Example");
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    final JTextArea area = new JTextArea("Text for test...", 5, 10);
    frame.add(area, BorderLayout.CENTER);

    JButton button = new JButton("Select Color");
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Color color = JColorChooser.showDialog(frame, "Colors",
                    Color.BLUE);
            area.selectAll();
            // area.setSelectedTextColor(color); // color of selected text
            area.setSelectionColor(color); // background of selected text
            area.requestFocusInWindow();
        }
    });
    frame.add(button, BorderLayout.PAGE_END);

    frame.pack();
    frame.setVisible(true);

}

【讨论】:

    猜你喜欢
    • 2021-08-25
    • 1970-01-01
    • 2014-05-07
    • 1970-01-01
    • 2012-02-24
    • 2011-02-27
    • 2010-10-28
    • 2015-07-12
    • 1970-01-01
    相关资源
    最近更新 更多