0

我们想在JComboBoxa中添加一些词JTextArea,但我们希望这些词成为块。

我的意思是当用户试图从这个块中删除一个字母时,整个块将被删除。

例子:

让块词为“Title”,那么当我们在 a 中有这个块时JTextArea,我们将其作为一个字母处理。

我们怎么能做到这一点?

4

3 回答 3

1

获取JTextArea的文档并添加DocumentFilter. 检查事件的偏移量是否在块文本内并跳过事件(删除或插入)

于 2012-12-20T05:51:13.350 回答
1

您也许可以像这样将 customEditorKit 附加到jetTextPane
1. 扩展EditorKit并覆盖ViewFactory以返回 CustomViewFactory 的实例2.
实现并返回BoxView、ComponentView、IconView(如果要添加一些图标 + 文本)等的覆盖方法。createCustomViewFactoryViewFactory

于 2012-12-19T22:07:43.403 回答
0

如评论中所述,您可以使用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);
    }
}
于 2012-12-19T21:43:44.683 回答