2012-12-19 18 views
0

我們想從JComboBox添加一些單詞到JTextArea,但我們希望這些單詞是塊。將一些單詞作爲塊添加到JTextarea

我的意思是,當用戶試圖從這個塊中刪除一個字母時,整個塊將被刪除。

例子:

讓模塊字是「標題」,那麼當我們在JTextArea有該程序,我們對待它作爲一個字母。

我們該怎麼做?

+0

可能不在JTextArea中,請嘗試使用JTextPane或類似的東西。 – 11684

回答

0

如評論中所述,您可以使用JTextPaneComponent添加到文本區域。然後它總是被視爲一個整體詞。這裏有一個例子:

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); 
    } 
} 
1

你或許可以連接到customEditorKit jetTextPane這樣的:
1.擴展EditorKit,並覆蓋ViewFactory
2.重寫方法createCustomViewFactory返回CustomViewFactory的實例實現ViewFactory並返回
BoxView中,ComponentView軟件,圖標型控件(如果你想添加一些圖標+文字)等

1

獲取JTextArea的文件,並添加DocumentFilter。檢查是否有事件偏移量在塊文本中,並跳過事件(刪除或插入)