首页 > 解决方案 > 如何将 JTextArea 放在另一个 JTextArea 旁边?

问题描述

我正在尝试在 GUI 中将一个并排JTextArea放置JTextArea

我正在为数据库编写 GUI,并希望将每列中的数据放在不同的 JTextArea 中。这将使我的 GUI 看起来更好,并且更容易查看数据。我已经尝试将其添加JTextAreas到 a JPanel,但这似乎不起作用。

这是我迄今为止尝试过的:

public class GUIDisplayBooks extends JFrame{

    JPanel panel = new JPanel();
    JTextArea textAreaIsbn = new JTextArea();
    JTextArea textAreaTitle = new JTextArea();
    JTextArea textAreaSurname = new JTextArea();
    JTextArea textAreaForename = new JTextArea();
    JTextArea textAreaCategory = new JTextArea();
    JScrollPane scrollPane = new JScrollPane(panel);

    GUIDisplayBooks(ArrayList<Book> books)
    {
        this.add(panel);
        this.setSize(600,200);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    for(Book book : books){            
        textAreaIsbn.append(book.getIsbn() + "\n");
        textAreaTitle.append(book.getTitle() + "\n");
        textAreaSurname.append(book.getSurname() + "\n");
        textAreaForename.append(book.getForename() + "\n");
        textAreaCategory.append(book.getCategory() + "\n");
    }
        panel.add(textAreaIsbn);
        panel.add(textAreaTitle);
        panel.add(textAreaSurname);
        panel.add(textAreaForename);
        panel.add(textAreaCategory);
        add(scrollPane);

    }

}

我不断得到一个空白的 GUI 窗口。也许这真的很明显,任何帮助

标签: javaswinglayout-managerjtextarea

解决方案


Swing 组件只能有一个父组件:

JScrollPane scrollPane = new JScrollPane(panel);

这个我基本一样:

JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(panel);

然后你将同样的添加panel到你的JFrame

this.add(panel);

它将它从中删除JScrollPane,然后将空添加JScrollPaneJFrame

add(scrollPane);

所以,删除这一行,应该让你的程序工作:

this.add(panel);

推荐阅读