JScrollPane有多个JTextAreas

我需要一种简单的方法来实现JScrollPane,我可以在其中添加JTextAreas。 这应该像评论系统一样工作,就像你在youtube上看到的那样,在这里就是Stackoverflow。

它应该是在java代码中,如果我和其他简单的方法我想知道它。

List comments = businessLogicRepair.getComments(oid, "Internal"); for (Comment comment : comments) { jInternalCommentScrollPane.add(new JTextArea(comment.getText())); } 

我的评论对象包含:

 public Comment(String id, String type, String text, String author, String postDate, String repairId) { super(id); this.type = type; this.text = text; this.author = author; this.postDate = postDate; this.repairId = repairId; } 

我将评论保存在数据库中,我可以轻松搞定。 问题是显示部分。

谢谢您的帮助

你必须接受可以只将一个JComponent放到JScrollPane ,在你的情况下只有一个JTextArea

这是一个向滚动的GridLayout添加新文本区域的简单示例。

在此处输入图像描述

 import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.GridLayout; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; /** @see http://stackoverflow.com/questions/7818387 */ public class ScrollGrid extends JPanel { private static final int N = 16; private JTextArea last; private int index; public ScrollGrid() { this.setLayout(new GridLayout(0, 1, 3, 3)); for (int i = 0; i < N; i++) { this.add(create()); } } private JTextArea create() { last = new JTextArea("Stackoverflow…" + ++index); return last; } private void display() { JFrame f = new JFrame("ScrollGrid"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add(new JScrollPane(this)); f.add(new JButton(new AbstractAction("Add") { @Override public void actionPerformed(ActionEvent e) { add(create()); revalidate(); scrollRectToVisible(last.getBounds()); } }), BorderLayout.SOUTH); f.pack(); f.setSize(200, 160); f.setLocationRelativeTo(null); f.setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { new ScrollGrid().display(); } }); } } 

也许JTable比JTextArea更容易使用。

请参阅: 如何使用表 。