我们想将一些单词从JComboBox
添加到JTextArea
,但我们希望这些单词作为块。
我的意思是,当用户尝试从此块中删除字母时,整个块将被删除。
例:
设块词为"标题",那么当我们在JTextArea
中有这个块时,我们将其处理为一个字母。
我们该怎么做呢?
你也许可以像这样将 customEditorKit 附加到 jetTextPane:
1. 扩展EditorKit
并覆盖ViewFactory
以返回 CustomViewFactory
的实例2.覆盖CustomViewFactory
中实现ViewFactory
的方法create
并返回
BoxView,组件视图,图标视图(如果要添加一些图标+文本)等。
获取JTextArea
的文档并添加一个DocumentFilter
。检查事件偏移量是否在块文本内并跳过事件(删除或插入)
如注释中所述,您可以使用JTextPane
向文本区域添加Component
。 然后它总是被视为一个完整的词。 下面是一个示例:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TextComponent extends Box{
public TextComponent(){
super(BoxLayout.Y_AXIS);
final JTextPane textArea = new JTextPane();
textArea.setAlignmentX(CENTER_ALIGNMENT);
add(textArea);
JButton addText = new JButton("Add Text");
addText.setAlignmentX(CENTER_ALIGNMENT);
addText.addActionListener(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
JLabel text = new JLabel("Original Text");
text.setAlignmentY(0.8f);
text.setOpaque(true);
text.setBackground(Color.yellow);
textArea.insertComponent(text);
}});
add(addText);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new TextComponent());
frame.pack();
frame.setVisible(true);
}
}