2013-04-04 81 views
3

我在嘗試將JButton添加到帶有String的JTextPane時出現問題。所以我想要做的是在for循環中添加每個字符串,然後在添加String之後添加廣告JButton。下面的代碼是我正在嘗試完成的。將JButton添加到JTextPane

ArrayLst<String> data = new ArrayList(); 
data.add("Data here"); 
data.add("Data here 2"); 
data.add("Data here 3"); 
data.add("Data here 4"); 

Container cp = getContentPane(); 

JTextPane pane = new JTextPane(); 
SimpleAttributeSet set = new SimpleAttributeSet(); 
StyleConstants.setBold(set, true); 
pane.setBackground(Color.BLUE); 
pane.setEditable(false); 

Document doc = pane.getStyledDocument(); 

for(int i=0; i<data.size(); i++) 
{ 
    doc.insertString(doc.getLength(), data.get(i)+ "\n", set); 
    pane.insertComponent(new JButton("View Info")); 
} 

誰能告訴我如何將JButton添加到同一行上的每個字符串?

非常感謝讚賞

回答

4

你可以嘗試這樣的:
enter image description here

import javax.swing.*; 
import javax.swing.text.*; 
import java.awt.event.*; 
import java.awt.*; 
import java.util.*; 

class TextPaneDemo extends JFrame 
{ 
    public void createAndShowGUI()throws Exception 
    { 
     JTextPane tp = new JTextPane(); 
     ArrayList<String> data = new ArrayList(); 
     data.add("Data here"); 
     data.add("Data here 2"); 
     data.add("Data here 3"); 
     data.add("Data here 4"); 
     getContentPane().add(tp); 
     setSize(300,400); 
     StyledDocument doc = tp.getStyledDocument(); 
     SimpleAttributeSet attr = new SimpleAttributeSet(); 
     for (String dat : data) 
     { 
      doc.insertString(doc.getLength(), dat, attr); 
      tp.setCaretPosition(tp.getDocument().getLength()); 
      tp.insertComponent(new JButton("Click")); 
      doc.insertString(doc.getLength(), "\n", attr); 
     } 

     setLocationRelativeTo(null); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setVisible(true); 
    } 
    public static void main(String[] args) 
    { 
     SwingUtilities.invokeLater(new Runnable() 
     { 
      @Override 
      public void run() 
      { 
       TextPaneDemo tpd = new TextPaneDemo(); 
       try 
       { 
        tpd.createAndShowGUI(); 
       } 
       catch (Exception ex){} 
      } 
     }); 
    } 
} 
+0

非常感謝您的回覆。它像一個魅力。非常感謝 – 2013-04-04 20:03:36

2

誰能告訴我怎麼可以在 同一行添加一個JButton到每個字符串?

  • doc.insertString(doc.getLength(), data.get(i)+ "\n", set);

僞代碼除去LineSeparator ("\n")可能是

for (int i = 0; i < data.size(); i++) { 
    try { 
     doc.insertString(doc.getLength(), data.get(i), set); 
     textPane.insertComponent(new JButton("View Info")); 
     doc.insertString(doc.getLength(), "\n", set); 
    } catch (BadLocationException ex) { 
    }  
} 
  • 與輸出

nnn

+1

感謝您的回覆。輸出有點混亂,但我解決了。非常感激 – 2013-04-04 20:04:21