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

标签 java resize listener

enter image description here

我已在 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 时,一切都很好。所有获得的空间都正确计算,两个 JTable 获得新的 Y 定位 并以一半的获得空间扩展自身并填满屏幕。

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

但有时(通常是缓慢拖动或长时间拖动)JTable 不会垂直调整大小并转到原始 Y 位置,如下所示。但是“水平调整大小总是有效。”

enter image description here

在有问题的拖动调整大小后稍微拖动一下,就会再次恢复正常。

最佳答案

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

  4. 一定要使用布局管理器。 Swing 被设计为与布局管理器一起使用。在您的情况下,表格看起来大小相同,因此最简单的可能是使用 Grid Layout .

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

关于java - 调整 JFrame 大小后组件重新定位,并通过拖动鼠标手动调整右上角大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34618869/

相关文章:

javascript - 更新: How to find event listeners on a DOM node in prototype?

java - cursor.getCount() 返回 1 但应该返回 0

java - 如果键是字符串数组,为什么 HashMap 无法识别它的键?

java - 如何从 JformattedTextfield 检索货币格式值

java - 在 Java 中删除二维数组中的空元素

javax.naming.NamingException : Name is not bound to a Context

java - 更新数据库java

c++ - 如何在 QT 中设置中央小部件的大小/位置

winforms - Winform 列表框未正确锚定

android - 通过代码设置所选项目时如何禁用要调用的onItemSelectedListener