我们想在JComboBox
a中添加一些词JTextArea
,但我们希望这些词成为块。
我的意思是当用户试图从这个块中删除一个字母时,整个块将被删除。
例子:
让块词为“Title”,那么当我们在 a 中有这个块时JTextArea
,我们将其作为一个字母处理。
我们怎么能做到这一点?
我们想在JComboBox
a中添加一些词JTextArea
,但我们希望这些词成为块。
我的意思是当用户试图从这个块中删除一个字母时,整个块将被删除。
例子:
让块词为“Title”,那么当我们在 a 中有这个块时JTextArea
,我们将其作为一个字母处理。
我们怎么能做到这一点?
获取JTextArea
的文档并添加DocumentFilter
. 检查事件的偏移量是否在块文本内并跳过事件(删除或插入)
您也许可以像这样将 customEditorKit 附加到jetTextPane:
1. 扩展EditorKit
并覆盖ViewFactory
以返回 CustomViewFactory 的实例2.
实现并返回BoxView、ComponentView、IconView(如果要添加一些图标 + 文本)等的覆盖方法。create
CustomViewFactory
ViewFactory
如评论中所述,您可以使用JTextPane
将 a 添加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);
}
}