2

カスタム描画を行い、次のメソッドをオーバーライドする JComponent があります。

public Dimension getPreferredSize() {
    return new Dimension(imageWidth, imageHeight);
}

public Dimension getMinimumSize() {
    return new Dimension(imageWidth, imageHeight);
}

imageWidth と imageHeight は、画像の実際のサイズです。

SpringLayout を使用してコンテンツ ペインに追加しました。

layout.putConstraint(SpringLayout.SOUTH, customComponent, -10, SpringLayout.SOUTH, contentPane);
layout.putConstraint(SpringLayout.EAST, customComponent, -10, SpringLayout.EAST, contentPane);
layout.putConstraint(SpringLayout.NORTH, customComponent, 10, SpringLayout.NORTH, contentPane);

そのため、サイズ変更時に高さが変更されるように南北に制限され、東はコンテンツ ペインの端に制限されますが、西は自由に左に移動できます。

サイズ変更時に正方形のサイズ(幅==高さ)を維持したいと思います。誰でもこれを行う方法を知っていますか?

4

1 に答える 1

3

最小/推奨/最大サイズは、レイアウト マネージャーへのヒントにすぎません。特定のサイズを強制するには、コンポーネントでサイズ処理をオーバーライドする必要があります。

すべてのサイズ変更/配置メソッド (setHeight、setLocation、setBounds など) は、最終的に を呼び出しますreshape。コンポーネントでこのメソッドをオーバーライドすることにより、コンポーネントを強制的に正方形にすることができます。

void reshape(int x, int y, int width, int height) {
   int currentWidth = getWidth();
   int currentHeight = getHeight();
   if (currentWidth!=width || currentHeight!=height) {
      // find out which one has changed
      if (currentWidth!=width && currentHeight!=height) {  
         // both changed, set size to max
         width = height = Math.max(width, height);
      }
      else if (currentWidth==width) {
          // height changed, make width the same
          width = height;
      }
      else // currentHeight==height
          height = width;
   }
   super.reshape(x, y, width, height);
}
于 2010-08-15T23:31:29.873 に答える