• category: swing folder: UndoRedoCheckBoxes title: JCheckBoxの選択状態をBigIntegerで記憶し、UndoManagerを使用して元に戻したりやり直したりする tags: [JCheckBox, UndoManager, UndoableEditSupport] author: aterai pubdate: 2016-04-18T00:42:25+09:00 description: 複数のJCheckBoxの選択状態をBigIntegerで記憶し、UndoManagerを使用してアンドゥ・リドゥを行います。 image: https://lh3.googleusercontent.com/-lcOSQhE6Wp4/VxOpe3dlKII/AAAAAAAAOTE/_lpl9dzIlw8hXFZ-GfuX8HT2fGsENQNvgCCo/s800-Ic42/UndoRedoCheckBoxes.png

概要

複数のJCheckBoxの選択状態をBigIntegerで記憶し、UndoManagerを使用してアンドゥ・リドゥを行います。

サンプルコード

private BigInteger status = new BigInteger("111000111", 2);
private static final int BIT_LENGTH = 50;
//...
for (int i = 0; i < BIT_LENGTH; i++) {
  BigInteger l = BigInteger.ONE.shiftLeft(i);
  JCheckBox c = new JCheckBox(Integer.toString(i + 1));
  c.addActionListener(e -> {
    JCheckBox cb = (JCheckBox) e.getSource();
    BigInteger newValue = cb.isSelected() ? status.or(l) : status.xor(l);
    undoSupport.postEdit(new StatusEdit(status, newValue));
    status = newValue;
    label.setText(print(status));
  });
  c.setSelected(!status.and(l).equals(BigInteger.ZERO));
  p.add(c);
}
View in GitHub: Java, Kotlin

解説

  • JCheckBoxの選択状態をBigIntegerのビットフラグで管理、記憶
  • UndoableEditSupport#addUndoableEditListener(...)でリスナにUndoManagerを追加
  • JCheckBoxがクリックされるなどで値が変化した場合、変更前と変更後のBigIntegerを持つUndoableEditを作成して、UndoableEditSupport#postEdit(...)で登録
  • UndoManager#undo()でアンドゥ、UndoManager#redo()でリドゥを実行し、BigIntegerのステータスを更新
    • 更新されたBigIntegerから各JCheckBoxの選択状態を復元

参考リンク

コメント