Swing/Preferences のバックアップの現在との差分(No.7)
2021-08-20 (金) 13:59:29
概要
Preferences
(レジストリなど)にフレーム(パネル)の位置・サイズを記憶しておきます。
Screenshot
Advertisement
public abstract class AbstractHogePanel extends JPanel{ final private Point pos = new Point(0, 0); final private Dimension dim = new Dimension(900, 800); private JFrame frame; public AbstractHogePanel(){ super(); frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); frame.addWindowListener(new java.awt.event.WindowAdapter(){ public void windowClosing(WindowEvent e){ exitActionPerformed(null); } }); frame.addComponentListener(new ComponentAdapter(){ public void componentMoved(ComponentEvent e){ JFrame frm = (JFrame)e.getSource(); if(frm.getExtendedState()==JFrame.NORMAL){ try{ pos.setLocation(frm.getLocationOnScreen()); }catch(IllegalComponentStateException icse){} } } public void componentResized(ComponentEvent e){ JFrame frm = (JFrame)e.getSource(); if(frm.getExtendedState()==JFrame.NORMAL){ dim.setSize(getSize()); } } //void componentHidden(ComponentEvent e){} //void componentShown(ComponentEvent e) }); } private String prefix = ""; protected void setPrefix(String str){ str = str.toLowerCase().trim(); if(str!=null && str.length()>0){ prefix = str+"_"; } } protected void initLocation(Preferences lprefs){ int xpos = lprefs.getInt(prefix+"locx", pos.x); int ypos = lprefs.getInt(prefix+"locy", pos.y); pos.setLocation(xpos,ypos); getFrame().setLocation(pos.x, pos.y); int wdim = lprefs.getInt(prefix+"dimw", dim.width); int hdim = lprefs.getInt(prefix+"dimh", dim.height); dim.setSize(wdim, hdim); this.setPreferredSize(dim); } protected void saveLocation(Preferences lprefs){ lprefs.putInt(prefix+"locx", pos.x); lprefs.putInt(prefix+"locy", pos.y); lprefs.putInt(prefix+"dimw", dim.width); lprefs.putInt(prefix+"dimh", dim.height); try{ lprefs.flush(); }catch(java.util.prefs.BackingStoreException e){ } } public JFrame getFrame(){ return frame; } public void showPanel(){ if(getFrame()!=null){ JFrame f = getFrame(); f.setExtendedState(JFrame.NORMAL); f.getContentPane().add(this, BorderLayout.CENTER); f.pack(); f.show(); } } protected class ExitAction extends AbstractAction{ public ExitAction(){ super("exit"); } public void actionPerformed(ActionEvent evt){ exitActionPerformed(evt); } } abstract public void exitActionPerformed(ActionEvent e); }
サンプルコード
解説
上記のサンプルでは、対象フレームが最大化、最小化された状態で終了した場合、その前の位置サイズを記憶するよう設定しています。参考リンク
- Preferences (Java Platform SE 8)
- Preferences APIの概要
- メモ:
Java 6
のPreferences API の概要にある「Java
コレクションAPI
の設計に関するFAQ
」は「Preferences API
の設計に関するFAQ
」の間違い -
Java 8
の「Preferences API
の概要」で修正済み
- メモ:
- PersistenceServiceを使ってJFrameの位置・サイズを記憶