【问题标题】:How to make a dynamic JPanel stick to the top?如何让动态 JPanel 贴在顶部?
【发布时间】:2020-09-10 16:27:02
【问题描述】:

我正在使用 GridBagLayout 并且 JPanel 2 似乎始终位于 JPanel 1 的中心。JPanel 2 在整个程序中的高度都得到动态调整,所以我不能使用 gbc.insets.top = -15; 将它固定在顶部(gbc = GridBagConstraints)例如。我试过 gbc.anchor = GridBagConstraints.PAGE_START;gbc.gridheight = 3; 但他们似乎没有做我想要的。

假设 JPanel 1 和 JFrame 保持相同大小(JFrame 不可调整大小),我怎样才能让 JPanel 2 一直在顶部,而没有那个差距?

【问题讨论】:

  • gridbaglayout 本身并不支持重叠组件。我建议您尝试使用 JLayeredPane 的模态层,或者在 GridBagLayout 内的 JPanel 上使用 CardLayout
  • 我正在使用 GridBagLayout - 在哪里?在框架上?我没有看到您设置布局管理器或将组件添加到框架的任何代码。为每个问题发布正确的minimal reproducible example,这样我们就不必准确猜测您在做什么。

标签: java swing jframe jpanel gridbaglayout


【解决方案1】:

JPanel 2 似乎总是在 JPanel 的中心

然后看起来您正在将 panel1 添加到 panel2,因为 GridBagLayout 的默认行为是将组件相对于其父组件居中。

根据显示的图片,只需在框架上使用BorderLayout(这是默认设置)。那么你会:

  1. 将 panel2 添加到 BorderLayout.LINE_START
  2. 将 panel1 添加到 BorderLayout.CENTER

阅读 How to Use BorderLayout 上的 Swing 教程部分了解更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-15
    • 2010-11-16
    • 1970-01-01
    • 2017-06-19
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    相关资源
    最近更新 更多