【问题标题】:Auto generating new JPanels onto a JFrame在 JFrame 上自动生成新的 JPanel
【发布时间】:2019-01-30 13:49:10
【问题描述】:

我目前正在开发一个博客/论坛门户,作为大学的学校项目。

我正在使用 Swing 作为 GUI。

我的问题是,是否可以在 JFrame 上自动生成已经预制的 JPanel 类,使其看起来像 stackoverflow 主页上的问题。

所以基本上,当创建一个帖子时,它会进入数据库 -> 我使用 getter 方法来填充面板上的信息,然后它会自动生成到框架上,这样我就不需要创建几个固定面板到框架上。

因此,如果没有帖子,页面将是空白的。创建新帖子时,它会显示为第一个帖子,下一个帖子会覆盖该帖子,依此类推。

可以这样做吗?

【问题讨论】:

  • 使用JList 而不是多个面板。 “是否可以在 Netbeans 中执行此操作?” 如果可以在 Netbeans 中执行此操作,则可以在任何其他 IDE 中执行此操作。代码编辑器无关紧要。

标签: java swing jpanel


【解决方案1】:

可以这样做吗?

当然有可能。

首先,您需要扩展JPanel 以包含您需要的组件。这个JPanel 子类将包含以您想要的方式表示数据所需的所有标签、按钮等。示例:

public class CommentPanel extends JPanel {
    private final JLabel usernameLabel = new JLabel();
    private final JLabel timestampLabel = new JLabel();
    // etc...
}

接下来,这个新类应该可以使用您的模型对象设置组件状态。 此步骤是可选的,但这样做会带来很多便利。示例:

public void setComment(Comment comment) {
    // appearance
    usernameLabel.setText(comment.getUser().getName());
    timestampLabel.setText(comment.getDate());
    commentText.setText(comment.getContent());

    // button behavior
    editButton.setActionListener(e -> editComment(comment));
    deleteButton.setActionListener(e -> deleteComment(comment));
}

接下来是您需要在父容器中添加一个容器,例如您的 JFrame 来保存可能生成的自定义面板。带有受控LayoutManager 的面板非常适合。

public class MainFrame extends JFrame {
    private final JPanel commentHolder = new JPanel();
    // etc...
    // add `commentHolder` to this frame
}

最后,您需要实例化自定义面板并设置数据。如果您创建了一个包装设置数据逻辑的方法(可选步骤),这将是一个单行。

List<Comment> comments = fetchAllFromDb();
for (Comment comment : comments) {
    // instantiate the custom panel
    CommentPanel commentPanel = new CommentPanel();

    // set the panel states and behavior
    commentPanel.setComment(comment);

    // add the created panel to the parent using the holder
    commentHolder.add(commentPanel);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    • 1970-01-01
    • 1970-01-01
    • 2014-10-02
    • 2013-09-22
    相关资源
    最近更新 更多