TITLE:Windowの形を変更
Posted by aterai at 2011-12-19

Windowの形を変更

Windowの形を非矩形図形に変更します。
  • category: swing folder: WindowShape title: Windowの形を変更 tags: [JFrame, Shape, TextLayout] author: aterai pubdate: 2011-12-19T19:46:54+09:00 description: JFrameのタイトルバーなどを非表示にし、Windowの形を非矩形図形に変更します。 image: https://lh4.googleusercontent.com/-f54GogC4jCU/Tu7AbPCJhsI/AAAAAAAABGc/EzG0Tf9ITFI/s800/WindowShape.png

概要

JFrameのタイトルバーなどを非表示にし、Windowの形を非矩形図形に変更します。
WindowShape.png

サンプルコード

#spanend
#spanadd
* サンプルコード [#sourcecode]
#spanend
#spanadd
#code(link){{
#spanend
JFrame frame = new JFrame();
frame.setUndecorated(true);
frame.setAlwaysOnTop(true);
frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
frame.getContentPane().add(label);
frame.getContentPane().setBackground(Color.GREEN);
frame.pack();

String str = textField.getText().trim();
#spandel
//label.setText(str);
#spanend
TextLayout tl = new TextLayout(str, font, frc);
Rectangle2D b = tl.getBounds();
#spandel
Shape shape = tl.getOutline(AffineTransform.getTranslateInstance(-b.getX(),-b.getY()));
#spanend
#spanadd
Shape shape = tl.getOutline(AffineTransform.getTranslateInstance(-b.getX(), -b.getY()));
#spanend

frame.setBounds(shape.getBounds());
#spandel
//frame.setSize(shape.getBounds().width, shape.getBounds().height);
#spanend
#spandel
com.sun.awt.AWTUtilities.setWindowShape(frame, shape);
#spanend
#spandel
//frame.setShape(shape); // 1.7.0
#spanend
#spanadd
// JDK 1.6.0: com.sun.awt.AWTUtilities.setWindowShape(frame, shape);
#spanend
#spanadd
frame.setShape(shape);
#spanend
frame.setLocationRelativeTo(parent);
frame.setVisible(true);

解説

上記のサンプルでは、com.sun.awt.AWTUtilities.setWindowShape(...)メソッドを使用して、JFrameの形を変更しています。
  • Java 1.7.0 の場合は、Window#setShape(Shape)を使用

解説

上記のサンプルでは、JDK 1.7.0で導入されたWindow#setShape(Shape)メソッドを使用してJFrameの形を変更しています。

コメント

  • JDK 1.6.0_10の場合はcom.sun.awt.AWTUtilities.setWindowShape(...)を使用する

参考リンク

コメント