Swing/FileHistory のバックアップの現在との差分(No.16)
- category: swing folder: FileHistory title: JMenuに最近使ったファイルを追加 tags: [JMenu, File] tags: [JMenu, JMenuBar, File] author: aterai pubdate: 2003-11-10 description: JMenuに、「最近使ったファイル(F)」を履歴として追加していきます。 description: JMenuに「最近使ったファイル(F)」を履歴として追加していきます。 image:
概要
JMenu
に、「最近使ったファイル(F
)」を履歴として追加していきます。
概要
JMenu
に「最近使ったファイル(F
)」を履歴として追加していきます。
Screenshot
Advertisement
サンプルコード
サンプルコード
private int MAXHISTORY = 3;
private void updateHistory(String str) {
fileHistory.removeAll();
fh.removeElement(str);
fh.insertElementAt(str, 0);
if(fh.size()>MAXHISTORY) fh.remove(fh.size()-1);
for(int i=0;i<fh.size();i++) {
String name = (String)fh.elementAt(i);
String num = Integer.toString(i+1);
JMenuItem mi = new JMenuItem(new HistoryAction(new File(name)));
mi.setText(num + ": "+ name);
byte[] bt = num.getBytes();
mi.setMnemonic((int) bt[0]);
fileHistory.add(mi, i);
fileHistoryMenu.removeAll();
fileHistoryCache.remove(str);
fileHistoryCache.add(0, str);
if (fileHistoryCache.size() > MAX_HISTORY) {
fileHistoryCache.remove(fileHistoryCache.size() - 1);
}
for (int i = 0; i < fileHistoryCache.size(); i++) {
String name = fileHistoryCache.get(i);
String num = Integer.toString(i + 1);
JMenuItem mi = new JMenuItem(new HistoryAction(name));
mi.setText(num + ": " + name);
mi.setMnemonic((int) num.charAt(0));
fileHistoryMenu.add(mi, i);
}
}
#spandel
class HistoryAction extends AbstractAction{
#spanend
final private File file;
public HistoryAction(File file) {
#spanadd
#spanend
#spanadd
class HistoryAction extends AbstractAction {
#spanend
private final String fileName;
public HistoryAction(String fileName) {
super();
this.file = file;
this.fileName = fileName;
}
#spanadd
#spanend
@Override public void actionPerformed(ActionEvent e) {
historyActionPerformed(file);
Object[] obj = {"本来はファイルを開いたりする。\n",
"このサンプルではなにもせずに\n",
"履歴の先頭にファイルを移動する。"};
JComponent c = (JComponent) e.getSource();
JOptionPane.showMessageDialog(c.getRootPane(), obj, VersionAction.APP_NAME,
JOptionPane.INFORMATION_MESSAGE);
updateHistory(fileName);
}
}
#spandel
private void historyActionPerformed(File file) {
#spanend
Object[] obj = {"本来はファイルを開いたりする。\n",
"このサンプルではなにもせずに\n",
"履歴の先頭にファイルを移動する。"};
JOptionPane.showMessageDialog(this, obj, APP_NAME,
JOptionPane.INFORMATION_MESSAGE);
repaint();
updateHistory(file.getAbsolutePath());
#spandel
}
#spanend
View in GitHub: Java, Kotlin解説
上記のサンプルでは、「ファイル->開く」で、ダミーファイルの履歴が残ります。履歴は3
件まで残り、履歴をメニューから選択すると、そのファイルが履歴の先頭に移動します。
解説
上記のサンプルでは「ファイル、開く」のJMenuItem
をクリックするとファイルのオープン履歴を「最近使ったファイル(F
)」のJMenu
中に追加しています。
実際に使用する場合は、ダミーファイルを使用している箇所を修正したり、アプリケーションを終了する際に履歴を保存したりするコードを追加する必要があります。
- 履歴を表示する
JMenuItem
は3
件までに制限 - 履歴用の
JMenuItem
をメニューから選択するとそのファイルを履歴の先頭に移動(ファイルを開く処理などはない)- 実際に使用する場合はファイルを使用している箇所を修正したり、アプリケーションを終了する際に履歴を保存したりするコードを追加する必要がある