问题描述
我正在使用具有Java摆动和布局的简单文字处理器进行工作,并且我试图找出如何使单个文本块变为粗体,斜体或不同的字体大小,而不是使整个文本块在一次在我的JTextArea中.
I'm working on a simple word processor with java swing and layouts, and I'm trying to figure out how to make individual blocks of text bold, italics, or different font sizes instead of the whole block of text changing at once in my JTextArea.
当用户用鼠标突出显示JTextArea中的文本时,是否可以通过某种方式初始化String?如果有某种ActionListener或JTextArea可以检测到所有这些内容并轻松地将任何内容另存为字符串,我会喜欢它,但是我不确定是否可行.像这样的东西会很棒:
Is there some way to initialize a String as the user highlights the text in the JTextArea with their mouse? I would love it if there was some sort of ActionListener or something for JTextArea which could detect all this and easily save anything as a string, but I'm not sure if this is possible. Something like this would be great:
String selectedtext;
JTextArea type;
class TextPanel extends JPanel implements ActionListener
{
public TextPanel()
{
type = new JTextArea();
type.addActionListener(this);
this.add(type);
}
public void actionPerformed(ActionEvent e)
{
selectedtext = e.getSelected();
}
}
推荐答案
JTextArea没有任何内置功能可以做到这一点,但是:
JTextArea doesn't have any built-in functionality that will do this, but:
要使某人选择文本,他们必须单击文本区域,然后拖动并释放该单击.因此,附加一个MouseListener并实现mouseReleased方法来检查是否选择了任何文本,如果是,则将其保存为字符串:
In order for someone to select text, they have to click on the text area, drag and release the click. So, attach a MouseListener and implement the mouseReleased method to check if any text was selected, and if so to save it as a string:
public void mouseReleased(MouseEvent e) {
if (textArea.getSelectedText() != null) { // See if they selected something
String s = textArea.getSelectedText();
// Do work with String s
}
}
这篇关于如何使JTextArea中的选定文本成为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!