JScrollPane with multiple JTextAreas

2020-01-29 20:39发布

I am in need of an easy way to implement a JScrollPane where i can add JTextAreas. This should work like a comment system as you see it on youtube and here on Stackoverflow.

it should be in java code and if theres and other easy way I would like to know about it.

List<Comment> comments = businessLogicRepair.getComments(oid, "Internal");

        for (Comment comment : comments) {
            jInternalCommentScrollPane.add(new JTextArea(comment.getText()));

        }

My comment objects contain:

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

I save the comments in a database and i can get em up easily. The problem is the showing part.

Thanks for the help

3条回答
Juvenile、少年°
2楼-- · 2020-01-29 21:28

Maybe a JTable would be easier to use than a JTextArea.

See: How to Use Tables.

查看更多
你好瞎i
3楼-- · 2020-01-29 21:34

Here's a simple example that adds new text areas to a scrolling GridLayout.

enter image description here

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();
            }
        });
    }
}
查看更多
家丑人穷心不美
4楼-- · 2020-01-29 21:41

you have to accept that is possible to put only one JComponent to the JScrollPane, in your case only one JTextArea

查看更多
登录 后发表回答