调整 JFrame 大小后组件重新定位,右角通过拖动鼠标手动调整大小

Component relocate after resize JFrame and right corner manually resizing via drag mouse

我已经在 NetBeans Swing Builder 中构建了这个 JFrame 并添加到下面 ComponentListener

this.addComponentListener(new ComponentAdapter() 
{  
   public void componentResized(ComponentEvent evt) {

       //Get mainJPanel last Bounds after resizing
       Rectangle panelCurrentRec = new Rectangle();
       panelCurrentRec = mainJPanel.getBounds();

       //Calculate gained/losed how much vertical pixels
       int heightVariation = panelCurrentRec.height - panelOriginalHeight;

       //First set new vertical and horizontal bounds for below jtable and revalidate
       Rectangle rec = new Rectangle();
       rec = jScrollPane2.getBounds();
       jScrollPane2.setBounds(rec.x, rec.y+(heightVariation/2), mainJPanel.getWidth(), rec.height+(heightVariation/2));
       jScrollPane2.revalidate();

       //Second set new vertical and horizontal bounds for above jtable and revalidate
       rec = jScrollPane1.getBounds();
       jScrollPane1.setBounds(rec.x, rec.y, mainJPanel.getWidth(), rec.height+(heightVariation/2));
       jScrollPane1.revalidate();

    }

});

当我按下 JFrame 的 Maximize 时一切正常。所有获得的 space 计算正确并且两个 JTables 获得新的 Y positioning 并通过获得 space 的一半扩展自身并填满屏幕。

但是当我转到 JFrame 的右上角,按住并尝试手动调整大小时,ComponentListener 开火太多了。如果我快速拖动并完成调整大小,一切都很好。

但有时(通常是缓慢拖动或长时间拖动)JTables 未调整大小 vertically 并变为原始 Y position 如下所示。但是`水平调整大小总是有效。

在有问题的拖动调整大小后稍微拖动一下又恢复正常。

  1. 不要使用空布局。
  2. 不要使用 setBounds(...)。
  3. 不要使用 ComponentListener。

  4. 一定要使用布局管理器。 Swing 旨在与布局管理器一起使用。在您的情况下,看起来表的大小相等,因此最简单的方法可能是使用 Grid Layout.

您可能需要使用具有不同布局的多个嵌套面板来获得您想要的效果。