TITLE:JInternalFrameをJFrameとして表示する

Posted by terai at 2009-08-31

JInternalFrameをJFrameとして表示する

JFrameのタイトルバーなどを非表示にし、JInternalFrameのタイトルバーでこれらを代用します。

  • &jnlp;
  • &jar;
  • &zip;

#screenshot

サンプルコード

final JInternalFrame internal = new JInternalFrame("@title@");
BasicInternalFrameUI ui = (BasicInternalFrameUI)internal.getUI();
Component title = ui.getNorthPane();
for(MouseMotionListener l:title.getListeners(MouseMotionListener.class)) {
  title.removeMouseMotionListener(l);
}
DragWindowListener dwl = new DragWindowListener();
title.addMouseListener(dwl);
title.addMouseMotionListener(dwl);
JPanel p = new JPanel(new BorderLayout());
p.add(new JScrollPane(new JTree()));
p.add(new JButton(new AbstractAction("close") {
  public void actionPerformed(ActionEvent e) {
    Window w = SwingUtilities.windowForComponent((Component)e.getSource());
    //w.dispose();
    w.getToolkit().getSystemEventQueue().postEvent(
      new WindowEvent(w, WindowEvent.WINDOW_CLOSING));
  }
}), BorderLayout.SOUTH);
internal.getContentPane().add(p);
internal.setVisible(true);

KeyboardFocusManager focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
focusManager.addPropertyChangeListener(new PropertyChangeListener() {
  public void propertyChange(PropertyChangeEvent e) {
    String prop = e.getPropertyName();
    if("activeWindow".equals(prop)) {
      try{
        internal.setSelected(e.getNewValue()!=null);
      }catch(PropertyVetoException ex) {
        ex.printStackTrace();
      }
    }
  }
});

解説

上記のサンプルでは、JInternalFrameのタイトルバーを使用することで、タイトルバーに閉じるボタンのないフレームを作成しています。

  • JFrame#setUndecorated(true) で、JFrameのタイトルバーなどを非表示
  • BasicInternalFrameUI#getNorthPane()でJInternalFrameのタイトルバーを取得
    • 元のMouseMotionListenerを削除
    • JInternalFrameをドラッグすると親のJFrameが移動するMouseMotionListenerを追加
  • 制限
    • 最大化、最小化、リサイズなどには未対応
      • Alt+Spaceで最大化、最小化できるが、元のサイズに戻せなくなる場合がある
    • 角の透明化には未対応
      • 目立たなくするために、LookAndFeelはNimbusに変更
      • JDK 1.7.0 なら、frame.setBackground(new Color(0,0,0,0));frame.add(p=new MainPanel());p.setOpaque(false); で角の透明化が可能

コメント

  • JFrameのアクティブ状態が変わったら、JInternalFrameの選択状態も変化するように変更。 -- terai