TITLE:JFrameの透明化と再描画

Posted by aterai at 2011-10-24

JFrameの透明化と再描画

半透明にしたJFrameの再描画を行います。

  • &jnlp;
  • &jar;
  • &zip;
TranslucentFrameRepaint.png

サンプルコード

private final SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
private final JLabel label = new JLabel(df.format(new Date()));
private final Timer timer = new Timer(1000, new ActionListener() {
  @Override public void actionPerformed(ActionEvent e) {
    label.setText(df.format(new Date()));
    repaintWindowAncestor(label);
  }
});
private void repaintWindowAncestor(Component c) {
  Window w = SwingUtilities.getWindowAncestor(c);
  if(w instanceof JFrame) {
    JFrame f = (JFrame)w;
    JComponent cp = (JComponent)f.getContentPane();
    //cp.repaint();
    Rectangle r = c.getBounds();
    r = SwingUtilities.convertRectangle(c, r, cp);
    cp.repaint(r.x, r.y, r.width, r.height);
    //r = SwingUtilities.convertRectangle(c, r, f);
    //f.repaint(r.x, r.y, r.width, r.height);
  }else{
    c.repaint();
  }
}

解説

上記のサンプルでは、以下のように半透明にしたJFrameに、一秒ごとに文字列が変化するJLabel(時計)を配置しています。

com.sun.awt.AWTUtilities.setWindowOpaque(frame, false);
//frame.setBackground(new Color(0,0,0,0)); //1.7.0

JFrameが半透明なので、そのContentPaneから再描画しないと、JLabelとの間にあるContainerの背景色などが重複して上書きされる(色が濃くなる)ようです。

コメント