• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JComponentの形状を変更する
#navi(../)
#tags()
RIGHT:Posted by &author(aterai); at 2008-11-17
*JComponentの形状定義を変更する [#hda649fc]
コンポーネントの形状を画像の不透明領域に合わせて変更します。
---
category: swing
folder: MoveNonRectangularImage
title: JComponentの形状を変更する
tags: [JComponent, JLabel, BufferedImage, DragAndDrop]
author: aterai
pubdate: 2008-11-17T16:07:53+09:00
description: マウスカーソルに反応するコンポーネントの領域をJLabelに設定した画像アイコンの不透明領域に合わせて変更します。
image: https://lh5.googleusercontent.com/_9Z4BYR88imo/TQTQKdiDk4I/AAAAAAAAAfI/tb322r8ngL0/s800/MoveNonRectangularImage.png
---
* 概要 [#summary]
マウスカーソルに反応するコンポーネントの領域を`JLabel`に設定した画像アイコンの不透明領域に合わせて変更します。

-&jnlp;
-&jar;
-&zip;
#download(https://lh5.googleusercontent.com/_9Z4BYR88imo/TQTQKdiDk4I/AAAAAAAAAfI/tb322r8ngL0/s800/MoveNonRectangularImage.png)

//#screenshot
#ref(http://lh5.ggpht.com/_9Z4BYR88imo/TQTQKdiDk4I/AAAAAAAAAfI/tb322r8ngL0/s800/MoveNonRectangularImage.png)

**サンプルコード [#h071e116]
* サンプルコード [#sourcecode]
#code(link){{
JLabel label = new JLabel(dukeIcon) {
BufferedImage image = ImageIO.read(getClass().getResource("duke.gif"));
JLabel label = new JLabel(new ImageIcon(image)) {
  @Override public boolean contains(int x, int y) {
    return super.contains(x, y) && ((image.getRGB(x, y) >> 24) & 0xff) > 0;
    return super.contains(x, y) && ((image.getRGB(x, y) >> 24) & 0xFF) > 0;
  }
};
}}

**解説 [#lea73de2]
上記のサンプルでは、非矩形画像の不透明部分だけマウスでドラッグできるように、マウス処理にUIが使用する contains メソッドをオーバーライドし、透明部分がJLabelの形状に含まれないようにしています。
* 解説 [#explanation]
- `JLabel#contains(int, int)`メソッドをオーバーライドして与えられた座標にある画像の色成分が透明の場合は`false`を返すよう設定
- 画像の透明部分は`JLabel`に含まれないことになり`JLabel`に設定した`MouseListener`などに反応しない
- 非矩形画像の不透明部分だけがマウスでドラッグ可能になる

**参考リンク [#va0cebde]
-[http://duke.kenai.com/iconSized/index.html Duke Images: iconSized]
-[[JButtonの形を変更>Swing/RoundButton]]
-[[ImageIconの形でJButtonを作成>Swing/RoundImageButton]]
* 参考リンク [#reference]
- [http://duke.kenai.com/iconSized/index.html Duke Images: iconSized]
- [[JButtonの形を変更>Swing/RoundButton]]
- [[ImageIconの形でJButtonを作成>Swing/RoundImageButton]]

**コメント [#a017a413]
* コメント [#comment]
#comment
#comment