ContextAction.java revision 1472:c18cbe5936b8
1/* 2 * Copyright (c) 1998, 2007, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25package com.sun.hotspot.igv.util; 26 27import java.awt.EventQueue; 28import org.openide.util.ContextAwareAction; 29import org.openide.util.Lookup; 30import org.openide.util.LookupEvent; 31import org.openide.util.LookupListener; 32import org.openide.util.Utilities; 33import org.openide.util.actions.CallableSystemAction; 34 35/** 36 * 37 * @author Thomas Wuerthinger 38 */ 39public abstract class ContextAction<T> extends CallableSystemAction implements LookupListener, ContextAwareAction { 40 41 private Lookup context = null; 42 private Lookup.Result<T> result = null; 43 44 public ContextAction() { 45 this(Utilities.actionsGlobalContext()); 46 } 47 48 public ContextAction(Lookup context) { 49 init(context); 50 } 51 52 private void init(Lookup context) { 53 this.context = context; 54 result = context.lookupResult(contextClass()); 55 result.addLookupListener(this); 56 resultChanged(null); 57 } 58 59 public void resultChanged(LookupEvent e) { 60 if (result.allItems().size() != 0) { 61 update(result.allInstances().iterator().next()); 62 } else { 63 update(null); 64 } 65 } 66 67 @Override 68 public void performAction() { 69 final T t = result.allInstances().iterator().next(); 70 71 // Ensure it's AWT event thread 72 EventQueue.invokeLater(new Runnable() { 73 74 public void run() { 75 performAction(t); 76 } 77 }); 78 } 79 80 public void update(T t) { 81 if (t == null) { 82 setEnabled(false); 83 } else { 84 setEnabled(isEnabled(t)); 85 } 86 } 87 88 public boolean isEnabled(T context) { 89 return true; 90 } 91 92 public abstract Class<T> contextClass(); 93 94 public abstract void performAction(T context); 95} 96