JLabel上に表示した画像のクリックした位置の色を取得する
Total: 2946, Today: 1, Yesterday: 1
Posted by aterai at
Last-modified:
Summary
JLabelにIconとして画像を表示し、その画像をマウスでクリックした位置の色を取得します。
Screenshot

Advertisement
Source Code Examples
JLabel label = new JLabel(new ImageIcon(image));
label.addMouseListener(new MouseAdapter() {
@Override public void mousePressed(MouseEvent e) {
updateViewRect(label);
Point pt = e.getPoint();
if (iconRect.contains(pt)) {
int argb = image.getRGB(pt.x - iconRect.x, pt.y - iconRect.y);
field.setText(String.format("#%06X", argb & 0x00_FF_FF_FF));
sample.setIcon(new ColorIcon(new Color(argb, true)));
}
}
});
View in GitHub: Java, KotlinDescription
ImageIO.read(...)で画像ファイルをBufferedImageとして読み込むJLabelにnew ImageIcon(BufferedImage)で作成したIconを設定JLabelにMouseListenerを追加してマウスクリック位置を取得JLabel内のIcon表示領域をSwingUtilities.layoutCompoundLabel(...)で更新JLabel上のマウスクリック位置をIcon(BufferedImage)の座標に変換し、BufferedImage#getRGB(...)メソッドで整数型ピクセル値で色を取得- 取得した色から
Iconを生成してサンプル表示用のJLabelに設定 - 取得した色を
16進数カラーコードの6桁文字列に変換してJTextFieldに設定
- 取得した色から