index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/instance/ReservoirSample.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ReservoirSample.java * Copyright (C) 2007-2012 University of Waikato, Hamilton, New Zealand * */ package weka.filters.unsupervised.instance; import weka.core.*; import weka.core.Capabilities.Capability; import weka.filters.Filter; import weka.filters.StreamableFilter; import weka.filters.UnsupervisedFilter; import weka.gui.ProgrammaticProperty; import java.io.IOException; import java.io.StringReader; import java.util.Enumeration; import java.util.Random; import java.util.Vector; /** * <!-- globalinfo-start --> Produces a random subsample of a dataset using the * reservoir sampling Algorithm "R" by Vitter. The original data set does not * have to fit into main memory, but the reservoir does. * <p/> * <!-- globalinfo-end --> * * <!-- technical-bibtex-start --> BibTeX: * * <pre> * &#64;article{Vitter1985, * author = {J. S. Vitter}, * journal = {ACM Transactions on Mathematical Software}, * number = {1} * volume = {11} * pages = {37-57}, * title = {Random Sampling with a Reservoir}, * year = {1985} * } * </pre> * * </p> * <!-- options-start --> Valid options are: * <p/> * * <pre> * -S &lt;num&gt; * Specify the random number seed (default 1) * </pre> * * <pre> * -Z &lt;num&gt; * The size of the output dataset - number of instances * (default 100) * </pre> * * <!-- options-end --> * * @author Mark Hall (mhall{[at]}pentaho{[dot]}org) * @version $Revision$ */ public class ReservoirSample extends Filter implements UnsupervisedFilter, OptionHandler, StreamableFilter, Randomizable, WeightedAttributesHandler { /** for serialization */ static final long serialVersionUID = 3119607037607101160L; /** The subsample size, number of instances% */ protected int m_SampleSize = 100; /** Holds the sub-sample (reservoir) */ protected Object[] m_subSample; /** The current instance being processed */ protected int m_currentInst; /** The random number generator seed */ protected int m_RandomSeed = 1; /** The random number generator */ protected Random m_random; /** True if the incoming data contains string attributes */ protected boolean m_containsStringAtts; /** * Returns a string describing this filter * * @return a description of the classifier suitable for displaying in the * explorer/experimenter gui */ public String globalInfo() { return "Produces a random subsample of a dataset using the reservoir sampling " + "Algorithm \"R\" by Vitter. The original data set does not have to fit " + "into main memory, but the reservoir does. "; } /** * Returns an enumeration describing the available options. * * @return an enumeration of all the available options. */ @Override public Enumeration<Option> listOptions() { Vector<Option> result = new Vector<Option>(); result.addElement(new Option( "\tSpecify the random number seed (default 1)", "S", 1, "-S <num>")); result.addElement(new Option( "\tThe size of the output dataset - number of instances\n" + "\t(default 100)", "Z", 1, "-Z <num>")); return result.elements(); } /** * Parses a given list of options. * <p/> * * <!-- options-start --> Valid options are: * <p/> * * <pre> * -S &lt;num&gt; * Specify the random number seed (default 1) * </pre> * * <pre> * -Z &lt;num&gt; * The size of the output dataset - number of instances * (default 100) * </pre> * * <!-- options-end --> * * @param options the list of options as an array of strings * @throws Exception if an option is not supported */ @Override public void setOptions(String[] options) throws Exception { String tmpStr = Utils.getOption('S', options); if (tmpStr.length() != 0) { setRandomSeed(Integer.parseInt(tmpStr)); } else { setRandomSeed(1); } tmpStr = Utils.getOption('Z', options); if (tmpStr.length() != 0) { setSampleSize(Integer.parseInt(tmpStr)); } else { setSampleSize(100); } Utils.checkForRemainingOptions(options); } /** * Gets the current settings of the filter. * * @return an array of strings suitable for passing to setOptions */ @Override public String[] getOptions() { Vector<String> result = new Vector<String>(); result.add("-S"); result.add("" + getRandomSeed()); result.add("-Z"); result.add("" + getSampleSize()); return result.toArray(new String[result.size()]); } /** * Returns the tip text for this property * * @return tip text for this property suitable for displaying in the * explorer/experimenter gui */ public String randomSeedTipText() { return "The seed used for random sampling."; } /** * Gets the random number seed. * * @return the random number seed. */ public int getRandomSeed() { return m_RandomSeed; } /** * Sets the random number seed. * * @param newSeed the new random number seed. */ public void setRandomSeed(int newSeed) { m_RandomSeed = newSeed; } @ProgrammaticProperty public void setSeed(int seed) { setRandomSeed(seed); } @ProgrammaticProperty public int getSeed() { return getRandomSeed(); } /** * Returns the tip text for this property * * @return tip text for this property suitable for displaying in the * explorer/experimenter gui */ public String sampleSizeTipText() { return "Size of the subsample (reservoir). i.e. the number of instances."; } /** * Gets the subsample size. * * @return the subsample size */ public int getSampleSize() { return m_SampleSize; } /** * Sets the size of the subsample. * * @param newSampleSize size of the subsample. */ public void setSampleSize(int newSampleSize) { m_SampleSize = newSampleSize; } /** * Returns the Capabilities of this filter. * * @return the capabilities of this object * @see Capabilities */ @Override public Capabilities getCapabilities() { Capabilities result = super.getCapabilities(); result.disableAll(); // attributes result.enableAllAttributes(); result.enable(Capability.MISSING_VALUES); // class result.enableAllClasses(); result.enable(Capability.MISSING_CLASS_VALUES); result.enable(Capability.NO_CLASS); return result; } /** * Sets the format of the input instances. * * @param instanceInfo an Instances object containing the input instance * structure (any instances contained in the object are ignored - * only the structure is required). * @return true if the outputFormat may be collected immediately * @throws Exception if the input format can't be set successfully */ @Override public boolean setInputFormat(Instances instanceInfo) throws Exception { super.setInputFormat(instanceInfo); m_containsStringAtts = instanceInfo.checkForStringAttributes(); setOutputFormat(instanceInfo); m_subSample = new Object[m_SampleSize]; m_currentInst = 0; m_random = new Random(m_RandomSeed); return true; } /** * Decides whether the current instance gets retained in the reservoir. * * @param instance the Instance to potentially retain */ protected void processInstance(Instance instance) { if (m_currentInst < m_SampleSize) { m_subSample[m_currentInst] = m_containsStringAtts ? instance.toString() : instance.copy(); } else { double r = m_random.nextDouble(); if (r < ((double) m_SampleSize / (double) m_currentInst)) { r = m_random.nextDouble(); int replace = (int) (m_SampleSize * r); m_subSample[replace] = m_containsStringAtts ? instance.toString() : instance.copy(); } } m_currentInst++; } /** * Input an instance for filtering. Filter requires all training instances be * read before producing output. * * @param instance the input instance * @return true if the filtered instance may now be collected with output(). * @throws IllegalStateException if no input structure has been defined */ @Override public boolean input(Instance instance) { if (getInputFormat() == null) { throw new IllegalStateException("No input instance format defined"); } if (m_NewBatch) { resetQueue(); m_NewBatch = false; } if (isFirstBatchDone()) { push(instance); return true; } else { // bufferInput(instance); if (!m_containsStringAtts) { copyValues(instance, false); } processInstance(instance); return false; } } /** * Signify that this batch of input to the filter is finished. If the filter * requires all instances prior to filtering, output() may now be called to * retrieve the filtered instances. * * @return true if there are instances pending output * @throws IllegalStateException if no input structure has been defined */ @Override public boolean batchFinished() { if (getInputFormat() == null) { throw new IllegalStateException("No input instance format defined"); } if (!isFirstBatchDone()) { // Do the subsample, and clear the input instances. createSubsample(); } flushInput(); m_NewBatch = true; m_FirstBatchDone = true; return (numPendingOutput() != 0); } /** * Creates a subsample of the current set of input instances. The output * instances are pushed onto the output queue for collection. */ protected void createSubsample() { StringBuilder sb = null; if (m_containsStringAtts) { sb = new StringBuilder(); sb.append(getInputFormat().stringFreeStructure()).append("\n"); } for (int i = 0; i < m_SampleSize; i++) { if (m_subSample[i] != null) { if (!m_containsStringAtts) { Instance copy = (Instance) ((Instance) m_subSample[i]).copy(); push(copy, false); // No need to copy instance } else { sb.append(m_subSample[i].toString()).append("\n"); } } else { // less data in the original than was asked for // as a sample. break; } } m_subSample = null; if (m_containsStringAtts) { try { Instances stringSample = new Instances(new StringReader(sb.toString())); for (int i = 0; i < stringSample.numInstances(); i++) { push(stringSample.instance(i), false); } } catch (IOException ex) { throw new RuntimeException(ex); } } } /** * Returns the revision string. * * @return the revision */ @Override public String getRevision() { return RevisionUtils.extract("$Revision$"); } /** * Main method for testing this class. * * @param argv should contain arguments to the filter: use -h for help */ public static void main(String[] argv) { runFilter(new ReservoirSample(), argv); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/instance/SparseToNonSparse.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SparseToNonSparse.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.filters.unsupervised.instance; import weka.core.*; import weka.core.Capabilities.Capability; import weka.filters.Filter; import weka.filters.StreamableFilter; import weka.filters.UnsupervisedFilter; /** <!-- globalinfo-start --> * An instance filter that converts all incoming sparse instances into non-sparse format. * <p/> <!-- globalinfo-end --> * * @author Len Trigg (len@reeltwo.com) * @version $Revision$ */ public class SparseToNonSparse extends Filter implements UnsupervisedFilter, StreamableFilter, WeightedAttributesHandler, WeightedInstancesHandler { /** for serialization */ static final long serialVersionUID = 2481634184210236074L; /** * Returns a string describing this filter * * @return a description of the filter suitable for * displaying in the explorer/experimenter gui */ public String globalInfo() { return "An instance filter that converts all incoming sparse instances" + " into non-sparse format."; } /** * Returns the Capabilities of this filter. * * @return the capabilities of this object * @see Capabilities */ public Capabilities getCapabilities() { Capabilities result = super.getCapabilities(); result.disableAll(); // attributes result.enableAllAttributes(); result.enable(Capability.MISSING_VALUES); // class result.enableAllClasses(); result.enable(Capability.MISSING_CLASS_VALUES); result.enable(Capability.NO_CLASS); return result; } /** * Sets the format of the input instances. * * @param instanceInfo an Instances object containing the input instance * structure (any instances contained in the object are ignored - only the * structure is required). * @return true if the outputFormat may be collected immediately * @throws Exception if format cannot be processed */ public boolean setInputFormat(Instances instanceInfo) throws Exception { super.setInputFormat(instanceInfo); setOutputFormat(instanceInfo); return true; } /** * Input an instance for filtering. Ordinarily the instance is processed * and made available for output immediately. Some filters require all * instances be read before producing output. * * @param instance the input instance * @return true if the filtered instance may now be * collected with output(). * @throws IllegalStateException if no input structure has been defined */ public boolean input(Instance instance) { if (getInputFormat() == null) { throw new IllegalStateException("No input instance format defined"); } if (m_NewBatch) { resetQueue(); m_NewBatch = false; } Instance inst = null; if (instance instanceof SparseInstance) { inst = new DenseInstance(instance.weight(), instance.toDoubleArray()); inst.setDataset(instance.dataset()); } else { inst = (Instance)instance.copy(); } push(inst, false); // No need to copy instance return true; } /** * Returns the revision string. * * @return the revision */ public String getRevision() { return RevisionUtils.extract("$Revision$"); } /** * Main method for testing this class. * * @param argv should contain arguments to the filter: use -h for help */ public static void main(String [] argv) { runFilter(new SparseToNonSparse(), argv); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/instance/SubsetByExpression.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SubsetByExpression.java * Copyright (C) 2008-2014 University of Waikato, Hamilton, New Zealand */ package weka.filters.unsupervised.instance; import java.util.Collections; import java.util.Enumeration; import java.util.Vector; import weka.core.*; import weka.core.Capabilities.Capability; import weka.core.expressionlanguage.common.IfElseMacro; import weka.core.expressionlanguage.common.JavaMacro; import weka.core.expressionlanguage.common.MacroDeclarationsCompositor; import weka.core.expressionlanguage.common.MathFunctions; import weka.core.expressionlanguage.common.Primitives.BooleanExpression; import weka.core.expressionlanguage.core.Node; import weka.core.expressionlanguage.parser.Parser; import weka.core.expressionlanguage.weka.InstancesHelper; import weka.filters.SimpleBatchFilter; /** * <!-- globalinfo-start --> * Filters instances according to a user-specified expression.<br/> * <br/> * Examples:<br/> * - extracting only mammals and birds from the 'zoo' UCI dataset:<br/> * (CLASS is 'mammal') or (CLASS is 'bird')<br/> * - extracting only animals with at least 2 legs from the 'zoo' UCI dataset:<br/> * (ATT14 &gt;= 2)<br/> * - extracting only instances with non-missing 'wage-increase-second-year'<br/> * from the 'labor' UCI dataset:<br/> * not ismissing(ATT3)<br/> * <p/> * <!-- globalinfo-end --> * * <!-- options-start --> * Valid options are: <p/> * * <pre> -E &lt;expr&gt; * The expression to use for filtering * (default: true).</pre> * * <pre> -F * Apply the filter to instances that arrive after the first * (training) batch. The default is to not apply the filter (i.e., * always return the instance)</pre> * * <pre> -output-debug-info * If set, filter is run in debug mode and * may output additional info to the console</pre> * * <pre> -do-not-check-capabilities * If set, filter capabilities are not checked when input format is set * (use with caution).</pre> * * <!-- options-end --> * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class SubsetByExpression extends SimpleBatchFilter implements WeightedInstancesHandler, WeightedAttributesHandler{ /** for serialization. */ private static final long serialVersionUID = 5628686110979589602L; /** the expresion to use for filtering. */ protected String m_Expression = "true"; /** Whether to filter instances after the first batch has been processed */ protected boolean m_filterAfterFirstBatch = false; /** * Returns a string describing this filter. * * @return a description of the filter suitable for displaying in the * explorer/experimenter gui */ @Override public String globalInfo() { return "Filters instances according to a user-specified expression.\n\n" + "\n" + "Examples:\n" + "- extracting only mammals and birds from the 'zoo' UCI dataset:\n" + " (CLASS is 'mammal') or (CLASS is 'bird')\n" + "- extracting only animals with at least 2 legs from the 'zoo' UCI dataset:\n" + " (ATT14 >= 2)\n" + "- extracting only instances with non-missing 'wage-increase-second-year'\n" + " from the 'labor' UCI dataset:\n" + " not ismissing(ATT3)\n"; } /** * SubsetByExpression may return false from input() (thus not making an * instance available immediately) even after the first batch has been * completed if the user has opted to apply the filter to instances after the * first batch (rather than just passing them through). * * @return true this filter may remove (consume) input instances after the * first batch has been completed. */ @Override public boolean mayRemoveInstanceAfterFirstBatchDone() { return true; } /** * Input an instance for filtering. Filter requires all training instances be * read before producing output (calling the method batchFinished() makes the * data available). If this instance is part of a new batch, m_NewBatch is set * to false. * * @param instance the input instance * @return true if the filtered instance may now be collected with output(). * @throws IllegalStateException if no input structure has been defined * @throws Exception if something goes wrong * @see #batchFinished() */ @Override public boolean input(Instance instance) throws Exception { if (getInputFormat() == null) { throw new IllegalStateException("No input instance format defined"); } if (m_NewBatch) { resetQueue(); m_NewBatch = false; } bufferInput(instance); int numReturnedFromParser = 0; if (isFirstBatchDone()) { Instances inst = new Instances(getInputFormat()); inst = process(inst); numReturnedFromParser = inst.numInstances(); for (int i = 0; i < inst.numInstances(); i++) { push(inst.instance(i), false); // No need to copy instance } flushInput(); } return (numReturnedFromParser > 0); } /** * Returns an enumeration describing the available options. * * @return an enumeration of all the available options. */ @Override public Enumeration<Option> listOptions() { Vector<Option> result = new Vector<Option>(); result.addElement(new Option("\tThe expression to use for filtering\n" + "\t(default: true).", "E", 1, "-E <expr>")); result.addElement(new Option( "\tApply the filter to instances that arrive after the first\n" + "\t(training) batch. The default is to not apply the filter (i.e.,\n" + "\talways return the instance)", "F", 0, "-F")); result.addAll(Collections.list(super.listOptions())); return result.elements(); } /** * Parses a given list of options. * <p/> * * <!-- options-start --> * Valid options are: <p/> * * <pre> -E &lt;expr&gt; * The expression to use for filtering * (default: true).</pre> * * <pre> -F * Apply the filter to instances that arrive after the first * (training) batch. The default is to not apply the filter (i.e., * always return the instance)</pre> * * <pre> -output-debug-info * If set, filter is run in debug mode and * may output additional info to the console</pre> * * <pre> -do-not-check-capabilities * If set, filter capabilities are not checked when input format is set * (use with caution).</pre> * * <!-- options-end --> * * @param options the list of options as an array of strings * @throws Exception if an option is not supported */ @Override public void setOptions(String[] options) throws Exception { String tmpStr = Utils.getOption('E', options); if (tmpStr.length() != 0) { setExpression(tmpStr); } else { setExpression("true"); } m_filterAfterFirstBatch = Utils.getFlag('F', options); if (getInputFormat() != null) { setInputFormat(getInputFormat()); } super.setOptions(options); Utils.checkForRemainingOptions(options); } /** * Gets the current settings of the filter. * * @return an array of strings suitable for passing to setOptions */ @Override public String[] getOptions() { Vector<String> result = new Vector<String>(); result.add("-E"); result.add("" + getExpression()); if (m_filterAfterFirstBatch) { result.add("-F"); } Collections.addAll(result, super.getOptions()); return result.toArray(new String[result.size()]); } /** * Returns the Capabilities of this filter. * * @return the capabilities of this object * @see Capabilities */ @Override public Capabilities getCapabilities() { Capabilities result = super.getCapabilities(); result.disableAll(); // attributes result.enable(Capability.STRING_ATTRIBUTES); result.enable(Capability.NOMINAL_ATTRIBUTES); result.enable(Capability.NUMERIC_ATTRIBUTES); result.enable(Capability.DATE_ATTRIBUTES); result.enable(Capability.MISSING_VALUES); // class result.enable(Capability.STRING_CLASS); result.enable(Capability.NOMINAL_CLASS); result.enable(Capability.NUMERIC_CLASS); result.enable(Capability.DATE_CLASS); result.enable(Capability.MISSING_CLASS_VALUES); result.enable(Capability.NO_CLASS); return result; } /** * Sets the expression used for filtering. * * @param value the expression */ public void setExpression(String value) { m_Expression = value; } /** * Returns the expression used for filtering. * * @return the expression */ public String getExpression() { return m_Expression; } /** * Returns the tip text for this property. * * @return tip text for this property suitable for displaying in the * explorer/experimenter gui */ public String expressionTipText() { return "The expression to used for filtering the dataset."; } /** * Set whether to apply the filter to instances that arrive once the first * (training) batch has been seen. The default is to not apply the filter and * just return each instance input. This is so that, when used in the * FilteredClassifier, a test instance does not get "consumed" by the filter * and a prediction is always generated. * * @param b true if the filter should be applied to instances that arrive * after the first (training) batch has been processed. */ public void setFilterAfterFirstBatch(boolean b) { m_filterAfterFirstBatch = b; } /** * Get whether to apply the filter to instances that arrive once the first * (training) batch has been seen. The default is to not apply the filter and * just return each instance input. This is so that, when used in the * FilteredClassifier, a test instance does not get "consumed" by the filter * and a prediction is always generated. * * @return true if the filter should be applied to instances that arrive after * the first (training) batch has been processed. */ public boolean getFilterAfterFirstBatch() { return m_filterAfterFirstBatch; } /** * Returns the tip text for this property. * * @return tip text for this property suitable for displaying in the * explorer/experimenter gui */ public String filterAfterFirstBatchTipText() { return "Whether to apply the filtering process to instances that " + "are input after the first (training) batch. The default " + "is false so that, when used in a FilteredClassifier, test" + " instances do not potentially get 'consumed' by the filter " + "and a prediction is always made."; } /** * Determines the output format based on the input format and returns this. * * @param inputFormat the input format to base the output format on * @return the output format * @throws Exception in case the determination goes wrong */ @Override protected Instances determineOutputFormat(Instances inputFormat) throws Exception { return new Instances(inputFormat, 0); } /** * Processes the given data (may change the provided dataset) and returns the * modified version. This method is called in batchFinished(). * * @param instances the data to process * @return the modified data * @throws Exception in case the processing goes wrong * @see #batchFinished() */ @Override protected Instances process(Instances instances) throws Exception { if (!isFirstBatchDone() || m_filterAfterFirstBatch) { // setup output Instances output = new Instances(instances, 0); // compile expression InstancesHelper instancesHelper = new InstancesHelper(instances); Node node = Parser.parse( // expression m_Expression, // variables instancesHelper, // macros new MacroDeclarationsCompositor( instancesHelper, new MathFunctions(), new IfElseMacro(), new JavaMacro() ) ); if (!(node instanceof BooleanExpression)) throw new Exception("Expression must be of boolean type!"); BooleanExpression condition = (BooleanExpression) node; // filter dataset for (int i = 0; i < instances.numInstances(); i++) { Instance instance = instances.get(i); instancesHelper.setInstance(instance); // evaluate expression if (condition.evaluate()) output.add((Instance) instance.copy()); } return output; } else { return instances; } } /** * Returns the revision string. * * @return the revision */ @Override public String getRevision() { return RevisionUtils.extract("$Revision$"); } /** * Main method for running this filter. * * @param args arguments for the filter: use -h for help */ public static void main(String[] args) { runFilter(new SubsetByExpression(), args); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/AbstractGUIApplication.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * AbstractGUIApplication * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import weka.core.Settings; import weka.knowledgeflow.LogManager; import javax.swing.*; import java.awt.*; /** * Base class for GUI applications in Weka * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public abstract class AbstractGUIApplication extends JPanel implements GUIApplication { private static final long serialVersionUID = -2116770422043462730L; /** Manages perspectives and provides the perspectives toolbar */ protected PerspectiveManager m_perspectiveManager; /** The settings for the application */ protected Settings m_applicationSettings; /** * Default constructor */ public AbstractGUIApplication() { this(true); } /** * Constructor * * @param layoutComponent true if the application should layout the component * with the "default" layout - i.e. the perspectives toolbar at the * north of a {@code BorderLayout} and the {@code PerspectiveManager} * at the center * @param allowedPerspectiveClassPrefixes {@code Perspective}s (loaded via the * PluginManager) whose fully qualified class names start with these * prefixes will be displayed in this application * @param disallowedPerspectiveClassPrefixes {@code Perspective}s (loaded via * the PluginManager) whose fully qualified class names start with * these prefixes will not be displayed in this application. Note * that disallowedPerspectiveClassPrefixes override * allowedPerspectivePrefixes */ public AbstractGUIApplication(boolean layoutComponent, String[] allowedPerspectiveClassPrefixes, String[] disallowedPerspectiveClassPrefixes) { m_perspectiveManager = new PerspectiveManager(this, allowedPerspectiveClassPrefixes, disallowedPerspectiveClassPrefixes); m_perspectiveManager.setMainApplicationForAllPerspectives(); if (layoutComponent) { setLayout(new BorderLayout()); add(m_perspectiveManager, BorderLayout.CENTER); if (m_perspectiveManager.perspectiveToolBarIsVisible()) { add(m_perspectiveManager.getPerspectiveToolBar(), BorderLayout.NORTH); } } } /** * Constructor * * @param layoutComponent true if the application should layout the component * with the "default" layout - i.e. the perspectives toolbar at the * north of a {@code BorderLayout} and the {@code PerspectiveManager} * at the center * @param allowedPerspectiveClassPrefixes {@code Perspective}s (loaded via the * PluginManager) whose fully qualified class names start with these * prefixes will be displayed in this application */ public AbstractGUIApplication(boolean layoutComponent, String... allowedPerspectiveClassPrefixes) { this(layoutComponent, allowedPerspectiveClassPrefixes, new String[0]); } /** * Get the {@code PerspectiveManager} in use by this application * * @return the {@code Perspective Manager} */ @Override public PerspectiveManager getPerspectiveManager() { return m_perspectiveManager; } /** * Get the current settings for this application * * @return the current settings for this application */ @Override public Settings getApplicationSettings() { if (m_applicationSettings == null) { m_applicationSettings = new Settings("weka", getApplicationID()); m_applicationSettings.applyDefaults(getApplicationDefaults()); } return m_applicationSettings; } /** * Returns true if the perspectives toolbar is visible at the current time * * @return true if the perspectives toolbar is visible */ @Override public boolean isPerspectivesToolBarVisible() { return m_perspectiveManager.perspectiveToolBarIsVisible(); } /** * Hide the perspectives toolbar */ @Override public void hidePerspectivesToolBar() { if (isPerspectivesToolBarVisible()) { m_perspectiveManager.setPerspectiveToolBarIsVisible(false); remove(m_perspectiveManager.getPerspectiveToolBar()); } } /** * Show the perspectives toolbar */ @Override public void showPerspectivesToolBar() { if (!isPerspectivesToolBarVisible()) { m_perspectiveManager.setPerspectiveToolBarIsVisible(true); add(m_perspectiveManager.getPerspectiveToolBar(), BorderLayout.NORTH); } } /** * Called when settings are changed by the user */ @Override public void settingsChanged() { // no-op. Subclasses to override if necessary } /** * Show the menu bar for the application * * @param topLevelAncestor the JFrame that contains the application */ @Override public void showMenuBar(JFrame topLevelAncestor) { m_perspectiveManager.showMenuBar(topLevelAncestor); } /** * Popup a dialog displaying the supplied Exception * * @param cause the exception to show */ @Override public void showErrorDialog(Exception cause) { String stackTrace = LogManager.stackTraceToString(cause); Object[] options = null; if (stackTrace != null && stackTrace.length() > 0) { options = new Object[2]; options[0] = "OK"; options[1] = "Show error"; } else { options = new Object[1]; options[0] = "OK"; } int result = JOptionPane.showOptionDialog(this, "An error has occurred: " + cause.getMessage(), getApplicationName(), JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[0]); if (result == 1) { JTextArea jt = new JTextArea(stackTrace, 10, 40); JOptionPane.showMessageDialog(this, new JScrollPane(jt), getApplicationName(), JOptionPane.ERROR_MESSAGE); } } /** * Popup an information dialog * * @param information the "information" (typically some text) to display * @param title the title for the dialog * @param isWarning true if this is a warning rather than just information */ @Override public void showInfoDialog(Object information, String title, boolean isWarning) { JOptionPane .showMessageDialog(this, information, title, isWarning ? JOptionPane.WARNING_MESSAGE : JOptionPane.INFORMATION_MESSAGE); } /** * Force a re-validation and repaint() of the application */ @Override public void revalidate() { if (getTopLevelAncestor() != null) { getTopLevelAncestor().revalidate(); getTopLevelAncestor().repaint(); } else { super.revalidate(); } repaint(); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/AbstractPerspective.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * AbstractPerspective.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand */ package weka.gui; import weka.core.Defaults; import weka.core.Instances; import weka.gui.knowledgeflow.StepVisual; import javax.swing.Icon; import javax.swing.JMenu; import javax.swing.JPanel; import java.util.ArrayList; import java.util.List; /** * Base classes for GUI perspectives to extend. Clients that extend this class * and make use of the {@code @PerspectiveInfo} annotation will only need to * override/implement a few methods. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public abstract class AbstractPerspective extends JPanel implements Perspective { /** For serialization */ private static final long serialVersionUID = 1919714661641262879L; /** True if this perspective is currently the active/visible one */ protected boolean m_isActive; /** True if this perspective has been loaded */ protected boolean m_isLoaded; /** The main application that is displaying this perspective */ protected GUIApplication m_mainApplication; /** The title of the perspective */ protected String m_perspectiveTitle = ""; /** The ID of the perspective */ protected String m_perspectiveID = ""; /** Tip text for this perspective */ protected String m_perspectiveTipText = ""; /** Icon for this perspective */ protected Icon m_perspectiveIcon; /** Logger for this perspective */ protected Logger m_log; /** * Constructor */ public AbstractPerspective() { } /** * Constructor * * @param ID the ID of the perspective * @param title the title of the the perspective */ public AbstractPerspective(String ID, String title) { m_perspectiveTitle = title; m_perspectiveID = ID; } /** * No-opp implementation. Subclasses should override if they can only complete * initialization by accessing the main application and/or the * PerspectiveManager. References to these two things are guaranteed to be * available when this method is called during the startup process */ @Override public void instantiationComplete() { // no-opp method. Subclasses should override } /** * Returns true if the perspective is usable at this time. This is a no-opp * implementation that always returns true. Subclasses should override if * there are specific conditions that need to be met (e.g. can't operate if * there are no instances set). * * @return true if this perspective is usable at this time */ @Override public boolean okToBeActive() { return true; } /** * Set active status of this perspective. True indicates that this perspective * is the visible active perspective in the application * * @param active true if this perspective is the active one */ @Override public void setActive(boolean active) { m_isActive = active; } /** * Set whether this perspective is "loaded" - i.e. whether or not the user has * opted to have it available in the perspective toolbar. The perspective can * make the decision as to allocating or freeing resources on the basis of * this. Note that the main application and perspective manager instances are * not available to the perspective until the instantiationComplete() method * has been called. * * @param loaded true if the perspective is available in the perspective * toolbar of the KnowledgeFlow */ @Override public void setLoaded(boolean loaded) { m_isLoaded = loaded; } /** * Set the main application. Gives other perspectives access to information * provided by the main application * * @param main the main application */ @Override public void setMainApplication(GUIApplication main) { m_mainApplication = main; } /** * Get the main application that this perspective belongs to * * @return the main application that this perspective belongs to */ @Override public GUIApplication getMainApplication() { return m_mainApplication; } /** * Get the ID of this perspective * * @return the ID of this perspective */ @Override public String getPerspectiveID() { if (m_perspectiveID != null && m_perspectiveID.length() > 0) { return m_perspectiveID; } PerspectiveInfo perspectiveA = this.getClass().getAnnotation(PerspectiveInfo.class); if (perspectiveA != null) { m_perspectiveID = perspectiveA.ID(); } return m_perspectiveID; } /** * Get the title of this perspective * * @return the title of this perspective */ @Override public String getPerspectiveTitle() { if (m_perspectiveTitle != null && m_perspectiveTitle.length() > 0) { return m_perspectiveTitle; } PerspectiveInfo perspectiveA = this.getClass().getAnnotation(PerspectiveInfo.class); if (perspectiveA != null) { m_perspectiveTitle = perspectiveA.title(); } return m_perspectiveTitle; } /** * Get the tool tip text for this perspective * * @return the tool tip text for this perspective */ @Override public String getPerspectiveTipText() { if (m_perspectiveTipText != null && m_perspectiveTipText.length() > 0) { return m_perspectiveTipText; } PerspectiveInfo perspectiveA = this.getClass().getAnnotation(PerspectiveInfo.class); if (perspectiveA != null) { m_perspectiveTipText = perspectiveA.toolTipText(); } return m_perspectiveTipText; } /** * Get the icon for this perspective * * @return the icon for this perspective */ @Override public Icon getPerspectiveIcon() { if (m_perspectiveIcon != null) { return m_perspectiveIcon; } PerspectiveInfo perspectiveA = this.getClass().getAnnotation(PerspectiveInfo.class); if (perspectiveA != null && perspectiveA.iconPath() != null && perspectiveA.iconPath().length() > 0) { m_perspectiveIcon = StepVisual.loadIcon(this.getClass().getClassLoader(), perspectiveA.iconPath()); } return m_perspectiveIcon; } /** * Get an ordered list of menus to appear in the main menu bar. Return null * for no menus * * @return a list of menus to appear in the main menu bar or null for no menus */ @Override public List<JMenu> getMenus() { return new ArrayList<JMenu>(); } /** * Set instances (if this perspective can use them) * * @param instances the instances */ @Override public void setInstances(Instances instances) { // subclasses to override as necessary } /** * Returns true if this perspective can do something meaningful with a set of * instances * * @return true if this perspective accepts instances */ @Override public boolean acceptsInstances() { // subclasses to override as necessary return false; } /** * Whether this perspective requires a graphical log to write to * * @return true if a log is needed by this perspective */ @Override public boolean requiresLog() { // subclasses to override as necessary return false; } /** * Get the default settings for this perspective (or null if there are none) * * @return the default settings for this perspective, or null if the * perspective does not have any settings */ @Override public Defaults getDefaultSettings() { // subclasses to override if they have default settings return null; } /** * Called when the user alters settings. The settings altered by the user are * not necessarily ones related to this perspective */ @Override public void settingsChanged() { // no-op. subclasses to override if necessary } /** * Set a log to use (if required by the perspective) * * @param log the graphical log to use */ @Override public void setLog(Logger log) { m_log = log; } /** * Returns the perspective's title * * @return the title of the perspective */ public String toString() { return getPerspectiveTitle(); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/AttributeListPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * AttributeListPanel.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.awt.BorderLayout; import java.awt.Dimension; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableColumnModel; import weka.core.Instances; /** * Creates a panel that displays the attributes contained in a set of instances, * letting the user select a single attribute for inspection. * * @author Richard Kirkby (rkirkby@cs.waikato.ac.nz) * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public class AttributeListPanel extends JPanel { /** for serialization */ private static final long serialVersionUID = -2030706987910400362L; /** * A table model that looks at the names of attributes. */ class AttributeTableModel extends AbstractTableModel { /** for serialization */ private static final long serialVersionUID = -7345701953670327707L; /** The instances who's attribute structure we are reporting */ protected Instances m_Instances; /** * Creates the tablemodel with the given set of instances. * * @param instances the initial set of Instances */ public AttributeTableModel(Instances instances) { setInstances(instances); } /** * Sets the tablemodel to look at a new set of instances. * * @param instances the new set of Instances. */ public void setInstances(Instances instances) { m_Instances = instances; } /** * Gets the number of attributes. * * @return the number of attributes. */ @Override public int getRowCount() { return m_Instances.numAttributes(); } /** * Gets the number of columns: 2 * * @return 2 */ @Override public int getColumnCount() { return 2; } /** * Gets a table cell * * @param row the row index * @param column the column index * @return the value at row, column */ @Override public Object getValueAt(int row, int column) { switch (column) { case 0: return new Integer(row + 1); case 1: return m_Instances.attribute(row).name(); default: return null; } } /** * Gets the name for a column. * * @param column the column index. * @return the name of the column. */ @Override public String getColumnName(int column) { switch (column) { case 0: return new String("No."); case 1: return new String("Name"); default: return null; } } /** * Gets the class of elements in a column. * * @param col the column index. * @return the class of elements in the column. */ @Override public Class<?> getColumnClass(int col) { return getValueAt(0, col).getClass(); } /** * Returns false * * @param row ignored * @param col ignored * @return false */ @Override public boolean isCellEditable(int row, int col) { return false; } } /** The table displaying attribute names */ protected JTable m_Table = new JTable(); /** The table model containing attribute names */ protected AttributeTableModel m_Model; /** * Creates the attribute selection panel with no initial instances. */ public AttributeListPanel() { m_Table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); m_Table.setColumnSelectionAllowed(false); m_Table.setPreferredScrollableViewportSize(new Dimension(250, 150)); setLayout(new BorderLayout()); add(new JScrollPane(m_Table), BorderLayout.CENTER); } /** * Sets the instances who's attribute names will be displayed. * * @param newInstances the new set of instances */ public void setInstances(Instances newInstances) { if (m_Model == null) { m_Model = new AttributeTableModel(newInstances); m_Table.setModel(m_Model); TableColumnModel tcm = m_Table.getColumnModel(); tcm.getColumn(0).setMaxWidth(60); tcm.getColumn(1).setMinWidth(100); } else { m_Model.setInstances(newInstances); } m_Table.sizeColumnsToFit(-1); m_Table.revalidate(); m_Table.repaint(); } /** * Gets the selection model used by the table. * * @return a value of type 'ListSelectionModel' */ public ListSelectionModel getSelectionModel() { return m_Table.getSelectionModel(); } /** * Tests the attribute list panel from the command line. * * @param args must contain the name of an arff file to load. */ public static void main(String[] args) { try { if (args.length == 0) { throw new Exception("supply the name of an arff file"); } Instances i = new Instances(new java.io.BufferedReader( new java.io.FileReader(args[0]))); AttributeListPanel asp = new AttributeListPanel(); final javax.swing.JFrame jf = new javax.swing.JFrame( "Attribute List Panel"); jf.getContentPane().setLayout(new BorderLayout()); jf.getContentPane().add(asp, BorderLayout.CENTER); jf.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { jf.dispose(); System.exit(0); } }); jf.pack(); jf.setVisible(true); asp.setInstances(i); } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } } } // AttributeListPanel
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/AttributeSelectionPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * AttributeSelectionPanel.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.regex.Pattern; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableColumnModel; import javax.swing.table.TableModel; import weka.core.Instances; /** * Creates a panel that displays the attributes contained in a set of instances, * letting the user toggle whether each attribute is selected or not (eg: so * that unselected attributes can be removed before classification). <br> * Besides the All, None and Invert button one can also choose attributes which * names match a regular expression (Pattern button). E.g. for removing all * attributes that contain an ID and therefore unwanted information, one can * match all names that contain "id" in the name:<br> * * <pre> * (.*_id_.*|.*_id$|^id$) * </pre> * * This does not match e.g. "humidity", which could be an attribute we would * like to keep. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class AttributeSelectionPanel extends JPanel { /** for serialization */ private static final long serialVersionUID = 627131485290359194L; /** * A table model that looks at the names of attributes and maintains a list of * attributes that have been "selected". */ class AttributeTableModel extends AbstractTableModel { /** for serialization */ private static final long serialVersionUID = -4152987434024338064L; /** The instances who's attribute structure we are reporting */ protected Instances m_Instances; /** The flag for whether the instance will be included */ protected boolean[] m_Selected; /** * Creates the tablemodel with the given set of instances. * * @param instances the initial set of Instances */ public AttributeTableModel(Instances instances) { setInstances(instances); } /** * Sets the tablemodel to look at a new set of instances. * * @param instances the new set of Instances. */ public void setInstances(Instances instances) { m_Instances = instances; m_Selected = new boolean[m_Instances.numAttributes()]; } /** * Gets the number of attributes. * * @return the number of attributes. */ @Override public int getRowCount() { return m_Selected.length; } /** * Gets the number of columns: 3 * * @return 3 */ @Override public int getColumnCount() { return 3; } /** * Gets a table cell * * @param row the row index * @param column the column index * @return the value at row, column */ @Override public Object getValueAt(int row, int column) { switch (column) { case 0: return new Integer(row + 1); case 1: return new Boolean(m_Selected[row]); case 2: return m_Instances.attribute(row).name(); default: return null; } } /** * Gets the name for a column. * * @param column the column index. * @return the name of the column. */ @Override public String getColumnName(int column) { switch (column) { case 0: return new String("No."); case 1: return new String(""); case 2: return new String("Name"); default: return null; } } /** * Sets the value at a cell. * * @param value the new value. * @param row the row index. * @param col the column index. */ @Override public void setValueAt(Object value, int row, int col) { if (col == 1) { m_Selected[row] = ((Boolean) value).booleanValue(); fireTableRowsUpdated(0, m_Selected.length); } } /** * Gets the class of elements in a column. * * @param col the column index. * @return the class of elements in the column. */ @Override public Class<?> getColumnClass(int col) { return getValueAt(0, col).getClass(); } /** * Returns true if the column is the "selected" column. * * @param row ignored * @param col the column index. * @return true if col == 1. */ @Override public boolean isCellEditable(int row, int col) { if (col == 1) { return true; } return false; } /** * Gets an array containing the indices of all selected attributes. * * @return the array of selected indices. */ public int[] getSelectedAttributes() { int[] r1 = new int[getRowCount()]; int selCount = 0; for (int i = 0; i < getRowCount(); i++) { if (m_Selected[i]) { r1[selCount++] = i; } } int[] result = new int[selCount]; System.arraycopy(r1, 0, result, 0, selCount); return result; } /** * Sets the state of all attributes to selected. */ public void includeAll() { for (int i = 0; i < m_Selected.length; i++) { m_Selected[i] = true; } fireTableRowsUpdated(0, m_Selected.length); } /** * Deselects all attributes. */ public void removeAll() { for (int i = 0; i < m_Selected.length; i++) { m_Selected[i] = false; } fireTableRowsUpdated(0, m_Selected.length); } /** * Inverts the selected status of each attribute. */ public void invert() { for (int i = 0; i < m_Selected.length; i++) { m_Selected[i] = !m_Selected[i]; } fireTableRowsUpdated(0, m_Selected.length); } /** * applies the perl regular expression pattern to select the attribute names * (expects a valid reg expression!) * * @param pattern a perl reg. expression */ public void pattern(String pattern) { for (int i = 0; i < m_Selected.length; i++) { m_Selected[i] = Pattern.matches(pattern, m_Instances.attribute(i) .name()); } fireTableRowsUpdated(0, m_Selected.length); } public void setSelectedAttributes(boolean[] selected) throws Exception { if (selected.length != m_Selected.length) { throw new Exception("Supplied array does not have the same number " + "of elements as there are attributes!"); } for (int i = 0; i < selected.length; i++) { m_Selected[i] = selected[i]; } fireTableRowsUpdated(0, m_Selected.length); } } /** Press to select all attributes */ protected JButton m_IncludeAll = new JButton("All"); /** Press to deselect all attributes */ protected JButton m_RemoveAll = new JButton("None"); /** Press to invert the current selection */ protected JButton m_Invert = new JButton("Invert"); /** Press to enter a perl regular expression for selection */ protected JButton m_Pattern = new JButton("Pattern"); /** The table displaying attribute names and selection status */ protected JTable m_Table = new JTable(); /** The table model containing attribute names and selection status */ protected AttributeTableModel m_Model; /** The current regular expression. */ protected String m_PatternRegEx = ""; /** * Creates the attribute selection panel with no initial instances. */ public AttributeSelectionPanel() { this(true, true, true, true); } /** * Creates the attribute selection panel with no initial instances. * * @param include true if the include button is to be shown * @param remove true if the remove button is to be shown * @param invert true if the invert button is to be shown * @param patter true if the pattern button is to be shown */ public AttributeSelectionPanel(boolean include, boolean remove, boolean invert, boolean pattern) { m_IncludeAll.setToolTipText("Selects all attributes"); m_IncludeAll.setEnabled(false); m_IncludeAll.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_Model.includeAll(); } }); m_RemoveAll.setToolTipText("Unselects all attributes"); m_RemoveAll.setEnabled(false); m_RemoveAll.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_Model.removeAll(); } }); m_Invert.setToolTipText("Inverts the current attribute selection"); m_Invert.setEnabled(false); m_Invert.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_Model.invert(); } }); m_Pattern .setToolTipText("Selects all attributes that match a reg. expression"); m_Pattern.setEnabled(false); m_Pattern.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String pattern = JOptionPane.showInputDialog(m_Pattern.getParent(), "Enter a Perl regular expression", m_PatternRegEx); if (pattern != null) { try { Pattern.compile(pattern); m_PatternRegEx = pattern; m_Model.pattern(pattern); } catch (Exception ex) { JOptionPane.showMessageDialog(m_Pattern.getParent(), "'" + pattern + "' is not a valid Perl regular expression!\n" + "Error: " + ex, "Error in Pattern...", JOptionPane.ERROR_MESSAGE); } } } }); m_Table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); m_Table.setColumnSelectionAllowed(false); m_Table.setPreferredScrollableViewportSize(new Dimension(250, 150)); m_Table.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); if (((e.getModifiers() & InputEvent.BUTTON1_MASK) != InputEvent.BUTTON1_MASK) || e.isAltDown()) { popupCopyRangeMenu(e.getX(), e.getY()); } } }); // Set up the layout JPanel p1 = new JPanel(); p1.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5)); p1.setLayout(new GridLayout(1, 4, 5, 5)); if (include) { p1.add(m_IncludeAll); } if (remove) { p1.add(m_RemoveAll); } if (invert) { p1.add(m_Invert); } if (pattern) { p1.add(m_Pattern); } setLayout(new BorderLayout()); if (include || remove || invert || pattern) { add(p1, BorderLayout.NORTH); } add(new JScrollPane(m_Table), BorderLayout.CENTER); } public Dimension getPreferredScrollableViewportSize() { return m_Table.getPreferredScrollableViewportSize(); } public void setPreferredScrollableViewportSize(Dimension d) { m_Table.setPreferredScrollableViewportSize(d); } protected void popupCopyRangeMenu(int x, int y) { JPopupMenu popupMenu = new JPopupMenu(); final JMenuItem copyRangeItem = new JMenuItem("Copy checked items to range in clipboard"); popupMenu.add(copyRangeItem); if (getSelectedAttributes().length == 0) { copyRangeItem.setEnabled(false); } copyRangeItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int[] selected = getSelectedAttributes(); StringBuilder b = new StringBuilder(); int prev = -1; int lastInString = -1; for (int v : selected) { if (v == 0) { b.append("first-"); prev = v; lastInString = v; } else { if (prev < 0) { prev = v; lastInString = v; b.append(v + 1).append("-"); } else { if (v - prev == 1) { prev = v; continue; } if (b.charAt(b.length() - 1) == '-') { if (prev == lastInString) { b.setCharAt(b.length() - 1, ','); } else { b.append(prev + 1).append(","); } } if (v == m_Model.getRowCount() - 1) { b.append("last"); } else { b.append(v + 1).append("-"); } prev = v; lastInString = v; } } } if (b.charAt(b.length() - 1) == '-') { if (selected.length > 1 && lastInString != selected[selected.length - 1]) { if (selected[selected.length - 1] == m_Model.getRowCount() - 1) { b.append("last"); } else { b.append(selected[selected.length - 1] + 1); } } else { b.setLength(b.length() - 1); } } StringSelection selection = new StringSelection(b.toString()); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(selection, selection); } }); popupMenu.show(m_Table, x, y); } /** * Sets the instances who's attribute names will be displayed. * * @param newInstances the new set of instances */ public void setInstances(Instances newInstances) { if (m_Model == null) { m_Model = new AttributeTableModel(newInstances); m_Table.setModel(m_Model); TableColumnModel tcm = m_Table.getColumnModel(); tcm.getColumn(0).setMaxWidth(60); tcm.getColumn(1).setMaxWidth(tcm.getColumn(1).getMinWidth()); tcm.getColumn(2).setMinWidth(100); } else { m_Model.setInstances(newInstances); m_Table.clearSelection(); } m_IncludeAll.setEnabled(true); m_RemoveAll.setEnabled(true); m_Invert.setEnabled(true); m_Pattern.setEnabled(true); m_Table.sizeColumnsToFit(2); m_Table.revalidate(); m_Table.repaint(); } /** * Gets an array containing the indices of all selected attributes. * * @return the array of selected indices. */ public int[] getSelectedAttributes() { return (m_Model == null) ? null : m_Model.getSelectedAttributes(); } /** * Set the selected attributes in the widget. Note that setInstances() must * have been called first. * * @param selected an array of boolean indicating which attributes are to have * their check boxes selected. * @throws Exception if the supplied array of booleans does not have the same * number of elements as there are attributes. */ public void setSelectedAttributes(boolean[] selected) throws Exception { if (m_Model != null) { m_Model.setSelectedAttributes(selected); } } /** * Get the table model in use (or null if no instances have been set yet). * * @return the table model in use or null if no instances have been seen yet. */ public TableModel getTableModel() { return m_Model; } /** * Gets the selection model used by the table. * * @return a value of type 'ListSelectionModel' */ public ListSelectionModel getSelectionModel() { return m_Table.getSelectionModel(); } /** * Tests the attribute selection panel from the command line. * * @param args must contain the name of an arff file to load. */ public static void main(String[] args) { try { if (args.length == 0) { throw new Exception("supply the name of an arff file"); } Instances i = new Instances(new java.io.BufferedReader( new java.io.FileReader(args[0]))); AttributeSelectionPanel asp = new AttributeSelectionPanel(); final javax.swing.JFrame jf = new javax.swing.JFrame( "Attribute Selection Panel"); jf.getContentPane().setLayout(new BorderLayout()); jf.getContentPane().add(asp, BorderLayout.CENTER); jf.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { jf.dispose(); System.exit(0); } }); jf.pack(); jf.setVisible(true); asp.setInstances(i); } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } } } // AttributeSelectionPanel
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/AttributeSummaryPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * AttributeSummaryPanel.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.BorderFactory; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import weka.core.Attribute; import weka.core.AttributeStats; import weka.core.Instances; import weka.core.Utils; /** * This panel displays summary statistics about an attribute: name, type * number/% of missing/unique values, number of distinct values. For numeric * attributes gives some other stats (mean/std dev), for nominal attributes * gives counts for each attribute value. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public class AttributeSummaryPanel extends JPanel { /** for serialization */ static final long serialVersionUID = -5434987925737735880L; /** Message shown when no instances have been loaded and no attribute set */ protected static final String NO_SOURCE = "None"; /** Displays the name of the relation */ protected JLabel m_AttributeNameLab = new JLabel(NO_SOURCE); /** Displays the weight of attribute */ protected JLabel m_AttributeWeightLab = new JLabel(NO_SOURCE); /** Displays the string "Weight:" */ protected JLabel m_WeightLab = new JLabel("Weight:", SwingConstants.RIGHT); /** Displays the type of attribute */ protected JLabel m_AttributeTypeLab = new JLabel(NO_SOURCE); /** Displays the number of missing values */ protected JLabel m_MissingLab = new JLabel(NO_SOURCE); /** Displays the number of unique values */ protected JLabel m_UniqueLab = new JLabel(NO_SOURCE); /** Displays the number of distinct values */ protected JLabel m_DistinctLab = new JLabel(NO_SOURCE); /** Displays other stats in a table */ protected JTable m_StatsTable = new JTable() { /** for serialization */ private static final long serialVersionUID = 7165142874670048578L; /** * returns always false, since it's just information for the user * * @param row the row * @param column the column * @return always false, i.e., the whole table is not editable */ @Override public boolean isCellEditable(final int row, final int column) { return false; } }; /** The instances we're playing with */ protected Instances m_Instances; /** Cached stats on the attributes we've summarized so far */ protected AttributeStats[] m_AttributeStats; /** Do all instances have the same weight */ protected boolean m_allEqualWeights = true; /** * Creates the instances panel with no initial instances. */ public AttributeSummaryPanel() { JPanel simple = new JPanel(); GridBagLayout gbL = new GridBagLayout(); simple.setLayout(gbL); JLabel lab = new JLabel("Name:", SwingConstants.RIGHT); lab.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0)); GridBagConstraints gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.EAST; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 0; gbC.gridx = 0; gbL.setConstraints(lab, gbC); simple.add(lab); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.WEST; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 0; gbC.gridx = 1; gbC.weightx = 100; gbC.gridwidth = 3; gbL.setConstraints(this.m_AttributeNameLab, gbC); simple.add(this.m_AttributeNameLab); this.m_AttributeNameLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 10)); this.m_WeightLab.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0)); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.EAST; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 0; gbC.gridx = 2; gbL.setConstraints(this.m_WeightLab, gbC); simple.add(this.m_WeightLab); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.WEST; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 0; gbC.gridx = 3; gbC.weightx = 100; gbC.gridwidth = 3; gbL.setConstraints(this.m_AttributeWeightLab, gbC); simple.add(this.m_AttributeWeightLab); this.m_AttributeWeightLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 10)); lab = new JLabel("Type:", SwingConstants.RIGHT); lab.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0)); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.EAST; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 0; gbC.gridx = 4; gbL.setConstraints(lab, gbC); simple.add(lab); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.WEST; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 0; gbC.gridx = 5; gbC.weightx = 100; gbL.setConstraints(this.m_AttributeTypeLab, gbC); simple.add(this.m_AttributeTypeLab); this.m_AttributeTypeLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 10)); // Put into a separate panel? lab = new JLabel("Missing:", SwingConstants.RIGHT); lab.setBorder(BorderFactory.createEmptyBorder(0, 10, 5, 0)); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.EAST; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 1; gbC.gridx = 0; gbL.setConstraints(lab, gbC); simple.add(lab); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.WEST; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 1; gbC.gridx = 1; gbC.weightx = 100; gbL.setConstraints(this.m_MissingLab, gbC); simple.add(this.m_MissingLab); this.m_MissingLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 10)); lab = new JLabel("Distinct:", SwingConstants.RIGHT); lab.setBorder(BorderFactory.createEmptyBorder(0, 10, 5, 0)); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.EAST; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 1; gbC.gridx = 2; gbL.setConstraints(lab, gbC); simple.add(lab); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.WEST; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 1; gbC.gridx = 3; gbC.weightx = 100; gbL.setConstraints(this.m_DistinctLab, gbC); simple.add(this.m_DistinctLab); this.m_DistinctLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 10)); lab = new JLabel("Unique:", SwingConstants.RIGHT); lab.setBorder(BorderFactory.createEmptyBorder(0, 10, 5, 0)); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.EAST; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 1; gbC.gridx = 4; gbL.setConstraints(lab, gbC); simple.add(lab); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.WEST; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 1; gbC.gridx = 5; gbC.weightx = 100; gbL.setConstraints(this.m_UniqueLab, gbC); simple.add(this.m_UniqueLab); this.m_UniqueLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 10)); this.setLayout(new BorderLayout()); this.add(simple, BorderLayout.NORTH); this.add(new JScrollPane(this.m_StatsTable), BorderLayout.CENTER); this.m_StatsTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION); } /** * Tells the panel to use a new set of instances. * * @param inst a set of Instances */ public void setInstances(final Instances inst) { this.m_Instances = inst; this.m_AttributeStats = new AttributeStats[inst.numAttributes()]; this.m_AttributeNameLab.setText(NO_SOURCE); this.m_AttributeTypeLab.setText(NO_SOURCE); this.m_AttributeWeightLab.setText(NO_SOURCE); this.m_MissingLab.setText(NO_SOURCE); this.m_UniqueLab.setText(NO_SOURCE); this.m_DistinctLab.setText(NO_SOURCE); this.m_StatsTable.setModel(new DefaultTableModel()); this.m_allEqualWeights = true; if (this.m_Instances.numInstances() == 0) { return; } double w = this.m_Instances.instance(0).weight(); for (int i = 1; i < this.m_Instances.numInstances(); i++) { if (this.m_Instances.instance(i).weight() != w) { this.m_allEqualWeights = false; break; } } } /** * Sets the attribute that statistics will be displayed for. * * @param index the index of the attribute to display */ public void setAttribute(final int index) { this.setHeader(index); if (this.m_AttributeStats[index] == null) { Thread t = new Thread() { @Override public void run() { try { AttributeSummaryPanel.this.m_AttributeStats[index] = AttributeSummaryPanel.this.m_Instances.attributeStats(index); } catch (InterruptedException e) { throw new IllegalStateException(e); } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { AttributeSummaryPanel.this.setDerived(index); AttributeSummaryPanel.this.m_StatsTable.sizeColumnsToFit(-1); AttributeSummaryPanel.this.m_StatsTable.revalidate(); AttributeSummaryPanel.this.m_StatsTable.repaint(); } }); } }; t.setPriority(Thread.MIN_PRIORITY); t.start(); } else { this.setDerived(index); } } /** * Sets the gui elements for fields that are stored in the AttributeStats * structure. * * @param index the index of the attribute */ protected void setDerived(final int index) { AttributeStats as = this.m_AttributeStats[index]; long percent = Math.round(100.0 * as.missingCount / as.totalCount); this.m_MissingLab.setText("" + as.missingCount + " (" + percent + "%)"); percent = Math.round(100.0 * as.uniqueCount / as.totalCount); this.m_UniqueLab.setText("" + as.uniqueCount + " (" + percent + "%)"); this.m_DistinctLab.setText("" + as.distinctCount); this.setTable(as, index); } /** * Creates a tablemodel for the attribute being displayed * * @param as the attribute statistics * @param index the index of the attribute */ protected void setTable(final AttributeStats as, final int index) { if (as.nominalCounts != null) { Attribute att = this.m_Instances.attribute(index); Object[] colNames = { "No.", "Label", "Count", "Weight" }; Object[][] data = new Object[as.nominalCounts.length][4]; for (int i = 0; i < as.nominalCounts.length; i++) { data[i][0] = new Integer(i + 1); data[i][1] = att.value(i); data[i][2] = new Integer(as.nominalCounts[i]); data[i][3] = new Double(Utils.doubleToString(as.nominalWeights[i], 3)); } this.m_StatsTable.setModel(new DefaultTableModel(data, colNames)); this.m_StatsTable.getColumnModel().getColumn(0).setMaxWidth(60); DefaultTableCellRenderer tempR = new DefaultTableCellRenderer(); tempR.setHorizontalAlignment(JLabel.RIGHT); this.m_StatsTable.getColumnModel().getColumn(0).setCellRenderer(tempR); } else if (as.numericStats != null) { Object[] colNames = { "Statistic", "Value" }; Object[][] data = new Object[4][2]; data[0][0] = "Minimum"; data[0][1] = Utils.doubleToString(as.numericStats.min, 3); data[1][0] = "Maximum"; data[1][1] = Utils.doubleToString(as.numericStats.max, 3); data[2][0] = "Mean" + ((!this.m_allEqualWeights) ? " (weighted)" : ""); data[2][1] = Utils.doubleToString(as.numericStats.mean, 3); data[3][0] = "StdDev" + ((!this.m_allEqualWeights) ? " (weighted)" : ""); data[3][1] = Utils.doubleToString(as.numericStats.stdDev, 3); this.m_StatsTable.setModel(new DefaultTableModel(data, colNames)); } else { this.m_StatsTable.setModel(new DefaultTableModel()); } this.m_StatsTable.getColumnModel().setColumnMargin(4); } /** * Sets the labels for fields we can determine just from the instance header. * * @param index the index of the attribute */ protected void setHeader(final int index) { Attribute att = this.m_Instances.attribute(index); this.m_AttributeNameLab.setText(att.name()); switch (att.type()) { case Attribute.NOMINAL: this.m_AttributeTypeLab.setText("Nominal"); break; case Attribute.NUMERIC: this.m_AttributeTypeLab.setText("Numeric"); break; case Attribute.STRING: this.m_AttributeTypeLab.setText("String"); break; case Attribute.DATE: this.m_AttributeTypeLab.setText("Date"); break; case Attribute.RELATIONAL: this.m_AttributeTypeLab.setText("Relational"); break; default: this.m_AttributeTypeLab.setText("Unknown"); break; } if (att.weight() != 1.0) { this.m_AttributeWeightLab.setText(Utils.doubleToString(att.weight(), 3)); this.m_AttributeWeightLab.setVisible(true); this.m_WeightLab.setVisible(true); } else { this.m_AttributeWeightLab.setVisible(false); this.m_WeightLab.setVisible(false); } this.m_MissingLab.setText("..."); this.m_UniqueLab.setText("..."); this.m_DistinctLab.setText("..."); } /** * Tests out the attribute summary panel from the command line. * * @param args optional name of dataset to load */ public static void main(final String[] args) { try { final javax.swing.JFrame jf = new javax.swing.JFrame("Attribute Panel"); jf.getContentPane().setLayout(new BorderLayout()); final AttributeSummaryPanel p = new AttributeSummaryPanel(); p.setBorder(BorderFactory.createTitledBorder("Attribute")); jf.getContentPane().add(p, BorderLayout.CENTER); final javax.swing.JComboBox j = new javax.swing.JComboBox(); j.setEnabled(false); j.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent e) { p.setAttribute(j.getSelectedIndex()); } }); jf.getContentPane().add(j, BorderLayout.NORTH); jf.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(final java.awt.event.WindowEvent e) { jf.dispose(); System.exit(0); } }); jf.pack(); jf.setVisible(true); if (args.length == 1) { java.io.Reader r = new java.io.BufferedReader(new java.io.FileReader(args[0])); Instances inst = new Instances(r); p.setInstances(inst); p.setAttribute(0); String[] names = new String[inst.numAttributes()]; for (int i = 0; i < names.length; i++) { names[i] = inst.attribute(i).name(); } j.setModel(new javax.swing.DefaultComboBoxModel(names)); j.setEnabled(true); } } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/AttributeVisualizationPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * AttributeVisualizationPanel.java * Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.FlowLayout; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseEvent; import java.io.FileReader; import java.util.ArrayList; import javax.swing.JComboBox; import javax.swing.JFrame; import weka.core.Attribute; import weka.core.AttributeStats; import weka.core.Instances; import weka.core.SparseInstance; import weka.core.Utils; import weka.gui.visualize.PrintableComponent; import weka.gui.visualize.PrintablePanel; /** * Creates a panel that shows a visualization of an attribute in a dataset. For * nominal attribute it shows a bar plot, with each bar corresponding to each * nominal value of the attribute with its height equal to the frequecy that * value appears in the dataset. For numeric attributes, it displays a * histogram. The width of an interval in the histogram is calculated using * Scott's(1979) method: <br> * intervalWidth = Max(1, 3.49*Std.Dev*numInstances^(1/3)) Then the number of * intervals is calculated by: <br> * intervals = max(1, Math.round(Range/intervalWidth); * * @author Ashraf M. Kibriya (amk14@cs.waikato.ac.nz) * @version $Revision$ */ public class AttributeVisualizationPanel extends PrintablePanel { /** for serialization */ private static final long serialVersionUID = -8650490488825371193L; /** This holds the current set of instances */ protected Instances m_data; /** * This holds the attribute stats of the current attribute on display. It is * calculated in setAttribute(int idx) when it is called to set a new * attribute index. */ protected AttributeStats m_as; /** Cache of attribute stats info for the current data set */ protected AttributeStats[] m_asCache; /** * This holds the index of the current attribute on display and should be set * through setAttribute(int idx). */ protected int m_attribIndex; /** * This holds the max value of the current attribute. In case of nominal * attribute it is the highest count that a nominal value has in the attribute * (given by m_as.nominalWeights[i]), otherwise in case of numeric attribute * it is simply the maximum value present in the attribute (given by * m_as.numericStats.max). It is used to calculate the ratio of the height of * the bars with respect to the height of the display area. */ protected double m_maxValue; /** * This array holds the count (or height) for the each of the bars in a * barplot or a histogram. In case of barplots (and current attribute being * nominal) its length (and the number of bars) is equal to the number of * nominal values in the current attribute, with each field of the array being * equal to the count of each nominal that it represents (the count of ith * nominal value of an attribute is given by m_as.nominalWeights[i]). Whereas, * in case of histograms (and current attribute being numeric) the width of * its intervals is calculated by Scott's(1979) method: <br> * intervalWidth = Max(1, 3.49*Std.Dev*numInstances^(1/3)) And the number of * intervals by: <br> * intervals = max(1, Math.round(Range/intervalWidth); Then each field of this * array contains the number of values of the current attribute that fall in * the histogram interval that it represents. <br> * NOTE: The values of this array are only calculated if the class attribute * is not set or if it is numeric. */ protected double[] m_histBarCounts; /** * This array holds the per class count (or per class height) of the each of * the bars in a barplot or a histogram. For nominal attributes the format is: <br> * m_histBarClassCounts[nominalValue][classValue+1]. For numeric attributes * the format is: <br> * m_histBarClassCounts[interval][classValues+1], <br> * where the number of intervals is calculated by the Scott's method as * mentioned above. The array is initialized to have 1+numClasses to * accomodate for instances with missing class value. The ones with missing * class value are displayed as a black sub par in a histogram or a barplot. * * NOTE: The values of this array are only calculated if the class attribute * is set and it is nominal. */ SparseInstance m_histBarClassCounts[]; /** * Contains the range of each bar in a histogram. It is used to work out the * range of bar the mouse pointer is on in getToolTipText(). */ protected double m_barRange; /** Contains the current class index. */ protected int m_classIndex; /** * This stores the BarCalc or HistCalc thread while a new barplot or histogram * is being calculated. */ private Thread m_hc; /** True if the thread m_hc above is running. */ private boolean m_threadRun = false; private boolean m_doneCurrentAttribute = false; private boolean m_displayCurrentAttribute = false; /** * This stores and lets the user select a class attribute. It also has an * entry "No Class" if the user does not want to set a class attribute for * colouring. */ protected JComboBox m_colorAttrib; /** * Fontmetrics used to get the font size which is required for calculating * displayable area size, bar height ratio and width of strings that are * displayed on top of bars indicating their count. */ private final FontMetrics m_fm; /** * Lock variable to synchronize the different threads running currently in * this class. There are two to three threads in this class, AWT paint thread * which is handled differently in paintComponent() which checks on * m_threadRun to determine if it can perform full paint or not, the second * thread is the main execution thread and the third is the one represented by * m_hc which we start when we want to calculate the internal fields for a bar * plot or a histogram. */ private final Integer m_locker = new Integer(1); // Image img; /** * Contains discrete colours for colouring of subbars of histograms and bar * plots when the class attribute is set and is nominal */ private final ArrayList<Color> m_colorList = new ArrayList<Color>(); /** default colour list */ private static final Color[] m_defaultColors = { Color.blue, Color.red, Color.cyan, new Color(75, 123, 130), Color.pink, Color.green, Color.orange, new Color(255, 0, 255), new Color(255, 0, 0), new Color(0, 255, 0), }; /** * Constructor - If used then the class will not show the class selection * combo box. */ public AttributeVisualizationPanel() { this(false); } /** * Constructor. * * @param showColouringOption - should be true if the class selection combo * box is to be displayed with the histogram/barplot, or false * otherwise. P.S: the combo box is always created it just won't be * shown if showColouringOption is false. */ public AttributeVisualizationPanel(final boolean showColouringOption) { this.setFont(new Font("Default", Font.PLAIN, 9)); this.m_fm = this.getFontMetrics(this.getFont()); this.setToolTipText(""); FlowLayout fl = new FlowLayout(FlowLayout.LEFT); this.setLayout(fl); this.addComponentListener(new ComponentAdapter() { @Override public void componentResized(final ComponentEvent ce) { if (AttributeVisualizationPanel.this.m_data != null) { // calcGraph(); } } }); this.m_colorAttrib = new JComboBox(); this.m_colorAttrib.addItemListener(new ItemListener() { @Override public void itemStateChanged(final ItemEvent ie) { if (ie.getStateChange() == ItemEvent.SELECTED) { AttributeVisualizationPanel.this.m_classIndex = AttributeVisualizationPanel.this.m_colorAttrib.getSelectedIndex() - 1; if (AttributeVisualizationPanel.this.m_as != null) { AttributeVisualizationPanel.this.setAttribute(AttributeVisualizationPanel.this.m_attribIndex); } } } }); if (showColouringOption) { // m_colorAttrib.setVisible(false); this.add(this.m_colorAttrib); this.validate(); } } /** * Sets the instances for use * * @param newins a set of Instances */ public void setInstances(final Instances newins) { this.m_attribIndex = 0; this.m_as = null; this.m_data = new Instances(newins); if (this.m_colorAttrib != null) { this.m_colorAttrib.removeAllItems(); this.m_colorAttrib.addItem("No class"); for (int i = 0; i < this.m_data.numAttributes(); i++) { String type = "(" + Attribute.typeToStringShort(this.m_data.attribute(i)) + ")"; this.m_colorAttrib.addItem(new String("Class: " + this.m_data.attribute(i).name() + " " + type)); } if (this.m_data.classIndex() >= 0) { this.m_colorAttrib.setSelectedIndex(this.m_data.classIndex() + 1); } else { this.m_colorAttrib.setSelectedIndex(this.m_data.numAttributes()); } // if (m_data.classIndex() >= 0) { // m_colorAttrib.setSelectedIndex(m_data.classIndex()); // } } if (this.m_data.classIndex() >= 0) { this.m_classIndex = this.m_data.classIndex(); } else { this.m_classIndex = this.m_data.numAttributes() - 1; } this.m_asCache = new AttributeStats[this.m_data.numAttributes()]; } /** * Returns the class selection combo box if the parent component wants to * place it in itself or in some component other than this component. */ public JComboBox getColorBox() { return this.m_colorAttrib; } /** * Get the coloring (class) index for the plot * * @return an <code>int</code> value */ public int getColoringIndex() { return this.m_classIndex; // m_colorAttrib.getSelectedIndex(); } /** * Set the coloring (class) index for the plot * * @param ci an <code>int</code> value */ public void setColoringIndex(final int ci) { this.m_classIndex = ci; if (this.m_colorAttrib != null) { this.m_colorAttrib.setSelectedIndex(ci + 1); } else { this.setAttribute(this.m_attribIndex); } } /** * Tells the panel which attribute to visualize. * * @param index The index of the attribute */ public void setAttribute(final int index) { synchronized (this.m_locker) { // m_threadRun = true; this.m_threadRun = false; this.m_doneCurrentAttribute = false; this.m_displayCurrentAttribute = true; // if(m_hc!=null && m_hc.isAlive()) m_hc.stop(); this.m_attribIndex = index; if (this.m_asCache[index] != null) { this.m_as = this.m_asCache[index]; } else { try { this.m_asCache[index] = this.m_data.attributeStats(index); } catch (InterruptedException e) { throw new IllegalStateException(e); } this.m_as = this.m_asCache[index]; } // m_as = m_data.attributeStats(m_attribIndex); // m_classIndex = m_colorAttrib.getSelectedIndex(); } this.repaint(); // calcGraph(); } /** * Recalculates the barplot or histogram to display, required usually when the * attribute is changed or the component is resized. */ public void calcGraph(final int panelWidth, final int panelHeight) { synchronized (this.m_locker) { this.m_threadRun = true; if (this.m_as.nominalWeights != null) { this.m_hc = new BarCalc(panelWidth, panelHeight); this.m_hc.setPriority(Thread.MIN_PRIORITY); this.m_hc.start(); } else if (this.m_as.numericStats != null) { this.m_hc = new HistCalc(); this.m_hc.setPriority(Thread.MIN_PRIORITY); this.m_hc.start(); } else { this.m_histBarCounts = null; this.m_histBarClassCounts = null; this.m_doneCurrentAttribute = true; this.m_threadRun = false; this.repaint(); } } } /** * Internal class that calculates the barplot to display, in a separate * thread. In particular it initializes some of the crucial internal fields * required by paintComponent() to display the histogram for the current * attribute. These include: m_histBarCounts or m_histBarClassCounts, * m_maxValue and m_colorList. */ private class BarCalc extends Thread { private final int m_panelWidth; public BarCalc(final int panelWidth, final int panelHeight) { this.m_panelWidth = panelWidth; } @Override public void run() { synchronized (AttributeVisualizationPanel.this.m_locker) { // there is no use doing/displaying anything if the resolution // of the panel is less than the number of values for this attribute if (AttributeVisualizationPanel.this.m_data.attribute(AttributeVisualizationPanel.this.m_attribIndex).numValues() > this.m_panelWidth) { AttributeVisualizationPanel.this.m_histBarClassCounts = null; AttributeVisualizationPanel.this.m_threadRun = false; AttributeVisualizationPanel.this.m_doneCurrentAttribute = true; AttributeVisualizationPanel.this.m_displayCurrentAttribute = false; AttributeVisualizationPanel.this.repaint(); return; } if ((AttributeVisualizationPanel.this.m_classIndex >= 0) && (AttributeVisualizationPanel.this.m_data.attribute(AttributeVisualizationPanel.this.m_classIndex).isNominal())) { SparseInstance histClassCounts[]; histClassCounts = new SparseInstance[AttributeVisualizationPanel.this.m_data.attribute(AttributeVisualizationPanel.this.m_attribIndex).numValues()]; // [m_data.attribute(m_classIndex).numValues()+1]; if (AttributeVisualizationPanel.this.m_as.nominalWeights.length > 0) { AttributeVisualizationPanel.this.m_maxValue = AttributeVisualizationPanel.this.m_as.nominalWeights[0]; for (int i = 0; i < AttributeVisualizationPanel.this.m_data.attribute(AttributeVisualizationPanel.this.m_attribIndex).numValues(); i++) { if (AttributeVisualizationPanel.this.m_as.nominalWeights[i] > AttributeVisualizationPanel.this.m_maxValue) { AttributeVisualizationPanel.this.m_maxValue = AttributeVisualizationPanel.this.m_as.nominalWeights[i]; } } } else { AttributeVisualizationPanel.this.m_maxValue = 0; } if (AttributeVisualizationPanel.this.m_colorList.size() == 0) { AttributeVisualizationPanel.this.m_colorList.add(Color.black); } for (int i = AttributeVisualizationPanel.this.m_colorList.size(); i < AttributeVisualizationPanel.this.m_data.attribute(AttributeVisualizationPanel.this.m_classIndex).numValues() + 1; i++) { Color pc = m_defaultColors[(i - 1) % 10]; int ija = (i - 1) / 10; ija *= 2; for (int j = 0; j < ija; j++) { pc = pc.darker(); } AttributeVisualizationPanel.this.m_colorList.add(pc); } // first sort data on attribute values try { AttributeVisualizationPanel.this.m_data.sort(AttributeVisualizationPanel.this.m_attribIndex); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } double[] tempClassCounts = null; int tempAttValueIndex = -1; for (int k = 0; k < AttributeVisualizationPanel.this.m_data.numInstances(); k++) { // System.out.println("attrib: "+ // m_data.instance(k).value(m_attribIndex)+ // " class: "+ // m_data.instance(k).value(m_classIndex)); if (!AttributeVisualizationPanel.this.m_data.instance(k).isMissing(AttributeVisualizationPanel.this.m_attribIndex)) { // check to see if we need to allocate some space here if (AttributeVisualizationPanel.this.m_data.instance(k).value(AttributeVisualizationPanel.this.m_attribIndex) != tempAttValueIndex) { if (tempClassCounts != null) { // set up the sparse instance for the previous bar (if any) int numNonZero = 0; for (double tempClassCount : tempClassCounts) { if (tempClassCount > 0) { numNonZero++; } } double[] nonZeroVals = new double[numNonZero]; int[] nonZeroIndices = new int[numNonZero]; int count = 0; for (int z = 0; z < tempClassCounts.length; z++) { if (tempClassCounts[z] > 0) { nonZeroVals[count] = tempClassCounts[z]; nonZeroIndices[count++] = z; } } SparseInstance tempS = new SparseInstance(1.0, nonZeroVals, nonZeroIndices, tempClassCounts.length); histClassCounts[tempAttValueIndex] = tempS; } tempClassCounts = new double[AttributeVisualizationPanel.this.m_data.attribute(AttributeVisualizationPanel.this.m_classIndex).numValues() + 1]; tempAttValueIndex = (int) AttributeVisualizationPanel.this.m_data.instance(k).value(AttributeVisualizationPanel.this.m_attribIndex); /* * histClassCounts[(int)m_data.instance(k).value(m_attribIndex)] * = new double[m_data.attribute(m_classIndex).numValues()+1]; */ } if (AttributeVisualizationPanel.this.m_data.instance(k).isMissing(AttributeVisualizationPanel.this.m_classIndex)) { /* * histClassCounts[(int)m_data.instance(k).value(m_attribIndex)] * [0] += m_data.instance(k).weight(); */ tempClassCounts[0] += AttributeVisualizationPanel.this.m_data.instance(k).weight(); } else { tempClassCounts[(int) AttributeVisualizationPanel.this.m_data.instance(k).value(AttributeVisualizationPanel.this.m_classIndex) + 1] += AttributeVisualizationPanel.this.m_data.instance(k).weight(); /* * histClassCounts[(int)m_data.instance(k).value(m_attribIndex)] * [(int)m_data.instance(k).value(m_classIndex)+1] += * m_data.instance(k).weight(); */ } } } // set up sparse instance for last bar? if (tempClassCounts != null) { // set up the sparse instance for the previous bar (if any) int numNonZero = 0; for (double tempClassCount : tempClassCounts) { if (tempClassCount > 0) { numNonZero++; } } double[] nonZeroVals = new double[numNonZero]; int[] nonZeroIndices = new int[numNonZero]; int count = 0; for (int z = 0; z < tempClassCounts.length; z++) { if (tempClassCounts[z] > 0) { nonZeroVals[count] = tempClassCounts[z]; nonZeroIndices[count++] = z; } } SparseInstance tempS = new SparseInstance(1.0, nonZeroVals, nonZeroIndices, tempClassCounts.length); histClassCounts[tempAttValueIndex] = tempS; } // for(int i=0; i<histClassCounts.length; i++) { // int sum=0; // for(int j=0; j<histClassCounts[i].length; j++) { // sum = sum+histClassCounts[i][j]; // } // System.out.println("histCount: "+sum+" Actual: "+ // m_as.nominalWeights[i]); // } AttributeVisualizationPanel.this.m_threadRun = false; AttributeVisualizationPanel.this.m_doneCurrentAttribute = true; AttributeVisualizationPanel.this.m_displayCurrentAttribute = true; AttributeVisualizationPanel.this.m_histBarClassCounts = histClassCounts; // Image tmpImg = new BufferedImage(getWidth(), getHeight(), // BufferedImage.TYPE_INT_RGB); // drawGraph( tmpImg.getGraphics() ); // img = tmpImg; AttributeVisualizationPanel.this.repaint(); } else { double histCounts[]; histCounts = new double[AttributeVisualizationPanel.this.m_data.attribute(AttributeVisualizationPanel.this.m_attribIndex).numValues()]; if (AttributeVisualizationPanel.this.m_as.nominalWeights.length > 0) { AttributeVisualizationPanel.this.m_maxValue = AttributeVisualizationPanel.this.m_as.nominalWeights[0]; for (int i = 0; i < AttributeVisualizationPanel.this.m_data.attribute(AttributeVisualizationPanel.this.m_attribIndex).numValues(); i++) { if (AttributeVisualizationPanel.this.m_as.nominalWeights[i] > AttributeVisualizationPanel.this.m_maxValue) { AttributeVisualizationPanel.this.m_maxValue = AttributeVisualizationPanel.this.m_as.nominalWeights[i]; } } } else { AttributeVisualizationPanel.this.m_maxValue = 0; } for (int k = 0; k < AttributeVisualizationPanel.this.m_data.numInstances(); k++) { if (!AttributeVisualizationPanel.this.m_data.instance(k).isMissing(AttributeVisualizationPanel.this.m_attribIndex)) { histCounts[(int) AttributeVisualizationPanel.this.m_data.instance(k).value(AttributeVisualizationPanel.this.m_attribIndex)] += AttributeVisualizationPanel.this.m_data.instance(k).weight(); } } AttributeVisualizationPanel.this.m_threadRun = false; AttributeVisualizationPanel.this.m_displayCurrentAttribute = true; AttributeVisualizationPanel.this.m_doneCurrentAttribute = true; AttributeVisualizationPanel.this.m_histBarCounts = histCounts; // Image tmpImg = new BufferedImage(getWidth(), getHeight(), // BufferedImage.TYPE_INT_RGB); // drawGraph( tmpImg.getGraphics() ); // img = tmpImg; AttributeVisualizationPanel.this.repaint(); } } // end synchronized } // end run() } /** * Internal class that calculates the histogram to display, in a separate * thread. In particular it initializes some of the crucial internal fields * required by paintComponent() to display the histogram for the current * attribute. These include: m_histBarCounts or m_histBarClassCounts, * m_maxValue and m_colorList. */ private class HistCalc extends Thread { @Override public void run() { synchronized (AttributeVisualizationPanel.this.m_locker) { if ((AttributeVisualizationPanel.this.m_classIndex >= 0) && (AttributeVisualizationPanel.this.m_data.attribute(AttributeVisualizationPanel.this.m_classIndex).isNominal())) { int intervals; double intervalWidth = 0.0; // This uses the M.P.Wand's method to calculate the histogram's // interval width. See "Data-Based Choice of Histogram Bin Width", in // The American Statistician, Vol. 51, No. 1, Feb., 1997, pp. 59-64. // intervalWidth = Math.pow(6D/( -psi(2, // g21())*m_data.numInstances()), // 1/3D ); // This uses the Scott's method to calculate the histogram's interval // width. See "On optimal and data-based histograms". // See Biometrika, 66, 605-610 OR see the same paper mentioned above. intervalWidth = 3.49 * AttributeVisualizationPanel.this.m_as.numericStats.stdDev * Math.pow(AttributeVisualizationPanel.this.m_data.numInstances(), -1 / 3D); // The Math.max is introduced to remove the possibility of // intervals=0 and =NAN that can happen if respectively all the // numeric // values are the same or the interval width is evaluated to zero. intervals = Math.max(1, (int) Math.round((AttributeVisualizationPanel.this.m_as.numericStats.max - AttributeVisualizationPanel.this.m_as.numericStats.min) / intervalWidth)); // System.out.println("Max: "+m_as.numericStats.max+ // " Min: "+m_as.numericStats.min+ // " stdDev: "+m_as.numericStats.stdDev+ // "intervalWidth: "+intervalWidth); // The number 4 below actually represents a padding of 3 pixels on // each side of the histogram, and is also reflected in other parts of // the code in the shape of numerical constants like "6" here. if (intervals > AttributeVisualizationPanel.this.getWidth()) { intervals = AttributeVisualizationPanel.this.getWidth() - 6; if (intervals < 1) { intervals = 1; } } double histClassCounts[][] = new double[intervals][AttributeVisualizationPanel.this.m_data.attribute(AttributeVisualizationPanel.this.m_classIndex).numValues() + 1]; double barRange = (AttributeVisualizationPanel.this.m_as.numericStats.max - AttributeVisualizationPanel.this.m_as.numericStats.min) / histClassCounts.length; AttributeVisualizationPanel.this.m_maxValue = 0; if (AttributeVisualizationPanel.this.m_colorList.size() == 0) { AttributeVisualizationPanel.this.m_colorList.add(Color.black); } for (int i = AttributeVisualizationPanel.this.m_colorList.size(); i < AttributeVisualizationPanel.this.m_data.attribute(AttributeVisualizationPanel.this.m_classIndex).numValues() + 1; i++) { Color pc = m_defaultColors[(i - 1) % 10]; int ija = (i - 1) / 10; ija *= 2; for (int j = 0; j < ija; j++) { pc = pc.darker(); } AttributeVisualizationPanel.this.m_colorList.add(pc); } for (int k = 0; k < AttributeVisualizationPanel.this.m_data.numInstances(); k++) { int t = 0; // This holds the interval that the attibute value of the // new instance belongs to. try { if (!AttributeVisualizationPanel.this.m_data.instance(k).isMissing(AttributeVisualizationPanel.this.m_attribIndex)) { // 1. see footnote at the end of this file t = (int) Math.ceil((float) ((AttributeVisualizationPanel.this.m_data.instance(k).value(AttributeVisualizationPanel.this.m_attribIndex) - AttributeVisualizationPanel.this.m_as.numericStats.min) / barRange)); if (t == 0) { if (AttributeVisualizationPanel.this.m_data.instance(k).isMissing(AttributeVisualizationPanel.this.m_classIndex)) { histClassCounts[t][0] += AttributeVisualizationPanel.this.m_data.instance(k).weight(); } else { histClassCounts[t][(int) AttributeVisualizationPanel.this.m_data.instance(k).value(AttributeVisualizationPanel.this.m_classIndex) + 1] += AttributeVisualizationPanel.this.m_data.instance(k).weight(); // if(histCounts[t]>m_maxValue) // m_maxValue = histCounts[t]; } } else { if (AttributeVisualizationPanel.this.m_data.instance(k).isMissing(AttributeVisualizationPanel.this.m_classIndex)) { histClassCounts[t - 1][0] += AttributeVisualizationPanel.this.m_data.instance(k).weight(); } else { histClassCounts[t - 1][(int) AttributeVisualizationPanel.this.m_data.instance(k).value(AttributeVisualizationPanel.this.m_classIndex) + 1] += AttributeVisualizationPanel.this.m_data.instance(k) .weight(); // if(histCounts[t-1]>m_maxValue) // m_maxValue = histCounts[t-1]; } } } } catch (ArrayIndexOutOfBoundsException ae) { System.out.println("t:" + (t) + " barRange:" + barRange + " histLength:" + histClassCounts.length + " value:" + AttributeVisualizationPanel.this.m_data.instance(k).value(AttributeVisualizationPanel.this.m_attribIndex) + " min:" + AttributeVisualizationPanel.this.m_as.numericStats.min + " sumResult:" + (AttributeVisualizationPanel.this.m_data.instance(k).value(AttributeVisualizationPanel.this.m_attribIndex) - AttributeVisualizationPanel.this.m_as.numericStats.min) + " divideResult:" + (float) ((AttributeVisualizationPanel.this.m_data.instance(k).value(AttributeVisualizationPanel.this.m_attribIndex) - AttributeVisualizationPanel.this.m_as.numericStats.min) / barRange) + " finalResult:" + Math.ceil((float) ((AttributeVisualizationPanel.this.m_data.instance(k).value(AttributeVisualizationPanel.this.m_attribIndex) - AttributeVisualizationPanel.this.m_as.numericStats.min) / barRange))); } } for (double[] histClassCount : histClassCounts) { double sum = 0; for (double element : histClassCount) { sum = sum + element; } if (AttributeVisualizationPanel.this.m_maxValue < sum) { AttributeVisualizationPanel.this.m_maxValue = sum; } } // convert to sparse instances SparseInstance[] histClassCountsSparse = new SparseInstance[histClassCounts.length]; for (int i = 0; i < histClassCounts.length; i++) { int numSparseValues = 0; for (int j = 0; j < histClassCounts[i].length; j++) { if (histClassCounts[i][j] > 0) { numSparseValues++; } } double[] sparseValues = new double[numSparseValues]; int[] sparseIndices = new int[numSparseValues]; int count = 0; for (int j = 0; j < histClassCounts[i].length; j++) { if (histClassCounts[i][j] > 0) { sparseValues[count] = histClassCounts[i][j]; sparseIndices[count++] = j; } } SparseInstance tempS = new SparseInstance(1.0, sparseValues, sparseIndices, histClassCounts[i].length); histClassCountsSparse[i] = tempS; } AttributeVisualizationPanel.this.m_histBarClassCounts = histClassCountsSparse; AttributeVisualizationPanel.this.m_barRange = barRange; } else { // else if the class attribute is numeric or the class is not // set int intervals; double intervalWidth; // At the time of this coding the // possibility of datasets with zero instances // was being dealt with in the // PreProcessPanel of weka Explorer. // old method of calculating number of intervals // intervals = m_as.totalCount>10 ? // (int)(m_as.totalCount*0.1):(int)m_as.totalCount; // This uses the M.P.Wand's method to calculate the histogram's // interval width. See "Data-Based Choice of Histogram Bin Width", in // The American Statistician, Vol. 51, No. 1, Feb., 1997, pp. 59-64. // intervalWidth = Math.pow(6D/(-psi(2, g21())*m_data.numInstances() // ), // 1/3D ); // This uses the Scott's method to calculate the histogram's interval // width. See "On optimal and data-based histograms". // See Biometrika, 66, 605-610 OR see the same paper mentioned above. intervalWidth = 3.49 * AttributeVisualizationPanel.this.m_as.numericStats.stdDev * Math.pow(AttributeVisualizationPanel.this.m_data.numInstances(), -1 / 3D); // The Math.max is introduced to remove the possibility of // intervals=0 and =NAN that can happen if respectively all the // numeric // values are the same or the interval width is evaluated to zero. intervals = Math.max(1, (int) Math.round((AttributeVisualizationPanel.this.m_as.numericStats.max - AttributeVisualizationPanel.this.m_as.numericStats.min) / intervalWidth)); // The number 4 below actually represents a padding of 3 pixels on // each side of the histogram, and is also reflected in other parts of // the code in the shape of numerical constants like "6" here. if (intervals > AttributeVisualizationPanel.this.getWidth()) { intervals = AttributeVisualizationPanel.this.getWidth() - 6; if (intervals < 1) { intervals = 1; } } double[] histCounts = new double[intervals]; double barRange = (AttributeVisualizationPanel.this.m_as.numericStats.max - AttributeVisualizationPanel.this.m_as.numericStats.min) / histCounts.length; AttributeVisualizationPanel.this.m_maxValue = 0; for (int k = 0; k < AttributeVisualizationPanel.this.m_data.numInstances(); k++) { int t = 0; // This holds the interval to which the current // attribute's // value of this particular instance k belongs to. if (AttributeVisualizationPanel.this.m_data.instance(k).isMissing(AttributeVisualizationPanel.this.m_attribIndex)) { continue; // ignore missing values } try { // 1. see footnote at the end of this file t = (int) Math.ceil((float) ((AttributeVisualizationPanel.this.m_data.instance(k).value(AttributeVisualizationPanel.this.m_attribIndex) - AttributeVisualizationPanel.this.m_as.numericStats.min) / barRange)); if (t == 0) { histCounts[t] += AttributeVisualizationPanel.this.m_data.instance(k).weight(); if (histCounts[t] > AttributeVisualizationPanel.this.m_maxValue) { AttributeVisualizationPanel.this.m_maxValue = histCounts[t]; } } else { histCounts[t - 1] += AttributeVisualizationPanel.this.m_data.instance(k).weight(); if (histCounts[t - 1] > AttributeVisualizationPanel.this.m_maxValue) { AttributeVisualizationPanel.this.m_maxValue = histCounts[t - 1]; } } } catch (ArrayIndexOutOfBoundsException ae) { ae.printStackTrace(); System.out.println("t:" + (t) + " barRange:" + barRange + " histLength:" + histCounts.length + " value:" + AttributeVisualizationPanel.this.m_data.instance(k).value(AttributeVisualizationPanel.this.m_attribIndex) + " min:" + AttributeVisualizationPanel.this.m_as.numericStats.min + " sumResult:" + (AttributeVisualizationPanel.this.m_data.instance(k).value(AttributeVisualizationPanel.this.m_attribIndex) - AttributeVisualizationPanel.this.m_as.numericStats.min) + " divideResult:" + (float) ((AttributeVisualizationPanel.this.m_data.instance(k).value(AttributeVisualizationPanel.this.m_attribIndex) - AttributeVisualizationPanel.this.m_as.numericStats.min) / barRange) + " finalResult:" + Math.ceil((float) ((AttributeVisualizationPanel.this.m_data.instance(k).value(AttributeVisualizationPanel.this.m_attribIndex) - AttributeVisualizationPanel.this.m_as.numericStats.min) / barRange))); } } AttributeVisualizationPanel.this.m_histBarCounts = histCounts; AttributeVisualizationPanel.this.m_barRange = barRange; } AttributeVisualizationPanel.this.m_threadRun = false; AttributeVisualizationPanel.this.m_displayCurrentAttribute = true; AttributeVisualizationPanel.this.m_doneCurrentAttribute = true; // Image tmpImg = new BufferedImage(getWidth(), getHeight(), // BufferedImage.TYPE_INT_RGB); // drawGraph( tmpImg.getGraphics() ); // img = tmpImg; AttributeVisualizationPanel.this.repaint(); } } /**** * Code for M.P.Wand's method of histogram bin width selection. There is * some problem with it. It always comes up -ve value which is raised to the * power 1/3 and gives an NAN. private static final int M=400; private * double psi(int r, double g) { double val; * * double sum=0.0; for(int i=0; i<M; i++) { double valCjKj=0.0; for(int j=0; * j<M; j++) { valCjKj += c(j) * k(r, j-i, g); } sum += valCjKj*c(i); } * * val = Math.pow(m_data.numInstances(), -2) * sum; * //System.out.println("psi returns: "+val); return val; } private double * g21() { double val; * * val = Math.pow(2 / ( Math.sqrt(2D*Math.PI)*psi(4, g22()) * * m_data.numInstances() ), 1/5D) * Math.sqrt(2) * m_as.numericStats.stdDev; * //System.out.println("g21 returns: "+val); return val; } private double * g22() { double val; * * val = Math.pow( 2D/(5*m_data.numInstances()), 1/7D) * Math.sqrt(2) * * m_as.numericStats.stdDev; //System.out.println("g22 returns: "+val); * return val; } private double c(int j) { double val=0.0; double sigma = * (m_as.numericStats.max - m_as.numericStats.min)/(M-1); * * //System.out.println("In c before doing the sum we have"); * //System.out.println("max: " +m_as.numericStats.max+" min: "+ // * m_as.numericStats.min+" sigma: "+sigma); * * for(int i=0; i<m_data.numInstances(); i++) { * if(!m_data.instance(i).isMissing(m_attribIndex)) val += Math.max( 0, ( 1 * - Math.abs( Math.pow(sigma, -1)*(m_data.instance(i).value(m_attribIndex) * - j) ) ) ); } //System.out.println("c returns: "+val); return val; } * private double k(int r, int j, double g) { double val; double sigma = * (m_as.numericStats.max - m_as.numericStats.min)/(M-1); * //System.out.println("Before calling L we have"); * //System.out.println("Max: " * +m_as.numericStats.max+" Min: "+m_as.numericStats.min+"\n"+ // * "r: "+r+" j: "+j+" g: "+g); val = Math.pow( g, -r-1) * L(sigma*j/g); * //System.out.println("k returns: "+val); return val; } private double * L(double x) { double val; * * val = Math.pow( 2*Math.PI, -1/2D ) * Math.exp( -(x*x)/2D ); * //System.out.println("L returns: "+val); return val; } End of Wand's * method */ } /** * Returns "&lt;nominal value&gt; [&lt;nominal value count&gt;]" if displaying * a bar plot and mouse is on some bar. If displaying histogram then it <li> * returns "count &lt;br&gt; [&lt;bars Range&gt;]" if mouse is on the first * bar.</li> <li>returns "count &lt;br&gt; (&lt;bar's Range&gt;]" if mouse is * on some bar other than the first one.</li> Otherwise it returns "" * * @param ev The mouse event */ @Override public String getToolTipText(final MouseEvent ev) { if (this.m_as != null && this.m_as.nominalWeights != null) { // if current attrib is // nominal float intervalWidth = this.getWidth() / (float) this.m_as.nominalWeights.length; double heightRatio; int barWidth, x = 0; // if intervalWidth is at least six then bar width is 80% of intervalwidth if (intervalWidth > 5) { barWidth = (int) Math.floor(intervalWidth * 0.8F); } else { barWidth = 1; // Otherwise barwidth is 1 & padding would be at least 1. } // initializing x to maximum of 1 or 10% of interval width (i.e. half of // the padding which is 20% of interval width, as there is 10% on each // side of the bar) so that it points to the start of the 1st bar x = x + (int) ((Math.floor(intervalWidth * 0.1F)) < 1 ? 1 : (Math.floor(intervalWidth * 0.1F))); // Adding to x the appropriate value so that it points to the 1st bar of // our "centered" barplot. If subtracting barplots width from panel width // gives <=2 then the barplot is not centered. if (this.getWidth() - (this.m_as.nominalWeights.length * barWidth + (int) ((Math.floor(intervalWidth * 0.2F)) < 1 ? 1 : (Math.floor(intervalWidth * 0.2F))) * this.m_as.nominalWeights.length) > 2) { // The following amounts to adding to x the half of the area left after // subtracting from the components width the width of the whole barplot // (i.e. width of all the bars plus the width of all the bar paddings, // thereby equaling to the whole barplot), since our barplot is // centered. x += (this.getWidth() - (this.m_as.nominalWeights.length * barWidth + (int) ((Math.floor(intervalWidth * 0.2F)) < 1 ? 1 : (Math.floor(intervalWidth * 0.2F))) * this.m_as.nominalWeights.length)) / 2; } for (int i = 0; i < this.m_as.nominalWeights.length; i++) { heightRatio = (this.getHeight() - (double) this.m_fm.getHeight()) / this.m_maxValue; // if our mouse is on a bar then return the count of this bar in our // barplot if (ev.getX() >= x && ev.getX() <= x + barWidth && ev.getY() >= this.getHeight() - Math.round(this.m_as.nominalWeights[i] * heightRatio)) { return (this.m_data.attribute(this.m_attribIndex).value(i) + " [" + Utils.doubleToString(this.m_as.nominalWeights[i], 3) + "]"); } // otherwise advance x to next bar and check that. Add barwidth to x // and padding which is max(1, 20% of interval width) x = x + barWidth + (int) ((Math.floor(intervalWidth * 0.2F)) < 1 ? 1 : (Math.floor(intervalWidth * 0.2F))); } } else if (this.m_threadRun == false && // if attrib is numeric (this.m_histBarCounts != null || this.m_histBarClassCounts != null)) { int x = 0, barWidth; double bar = this.m_as.numericStats.min; // if the class attribute is set and it is nominal if ((this.m_classIndex >= 0) && (this.m_data.attribute(this.m_classIndex).isNominal())) { // there is 3 pixels of padding on each side of the histogram // the barwidth is 1 if after removing the padding its width is less // then the displayable width barWidth = ((this.getWidth() - 6) / this.m_histBarClassCounts.length) < 1 ? 1 : ((this.getWidth() - 6) / this.m_histBarClassCounts.length); // initializing x to 3 adding appropriate value to make it point to the // start of the 1st bar of our "centered" histogram. x = 3; if ((this.getWidth() - (x + this.m_histBarClassCounts.length * barWidth)) > 5) { x += (this.getWidth() - (x + this.m_histBarClassCounts.length * barWidth)) / 2; } if (ev.getX() - x >= 0) { // The temp holds the index of the current interval that we are // looking // at int temp = (int) ((ev.getX() - x) / (barWidth + 0.0000000001)); if (temp == 0) { // handle the special case temp==0. see footnote 1 double sum = 0; for (int k = 0; k < this.m_histBarClassCounts[0].numValues(); k++) { sum += this.m_histBarClassCounts[0].valueSparse(k); } // return the count of the interval mouse is pointing to plus // the range of values that fall into this interval return ("<html><center><font face=Dialog size=-1>" + Utils.doubleToString(sum, 3) + "<br>" + "[" + Utils.doubleToString(bar + this.m_barRange * temp, 3) + ", " + Utils.doubleToString((bar + this.m_barRange * (temp + 1)), 3) + "]" + "</font></center></html>"); } else if (temp < this.m_histBarClassCounts.length) { // handle case // temp!=0 double sum = 0; for (int k = 0; k < this.m_histBarClassCounts[temp].numValues(); k++) { sum += this.m_histBarClassCounts[temp].valueSparse(k); } // return the count of the interval mouse is pointing to plus // the range of values that fall into this interval return ("<html><center><font face=Dialog size=-1>" + Utils.doubleToString(sum, 3) + "<br>(" + Utils.doubleToString(bar + this.m_barRange * temp, 3) + ", " + Utils.doubleToString((bar + this.m_barRange * (temp + 1)), 3) + "]</font></center></html>"); } } } else { // else if the class attribute is not set or is numeric barWidth = ((this.getWidth() - 6) / this.m_histBarCounts.length) < 1 ? 1 : ((this.getWidth() - 6) / this.m_histBarCounts.length); // initializing x to 3 adding appropriate value to make it point to the // start of the 1st bar of our "centered" histogram. x = 3; if ((this.getWidth() - (x + this.m_histBarCounts.length * barWidth)) > 5) { x += (this.getWidth() - (x + this.m_histBarCounts.length * barWidth)) / 2; } if (ev.getX() - x >= 0) { // Temp holds the index of the current bar we are looking at. int temp = (int) ((ev.getX() - x) / (barWidth + 0.0000000001)); // return interval count as well as its range if (temp == 0) { return ("<html><center><font face=Dialog size=-1>" + this.m_histBarCounts[0] + "<br>" + "[" + Utils.doubleToString(bar + this.m_barRange * temp, 3) + ", " + Utils.doubleToString((bar + this.m_barRange * (temp + 1)), 3) + "]" + "</font></center></html>"); } else if (temp < this.m_histBarCounts.length) { return ("<html><center><font face=Dialog size=-1>" + this.m_histBarCounts[temp] + "<br>" + "(" + Utils.doubleToString(bar + this.m_barRange * temp, 3) + ", " + Utils.doubleToString((bar + this.m_barRange * (temp + 1)), 3) + "]" + "</font></center></html>"); } } } } return PrintableComponent.getToolTipText(this.m_Printer); } /** * Paints this component * * @param g The graphics object for this component */ @Override public void paintComponent(final Graphics g) { g.setColor(Color.WHITE); g.fillRect(0, 0, this.getWidth(), this.getHeight()); g.setColor(Color.BLACK); if (this.m_as != null) { // If calculations have been done and histogram/barplot if (!this.m_doneCurrentAttribute && !this.m_threadRun) { this.calcGraph(this.getWidth(), this.getHeight()); } if (this.m_threadRun == false && this.m_displayCurrentAttribute) { // calculation // thread is not // running int buttonHeight = 0; if (this.m_colorAttrib != null) { buttonHeight = this.m_colorAttrib.getHeight() + this.m_colorAttrib.getLocation().y; } // if current attribute is nominal then draw barplot. if (this.m_as.nominalWeights != null && (this.m_histBarClassCounts != null || this.m_histBarCounts != null)) { double heightRatio, intervalWidth; int x = 0, y = 0, barWidth; // if the class attribute is set and is nominal then draw coloured // subbars for each bar if ((this.m_classIndex >= 0) && (this.m_data.attribute(this.m_classIndex).isNominal())) { intervalWidth = (this.getWidth() / (float) this.m_histBarClassCounts.length); // Barwidth is 80% of interval width.The remaining 20% is padding, // 10% on each side of the bar. If interval width is less then 5 the // 20% of that value is less than 1, in that case we use bar width // of // 1 and padding of 1 pixel on each side of the bar. if (intervalWidth > 5) { barWidth = (int) Math.floor(intervalWidth * 0.8F); } else { barWidth = 1; } // initializing x to 10% of interval width or to 1 if 10% is <1. // This // is essentially the LHS padding of the 1st bar. x = x + (int) ((Math.floor(intervalWidth * 0.1F)) < 1 ? 1 : (Math.floor(intervalWidth * 0.1F))); // Add appropriate value to x so that it starts at the 1st bar of // a "centered" barplot. if (this.getWidth() - (this.m_histBarClassCounts.length * barWidth + (int) ((Math.floor(intervalWidth * 0.2F)) < 1 ? 1 : (Math.floor(intervalWidth * 0.2F))) * this.m_histBarClassCounts.length) > 2) { // We take the width of all the bars and all the paddings (20% // of interval width), and subtract it from the width of the panel // to get the extra space that would be left after drawing. We // divide that space by 2 to get its mid-point and add that to our // x, thus making the whole bar plot drawn centered in our // component. x += (this.getWidth() - (this.m_histBarClassCounts.length * barWidth + (int) ((Math.floor(intervalWidth * 0.2F)) < 1 ? 1 : (Math.floor(intervalWidth * 0.2F))) * this.m_histBarClassCounts.length)) / 2; } // this holds the count of the bar and will be calculated by adding // up the counts of individual subbars. It is displayed at the top // of each bar. double sum = 0; for (SparseInstance m_histBarClassCount : this.m_histBarClassCounts) { // calculating the proportion of the components height compared to // the maxvalue in our attribute, also taking into account the // height of font to display bars count and the height of the // class // ComboBox. heightRatio = (this.getHeight() - (double) this.m_fm.getHeight() - buttonHeight) / this.m_maxValue; y = this.getHeight(); if (m_histBarClassCount != null) { for (int j = 0; j < m_histBarClassCount.numAttributes(); j++) { sum = sum + m_histBarClassCount.value(j); y = (int) (y - Math.round(m_histBarClassCount.value(j) * heightRatio)); // selecting the colour corresponding to the current class. g.setColor(this.m_colorList.get(j)); g.fillRect(x, y, barWidth, (int) Math.round(m_histBarClassCount.value(j) * heightRatio)); g.setColor(Color.black); } } // drawing the bar count at the top of the bar if it is less than // interval width. draw it 1px up to avoid touching the bar. if (this.m_fm.stringWidth(Utils.doubleToString(sum, 1)) < intervalWidth) { g.drawString(Utils.doubleToString(sum, 1), x, y - 1); } // advancing x to the next bar by adding bar width and padding // of both the bars (i.e. RHS padding of the bar just drawn and // LHS // padding of the new bar). x = x + barWidth + (int) ((Math.floor(intervalWidth * 0.2F)) < 1 ? 1 : (Math.floor(intervalWidth * 0.2F))); // reseting sum for the next bar. sum = 0; } } // else if class attribute is numeric or not set then draw black bars. else { intervalWidth = (this.getWidth() / (float) this.m_histBarCounts.length); // same as in the case of nominal class (see inside of if stmt // corresponding to the current else above). if (intervalWidth > 5) { barWidth = (int) Math.floor(intervalWidth * 0.8F); } else { barWidth = 1; } // same as in the case of nominal class (see inside of if stmt // corresponding to the current else above). x = x + (int) ((Math.floor(intervalWidth * 0.1F)) < 1 ? 1 : (Math.floor(intervalWidth * 0.1F))); // same as in the case of nominal class if (this.getWidth() - (this.m_histBarCounts.length * barWidth + (int) ((Math.floor(intervalWidth * 0.2F)) < 1 ? 1 : (Math.floor(intervalWidth * 0.2F))) * this.m_histBarCounts.length) > 2) { x += (this.getWidth() - (this.m_histBarCounts.length * barWidth + (int) ((Math.floor(intervalWidth * 0.2F)) < 1 ? 1 : (Math.floor(intervalWidth * 0.2F))) * this.m_histBarCounts.length)) / 2; } for (double m_histBarCount : this.m_histBarCounts) { // calculating the proportion of the height of the component // compared to the maxValue in our attribute. heightRatio = (this.getHeight() - (float) this.m_fm.getHeight() - buttonHeight) / this.m_maxValue; y = (int) (this.getHeight() - Math.round(m_histBarCount * heightRatio)); g.fillRect(x, y, barWidth, (int) Math.round(m_histBarCount * heightRatio)); // draw the bar count if it's width is smaller than intervalWidth. // draw it 1px above to avoid touching the bar. if (this.m_fm.stringWidth(Utils.doubleToString(m_histBarCount, 1)) < intervalWidth) { g.drawString(Utils.doubleToString(m_histBarCount, 1), x, y - 1); } // Advance x to the next bar by adding bar-width and padding // of the bars (RHS padding of current bar & LHS padding of next // bar). x = x + barWidth + (int) ((Math.floor(intervalWidth * 0.2F)) < 1 ? 1 : (Math.floor(intervalWidth * 0.2F))); } } } // <--end if m_as.nominalCount!=null // if the current attribute is numeric then draw a histogram. else if (this.m_as.numericStats != null && (this.m_histBarClassCounts != null || this.m_histBarCounts != null)) { double heightRatio; int x = 0, y = 0, barWidth; // If the class attribute is set and is not numeric then draw coloured // subbars for the histogram bars if ((this.m_classIndex >= 0) && (this.m_data.attribute(this.m_classIndex).isNominal())) { // There is a padding of 3px on each side of the histogram. barWidth = ((this.getWidth() - 6) / this.m_histBarClassCounts.length) < 1 ? 1 : ((this.getWidth() - 6) / this.m_histBarClassCounts.length); // initializing x to start at the start of the 1st bar after // padding. x = 3; // Adding appropriate value to x to account for a "centered" // histogram if ((this.getWidth() - (x + this.m_histBarClassCounts.length * barWidth)) > 5) { // We take the current value of x (histogram's RHS padding) and // add // the barWidths of all the bars to it to us the size of // our histogram. We subtract that from the width of the panel // giving us the extra space that would be left if the histogram // is // drawn and divide that by 2 to get the midpoint of that extra // space. That space is then added to our x, hence making the // histogram centered. x += (this.getWidth() - (x + this.m_histBarClassCounts.length * barWidth)) / 2; } for (SparseInstance m_histBarClassCount : this.m_histBarClassCounts) { if (m_histBarClassCount != null) { // Calculating height ratio. Leave space of 19 for an axis line // at // the bottom heightRatio = (this.getHeight() - (float) this.m_fm.getHeight() - buttonHeight - 19) / this.m_maxValue; y = this.getHeight() - 19; // This would hold the count of the bar (sum of sub-bars). double sum = 0; for (int j = 0; j < m_histBarClassCount.numValues(); j++) { y = (int) (y - Math.round(m_histBarClassCount.valueSparse(j) * heightRatio)); // System.out.println("Filling x:"+x+" y:"+y+" width:"+barWidth+ // " height:"+ // (m_histBarClassCounts[i][j]*heightRatio)); // selecting the color corresponding to our class g.setColor(this.m_colorList.get(m_histBarClassCount.index(j))); // drawing the bar if its width is greater than 1 if (barWidth > 1) { g.fillRect(x, y, barWidth, (int) Math.round(m_histBarClassCount.valueSparse(j) * heightRatio)); } else if ((m_histBarClassCount.valueSparse(j) * heightRatio) > 0) { g.drawLine(x, y, x, (int) (y + Math.round(m_histBarClassCount.valueSparse(j) * heightRatio))); } g.setColor(Color.black); sum = sum + m_histBarClassCount.valueSparse(j); } // Drawing bar count on the top of the bar if it is < barWidth if (this.m_fm.stringWidth(" " + Utils.doubleToString(sum, 1)) < barWidth) { g.drawString(" " + Utils.doubleToString(sum, 1), x, y - 1); } // Moving x to the next bar x = x + barWidth; } } // Now drawing the axis line at the bottom of the histogram // initializing x again to the start of the plot x = 3; if ((this.getWidth() - (x + this.m_histBarClassCounts.length * barWidth)) > 5) { x += (this.getWidth() - (x + this.m_histBarClassCounts.length * barWidth)) / 2; } g.drawLine(x, this.getHeight() - 17, (barWidth == 1) ? x + barWidth * this.m_histBarClassCounts.length - 1 : x + barWidth * this.m_histBarClassCounts.length, this.getHeight() - 17); // axis // line -- // see // footnote // 2. g.drawLine(x, this.getHeight() - 16, x, this.getHeight() - 12); // minimum // line g.drawString(Utils.doubleToString(this.m_as.numericStats.min, 2), x, this.getHeight() - 12 + this.m_fm.getHeight()); // minimum value g.drawLine(x + (barWidth * this.m_histBarClassCounts.length) / 2, this.getHeight() - 16, x + (barWidth * this.m_histBarClassCounts.length) / 2, this.getHeight() - 12); // median line // Drawing median value. X position for drawing the value is: from // start of the plot take the mid point and subtract from it half // of the width of the value to draw. g.drawString(Utils.doubleToString(this.m_as.numericStats.max / 2 + this.m_as.numericStats.min / 2, 2), x + (barWidth * this.m_histBarClassCounts.length) / 2 - this.m_fm.stringWidth(Utils.doubleToString(this.m_as.numericStats.max / 2 + this.m_as.numericStats.min / 2, 2)) / 2, this.getHeight() - 12 + this.m_fm.getHeight()); // median value g.drawLine((barWidth == 1) ? x + barWidth * this.m_histBarClassCounts.length - 1 : x + barWidth * this.m_histBarClassCounts.length, this.getHeight() - 16, (barWidth == 1) ? x + barWidth * this.m_histBarClassCounts.length - 1 : x + barWidth * this.m_histBarClassCounts.length, this.getHeight() - 12); // maximum line g.drawString(Utils.doubleToString(this.m_as.numericStats.max, 2), (barWidth == 1) ? x + barWidth * this.m_histBarClassCounts.length - this.m_fm.stringWidth(Utils.doubleToString(this.m_as.numericStats.max, 2)) - 1 : x + barWidth * this.m_histBarClassCounts.length - this.m_fm.stringWidth(Utils.doubleToString(this.m_as.numericStats.max, 2)), this.getHeight() - 12 + this.m_fm.getHeight()); // maximum // value -- // see 2. } else { // if class attribute is numeric // There is a padding of 3px on each side of the histogram. barWidth = ((this.getWidth() - 6) / this.m_histBarCounts.length) < 1 ? 1 : ((this.getWidth() - 6) / this.m_histBarCounts.length); // Same as above. Pls inside of the if stmt. x = 3; if ((this.getWidth() - (x + this.m_histBarCounts.length * barWidth)) > 5) { x += (this.getWidth() - (x + this.m_histBarCounts.length * barWidth)) / 2; } // Same as above for (double m_histBarCount : this.m_histBarCounts) { // calculating the ration of the component's height compared to // the maxValue in our current attribute. Leaving 19 pixels to // draw the axis at the bottom of the histogram. heightRatio = (this.getHeight() - (float) this.m_fm.getHeight() - buttonHeight - 19) / this.m_maxValue; y = (int) (this.getHeight() - Math.round(m_histBarCount * heightRatio) - 19); // System.out.println("Filling x:"+x+" y:"+y+" width:"+barWidth+ // " height:"+(m_histBarCounts[i]*heightRatio)); // same as in the if stmt above if (barWidth > 1) { g.drawRect(x, y, barWidth, (int) Math.round(m_histBarCount * heightRatio)); } else if ((m_histBarCount * heightRatio) > 0) { g.drawLine(x, y, x, (int) (y + Math.round(m_histBarCount * heightRatio))); } if (this.m_fm.stringWidth(" " + Utils.doubleToString(m_histBarCount, 1)) < barWidth) { g.drawString(" " + Utils.doubleToString(m_histBarCount, 1), x, y - 1); } x = x + barWidth; } // Now drawing the axis at the bottom of the histogram x = 3; if ((this.getWidth() - (x + this.m_histBarCounts.length * barWidth)) > 5) { x += (this.getWidth() - (x + this.m_histBarCounts.length * barWidth)) / 2; } // This is exact the same as in the if stmt above. See the inside of // the stmt for details g.drawLine(x, this.getHeight() - 17, (barWidth == 1) ? x + barWidth * this.m_histBarCounts.length - 1 : x + barWidth * this.m_histBarCounts.length, this.getHeight() - 17); // axis line g.drawLine(x, this.getHeight() - 16, x, this.getHeight() - 12); // minimum // line g.drawString(Utils.doubleToString(this.m_as.numericStats.min, 2), x, this.getHeight() - 12 + this.m_fm.getHeight()); // minimum value g.drawLine(x + (barWidth * this.m_histBarCounts.length) / 2, this.getHeight() - 16, x + (barWidth * this.m_histBarCounts.length) / 2, this.getHeight() - 12); // median line g.drawString(Utils.doubleToString(this.m_as.numericStats.max / 2 + this.m_as.numericStats.min / 2, 2), x + (barWidth * this.m_histBarCounts.length) / 2 - this.m_fm.stringWidth(Utils.doubleToString(this.m_as.numericStats.max / 2 + this.m_as.numericStats.min / 2, 2)) / 2, this.getHeight() - 12 + this.m_fm.getHeight()); // median value g.drawLine((barWidth == 1) ? x + barWidth * this.m_histBarCounts.length - 1 : x + barWidth * this.m_histBarCounts.length, this.getHeight() - 16, (barWidth == 1) ? x + barWidth * this.m_histBarCounts.length - 1 : x + barWidth * this.m_histBarCounts.length, this.getHeight() - 12); // maximum // line g.drawString(Utils.doubleToString(this.m_as.numericStats.max, 2), (barWidth == 1) ? x + barWidth * this.m_histBarCounts.length - this.m_fm.stringWidth(Utils.doubleToString(this.m_as.numericStats.max, 2)) - 1 : x + barWidth * this.m_histBarCounts.length - this.m_fm.stringWidth(Utils.doubleToString(this.m_as.numericStats.max, 2)), this.getHeight() - 12 + this.m_fm.getHeight()); // maximum // value } // System.out.println("barWidth:"+barWidth+ // " histBarCount:"+m_histBarCounts.length); } else { g.clearRect(0, 0, this.getWidth(), this.getHeight()); g.drawString("Attribute is neither numeric nor nominal.", this.getWidth() / 2 - this.m_fm.stringWidth("Attribute is neither numeric nor nominal.") / 2, this.getHeight() / 2 - this.m_fm.getHeight() / 2); } } // <--end if of calculation thread else if (this.m_displayCurrentAttribute) { // if still calculation thread is // running plot g.clearRect(0, 0, this.getWidth(), this.getHeight()); g.drawString("Calculating. Please Wait...", this.getWidth() / 2 - this.m_fm.stringWidth("Calculating. Please Wait...") / 2, this.getHeight() / 2 - this.m_fm.getHeight() / 2); } else if (!this.m_displayCurrentAttribute) { g.clearRect(0, 0, this.getWidth(), this.getHeight()); g.drawString("Too many values to display.", this.getWidth() / 2 - this.m_fm.stringWidth("Too many values to display.") / 2, this.getHeight() / 2 - this.m_fm.getHeight() / 2); } } // <--end if(m_as==null) this means } /** * Main method to test this class from command line * * @param args The arff file and the index of the attribute to use */ public static void main(final String[] args) { if (args.length != 3) { final JFrame jf = new JFrame("AttribVisualization"); AttributeVisualizationPanel ap = new AttributeVisualizationPanel(); try { Instances ins = new Instances(new FileReader(args[0])); ap.setInstances(ins); System.out.println("Loaded: " + args[0] + "\nRelation: " + ap.m_data.relationName() + "\nAttributes: " + ap.m_data.numAttributes()); ap.setAttribute(Integer.parseInt(args[1])); } catch (Exception ex) { ex.printStackTrace(); System.exit(-1); } System.out.println("The attributes are: "); for (int i = 0; i < ap.m_data.numAttributes(); i++) { System.out.println(ap.m_data.attribute(i).name()); } jf.setSize(500, 300); jf.getContentPane().setLayout(new BorderLayout()); jf.getContentPane().add(ap, BorderLayout.CENTER); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setVisible(true); } else { System.out.println("Usage: java AttributeVisualizationPanel" + " [arff file] [index of attribute]"); } } } /* * t =(int) Math.ceil((float)( * (m_data.instance(k).value(m_attribIndex)-m_as.numericStats.min) / barRange)); * 1. This equation gives a value between (i-1)+smallfraction and i if the * attribute m_attribIndex for the current instances lies in the ith interval. * We then increment the value of our i-1th field of our histogram/barplot * array. If, for example, barRange=3 then, apart from the 1st interval, each * interval i has values in the range (minValue+3*i-1, minValue+3*i]. The 1st * interval has range [minValue, minValue+i]. Hence it can be seen in the code * we specifically handle t=0 separately. */ /** * (barWidth==1)?x+barWidth*m_histBarClassCounts.length-1 : * x+barWidth*m_histBarClassCounts.length 2. In the case barWidth==1 we subtract * 1 otherwise the line become one pixel longer than the actual size of the * histogram */
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/BrowserHelper.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * BrowserHelper.java * Copyright (C) 2006-2012,2015 University of Waikato, Hamilton, New Zealand */ package weka.gui; import java.awt.Color; import java.awt.Component; import java.awt.Desktop; import java.awt.Desktop.Action; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.lang.reflect.Method; import java.net.URI; import javax.swing.JLabel; import javax.swing.JOptionPane; /** * A little helper class for browser related stuff. * <p/> * * The <code>openURL</code> method is based on <a * href="http://www.centerkey.com/java/browser/" target="_blank">Bare Bones * Browser Launch</a>, which is placed in the public domain. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class BrowserHelper { /** Linux/Unix binaries to look for */ public final static String[] LINUX_BROWSERS = { "firefox", "google-chrome", "opera", "konqueror", "epiphany", "mozilla", "netscape" }; /** * opens the URL in a browser. * * @param url the URL to open */ public static void openURL(String url) { openURL(null, url); } /** * opens the URL in a browser. * * @param parent the parent component * @param url the URL to open */ public static void openURL(Component parent, String url) { openURL(parent, url, true); } /** * opens the URL in a browser. * * @param parent the parent component * @param url the URL to open * @param showDialog whether to display a dialog in case of an error or just * print the error to the console */ public static void openURL(Component parent, String url, boolean showDialog) { String osName = System.getProperty("os.name"); try { if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Action.BROWSE)) { Desktop.getDesktop().browse(new URI(url)); } else { System.err.println("Desktop or browse action not supported, using fallback to determine browser."); // Mac OS if (osName.startsWith("Mac OS")) { Class<?> fileMgr = Class.forName("com.apple.eio.FileManager"); Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[] { String.class }); openURL.invoke(null, new Object[] { url }); } // Windows else if (osName.startsWith("Windows")) { Runtime.getRuntime() .exec("rundll32 url.dll,FileProtocolHandler " + url); } // assume Unix or Linux else { String browser = null; for (int count = 0; count < LINUX_BROWSERS.length && browser == null; count++) { // look for binaries and take first that's available if (Runtime.getRuntime() .exec(new String[] { "which", LINUX_BROWSERS[count] }).waitFor() == 0) { browser = LINUX_BROWSERS[count]; break; } } if (browser == null) { throw new Exception("Could not find web browser"); } else { Runtime.getRuntime().exec(new String[] { browser, url }); } } } } catch (Exception e) { String errMsg = "Error attempting to launch web browser:\n" + e.getMessage(); if (showDialog) { JOptionPane.showMessageDialog(parent, errMsg); } else { System.err.println(errMsg); } } } /** * Generates a label with a clickable link. * * @param url the url of the link * @param text the text to display instead of URL. if null or of length 0 then * the URL is used * @return the generated label */ public static JLabel createLink(String url, String text) { final String urlF = url; final JLabel result = new JLabel(); result.setText((text == null) || (text.length() == 0) ? url : text); result.setToolTipText("Click to open link in browser"); result.setForeground(Color.BLUE); result.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { BrowserHelper.openURL(urlF); } else { super.mouseClicked(e); } } @Override public void mouseEntered(MouseEvent e) { result.setForeground(Color.RED); } @Override public void mouseExited(MouseEvent e) { result.setForeground(Color.BLUE); } }); return result; } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/CheckBoxList.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * CheckBoxList.java * Copyright (C) 2006-2012 University of Waikato, Hamilton, New Zealand */ package weka.gui; import java.awt.Component; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.NoSuchElementException; import java.util.Vector; import javax.swing.DefaultListModel; import javax.swing.JCheckBox; import javax.swing.JList; import javax.swing.ListCellRenderer; import javax.swing.ListModel; /** * An extended JList that contains CheckBoxes. If necessary a CheckBoxListItem * wrapper is added around the displayed object in any of the Model methods, * e.g., addElement. For methods returning objects the opposite takes place, the * wrapper is removed and only the payload object is returned. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class CheckBoxList extends JList { /** for serialization */ private static final long serialVersionUID = -4359573373359270258L; /** * represents an item in the CheckBoxListModel * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ protected class CheckBoxListItem { /** whether item is checked or not */ private boolean m_Checked = false; /** the actual object */ private Object m_Content = null; /** * initializes the item with the given object and initially unchecked * * @param o the content object */ public CheckBoxListItem(Object o) { this(o, false); } /** * initializes the item with the given object and whether it's checked * initially * * @param o the content object * @param checked whether the item should be checked initially */ public CheckBoxListItem(Object o, boolean checked) { m_Checked = checked; m_Content = o; } /** * returns the content object */ public Object getContent() { return m_Content; } /** * sets the checked state of the item */ public void setChecked(boolean value) { m_Checked = value; } /** * returns the checked state of the item */ public boolean getChecked() { return m_Checked; } /** * returns the string representation of the content object */ @Override public String toString() { return m_Content.toString(); } /** * returns true if the "payload" objects of the current and the given * CheckBoxListItem are the same. * * @param o the CheckBoxListItem to check * @throws IllegalArgumentException if the provided object is not a * CheckBoxListItem */ @Override public boolean equals(Object o) { if (!(o instanceof CheckBoxListItem)) { throw new IllegalArgumentException("Must be a CheckBoxListItem!"); } return getContent().equals(((CheckBoxListItem) o).getContent()); } } /** * A specialized model. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ @SuppressWarnings("rawtypes") public class CheckBoxListModel extends DefaultListModel { /** for serialization */ private static final long serialVersionUID = 7772455499540273507L; /** * initializes the model with no data. */ public CheckBoxListModel() { super(); } /** * Constructs a CheckBoxListModel from an array of objects and then applies * setModel to it. * * @param listData the data to use */ public CheckBoxListModel(Object[] listData) { for (Object element : listData) { addElement(element); } } /** * Constructs a CheckBoxListModel from a Vector and then applies setModel to * it. */ public CheckBoxListModel(Vector listData) { for (int i = 0; i < listData.size(); i++) { addElement(listData.get(i)); } } /** * Inserts the specified element at the specified position in this list. * * @param index index at which the specified element is to be inserted * @param element element to be inserted */ @Override public void add(int index, Object element) { if (!(element instanceof CheckBoxListItem)) { super.add(index, new CheckBoxListItem(element)); } else { super.add(index, element); } } /** * Adds the specified component to the end of this list. * * @param obj the component to be added */ @Override public void addElement(Object obj) { if (!(obj instanceof CheckBoxListItem)) { super.addElement(new CheckBoxListItem(obj)); } else { super.addElement(obj); } } /** * Tests whether the specified object is a component in this list. * * @param elem the element to check * @return true if the element is in the list */ @Override public boolean contains(Object elem) { if (!(elem instanceof CheckBoxListItem)) { return super.contains(new CheckBoxListItem(elem)); } else { return super.contains(elem); } } /** * Copies the components of this list into the specified array. * * @param anArray the array into which the components get copied * @throws IndexOutOfBoundsException if the array is not big enough */ @Override public void copyInto(Object[] anArray) { if (anArray.length < getSize()) { throw new IndexOutOfBoundsException("Array not big enough!"); } for (int i = 0; i < getSize(); i++) { anArray[i] = ((CheckBoxListItem) getElementAt(i)).getContent(); } } /** * Returns the component at the specified index. Throws an * ArrayIndexOutOfBoundsException if the index is negative or not less than * the size of the list. * * @param index an index into this list * @return the component at the specified index * @throws ArrayIndexOutOfBoundsException */ @Override public Object elementAt(int index) { return ((CheckBoxListItem) super.elementAt(index)).getContent(); } /** * Returns the first component of this list. Throws a NoSuchElementException * if this vector has no components. * * @return the first component of this list * @throws NoSuchElementException */ @Override public Object firstElement() { return ((CheckBoxListItem) super.firstElement()).getContent(); } /** * Returns the element at the specified position in this list. * * @param index of element to return * @throws ArrayIndexOutOfBoundsException */ @Override public Object get(int index) { return ((CheckBoxListItem) super.get(index)).getContent(); } /** * Returns the component at the specified index. * * @param index an index into this list * @return the component at the specified index * @throws ArrayIndexOutOfBoundsException */ @Override public Object getElementAt(int index) { return ((CheckBoxListItem) super.getElementAt(index)).getContent(); } /** * Searches for the first occurrence of elem. * * @param elem an object * @return the index of the first occurrence of the argument in this list; * returns -1 if the object is not found */ @Override public int indexOf(Object elem) { if (!(elem instanceof CheckBoxListItem)) { return super.indexOf(new CheckBoxListItem(elem)); } else { return super.indexOf(elem); } } /** * Searches for the first occurrence of elem, beginning the search at index. * * @param elem the desired component * @param index the index from which to begin searching * @return the index where the first occurrence of elem is found after * index; returns -1 if the elem is not found in the list */ @Override public int indexOf(Object elem, int index) { if (!(elem instanceof CheckBoxListItem)) { return super.indexOf(new CheckBoxListItem(elem), index); } else { return super.indexOf(elem, index); } } /** * Inserts the specified object as a component in this list at the specified * index. * * @param obj the component to insert * @param index where to insert the new component * @throws ArrayIndexOutOfBoundsException */ @Override public void insertElementAt(Object obj, int index) { if (!(obj instanceof CheckBoxListItem)) { super.insertElementAt(new CheckBoxListItem(obj), index); } else { super.insertElementAt(obj, index); } } /** * Returns the last component of the list. Throws a NoSuchElementException * if this vector has no components. * * @return the last component of the list * @throws NoSuchElementException */ @Override public Object lastElement() { return ((CheckBoxListItem) super.lastElement()).getContent(); } /** * Returns the index of the last occurrence of elem. * * @param elem the desired component * @return the index of the last occurrence of elem in the list; returns -1 * if the object is not found */ @Override public int lastIndexOf(Object elem) { if (!(elem instanceof CheckBoxListItem)) { return super.lastIndexOf(new CheckBoxListItem(elem)); } else { return super.lastIndexOf(elem); } } /** * Searches backwards for elem, starting from the specified index, and * returns an index to it. * * @param elem the desired component * @param index the index to start searching from * @return the index of the last occurrence of the elem in this list at * position less than index; returns -1 if the object is not found */ @Override public int lastIndexOf(Object elem, int index) { if (!(elem instanceof CheckBoxListItem)) { return super.lastIndexOf(new CheckBoxListItem(elem), index); } else { return super.lastIndexOf(elem, index); } } /** * Removes the element at the specified position in this list. Returns the * element that was removed from the list. * * @param index the index of the element to removed * @throws ArrayIndexOutOfBoundsException */ @Override public Object remove(int index) { return ((CheckBoxListItem) super.remove(index)).getContent(); } /** * Removes the first (lowest-indexed) occurrence of the argument from this * list. * * @param obj the component to be removed * @return true if the argument was a component of this list; false * otherwise */ @Override public boolean removeElement(Object obj) { if (!(obj instanceof CheckBoxListItem)) { return super.removeElement(new CheckBoxListItem(obj)); } else { return super.removeElement(obj); } } /** * Replaces the element at the specified position in this list with the * specified element. * * @param index index of element to replace * @param element element to be stored at the specified position * @throws ArrayIndexOutOfBoundsException */ @Override public Object set(int index, Object element) { if (!(element instanceof CheckBoxListItem)) { return ((CheckBoxListItem) super.set(index, new CheckBoxListItem( element))).getContent(); } else { return ((CheckBoxListItem) super.set(index, element)).getContent(); } } /** * Sets the component at the specified index of this list to be the * specified object. The previous component at that position is discarded. * * @param obj what the component is to be set to * @param index the specified index * @throws ArrayIndexOutOfBoundsException */ @Override public void setElementAt(Object obj, int index) { if (!(obj instanceof CheckBoxListItem)) { super.setElementAt(new CheckBoxListItem(obj), index); } else { super.setElementAt(obj, index); } } /** * Returns an array containing all of the elements in this list in the * correct order. * * @return an array containing the elements of the list */ @Override public Object[] toArray() { Object[] result; Object[] internal; int i; internal = super.toArray(); result = new Object[internal.length]; for (i = 0; i < internal.length; i++) { result[i] = ((CheckBoxListItem) internal[i]).getContent(); } return result; } /** * returns the checked state of the element at the given index * * @param index the index of the element to return the checked state for * @return the checked state of the specifed element */ public boolean getChecked(int index) { return ((CheckBoxListItem) super.getElementAt(index)).getChecked(); } /** * sets the checked state of the element at the given index * * @param index the index of the element to set the checked state for * @param checked the new checked state */ public void setChecked(int index, boolean checked) { ((CheckBoxListItem) super.getElementAt(index)).setChecked(checked); } } /** * A specialized CellRenderer for the CheckBoxList * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ * @see CheckBoxList */ public class CheckBoxListRenderer extends JCheckBox implements ListCellRenderer { /** for serialization */ private static final long serialVersionUID = 1059591605858524586L; /** * Return a component that has been configured to display the specified * value. * * @param list The JList we're painting. * @param value The value returned by list.getModel().getElementAt(index). * @param index The cells index. * @param isSelected True if the specified cell was selected. * @param cellHasFocus True if the specified cell has the focus. * @return A component whose paint() method will render the specified value. */ @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { setText(value.toString()); setSelected(((CheckBoxList) list).getChecked(index)); setBackground(isSelected ? list.getSelectionBackground() : list .getBackground()); setForeground(isSelected ? list.getSelectionForeground() : list .getForeground()); setFocusPainted(false); return this; } } /** * initializes the list with an empty CheckBoxListModel */ public CheckBoxList() { this(null); } /** * initializes the list with the given CheckBoxListModel * * @param model the model to initialize with */ public CheckBoxList(CheckBoxListModel model) { super(); if (model == null) { model = this.new CheckBoxListModel(); } setModel(model); setCellRenderer(new CheckBoxListRenderer()); addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { int index = locationToIndex(e.getPoint()); if (index != -1) { setChecked(index, !getChecked(index)); repaint(); } } }); addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { if ((e.getKeyChar() == ' ') && (e.getModifiers() == 0)) { int index = getSelectedIndex(); setChecked(index, !getChecked(index)); e.consume(); repaint(); } } }); } /** * sets the model - must be an instance of CheckBoxListModel * * @param model the model to use * @throws IllegalArgumentException if the model is not an instance of * CheckBoxListModel * @see CheckBoxListModel */ @Override public void setModel(ListModel model) { if (!(model instanceof CheckBoxListModel)) { throw new IllegalArgumentException( "Model must be an instance of CheckBoxListModel!"); } super.setModel(model); } /** * Constructs a CheckBoxListModel from an array of objects and then applies * setModel to it. * * @param listData the data to use */ @Override public void setListData(Object[] listData) { setModel(new CheckBoxListModel(listData)); } /** * Constructs a CheckBoxListModel from a Vector and then applies setModel to * it. */ @Override public void setListData(@SuppressWarnings("rawtypes") Vector listData) { setModel(new CheckBoxListModel(listData)); } /** * returns the checked state of the element at the given index * * @param index the index of the element to return the checked state for * @return the checked state of the specifed element */ public boolean getChecked(int index) { return ((CheckBoxListModel) getModel()).getChecked(index); } /** * sets the checked state of the element at the given index * * @param index the index of the element to set the checked state for * @param checked the new checked state */ public void setChecked(int index, boolean checked) { ((CheckBoxListModel) getModel()).setChecked(index, checked); } /** * returns an array with the indices of all checked items * * @return the indices of all items that are currently checked */ public int[] getCheckedIndices() { Vector<Integer> list; int[] result; int i; // traverse over model list = new Vector<Integer>(); for (i = 0; i < getModel().getSize(); i++) { if (getChecked(i)) { list.add(new Integer(i)); } } // generate result array result = new int[list.size()]; for (i = 0; i < list.size(); i++) { result[i] = list.get(i).intValue(); } return result; } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/CloseableTabTitle.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * CloseableTabTitle.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.AbstractButton; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.plaf.basic.BasicButtonUI; /** * Tab title widget that allows the user to click a little cross in order to * close the tab * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ public class CloseableTabTitle extends JPanel { /** For serialization */ private static final long serialVersionUID = 9178081197757118130L; /** * Interface for a callback for notification of a tab's close widget being * clicked */ public static interface ClosingCallback { void tabClosing(int tabIndex); } /** The enclosing JTabbedPane */ private final JTabbedPane m_enclosingPane; /** The label for the tab */ private JLabel m_tabLabel; /** The close widget */ private TabButton m_tabButton; /** Owner to callback on closing widget click */ private ClosingCallback m_callback; /** * Description of the keyboard accellerator used for closing the active tab * (if any) */ private String m_closeAccelleratorText = ""; /** * Constructor. * * @param pane the enclosing JTabbedPane * @param callback the callback to notify on closing widget click */ public CloseableTabTitle(final JTabbedPane pane, String closeAccelleratorText, ClosingCallback callback) { super(new FlowLayout(FlowLayout.LEFT, 0, 0)); if (closeAccelleratorText != null) { m_closeAccelleratorText = closeAccelleratorText; } m_enclosingPane = pane; setOpaque(false); setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0)); // read the title from the JTabbedPane m_tabLabel = new JLabel() { /** For serialization */ private static final long serialVersionUID = 8515052190461050324L; @Override public String getText() { int index = m_enclosingPane.indexOfTabComponent(CloseableTabTitle.this); if (index >= 0) { return m_enclosingPane.getTitleAt(index); } return null; } }; add(m_tabLabel); m_tabLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5)); m_tabButton = new TabButton(); add(m_tabButton); m_callback = callback; m_tabLabel.setEnabled(false); } /** * Set a bold look for the tab * * @param bold true for bold */ public void setBold(boolean bold) { m_tabLabel.setEnabled(bold); } /** * Enable/disable the close widget * * @param enabled */ public void setButtonEnabled(boolean enabled) { m_tabButton.setEnabled(enabled); } /** * Class that implements the cross shaped close widget */ private class TabButton extends JButton implements ActionListener { /** For serialization */ private static final long serialVersionUID = -4915800749132175968L; public TabButton() { int size = 17; setPreferredSize(new Dimension(size, size)); setToolTipText("close this tab"); // Make the button looks the same for all Laf's setUI(new BasicButtonUI()); // Make it transparent setContentAreaFilled(false); // No need to be focusable setFocusable(false); setBorder(BorderFactory.createEtchedBorder()); setBorderPainted(false); // Making nice rollover effect // we use the same listener for all buttons addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { Component component = e.getComponent(); if (component instanceof AbstractButton) { AbstractButton button = (AbstractButton) component; button.setBorderPainted(true); int i = m_enclosingPane.indexOfTabComponent(CloseableTabTitle.this); if (i == m_enclosingPane.getSelectedIndex()) { button .setToolTipText("close this tab " + m_closeAccelleratorText); } else { button.setToolTipText("close this tab"); } } } @Override public void mouseExited(MouseEvent e) { Component component = e.getComponent(); if (component instanceof AbstractButton) { AbstractButton button = (AbstractButton) component; button.setBorderPainted(false); } } }); setRolloverEnabled(true); // Close the proper tab by clicking the button addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { int i = m_enclosingPane.indexOfTabComponent(CloseableTabTitle.this); if (i >= 0) { if (m_callback != null) { m_callback.tabClosing(i); } } } // we don't want to update UI for this button @Override public void updateUI() { } // paint the cross @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g.create(); // shift the image for pressed buttons if (getModel().isPressed()) { g2.translate(1, 1); } g2.setStroke(new BasicStroke(2)); g2.setColor(Color.BLACK); if (!isEnabled()) { g2.setColor(Color.GRAY); } if (getModel().isRollover()) { g2.setColor(Color.MAGENTA); } int delta = 6; g2.drawLine(delta, delta, getWidth() - delta - 1, getHeight() - delta - 1); g2.drawLine(getWidth() - delta - 1, delta, delta, getHeight() - delta - 1); g2.dispose(); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/ColorEditor.java
package weka.gui; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.awt.Rectangle; import java.beans.PropertyChangeListener; import java.beans.PropertyEditor; import javax.swing.JColorChooser; /** * A property editor for colors that uses JColorChooser as the * underlying editor. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class ColorEditor implements PropertyEditor { /** The underlying JColorChooser used as the custom editor */ protected JColorChooser m_editor = new JColorChooser(); public ColorEditor() { super(); } /** * Set the current color * * @param value the current color */ @Override public void setValue(Object value) { m_editor.setColor((Color) value); } /** * Get the current color * * @return the current color */ @Override public Object getValue() { return m_editor.getColor(); } /** * We paint our current color into the supplied bounding box * * @return true as we are paintable */ @Override public boolean isPaintable() { return true; } /** * Paint our current color into the supplied bounding box * * @param gfx the graphics object to use * @param box the bounding box */ @Override public void paintValue(Graphics gfx, Rectangle box) { Color c = m_editor.getColor(); gfx.setColor(c); gfx.fillRect(box.x, box.y, box.width, box.height); } /** * Don't really need this * * @return some arbitrary string */ @Override public String getJavaInitializationString() { return "null"; } /** * Not representable as a string * * @return null */ @Override public String getAsText() { return null; } /** * Throws an exception as we are not representable in text form * * @param text text * @throws IllegalArgumentException */ @Override public void setAsText(String text) throws IllegalArgumentException { throw new IllegalArgumentException(text); } /** * Not applicable - returns null * * @return null */ @Override public String[] getTags() { return null; } /** * Returns our JColorChooser object * * @return our JColorChooser object */ @Override public Component getCustomEditor() { return m_editor; } /** * We use JColorChooser, so return true * * @return true */ @Override public boolean supportsCustomEditor() { return true; } @Override public void addPropertyChangeListener(PropertyChangeListener listener) { m_editor.addPropertyChangeListener(listener); } @Override public void removePropertyChangeListener(PropertyChangeListener listener) { m_editor.removePropertyChangeListener(listener); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/ComponentHelper.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ComponentHelper.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.awt.Component; import java.awt.Image; import java.net.URL; import javax.swing.ImageIcon; import javax.swing.JOptionPane; /** * A helper class for some common tasks with Dialogs, Icons, etc. * * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class ComponentHelper { /** the default directories for images */ public final static String[] IMAGES = {"weka/gui/", "weka/gui/images/"}; /** * returns the ImageIcon for a given filename and directory, NULL if not successful * * @param dir the directory to look in for the file * @param filename the file to retrieve * @return the imageicon if found, otherwise null */ public static ImageIcon getImageIcon(String dir, String filename) { URL url; ImageIcon result; int i; result = null; url = Loader.getURL(dir, filename); // try to find the image at default locations if (url == null) { for (i = 0; i < IMAGES.length; i++) { url = Loader.getURL(IMAGES[i], filename); if (url != null) break; } } if (url != null) result = new ImageIcon(url); return result; } /** * returns the ImageIcon for a given filename, NULL if not successful * * @param filename the file to retrieve * @return the imageicon if found, otherwise null */ public static ImageIcon getImageIcon(String filename) { return getImageIcon("", filename); } /** * returns the Image for a given directory and filename, NULL if not successful * * @param dir the directory to look in for the file * @param filename the file to retrieve * @return the image if found, otherwise null */ public static Image getImage(String dir, String filename) { ImageIcon img; Image result; result = null; img = getImageIcon(dir, filename); if (img != null) result = img.getImage(); return result; } /** * returns the Image for a given filename, NULL if not successful * * @param filename the file to retrieve * @return the image if found, otherwise null */ public static Image getImage(String filename) { ImageIcon img; Image result; result = null; img = getImageIcon(filename); if (img != null) result = img.getImage(); return result; } /** * displays a message box with the given title, message, buttons and icon * ant the dimension. * it returns the pressed button. * @param parent the parent component * @param title the title of the message box * @param msg the text to display * @param buttons the captions of the buttons to display * @param messageType the type of message like defined in <code>JOptionPane</code> (the icon is determined on this basis) * @return the button that was pressed * @see JOptionPane */ public static int showMessageBox(Component parent, String title, String msg, int buttons, int messageType) { String icon; switch (messageType) { case JOptionPane.ERROR_MESSAGE: icon = "weka/gui/images/error.gif"; break; case JOptionPane.INFORMATION_MESSAGE: icon = "weka/gui/images/information.gif"; break; case JOptionPane.WARNING_MESSAGE: icon = "weka/gui/images/information.gif"; break; case JOptionPane.QUESTION_MESSAGE: icon = "weka/gui/images/question.gif"; break; default: icon = "weka/gui/images/information.gif"; break; } return JOptionPane.showConfirmDialog(parent, msg, title, buttons, messageType, getImageIcon(icon)); } /** * pops up an input dialog * * @param parent the parent of this dialog, can be <code>null</code> * @param title the title to display, can be <code>null</code> * @param msg the message to display * @param initialValue the initial value to display as input * @return the entered value, or if cancelled <code>null</code> */ public static String showInputBox(Component parent, String title, String msg, Object initialValue) { Object result; if (title == null) title = "Input..."; result = JOptionPane.showInputDialog( parent, msg, title, JOptionPane.QUESTION_MESSAGE, getImageIcon("question.gif"), null, initialValue); if (result != null) return result.toString(); else return null; } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/ConverterFileChooser.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ConverterFileChooser.java * Copyright (C) 2006-2012 University of Waikato, Hamilton, New Zealand */ package weka.gui; import weka.core.Capabilities; import weka.core.Instances; import weka.core.WekaPackageClassLoaderManager; import weka.core.converters.AbstractFileLoader; import weka.core.converters.AbstractFileSaver; import weka.core.converters.AbstractLoader; import weka.core.converters.AbstractSaver; import weka.core.converters.ConverterResources; import weka.core.converters.ConverterUtils; import weka.core.converters.FileSourcedConverter; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.filechooser.FileFilter; import java.awt.BorderLayout; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.util.Vector; /** * A specialized JFileChooser that lists all available file Loaders and Savers. * To list only savers that can handle the data that is about to be saved, one * can set a Capabilities filter. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ * @see #setCapabilitiesFilter(Capabilities) */ public class ConverterFileChooser extends JFileChooser { /** for serialization. */ private static final long serialVersionUID = -5373058011025481738L; /** unhandled type of dialog. */ public final static int UNHANDLED_DIALOG = 0; /** the loader dialog. */ public final static int LOADER_DIALOG = 1; /** the saver dialog. */ public final static int SAVER_DIALOG = 2; /** the file chooser itself. */ protected ConverterFileChooser m_Self; /** the file filters for the loaders. */ protected static Vector<ExtensionFileFilter> m_LoaderFileFilters; /** the file filters for the savers. */ protected static Vector<ExtensionFileFilter> m_SaverFileFilters; /** the type of dialog to display. */ protected int m_DialogType; /** the converter that was chosen by the user. */ protected Object m_CurrentConverter; /** the configure button. */ protected JButton m_ConfigureButton; /** the propertychangelistener. */ protected PropertyChangeListener m_Listener; /** the last filter that was used for opening/saving. */ protected FileFilter m_LastFilter; /** the Capabilities filter for the savers. */ protected Capabilities m_CapabilitiesFilter; /** * whether to popup a dialog in case the file already exists (only save * dialog). */ protected boolean m_OverwriteWarning = true; /** whether the file to be opened must exist (only open dialog). */ protected boolean m_FileMustExist = true; /** the checkbox for bringing up the GenericObjectEditor. */ protected JCheckBox m_CheckBoxOptions; /** the note about the options dialog. */ protected JLabel m_LabelOptions; /** the GOE for displaying the options of a loader/saver. */ protected GenericObjectEditor m_Editor = null; /** whether the GOE was OKed or Canceled. */ protected int m_EditorResult; /** * whether to display only core converters (hardcoded in ConverterUtils). * Necessary for RMI/Remote Experiments for instance. * * @see weka.core.converters.ConverterResources#CORE_FILE_LOADERS * @see weka.core.converters.ConverterResources#CORE_FILE_SAVERS */ protected boolean m_CoreConvertersOnly = false; static { initDefaultFilters(); } /** * Initialize the default set of filters for loaders and savers */ public static void initDefaultFilters() { ConverterUtils.initialize(); initFilters(true, ConverterUtils.getFileLoaders()); initFilters(false, ConverterUtils.getFileSavers()); } /** * onstructs a FileChooser pointing to the user's default directory. */ public ConverterFileChooser() { super(); initialize(); } /** * Constructs a FileChooser using the given File as the path. * * @param currentDirectory the path to start in */ public ConverterFileChooser(File currentDirectory) { super(currentDirectory); initialize(); } /** * Constructs a FileChooser using the given path. * * @param currentDirectory the path to start in */ public ConverterFileChooser(String currentDirectory) { super(currentDirectory); initialize(); } /** * Further initializations. */ protected void initialize() { JPanel panel; JPanel panel2; m_Self = this; m_CheckBoxOptions = new JCheckBox("Invoke options dialog"); m_CheckBoxOptions.setMnemonic('I'); m_LabelOptions = new JLabel( "<html><br>Note:<br><br>Some file formats offer additional<br>options which can be customized<br>when invoking the options dialog.</html>"); panel = new JPanel(new BorderLayout()); panel.add(m_CheckBoxOptions, BorderLayout.NORTH); panel2 = new JPanel(new BorderLayout()); panel2.add(m_LabelOptions, BorderLayout.NORTH); panel2.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); panel.add(panel2, BorderLayout.CENTER); setAccessory(panel); m_Editor = new GenericObjectEditor(false); ((GenericObjectEditor.GOEPanel) m_Editor.getCustomEditor()) .addOkListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_EditorResult = JFileChooser.APPROVE_OPTION; m_CurrentConverter = m_Editor.getValue(); // thanks to serialization and transient readers/streams, we have // to set the file again to initialize the converter again try { ((FileSourcedConverter) m_CurrentConverter) .setFile(((FileSourcedConverter) m_CurrentConverter) .retrieveFile()); } catch (Exception ex) { // ignored } } }); ((GenericObjectEditor.GOEPanel) m_Editor.getCustomEditor()) .addCancelListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_EditorResult = JFileChooser.CANCEL_OPTION; } }); } /** * filters out all non-core loaders if only those should be displayed. * * @param list the list of filters to check * @return the filtered list of filters * @see #m_CoreConvertersOnly */ protected Vector<ExtensionFileFilter> filterNonCoreLoaderFileFilters( Vector<ExtensionFileFilter> list) { Vector<ExtensionFileFilter> result; int i; ExtensionFileFilter filter; AbstractLoader loader; if (!getCoreConvertersOnly()) { result = list; } else { result = new Vector<ExtensionFileFilter>(); for (i = 0; i < list.size(); i++) { filter = list.get(i); loader = ConverterUtils .getLoaderForExtension(filter.getExtensions()[0]); if (ConverterResources.isCoreFileLoader(loader.getClass().getName())) { result.add(filter); } } } return result; } /** * filters out all non-core savers if only those should be displayed. * * @param list the list of filters to check * @return the filtered list of filters * @see #m_CoreConvertersOnly */ protected Vector<ExtensionFileFilter> filterNonCoreSaverFileFilters( Vector<ExtensionFileFilter> list) { Vector<ExtensionFileFilter> result; int i; ExtensionFileFilter filter; AbstractSaver saver; if (!getCoreConvertersOnly()) { result = list; } else { result = new Vector<ExtensionFileFilter>(); for (i = 0; i < list.size(); i++) { filter = list.get(i); saver = ConverterUtils.getSaverForExtension(filter.getExtensions()[0]); if (ConverterResources.isCoreFileSaver(saver.getClass().getName())) { result.add(filter); } } } return result; } /** * filters the list of file filters according to the currently set. * Capabilities * * @param list the filters to check * @return the filtered list of filters */ protected Vector<ExtensionFileFilter> filterSaverFileFilters( Vector<ExtensionFileFilter> list) { Vector<ExtensionFileFilter> result; int i; ExtensionFileFilter filter; AbstractSaver saver; if (m_CapabilitiesFilter == null) { result = list; } else { result = new Vector<ExtensionFileFilter>(); for (i = 0; i < list.size(); i++) { filter = list.get(i); saver = ConverterUtils.getSaverForExtension(filter.getExtensions()[0]); if (saver.getCapabilities().supports(m_CapabilitiesFilter)) { result.add(filter); } } } return result; } /** * initializes the ExtensionFileFilters. * * @param loader if true then the loader filter are initialized * @param classnames the classnames of the converters */ protected static void initFilters(boolean loader, Vector<String> classnames) { int i; int n; String classname; Class<?> cls; String[] ext; String desc; FileSourcedConverter converter; ExtensionFileFilter filter; if (loader) { m_LoaderFileFilters = new Vector<ExtensionFileFilter>(); } else { m_SaverFileFilters = new Vector<ExtensionFileFilter>(); } for (i = 0; i < classnames.size(); i++) { classname = classnames.get(i); // get data from converter try { cls = WekaPackageClassLoaderManager.forName(classname); converter = (FileSourcedConverter) cls.newInstance(); ext = converter.getFileExtensions(); desc = converter.getFileDescription(); } catch (Exception e) { cls = null; converter = null; ext = new String[0]; desc = ""; } if (converter == null) { continue; } // loader? if (loader) { for (n = 0; n < ext.length; n++) { filter = new ExtensionFileFilter(ext[n], desc + " (*" + ext[n] + ")"); m_LoaderFileFilters.add(filter); } } else { for (n = 0; n < ext.length; n++) { filter = new ExtensionFileFilter(ext[n], desc + " (*" + ext[n] + ")"); m_SaverFileFilters.add(filter); } } } } /** * initializes the GUI. * * @param dialogType the type of dialog to setup the GUI for */ protected void initGUI(int dialogType) { Vector<ExtensionFileFilter> list; int i; boolean acceptAll; // backup current state acceptAll = isAcceptAllFileFilterUsed(); // setup filters resetChoosableFileFilters(); setAcceptAllFileFilterUsed(acceptAll); if (dialogType == LOADER_DIALOG) { list = filterNonCoreLoaderFileFilters(m_LoaderFileFilters); } else { list = filterSaverFileFilters(filterNonCoreSaverFileFilters(m_SaverFileFilters)); } for (i = 0; i < list.size(); i++) { addChoosableFileFilter(list.get(i)); } if (list.size() > 0) { if ((m_LastFilter == null) || (!list.contains(m_LastFilter))) { setFileFilter(list.get(0)); } else { setFileFilter(m_LastFilter); } } // listener if (m_Listener != null) { removePropertyChangeListener(m_Listener); } m_Listener = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { // filter changed if (evt.getPropertyName().equals(FILE_FILTER_CHANGED_PROPERTY)) { updateCurrentConverter(); } } }; addPropertyChangeListener(m_Listener); // initial setup if (dialogType == LOADER_DIALOG) { m_Editor.setClassType(AbstractFileLoader.class); m_Editor.setValue(new weka.core.converters.ArffLoader()); } else { m_Editor.setClassType(AbstractFileSaver.class); m_Editor.setValue(new weka.core.converters.ArffSaver()); } updateCurrentConverter(); } /** * sets the capabilities that the savers must have. use null if all should be * listed. * * @param value the minimum Capabilities the savers must have */ public void setCapabilitiesFilter(Capabilities value) { m_CapabilitiesFilter = (Capabilities) value.clone(); } /** * returns the capabilities filter for the savers, can be null if all are * listed. * * @return the minimum Capabilities the savers must have */ public Capabilities getCapabilitiesFilter() { if (m_CapabilitiesFilter != null) { return (Capabilities) m_CapabilitiesFilter.clone(); } else { return null; } } /** * Whether a warning is popped up if the file that is to be saved already * exists (only save dialog). * * @param value if true a warning will be popup */ public void setOverwriteWarning(boolean value) { m_OverwriteWarning = value; } /** * Returns whether a popup appears with a warning that the file already exists * (only save dialog). * * @return true if a warning pops up */ public boolean getOverwriteWarning() { return m_OverwriteWarning; } /** * Whether the selected file must exst (only open dialog). * * @param value if true the file must exist */ public void setFileMustExist(boolean value) { m_FileMustExist = value; } /** * Returns whether the selected file must exist (only open dialog). * * @return true if the file must exist */ public boolean getFileMustExist() { return m_FileMustExist; } /** * Whether to display only the hardocded core converters. Necessary for * RMI/Remote Experiments (dynamic class discovery doesn't work there!). * * @param value if true only the core converters will be displayed * @see #m_CoreConvertersOnly */ public void setCoreConvertersOnly(boolean value) { m_CoreConvertersOnly = value; } /** * Returns whether only the hardcoded core converters are displayed. Necessary * for RMI/REmote Experiments (dynamic class discovery doesn't work there!). * * @return true if the file must exist * @see #m_CoreConvertersOnly */ public boolean getCoreConvertersOnly() { return m_CoreConvertersOnly; } /** * Pops a custom file chooser dialog with a custom approve button. Throws an * exception, if the dialog type is UNHANDLED_DIALOG. * * @param parent the parent of this dialog * @param approveButtonText the text for the OK button * @return the user's action */ @Override public int showDialog(Component parent, String approveButtonText) { if (m_DialogType == UNHANDLED_DIALOG) { throw new IllegalStateException( "Either use showOpenDialog or showSaveDialog!"); } else { return super.showDialog(parent, approveButtonText); } } /** * Pops up an "Open File" file chooser dialog. * * @param parent the parent of this file chooser * @return the result of the user's action */ @Override public int showOpenDialog(Component parent) { m_DialogType = LOADER_DIALOG; m_CurrentConverter = null; initGUI(LOADER_DIALOG); int result = super.showOpenDialog(parent); m_DialogType = UNHANDLED_DIALOG; removePropertyChangeListener(m_Listener); // do we have to add the extension? if ((result == APPROVE_OPTION) && (getSelectedFile().isFile())) { if (getFileFilter() instanceof ExtensionFileFilter) { String filename = getSelectedFile().getAbsolutePath(); String[] extensions = ((ExtensionFileFilter) getFileFilter()) .getExtensions(); if (!filename.endsWith(extensions[0])) { filename += extensions[0]; setSelectedFile(new File(filename)); } } } // does file exist? if ((result == APPROVE_OPTION) && (getFileMustExist()) && (getSelectedFile().isFile()) && (!getSelectedFile().exists())) { int retVal = JOptionPane.showConfirmDialog(parent, "The file '" + getSelectedFile() + "' does not exist - please select again!"); if (retVal == JOptionPane.OK_OPTION) { result = showOpenDialog(parent); } else { result = CANCEL_OPTION; } } if (result == APPROVE_OPTION) { m_LastFilter = getFileFilter(); configureCurrentConverter(LOADER_DIALOG); // bring up options dialog? if (m_CheckBoxOptions.isSelected() && m_CurrentConverter != null) { m_EditorResult = JFileChooser.CANCEL_OPTION; m_Editor.setValue(m_CurrentConverter); PropertyDialog pd; if (PropertyDialog.getParentDialog(this) != null) { pd = new PropertyDialog(PropertyDialog.getParentDialog(this), m_Editor); } else { pd = new PropertyDialog(PropertyDialog.getParentFrame(this), m_Editor); } pd.setVisible(true); result = m_EditorResult; } } return result; } /** * Pops up an "Save File" file chooser dialog. * * @param parent the parent of this file chooser * @return the result of the user's action */ @Override public int showSaveDialog(Component parent) { m_DialogType = SAVER_DIALOG; m_CurrentConverter = null; initGUI(SAVER_DIALOG); boolean acceptAll = isAcceptAllFileFilterUsed(); // using "setAcceptAllFileFilterUsed" messes up the currently selected // file filter/file, hence backup/restore of currently selected // file filter/file FileFilter currentFilter = getFileFilter(); File currentFile = getSelectedFile(); setAcceptAllFileFilterUsed(false); setFileFilter(currentFilter); setSelectedFile(currentFile); int result = super.showSaveDialog(parent); // do we have to add the extension? if (result == APPROVE_OPTION) { if (getFileFilter() instanceof ExtensionFileFilter) { String filename = getSelectedFile().getAbsolutePath(); String[] extensions = ((ExtensionFileFilter) getFileFilter()) .getExtensions(); if (!filename.endsWith(extensions[0])) { filename += extensions[0]; setSelectedFile(new File(filename)); } } } // using "setAcceptAllFileFilterUsed" messes up the currently selected // file filter/file, hence backup/restore of currently selected // file filter/file currentFilter = getFileFilter(); currentFile = getSelectedFile(); setAcceptAllFileFilterUsed(acceptAll); setFileFilter(currentFilter); setSelectedFile(currentFile); m_DialogType = UNHANDLED_DIALOG; removePropertyChangeListener(m_Listener); // overwrite the file? if ((result == APPROVE_OPTION) && (getOverwriteWarning()) && (getSelectedFile().exists())) { int retVal = JOptionPane.showConfirmDialog(parent, "The file '" + getSelectedFile() + "' already exists - overwrite it?"); if (retVal == JOptionPane.OK_OPTION) { result = APPROVE_OPTION; } else if (retVal == JOptionPane.NO_OPTION) { result = showSaveDialog(parent); } else { result = CANCEL_OPTION; } } if (result == APPROVE_OPTION) { m_LastFilter = getFileFilter(); // configureCurrentConverter(SAVER_DIALOG); // bring up options dialog? if (m_CheckBoxOptions.isSelected()) { m_EditorResult = JFileChooser.CANCEL_OPTION; m_Editor.setValue(m_CurrentConverter); PropertyDialog pd; if (PropertyDialog.getParentDialog(this) != null) { pd = new PropertyDialog(PropertyDialog.getParentDialog(this), m_Editor); } else { pd = new PropertyDialog(PropertyDialog.getParentFrame(this), m_Editor); } pd.setVisible(true); result = m_EditorResult; // configureCurrentConverter(SAVER_DIALOG); } } return result; } /** * returns the loader that was chosen by the user, can be null in case the * user aborted the dialog or the save dialog was shown. * * @return the chosen loader, if any */ public AbstractFileLoader getLoader() { configureCurrentConverter(LOADER_DIALOG); if (m_CurrentConverter instanceof AbstractFileSaver) { return null; } else { return (AbstractFileLoader) m_CurrentConverter; } } /** * returns the saver that was chosen by the user, can be null in case the user * aborted the dialog or the open dialog was shown. * * @return the chosen saver, if any */ public AbstractFileSaver getSaver() { configureCurrentConverter(SAVER_DIALOG); if (m_CurrentConverter instanceof AbstractFileLoader) { return null; } else { return (AbstractFileSaver) m_CurrentConverter; } } /** * sets the current converter according to the current filefilter. */ protected void updateCurrentConverter() { String[] extensions; Object newConverter; if (getFileFilter() == null) { return; } if (!isAcceptAllFileFilterUsed()) { // determine current converter extensions = ((ExtensionFileFilter) getFileFilter()).getExtensions(); if (m_DialogType == LOADER_DIALOG) { newConverter = ConverterUtils.getLoaderForExtension(extensions[0]); } else { newConverter = ConverterUtils.getSaverForExtension(extensions[0]); } try { if (m_CurrentConverter == null) { m_CurrentConverter = newConverter; } else { if (!m_CurrentConverter.getClass().equals(newConverter.getClass())) { m_CurrentConverter = newConverter; } } } catch (Exception e) { m_CurrentConverter = null; e.printStackTrace(); } } else { m_CurrentConverter = null; } } /** * configures the current converter. * * @param dialogType the type of dialog to configure for */ protected void configureCurrentConverter(int dialogType) { String filename; File currFile; if ((getSelectedFile() == null) || (getSelectedFile().isDirectory())) { return; } filename = getSelectedFile().getAbsolutePath(); if (m_CurrentConverter == null) { if (dialogType == LOADER_DIALOG) { m_CurrentConverter = ConverterUtils.getLoaderForFile(filename); } else if (dialogType == SAVER_DIALOG) { m_CurrentConverter = ConverterUtils.getSaverForFile(filename); } else { throw new IllegalStateException("Cannot determine loader/saver!"); } // none found? if (m_CurrentConverter == null) { return; } } try { currFile = ((FileSourcedConverter) m_CurrentConverter).retrieveFile(); if ((currFile == null) || (!currFile.getAbsolutePath().equals(filename))) { ((FileSourcedConverter) m_CurrentConverter).setFile(new File(filename)); } } catch (Exception e) { e.printStackTrace(); } } /** * For testing the file chooser. * * @param args the commandline options - ignored * @throws Exception if something goes wrong with loading/saving */ public static void main(String[] args) throws Exception { ConverterFileChooser fc; int retVal; AbstractFileLoader loader; AbstractFileSaver saver; Instances data; fc = new ConverterFileChooser(); retVal = fc.showOpenDialog(null); // load file if (retVal == ConverterFileChooser.APPROVE_OPTION) { loader = fc.getLoader(); data = loader.getDataSet(); retVal = fc.showSaveDialog(null); // save file if (retVal == ConverterFileChooser.APPROVE_OPTION) { saver = fc.getSaver(); saver.setInstances(data); saver.writeBatch(); } else { System.out.println("Saving aborted!"); } } else { System.out.println("Loading aborted!"); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/CostBenefitAnalysisPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * CostBenefitAnalysisPanel.java * Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import weka.classifiers.evaluation.ThresholdCurve; import weka.core.Attribute; import weka.core.DenseInstance; import weka.core.Instance; import weka.core.Instances; import weka.core.Utils; import weka.gui.beans.CostBenefitAnalysis; import weka.gui.visualize.PlotData2D; import weka.gui.visualize.VisualizePanel; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JSlider; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.util.ArrayList; /** * Panel for displaying the cost-benefit plots and all control widgets. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class CostBenefitAnalysisPanel extends JPanel { /** For serialization */ private static final long serialVersionUID = 5364871945448769003L; /** Displays the performance graphs(s) */ protected VisualizePanel m_performancePanel = new VisualizePanel(); /** Displays the cost/benefit (profit/loss) graph */ protected VisualizePanel m_costBenefitPanel = new VisualizePanel(); /** * The class attribute from the data that was used to generate the threshold * curve */ protected Attribute m_classAttribute; /** Data for the threshold curve */ protected PlotData2D m_masterPlot; /** Data for the cost/benefit curve */ protected PlotData2D m_costBenefit; /** The size of the points being plotted */ protected int[] m_shapeSizes; /** The index of the previous plotted point that was highlighted */ protected int m_previousShapeIndex = -1; /** The slider for adjusting the threshold */ protected JSlider m_thresholdSlider = new JSlider(0, 100, 0); protected JRadioButton m_percPop = new JRadioButton("% of Population"); protected JRadioButton m_percOfTarget = new JRadioButton( "% of Target (recall)"); protected JRadioButton m_threshold = new JRadioButton("Score Threshold"); protected JLabel m_percPopLab = new JLabel(); protected JLabel m_percOfTargetLab = new JLabel(); protected JLabel m_thresholdLab = new JLabel(); // Confusion matrix stuff protected JLabel m_conf_predictedA = new JLabel("Predicted (a)", SwingConstants.RIGHT); protected JLabel m_conf_predictedB = new JLabel("Predicted (b)", SwingConstants.RIGHT); protected JLabel m_conf_actualA = new JLabel(" Actual (a):"); protected JLabel m_conf_actualB = new JLabel(" Actual (b):"); protected ConfusionCell m_conf_aa = new ConfusionCell(); protected ConfusionCell m_conf_ab = new ConfusionCell(); protected ConfusionCell m_conf_ba = new ConfusionCell(); protected ConfusionCell m_conf_bb = new ConfusionCell(); // Cost matrix stuff protected JLabel m_cost_predictedA = new JLabel("Predicted (a)", SwingConstants.RIGHT); protected JLabel m_cost_predictedB = new JLabel("Predicted (b)", SwingConstants.RIGHT); protected JLabel m_cost_actualA = new JLabel(" Actual (a)"); protected JLabel m_cost_actualB = new JLabel(" Actual (b)"); protected JTextField m_cost_aa = new JTextField("0.0", 5); protected JTextField m_cost_ab = new JTextField("1.0", 5); protected JTextField m_cost_ba = new JTextField("1.0", 5); protected JTextField m_cost_bb = new JTextField("0.0", 5); protected JButton m_maximizeCB = new JButton("Maximize Cost/Benefit"); protected JButton m_minimizeCB = new JButton("Minimize Cost/Benefit"); protected JRadioButton m_costR = new JRadioButton("Cost"); protected JRadioButton m_benefitR = new JRadioButton("Benefit"); protected JLabel m_costBenefitL = new JLabel("Cost: ", SwingConstants.RIGHT); protected JLabel m_costBenefitV = new JLabel("0"); protected JLabel m_randomV = new JLabel("0"); protected JLabel m_gainV = new JLabel("0"); protected int m_originalPopSize; /** Population text field */ protected JTextField m_totalPopField = new JTextField(6); protected int m_totalPopPrevious; /** Classification accuracy */ protected JLabel m_classificationAccV = new JLabel("-"); // Only update curve & stats if values in cost matrix have changed protected double m_tpPrevious; protected double m_fpPrevious; protected double m_tnPrevious; protected double m_fnPrevious; /** * Inner class for handling a single cell in the confusion matrix. Displays * the value, value as a percentage of total population and graphical * depiction of percentage. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) */ protected static class ConfusionCell extends JPanel { /** For serialization */ private static final long serialVersionUID = 6148640235434494767L; private final JLabel m_conf_cell = new JLabel("-", SwingConstants.RIGHT); JLabel m_conf_perc = new JLabel("-", SwingConstants.RIGHT); private final JPanel m_percentageP; protected double m_percentage = 0; @SuppressWarnings("serial") public ConfusionCell() { setLayout(new BorderLayout()); setBorder(BorderFactory.createEtchedBorder()); add(m_conf_cell, BorderLayout.NORTH); m_percentageP = new JPanel() { @Override public void paintComponent(Graphics gx) { super.paintComponent(gx); if (m_percentage > 0) { gx.setColor(Color.BLUE); int height = this.getHeight(); double width = this.getWidth(); int barWidth = (int) (m_percentage * width); gx.fillRect(0, 0, barWidth, height); } } }; Dimension d = new Dimension(30, 5); m_percentageP.setMinimumSize(d); m_percentageP.setPreferredSize(d); JPanel percHolder = new JPanel(); percHolder.setLayout(new BorderLayout()); percHolder.add(m_percentageP, BorderLayout.CENTER); percHolder.add(m_conf_perc, BorderLayout.EAST); add(percHolder, BorderLayout.SOUTH); } /** * Set the value of a cell. * * @param cellValue the value of the cell * @param max the max (for setting value as a percentage) * @param scaleFactor scale the value by this amount * @param precision precision for the percentage value */ public void setCellValue(double cellValue, double max, double scaleFactor, int precision) { if (!Utils.isMissingValue(cellValue)) { m_percentage = cellValue / max; } else { m_percentage = 0; } m_conf_cell.setText(Utils.doubleToString((cellValue * scaleFactor), 0)); m_conf_perc.setText(Utils.doubleToString(m_percentage * 100.0, precision) + "%"); // refresh the percentage bar m_percentageP.repaint(); } } public CostBenefitAnalysisPanel() { setLayout(new BorderLayout()); m_performancePanel.setShowAttBars(false); m_performancePanel.setShowClassPanel(false); m_costBenefitPanel.setShowAttBars(false); m_costBenefitPanel.setShowClassPanel(false); Dimension size = new Dimension(500, 400); m_performancePanel.setPreferredSize(size); m_performancePanel.setMinimumSize(size); size = new Dimension(500, 400); m_costBenefitPanel.setMinimumSize(size); m_costBenefitPanel.setPreferredSize(size); m_thresholdSlider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { updateInfoForSliderValue(m_thresholdSlider.getValue() / 100.0); } }); JPanel plotHolder = new JPanel(); plotHolder.setLayout(new GridLayout(1, 2)); plotHolder.add(m_performancePanel); plotHolder.add(m_costBenefitPanel); add(plotHolder, BorderLayout.CENTER); JPanel lowerPanel = new JPanel(); lowerPanel.setLayout(new BorderLayout()); ButtonGroup bGroup = new ButtonGroup(); bGroup.add(m_percPop); bGroup.add(m_percOfTarget); bGroup.add(m_threshold); ButtonGroup bGroup2 = new ButtonGroup(); bGroup2.add(m_costR); bGroup2.add(m_benefitR); ActionListener rl = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (m_costR.isSelected()) { m_costBenefitL.setText("Cost: "); } else { m_costBenefitL.setText("Benefit: "); } double gain = Double.parseDouble(m_gainV.getText()); gain = -gain; m_gainV.setText(Utils.doubleToString(gain, 2)); } }; m_costR.addActionListener(rl); m_benefitR.addActionListener(rl); m_costR.setSelected(true); m_percPop.setSelected(true); JPanel threshPanel = new JPanel(); threshPanel.setLayout(new BorderLayout()); JPanel radioHolder = new JPanel(); radioHolder.setLayout(new FlowLayout()); radioHolder.add(m_percPop); radioHolder.add(m_percOfTarget); radioHolder.add(m_threshold); threshPanel.add(radioHolder, BorderLayout.NORTH); threshPanel.add(m_thresholdSlider, BorderLayout.SOUTH); JPanel threshInfoPanel = new JPanel(); threshInfoPanel.setLayout(new GridLayout(3, 2)); threshInfoPanel .add(new JLabel("% of Population: ", SwingConstants.RIGHT)); threshInfoPanel.add(m_percPopLab); threshInfoPanel.add(new JLabel("% of Target: ", SwingConstants.RIGHT)); threshInfoPanel.add(m_percOfTargetLab); threshInfoPanel .add(new JLabel("Score Threshold: ", SwingConstants.RIGHT)); threshInfoPanel.add(m_thresholdLab); JPanel threshHolder = new JPanel(); threshHolder.setBorder(BorderFactory.createTitledBorder("Threshold")); threshHolder.setLayout(new BorderLayout()); threshHolder.add(threshPanel, BorderLayout.CENTER); threshHolder.add(threshInfoPanel, BorderLayout.EAST); lowerPanel.add(threshHolder, BorderLayout.NORTH); // holder for the two matrixes JPanel matrixHolder = new JPanel(); matrixHolder.setLayout(new GridLayout(1, 2)); // confusion matrix JPanel confusionPanel = new JPanel(); confusionPanel.setLayout(new GridLayout(3, 3)); confusionPanel.add(m_conf_predictedA); confusionPanel.add(m_conf_predictedB); confusionPanel.add(new JLabel()); // dummy confusionPanel.add(m_conf_aa); confusionPanel.add(m_conf_ab); confusionPanel.add(m_conf_actualA); confusionPanel.add(m_conf_ba); confusionPanel.add(m_conf_bb); confusionPanel.add(m_conf_actualB); JPanel tempHolderCA = new JPanel(); tempHolderCA.setLayout(new BorderLayout()); tempHolderCA.setBorder(BorderFactory .createTitledBorder("Confusion Matrix")); tempHolderCA.add(confusionPanel, BorderLayout.CENTER); JPanel accHolder = new JPanel(); accHolder.setLayout(new FlowLayout(FlowLayout.LEFT)); accHolder.add(new JLabel("Classification Accuracy: ")); accHolder.add(m_classificationAccV); tempHolderCA.add(accHolder, BorderLayout.SOUTH); matrixHolder.add(tempHolderCA); // cost matrix JPanel costPanel = new JPanel(); costPanel.setBorder(BorderFactory.createTitledBorder("Cost Matrix")); costPanel.setLayout(new BorderLayout()); JPanel cmHolder = new JPanel(); cmHolder.setLayout(new GridLayout(3, 3)); cmHolder.add(m_cost_predictedA); cmHolder.add(m_cost_predictedB); cmHolder.add(new JLabel()); // dummy cmHolder.add(m_cost_aa); cmHolder.add(m_cost_ab); cmHolder.add(m_cost_actualA); cmHolder.add(m_cost_ba); cmHolder.add(m_cost_bb); cmHolder.add(m_cost_actualB); costPanel.add(cmHolder, BorderLayout.CENTER); FocusListener fl = new FocusListener() { @Override public void focusGained(FocusEvent e) { } @Override public void focusLost(FocusEvent e) { if (constructCostBenefitData()) { try { m_costBenefitPanel.setMasterPlot(m_costBenefit); m_costBenefitPanel.validate(); m_costBenefitPanel.repaint(); } catch (Exception ex) { ex.printStackTrace(); } updateCostBenefit(); } } }; ActionListener al = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (constructCostBenefitData()) { try { m_costBenefitPanel.setMasterPlot(m_costBenefit); m_costBenefitPanel.validate(); m_costBenefitPanel.repaint(); } catch (Exception ex) { ex.printStackTrace(); } updateCostBenefit(); } } }; m_cost_aa.addFocusListener(fl); m_cost_aa.addActionListener(al); m_cost_ab.addFocusListener(fl); m_cost_ab.addActionListener(al); m_cost_ba.addFocusListener(fl); m_cost_ba.addActionListener(al); m_cost_bb.addFocusListener(fl); m_cost_bb.addActionListener(al); m_totalPopField.addFocusListener(fl); m_totalPopField.addActionListener(al); JPanel cbHolder = new JPanel(); cbHolder.setLayout(new BorderLayout()); JPanel tempP = new JPanel(); tempP.setLayout(new GridLayout(3, 2)); tempP.add(m_costBenefitL); tempP.add(m_costBenefitV); tempP.add(new JLabel("Random: ", SwingConstants.RIGHT)); tempP.add(m_randomV); tempP.add(new JLabel("Gain: ", SwingConstants.RIGHT)); tempP.add(m_gainV); cbHolder.add(tempP, BorderLayout.NORTH); JPanel butHolder = new JPanel(); butHolder.setLayout(new GridLayout(2, 1)); butHolder.add(m_maximizeCB); butHolder.add(m_minimizeCB); m_maximizeCB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { findMaxMinCB(true); } }); m_minimizeCB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { findMaxMinCB(false); } }); cbHolder.add(butHolder, BorderLayout.SOUTH); costPanel.add(cbHolder, BorderLayout.EAST); JPanel popCBR = new JPanel(); popCBR.setLayout(new GridLayout(1, 2)); JPanel popHolder = new JPanel(); popHolder.setLayout(new FlowLayout(FlowLayout.LEFT)); popHolder.add(new JLabel("Total Population: ")); popHolder.add(m_totalPopField); JPanel radioHolder2 = new JPanel(); radioHolder2.setLayout(new FlowLayout(FlowLayout.RIGHT)); radioHolder2.add(m_costR); radioHolder2.add(m_benefitR); popCBR.add(popHolder); popCBR.add(radioHolder2); costPanel.add(popCBR, BorderLayout.SOUTH); matrixHolder.add(costPanel); lowerPanel.add(matrixHolder, BorderLayout.SOUTH); // popAccHolder.add(popHolder); // popAccHolder.add(accHolder); /* * JPanel lowerPanel2 = new JPanel(); lowerPanel2.setLayout(new * BorderLayout()); lowerPanel2.add(lowerPanel, BorderLayout.NORTH); * lowerPanel2.add(popAccHolder, BorderLayout.SOUTH); */ add(lowerPanel, BorderLayout.SOUTH); } /** * Get the master threshold plot data * * @return the master threshold data */ public PlotData2D getMasterPlot() { return m_masterPlot; } private void findMaxMinCB(boolean max) { double maxMin = (max) ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY; Instances cBCurve = m_costBenefit.getPlotInstances(); int maxMinIndex = 0; for (int i = 0; i < cBCurve.numInstances(); i++) { Instance current = cBCurve.instance(i); if (max) { if (current.value(1) > maxMin) { maxMin = current.value(1); maxMinIndex = i; } } else { if (current.value(1) < maxMin) { maxMin = current.value(1); maxMinIndex = i; } } } // set the slider to the correct position int indexOfSampleSize = m_masterPlot.getPlotInstances() .attribute(ThresholdCurve.SAMPLE_SIZE_NAME).index(); int indexOfPercOfTarget = m_masterPlot.getPlotInstances() .attribute(ThresholdCurve.RECALL_NAME).index(); int indexOfThreshold = m_masterPlot.getPlotInstances() .attribute(ThresholdCurve.THRESHOLD_NAME).index(); int indexOfMetric; if (m_percPop.isSelected()) { indexOfMetric = indexOfSampleSize; } else if (m_percOfTarget.isSelected()) { indexOfMetric = indexOfPercOfTarget; } else { indexOfMetric = indexOfThreshold; } double valueOfMetric = m_masterPlot.getPlotInstances() .instance(maxMinIndex).value(indexOfMetric); valueOfMetric *= 100.0; // set the approximate location of the slider m_thresholdSlider.setValue((int) valueOfMetric); // make sure the actual values relate to the true min/max rather // than being off due to slider location error. updateInfoGivenIndex(maxMinIndex); } private void updateCostBenefit() { double value = m_thresholdSlider.getValue() / 100.0; Instances plotInstances = m_masterPlot.getPlotInstances(); int indexOfSampleSize = m_masterPlot.getPlotInstances() .attribute(ThresholdCurve.SAMPLE_SIZE_NAME).index(); int indexOfPercOfTarget = m_masterPlot.getPlotInstances() .attribute(ThresholdCurve.RECALL_NAME).index(); int indexOfThreshold = m_masterPlot.getPlotInstances() .attribute(ThresholdCurve.THRESHOLD_NAME).index(); int indexOfMetric; if (m_percPop.isSelected()) { indexOfMetric = indexOfSampleSize; } else if (m_percOfTarget.isSelected()) { indexOfMetric = indexOfPercOfTarget; } else { indexOfMetric = indexOfThreshold; } int index = findIndexForValue(value, plotInstances, indexOfMetric); updateCBRandomGainInfo(index); } private void updateCBRandomGainInfo(int index) { double requestedPopSize = m_originalPopSize; try { requestedPopSize = Double.parseDouble(m_totalPopField.getText()); } catch (NumberFormatException e) { } double scaleFactor = requestedPopSize / m_originalPopSize; double CB = m_costBenefit.getPlotInstances().instance(index).value(1); m_costBenefitV.setText(Utils.doubleToString(CB, 2)); double totalRandomCB = 0.0; Instance first = m_masterPlot.getPlotInstances().instance(0); double totalPos = first.value(m_masterPlot.getPlotInstances() .attribute(ThresholdCurve.TRUE_POS_NAME).index()) * scaleFactor; double totalNeg = first.value(m_masterPlot.getPlotInstances().attribute( ThresholdCurve.FALSE_POS_NAME)) * scaleFactor; double posInSample = (totalPos * (Double.parseDouble(m_percPopLab .getText()) / 100.0)); double negInSample = (totalNeg * (Double.parseDouble(m_percPopLab .getText()) / 100.0)); double posOutSample = totalPos - posInSample; double negOutSample = totalNeg - negInSample; double tpCost = 0.0; try { tpCost = Double.parseDouble(m_cost_aa.getText()); } catch (NumberFormatException n) { } double fpCost = 0.0; try { fpCost = Double.parseDouble(m_cost_ba.getText()); } catch (NumberFormatException n) { } double tnCost = 0.0; try { tnCost = Double.parseDouble(m_cost_bb.getText()); } catch (NumberFormatException n) { } double fnCost = 0.0; try { fnCost = Double.parseDouble(m_cost_ab.getText()); } catch (NumberFormatException n) { } totalRandomCB += posInSample * tpCost; totalRandomCB += negInSample * fpCost; totalRandomCB += posOutSample * fnCost; totalRandomCB += negOutSample * tnCost; m_randomV.setText(Utils.doubleToString(totalRandomCB, 2)); double gain = (m_costR.isSelected()) ? totalRandomCB - CB : CB - totalRandomCB; m_gainV.setText(Utils.doubleToString(gain, 2)); // update classification rate Instance currentInst = m_masterPlot.getPlotInstances().instance(index); double tp = currentInst.value(m_masterPlot.getPlotInstances() .attribute(ThresholdCurve.TRUE_POS_NAME).index()); double tn = currentInst.value(m_masterPlot.getPlotInstances() .attribute(ThresholdCurve.TRUE_NEG_NAME).index()); m_classificationAccV.setText(Utils.doubleToString((tp + tn) / (totalPos + totalNeg) * 100.0, 4) + "%"); } private void updateInfoGivenIndex(int index) { Instances plotInstances = m_masterPlot.getPlotInstances(); int indexOfSampleSize = m_masterPlot.getPlotInstances() .attribute(ThresholdCurve.SAMPLE_SIZE_NAME).index(); int indexOfPercOfTarget = m_masterPlot.getPlotInstances() .attribute(ThresholdCurve.RECALL_NAME).index(); int indexOfThreshold = m_masterPlot.getPlotInstances() .attribute(ThresholdCurve.THRESHOLD_NAME).index(); // update labels m_percPopLab.setText(Utils.doubleToString( 100.0 * plotInstances.instance(index).value(indexOfSampleSize), 4)); m_percOfTargetLab.setText(Utils.doubleToString(100.0 * plotInstances .instance(index).value(indexOfPercOfTarget), 4)); m_thresholdLab.setText(Utils.doubleToString(plotInstances.instance(index) .value(indexOfThreshold), 4)); /* * if (m_percPop.isSelected()) { * m_percPopLab.setText(Utils.doubleToString(100.0 * value, 4)); } else if * (m_percOfTarget.isSelected()) { * m_percOfTargetLab.setText(Utils.doubleToString(100.0 * value, 4)); } * else { m_thresholdLab.setText(Utils.doubleToString(value, 4)); } */ // Update the highlighted point on the graphs */ if (m_previousShapeIndex >= 0) { m_shapeSizes[m_previousShapeIndex] = 1; } m_shapeSizes[index] = 10; m_previousShapeIndex = index; // Update the confusion matrix // double totalInstances = int tp = plotInstances.attribute(ThresholdCurve.TRUE_POS_NAME).index(); int fp = plotInstances.attribute(ThresholdCurve.FALSE_POS_NAME).index(); int tn = plotInstances.attribute(ThresholdCurve.TRUE_NEG_NAME).index(); int fn = plotInstances.attribute(ThresholdCurve.FALSE_NEG_NAME).index(); Instance temp = plotInstances.instance(index); double totalInstances = temp.value(tp) + temp.value(fp) + temp.value(tn) + temp.value(fn); // get the value out of the total pop field (if possible) double requestedPopSize = totalInstances; try { requestedPopSize = Double.parseDouble(m_totalPopField.getText()); } catch (NumberFormatException e) { } m_conf_aa.setCellValue(temp.value(tp), totalInstances, requestedPopSize / totalInstances, 2); m_conf_ab.setCellValue(temp.value(fn), totalInstances, requestedPopSize / totalInstances, 2); m_conf_ba.setCellValue(temp.value(fp), totalInstances, requestedPopSize / totalInstances, 2); m_conf_bb.setCellValue(temp.value(tn), totalInstances, requestedPopSize / totalInstances, 2); updateCBRandomGainInfo(index); repaint(); } private void updateInfoForSliderValue(double value) { int indexOfSampleSize = m_masterPlot.getPlotInstances() .attribute(ThresholdCurve.SAMPLE_SIZE_NAME).index(); int indexOfPercOfTarget = m_masterPlot.getPlotInstances() .attribute(ThresholdCurve.RECALL_NAME).index(); int indexOfThreshold = m_masterPlot.getPlotInstances() .attribute(ThresholdCurve.THRESHOLD_NAME).index(); int indexOfMetric; if (m_percPop.isSelected()) { indexOfMetric = indexOfSampleSize; } else if (m_percOfTarget.isSelected()) { indexOfMetric = indexOfPercOfTarget; } else { indexOfMetric = indexOfThreshold; } Instances plotInstances = m_masterPlot.getPlotInstances(); int index = findIndexForValue(value, plotInstances, indexOfMetric); updateInfoGivenIndex(index); } private int findIndexForValue(double value, Instances plotInstances, int indexOfMetric) { // binary search // threshold curve is sorted ascending in the threshold (thus // descending for recall and pop size) int index = -1; int lower = 0; int upper = plotInstances.numInstances() - 1; int mid = (upper - lower) / 2; boolean done = false; while (!done) { if (upper - lower <= 1) { // choose the one closest to the value double comp1 = plotInstances.instance(upper).value(indexOfMetric); double comp2 = plotInstances.instance(lower).value(indexOfMetric); if (Math.abs(comp1 - value) < Math.abs(comp2 - value)) { index = upper; } else { index = lower; } break; } double comparisonVal = plotInstances.instance(mid).value(indexOfMetric); if (value > comparisonVal) { if (m_threshold.isSelected()) { lower = mid; mid += (upper - lower) / 2; } else { upper = mid; mid -= (upper - lower) / 2; } } else if (value < comparisonVal) { if (m_threshold.isSelected()) { upper = mid; mid -= (upper - lower) / 2; } else { lower = mid; mid += (upper - lower) / 2; } } else { index = mid; done = true; } } // now check for ties in the appropriate direction if (!m_threshold.isSelected()) { while (index + 1 < plotInstances.numInstances()) { if (plotInstances.instance(index + 1).value(indexOfMetric) == plotInstances .instance(index).value(indexOfMetric)) { index++; } else { break; } } } else { while (index - 1 >= 0) { if (plotInstances.instance(index - 1).value(indexOfMetric) == plotInstances .instance(index).value(indexOfMetric)) { index--; } else { break; } } } return index; } /** * Set the threshold data for the panel to use. * * @param data PlotData2D object encapsulating the threshold data. * @param classAtt the class attribute from the original data used to * generate the threshold data. * @throws Exception if something goes wrong. */ public synchronized void setDataSet(PlotData2D data, Attribute classAtt) throws Exception { // make a copy of the PlotData2D object m_masterPlot = new PlotData2D(data.getPlotInstances()); boolean[] connectPoints = new boolean[m_masterPlot.getPlotInstances() .numInstances()]; for (int i = 1; i < connectPoints.length; i++) { connectPoints[i] = true; } m_masterPlot.setConnectPoints(connectPoints); m_masterPlot.m_alwaysDisplayPointsOfThisSize = 10; setClassForConfusionMatrix(classAtt); m_performancePanel.setMasterPlot(m_masterPlot); m_performancePanel.validate(); m_performancePanel.repaint(); m_shapeSizes = new int[m_masterPlot.getPlotInstances().numInstances()]; for (int i = 0; i < m_shapeSizes.length; i++) { m_shapeSizes[i] = 1; } m_masterPlot.setShapeSize(m_shapeSizes); constructCostBenefitData(); m_costBenefitPanel.setMasterPlot(m_costBenefit); m_costBenefitPanel.validate(); m_costBenefitPanel.repaint(); m_totalPopPrevious = 0; m_fpPrevious = 0; m_tpPrevious = 0; m_tnPrevious = 0; m_fnPrevious = 0; m_previousShapeIndex = -1; // set the total population size Instance first = m_masterPlot.getPlotInstances().instance(0); double totalPos = first.value(m_masterPlot.getPlotInstances() .attribute(ThresholdCurve.TRUE_POS_NAME).index()); double totalNeg = first.value(m_masterPlot.getPlotInstances().attribute( ThresholdCurve.FALSE_POS_NAME)); m_originalPopSize = (int) (totalPos + totalNeg); m_totalPopField.setText("" + m_originalPopSize); m_performancePanel.setYIndex(5); m_performancePanel.setXIndex(10); m_costBenefitPanel.setXIndex(0); m_costBenefitPanel.setYIndex(1); // System.err.println(m_masterPlot.getPlotInstances()); updateInfoForSliderValue(m_thresholdSlider.getValue() / 100.0); } private void setClassForConfusionMatrix(Attribute classAtt) { m_classAttribute = classAtt; m_conf_actualA.setText(" Actual (a): " + classAtt.value(0)); m_conf_actualA.setToolTipText(classAtt.value(0)); String negClasses = ""; for (int i = 1; i < classAtt.numValues(); i++) { negClasses += classAtt.value(i); if (i < classAtt.numValues() - 1) { negClasses += ","; } } m_conf_actualB.setText(" Actual (b): " + negClasses); m_conf_actualB.setToolTipText(negClasses); } private boolean constructCostBenefitData() { double tpCost = 0.0; try { tpCost = Double.parseDouble(m_cost_aa.getText()); } catch (NumberFormatException n) { } double fpCost = 0.0; try { fpCost = Double.parseDouble(m_cost_ba.getText()); } catch (NumberFormatException n) { } double tnCost = 0.0; try { tnCost = Double.parseDouble(m_cost_bb.getText()); } catch (NumberFormatException n) { } double fnCost = 0.0; try { fnCost = Double.parseDouble(m_cost_ab.getText()); } catch (NumberFormatException n) { } double requestedPopSize = m_originalPopSize; try { requestedPopSize = Double.parseDouble(m_totalPopField.getText()); } catch (NumberFormatException e) { } double scaleFactor = 1.0; if (m_originalPopSize != 0) { scaleFactor = requestedPopSize / m_originalPopSize; } if (tpCost == m_tpPrevious && fpCost == m_fpPrevious && tnCost == m_tnPrevious && fnCost == m_fnPrevious && requestedPopSize == m_totalPopPrevious) { return false; } // First construct some Instances for the curve ArrayList<Attribute> fv = new ArrayList<Attribute>(); fv.add(new Attribute("Sample Size")); fv.add(new Attribute("Cost/Benefit")); fv.add(new Attribute("Threshold")); Instances costBenefitI = new Instances("Cost/Benefit Curve", fv, 100); // process the performance data to make this curve Instances performanceI = m_masterPlot.getPlotInstances(); for (int i = 0; i < performanceI.numInstances(); i++) { Instance current = performanceI.instance(i); double[] vals = new double[3]; vals[0] = current.value(10); // sample size vals[1] = (current.value(0) * tpCost + current.value(1) * fnCost + current.value(2) * fpCost + current.value(3) * tnCost) * scaleFactor; vals[2] = current.value(current.numAttributes() - 1); Instance newInst = new DenseInstance(1.0, vals); costBenefitI.add(newInst); } costBenefitI.compactify(); // now set up the plot data m_costBenefit = new PlotData2D(costBenefitI); m_costBenefit.m_alwaysDisplayPointsOfThisSize = 10; m_costBenefit.setPlotName("Cost/benefit curve"); boolean[] connectPoints = new boolean[costBenefitI.numInstances()]; for (int i = 0; i < connectPoints.length; i++) { connectPoints[i] = true; } try { m_costBenefit.setConnectPoints(connectPoints); m_costBenefit.setShapeSize(m_shapeSizes); } catch (Exception ex) { // ignore } m_tpPrevious = tpCost; m_fpPrevious = fpCost; m_tnPrevious = tnCost; m_fnPrevious = fnCost; return true; } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/CostMatrixEditor.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * CostMatrixEditor.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Graphics; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Insets; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.beans.PropertyEditor; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.Reader; import java.io.Writer; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.AbstractTableModel; import weka.classifiers.CostMatrix; /** * Class for editing CostMatrix objects. Brings up a custom editing panel with * which the user can edit the matrix interactively, as well as save load cost * matrices from files. * * @author Richard Kirkby (rkirkby@cs.waikato.ac.nz) * @version $Revision$ */ public class CostMatrixEditor implements PropertyEditor { /** The cost matrix being edited */ private CostMatrix m_matrix; /** A helper class for notifying listeners */ private final PropertyChangeSupport m_propSupport; /** An instance of the custom editor */ private final CustomEditor m_customEditor; /** The file chooser for the user to select cost files to save and load */ private final JFileChooser m_fileChooser = new JFileChooser(new File( System.getProperty("user.dir"))); /** * This class wraps around the cost matrix presenting it as a TableModel so * that it can be displayed and edited in a JTable. */ private class CostMatrixTableModel extends AbstractTableModel { /** for serialization */ static final long serialVersionUID = -2762326138357037181L; /** * Gets the number of rows in the matrix. Cost matrices are square so it is * the same as the column count, i.e. the size of the matrix. * * @return the row count */ @Override public int getRowCount() { return m_matrix.size(); } /** * Gets the number of columns in the matrix. Cost matrices are square so it * is the same as the row count, i.e. the size of the matrix. * * @return the row count */ @Override public int getColumnCount() { return m_matrix.size(); } /** * Returns a value at the specified position in the cost matrix. * * @param row the row position * @param column the column position * @return the value */ @Override public Object getValueAt(int row, int column) { // return new Double(m_matrix.getElement(row, column)); try { return m_matrix.getCell(row, column); } catch (Exception ex) { ex.printStackTrace(); } return new Double(0.0); } /** * Sets a value at a specified position in the cost matrix. * * @param aValue the new value (should be of type Double). * @param rowIndex the row position * @param columnIndex the column position */ @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { // double value = ((Double) aValue).doubleValue(); // m_matrix.setElement(rowIndex, columnIndex, value); // try to parse it as a double first Double val; try { val = new Double(((String) aValue)); } catch (Exception ex) { val = null; } if (val == null) { m_matrix.setCell(rowIndex, columnIndex, aValue); } else { m_matrix.setCell(rowIndex, columnIndex, val); } fireTableCellUpdated(rowIndex, columnIndex); } /** * Indicates whether a cell in the table is editable. In this case all cells * are editable so true is always returned. * * @param rowIndex the row position * @param columnIndex the column position * @return true */ @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return true; } /** * Indicates the class of the objects within a column of the table. In this * case all columns in the cost matrix consist of double values so * Double.class is always returned. * * @param columnIndex the column position * @return Double.class */ @Override public Class<?> getColumnClass(int columnIndex) { return Object.class; } } /** * This class presents a GUI for editing the cost matrix, and saving and * loading from files. */ private class CustomEditor extends JPanel implements ActionListener, TableModelListener { /** for serialization */ static final long serialVersionUID = -2931593489871197274L; /** The table model of the cost matrix being edited */ private final CostMatrixTableModel m_tableModel; /** The button for setting default matrix values */ private final JButton m_defaultButton; /** The button for opening a cost matrix from a file */ private final JButton m_openButton; /** The button for saving a cost matrix to a file */ private final JButton m_saveButton; /** The field for changing the size of the cost matrix */ private final JTextField m_classesField; /** The button for resizing a matrix */ private final JButton m_resizeButton; /** * Constructs a new CustomEditor. * */ public CustomEditor() { // set up the file chooser m_fileChooser.setFileFilter(new ExtensionFileFilter( CostMatrix.FILE_EXTENSION, "Cost files")); m_fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); // create the buttons + field m_defaultButton = new JButton("Defaults"); m_openButton = new JButton("Open..."); m_saveButton = new JButton("Save..."); m_resizeButton = new JButton("Resize"); m_classesField = new JTextField("" + m_matrix.size()); m_defaultButton.addActionListener(this); m_openButton.addActionListener(this); m_saveButton.addActionListener(this); m_resizeButton.addActionListener(this); m_classesField.addActionListener(this); // lay out the GUI JPanel classesPanel = new JPanel(); classesPanel.setLayout(new GridLayout(1, 2, 0, 0)); classesPanel.add(new JLabel("Classes:", SwingConstants.RIGHT)); classesPanel.add(m_classesField); JPanel rightPanel = new JPanel(); GridBagLayout gridBag = new GridBagLayout(); GridBagConstraints gbc = new GridBagConstraints(); rightPanel.setLayout(gridBag); gbc.gridx = 0; gbc.gridy = GridBagConstraints.RELATIVE; gbc.insets = new Insets(2, 10, 2, 10); gbc.fill = GridBagConstraints.HORIZONTAL; gridBag.setConstraints(m_defaultButton, gbc); rightPanel.add(m_defaultButton); gridBag.setConstraints(m_openButton, gbc); rightPanel.add(m_openButton); gridBag.setConstraints(m_saveButton, gbc); rightPanel.add(m_saveButton); gridBag.setConstraints(classesPanel, gbc); rightPanel.add(classesPanel); gridBag.setConstraints(m_resizeButton, gbc); rightPanel.add(m_resizeButton); JPanel fill = new JPanel(); gbc.weightx = 1.0; gbc.weighty = 1.0; gbc.fill = GridBagConstraints.BOTH; gridBag.setConstraints(fill, gbc); rightPanel.add(fill); m_tableModel = new CostMatrixTableModel(); m_tableModel.addTableModelListener(this); JTable matrixTable = new JTable(m_tableModel); setLayout(new BorderLayout()); add(matrixTable, BorderLayout.CENTER); add(rightPanel, BorderLayout.EAST); } /** * Responds to the user perfoming an action. * * @param e the action event that occured */ @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == m_defaultButton) { m_matrix.initialize(); matrixChanged(); } else if (e.getSource() == m_openButton) { openMatrix(); } else if (e.getSource() == m_saveButton) { saveMatrix(); } else if ((e.getSource() == m_classesField) || (e.getSource() == m_resizeButton)) { try { int newNumClasses = Integer.parseInt(m_classesField.getText()); if (newNumClasses > 0 && newNumClasses != m_matrix.size()) { setValue(new CostMatrix(newNumClasses)); } } catch (Exception ex) { } } } /** * Responds to a change in the cost matrix table. * * @param e the tabel model event that occured */ @Override public void tableChanged(TableModelEvent e) { m_propSupport.firePropertyChange(null, null, null); } /** * Responds to a change in structure of the matrix being edited. * */ public void matrixChanged() { m_tableModel.fireTableStructureChanged(); m_classesField.setText("" + m_matrix.size()); } /** * Prompts the user to open a matrix, and attemps to load it. * */ private void openMatrix() { int returnVal = m_fileChooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File selectedFile = m_fileChooser.getSelectedFile(); Reader reader = null; try { reader = new BufferedReader(new FileReader(selectedFile)); m_matrix = new CostMatrix(reader); reader.close(); matrixChanged(); } catch (Exception ex) { JOptionPane.showMessageDialog(this, "Error reading file '" + selectedFile.getName() + "':\n" + ex.getMessage(), "Load failed", JOptionPane.ERROR_MESSAGE); System.out.println(ex.getMessage()); } } } /** * Prompts the user to save a matrix, and attemps to save it. * */ private void saveMatrix() { int returnVal = m_fileChooser.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File selectedFile = m_fileChooser.getSelectedFile(); // append extension if not already present if (!selectedFile.getName().toLowerCase() .endsWith(CostMatrix.FILE_EXTENSION)) { selectedFile = new File(selectedFile.getParent(), selectedFile.getName() + CostMatrix.FILE_EXTENSION); } Writer writer = null; try { writer = new BufferedWriter(new FileWriter(selectedFile)); m_matrix.write(writer); writer.close(); } catch (Exception ex) { JOptionPane.showMessageDialog(this, "Error writing file '" + selectedFile.getName() + "':\n" + ex.getMessage(), "Save failed", JOptionPane.ERROR_MESSAGE); System.out.println(ex.getMessage()); } } } } /** * Constructs a new CostMatrixEditor. * */ public CostMatrixEditor() { m_matrix = new CostMatrix(2); m_propSupport = new PropertyChangeSupport(this); m_customEditor = new CustomEditor(); } /** * Sets the value of the CostMatrix to be edited. * * @param value a CostMatrix object to be edited */ @Override public void setValue(Object value) { m_matrix = (CostMatrix) value; m_customEditor.matrixChanged(); } /** * Gets the cost matrix that is being edited. * * @return the edited CostMatrix object */ @Override public Object getValue() { return m_matrix; } /** * Indicates whether the object can be represented graphically. In this case * it can. * * @return true */ @Override public boolean isPaintable() { return true; } /** * Paints a graphical representation of the object. For the cost matrix it * prints out the text "X x X matrix", where X is the size of the matrix. * * @param gfx the graphics context to draw the representation to * @param box the bounds within which the representation should fit. */ @Override public void paintValue(Graphics gfx, Rectangle box) { gfx.drawString(m_matrix.size() + " x " + m_matrix.size() + " cost matrix", box.x, box.y + box.height); } /** * Returns the Java code that generates an object the same as the one being * edited. Unfortunately this can't be done in a single line of code, so the * code returned will only build a default cost matrix of the same size. * * @return the initialization string */ @Override public String getJavaInitializationString() { return ("new CostMatrix(" + m_matrix.size() + ")"); } /** * Some objects can be represented as text, but a cost matrix cannot. * * @return null */ @Override public String getAsText() { return null; } /** * Some objects can be represented as text, but a cost matrix cannot. * * @param text ignored * @throws IllegalArgumentException always throws an IllegalArgumentException */ @Override public void setAsText(String text) { throw new IllegalArgumentException("CostMatrixEditor: " + "CostMatrix properties cannot be " + "expressed as text"); } /** * Some objects can return tags, but a cost matrix cannot. * * @return null */ @Override public String[] getTags() { return null; } /** * Gets a GUI component with which the user can edit the cost matrix. * * @return an editor GUI component */ @Override public Component getCustomEditor() { return m_customEditor; } /** * Indicates whether the cost matrix can be edited in a GUI, which it can. * * @return true */ @Override public boolean supportsCustomEditor() { return true; } /** * Adds an object to the list of those that wish to be informed when the cost * matrix changes. * * @param listener a new listener to add to the list */ @Override public void addPropertyChangeListener(PropertyChangeListener listener) { m_propSupport.addPropertyChangeListener(listener); } /** * Removes an object from the list of those that wish to be informed when the * cost matrix changes. * * @param listener the listener to remove from the list */ @Override public void removePropertyChangeListener(PropertyChangeListener listener) { m_propSupport.removePropertyChangeListener(listener); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/CustomPanelSupplier.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * CustomPanelSupplier.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import javax.swing.JPanel; /** * An interface for objects that are capable of supplying their own * custom GUI components. The original purpose for this interface is * to provide a mechanism allowing the GenericObjectEditor to override * the standard PropertyPanel GUI. * * @author Richard Kirkby (rkirkby@cs.waikato.ac.nz) * @version $Revision$ */ public interface CustomPanelSupplier { /** * Gets the custom panel for the object. * * @return the custom JPanel */ JPanel getCustomPanel(); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/DatabaseConnectionDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * DatabaseConnectionDialog.java * Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Frame; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.SwingConstants; /** * A dialog to enter URL, username and password for a database connection. * * @author Dale Fletcher (dale@cs.waikato.ac.nz) * @version $Revision$ */ public class DatabaseConnectionDialog extends JDialog { /** for serialization */ private static final long serialVersionUID = -1081946748666245054L; /* URL field and label */ protected JTextField m_DbaseURLText; protected JLabel m_DbaseURLLab; /* Username field and label */ protected JTextField m_UserNameText; protected JLabel m_UserNameLab; /* Password field and label */ protected JPasswordField m_PasswordText; protected JLabel m_PasswordLab; /* Debug checkbox and label */ protected JCheckBox m_DebugCheckBox; protected JLabel m_DebugLab; /* whether dialog was cancel'ed or OK'ed */ protected int m_returnValue; /** * Create database connection dialog. * * @param parentFrame the parent frame of the dialog */ public DatabaseConnectionDialog(Frame parentFrame) { this(parentFrame, "", ""); } /** * Create database connection dialog. * * @param parentFrame the parent frame of the dialog * @param url initial text for URL field * @param uname initial text for username field */ public DatabaseConnectionDialog(Frame parentFrame, String url, String uname) { this(parentFrame, url, uname, true); } /** * Create database connection dialog. * * @param parentFrame the parent frame of the dialog * @param url initial text for URL field * @param uname initial text for username field * @param debug whether to display the debug checkbox */ public DatabaseConnectionDialog(Frame parentFrame, String url, String uname, boolean debug) { super(parentFrame,"Database Connection Parameters", true); DbConnectionDialog(url, uname, debug); } /** * Returns URL from dialog * * @return URL string */ public String getURL(){ return(m_DbaseURLText.getText()); } /** * Returns Username from dialog * * @return Username string */ public String getUsername(){ return(m_UserNameText.getText()); } /** * Returns password from dialog * * @return Password string */ public String getPassword(){ return(new String(m_PasswordText.getPassword())); } /** * Returns the debug flag * * @return true if debugging should be enabled */ public boolean getDebug() { return m_DebugCheckBox.isSelected(); } /** * Returns which of OK or cancel was clicked from dialog * * @return either JOptionPane.OK_OPTION or JOptionPane.CLOSED_OPTION */ public int getReturnValue(){ return(m_returnValue); } /** * Display the database connection dialog * * @param url initial text for URL field * @param uname initial text for username field */ public void DbConnectionDialog(String url, String uname) { DbConnectionDialog(url, uname, true); } /** * Display the database connection dialog * * @param url initial text for URL field * @param uname initial text for username field * @param debug whether to display the debug checkbox */ public void DbConnectionDialog(String url, String uname, boolean debug) { JPanel DbP = new JPanel(); if (debug) DbP.setLayout(new GridLayout(5, 1)); else DbP.setLayout(new GridLayout(4, 1)); m_DbaseURLText = new JTextField(url,50); m_DbaseURLLab = new JLabel(" Database URL", SwingConstants.LEFT); m_DbaseURLLab.setFont(new Font("Monospaced", Font.PLAIN, 12)); m_DbaseURLLab.setDisplayedMnemonic('D'); m_DbaseURLLab.setLabelFor(m_DbaseURLText); m_UserNameText = new JTextField(uname,25); m_UserNameLab = new JLabel(" Username ", SwingConstants.LEFT); m_UserNameLab.setFont(new Font("Monospaced", Font.PLAIN, 12)); m_UserNameLab.setDisplayedMnemonic('U'); m_UserNameLab.setLabelFor(m_UserNameText); m_PasswordText = new JPasswordField(25); m_PasswordLab = new JLabel(" Password ", SwingConstants.LEFT); m_PasswordLab.setFont(new Font("Monospaced", Font.PLAIN, 12)); m_PasswordLab.setDisplayedMnemonic('P'); m_PasswordLab.setLabelFor(m_PasswordText); m_DebugCheckBox = new JCheckBox(); m_DebugLab = new JLabel(" Debug ", SwingConstants.LEFT); m_DebugLab.setFont(new Font("Monospaced", Font.PLAIN, 12)); m_DebugLab.setDisplayedMnemonic('P'); m_DebugLab.setLabelFor(m_DebugCheckBox); JPanel urlP = new JPanel(); urlP.setLayout(new FlowLayout(FlowLayout.LEFT)); urlP.add(m_DbaseURLLab); urlP.add(m_DbaseURLText); DbP.add(urlP); JPanel usernameP = new JPanel(); usernameP.setLayout(new FlowLayout(FlowLayout.LEFT)); usernameP.add(m_UserNameLab); usernameP.add(m_UserNameText); DbP.add(usernameP); JPanel passwordP = new JPanel(); passwordP.setLayout(new FlowLayout(FlowLayout.LEFT)); passwordP.add(m_PasswordLab); passwordP.add(m_PasswordText); DbP.add(passwordP); if (debug) { JPanel debugP = new JPanel(); debugP.setLayout(new FlowLayout(FlowLayout.LEFT)); debugP.add(m_DebugLab); debugP.add(m_DebugCheckBox); DbP.add(debugP); } JPanel buttonsP = new JPanel(); buttonsP.setLayout(new FlowLayout()); JButton ok,cancel; buttonsP.add(ok = new JButton("OK")); buttonsP.add(cancel=new JButton("Cancel")); ok.setMnemonic('O'); ok.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ m_returnValue=JOptionPane.OK_OPTION; DatabaseConnectionDialog.this.dispose(); } }); cancel.setMnemonic('C'); cancel.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ m_returnValue=JOptionPane.CLOSED_OPTION; DatabaseConnectionDialog.this.dispose(); } }); // Listen for window close events addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { System.err.println("Cancelled!!"); m_returnValue = JOptionPane.CLOSED_OPTION; } }); DbP.add(buttonsP); this.getContentPane().add(DbP,BorderLayout.CENTER); this.pack(); getRootPane().setDefaultButton(ok); setResizable(false); } /** * for testing only */ public static void main(String[] args){ DatabaseConnectionDialog dbd= new DatabaseConnectionDialog(null,"URL","username"); dbd.setVisible(true); System.out.println(dbd.getReturnValue()+":"+dbd.getUsername()+":"+dbd.getPassword()+":"+dbd.getURL()); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/DocumentPrinting.java
/* * DocumentPrinting.java (original classname: PrintMe) * (C) Jan Michael Soan (http://it.toolbox.com/wiki/index.php/How_to_print_in_Java) * (C) 2009 University of Waikato, Hamilton NewZealand */ package weka.gui; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.Shape; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import javax.swing.JTextPane; import javax.swing.text.Document; import javax.swing.text.View; /** * DocumentPrinting is a class that lets you print documents on * the fly for free ;) Printing in JDK 1.2 - 1.5 is hard. * With this, you just simply call it in your application * and add your text component like JTextPane: * <pre> * new DocumentPrinting().print(YourJTextComponent); * </pre> * Reminder: Just make sure there is a text on your component ;P * <pre> * Author : Jan Michael Soan * WebSite: http://www.jmsoan.com * Date : 04/17/2004 * Time : 2:20 PM * </pre> * * Found on <a href="http://it.toolbox.com/wiki/index.php/How_to_print_in_Java" target="_blank">Toolbox</a> * (<a href="http://www.toolbox.com/TermsofUse.aspx" target="_blank">Terms of Use</a>). * * @author Jan Michael Soan (<a href="http://it.toolbox.com/wiki/index.php/How_to_print_in_Java" target="_blank">original code</a>) * @author FracPete (fracpete at waikato dot ac dot nz) */ public class DocumentPrinting implements Printable { /** the current page. */ protected int m_CurrentPage = -1; /** the JTextPane which content is to be printed. */ protected JTextPane m_PrintPane; /** the page end. */ protected double m_PageEndY = 0; /** the page start. */ protected double m_PageStartY = 0; /** whether to scale the width to fit. */ protected boolean m_ScaleWidthToFit = true; /** the pageformat. */ protected PageFormat m_PageFormat; /** the printer job. */ protected PrinterJob m_PrinterJob; /** * Initializes the printing. */ public DocumentPrinting() { m_PrintPane = new JTextPane(); m_PageFormat = new PageFormat(); m_PrinterJob = PrinterJob.getPrinterJob(); } /** * Brings up the page dialog. */ protected void pageDialog() { m_PageFormat = m_PrinterJob.pageDialog(m_PageFormat); } /** * Prints the page. * * @param graphics the graphics context * @param pageFormat the format of the page * @param pageIndex the page index * @return either NO_SUCH_PAGE or PAGE_EXISTS * @see Printable#NO_SUCH_PAGE * @see Printable#PAGE_EXISTS */ public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) { double scale = 1.0; Graphics2D graphics2D; View rootView; graphics2D = (Graphics2D) graphics; m_PrintPane.setSize((int) pageFormat.getImageableWidth(),Integer.MAX_VALUE); m_PrintPane.validate(); rootView = m_PrintPane.getUI().getRootView(m_PrintPane); if ((m_ScaleWidthToFit) && (m_PrintPane.getMinimumSize().getWidth() > pageFormat.getImageableWidth())) { scale = pageFormat.getImageableWidth()/ m_PrintPane.getMinimumSize().getWidth(); graphics2D.scale(scale,scale); } graphics2D.setClip( (int) (pageFormat.getImageableX()/scale), (int) (pageFormat.getImageableY()/scale), (int) (pageFormat.getImageableWidth()/scale), (int) (pageFormat.getImageableHeight()/scale)); if (pageIndex > m_CurrentPage) { m_CurrentPage = pageIndex; m_PageStartY += m_PageEndY; m_PageEndY = graphics2D.getClipBounds().getHeight(); } graphics2D.translate( graphics2D.getClipBounds().getX(), graphics2D.getClipBounds().getY()); Rectangle allocation = new Rectangle( 0, (int) -m_PageStartY, (int) (m_PrintPane.getMinimumSize().getWidth()), (int) (m_PrintPane.getPreferredSize().getHeight())); if (printView(graphics2D,allocation,rootView)) { return Printable.PAGE_EXISTS; } else { m_PageStartY = 0; m_PageEndY = 0; m_CurrentPage = -1; return Printable.NO_SUCH_PAGE; } } /** * Prints the document in the JTextPane. * * @param pane the document to print */ public void print(JTextPane pane) { setDocument(pane); printDialog(); } /** * Shows the print dialog. */ public void printDialog() { if (m_PrinterJob.printDialog()) { m_PrinterJob.setPrintable(this,m_PageFormat); try { m_PrinterJob.print(); } catch (PrinterException printerException) { m_PageStartY = 0; m_PageEndY = 0; m_CurrentPage = -1; System.out.println("Error Printing Document"); } } } /** * Shows a print view. * * @param graphics2D the graphics context * @param allocation the allocation * @param view the view * @return true if the page exists */ protected boolean printView(Graphics2D graphics2D, Shape allocation, View view) { boolean pageExists = false; Rectangle clipRectangle = graphics2D.getClipBounds(); Shape childAllocation; View childView; if (view.getViewCount() > 0) { for (int i = 0; i < view.getViewCount(); i++) { childAllocation = view.getChildAllocation(i,allocation); if (childAllocation != null) { childView = view.getView(i); if (printView(graphics2D,childAllocation,childView)) { pageExists = true; } } } } else { if (allocation.getBounds().getMaxY() >= clipRectangle.getY()) { pageExists = true; if ((allocation.getBounds().getHeight() > clipRectangle.getHeight()) && (allocation.intersects(clipRectangle))) { view.paint(graphics2D,allocation); } else { if (allocation.getBounds().getY() >= clipRectangle.getY()) { if (allocation.getBounds().getMaxY() <= clipRectangle.getMaxY()) { view.paint(graphics2D,allocation); } else { if (allocation.getBounds().getY() < m_PageEndY) { m_PageEndY = allocation.getBounds().getY(); } } } } } } return pageExists; } /** * Sets the content type. * * @param type the content type */ public void setContentType(String type) { m_PrintPane.setContentType(type); } /** * Returns the document to print. * * @return the document or null */ public Document getDocument() { if (m_PrintPane != null) return m_PrintPane.getDocument(); else return null; } /** * Sets the document from the given JTextPane. * * @param pane the JTextPane to get the document from */ public void setDocument(JTextPane pane) { m_PrintPane = new JTextPane(); setDocument(pane.getContentType(), pane.getDocument()); } /** * Sets the document and the according content type. * * @param type the content type * @param document the document to print */ public void setDocument(String type, Document document) { setContentType(type); m_PrintPane.setDocument(document); } /** * Sets whether to scale the width to fit. * * @param scaleWidth if true then the width will be scaled */ public void setScaleWidthToFit(boolean scaleWidth) { m_ScaleWidthToFit = scaleWidth; } /** * Returns whether the width is to be scaled. * * @return true if scaled */ public boolean getScaleWidthToFit() { return m_ScaleWidthToFit; } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/ETable.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package weka.gui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.MouseEvent; import javax.swing.BorderFactory; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JViewport; import javax.swing.SwingConstants; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; /** * A better-looking table than JTable. In particular, on Mac OS this looks more * like a Cocoa table than the default Aqua LAF manages. * * @author Elliott Hughes */ public class ETable extends JTable { /** * For serialization */ private static final long serialVersionUID = -3028630226368293049L; private final Color MAC_FOCUSED_SELECTED_CELL_HORIZONTAL_LINE_COLOR = new Color(0x7daaea); private final Color MAC_UNFOCUSED_SELECTED_CELL_HORIZONTAL_LINE_COLOR = new Color(0xe0e0e0); private final Color MAC_UNFOCUSED_SELECTED_CELL_BACKGROUND_COLOR = new Color( 0xc0c0c0); private final Color MAC_FOCUSED_UNSELECTED_VERTICAL_LINE_COLOR = new Color( 0xd9d9d9); private final Color MAC_FOCUSED_SELECTED_VERTICAL_LINE_COLOR = new Color( 0x346dbe); private final Color MAC_UNFOCUSED_UNSELECTED_VERTICAL_LINE_COLOR = new Color( 0xd9d9d9); private final Color MAC_UNFOCUSED_SELECTED_VERTICAL_LINE_COLOR = new Color( 0xacacac); private final Color MAC_OS_ALTERNATE_ROW_COLOR = new Color(0.92f, 0.95f, 0.99f); public ETable() { // Although it's the JTable default, most systems' tables don't draw a grid // by default. // Worse, it's not easy (or possible?) for us to take over grid painting // ourselves for those LAFs (Metal, for example) that do paint grids. // The Aqua and GTK LAFs ignore the grid settings anyway, so this causes no // change there. setShowGrid(false); // Tighten the cells up, and enable the manual painting of the vertical grid // lines. setIntercellSpacing(new Dimension()); // Table column re-ordering is too badly implemented to enable. getTableHeader().setReorderingAllowed(false); if (System.getProperty("os.name").contains("Mac")) { // Work-around for Apple 4352937. JLabel.class.cast(getTableHeader().getDefaultRenderer()) .setHorizontalAlignment(SwingConstants.LEADING); // Use an iTunes-style vertical-only "grid". setShowHorizontalLines(false); setShowVerticalLines(true); } } /** * Paints empty rows too, after letting the UI delegate do its painting. */ @Override public void paint(Graphics g) { super.paint(g); paintEmptyRows(g); } /** * Paints the backgrounds of the implied empty rows when the table model is * insufficient to fill all the visible area available to us. We don't involve * cell renderers, because we have no data. */ protected void paintEmptyRows(Graphics g) { final int rowCount = getRowCount(); final Rectangle clip = g.getClipBounds(); final int height = clip.y + clip.height; if (rowCount * rowHeight < height) { for (int i = rowCount; i <= height / rowHeight; ++i) { g.setColor(colorForRow(i)); g.fillRect(clip.x, i * rowHeight, clip.width, rowHeight); } // Mac OS' Aqua LAF never draws vertical grid lines, so we have to draw // them ourselves. if (System.getProperty("os.name").contains("Mac") && getShowVerticalLines()) { g.setColor(MAC_UNFOCUSED_UNSELECTED_VERTICAL_LINE_COLOR); TableColumnModel columnModel = getColumnModel(); int x = 0; for (int i = 0; i < columnModel.getColumnCount(); ++i) { TableColumn column = columnModel.getColumn(i); x += column.getWidth(); g.drawLine(x - 1, rowCount * rowHeight, x - 1, height); } } } } /** * Changes the behavior of a table in a JScrollPane to be more like the * behavior of JList, which expands to fill the available space. JTable * normally restricts its size to just what's needed by its model. */ @Override public boolean getScrollableTracksViewportHeight() { if (getParent() instanceof JViewport) { JViewport parent = (JViewport) getParent(); return (parent.getHeight() > getPreferredSize().height); } return false; } /** * Returns the appropriate background color for the given row. */ protected Color colorForRow(int row) { return (row % 2 == 0) ? alternateRowColor() : getBackground(); } private Color alternateRowColor() { return UIManager.getLookAndFeel().getClass().getName().contains("GTK") ? Color.WHITE : MAC_OS_ALTERNATE_ROW_COLOR; } /** * Shades alternate rows in different colors. */ @Override public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { Component c = super.prepareRenderer(renderer, row, column); boolean focused = hasFocus(); boolean selected = isCellSelected(row, column); if (selected) { if (System.getProperty("os.name").contains("Mac") && focused == false) { // Native Mac OS renders the selection differently if the table doesn't // have the focus. // The Mac OS LAF doesn't imitate this for us. c.setBackground(MAC_UNFOCUSED_SELECTED_CELL_BACKGROUND_COLOR); c.setForeground(UIManager.getColor("Table.foreground")); } else { c.setBackground(UIManager.getColor("Table.selectionBackground")); c.setForeground(UIManager.getColor("Table.selectionForeground")); } } else { // Outside of selected rows, we want to alternate the background color. c.setBackground(colorForRow(row)); c.setForeground(UIManager.getColor("Table.foreground")); } if (c instanceof JComponent) { JComponent jc = (JComponent) c; // The Java 6 GTK LAF JCheckBox doesn't paint its background by default. // Sun 5043225 says this is the intended behavior, though presumably not // when it's being used as a table cell renderer. if (UIManager.getLookAndFeel().getClass().getName().contains("GTK") && c instanceof JCheckBox) { jc.setOpaque(true); } if (getCellSelectionEnabled() == false && isEditing() == false) { if (System.getProperty("os.name").contains("Mac")) { // Native Mac OS doesn't draw a border on the selected cell. // It does however draw a horizontal line under the whole row, and a // vertical line separating each column. fixMacOsCellRendererBorder(jc, selected, focused); } else { // FIXME: doesn't Windows have row-wide selection focus? // Hide the cell focus. jc.setBorder(null); } } initToolTip(jc, row, column); } return c; } private void fixMacOsCellRendererBorder(JComponent renderer, boolean selected, boolean focused) { Border border; if (selected) { border = BorderFactory.createMatteBorder(0, 0, 1, 0, focused ? MAC_FOCUSED_SELECTED_CELL_HORIZONTAL_LINE_COLOR : MAC_UNFOCUSED_SELECTED_CELL_HORIZONTAL_LINE_COLOR); } else { border = BorderFactory.createEmptyBorder(0, 0, 1, 0); } // Mac OS' Aqua LAF never draws vertical grid lines, so we have to draw them // ourselves. if (getShowVerticalLines()) { Color verticalLineColor; if (focused) { verticalLineColor = selected ? MAC_FOCUSED_SELECTED_VERTICAL_LINE_COLOR : MAC_FOCUSED_UNSELECTED_VERTICAL_LINE_COLOR; } else { verticalLineColor = selected ? MAC_UNFOCUSED_SELECTED_VERTICAL_LINE_COLOR : MAC_UNFOCUSED_UNSELECTED_VERTICAL_LINE_COLOR; } Border verticalBorder = BorderFactory.createMatteBorder(0, 0, 0, 1, verticalLineColor); border = BorderFactory.createCompoundBorder(border, verticalBorder); } renderer.setBorder(border); } /** * Sets the component's tool tip if the component is being rendered smaller * than its preferred size. This means that all users automatically get tool * tips on truncated text fields that show them the full value. */ private void initToolTip(JComponent c, int row, int column) { String toolTipText = null; if (c.getPreferredSize().width > getCellRect(row, column, false).width) { toolTipText = getValueAt(row, column).toString(); } c.setToolTipText(toolTipText); } /** * Places tool tips over the cell they correspond to. MS Outlook does this, * and it works rather well. Swing will automatically override our suggested * location if it would cause the tool tip to go off the display. */ @Override public Point getToolTipLocation(MouseEvent e) { // After a tool tip has been displayed for a cell that has a tool tip, cells // without tool tips will show an empty tool tip until the tool tip mode // times out (or the table has a global default tool tip). // (ToolTipManager.checkForTipChange considers a non-null result from // getToolTipText *or* a non-null result from getToolTipLocation as implying // that the tool tip should be displayed. This seems like a bug, but that's // the way it is.) if (getToolTipText(e) == null) { return null; } final int row = rowAtPoint(e.getPoint()); final int column = columnAtPoint(e.getPoint()); if (row == -1 || column == -1) { return null; } return getCellRect(row, column, false).getLocation(); } /** * Improve the appearance of of a table in a JScrollPane on Mac OS, where * there's otherwise an unsightly hole. */ @Override protected void configureEnclosingScrollPane() { super.configureEnclosingScrollPane(); if (System.getProperty("os.name").contains("Mac") == false) { return; } Container p = getParent(); if (p instanceof JViewport) { Container gp = p.getParent(); if (gp instanceof JScrollPane) { JScrollPane scrollPane = (JScrollPane) gp; // Make certain we are the viewPort's view and not, for // example, the rowHeaderView of the scrollPane - // an implementor of fixed columns might do this. JViewport viewport = scrollPane.getViewport(); if (viewport == null || viewport.getView() != this) { return; } // JTable copy & paste above this point; our code below. // Put a dummy header in the upper-right corner. final Component renderer = new JTableHeader().getDefaultRenderer() .getTableCellRendererComponent(null, "", false, false, -1, 0); JPanel panel = new JPanel(new BorderLayout()); panel.add(renderer, BorderLayout.CENTER); scrollPane.setCorner(JScrollPane.UPPER_RIGHT_CORNER, panel); } } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/EnvironmentField.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * EnvironmentField.java * Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import weka.core.Environment; import weka.core.EnvironmentHandler; import javax.swing.BorderFactory; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.event.CaretEvent; import javax.swing.event.CaretListener; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.beans.PropertyEditor; import java.util.Vector; /** * Widget that displays a label and a combo box for selecting environment * variables. The enter arbitrary text, select an environment variable or a * combination of both. Any variables are resolved (if possible) and resolved * values are displayed in a tip-text. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ public class EnvironmentField extends JPanel implements EnvironmentHandler, PropertyEditor, CustomPanelSupplier { /** For serialization */ private static final long serialVersionUID = -3125404573324734121L; /** The label for the widget */ protected JLabel m_label; /** The combo box */ protected JComboBox m_combo; /** The current environment variables */ protected Environment m_env; protected String m_currentContents = ""; protected int m_firstCaretPos = 0; protected int m_previousCaretPos = 0; protected int m_currentCaretPos = 0; protected PropertyChangeSupport m_support = new PropertyChangeSupport(this); /** * Combo box that allows the drop-down list to be wider than the component * itself. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) */ public static class WideComboBox extends JComboBox { /** * For serialization */ private static final long serialVersionUID = -6512065375459733517L; public WideComboBox() { } public WideComboBox(final Object items[]) { super(items); } public WideComboBox(Vector<Object> items) { super(items); } public WideComboBox(ComboBoxModel aModel) { super(aModel); } private boolean m_layingOut = false; @Override public void doLayout() { try { m_layingOut = true; super.doLayout(); } finally { m_layingOut = false; } } @Override public Dimension getSize() { Dimension dim = super.getSize(); if (!m_layingOut) { dim.width = Math.max(dim.width, getPreferredSize().width); } return dim; } } /** * Construct an EnvironmentField with no label. */ public EnvironmentField() { this(""); setEnvironment(Environment.getSystemWide()); } /** * Construct an EnvironmentField with no label. * * @param env the environment variables to display in the drop-down box */ public EnvironmentField(Environment env) { this(""); setEnvironment(env); } /** * Constructor. * * @param label the label to use * @param env the environment variables to display in the drop-down box */ public EnvironmentField(String label, Environment env) { this(label); setEnvironment(env); } /** * Constructor. * * @param label the label to use */ public EnvironmentField(String label) { setLayout(new BorderLayout()); m_label = new JLabel(label); if (label.length() > 0) { m_label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5)); } add(m_label, BorderLayout.WEST); m_combo = new WideComboBox(); m_combo.setEditable(true); // m_combo.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); java.awt.Component theEditor = m_combo.getEditor().getEditorComponent(); if (theEditor instanceof JTextField) { ((JTextField) m_combo.getEditor().getEditorComponent()) .addCaretListener(new CaretListener() { @Override public void caretUpdate(CaretEvent e) { m_firstCaretPos = m_previousCaretPos; m_previousCaretPos = m_currentCaretPos; m_currentCaretPos = e.getDot(); } }); /* m_combo.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { m_support.firePropertyChange("", null, null); } }); */ ((JTextField) m_combo.getEditor().getEditorComponent()) .addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { m_support.firePropertyChange("", null, null); } }); } add(m_combo, BorderLayout.CENTER); // setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); Dimension d = getPreferredSize(); setPreferredSize(new Dimension(250, d.height)); } /** * Set the label for this widget. * * @param label the label to use */ public void setLabel(String label) { m_label.setText(label); } /** * Set the text to display in the editable combo box. * * @param text the text to display */ public void setText(String text) { m_currentContents = text; java.awt.Component theEditor = m_combo.getEditor().getEditorComponent(); if (theEditor instanceof JTextField) { ((JTextField) theEditor).setText(text); } else { m_combo.setSelectedItem(m_currentContents); } m_support.firePropertyChange("", null, null); } /** * Return the text from the combo box. * * @return the text from the combo box */ public String getText() { java.awt.Component theEditor = m_combo.getEditor().getEditorComponent(); String text = m_combo.getSelectedItem().toString(); if (theEditor instanceof JTextField) { text = ((JTextField) theEditor).getText(); } return text; } @Override public void setAsText(String s) { setText(s); } @Override public String getAsText() { return getText(); } @Override public void setValue(Object o) { setAsText((String) o); } @Override public Object getValue() { return getAsText(); } @Override public String getJavaInitializationString() { return null; } @Override public boolean isPaintable() { return true; // we don't want to appear in a separate popup } @Override public String[] getTags() { return null; } @Override public boolean supportsCustomEditor() { return true; } @Override public Component getCustomEditor() { return this; } @Override public JPanel getCustomPanel() { return this; } @Override public void addPropertyChangeListener(PropertyChangeListener pcl) { if (m_support != null && pcl != null) { m_support.addPropertyChangeListener(pcl); } } @Override public void removePropertyChangeListener(PropertyChangeListener pcl) { if (m_support != null && pcl != null) { m_support.removePropertyChangeListener(pcl); } } @Override public void paintValue(Graphics gfx, Rectangle box) { // TODO Auto-generated method stub } private String processSelected(String selected) { if (selected.equals(m_currentContents)) { // don't do anything if the user has just pressed return // without adding anything new return selected; } if (m_firstCaretPos == 0) { m_currentContents = selected + m_currentContents; } else if (m_firstCaretPos >= m_currentContents.length()) { m_currentContents = m_currentContents + selected; } else { String left = m_currentContents.substring(0, m_firstCaretPos); String right = m_currentContents.substring(m_firstCaretPos, m_currentContents.length()); m_currentContents = left + selected + right; } /* * java.awt.Component theEditor = m_combo.getEditor().getEditorComponent(); * if (theEditor instanceof JTextField) { * System.err.println("Setting current contents..." + m_currentContents); * ((JTextField)theEditor).setText(m_currentContents); } */ m_combo.setSelectedItem(m_currentContents); m_support.firePropertyChange("", null, null); return m_currentContents; } /** * Set the environment variables to display in the drop down list. * * @param env the environment variables to display */ @Override public void setEnvironment(final Environment env) { m_env = env; Vector<String> varKeys = new Vector<String>(env.getVariableNames()); @SuppressWarnings("serial") DefaultComboBoxModel dm = new DefaultComboBoxModel(varKeys) { @Override public Object getSelectedItem() { Object item = super.getSelectedItem(); if (item instanceof String) { if (env.getVariableValue((String) item) != null) { String newS = "${" + (String) item + "}"; item = newS; } } return item; } }; m_combo.setModel(dm); m_combo.setSelectedItem(""); m_combo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String selected = (String) m_combo.getSelectedItem(); try { selected = processSelected(selected); selected = m_env.substitute(selected); } catch (Exception ex) { // quietly ignore unresolved variables } m_combo.setToolTipText(selected); } }); m_combo.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { java.awt.Component theEditor = m_combo.getEditor().getEditorComponent(); if (theEditor instanceof JTextField) { String selected = ((JTextField) theEditor).getText(); m_currentContents = selected; if (m_env != null) { try { selected = m_env.substitute(selected); } catch (Exception ex) { // quietly ignore unresolved variables } } m_combo.setToolTipText(selected); } } }); } /** * Set the enabled status of the combo box. * * @param enabled true if the combo box is enabled */ @Override public void setEnabled(boolean enabled) { m_combo.setEnabled(enabled); } /** * Set the editable status of the combo box. * * @param editable true if the combo box is editable */ public void setEditable(boolean editable) { m_combo.setEditable(editable); } /** * Main method for testing this class * * @param args command line args (ignored) */ public static void main(String[] args) { try { final javax.swing.JFrame jf = new javax.swing.JFrame("EnvironmentField"); jf.getContentPane().setLayout(new BorderLayout()); final EnvironmentField f = new EnvironmentField("A label here"); jf.getContentPane().add(f, BorderLayout.CENTER); Environment env = Environment.getSystemWide(); f.setEnvironment(env); jf.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { jf.dispose(); System.exit(0); } }); jf.pack(); jf.setVisible(true); } catch (Exception ex) { ex.printStackTrace(); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/EvaluationMetricSelectionDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * EvaluationMetricSelectionDialog.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.awt.BorderLayout; import java.awt.Dialog; import java.awt.Frame; import java.awt.GridLayout; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JPanel; import weka.classifiers.evaluation.Evaluation; import weka.core.Attribute; import weka.core.Instances; /** * A GUI dialog for selecting classification/regression evaluation metrics to be * output. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ public class EvaluationMetricSelectionDialog extends JDialog { /** For serialization */ private static final long serialVersionUID = 4451184027143094270L; /** The list of selected evaluation metrics */ protected List<String> m_selectedEvalMetrics; /** * Constructor * * @param parent parent Dialog * @param evalMetrics initial list of selected evaluation metrics */ public EvaluationMetricSelectionDialog(Dialog parent, List<String> evalMetrics) { super(parent, "Manage evaluation metrics", ModalityType.DOCUMENT_MODAL); m_selectedEvalMetrics = evalMetrics; init(); } /** * Constructor * * @param parent parent Window * @param evalMetrics initial list of selected evaluation metrics */ public EvaluationMetricSelectionDialog(Window parent, List<String> evalMetrics) { super(parent, "Manage evaluation metrics", ModalityType.DOCUMENT_MODAL); m_selectedEvalMetrics = evalMetrics; init(); } /** * Constructor * * @param parent parent Frame * @param evalMetrics initial list of selected evaluation metrics */ public EvaluationMetricSelectionDialog(Frame parent, List<String> evalMetrics) { super(parent, "Manage evaluation metrics", ModalityType.DOCUMENT_MODAL); m_selectedEvalMetrics = evalMetrics; init(); } /** * Get the list of selected evaluation metrics * * @return the list of selected evaluation metrics */ public List<String> getSelectedEvalMetrics() { return m_selectedEvalMetrics; } private void init() { final weka.gui.AttributeSelectionPanel evalConfigurer = new weka.gui.AttributeSelectionPanel( true, true, true, true); ArrayList<Attribute> atts = new ArrayList<Attribute>(); List<String> allEvalMetrics = Evaluation.getAllEvaluationMetricNames(); for (String s : allEvalMetrics) { atts.add(new Attribute(s)); } final Instances metricInstances = new Instances("Metrics", atts, 1); boolean[] selectedMetrics = new boolean[metricInstances.numAttributes()]; if (m_selectedEvalMetrics == null) { // one-off initialization m_selectedEvalMetrics = new ArrayList<String>(); for (int i = 0; i < metricInstances.numAttributes(); i++) { m_selectedEvalMetrics.add(metricInstances.attribute(i).name()); } } for (int i = 0; i < selectedMetrics.length; i++) { if (m_selectedEvalMetrics.contains(metricInstances.attribute(i).name())) { selectedMetrics[i] = true; } } try { evalConfigurer.setInstances(metricInstances); evalConfigurer.setSelectedAttributes(selectedMetrics); } catch (Exception ex) { ex.printStackTrace(); return; } setLayout(new BorderLayout()); JPanel holder = new JPanel(); holder.setLayout(new BorderLayout()); holder.add(evalConfigurer, BorderLayout.CENTER); JButton okBut = new JButton("OK"); JButton cancelBut = new JButton("Cancel"); JPanel butHolder = new JPanel(); butHolder.setLayout(new GridLayout(1, 2)); butHolder.add(okBut); butHolder.add(cancelBut); holder.add(butHolder, BorderLayout.SOUTH); okBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int[] selected = evalConfigurer.getSelectedAttributes(); m_selectedEvalMetrics.clear(); for (int i = 0; i < selected.length; i++) { m_selectedEvalMetrics.add(metricInstances.attribute(selected[i]) .name()); } dispose(); } }); cancelBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dispose(); } }); getContentPane().add(holder, BorderLayout.CENTER); pack(); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/ExtensionFileFilter.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ExtensionFileFilter.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.io.File; import java.io.FilenameFilter; import java.io.Serializable; import javax.swing.filechooser.FileFilter; /** * Provides a file filter for FileChoosers that accepts or rejects files based * on their extension. Compatible with both java.io.FilenameFilter and * javax.swing.filechooser.FileFilter (why there are two I have no idea). * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public class ExtensionFileFilter extends FileFilter implements FilenameFilter, Serializable { /** Added ID to avoid warning. */ private static final long serialVersionUID = -5960622841390665131L; /** The text description of the types of files accepted */ protected String m_Description; /** The filename extensions of accepted files */ protected String[] m_Extension; /** * Creates the ExtensionFileFilter * * @param extension the extension of accepted files. * @param description a text description of accepted files. */ public ExtensionFileFilter(String extension, String description) { m_Extension = new String[1]; m_Extension[0] = extension; m_Description = description; } /** * Creates an ExtensionFileFilter that accepts files that have any of the * extensions contained in the supplied array. * * @param extensions an array of acceptable file extensions (as Strings). * @param description a text description of accepted files. */ public ExtensionFileFilter(String[] extensions, String description) { m_Extension = extensions; m_Description = description; } /** * Gets the description of accepted files. * * @return the description. */ @Override public String getDescription() { return m_Description; } /** * Returns a copy of the acceptable extensions. * * @return the accepted extensions */ public String[] getExtensions() { return m_Extension.clone(); } /** * Returns true if the supplied file should be accepted (i.e.: if it has the * required extension or is a directory). * * @param file the file of interest. * @return true if the file is accepted by the filter. */ @Override public boolean accept(File file) { String name = file.getName().toLowerCase(); if (file.isDirectory()) { return true; } for (String element : m_Extension) { if (name.endsWith(element)) { return true; } } return false; } /** * Returns true if the file in the given directory with the given name should * be accepted. * * @param dir the directory where the file resides. * @param name the name of the file. * @return true if the file is accepted. */ @Override public boolean accept(File dir, String name) { return accept(new File(dir, name)); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/FileEditor.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * FileEditor.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.awt.Container; import java.awt.Dialog; import java.awt.FontMetrics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyEditorSupport; import java.io.File; import javax.swing.JFileChooser; /** * A PropertyEditor for File objects that lets the user select a file. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public class FileEditor extends PropertyEditorSupport { /** The file chooser used for selecting files. */ protected JFileChooser m_FileChooser; /** * Returns a representation of the current property value as java source. * * @return a value of type 'String' */ public String getJavaInitializationString() { File f = (File) getValue(); if (f == null) { return "null"; } return "new File(\"" + f.getName() + "\")"; } /** * Returns true because we do support a custom editor. * * @return true */ public boolean supportsCustomEditor() { return true; } /** * Gets the custom editor component. * * @return a value of type 'java.awt.Component' */ public java.awt.Component getCustomEditor() { if (m_FileChooser == null) { File currentFile = (File) getValue(); if (currentFile != null) { m_FileChooser = new JFileChooser(); m_FileChooser.setSelectedFile(currentFile); } else { m_FileChooser = new JFileChooser(new File(System.getProperty("user.dir"))); } m_FileChooser.setApproveButtonText("Select"); m_FileChooser.setApproveButtonMnemonic('S'); m_FileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); m_FileChooser.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String cmdString = e.getActionCommand(); if (cmdString.equals(JFileChooser.APPROVE_SELECTION)) { File newVal = m_FileChooser.getSelectedFile(); setValue(newVal); } closeDialog(); } }); } return m_FileChooser; } /** * Returns true since this editor is paintable. * * @return true. */ public boolean isPaintable() { return true; } /** * Paints a representation of the current Object. * * @param gfx the graphics context to use * @param box the area we are allowed to paint into */ public void paintValue(java.awt.Graphics gfx, java.awt.Rectangle box) { FontMetrics fm = gfx.getFontMetrics(); int vpad = (box.height - fm.getHeight()) / 2 ; File f = (File) getValue(); String val = "No file"; if (f != null) { val = f.getName(); } gfx.drawString(val, 2, fm.getHeight() + vpad); } /** * Closes the dialog. */ protected void closeDialog() { if (m_FileChooser instanceof Container) { Dialog dlg = PropertyDialog.getParentDialog((Container) m_FileChooser); if (dlg != null) dlg.setVisible(false); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/FileEnvironmentField.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * FileEnvironmentField.java * Copyright (C) 2010-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import weka.core.Environment; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JPanel; import javax.swing.filechooser.FileFilter; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; /** * Widget that displays a label, editable combo box for selecting environment * variables and a button for brining up a file browser. The user can enter * arbitrary text, select an environment variable or a combination of both. Any * variables are resolved (if possible) and resolved values are displayed in a * tip-text. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ public class FileEnvironmentField extends EnvironmentField { /** For serialization */ private static final long serialVersionUID = -233731548086207652L; /** File editor component */ protected FileEditor m_fileEditor = new FileEditor(); /** Dialog to hold the file editor */ protected PropertyDialog m_fileEditorDialog; /** The button to pop up the file dialog */ protected JButton m_browseBut; /** * Constructor */ public FileEnvironmentField() { this("", JFileChooser.OPEN_DIALOG, false); setEnvironment(Environment.getSystemWide()); } /** * Constructor * * @param env an Environment object to use */ public FileEnvironmentField(Environment env) { this("", JFileChooser.OPEN_DIALOG, false); setEnvironment(env); } public FileEnvironmentField(String label, Environment env) { this(label, JFileChooser.OPEN_DIALOG, false); setEnvironment(env); } /** * Constructor * * @param label a label to display alongside the field. * @param env an Environment object to use. * @param fileChooserType the type of file chooser to use (either * JFileChooser.OPEN_DIALOG or JFileChooser.SAVE_DIALOG) */ public FileEnvironmentField(String label, Environment env, int fileChooserType) { this(label, fileChooserType, false); setEnvironment(env); } /** * Constructor * * @param label a label to display alongside the field. * @param env an Environment object to use. * @param fileChooserType the type of file chooser to use (either * JFileChooser.OPEN_DIALOG or JFileChooser.SAVE_DIALOG) * @param directoriesOnly true if file chooser should allow only directories * to be selected */ public FileEnvironmentField(String label, Environment env, int fileChooserType, boolean directoriesOnly) { this(label, fileChooserType, directoriesOnly); setEnvironment(env); } /** * Constructor * * @param label a label to display alongside the field. * @param fileChooserType the type of file chooser to use (either * JFileChooser.OPEN_DIALOG or JFileChooser.SAVE_DIALOG) */ public FileEnvironmentField(String label, int fileChooserType, boolean directoriesOnly) { super(label); m_fileEditor.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { File selected = (File) m_fileEditor.getValue(); if (selected != null) { FileEnvironmentField.this.setText(selected.toString()); } } }); final JFileChooser embeddedEditor = (JFileChooser) m_fileEditor.getCustomEditor(); if (directoriesOnly) { embeddedEditor.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); } else { embeddedEditor.setFileSelectionMode(JFileChooser.FILES_ONLY); } embeddedEditor.setDialogType(fileChooserType); ExtensionFileFilter ff = new ExtensionFileFilter(".model", "Serialized Weka classifier (*.model)"); embeddedEditor.addChoosableFileFilter(ff); m_browseBut = new JButton("Browse..."); m_browseBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { String modelPath = getText(); if (modelPath != null) { try { modelPath = m_env.substitute(modelPath); } catch (Exception ex) { } File toSet = new File(modelPath); if (toSet.isFile()) { m_fileEditor.setValue(new File(modelPath)); toSet = toSet.getParentFile(); } if (toSet.isDirectory()) { embeddedEditor.setCurrentDirectory(toSet); } } showFileEditor(); } catch (Exception ex) { ex.printStackTrace(); } } }); JPanel bP = new JPanel(); bP.setLayout(new BorderLayout()); // bP.setBorder(BorderFactory.createEmptyBorder(5,0,5,5)); bP.add(m_browseBut, BorderLayout.CENTER); add(bP, BorderLayout.EAST); } /** * Add a file filter to use * * @param toSet the file filter to use */ public void addFileFilter(FileFilter toSet) { JFileChooser embeddedEditor = (JFileChooser) m_fileEditor.getCustomEditor(); embeddedEditor.addChoosableFileFilter(toSet); } /** * Set the file filter to be the selected one in the drop down box * * @param toSet the file filter to set */ public void setFileFilter(FileFilter toSet) { JFileChooser embeddedEditor = (JFileChooser) m_fileEditor.getCustomEditor(); embeddedEditor.setFileFilter(toSet); } public void setCurrentDirectory(String directory) { setCurrentDirectory(new File(directory)); } public void setCurrentDirectory(File directory) { String tmpString = directory.toString(); if (Environment.containsEnvVariables(tmpString)) { try { tmpString = m_env.substitute(tmpString); } catch (Exception ex) { // ignore } } File tmp2 = new File((new File(tmpString)).getAbsolutePath()); JFileChooser embeddedEditor = (JFileChooser) m_fileEditor.getCustomEditor(); if (tmp2.isDirectory()) { embeddedEditor.setCurrentDirectory(tmp2); if (embeddedEditor.getFileSelectionMode() == JFileChooser.DIRECTORIES_ONLY) { super.setAsText(directory.toString()); } } else { embeddedEditor.setSelectedFile(tmp2); if (embeddedEditor.getFileSelectionMode() == JFileChooser.FILES_ONLY) { super.setAsText(directory.toString()); } } } /** * Resets the list of choosable file filters. */ public void resetFileFilters() { JFileChooser embeddedEditor = (JFileChooser) m_fileEditor.getCustomEditor(); embeddedEditor.resetChoosableFileFilters(); } private void showFileEditor() { if (m_fileEditorDialog == null) { if (PropertyDialog.getParentDialog(this) != null) { m_fileEditorDialog = new PropertyDialog(PropertyDialog.getParentDialog(this), m_fileEditor, -1, -1); } else { m_fileEditorDialog = new PropertyDialog(PropertyDialog.getParentFrame(this), m_fileEditor, -1, -1); } } if (PropertyDialog.getParentDialog(this) != null) { m_fileEditorDialog.setLocationRelativeTo(PropertyDialog.getParentDialog(this)); } else { m_fileEditorDialog.setLocationRelativeTo(PropertyDialog.getParentFrame(this)); } m_fileEditorDialog.setVisible(true); } @Override public void removeNotify() { super.removeNotify(); if (m_fileEditorDialog != null) { m_fileEditorDialog.dispose(); m_fileEditorDialog = null; } } /** * Set the enabled status of the combo box and button * * @param enabled true if the combo box and button are to be enabled */ @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); m_browseBut.setEnabled(enabled); } @Override public Object getValue() { String path = getAsText(); if (path != null && path.length() > 0) { return new File(path); } JFileChooser embeddedEditor = (JFileChooser) m_fileEditor.getCustomEditor(); if (embeddedEditor.getFileSelectionMode() == JFileChooser.DIRECTORIES_ONLY) { return new File("."); } else { return new File(""); } } @Override public void setValue(Object value) { if (value instanceof File) { setAsText(((File) value).toString()); } } @Override public void setAsText(String val) { setCurrentDirectory(val); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/FilePropertyMetadata.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * PropertyDisplayName.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Method annotation that can be used to provide some additional information for * handling file properties in the GUI. In particular, it can be used to * indicate whether an JFileChooser.OPEN_DIALOG or JFileChooser.SAVE_DIALOG * should be used with the property and, furthermore, whether the dialog should * allow only files or directories to be selected. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface FilePropertyMetadata { /** * Specify the type of JFileChooser dialog that should be used - i.e. either * JFileChooser.OPEN_DIALOG or JFileChooser.SAVE_DIALOG * * @return the type of JFileChooser dialog to use */ int fileChooserDialogType(); /** * Returns true if the file chooser dialog should only allow directories to be * selected, otherwise it will allow only files to be selected * * @return true if only directories rather than files should be selected */ boolean directoriesOnly(); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/GPCIgnore.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * GPCIgnore.java * Copyright (C) 2014 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marker annotation. Used to prevent the GenericPropertiesCreator from making * something available. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface GPCIgnore { }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/GUIApplication.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * GUIApplication * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import weka.core.Defaults; import weka.core.Settings; import javax.swing.*; /** * Interface to a GUIApplication that can have multiple "perspectives" and * provide application-level and perspective-level settings. Implementations * would typically extend {@code AbstractGUIApplication}. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public interface GUIApplication { /** * Get the name of this application * * @return the name of this application */ String getApplicationName(); /** * Get the ID of this application - any string unique to this application can * be used * * @return the ID of this application */ String getApplicationID(); /** * Get the {@code PerspectiveManager} in use by this application * * @return the {@code Perspective Manager} */ PerspectiveManager getPerspectiveManager(); /** * Get the main {@code Perspective} of this application - i.e. this is the * panel, tab, screen etc. that is visible first at start-up. * * @return the main perspective */ Perspective getMainPerspective(); /** * Returns true if the perspectives toolbar is visible at the current time * * @return true if the perspectives toolbar is visible */ boolean isPerspectivesToolBarVisible(); /** * Hide the perspectives toolbar */ void hidePerspectivesToolBar(); /** * Show the perspectives toolbar */ void showPerspectivesToolBar(); /** * Popup a dialog displaying the supplied Exception * * @param cause the exception to show */ void showErrorDialog(Exception cause); /** * Popup an information dialog * * @param information the "information" (typically some text) to display * @param title the title for the dialog * @param isWarning true if this is a warning rather than just information */ void showInfoDialog(Object information, String title, boolean isWarning); /** * Get the default values of settings for this application * * @return the default values of the settings for this applications */ Defaults getApplicationDefaults(); /** * Get the current settings for this application * * @return the current settings for this application */ Settings getApplicationSettings(); /** * Called when settings are changed by the user */ void settingsChanged(); /** * Force a re-validation and repaint() of the application */ void revalidate(); /** * Show the menu bar for the application * * @param topLevelAncestor the JFrame that contains the application */ void showMenuBar(JFrame topLevelAncestor); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/GUIChooser.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * GUIChooserApp.java * Copyright (C) 2016 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import weka.core.Copyright; import weka.core.Version; import javax.swing.JMenuBar; import java.util.Arrays; import java.util.List; /** * Launcher class for the Weka GUIChooser. Displays a splash window and * launches the actual GUIChooser app (GUIChooserApp). * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class GUIChooser { /** * Interface for plugin components that can be accessed from either the * Visualization or Tools menu. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) */ public static interface GUIChooserMenuPlugin { /** Enum listing possible menus that plugins can appear in */ public static enum Menu { TOOLS, VISUALIZATION }; /** * Get the name to display in title bar of the enclosing JFrame for the * plugin * * @return the name to display in the title bar */ String getApplicationName(); /** * Get the menu that the plugin is to be listed in * * @return the menu that the plugin is to be listed in */ Menu getMenuToDisplayIn(); /** * Get the text entry to appear in the menu * * @return the text entry to appear in the menu */ String getMenuEntryText(); /** * Return the menu bar for this plugin * * @return the menu bar for this plugin or null if it does not use a menu * bar */ JMenuBar getMenuBar(); } public static void main(String[] args) { List<String> message = Arrays.asList("Waikato Environment for Knowledge Analysis", "Version " + Version.VERSION, "(c) " + Copyright.getFromYear() + " - " + Copyright.getToYear(), "The University of Waikato", "Hamilton, New Zealand"); weka.gui.SplashWindow.splash( ClassLoader.getSystemResource("weka/gui/weka_icon_new.png"), message); weka.gui.SplashWindow.invokeMain("weka.gui.GUIChooserApp", args); weka.gui.SplashWindow.disposeSplash(); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/GUIChooserApp.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * GUIChooser.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import weka.classifiers.bayes.net.GUI; import weka.classifiers.evaluation.ThresholdCurve; import weka.core.Copyright; import weka.core.Defaults; import weka.core.Instances; import weka.core.Memory; import weka.core.PluginManager; import weka.core.Settings; import weka.core.SystemInfo; import weka.core.Utils; import weka.core.Version; import weka.core.WekaPackageClassLoaderManager; import weka.core.WekaPackageManager; import weka.core.scripting.Groovy; import weka.core.scripting.Jython; import weka.gui.arffviewer.ArffViewer; import weka.gui.boundaryvisualizer.BoundaryVisualizer; import weka.gui.experiment.Experimenter; import weka.gui.explorer.Explorer; import weka.gui.graphvisualizer.GraphVisualizer; import weka.gui.knowledgeflow.KnowledgeFlowApp; import weka.gui.knowledgeflow.MainKFPerspective; import weka.gui.scripting.JythonPanel; import weka.gui.sql.SqlViewer; import weka.gui.treevisualizer.Node; import weka.gui.treevisualizer.NodePlace; import weka.gui.treevisualizer.PlaceNode2; import weka.gui.treevisualizer.TreeBuild; import weka.gui.treevisualizer.TreeVisualizer; import weka.gui.visualize.PlotData2D; import weka.gui.visualize.ThresholdVisualizePanel; import weka.gui.visualize.VisualizePanel; import javax.swing.*; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Frame; import java.awt.GridLayout; import java.awt.Image; import java.awt.LayoutManager; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.io.Reader; import java.security.Permission; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import java.util.Set; import java.util.Vector; /** * The main class for the Weka GUIChooser. Lets the user choose which GUI they * want to run. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @author Mark Hall (mhall@cs.waikato.ac.nz) * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class GUIChooserApp extends JFrame { /** for serialization */ private static final long serialVersionUID = 9001529425230247914L; /** GUIChooser settings */ private Settings m_settings; /** the GUIChooser itself */ protected GUIChooserApp m_Self; // Menu stuff private JMenuBar m_jMenuBar; private JMenu m_jMenuProgram; private JMenu m_jMenuVisualization; private JMenu m_jMenuTools; private JMenu m_jMenuHelp; // Applications /** The frames for the various applications that are open */ protected Vector<JFrame> m_Frames = new Vector<JFrame>(); /** the panel for the application buttons */ protected JPanel m_PanelApplications = new JPanel(); /** Click to open the Workbench */ protected JButton m_WorkbenchBut = new JButton("Workbench"); /** Click to open the Explorer */ protected JButton m_ExplorerBut = new JButton("Explorer"); /** Click to open the Explorer */ protected JButton m_ExperimenterBut = new JButton("Experimenter"); /** Click to open the KnowledgeFlow */ protected JButton m_KnowledgeFlowBut = new JButton("KnowledgeFlow"); /** Click to open the simplecli */ protected JButton m_SimpleBut = new JButton("Simple CLI"); /** The frame of the LogWindow */ protected static LogWindow m_LogWindow = new LogWindow(); /** The weka image */ Image m_weka = Toolkit.getDefaultToolkit().getImage( GUIChooserApp.class.getClassLoader().getResource( "weka/gui/images/weka_background.gif")); /** filechooser for the TreeVisualizer */ protected JFileChooser m_FileChooserTreeVisualizer = new JFileChooser( new File(System.getProperty("user.dir"))); /** filechooser for the GraphVisualizer */ protected JFileChooser m_FileChooserGraphVisualizer = new JFileChooser( new File(System.getProperty("user.dir"))); /** filechooser for Plots */ protected JFileChooser m_FileChooserPlot = new JFileChooser(new File( System.getProperty("user.dir"))); /** filechooser for ROC curves */ protected JFileChooser m_FileChooserROC = new JFileChooser(new File( System.getProperty("user.dir"))); /** the icon for the frames */ protected Image m_Icon; /** contains the child frames (title &lt;-&gt; object). */ protected HashSet<Container> m_ChildFrames = new HashSet<Container>(); /** * Create a singleton instance of the GUIChooser */ public static synchronized void createSingleton() { if (m_chooser == null) { m_chooser = new GUIChooserApp(); } } /** * Get the singleton instance of the GUIChooser * * @return the singleton instance of the GUIChooser */ public static GUIChooserApp getSingleton() { return m_chooser; } /** * Creates the experiment environment gui with no initial experiment */ public GUIChooserApp() { super("Weka GUI Chooser"); m_Self = this; m_settings = new Settings("weka", GUIChooserDefaults.APP_ID); GUIChooserDefaults guiChooserDefaults = new GUIChooserDefaults(); Defaults pmDefaults = WekaPackageManager.getUnderlyingPackageManager().getDefaultSettings(); guiChooserDefaults.add(pmDefaults); m_settings.applyDefaults(guiChooserDefaults); WekaPackageManager.getUnderlyingPackageManager().applySettings(m_settings); // filechoosers m_FileChooserGraphVisualizer .addChoosableFileFilter(new ExtensionFileFilter(".bif", "BIF Files (*.bif)")); m_FileChooserGraphVisualizer .addChoosableFileFilter(new ExtensionFileFilter(".xml", "XML Files (*.xml)")); m_FileChooserPlot.addChoosableFileFilter(new ExtensionFileFilter( Instances.FILE_EXTENSION, "ARFF Files (*" + Instances.FILE_EXTENSION + ")")); m_FileChooserPlot.setMultiSelectionEnabled(true); m_FileChooserROC.addChoosableFileFilter(new ExtensionFileFilter( Instances.FILE_EXTENSION, "ARFF Files (*" + Instances.FILE_EXTENSION + ")")); // general layout m_Icon = Toolkit.getDefaultToolkit().getImage( GUIChooserApp.class.getClassLoader().getResource( "weka/gui/weka_icon_new_48.png")); setIconImage(m_Icon); this.getContentPane().setLayout(new BorderLayout()); this.getContentPane().add(m_PanelApplications, BorderLayout.EAST); // applications m_PanelApplications.setBorder(BorderFactory .createTitledBorder("Applications")); m_PanelApplications.setLayout(new GridLayout(0, 1)); m_PanelApplications.add(m_ExplorerBut); m_PanelApplications.add(m_ExperimenterBut); m_PanelApplications.add(m_KnowledgeFlowBut); m_PanelApplications.add(m_WorkbenchBut); m_PanelApplications.add(m_SimpleBut); // Weka image plus copyright info JPanel wekaPan = new JPanel(); wekaPan.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); wekaPan.setLayout(new BorderLayout()); wekaPan.setToolTipText("Weka, a native bird of New Zealand"); ImageIcon wii = new ImageIcon(m_weka); JLabel wekaLab = new JLabel(wii); wekaPan.add(wekaLab, BorderLayout.CENTER); String infoString = "<html>" + "<font size=-2>" + "Waikato Environment for Knowledge Analysis<br>" + "Version " + Version.VERSION + "<br>" + "(c) " + Copyright.getFromYear() + " - " + Copyright.getToYear() + "<br>" + Copyright.getOwner() + "<br>" + Copyright.getAddress() + "</font>" + "</html>"; JLabel infoLab = new JLabel(infoString); infoLab.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); wekaPan.add(infoLab, BorderLayout.SOUTH); this.getContentPane().add(wekaPan, BorderLayout.CENTER); // Menu bar m_jMenuBar = new JMenuBar(); // Program m_jMenuProgram = new JMenu(); m_jMenuBar.add(m_jMenuProgram); m_jMenuProgram.setText("Program"); m_jMenuProgram.setMnemonic('P'); // Program/LogWindow JMenuItem jMenuItemProgramLogWindow = new JMenuItem(); m_jMenuProgram.add(jMenuItemProgramLogWindow); jMenuItemProgramLogWindow.setText("LogWindow"); // jMenuItemProgramLogWindow.setMnemonic('L'); jMenuItemProgramLogWindow.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_L, KeyEvent.CTRL_MASK)); m_LogWindow.setIconImage(m_Icon); jMenuItemProgramLogWindow.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (m_Self != null) { m_LogWindow.pack(); m_LogWindow.setSize(800, 600); m_LogWindow.setLocationRelativeTo(m_Self); } m_LogWindow.setVisible(true); } }); final JMenuItem jMenuItemProgramMemUsage = new JMenuItem(); m_jMenuProgram.add(jMenuItemProgramMemUsage); jMenuItemProgramMemUsage.setText("Memory usage"); // jMenuItemProgramMemUsage.setMnemonic('M'); jMenuItemProgramMemUsage.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_M, KeyEvent.CTRL_MASK)); jMenuItemProgramMemUsage.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final MemoryUsagePanel panel = new MemoryUsagePanel(); final JFrame frame = Utils.getWekaJFrame("Memory usage", m_Self); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(panel, BorderLayout.CENTER); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent w) { panel.stopMonitoring(); frame.dispose(); m_Frames.remove(frame); checkExit(); } }); frame.pack(); frame.setSize(400, 50); Point l = panel.getFrameLocation(); if ((l.x != -1) && (l.y != -1)) { frame.setLocation(l); } frame.setLocationRelativeTo(m_Self); frame.setVisible(true); Dimension size = frame.getPreferredSize(); frame.setSize(new Dimension((int) size.getWidth(), (int) size.getHeight())); m_Frames.add(frame); } }); final JMenuItem jMenuItemSettings = new JMenuItem(); m_jMenuProgram.add(jMenuItemSettings); jMenuItemSettings.setText("Settings"); jMenuItemSettings.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { int result = SettingsEditor.showSingleSettingsEditor(m_settings, GUIChooserDefaults.APP_ID, "GUIChooser", (JComponent) GUIChooserApp.this.getContentPane().getComponent(0), 550, 100); if (result == JOptionPane.OK_OPTION) { WekaPackageManager.getUnderlyingPackageManager().applySettings( m_settings); } } catch (Exception ex) { ex.printStackTrace(); } } }); m_jMenuProgram.add(new JSeparator()); // Program/Exit JMenuItem jMenuItemProgramExit = new JMenuItem(); m_jMenuProgram.add(jMenuItemProgramExit); jMenuItemProgramExit.setText("Exit"); // jMenuItemProgramExit.setMnemonic('E'); jMenuItemProgramExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, KeyEvent.CTRL_MASK)); jMenuItemProgramExit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dispose(); checkExit(); } }); // Visualization m_jMenuVisualization = new JMenu(); m_jMenuBar.add(m_jMenuVisualization); m_jMenuVisualization.setText("Visualization"); m_jMenuVisualization.setMnemonic('V'); // Visualization/Plot JMenuItem jMenuItemVisualizationPlot = new JMenuItem(); m_jMenuVisualization.add(jMenuItemVisualizationPlot); jMenuItemVisualizationPlot.setText("Plot"); // jMenuItemVisualizationPlot.setMnemonic('P'); jMenuItemVisualizationPlot.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_P, KeyEvent.CTRL_MASK)); jMenuItemVisualizationPlot.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // choose file int retVal = m_FileChooserPlot.showOpenDialog(m_Self); if (retVal != JFileChooser.APPROVE_OPTION) { return; } // build plot VisualizePanel panel = new VisualizePanel(); String filenames = ""; File[] files = m_FileChooserPlot.getSelectedFiles(); for (int j = 0; j < files.length; j++) { String filename = files[j].getAbsolutePath(); if (j > 0) { filenames += ", "; } filenames += filename; System.err.println("Loading instances from " + filename); try { Reader r = new java.io.BufferedReader(new FileReader(filename)); Instances i = new Instances(r); i.setClassIndex(i.numAttributes() - 1); PlotData2D pd1 = new PlotData2D(i); if (j == 0) { pd1.setPlotName("Master plot"); panel.setMasterPlot(pd1); } else { pd1.setPlotName("Plot " + (j + 1)); pd1.m_useCustomColour = true; pd1.m_customColour = (j % 2 == 0) ? Color.red : Color.blue; panel.addPlot(pd1); } } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(m_Self, "Error loading file '" + files[j] + "':\n" + ex.getMessage()); return; } } // create frame final JFrame frame = Utils.getWekaJFrame("Plot - " + filenames, m_Self); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(panel, BorderLayout.CENTER); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { m_Frames.remove(frame); frame.dispose(); checkExit(); } }); frame.pack(); frame.setSize(1024, 768); frame.setLocationRelativeTo(m_Self); frame.setVisible(true); m_Frames.add(frame); } }); // Visualization/ROC JMenuItem jMenuItemVisualizationROC = new JMenuItem(); m_jMenuVisualization.add(jMenuItemVisualizationROC); jMenuItemVisualizationROC.setText("ROC"); // jMenuItemVisualizationROC.setMnemonic('R'); jMenuItemVisualizationROC.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_R, KeyEvent.CTRL_MASK)); jMenuItemVisualizationROC.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // choose file int retVal = m_FileChooserROC.showOpenDialog(m_Self); if (retVal != JFileChooser.APPROVE_OPTION) { return; } // create plot String filename = m_FileChooserROC.getSelectedFile().getAbsolutePath(); Instances result = null; try { result = new Instances(new BufferedReader(new FileReader(filename))); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(m_Self, "Error loading file '" + filename + "':\n" + ex.getMessage()); return; } result.setClassIndex(result.numAttributes() - 1); ThresholdVisualizePanel vmc = new ThresholdVisualizePanel(); vmc.setROCString("(Area under ROC = " + Utils.doubleToString(ThresholdCurve.getROCArea(result), 4) + ")"); vmc.setName(result.relationName()); PlotData2D tempd = new PlotData2D(result); tempd.setPlotName(result.relationName()); tempd.addInstanceNumberAttribute(); try { vmc.addPlot(tempd); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(m_Self, "Error adding plot:\n" + ex.getMessage()); return; } final JFrame frame = Utils.getWekaJFrame("ROC - " + filename, m_Self); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(vmc, BorderLayout.CENTER); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { m_Frames.remove(frame); frame.dispose(); checkExit(); } }); frame.pack(); frame.setSize(1024, 768); frame.setLocationRelativeTo(m_Self); frame.setVisible(true); m_Frames.add(frame); } }); // Visualization/TreeVisualizer JMenuItem jMenuItemVisualizationTree = new JMenuItem(); m_jMenuVisualization.add(jMenuItemVisualizationTree); jMenuItemVisualizationTree.setText("TreeVisualizer"); // jMenuItemVisualizationTree.setMnemonic('T'); jMenuItemVisualizationTree.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_T, KeyEvent.CTRL_MASK)); jMenuItemVisualizationTree.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // choose file int retVal = m_FileChooserTreeVisualizer.showOpenDialog(m_Self); if (retVal != JFileChooser.APPROVE_OPTION) { return; } // build tree String filename = m_FileChooserTreeVisualizer.getSelectedFile().getAbsolutePath(); TreeBuild builder = new TreeBuild(); Node top = null; NodePlace arrange = new PlaceNode2(); try { top = builder.create(new FileReader(filename)); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(m_Self, "Error loading file '" + filename + "':\n" + ex.getMessage()); return; } // create frame final JFrame frame = Utils.getWekaJFrame("TreeVisualizer - " + filename, m_Self); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(new TreeVisualizer(null, top, arrange), BorderLayout.CENTER); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { m_Frames.remove(frame); frame.dispose(); checkExit(); } }); frame.pack(); frame.setSize(1024, 768); frame.setLocationRelativeTo(m_Self); frame.setVisible(true); m_Frames.add(frame); } }); // Visualization/GraphVisualizer JMenuItem jMenuItemVisualizationGraph = new JMenuItem(); m_jMenuVisualization.add(jMenuItemVisualizationGraph); jMenuItemVisualizationGraph.setText("GraphVisualizer"); // jMenuItemVisualizationGraph.setMnemonic('G'); jMenuItemVisualizationGraph.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_G, KeyEvent.CTRL_MASK)); jMenuItemVisualizationGraph.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // choose file int retVal = m_FileChooserGraphVisualizer.showOpenDialog(m_Self); if (retVal != JFileChooser.APPROVE_OPTION) { return; } // build graph String filename = m_FileChooserGraphVisualizer.getSelectedFile().getAbsolutePath(); GraphVisualizer panel = new GraphVisualizer(); try { if (filename.toLowerCase().endsWith(".xml") || filename.toLowerCase().endsWith(".bif")) { panel.readBIF(new FileInputStream(filename)); } else { panel.readDOT(new FileReader(filename)); } } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(m_Self, "Error loading file '" + filename + "':\n" + ex.getMessage()); return; } // create frame final JFrame frame = Utils.getWekaJFrame("GraphVisualizer - " + filename, m_Self); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(panel, BorderLayout.CENTER); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { m_Frames.remove(frame); frame.dispose(); checkExit(); } }); frame.pack(); frame.setSize(1024, 768); frame.setLocationRelativeTo(m_Self); frame.setVisible(true); m_Frames.add(frame); } }); // Visualization/BoundaryVisualizer final JMenuItem jMenuItemVisualizationBoundary = new JMenuItem(); m_jMenuVisualization.add(jMenuItemVisualizationBoundary); jMenuItemVisualizationBoundary.setText("BoundaryVisualizer"); // jMenuItemVisualizationBoundary.setMnemonic('B'); jMenuItemVisualizationBoundary.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_B, KeyEvent.CTRL_MASK)); jMenuItemVisualizationBoundary.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final JFrame frame = Utils.getWekaJFrame("BoundaryVisualizer", m_Self); frame.getContentPane().setLayout( new BorderLayout()); final BoundaryVisualizer bv = new BoundaryVisualizer(); frame.getContentPane().add(bv, BorderLayout.CENTER); frame.setSize(bv.getMinimumSize()); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent w) { bv.stopPlotting(); frame.dispose(); m_Frames.remove(frame); checkExit(); } }); frame.pack(); // frame.setSize(1024, 768); frame.setResizable(false); frame.setLocationRelativeTo(m_Self); frame.setVisible(true); m_Frames.add(frame); // dont' do a System.exit after last window got closed! BoundaryVisualizer.setExitIfNoWindowsOpen(false); } }); // Extensions JMenu jMenuExtensions = new JMenu("Extensions"); jMenuExtensions.setMnemonic(java.awt.event.KeyEvent.VK_E); m_jMenuBar.add(jMenuExtensions); jMenuExtensions.setVisible(false); String extensions = GenericObjectEditor.EDITOR_PROPERTIES.getProperty( MainMenuExtension.class.getName(), ""); if (extensions.length() > 0) { jMenuExtensions.setVisible(true); String[] classnames = GenericObjectEditor.EDITOR_PROPERTIES.getProperty( MainMenuExtension.class.getName(), "").split(","); Hashtable<String, JMenu> submenus = new Hashtable<String, JMenu>(); // add all extensions for (String classname : classnames) { try { MainMenuExtension ext = (MainMenuExtension) WekaPackageClassLoaderManager.objectForName(classname); // menuitem in a submenu? JMenu submenu = null; if (ext.getSubmenuTitle() != null) { submenu = submenus.get(ext.getSubmenuTitle()); if (submenu == null) { submenu = new JMenu(ext.getSubmenuTitle()); submenus.put(ext.getSubmenuTitle(), submenu); insertMenuItem(jMenuExtensions, submenu); } } // create menu item JMenuItem menuitem = new JMenuItem(); menuitem.setText(ext.getMenuTitle()); // does the extension need a frame or does it have its own // ActionListener? ActionListener listener = ext.getActionListener(m_Self); if (listener != null) { menuitem.addActionListener(listener); } else { final JMenuItem finalMenuitem = menuitem; final MainMenuExtension finalExt = ext; menuitem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Component frame = createFrame(m_Self, finalMenuitem.getText(), null, null, null, -1, -1, null, false, false); finalExt.fillFrame(frame); frame.setVisible(true); } }); } // sorted insert of menu item if (submenu != null) { insertMenuItem(submenu, menuitem); } else { insertMenuItem(jMenuExtensions, menuitem); } } catch (Exception e) { e.printStackTrace(); } } } // Tools m_jMenuTools = new JMenu(); m_jMenuBar.add(m_jMenuTools); m_jMenuTools.setText("Tools"); m_jMenuTools.setMnemonic('T'); // Package Manager final JMenuItem jMenuItemToolsPackageManager = new JMenuItem(); m_jMenuTools.add(jMenuItemToolsPackageManager); final String offline = (WekaPackageManager.m_offline ? " (offline)" : ""); jMenuItemToolsPackageManager.setText("Package manager" + offline); jMenuItemToolsPackageManager.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_U, KeyEvent.CTRL_MASK)); jMenuItemToolsPackageManager.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Thread temp = new Thread() { @Override public void run() { final weka.gui.PackageManager pm; pm = new weka.gui.PackageManager(); if (!WekaPackageManager.m_noPackageMetaDataAvailable) { final JFrame frame = Utils.getWekaJFrame("Package Manager" + offline, m_Self); frame.getContentPane().setLayout( new BorderLayout()); frame.getContentPane().add(pm, BorderLayout.CENTER); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent w) { frame.dispose(); m_Frames.remove(frame); checkExit(); } }); frame.pack(); Dimension screenSize = frame.getToolkit().getScreenSize(); int width = screenSize.width * 8 / 10; int height = screenSize.height * 8 / 10; frame.setBounds(width / 8, height / 8, width, height); frame.setLocationRelativeTo(m_Self); frame.setVisible(true); pm.setInitialSplitPaneDividerLocation(); m_Frames.add(frame); } } }; temp.start(); } }); // Tools/ArffViewer JMenuItem jMenuItemToolsArffViewer = new JMenuItem(); m_jMenuTools.add(jMenuItemToolsArffViewer); jMenuItemToolsArffViewer.setText("ArffViewer"); // jMenuItemToolsArffViewer.setMnemonic('A'); jMenuItemToolsArffViewer.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_A, KeyEvent.CTRL_MASK)); jMenuItemToolsArffViewer.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final ArffViewer av = new ArffViewer(); av.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent w) { m_Frames.remove(av); checkExit(); } }); av.pack(); av.setSize(1024, 768); av.setLocationRelativeTo(m_Self); av.setVisible(true); m_Frames.add(av); } }); // Tools/SqlViewer final JMenuItem jMenuItemToolsSql = new JMenuItem(); m_jMenuTools.add(jMenuItemToolsSql); jMenuItemToolsSql.setText("SqlViewer"); // jMenuItemToolsSql.setMnemonic('S'); jMenuItemToolsSql.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_MASK)); jMenuItemToolsSql.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final JFrame frame = Utils.getWekaJFrame("SqlViewer", m_Self); final SqlViewer sql = new SqlViewer(frame); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(sql, BorderLayout.CENTER); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent w) { sql.saveSize(); frame.dispose(); m_Frames.remove(frame); checkExit(); } }); frame.pack(); frame.setSize(1024, 768); frame.setLocationRelativeTo(m_Self); frame.setVisible(true); m_Frames.add(frame); } }); // Tools/Bayes net editor final JMenuItem jMenuItemBayesNet = new JMenuItem(); m_jMenuTools.add(jMenuItemBayesNet); jMenuItemBayesNet.setText("Bayes net editor"); jMenuItemBayesNet.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, KeyEvent.CTRL_MASK)); jMenuItemBayesNet.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final GUI bayesNetGUI = new GUI(); JMenuBar bayesBar = bayesNetGUI.getMenuBar(); final JFrame frame = Utils.getWekaJFrame("Bayes Network Editor", m_Self); frame.setJMenuBar(bayesBar); frame.getContentPane().add(bayesNetGUI, BorderLayout.CENTER); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent w) { frame.dispose(); m_Frames.remove(frame); checkExit(); } }); frame.pack(); frame.setSize(1024, 768); frame.setLocationRelativeTo(m_Self); frame.setVisible(true); m_Frames.add(frame); } }); // Tools/Groovy console if (Groovy.isPresent()) { final JMenuItem jMenuItemGroovyConsole = new JMenuItem(); m_jMenuTools.add(jMenuItemGroovyConsole); jMenuItemGroovyConsole.setText("Groovy console"); jMenuItemGroovyConsole.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_G, KeyEvent.CTRL_MASK)); jMenuItemGroovyConsole.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { Class groovyConsoleClass = WekaPackageClassLoaderManager.forName("groovy.ui.Console"); if (System.getProperty("os.name").toLowerCase().startsWith("mac")) { // Awful hack to prevent the Groovy console from taking over the // Mac menu bar. // Could potentially cause problems due to multi-threading, but // hopefully // not problematic in practice. String realOS = System.getProperty("os.name"); System.setProperty("os.name", "pretending_not_to_be_an_apple"); groovyConsoleClass.getMethod("run").invoke( groovyConsoleClass.newInstance()); System.setProperty("os.name", realOS); } else { groovyConsoleClass.getMethod("run").invoke( groovyConsoleClass.newInstance()); } } catch (Exception ex) { System.err.println("Failed to start Groovy console."); } } }); } // Tools/Jython console if (Jython.isPresent() || WekaPackageClassLoaderManager.getWekaPackageClassLoaderManager().getPackageClassLoader("tigerjython") != null) { final JMenuItem jMenuItemJythonConsole = new JMenuItem(); m_jMenuTools.add(jMenuItemJythonConsole); jMenuItemJythonConsole.setText("Jython console"); jMenuItemJythonConsole.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_J, KeyEvent.CTRL_MASK)); jMenuItemJythonConsole.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Do we have TigerJython? try { ClassLoader tigerLoader = WekaPackageClassLoaderManager.getWekaPackageClassLoaderManager().getPackageClassLoader("tigerjython"); if (tigerLoader == null) { throw new Exception("no tigerjython"); } Class tigerJythonClass = Class.forName("tigerjython.core.TigerJython", true, tigerLoader); Object[] args = new Object[1]; args[0] = new String[0]; tigerJythonClass.getMethod("main", String[].class).invoke(null, args); } catch (Exception ex) { // Default to built-in console final JythonPanel jythonPanel = new JythonPanel(); final JFrame frame = Utils.getWekaJFrame(jythonPanel.getPlainTitle(), m_Self); frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE); frame.setJMenuBar(jythonPanel.getMenuBar()); frame.getContentPane().add(jythonPanel, BorderLayout.CENTER); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent w) { m_Frames.remove(frame); checkExit(); } }); frame.pack(); frame.setSize(1024, 768); frame.setLocationRelativeTo(m_Self); frame.setVisible(true); m_Frames.add(frame); } } }); } // plugins for Visualization and Tools Set<String> pluginNames = PluginManager .getPluginNamesOfType("weka.gui.GUIChooser.GUIChooserMenuPlugin"); if (pluginNames != null) { boolean firstVis = true; boolean firstTools = true; for (String name : pluginNames) { try { final GUIChooser.GUIChooserMenuPlugin p = (GUIChooser.GUIChooserMenuPlugin) PluginManager.getPluginInstance( "weka.gui.GUIChooser.GUIChooserMenuPlugin", name); if (p instanceof JComponent) { final JMenuItem mItem = new JMenuItem(p.getMenuEntryText()); mItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final JFrame appFrame = Utils.getWekaJFrame(p.getApplicationName(), m_Self); appFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE); JMenuBar appMenu = p.getMenuBar(); if (appMenu != null) { appFrame.setJMenuBar(appMenu); } appFrame.getContentPane().add((JComponent) p, BorderLayout.CENTER); appFrame.addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent e) { m_Frames.remove(appFrame); checkExit(); } }); appFrame.pack(); appFrame.setSize(1024, 768); appFrame.setLocationRelativeTo(m_Self); appFrame.setVisible(true); m_Frames.add(appFrame); } }); if (p.getMenuToDisplayIn() == GUIChooser.GUIChooserMenuPlugin.Menu.VISUALIZATION) { if (firstVis) { m_jMenuVisualization.add(new JSeparator()); firstVis = false; } m_jMenuVisualization.add(mItem); } else { if (firstTools) { m_jMenuTools.add(new JSeparator()); firstTools = false; } m_jMenuTools.add(mItem); } } } catch (Exception e1) { e1.printStackTrace(); } } } // Help m_jMenuHelp = new JMenu(); m_jMenuBar.add(m_jMenuHelp); m_jMenuHelp.setText("Help"); m_jMenuHelp.setMnemonic('H'); // Help/Homepage JMenuItem jMenuItemHelpHomepage = new JMenuItem(); m_jMenuHelp.add(jMenuItemHelpHomepage); jMenuItemHelpHomepage.setText("Weka homepage"); // jMenuItemHelpHomepage.setMnemonic('H'); jMenuItemHelpHomepage.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, KeyEvent.CTRL_MASK)); jMenuItemHelpHomepage.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { BrowserHelper.openURL("http://www.cs.waikato.ac.nz/~ml/weka/"); } }); m_jMenuHelp.add(new JSeparator()); // Help/WekaWiki JMenuItem jMenuItemHelpWekaWiki = new JMenuItem(); m_jMenuHelp.add(jMenuItemHelpWekaWiki); jMenuItemHelpWekaWiki.setText("HOWTOs, code snippets, etc."); // jMenuItemHelpWekaWiki.setMnemonic('W'); jMenuItemHelpWekaWiki.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, KeyEvent.CTRL_MASK)); jMenuItemHelpWekaWiki.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { BrowserHelper.openURL("http://weka.wikispaces.com/"); } }); // Help/Sourceforge JMenuItem jMenuItemHelpSourceforge = new JMenuItem(); m_jMenuHelp.add(jMenuItemHelpSourceforge); jMenuItemHelpSourceforge.setText("Weka on Sourceforge"); // jMenuItemHelpSourceforge.setMnemonic('F'); jMenuItemHelpSourceforge.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_F, KeyEvent.CTRL_MASK)); jMenuItemHelpSourceforge.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { BrowserHelper.openURL("http://sourceforge.net/projects/weka/"); } }); // Help/SystemInfo final JMenuItem jMenuItemHelpSysInfo = new JMenuItem(); m_jMenuHelp.add(jMenuItemHelpSysInfo); jMenuItemHelpSysInfo.setText("SystemInfo"); // jMenuItemHelpSysInfo.setMnemonic('S'); jMenuItemHelpSysInfo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, KeyEvent.CTRL_MASK)); jMenuItemHelpSysInfo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final JFrame frame = Utils.getWekaJFrame("SystemInfo", m_Self); frame.getContentPane().setLayout(new BorderLayout()); // get info Hashtable<String, String> info = new SystemInfo().getSystemInfo(); // sort names Vector<String> names = new Vector<String>(); Enumeration<String> enm = info.keys(); while (enm.hasMoreElements()) { names.add(enm.nextElement()); } Collections.sort(names); // generate table String[][] data = new String[info.size()][2]; for (int i = 0; i < names.size(); i++) { data[i][0] = names.get(i).toString(); data[i][1] = info.get(data[i][0]).toString(); } String[] titles = new String[]{"Key", "Value"}; JTable table = new JTable(data, titles); frame.getContentPane().add(new JScrollPane(table), BorderLayout.CENTER); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent w) { frame.dispose(); m_Frames.remove(frame); checkExit(); } }); frame.pack(); frame.setSize(1024, 768); frame.setLocationRelativeTo(m_Self); frame.setVisible(true); m_Frames.add(frame); } }); // applications m_ExplorerBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showExplorer(null); } }); m_ExperimenterBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final JFrame frame = Utils.getWekaJFrame("Weka Experiment Environment", m_Self); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(new Experimenter(false), BorderLayout.CENTER); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent w) { frame.dispose(); m_Frames.remove(frame); checkExit(); } }); frame.pack(); frame.setSize(1024, 768); frame.setLocationRelativeTo(m_Self); frame.setVisible(true); m_Frames.add(frame); } }); m_KnowledgeFlowBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showKnowledgeFlow(null); } }); m_WorkbenchBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { WorkbenchApp app = new WorkbenchApp(); final JFrame frame = Utils.getWekaJFrame("Weka Workbench", m_Self); frame.add(app, BorderLayout.CENTER); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { frame.dispose(); m_Frames.remove(frame); checkExit(); } }); app.showMenuBar(frame); frame.pack(); frame.setSize(1024, 768); frame.setLocationRelativeTo(m_Self); frame.setVisible(true); m_Frames.add(frame); } }); m_SimpleBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { final JFrame frame = new SimpleCLI(); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent w) { frame.dispose(); m_Frames.remove(frame); checkExit(); } }); frame.pack(); frame.setSize(1024, 768); frame.setLocationRelativeTo(m_Self); frame.setVisible(true); m_Frames.add(frame); } catch (Exception ex) { throw new Error("Could not start SimpleCLI!"); } } }); /* * m_EnsembleLibraryBut.addActionListener(new ActionListener() { public void * actionPerformed(ActionEvent e) { if (m_EnsembleLibraryFrame == null) { * m_EnsembleLibraryBut.setEnabled(false); m_EnsembleLibraryFrame = new * JFrame("EnsembleLibrary"); m_EnsembleLibraryFrame.setIconImage(m_Icon); * m_EnsembleLibraryFrame.getContentPane().setLayout(new BorderLayout()); * EnsembleLibrary value = new EnsembleLibrary(); EnsembleLibraryEditor * libraryEditor = new EnsembleLibraryEditor(); * libraryEditor.setValue(value); * m_EnsembleLibraryFrame.getContentPane().add * (libraryEditor.getCustomEditor(), BorderLayout.CENTER); * m_EnsembleLibraryFrame.addWindowListener(new WindowAdapter() { public * void windowClosing(WindowEvent w) { m_EnsembleLibraryFrame.dispose(); * m_EnsembleLibraryFrame = null; m_EnsembleLibraryBut.setEnabled(true); * checkExit(); } }); m_EnsembleLibraryFrame.pack(); * m_EnsembleLibraryFrame.setSize(1024, 768); * m_EnsembleLibraryFrame.setVisible(true); } } }); */ setJMenuBar(m_jMenuBar); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent w) { dispose(); checkExit(); } }); pack(); if (!Utils.getDontShowDialog("weka.gui.GUIChooser.HowToFindPackageManager")) { Thread tipThread = new Thread() { @Override public void run() { JCheckBox dontShow = new JCheckBox("Do not show this message again"); Object[] stuff = new Object[2]; stuff[0] = "Weka has a package manager that you\n" + "can use to install many learning schemes and tools.\nThe package manager can be " + "found under the \"Tools\" menu.\n"; stuff[1] = dontShow; // Display the tip on finding/using the package manager JOptionPane.showMessageDialog(GUIChooserApp.this, stuff, "Weka GUIChooser", JOptionPane.OK_OPTION); if (dontShow.isSelected()) { try { Utils .setDontShowDialog("weka.gui.GUIChooser.HowToFindPackageManager"); } catch (Exception ex) { // quietly ignore } } } }; tipThread.setPriority(Thread.MIN_PRIORITY); tipThread.start(); } } public void showKnowledgeFlow(String fileToLoad) { final JFrame frame = Utils.getWekaJFrame("Weka KnowledgeFlow Environment", m_Self); frame.getContentPane().setLayout(new BorderLayout()); final KnowledgeFlowApp knowledgeFlow = new KnowledgeFlowApp(); frame.getContentPane().add(knowledgeFlow, BorderLayout.CENTER); knowledgeFlow.showMenuBar(frame); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent w) { ((MainKFPerspective) knowledgeFlow.getMainPerspective()) .closeAllTabs(); ((MainKFPerspective) knowledgeFlow.getMainPerspective()) .addUntitledTab(); /* * kna.closeAllTabs(); kna.clearLayout(); // add a single "Untitled" * tab ready for next // time */ frame.dispose(); m_Frames.remove(frame); checkExit(); } }); frame.pack(); frame.setSize(1024, 768); frame.setLocationRelativeTo(m_Self); frame.setVisible(true); m_Frames.add(frame); } public void showExplorer(String fileToLoad) { final JFrame frame = Utils.getWekaJFrame("Weka Explorer", m_Self); frame.getContentPane().setLayout(new BorderLayout()); Explorer expl = new Explorer(); frame.getContentPane().add(expl, BorderLayout.CENTER); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent w) { frame.dispose(); m_Frames.remove(frame); checkExit(); } }); frame.pack(); frame.setSize(1024, 768); frame.setLocationRelativeTo(m_Self); frame.setVisible(true); m_Frames.add(frame); if (fileToLoad != null) { try { weka.core.converters.AbstractFileLoader loader = weka.core.converters.ConverterUtils.getLoaderForFile(fileToLoad); loader.setFile(new File(fileToLoad)); expl.getPreprocessPanel().setInstancesFromFile(loader); } catch (Exception ex) { ex.printStackTrace(); } } } /** * insert the menu item in a sorted fashion. * * @param menu the menu to add the item to * @param menuitem the menu item to add */ protected void insertMenuItem(JMenu menu, JMenuItem menuitem) { insertMenuItem(menu, menuitem, 0); } /** * insert the menu item in a sorted fashion. * * @param menu the menu to add the item to * @param menuitem the menu item to add * @param startIndex the index in the menu to start with (0-based) */ protected void insertMenuItem(JMenu menu, JMenuItem menuitem, int startIndex) { boolean inserted; int i; JMenuItem current; String currentStr; String newStr; inserted = false; newStr = menuitem.getText().toLowerCase(); // try to find a spot inbetween for (i = startIndex; i < menu.getMenuComponentCount(); i++) { if (!(menu.getMenuComponent(i) instanceof JMenuItem)) { continue; } current = (JMenuItem) menu.getMenuComponent(i); currentStr = current.getText().toLowerCase(); if (currentStr.compareTo(newStr) > 0) { inserted = true; menu.insert(menuitem, i); break; } } // add it at the end if not yet inserted if (!inserted) { menu.add(menuitem); } } /** * creates a frame and returns it. * * @param parent the parent of the generated frame * @param title the title of the frame * @param c the component to place, can be null * @param layout the layout to use, e.g., BorderLayout * @param layoutConstraints the layout constraints, e.g., BorderLayout.CENTER * @param width the width of the frame, ignored if -1 * @param height the height of the frame, ignored if -1 * @param menu an optional menu * @param listener if true a default listener is added * @param visible if true then the frame is made visible immediately * @return the generated frame */ protected Container createFrame(GUIChooserApp parent, String title, Component c, LayoutManager layout, Object layoutConstraints, int width, int height, JMenuBar menu, boolean listener, boolean visible) { Container result = null; final ChildFrameSDI frame = new ChildFrameSDI(parent, title); // layout frame.setLayout(layout); if (c != null) { frame.getContentPane().add(c, layoutConstraints); } // menu frame.setJMenuBar(menu); // size frame.pack(); if ((width > -1) && (height > -1)) { frame.setSize(width, height); } frame.validate(); // location //int screenHeight = getGraphicsConfiguration().getBounds().height; //int screenWidth = getGraphicsConfiguration().getBounds().width; //frame.setLocation((screenWidth - frame.getBounds().width) / 2, // (screenHeight - frame.getBounds().height) / 2); frame.setLocationRelativeTo(parent); // listener? if (listener) { frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { frame.dispose(); } }); } // display frame if (visible) { frame.setVisible(true); } result = frame; return result; } /** * Specialized JFrame class. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public static class ChildFrameSDI extends JFrame { /** for serialization. */ private static final long serialVersionUID = 8588293938686425618L; /** the parent frame. */ protected GUIChooserApp m_Parent; /** * constructs a new internal frame that knows about its parent. * * @param parent the parent frame * @param title the title of the frame */ public ChildFrameSDI(GUIChooserApp parent, String title) { super(title); m_Parent = parent; addWindowListener(new WindowAdapter() { @Override public void windowActivated(WindowEvent e) { // update title of parent if (getParentFrame() != null) { getParentFrame().createTitle(getTitle()); } } }); // add to parent if (getParentFrame() != null) { getParentFrame().addChildFrame(this); setIconImage(getParentFrame().getIconImage()); } } /** * returns the parent frame, can be null. * * @return the parent frame */ public GUIChooserApp getParentFrame() { return m_Parent; } /** * de-registers the child frame with the parent first. */ @Override public void dispose() { if (getParentFrame() != null) { getParentFrame().removeChildFrame(this); getParentFrame().createTitle(""); } super.dispose(); } } /** * creates and displays the title. * * @param title the additional part of the title */ protected void createTitle(String title) { String newTitle; newTitle = "Weka " + new Version(); if (title.length() != 0) { newTitle += " - " + title; } setTitle(newTitle); } /** * adds the given child frame to the list of frames. * * @param c the child frame to add */ public void addChildFrame(Container c) { m_ChildFrames.add(c); } /** * tries to remove the child frame, it returns true if it could do such. * * @param c the child frame to remove * @return true if the child frame could be removed */ public boolean removeChildFrame(Container c) { boolean result = m_ChildFrames.remove(c); return result; } /** * Kills the JVM if all windows have been closed. */ private void checkExit() { if (!isVisible() && (m_Frames.size() == 0)) { System.setSecurityManager(null); System.exit(0); } } /** * Inner class for defaults */ public static final class GUIChooserDefaults extends Defaults { /** APP name (GUIChooser isn't really an "app" as such */ public static final String APP_NAME = "GUIChooser"; /** ID */ public static final String APP_ID = "guichooser"; /** Settings key for LAF */ protected static final Settings.SettingKey LAF_KEY = new Settings.SettingKey(APP_ID + ".lookAndFeel", "Look and feel for UI", "Note: a restart is required for this setting to come into effect"); /** Default value for LAF */ protected static final String LAF = "javax.swing.plaf.nimbus.NimbusLookAndFeel"; private static final long serialVersionUID = -8524894440289936685L; /** * Constructor */ public GUIChooserDefaults() { super(APP_ID); List<String> lafs = LookAndFeel.getAvailableLookAndFeelClasses(); lafs.add(0, "<use platform default>"); LAF_KEY.setPickList(lafs); m_defaults.put(LAF_KEY, LAF); } } /** * variable for the GUIChooser class which would be set to null by the memory * monitoring thread to free up some memory if we running out of memory */ private static GUIChooserApp m_chooser; /** for monitoring the Memory consumption */ private static Memory m_Memory = new Memory(true); /** * Tests out the GUIChooser environment. * * @param args ignored. */ public static void main(String[] args) { weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, "Logging started"); try { LookAndFeel.setLookAndFeel(GUIChooserDefaults.APP_ID, GUIChooserDefaults.APP_ID + ".lookAndFeel", GUIChooserDefaults.LAF); } catch (IOException ex) { ex.printStackTrace(); } // Save std err and std out because they may be redirected by external code final PrintStream savedStdOut = System.out; final PrintStream savedStdErr = System.err; // Set up security manager to intercept System.exit() calls in external code final SecurityManager sm = System.getSecurityManager(); System.setSecurityManager(new SecurityManager() { public void checkExit(int status) { if (sm != null) { sm.checkExit(status); } // Currently, we are just checking for calls from TigerJython code for (Class cl : getClassContext()) { if (cl.getName().equals("tigerjython.gui.MainWindow")) { for (Frame frame : Frame.getFrames()) { if (frame.getTitle().toLowerCase().startsWith("tigerjython")) { frame.dispose(); } } // Set std err and std out back to original values System.setOut(savedStdOut); System.setErr(savedStdErr); // Make entry in log and /* * weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, * "Intercepted System.exit() from TigerJython. Please ignore"); * throw new SecurityException( * "Intercepted System.exit() from TigerJython. Please ignore!"); */ } } weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, "Intercepted System.exit() from a class other than the GUIChooser. " + "Please ignore."); throw new SecurityException("Intercepted System.exit() from " + "a class other than the GUIChooser. Please ignore."); } public void checkPermission(Permission perm) { if (sm != null) { sm.checkPermission(perm); } } public void checkPermission(Permission perm, Object context) { if (sm != null) { sm.checkPermission(perm, context); } } }); try { // uncomment to disable the memory management: // m_Memory.setEnabled(false); // m_chooser = new GUIChooser(); GUIChooserApp.createSingleton(); m_chooser.pack(); m_chooser.setSize(500, 350); m_chooser.setVisible(true); if (args != null && args.length > 0) { m_chooser.showExplorer(args[0]); } Thread memMonitor = new Thread() { @SuppressWarnings("static-access") @Override public void run() { while (true) { // try { // System.out.println("before sleeping"); // this.sleep(10); if (m_Memory.isOutOfMemory()) { // clean up m_chooser.dispose(); if (m_chooser.m_Frames.size() > 0) { for (int i = 0; i < m_chooser.m_Frames.size(); i++) { JFrame av = m_chooser.m_Frames.get(i); av.dispose(); } m_chooser.m_Frames.clear(); } m_chooser = null; System.gc(); // display error GUIChooserApp.m_LogWindow.pack(); GUIChooserApp.m_LogWindow.setSize(1024,768); GUIChooserApp.m_LogWindow.setVisible(true); GUIChooserApp.m_LogWindow.toFront(); System.err.println("\ndisplayed message:"); m_Memory.showOutOfMemory(); System.err.println("\nexiting..."); System.setSecurityManager(null); System.exit(-1); } // } catch (InterruptedException ex) { // ex.printStackTrace(); // } } } }; memMonitor.setPriority(Thread.NORM_PRIORITY); memMonitor.start(); } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/GenericArrayEditor.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * GenericArrayEditor.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import weka.core.SerializedObject; import javax.swing.DefaultListCellRenderer; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListCellRenderer; import javax.swing.SwingConstants; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Frame; import java.awt.Graphics; import java.awt.GridLayout; import java.awt.Insets; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.beans.PropertyEditor; import java.beans.PropertyEditorManager; import java.lang.reflect.Array; /** * A PropertyEditor for arrays of objects that themselves have property editors. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public class GenericArrayEditor implements PropertyEditor { private final CustomEditor m_customEditor; /** * This class presents a GUI for editing the array elements */ private class CustomEditor extends JPanel { /** for serialization. */ private static final long serialVersionUID = 3914616975334750480L; /** Handles property change notification. */ private final PropertyChangeSupport m_Support = new PropertyChangeSupport( GenericArrayEditor.this); /** The label for when we can't edit that type. */ private final JLabel m_Label = new JLabel("Can't edit", SwingConstants.CENTER); /** The list component displaying current values. */ private final JList m_ElementList = new JList(); /** The class of objects allowed in the array. */ private Class<?> m_ElementClass = String.class; /** The defaultlistmodel holding our data. */ private DefaultListModel m_ListModel; /** The property editor for the class we are editing. */ private PropertyEditor m_ElementEditor; /** Click this to delete the selected array values. */ private final JButton m_DeleteBut = new JButton("Delete"); /** Click this to edit the selected array value. */ private final JButton m_EditBut = new JButton("Edit"); /** Click this to move the selected array value(s) one up. */ private final JButton m_UpBut = new JButton("Up"); /** Click this to move the selected array value(s) one down. */ private final JButton m_DownBut = new JButton("Down"); /** Click to add the current object configuration to the array. */ private final JButton m_AddBut = new JButton("Add"); /** The property editor for editing existing elements. */ private PropertyEditor m_Editor = new GenericObjectEditor(); /** The currently displayed property dialog, if any. */ private PropertyDialog m_PD; /** Listens to buttons being pressed and taking the appropriate action. */ private final ActionListener m_InnerActionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == m_DeleteBut) { int[] selected = m_ElementList.getSelectedIndices(); if (selected != null) { for (int i = selected.length - 1; i >= 0; i--) { int current = selected[i]; m_ListModel.removeElementAt(current); if (m_ListModel.size() > current) { m_ElementList.setSelectedIndex(current); } } m_Support.firePropertyChange("", null, null); } } else if (e.getSource() == m_EditBut) { if (m_Editor instanceof GenericObjectEditor) { ((GenericObjectEditor) m_Editor).setClassType(m_ElementClass); } try { m_Editor.setValue(GenericObjectEditor.makeCopy(m_ElementList .getSelectedValue())); } catch (Exception ex) { // not possible to serialize? m_Editor.setValue(m_ElementList.getSelectedValue()); } if (m_Editor.getValue() != null) { if (PropertyDialog.getParentDialog(CustomEditor.this) != null) { m_PD = new PropertyDialog( PropertyDialog.getParentDialog(CustomEditor.this), m_Editor, -1, -1); } else { m_PD = new PropertyDialog( PropertyDialog.getParentFrame(CustomEditor.this), m_Editor, -1, -1); } m_PD.setVisible(true); if (!(m_Editor instanceof GenericObjectEditor) || (!((GenericObjectEditor)m_Editor).wasCancelPressed())) { m_ListModel.set(m_ElementList.getSelectedIndex(), m_Editor.getValue()); m_Support.firePropertyChange("", null, null); } } } else if (e.getSource() == m_UpBut) { JListHelper.moveUp(m_ElementList); m_Support.firePropertyChange("", null, null); } else if (e.getSource() == m_DownBut) { JListHelper.moveDown(m_ElementList); m_Support.firePropertyChange("", null, null); } else if (e.getSource() == m_AddBut) { int selected = m_ElementList.getSelectedIndex(); Object addObj = m_ElementEditor.getValue(); // Make a full copy of the object using serialization try { SerializedObject so = new SerializedObject(addObj); addObj = so.getObject(); if (selected != -1) { m_ListModel.insertElementAt(addObj, selected); } else { m_ListModel.addElement(addObj); } m_Support.firePropertyChange("", null, null); } catch (Exception ex) { JOptionPane.showMessageDialog(CustomEditor.this, "Could not create an object copy", null, JOptionPane.ERROR_MESSAGE); } } } }; /** Listens to list items being selected and takes appropriate action. */ private final ListSelectionListener m_InnerSelectionListener = new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (e.getSource() == m_ElementList) { // Enable the delete/edit button if (m_ElementList.getSelectedIndex() != -1) { m_DeleteBut.setEnabled(true); m_EditBut .setEnabled(m_ElementList.getSelectedIndices().length == 1); m_UpBut.setEnabled(JListHelper.canMoveUp(m_ElementList)); m_DownBut.setEnabled(JListHelper.canMoveDown(m_ElementList)); } // disable delete/edit button else { m_DeleteBut.setEnabled(false); m_EditBut.setEnabled(false); m_UpBut.setEnabled(false); m_DownBut.setEnabled(false); } } } }; /** Listens to mouse events and takes appropriate action. */ private final MouseListener m_InnerMouseListener = new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getSource() == m_ElementList) { if (e.getClickCount() == 2) { // unfortunately, locationToIndex only returns the nearest entry // and not the exact one, i.e. if there's one item in the list and // one doublelclicks somewhere in the list, this index will be // returned int index = m_ElementList.locationToIndex(e.getPoint()); if (index > -1) { m_InnerActionListener.actionPerformed(new ActionEvent(m_EditBut, 0, "")); } } } } }; /** * Sets up the array editor. */ public CustomEditor() { setLayout(new BorderLayout()); add(m_Label, BorderLayout.CENTER); m_DeleteBut.addActionListener(m_InnerActionListener); m_EditBut.addActionListener(m_InnerActionListener); m_UpBut.addActionListener(m_InnerActionListener); m_DownBut.addActionListener(m_InnerActionListener); m_AddBut.addActionListener(m_InnerActionListener); m_ElementList.addListSelectionListener(m_InnerSelectionListener); m_ElementList.addMouseListener(m_InnerMouseListener); m_AddBut.setToolTipText("Add the current item to the list"); m_DeleteBut.setToolTipText("Delete the selected list item"); m_EditBut.setToolTipText("Edit the selected list item"); m_UpBut.setToolTipText("Move the selected item(s) one up"); m_DownBut.setToolTipText("Move the selected item(s) one down"); } /** * This class handles the creation of list cell renderers from the property * editors. */ private class EditorListCellRenderer implements ListCellRenderer { /** The class of the property editor for array objects. */ private final Class<?> m_EditorClass; /** The class of the array values. */ private final Class<?> m_ValueClass; /** * Creates the list cell renderer. * * @param editorClass The class of the property editor for array objects * @param valueClass The class of the array values */ public EditorListCellRenderer(Class<?> editorClass, Class<?> valueClass) { m_EditorClass = editorClass; m_ValueClass = valueClass; } /** * Creates a cell rendering component. * * @param list the list that will be rendered in * @param value the cell value * @param index which element of the list to render * @param isSelected true if the cell is selected * @param cellHasFocus true if the cell has the focus * @return the rendering component */ @Override public Component getListCellRendererComponent(final JList list, final Object value, final int index, final boolean isSelected, final boolean cellHasFocus) { try { final PropertyEditor e = (PropertyEditor) m_EditorClass.newInstance(); if (e instanceof GenericObjectEditor) { // ((GenericObjectEditor) e).setDisplayOnly(true); ((GenericObjectEditor) e).setClassType(m_ValueClass); } e.setValue(value); return new JPanel() { private static final long serialVersionUID = -3124434678426673334L; @Override public void paintComponent(Graphics g) { Insets i = this.getInsets(); Rectangle box = new Rectangle(i.left, i.top, this.getWidth() - i.right, this.getHeight() - i.bottom); g.setColor(isSelected ? list.getSelectionBackground() : list .getBackground()); g.fillRect(0, 0, this.getWidth(), this.getHeight()); g.setColor(isSelected ? list.getSelectionForeground() : list .getForeground()); e.paintValue(g, box); } @Override public Dimension getPreferredSize() { Font f = this.getFont(); FontMetrics fm = this.getFontMetrics(f); return new Dimension(0, fm.getHeight()); } }; } catch (Exception ex) { return null; } } } /** * Updates the type of object being edited, so attempts to find an * appropriate propertyeditor. * * @param o a value of type 'Object' */ private void updateEditorType(Object o) { // Determine if the current object is an array if ((o != null) && (o.getClass().isArray())) { Class<?> elementClass = o.getClass().getComponentType(); PropertyEditor editor = PropertyEditorManager.findEditor(elementClass); Component view = null; ListCellRenderer lcr = new DefaultListCellRenderer(); if (editor != null) { if (editor instanceof GenericObjectEditor) { ((GenericObjectEditor) editor).setClassType(elementClass); } // setting the value in the editor so that // we don't get a NullPointerException // when we do getAsText() in the constructor of // PropertyValueSelector() if (Array.getLength(o) > 0) { editor.setValue(makeCopy(Array.get(o, 0))); } else { if (editor instanceof GenericObjectEditor) { ((GenericObjectEditor) editor).setDefaultValue(); } else { try { if (editor instanceof FileEditor) { editor.setValue(new java.io.File("-NONE-")); } else { editor.setValue(elementClass.newInstance()); } } catch (Exception ex) { m_ElementEditor = null; m_ListModel = null; removeAll(); System.err.println(ex.getMessage()); add(m_Label, BorderLayout.CENTER); m_Support.firePropertyChange("", null, null); validate(); return; } } } if (editor.isPaintable() && editor.supportsCustomEditor()) { view = new PropertyPanel(editor); lcr = new EditorListCellRenderer(editor.getClass(), elementClass); } else if (editor.getTags() != null) { view = new PropertyValueSelector(editor); } else if (editor.getAsText() != null) { view = new PropertyText(editor); } } if (view == null) { JOptionPane.showMessageDialog(this, "No property editor for class: " + elementClass.getName(), "Error...", JOptionPane.ERROR_MESSAGE); return; } else { removeAll(); m_ElementEditor = editor; try { m_Editor = editor.getClass().newInstance(); } catch (InstantiationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IllegalAccessException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // Create the ListModel and populate it m_ListModel = new DefaultListModel(); m_ElementClass = elementClass; for (int i = 0; i < Array.getLength(o); i++) { m_ListModel.addElement(Array.get(o, i)); } m_ElementList.setCellRenderer(lcr); m_ElementList.setModel(m_ListModel); if (m_ListModel.getSize() > 0) { m_ElementList.setSelectedIndex(0); } else { m_DeleteBut.setEnabled(false); m_EditBut.setEnabled(false); } m_UpBut.setEnabled(JListHelper.canMoveDown(m_ElementList)); m_DownBut.setEnabled(JListHelper.canMoveDown(m_ElementList)); // have already set the value above in the editor // try { // if (m_ListModel.getSize() > 0) { // m_ElementEditor.setValue(m_ListModel.getElementAt(0)); // } else { // if (m_ElementEditor instanceof GenericObjectEditor) { // ((GenericObjectEditor)m_ElementEditor).setDefaultValue(); // } else { // m_ElementEditor.setValue(m_ElementClass.newInstance()); // } // } JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); panel.add(view, BorderLayout.CENTER); panel.add(m_AddBut, BorderLayout.EAST); add(panel, BorderLayout.NORTH); add(new JScrollPane(m_ElementList), BorderLayout.CENTER); JPanel panel2 = new JPanel(); panel2.setLayout(new GridLayout(1, 4)); panel2.add(m_DeleteBut); panel2.add(m_EditBut); panel2.add(m_UpBut); panel2.add(m_DownBut); add(panel2, BorderLayout.SOUTH); m_ElementEditor .addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { repaint(); } }); // } catch (Exception ex) { // System.err.println(ex.getMessage()); // m_ElementEditor = null; // } } } if (m_ElementEditor == null) { add(m_Label, BorderLayout.CENTER); } m_Support.firePropertyChange("", null, null); validate(); } } public GenericArrayEditor() { m_customEditor = new CustomEditor(); } /** * Sets the current object array. * * @param o an object that must be an array. */ @Override public void setValue(Object o) { // Create a new list model, put it in the list and resize? m_customEditor.updateEditorType(o); } /** * Gets the current object array. * * @return the current object array */ @Override public Object getValue() { if (m_customEditor.m_ListModel == null) { return null; } // Convert the listmodel to an array of strings and return it. int length = m_customEditor.m_ListModel.getSize(); Object result = Array.newInstance(m_customEditor.m_ElementClass, length); for (int i = 0; i < length; i++) { Array.set(result, i, m_customEditor.m_ListModel.elementAt(i)); } return result; } /** * Supposedly returns an initialization string to create a classifier * identical to the current one, including it's state, but this doesn't appear * possible given that the initialization string isn't supposed to contain * multiple statements. * * @return the java source code initialisation string */ @Override public String getJavaInitializationString() { return "null"; } /** * Returns true to indicate that we can paint a representation of the string * array. * * @return true */ @Override public boolean isPaintable() { return true; } /** * Paints a representation of the current classifier. * * @param gfx the graphics context to use * @param box the area we are allowed to paint into */ @Override public void paintValue(java.awt.Graphics gfx, java.awt.Rectangle box) { FontMetrics fm = gfx.getFontMetrics(); int vpad = (box.height - fm.getHeight()) / 2; String rep = m_customEditor.m_ListModel.getSize() + " " + m_customEditor.m_ElementClass.getName(); gfx.drawString(rep, 2, fm.getAscent() + vpad + 2); } /** * Returns null as we don't support getting/setting values as text. * * @return null */ @Override public String getAsText() { return null; } /** * Returns null as we don't support getting/setting values as text. * * @param text the text value * @exception IllegalArgumentException as we don't support getting/setting * values as text. */ @Override public void setAsText(String text) { throw new IllegalArgumentException(text); } /** * Returns null as we don't support getting values as tags. * * @return null */ @Override public String[] getTags() { return null; } /** * Returns true because we do support a custom editor. * * @return true */ @Override public boolean supportsCustomEditor() { return true; } /** * Returns the array editing component. * * @return a value of type 'java.awt.Component' */ @Override public java.awt.Component getCustomEditor() { return m_customEditor; } /** * Adds a PropertyChangeListener who will be notified of value changes. * * @param l a value of type 'PropertyChangeListener' */ @Override public void addPropertyChangeListener(PropertyChangeListener l) { m_customEditor.m_Support.addPropertyChangeListener(l); } /** * Removes a PropertyChangeListener. * * @param l a value of type 'PropertyChangeListener' */ @Override public void removePropertyChangeListener(PropertyChangeListener l) { m_customEditor.m_Support.removePropertyChangeListener(l); } /** * Makes a copy of an object using serialization. * * @param source the object to copy * @return a copy of the source object, null if copying fails */ public static Object makeCopy(Object source) { Object result; try { result = GenericObjectEditor.makeCopy(source); } catch (Exception e) { result = null; } return result; } /** * Tests out the array editor from the command line. * * @param args ignored */ public static void main(String[] args) { try { GenericObjectEditor.registerEditors(); final GenericArrayEditor ce = new GenericArrayEditor(); final weka.filters.Filter[] initial = new weka.filters.Filter[0]; /* * { new weka.filters.AddFilter() }; */ /* * final String [] initial = { "Hello", "There", "Bob" }; */ PropertyDialog pd = new PropertyDialog((Frame) null, ce, 100, 100); pd.setSize(200, 200); pd.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); ce.setValue(initial); pd.setVisible(true); // ce.validate(); } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/GenericObjectEditor.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * GenericObjectEditor.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import weka.core.Capabilities; import weka.core.Capabilities.Capability; import weka.core.CapabilitiesHandler; import weka.core.ClassDiscovery; import weka.core.CustomDisplayStringProvider; import weka.core.InheritanceUtils; import weka.core.OptionHandler; import weka.core.SerializationHelper; import weka.core.SerializedObject; import weka.core.Utils; import weka.core.WekaPackageClassLoaderManager; import weka.core.WekaPackageManager; import weka.core.logging.Logger; import weka.gui.CheckBoxList.CheckBoxListModel; import weka.core.PluginManager; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import java.awt.*; import java.awt.event.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.beans.PropertyEditor; import java.beans.PropertyEditorManager; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import java.util.Vector; /** * A PropertyEditor for objects. It can be used either in a static or a dynamic * way. <br> * <br> * In the <b>static</b> way (<code>USE_DYNAMIC</code> is <code>false</code>) the * objects have been defined as editable in the GenericObjectEditor * configuration file, which lists possible values that can be selected from, * and themselves configured. The configuration file is called * "GenericObjectEditor.props" and may live in either the location given by * "user.home" or the current directory (this last will take precedence), and a * default properties file is read from the Weka distribution. For speed, the * properties file is read only once when the class is first loaded -- this may * need to be changed if we ever end up running in a Java OS ;-). <br> * <br> * If it is used in a <b>dynamic</b> way (the <code>UseDynamic</code> property * of the GenericPropertiesCreator props file is set to <code>true</code>) then * the classes to list are discovered by the * <code>GenericPropertiesCreator</code> class (it checks the complete * classpath). * * @see GenericPropertiesCreator * @see GenericPropertiesCreator#useDynamic() * @see GenericPropertiesCreator#CREATOR_FILE * @see weka.core.ClassDiscovery * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @author Xin Xu (xx5@cs.waikato.ac.nz) * @author Richard Kirkby (rkirkby@cs.waikato.ac.nz) * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier { /** The object being configured. */ protected Object m_Object; /** * Holds a copy of the current object that can be reverted to if the user * decides to cancel. */ protected Object m_Backup; /** Handles property change notification. */ protected PropertyChangeSupport m_Support = new PropertyChangeSupport(this); /** The Class of objects being edited. */ protected Class<?> m_ClassType; /** The model containing the list of names to select from. */ protected Hashtable<String, HierarchyPropertyParser> m_ObjectNames; /** The GUI component for editing values, created when needed. */ protected GOEPanel m_EditorComponent; /** True if the cancel button was pressed */ protected boolean m_CancelWasPressed; /** True if the GUI component is needed. */ protected boolean m_Enabled = true; /** The name of the properties file. */ protected static String PROPERTY_FILE = "weka/gui/GenericObjectEditor.props"; /** Contains the editor properties. */ protected static Properties EDITOR_PROPERTIES; /** the properties files containing the class/editor mappings. */ public static final String GUIEDITORS_PROPERTY_FILE = "weka/gui/GUIEditors.props"; /** The tree node of the current object so we can re-select it for the user. */ protected GOETreeNode m_treeNodeOfCurrentObject; /** The property panel created for the objects. */ protected PropertyPanel m_ObjectPropertyPanel; /** whether the class can be changed. */ protected boolean m_canChangeClassInDialog; /** the history of used setups. */ protected GenericObjectEditorHistory m_History; /** whether the Weka Editors were already registered. */ protected static boolean m_EditorsRegistered; /** whether to display the global info tool tip in the tree. */ protected static boolean m_ShowGlobalInfoToolTip; /** for filtering the tree based on the Capabilities of the leaves. */ protected Capabilities m_CapabilitiesFilter = null; public static void setShowGlobalInfoToolTips(boolean show) { m_ShowGlobalInfoToolTip = show; } public boolean getShowGlobalInfoToolTips() { return m_ShowGlobalInfoToolTip; } public static void determineClasses() { try { // make sure we load all packages first!!! WekaPackageManager.loadPackages(false); // Don't do anything else until all initial packages are loaded... if (WekaPackageManager.m_initialPackageLoadingInProcess) { return; } EDITOR_PROPERTIES = GenericPropertiesCreator.getGlobalOutputProperties(); if (EDITOR_PROPERTIES == null) { // try creating a new one from scratch GenericPropertiesCreator creator = new GenericPropertiesCreator(); // dynamic approach? if (creator.useDynamic()) { try { creator.execute(false); EDITOR_PROPERTIES = creator.getOutputProperties(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Could not determine the properties for the generic object\n" + "editor. This exception was produced:\n" + e.toString(), "GenericObjectEditor", JOptionPane.ERROR_MESSAGE); } } else { // Allow a properties file in the current directory to override try { EDITOR_PROPERTIES = Utils.readProperties(PROPERTY_FILE); java.util.Enumeration<?> keys = EDITOR_PROPERTIES.propertyNames(); if (!keys.hasMoreElements()) { throw new Exception("Failed to read a property file for the " + "generic object editor"); } } catch (Exception ex) { JOptionPane .showMessageDialog( null, "Could not read a configuration file for the generic object\n" + "editor. An example file is included with the Weka distribution.\n" + "This file should be named \"" + PROPERTY_FILE + "\" and\n" + "should be placed either in your user home (which is set\n" + "to \"" + System.getProperties().getProperty("user.home") + "\")\n" + "or the directory that java was started from\n", "GenericObjectEditor", JOptionPane.ERROR_MESSAGE); } } } if (EDITOR_PROPERTIES == null) { JOptionPane.showMessageDialog(null, "Could not initialize the GenericPropertiesCreator. ", "GenericObjectEditor", JOptionPane.ERROR_MESSAGE); } else { PluginManager.addFromProperties(EDITOR_PROPERTIES); } } catch (Exception e) { JOptionPane.showMessageDialog(null, "Could not initialize the GenericPropertiesCreator. " + "This exception was produced:\n" + e.toString(), "GenericObjectEditor", JOptionPane.ERROR_MESSAGE); } } /** * Loads the configuration property file (USE_DYNAMIC is FALSE) or determines * the classes dynamically (USE_DYNAMIC is TRUE) * * @see #USE_DYNAMIC * @see GenericPropertiesCreator */ static { determineClasses(); } /** * A specialized TreeNode for supporting filtering via Capabilities. */ public class GOETreeNode extends DefaultMutableTreeNode { /** for serialization. */ static final long serialVersionUID = -1707872446682150133L; /** color for "no support". */ public final static String NO_SUPPORT = "silver"; /** color for "maybe support". */ public final static String MAYBE_SUPPORT = "blue"; /** the Capabilities object to use for filtering. */ protected Capabilities m_Capabilities = null; /** tool tip */ protected String m_toolTipText; /** * Creates a tree node that has no parent and no children, but which allows * children. */ public GOETreeNode() { super(); } /** * Creates a tree node with no parent, no children, but which allows * children, and initializes it with the specified user object. * * @param userObject an Object provided by the user that constitutes the * node's data */ public GOETreeNode(Object userObject) { super(userObject); } /** * Creates a tree node with no parent, no children, initialized with the * specified user object, and that allows children only if specified. * * @param userObject an Object provided by the user that constitutes the * node's data * @param allowsChildren if true, the node is allowed to have child nodes -- * otherwise, it is always a leaf node */ public GOETreeNode(Object userObject, boolean allowsChildren) { super(userObject, allowsChildren); } /** * Set the tool tip for this node * * @param tip the tool tip for this node */ public void setToolTipText(String tip) { m_toolTipText = tip; } /** * Get the tool tip for this node * * @return the tool tip for this node */ public String getToolTipText() { return m_toolTipText; } /** * generates if necessary a Capabilities object for the given leaf. */ protected void initCapabilities() { String classname; Class<?> cls; Object obj; if (m_Capabilities != null) { return; } if (!isLeaf()) { return; } classname = getClassnameFromPath(new TreePath(getPath())); try { // cls = Class.forName(classname); cls = WekaPackageClassLoaderManager.forName(classname); if (!InheritanceUtils.hasInterface(CapabilitiesHandler.class, cls)) { return; } obj = cls.newInstance(); m_Capabilities = ((CapabilitiesHandler) obj).getCapabilities(); } catch (Exception e) { // ignore it } } /** * returns a string representation of this treenode. * * @return the text to display */ @Override public String toString() { String result; result = super.toString(); if (m_CapabilitiesFilter != null) { initCapabilities(); if (m_Capabilities != null) { if (m_Capabilities.supportsMaybe(m_CapabilitiesFilter) && !m_Capabilities.supports(m_CapabilitiesFilter)) { result = "<html><font color=\"" + MAYBE_SUPPORT + "\">" + result + "</font></i><html>"; } else if (!m_Capabilities.supports(m_CapabilitiesFilter)) { result = "<html><font color=\"" + NO_SUPPORT + "\">" + result + "</font></i><html>"; } } } return result; } } /** * A dialog for selecting Capabilities to look for in the GOE tree. */ public class CapabilitiesFilterDialog extends JDialog { /** for serialization. */ static final long serialVersionUID = -7845503345689646266L; /** the dialog itself. */ protected JDialog m_Self; /** the popup to display again. */ protected JPopupMenu m_Popup = null; /** the capabilities used for initializing the dialog. */ protected Capabilities m_Capabilities = new Capabilities(null); /** the label, listing the name of the superclass. */ protected JLabel m_InfoLabel = new JLabel(); /** the list with all the capabilities. */ protected CheckBoxList m_List = new CheckBoxList(); /** the OK button. */ protected JButton m_OkButton = new JButton("OK"); /** the Cancel button. */ protected JButton m_CancelButton = new JButton("Cancel"); /** * creates a dialog to choose Capabilities from. */ public CapabilitiesFilterDialog() { super(); m_Self = this; initGUI(); } /** * sets up the GUI. */ protected void initGUI() { JPanel panel; CheckBoxListModel model; setTitle("Filtering Capabilities..."); setLayout(new BorderLayout()); panel = new JPanel(new BorderLayout()); panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); getContentPane().add(panel, BorderLayout.NORTH); m_InfoLabel.setText("<html>" + m_ClassType.getName().replaceAll(".*\\.", "") + "s" + " have to support <i>at least</i> the following capabilities <br>" + "(the ones highlighted <font color=\"" + GOETreeNode.NO_SUPPORT + "\">" + GOETreeNode.NO_SUPPORT + "</font> don't meet these requirements <br>" + "the ones highlighted <font color=\"" + GOETreeNode.MAYBE_SUPPORT + "\">" + GOETreeNode.MAYBE_SUPPORT + "</font> possibly meet them):" + "</html>"); panel.add(m_InfoLabel, BorderLayout.CENTER); // list getContentPane().add(new JScrollPane(m_List), BorderLayout.CENTER); model = (CheckBoxListModel) m_List.getModel(); for (Capability cap : Capability.values()) { model.addElement(cap); } // buttons panel = new JPanel(new FlowLayout(FlowLayout.CENTER)); getContentPane().add(panel, BorderLayout.SOUTH); m_OkButton.setMnemonic('O'); m_OkButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateCapabilities(); if (m_CapabilitiesFilter == null) { m_CapabilitiesFilter = new Capabilities(null); } m_CapabilitiesFilter.assign(m_Capabilities); m_Self.setVisible(false); showPopup(); } }); panel.add(m_OkButton); m_CancelButton.setMnemonic('C'); m_CancelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_Self.setVisible(false); showPopup(); } }); panel.add(m_CancelButton); pack(); } /** * transfers the Capabilities object to the JList. * * @see #m_Capabilities * @see #m_List */ protected void updateList() { CheckBoxListModel model; model = (CheckBoxListModel) m_List.getModel(); for (Capability cap : Capability.values()) { model.setChecked(model.indexOf(cap), m_Capabilities.handles(cap)); } } /** * transfers the selected Capabilities from the JList to the Capabilities * object. * * @see #m_Capabilities * @see #m_List */ protected void updateCapabilities() { CheckBoxListModel model; model = (CheckBoxListModel) m_List.getModel(); for (Capability cap : Capability.values()) { if (model.getChecked(model.indexOf(cap))) { m_Capabilities.enable(cap); } else { m_Capabilities.disable(cap); } } } /** * sets the initial capabilities. * * @param value the capabilities to use */ public void setCapabilities(Capabilities value) { if (value != null) { m_Capabilities.assign(value); } else { m_Capabilities = new Capabilities(null); } updateList(); } /** * returns the currently selected capabilities. * * @return the currently selected capabilities */ public Capabilities getCapabilities() { return m_Capabilities; } /** * sets the JPopupMenu to display again after closing the dialog. * * @param value the JPopupMenu to display again */ public void setPopup(JPopupMenu value) { m_Popup = value; } /** * returns the currently set JPopupMenu. * * @return the current JPopupMenu */ public JPopupMenu getPopup() { return m_Popup; } /** * if a JPopupMenu is set, it is displayed again. Displaying this dialog * closes any JPopupMenu automatically. */ public void showPopup() { if (getPopup() != null) { getPopup().setVisible(true); } } } /** * Creates a popup menu containing a tree that is aware of the screen * dimensions. */ public class JTreePopupMenu extends JPopupMenu { /** for serialization. */ static final long serialVersionUID = -3404546329655057387L; /** the popup itself. */ private final JPopupMenu m_Self; /** The tree. */ private final JTree m_tree; /** The scroller. */ private final JScrollPane m_scroller; /** The filter button in case of CapabilitiesHandlers. */ private final JButton m_FilterButton = new JButton("Filter..."); /** The remove filter button in case of CapabilitiesHandlers. */ private final JButton m_RemoveFilterButton = new JButton("Remove filter"); /** The button for closing the popup again. */ private final JButton m_CloseButton = new JButton("Close"); /** * Constructs a new popup menu. * * @param tree the tree to put in the menu */ public JTreePopupMenu(JTree tree) { m_Self = this; setLayout(new BorderLayout()); JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); add(panel, BorderLayout.SOUTH); if (InheritanceUtils.hasInterface(CapabilitiesHandler.class, m_ClassType)) { // filter m_FilterButton.setMnemonic('F'); m_FilterButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == m_FilterButton) { CapabilitiesFilterDialog dialog = new CapabilitiesFilterDialog(); dialog.setCapabilities(m_CapabilitiesFilter); dialog.setPopup(m_Self); dialog.setLocationRelativeTo(m_Self); dialog.setVisible(true); m_Support.firePropertyChange("", null, null); repaint(); } } }); panel.add(m_FilterButton); // remove m_RemoveFilterButton.setMnemonic('R'); m_RemoveFilterButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == m_RemoveFilterButton) { m_CapabilitiesFilter = null; m_Support.firePropertyChange("", null, null); repaint(); } } }); panel.add(m_RemoveFilterButton); } // close m_CloseButton.setMnemonic('C'); m_CloseButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == m_CloseButton) { m_Self.setVisible(false); } } }); panel.add(m_CloseButton); m_tree = tree; JPanel treeView = new JPanel(); treeView.setLayout(new BorderLayout()); treeView.add(m_tree, BorderLayout.NORTH); // make backgrounds look the same treeView.setBackground(m_tree.getBackground()); m_scroller = new JScrollPane(treeView); m_scroller.setPreferredSize(new Dimension(350, 500)); m_scroller.getVerticalScrollBar().setUnitIncrement(20); add(m_scroller); } /** * Displays the menu, making sure it will fit on the screen. * * @param invoker the component thast invoked the menu * @param x the x location of the popup * @param y the y location of the popup */ @Override public void show(Component invoker, int x, int y) { super.show(invoker, x, y); // calculate available screen area for popup Rectangle r = new Rectangle(); GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice[] gs = ge.getScreenDevices(); for (int j = 0; j < gs.length; j++) { GraphicsDevice gd = gs[j]; GraphicsConfiguration[] gc = gd.getConfigurations(); for (int i =0 ; i < gc.length; i++) { r = r.union(gc[i].getBounds()); } } java.awt.Point location = invoker.getLocationOnScreen(); int maxWidth = (int) (r.getX() + r.getWidth() - location.getX()); int maxHeight = (int) (r.getY() + r.getHeight() - location.getY()); // if the part of the popup goes off the screen then resize it Dimension size = getPreferredSize(); int height = (int) size.getHeight(); int width = (int) size.getWidth(); if (width > maxWidth) { width = maxWidth; } if (height > maxHeight) { height = maxHeight; } // commit any size changes setPreferredSize(new Dimension(width, height)); setLocation(location); revalidate(); pack(); m_tree.requestFocusInWindow(); } } /** * Handles the GUI side of editing values. */ public class GOEPanel extends JPanel { /** for serialization. */ static final long serialVersionUID = 3656028520876011335L; /** The component that performs classifier customization. */ protected PropertySheetPanel m_ChildPropertySheet; /** The name of the current class. */ protected JLabel m_ClassNameLabel; /** Open object from disk. */ protected JButton m_OpenBut; /** Save object to disk. */ protected JButton m_SaveBut; /** ok button. */ protected JButton m_okBut; /** cancel button. */ protected JButton m_cancelBut; /** The filechooser for opening and saving object files. */ protected JFileChooser m_FileChooser; /** Creates the GUI editor component. */ public GOEPanel() { m_Backup = copyObject(m_Object); m_ClassNameLabel = new JLabel("None"); m_ClassNameLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); m_ChildPropertySheet = new PropertySheetPanel(); m_ChildPropertySheet .addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { m_Support.firePropertyChange("", null, null); } }); m_OpenBut = new JButton("Open..."); m_OpenBut.setToolTipText("Load a configured object"); m_OpenBut.setEnabled(true); m_OpenBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object object = openObject(); if (object != null) { // setValue takes care of: Making sure obj is of right type, // and firing property change. setValue(object); // Need a second setValue to get property values filled in OK. // Not sure why. setValue(object); } } }); m_SaveBut = new JButton("Save..."); m_SaveBut.setToolTipText("Save the current configured object"); m_SaveBut.setEnabled(true); m_SaveBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { saveObject(m_Object); } }); m_okBut = new JButton("OK"); m_okBut.setEnabled(true); m_okBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_ChildPropertySheet.closingOK(); m_CancelWasPressed = false; m_Backup = copyObject(m_Object); if ((getTopLevelAncestor() != null) && (getTopLevelAncestor() instanceof Window)) { Window w = (Window) getTopLevelAncestor(); w.dispose(); } } }); m_cancelBut = new JButton("Cancel"); m_cancelBut.setEnabled(true); m_cancelBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_ChildPropertySheet.closingCancel(); m_CancelWasPressed = true; if (m_Backup != null) { m_Object = copyObject(m_Backup); // To fire property change m_Support.firePropertyChange("", null, null); m_ObjectNames = getClassesFromProperties(); updateObjectNames(); updateChildPropertySheet(); } if ((getTopLevelAncestor() != null) && (getTopLevelAncestor() instanceof Window)) { Window w = (Window) getTopLevelAncestor(); w.dispose(); } } }); setLayout(new BorderLayout()); if (m_canChangeClassInDialog) { JButton chooseButton = createChooseClassButton(); JPanel top = new JPanel(); top.setLayout(new BorderLayout()); top.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); top.add(chooseButton, BorderLayout.WEST); top.add(m_ClassNameLabel, BorderLayout.CENTER); add(top, BorderLayout.NORTH); } else { add(m_ClassNameLabel, BorderLayout.NORTH); } add(m_ChildPropertySheet, BorderLayout.CENTER); // Since we resize to the size of the property sheet, a scrollpane isn't // typically needed // add(new JScrollPane(m_ChildPropertySheet), BorderLayout.CENTER); JPanel okcButs = new JPanel(); okcButs.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); okcButs.setLayout(new GridLayout(1, 4, 5, 5)); okcButs.add(m_OpenBut); okcButs.add(m_SaveBut); okcButs.add(m_okBut); okcButs.add(m_cancelBut); add(okcButs, BorderLayout.SOUTH); if (m_ClassType != null) { m_ObjectNames = getClassesFromProperties(); if (m_Object != null) { updateObjectNames(); updateChildPropertySheet(); } } } /** * Enables/disables the cancel button. * * @param flag true to enable cancel button, false to disable it */ protected void setCancelButton(boolean flag) { if (m_cancelBut != null) { m_cancelBut.setEnabled(flag); } } /** * Opens an object from a file selected by the user. * * @return the loaded object, or null if the operation was cancelled */ protected Object openObject() { if (m_FileChooser == null) { createFileChooser(); } int returnVal = m_FileChooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File selected = m_FileChooser.getSelectedFile(); try { ObjectInputStream oi = SerializationHelper.getObjectInputStream(new BufferedInputStream(new FileInputStream(selected))); /* ObjectInputStream oi = new ObjectInputStream(new BufferedInputStream( new FileInputStream(selected))); */ Object obj = oi.readObject(); oi.close(); if (!m_ClassType.isAssignableFrom(obj.getClass())) { throw new Exception("Object not of type: " + m_ClassType.getName()); } return obj; } catch (Exception ex) { JOptionPane.showMessageDialog(this, "Couldn't read object: " + selected.getName() + "\n" + ex.getMessage(), "Open object file", JOptionPane.ERROR_MESSAGE); } } return null; } /** * Saves an object to a file selected by the user. * * @param object the object to save */ protected void saveObject(Object object) { if (m_FileChooser == null) { createFileChooser(); } int returnVal = m_FileChooser.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File sFile = m_FileChooser.getSelectedFile(); try { ObjectOutputStream oo = new ObjectOutputStream( new BufferedOutputStream(new FileOutputStream(sFile))); oo.writeObject(object); oo.close(); } catch (Exception ex) { JOptionPane.showMessageDialog(this, "Couldn't write to file: " + sFile.getName() + "\n" + ex.getMessage(), "Save object", JOptionPane.ERROR_MESSAGE); } } } /** * Creates the file chooser the user will use to save/load files with. */ protected void createFileChooser() { m_FileChooser = new JFileChooser(new File(System.getProperty("user.dir"))); m_FileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); } /** * Makes a copy of an object using serialization. * * @param source the object to copy * @return a copy of the source object */ protected Object copyObject(Object source) { Object result = null; try { result = GenericObjectEditor.makeCopy(source); setCancelButton(true); } catch (Exception ex) { setCancelButton(false); Logger.log(weka.core.logging.Logger.Level.WARNING, "GenericObjectEditor: Problem making backup object"); Logger.log(weka.core.logging.Logger.Level.WARNING, ex); } return result; } /** * Allows customization of the action label on the dialog. * * @param newLabel the new string for the ok button */ public void setOkButtonText(String newLabel) { m_okBut.setText(newLabel); } /** * This is used to hook an action listener to the ok button. * * @param a The action listener. */ public void addOkListener(ActionListener a) { m_okBut.addActionListener(a); } /** * This is used to hook an action listener to the cancel button. * * @param a The action listener. */ public void addCancelListener(ActionListener a) { m_cancelBut.addActionListener(a); } /** * This is used to remove an action listener from the ok button. * * @param a The action listener */ public void removeOkListener(ActionListener a) { m_okBut.removeActionListener(a); } /** * This is used to remove an action listener from the cancel button. * * @param a The action listener */ public void removeCancelListener(ActionListener a) { m_cancelBut.removeActionListener(a); } /** * Updates the child property sheet, and creates if needed. */ public void updateChildPropertySheet() { // Update the object name displayed String className = "None"; if (m_Object != null) { className = m_Object.getClass().getName(); } m_ClassNameLabel.setText(className); // Set the object as the target of the propertysheet m_ChildPropertySheet.setTarget(m_Object); // Adjust size of containing window if possible if ((getTopLevelAncestor() != null) && (getTopLevelAncestor() instanceof Window)) { ((Window) getTopLevelAncestor()).pack(); } } } /** * Default constructor. */ public GenericObjectEditor() { this(false); } /** * Constructor that allows specifying whether it is possible to change the * class within the editor dialog. * * @param canChangeClassInDialog whether the user can change the class */ public GenericObjectEditor(boolean canChangeClassInDialog) { m_canChangeClassInDialog = canChangeClassInDialog; m_History = new GenericObjectEditorHistory(); ToolTipManager.sharedInstance().setDismissDelay(7000); } /** * registers all the editors in Weka. */ public static void registerEditors() { Properties props; Enumeration<?> enm; String name; String value; if (m_EditorsRegistered) { return; } Logger.log(weka.core.logging.Logger.Level.INFO, "---Registering Weka Editors---"); m_EditorsRegistered = true; // load properties try { props = Utils.readProperties(GUIEDITORS_PROPERTY_FILE); } catch (Exception e) { props = new Properties(); e.printStackTrace(); } // show the tool tip? m_ShowGlobalInfoToolTip = props.getProperty( "ShowGlobalInfoToolTip", "true").equals("true"); enm = props.propertyNames(); while (enm.hasMoreElements()) { name = enm.nextElement().toString(); value = props.getProperty(name, ""); registerEditor(name, value); } } public static void registerEditor(String name, String value) { // skip (and don't try to instantiate) the ShowGlobalInfoToolTip // property as a class; and any other non-class properties. Makes // the assumption that anything that should be instantiated is not // in the default package. if (!name.contains(".")) { return; } Class<?> baseCls; Class<?> cls; try { // array class? if (name.endsWith("[]")) { //baseCls = Class.forName(name.substring(0, name.indexOf("[]"))); baseCls = WekaPackageClassLoaderManager.forName(name.substring(0, name.indexOf("[]"))); cls = Array.newInstance(baseCls, 1).getClass(); } else { // cls = Class.forName(name); cls = WekaPackageClassLoaderManager.forName(name); } // register //PropertyEditorManager.registerEditor(cls, Class.forName(value)); PropertyEditorManager.registerEditor(cls, WekaPackageClassLoaderManager.forName(value)); } catch (Exception e) { Logger.log(weka.core.logging.Logger.Level.WARNING, "Problem registering " + name + "/" + value + ": " + e); } } /** * Sets whether the user can change the class in the dialog. * * @param value if true then the user can change the class */ public void setCanChangeClassInDialog(boolean value) { m_canChangeClassInDialog = value; } /** * Returns whether the user can change the class in the dialog. * * @return true if the user can change the class */ public boolean getCanChangeClassInDialog() { return m_canChangeClassInDialog; } /** * Returns the backup object (may be null if there is no backup. * * @return the backup object */ public Object getBackup() { return m_Backup; } /** * returns the name of the root element of the given class name, * <code>null</code> if it doesn't contain the separator. * * @param clsname the full classname * @param separator the separator * @return string the root element */ protected static String getRootFromClass(String clsname, String separator) { if (clsname.indexOf(separator) > -1) { return clsname.substring(0, clsname.indexOf(separator)); } else { return null; } } /** * parses the given string of classes separated by ", " and returns the a * hashtable with as many entries as there are different root elements in the * class names (the key is the root element). E.g. if there's only "weka." as * the prefix for all classes the a hashtable of size 1 is returned. if NULL * is the input, then NULL is also returned. * * @param classes the classnames to work on * @return for each distinct root element in the classnames, one entry in the * hashtable (with the root element as key) */ public static Hashtable<String, String> sortClassesByRoot(String classes) { Hashtable<String, Vector<String>> roots; Hashtable<String, String> result; Enumeration<String> enm; int i; StringTokenizer tok; String clsname; Vector<String> list; HierarchyPropertyParser hpp; String separator; String root; String tmpStr; if (classes == null) { return null; } roots = new Hashtable<String, Vector<String>>(); hpp = new HierarchyPropertyParser(); separator = hpp.getSeperator(); // go over all classnames and store them in the hashtable, with the // root element as the key tok = new StringTokenizer(classes, ", "); while (tok.hasMoreElements()) { clsname = tok.nextToken(); root = getRootFromClass(clsname, separator); if (root == null) { continue; } // already stored? if (!roots.containsKey(root)) { list = new Vector<String>(); roots.put(root, list); } else { list = roots.get(root); } list.add(clsname); } // build result result = new Hashtable<String, String>(); enm = roots.keys(); while (enm.hasMoreElements()) { root = enm.nextElement(); list = roots.get(root); tmpStr = ""; for (i = 0; i < list.size(); i++) { if (i > 0) { tmpStr += ","; } tmpStr += list.get(i); } result.put(root, tmpStr); } return result; } /** * Called when the class of object being edited changes. * * @return the hashtable containing the HierarchyPropertyParsers for the root * elements */ protected Hashtable<String, HierarchyPropertyParser> getClassesFromProperties() { Hashtable<String, HierarchyPropertyParser> hpps = new Hashtable<String, HierarchyPropertyParser>(); String className = m_ClassType.getName(); Set<String> cls = PluginManager.getPluginNamesOfType(className); if (cls == null) { return hpps; } List<String> toSort = new ArrayList<String>(cls); Collections.sort(toSort, new ClassDiscovery.StringCompare()); StringBuilder b = new StringBuilder(); for (String s : toSort) { b.append(s).append(","); } String listS = b.substring(0, b.length() - 1); // Hashtable typeOptions = // sortClassesByRoot(EDITOR_PROPERTIES.getProperty(className)); Hashtable<String, String> typeOptions = sortClassesByRoot(listS); if (typeOptions == null) { /* * System.err.println("Warning: No configuration property found in\n" + * PROPERTY_FILE + "\n" + "for " + className); */ } else { try { Enumeration<String> enm = typeOptions.keys(); while (enm.hasMoreElements()) { String root = enm.nextElement(); String typeOption = typeOptions.get(root); HierarchyPropertyParser hpp = new HierarchyPropertyParser(); hpp.build(typeOption, ", "); hpps.put(root, hpp); } } catch (Exception ex) { Logger.log(weka.core.logging.Logger.Level.WARNING, "Invalid property: " + typeOptions); } } return hpps; } /** * Updates the list of selectable object names, adding any new names to the * list. */ protected void updateObjectNames() { if (m_ObjectNames == null) { m_ObjectNames = getClassesFromProperties(); } if (m_Object != null) { String className = m_Object.getClass().getName(); String root = getRootFromClass(className, new HierarchyPropertyParser().getSeperator()); HierarchyPropertyParser hpp = m_ObjectNames.get(root); if (hpp != null) { if (!hpp.contains(className)) { hpp.add(className); } } } } /** * Sets whether the editor is "enabled", meaning that the current values will * be painted. * * @param newVal a value of type 'boolean' */ public void setEnabled(boolean newVal) { if (newVal != m_Enabled) { m_Enabled = newVal; } } /** * Sets the class of values that can be edited. * * @param type a value of type 'Class' */ public void setClassType(Class<?> type) { m_ClassType = type; m_ObjectNames = getClassesFromProperties(); } /** * Sets the current object to be the default, taken as the first item in the * chooser. */ public void setDefaultValue() { if (m_ClassType == null) { Logger.log(weka.core.logging.Logger.Level.WARNING, "No ClassType set up for GenericObjectEditor!!"); return; } Hashtable<String, HierarchyPropertyParser> hpps = getClassesFromProperties(); HierarchyPropertyParser hpp = null; Enumeration<HierarchyPropertyParser> enm = hpps.elements(); try { while (enm.hasMoreElements()) { hpp = enm.nextElement(); if (hpp.depth() > 0) { hpp.goToRoot(); while (!hpp.isLeafReached()) { hpp.goToChild(0); } String defaultValue = hpp.fullValue(); // setValue(Class.forName(defaultValue).newInstance()); setValue(WekaPackageClassLoaderManager.forName(defaultValue).newInstance()); } } } catch (Exception ex) { Logger.log(weka.core.logging.Logger.Level.WARNING, "Problem loading the first class: " + hpp.fullValue()); ex.printStackTrace(); } } /** * True if the cancel button was used to close the editor. * * @return true if the cancel button was pressed the last time the * editor was closed */ public boolean wasCancelPressed() { return m_CancelWasPressed; } /** * Sets the current Object. If the Object is in the Object chooser, this * becomes the selected item (and added to the chooser if necessary). * * @param o an object that must be a Object. */ @Override public void setValue(Object o) { if (m_ClassType == null) { JOptionPane.showMessageDialog(null, "No ClassType set up for GenericObjectEditor.", "Error...", JOptionPane.ERROR_MESSAGE); Logger.log(weka.core.logging.Logger.Level.WARNING, "No ClassType set up for GenericObjectEditor!"); return; } if (!m_ClassType.isAssignableFrom(o.getClass())) { JOptionPane.showMessageDialog(null, "Object not of correct type and cannot be assigned.", "Error...", JOptionPane.ERROR_MESSAGE); Logger.log(weka.core.logging.Logger.Level.WARNING, "Object not of correct type and cannot be assigned!"); return; } setObject(o); if (m_EditorComponent != null) { m_EditorComponent.repaint(); } updateObjectNames(); m_CancelWasPressed = false; } /** * Sets the current Object. * * @param c a value of type 'Object' */ protected void setObject(Object c) { // This should really call equals() for comparison. boolean trueChange; if (getValue() != null) { trueChange = (!c.equals(getValue())); } else { trueChange = true; } m_Backup = m_Object; m_Object = c; if (m_EditorComponent != null) { m_EditorComponent.updateChildPropertySheet(); } if (trueChange) { m_Support.firePropertyChange("", null, null); } } /** * Gets the current Object. * * @return the current Object */ @Override public Object getValue() { Object result = null; try { result = makeCopy(m_Object); } catch (Exception ex) { ex.printStackTrace(); } return result; } /** * Supposedly returns an initialization string to create a Object identical to * the current one, including it's state, but this doesn't appear possible * given that the initialization string isn't supposed to contain multiple * statements. * * @return the java source code initialisation string */ @Override public String getJavaInitializationString() { return "new " + m_Object.getClass().getName() + "()"; } /** * Returns true to indicate that we can paint a representation of the Object. * * @return true */ @Override public boolean isPaintable() { return true; } /** * Paints a representation of the current Object. * * @param gfx the graphics context to use * @param box the area we are allowed to paint into */ @Override public void paintValue(java.awt.Graphics gfx, java.awt.Rectangle box) { if (m_Enabled) { String rep; if (m_Object != null) { if (m_Object instanceof CustomDisplayStringProvider) { rep = ((CustomDisplayStringProvider) m_Object).toDisplay(); } else { rep = m_Object.getClass().getName(); int dotPos = rep.lastIndexOf('.'); if (dotPos != -1) { rep = rep.substring(dotPos + 1); } } } else { rep = "None"; } java.awt.Font originalFont = gfx.getFont(); gfx.setFont(originalFont.deriveFont(java.awt.Font.BOLD)); FontMetrics fm = gfx.getFontMetrics(); int vpad = (box.height - fm.getHeight()); gfx.drawString(rep, 2, fm.getAscent() + vpad); int repwidth = fm.stringWidth(rep); gfx.setFont(originalFont); if ((m_Object instanceof OptionHandler) && !(m_Object instanceof CustomDisplayStringProvider)) { gfx.drawString( " " + Utils.joinOptions(((OptionHandler) m_Object).getOptions()), repwidth + 2, fm.getAscent() + vpad); } } } /** * Returns null as we don't support getting/setting values as text. * * @return null */ @Override public String getAsText() { return null; } /** * Returns null as we don't support getting/setting values as text. * * @param text the text value * @throws IllegalArgumentException as we don't support getting/setting values * as text. */ @Override public void setAsText(String text) { throw new IllegalArgumentException(text); } /** * Returns null as we don't support getting values as tags. * * @return null */ @Override public String[] getTags() { return null; } /** * Returns true because we do support a custom editor. * * @return true */ @Override public boolean supportsCustomEditor() { return true; } /** * Returns the array editing component. * * @return a value of type 'java.awt.Component' */ @Override public java.awt.Component getCustomEditor() { if (m_EditorComponent == null) { m_EditorComponent = new GOEPanel(); } return m_EditorComponent; } /** * Adds a PropertyChangeListener who will be notified of value changes. * * @param l a value of type 'PropertyChangeListener' */ @Override public void addPropertyChangeListener(PropertyChangeListener l) { m_Support.addPropertyChangeListener(l); } /** * Removes a PropertyChangeListener. * * @param l a value of type 'PropertyChangeListener' */ @Override public void removePropertyChangeListener(PropertyChangeListener l) { m_Support.removePropertyChangeListener(l); } /** * Gets the custom panel used for editing the object. * * @return the panel */ @Override public JPanel getCustomPanel() { final JButton chooseButton = createChooseClassButton(); m_ObjectPropertyPanel = new PropertyPanel(this, true); JPanel customPanel = new JPanel() { /** ID added to avoid warning */ private static final long serialVersionUID = 1024049543672124980L; @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); chooseButton.setEnabled(enabled); } }; customPanel.setLayout(new BorderLayout()); customPanel.add(chooseButton, BorderLayout.WEST); customPanel.add(m_ObjectPropertyPanel, BorderLayout.CENTER); return customPanel; } /** * Creates a button that when clicked will enable the user to change the class * of the object being edited. * * @return the choose button */ protected JButton createChooseClassButton() { JButton setButton = new JButton("Choose"); // anonymous action listener shows a JTree popup and allows the user // to choose the class they want setButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JPopupMenu popup = getChooseClassPopupMenu(); // show the popup where the source component is if (e.getSource() instanceof Component) { Component comp = (Component) e.getSource(); popup.show(comp, comp.getX(), comp.getY()); } } }); return setButton; } /** * creates a classname from the given path. * * @param path the path to generate the classname from * @return the generated classname */ protected String getClassnameFromPath(TreePath path) { StringBuffer classname = new StringBuffer(); // recreate class name from path int start = 0; if (m_ObjectNames.size() > 1) { start = 1; } for (int i = start; i < path.getPathCount(); i++) { if (i > start) { classname.append("."); } classname.append((String) ((GOETreeNode) path.getPathComponent(i)).getUserObject()); } return classname.toString(); } /** * Returns a popup menu that allows the user to change the class of object. * * @return a JPopupMenu that when shown will let the user choose the class */ public JPopupMenu getChooseClassPopupMenu() { updateObjectNames(); // create the tree, and find the path to the current class m_treeNodeOfCurrentObject = null; final JTree tree = createTree(m_ObjectNames); if (m_treeNodeOfCurrentObject != null) { tree.setSelectionPath(new TreePath(m_treeNodeOfCurrentObject.getPath())); } else { TreePath path = tree.getPathForRow(0); if (path != null) { tree.setSelectionPath(path); } } tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); // create the popup final JPopupMenu popup = new JTreePopupMenu(tree); // respond when the user chooses a class tree.addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { GOETreeNode node = (GOETreeNode) tree.getLastSelectedPathComponent(); if (node == null) { return; } if (node.isLeaf()) { classSelected(getClassnameFromPath(tree.getSelectionPath())); } } }); MouseListener ml = new MouseAdapter() { public void mousePressed(MouseEvent e) { if(tree.getRowForLocation(e.getX(), e.getY()) != -1) { if(e.getClickCount() == 1) { popup.setVisible(false); } } } }; tree.addMouseListener(ml); tree.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter_action"); tree.getActionMap().put("enter_action", new AbstractAction() { public void actionPerformed(ActionEvent e) { if (((GOETreeNode)tree.getLastSelectedPathComponent()).isLeaf()) { popup.setVisible(false); } } }); return popup; } /** * Creates a JTree from an object heirarchy. * * @param hpps the hierarchy of objects to mirror in the tree * @return a JTree representation of the hierarchy */ protected JTree createTree(Hashtable<String, HierarchyPropertyParser> hpps) { GOETreeNode superRoot; Enumeration<HierarchyPropertyParser> enm; HierarchyPropertyParser hpp; if (hpps.size() > 1) { superRoot = new GOETreeNode("root"); } else { superRoot = null; } enm = hpps.elements(); while (enm.hasMoreElements()) { hpp = enm.nextElement(); hpp.goToRoot(); GOETreeNode root = new GOETreeNode(hpp.getValue()); addChildrenToTree(root, hpp); if (superRoot == null) { superRoot = root; } else { superRoot.add(root); } } JTree tree = new JTree(superRoot) { /** For serialization */ private static final long serialVersionUID = 6991903188102450549L; @Override public String getToolTipText(MouseEvent e) { if ((getRowForLocation(e.getX(), e.getY())) == -1) { return null; } TreePath currPath = getPathForLocation(e.getX(), e.getY()); if (currPath.getLastPathComponent() instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) currPath .getLastPathComponent(); if (node.isLeaf()) { return ((GOETreeNode) node).getToolTipText(); } } return null; } }; tree.setToolTipText(""); return tree; } /** * Recursively builds a JTree from an object heirarchy. Also updates * m_treeNodeOfCurrentObject if the current object is discovered during * creation. * * @param tree the root of the tree to add children to * @param hpp the hierarchy of objects to mirror in the tree */ protected void addChildrenToTree(GOETreeNode tree, HierarchyPropertyParser hpp) { try { for (int i = 0; i < hpp.numChildren(); i++) { hpp.goToChild(i); GOETreeNode child = new GOETreeNode(hpp.getValue()); if ((m_Object != null) && m_Object.getClass().getName().equals(hpp.fullValue())) { m_treeNodeOfCurrentObject = child; } tree.add(child); if (hpp.isLeafReached() && m_ShowGlobalInfoToolTip) { String algName = hpp.fullValue(); try { // Object alg = Class.forName(algName).newInstance(); Object alg = WekaPackageClassLoaderManager.forName(algName).newInstance(); String toolTip = Utils.getGlobalInfo(alg, true); if (toolTip != null) { child.setToolTipText(toolTip); } } catch (Exception ex) { } } addChildrenToTree(child, hpp); hpp.goToParent(); } } catch (Exception e) { e.printStackTrace(); } } /** * Called when the user selects an class type to change to. * * @param className the name of the class that was selected */ protected void classSelected(String className) { try { if ((m_Object != null) && m_Object.getClass().getName().equals(className)) { return; } //setValue(Class.forName(className).newInstance()); setValue(WekaPackageClassLoaderManager.forName(className).newInstance()); // m_ObjectPropertyPanel.showPropertyDialog(); if (m_EditorComponent != null) { m_EditorComponent.updateChildPropertySheet(); } } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Could not create an example of\n" + className + "\n" + "from the current classpath", "Class load failed", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); try { if (m_Backup != null) { setValue(m_Backup); } else { setDefaultValue(); } } catch (Exception e) { Logger.log(weka.core.logging.Logger.Level.WARNING, ex.getMessage()); ex.printStackTrace(); } } } /** * Sets the capabilities to use for filtering. * * @param value the object to get the filter capabilities from */ public void setCapabilitiesFilter(Capabilities value) { m_CapabilitiesFilter = new Capabilities(null); m_CapabilitiesFilter.assign(value); } /** * Returns the current Capabilities filter, can be null. * * @return the current Capabiliities used for filtering */ public Capabilities getCapabilitiesFilter() { return m_CapabilitiesFilter; } /** * Removes the current Capabilities filter. */ public void removeCapabilitiesFilter() { m_CapabilitiesFilter = null; } /** * Makes a copy of an object using serialization. * * @param source the object to copy * @return a copy of the source object * @exception Exception if the copy fails */ public static Object makeCopy(Object source) throws Exception { SerializedObject so = new SerializedObject(source); Object result = so.getObject(); return result; } /** * Returns the history of the used setups. * * @return the history */ public GenericObjectEditorHistory getHistory() { return m_History; } /** * Tests out the Object editor from the command line. * * @param args may contain the class name of a Object to edit */ public static void main(String[] args) { try { GenericObjectEditor.registerEditors(); GenericObjectEditor ce = new GenericObjectEditor(true); ce.setClassType(weka.classifiers.Classifier.class); Object initial = new weka.classifiers.rules.ZeroR(); if (args.length > 0) { //ce.setClassType(Class.forName(args[0])); ce.setClassType(WekaPackageClassLoaderManager.forName(args[0])); if (args.length > 1) { //initial = Class.forName(args[1]).newInstance(); initial = WekaPackageClassLoaderManager.forName(args[1]).newInstance(); ce.setValue(initial); } else { ce.setDefaultValue(); } } else { ce.setValue(initial); } PropertyDialog pd = new PropertyDialog((Frame) null, ce, 100, 100); pd.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { PropertyEditor pe = ((PropertyDialog) e.getSource()).getEditor(); Object c = pe.getValue(); String options = ""; if (c instanceof OptionHandler) { options = Utils.joinOptions(((OptionHandler) c).getOptions()); } System.out.println(c.getClass().getName() + " " + options); System.exit(0); } }); pd.setVisible(true); } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/GenericObjectEditorHistory.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ObjectHistory.java * Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand */ package weka.gui; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.Serializable; import java.util.EventObject; import java.util.Vector; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import weka.core.SerializedObject; import weka.core.Utils; /** * A helper class for maintaining a history of objects selected in the GOE. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class GenericObjectEditorHistory implements Serializable { /** for serialization. */ private static final long serialVersionUID = -1255734638729633595L; /** * Event that gets sent when a history item gets selected. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public static class HistorySelectionEvent extends EventObject { /** for serialization. */ private static final long serialVersionUID = 45824542929908105L; /** the selected favorite. */ protected Object m_HistoryItem; /** * Initializes the event. * * @param source the object that triggered the event * @param historyItem the selected history item */ public HistorySelectionEvent(Object source, Object historyItem) { super(source); m_HistoryItem = historyItem; } /** * Returns the selected history item. * * @return the history item */ public Object getHistoryItem() { return m_HistoryItem; } } /** * Interface for classes that listen to selections of history items. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public static interface HistorySelectionListener { /** * Gets called when a history item gets selected. * * @param e the event */ public void historySelected(HistorySelectionEvent e); } /** the maximum entries in the history. */ public final static int MAX_HISTORY_COUNT = 10; /** the maximum length of a caption in the history. */ public final static int MAX_HISTORY_LENGTH = 200; /** the menu max line length. */ public final static int MAX_LINE_LENGTH = 80; /** the history of objects. */ protected Vector<Object> m_History; /** * Initializes the history. */ public GenericObjectEditorHistory() { super(); initialize(); } /** * Initializes members. */ protected void initialize() { m_History = new Vector<Object>(); } /** * Clears the history. */ public synchronized void clear() { m_History.clear(); } /** * Adds the object to the history. * * @param obj the object to add */ public synchronized void add(Object obj) { obj = copy(obj); if (m_History.contains(obj)) { m_History.remove(obj); } m_History.insertElementAt(obj, 0); while (m_History.size() > MAX_HISTORY_COUNT) { m_History.remove(m_History.size() - 1); } } /** * Returns the number of entries in the history. * * @return the size of the history */ public synchronized int size() { return m_History.size(); } /** * Returns the current history. * * @return the history */ public synchronized Vector<Object> getHistory() { return m_History; } /** * Creates a copy of the object. * * @param obj the object to copy */ protected Object copy(Object obj) { SerializedObject so; Object result; try { so = new SerializedObject(obj); result = so.getObject(); } catch (Exception e) { result = null; e.printStackTrace(); } return result; } /** * Generates an HTML caption for the an entry in the history menu. * * @param obj the object to create the caption for * @return the generated HTML captiopn */ protected String generateMenuItemCaption(Object obj) { StringBuffer result; String cmd; String[] lines; int i; result = new StringBuffer(); cmd = Utils.toCommandLine(obj); if (cmd.length() > MAX_HISTORY_LENGTH) { cmd = cmd.substring(0, MAX_HISTORY_LENGTH) + "..."; } lines = Utils.breakUp(cmd, MAX_LINE_LENGTH); result.append("<html>"); for (i = 0; i < lines.length; i++) { if (i > 0) { result.append("<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"); } result.append(lines[i].trim()); } result.append("</html>"); return result.toString(); } /** * Adds a menu item with the history to the popup menu. * * @param menu the menu to add the history to * @param current the current object * @param listener the listener to attach to the menu items' ActionListener */ public void customizePopupMenu(JPopupMenu menu, Object current, HistorySelectionListener listener) { JMenu submenu; JMenuItem item; int i; if (m_History.size() == 0) { return; } submenu = new JMenu("History"); menu.addSeparator(); menu.add(submenu); // clear history item = new JMenuItem("Clear history"); item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_History.clear(); } }); submenu.add(item); // current history final HistorySelectionListener fListener = listener; for (i = 0; i < m_History.size(); i++) { if (i == 0) { submenu.addSeparator(); } final Object history = m_History.get(i); item = new JMenuItem(generateMenuItemCaption(history)); item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { fListener.historySelected(new HistorySelectionEvent(fListener, history)); } }); submenu.add(item); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/GenericPropertiesCreator.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * GenericPropertiesCreator.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import weka.core.ClassDiscovery; import weka.core.ClassDiscovery.StringCompare; import weka.core.InheritanceUtils; import weka.core.Utils; import weka.core.WekaPackageClassLoaderManager; import weka.core.WekaPackageManager; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.lang.annotation.Annotation; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.Properties; import java.util.StringTokenizer; import java.util.Vector; /** * This class can generate the properties object that is normally loaded from * the <code>GenericObjectEditor.props</code> file (= PROPERTY_FILE). It takes * the <code>GenericPropertiesCreator.props</code> file as a template to * determine all the derived classes by checking the classes in the given * packages (a file with the same name in your home directory overrides the the * one in the weka/gui directory/package). <br> * E.g. if we want to have all the subclasses of the <code>Classifier</code> * class then we specify the superclass ("weka.classifiers.Classifier") and the * packages where to look for ("weka.classifiers.bayes" etc.): * * <pre> * * weka.classifiers.Classifier=\ * weka.classifiers.bayes,\ * weka.classifiers.functions,\ * weka.classifiers.lazy,\ * weka.classifiers.meta,\ * weka.classifiers.trees,\ * weka.classifiers.rules * * </pre> * * This creates the same list as stored in the * <code>GenericObjectEditor.props</code> file, but it will also add additional * classes, that are not listed in the static list (e.g. a newly developed * Classifier), but still in the classpath. <br> * <br> * For discovering the subclasses the whole classpath is inspected, which means * that you can have several parallel directories with the same package * structure (e.g. a release directory and a developer directory with additional * classes). <br> * <br> * The dynamic discovery can be turned off via the <code>UseDyanmic</code> * property in the props file (values: true|false). * * @see #CREATOR_FILE * @see #PROPERTY_FILE * @see #USE_DYNAMIC * @see GenericObjectEditor * @see weka.core.ClassDiscovery * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class GenericPropertiesCreator { /** whether to output some debug information */ public final static boolean VERBOSE = false; /** * name of property whether to use the dynamic approach or the old * GenericObjectEditor.props file */ public final static String USE_DYNAMIC = "UseDynamic"; /** * The name of the properties file to use as a template. Contains the packages * in which to look for derived classes. It has the same structure as the * <code>PROPERTY_FILE</code> * * @see #PROPERTY_FILE */ protected static String CREATOR_FILE = "weka/gui/GenericPropertiesCreator.props"; /** * The name of the properties file that lists classes/interfaces/superclasses * to exclude from being shown in the GUI. See the file for more information. */ protected static String EXCLUDE_FILE = "weka/gui/GenericPropertiesCreator.excludes"; /** the prefix for an interface exclusion */ protected static String EXCLUDE_INTERFACE = "I"; /** the prefix for an (exact) class exclusion */ protected static String EXCLUDE_CLASS = "C"; /** the prefix for a superclass exclusion */ protected static String EXCLUDE_SUPERCLASS = "S"; /** * The name of the properties file for the static GenericObjectEditor ( * <code>USE_DYNAMIC</code> = <code>false</code>) * * @see GenericObjectEditor * @see #USE_DYNAMIC */ protected static String PROPERTY_FILE = "weka/gui/GenericObjectEditor.props"; /** the input file with the packages */ protected String m_InputFilename; /** the output props file for the GenericObjectEditor */ protected String m_OutputFilename; /** the "template" properties file with the layout and the packages */ protected Properties m_InputProperties; /** the output properties file with the filled in classes */ protected Properties m_OutputProperties; /** Globally available properties */ protected static GenericPropertiesCreator GLOBAL_CREATOR; protected static Properties GLOBAL_INPUT_PROPERTIES; protected static Properties GLOBAL_OUTPUT_PROPERTIES; /** * whether an explicit input file was given - if false, the Utils class is * used to locate the props-file */ protected boolean m_ExplicitPropsFile; /** * the hashtable that stores the excludes: key -&gt; Hashtable(prefix -&gt; * Vector of classnames) */ protected Hashtable<String, Hashtable<String, Vector<String>>> m_Excludes; static { try { GenericPropertiesCreator creator = new GenericPropertiesCreator(); GLOBAL_CREATOR = creator; if (creator.useDynamic() && !WekaPackageManager.m_initialPackageLoadingInProcess) { creator.execute(false, true); GLOBAL_INPUT_PROPERTIES = creator.getInputProperties(); GLOBAL_OUTPUT_PROPERTIES = creator.getOutputProperties(); } else { // Read the static information from the GenericObjectEditor.props GLOBAL_OUTPUT_PROPERTIES = Utils .readProperties("weka/gui/GenericObjectEditor.props"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Get the global output properties * * @return the global output properties */ public static Properties getGlobalOutputProperties() { return GLOBAL_OUTPUT_PROPERTIES; } /** * Get the global input properties * * @return the global input properties */ public static Properties getGlobalInputProperties() { return GLOBAL_INPUT_PROPERTIES; } /** * Regenerate the global output properties. Does not load the input * properties, instead uses the GLOBAL_INPUT_PROPERTIES */ public static void regenerateGlobalOutputProperties() { if (GLOBAL_CREATOR != null) { try { GLOBAL_CREATOR.execute(false, false); GLOBAL_INPUT_PROPERTIES = GLOBAL_CREATOR.getInputProperties(); GLOBAL_OUTPUT_PROPERTIES = GLOBAL_CREATOR.getOutputProperties(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * initializes the creator, locates the props file with the Utils class. * * @throws Exception if loading of CREATOR_FILE fails * @see #CREATOR_FILE * @see Utils#readProperties(String) * @see #loadInputProperties() */ public GenericPropertiesCreator() throws Exception { this(CREATOR_FILE); m_ExplicitPropsFile = false; } /** * initializes the creator, the given file overrides the props-file search of * the Utils class * * @param filename the file containing the packages to create a props file * from * @throws Exception if loading of the file fails * @see #CREATOR_FILE * @see Utils#readProperties(String) * @see #loadInputProperties() */ public GenericPropertiesCreator(String filename) throws Exception { super(); m_InputFilename = filename; m_OutputFilename = PROPERTY_FILE; m_InputProperties = null; m_OutputProperties = null; m_ExplicitPropsFile = true; m_Excludes = new Hashtable<String, Hashtable<String, Vector<String>>>(); } /** * if FALSE, the locating of a props-file of the Utils-class is used, * otherwise it's tried to load the specified file * * @param value if true the specified file will be loaded not via the * Utils-class * @see Utils#readProperties(String) * @see #loadInputProperties() */ public void setExplicitPropsFile(boolean value) { m_ExplicitPropsFile = value; } /** * returns TRUE, if a file is loaded and not the Utils class used for locating * the props file. * * @return true if the specified file is used and not the one found by the * Utils class * @see Utils#readProperties(String) * @see #loadInputProperties() */ public boolean getExplicitPropsFile() { return m_ExplicitPropsFile; } /** * returns the name of the output file * * @return the name of the output file */ public String getOutputFilename() { return m_OutputFilename; } /** * sets the file to output the properties for the GEO to * * @param filename the filename for the output */ public void setOutputFilename(String filename) { m_OutputFilename = filename; } /** * returns the name of the input file * * @return the name of the input file */ public String getInputFilename() { return m_InputFilename; } /** * sets the file to get the information about the packages from. automatically * sets explicitPropsFile to TRUE. * * @param filename the filename for the input * @see #setExplicitPropsFile(boolean) */ public void setInputFilename(String filename) { m_InputFilename = filename; setExplicitPropsFile(true); } /** * returns the input properties object (template containing the packages) * * @return the input properties (the template) */ public Properties getInputProperties() { return m_InputProperties; } /** * returns the output properties object (structure like the template, but * filled with classes instead of packages) * * @return the output properties (filled with classes) */ public Properties getOutputProperties() { return m_OutputProperties; } /** * loads the property file containing the layout and the packages of the * output-property-file. The exlcude property file is also read here. * * @see #m_InputProperties * @see #m_InputFilename */ protected void loadInputProperties() { if (VERBOSE) { System.out.println("Loading '" + getInputFilename() + "'..."); } m_InputProperties = new Properties(); try { File f = new File(getInputFilename()); if (getExplicitPropsFile() && f.exists()) { m_InputProperties.load(new FileInputStream(getInputFilename())); } else { m_InputProperties = Utils.readProperties(getInputFilename()); } // excludes m_Excludes.clear(); Properties p = Utils.readProperties(EXCLUDE_FILE); Enumeration<?> enm = p.propertyNames(); while (enm.hasMoreElements()) { String name = enm.nextElement().toString(); // new Hashtable for key Hashtable<String, Vector<String>> t = new Hashtable<String, Vector<String>>(); m_Excludes.put(name, t); t.put(EXCLUDE_INTERFACE, new Vector<String>()); t.put(EXCLUDE_CLASS, new Vector<String>()); t.put(EXCLUDE_SUPERCLASS, new Vector<String>()); // process entries StringTokenizer tok = new StringTokenizer(p.getProperty(name), ","); while (tok.hasMoreTokens()) { String item = tok.nextToken(); // get list Vector<String> list = new Vector<String>(); if (item.startsWith(EXCLUDE_INTERFACE + ":")) { list = t.get(EXCLUDE_INTERFACE); } else if (item.startsWith(EXCLUDE_CLASS + ":")) { list = t.get(EXCLUDE_CLASS); } else if (item.startsWith(EXCLUDE_SUPERCLASS)) { list = t.get(EXCLUDE_SUPERCLASS); } // add to list list.add(item.substring(item.indexOf(":") + 1)); } } } catch (Exception e) { e.printStackTrace(); } } /** * gets whether the dynamic approach should be used or not * * @return true if the dynamic approach is to be used */ public boolean useDynamic() { if (getInputProperties() == null) { loadInputProperties(); } // check our classloader against the system one - if different then // return false (as dynamic classloading only works for classes discoverable // in the system classpath /* * if * (!ClassLoader.getSystemClassLoader().equals(this.getClass().getClassLoader * ())) { if * (Boolean.parseBoolean(getInputProperties().getProperty(USE_DYNAMIC, * "true")) == true) { System.out.println( * "[GenericPropertiesCreator] classloader in use is not the system " + * "classloader: using static entries in weka/gui/GenericObjectEditor.props rather " * + "than dynamic class discovery."); } return false; } */ return Boolean.parseBoolean(getInputProperties().getProperty(USE_DYNAMIC, "true")); } /** * checks whether the classname is a valid one, i.e., from a public class * * @param classname the classname to check * @return whether the classname is a valid one */ protected boolean isValidClassname(String classname) { return (classname.indexOf("$") == -1); } /** * Checks whether the classname is a valid one for the given key. This is * based on the settings in the Exclude file. * * @param key the property key * @param classname the classname to check * @return whether the classname is a valid one * @see #EXCLUDE_FILE */ protected boolean isValidClassname(String key, String classname) { boolean result; Class<?> cls; Class<?> clsCurrent; Vector<String> list; int i; result = true; try { clsCurrent = WekaPackageClassLoaderManager.forName(classname); // check for GPCIgnore for (Annotation a : clsCurrent.getAnnotations()) { if (a instanceof GPCIgnore) { return false; } } } catch (Exception ex) { clsCurrent = null; } // are there excludes for this key? if (m_Excludes.containsKey(key)) { // interface if ((clsCurrent != null) && result) { list = m_Excludes.get(key).get(EXCLUDE_INTERFACE); for (i = 0; i < list.size(); i++) { try { cls = WekaPackageClassLoaderManager.forName(list.get(i).toString()); if (InheritanceUtils.hasInterface(cls, clsCurrent)) { result = false; break; } } catch (Exception e) { // we ignore this Exception } } } // superclass if ((clsCurrent != null) && result) { list = m_Excludes.get(key).get(EXCLUDE_SUPERCLASS); for (i = 0; i < list.size(); i++) { try { cls = WekaPackageClassLoaderManager.forName(list.get(i).toString()); if (InheritanceUtils.isSubclass(cls, clsCurrent)) { result = false; break; } } catch (Exception e) { // we ignore this Exception } } } // class if ((clsCurrent != null) && result) { list = m_Excludes.get(key).get(EXCLUDE_CLASS); for (i = 0; i < list.size(); i++) { try { cls = WekaPackageClassLoaderManager.forName(list.get(i).toString()); if (cls.getName().equals(clsCurrent.getName())) { result = false; } } catch (Exception e) { // we ignore this Exception } } } } return result; } /** * fills in all the classes (based on the packages in the input properties * file) into the output properties file * * @throws Exception if something goes wrong * @see #m_OutputProperties */ protected void generateOutputProperties() throws Exception { Enumeration<?> keys; String key; String value; String pkg; StringTokenizer tok; Vector<String> classes; HashSet<String> names; int i; m_OutputProperties = new Properties(); keys = m_InputProperties.propertyNames(); while (keys.hasMoreElements()) { key = keys.nextElement().toString(); if (key.equals(USE_DYNAMIC)) { continue; } tok = new StringTokenizer(m_InputProperties.getProperty(key), ","); names = new HashSet<String>(); // get classes for all packages while (tok.hasMoreTokens()) { pkg = tok.nextToken().trim(); try { classes = ClassDiscovery.find(WekaPackageClassLoaderManager.forName(key), pkg); } catch (Exception e) { System.out.println("Problem with '" + key + "': " + e); classes = new Vector<String>(); } for (i = 0; i < classes.size(); i++) { // skip non-public classes if (!isValidClassname(classes.get(i).toString())) { continue; } // some classes should not be listed for some keys if (!isValidClassname(key, classes.get(i).toString())) { continue; } names.add(classes.get(i)); } } // generate list value = ""; classes = new Vector<String>(); classes.addAll(names); Collections.sort(classes, new StringCompare()); for (i = 0; i < classes.size(); i++) { if (!value.equals("")) { value += ","; } value += classes.get(i).toString(); } if (VERBOSE) { System.out.println(pkg + " -> " + value); } // set value m_OutputProperties.setProperty(key, value); } } /** * stores the generated output properties file * * @throws Exception if the saving fails * @see #m_OutputProperties * @see #m_OutputFilename */ protected void storeOutputProperties() throws Exception { if (VERBOSE) { System.out.println("Saving '" + getOutputFilename() + "'..."); } m_OutputProperties .store( new FileOutputStream(getOutputFilename()), " Customises the list of options given by the GenericObjectEditor\n# for various superclasses."); } /** * generates the props-file for the GenericObjectEditor and stores it * * @throws Exception if something goes wrong * @see #execute(boolean) */ public void execute() throws Exception { execute(true, true); } /** * generates the props-file for the GenericObjectEditor * * @param store true if the generated props should be stored * @throws Exception */ public void execute(boolean store) throws Exception { execute(store, true); } /** * generates the props-file for the GenericObjectEditor and stores it only if * the the param <code>store</code> is TRUE. If it is FALSE then the generated * properties file can be retrieved via the <code>getOutputProperties</code> * method. * * @param store if TRUE then the properties file is stored to the stored * filename * @param loadInputProps true if the input properties should be loaded * @throws Exception if something goes wrong * @see #getOutputFilename() * @see #setOutputFilename(String) * @see #getOutputProperties() */ public void execute(boolean store, boolean loadInputProps) throws Exception { // read properties file if (loadInputProps) { loadInputProperties(); } // generate the props file generateOutputProperties(); // write properties file if (store) { storeOutputProperties(); } } /** * for generating props file: * <ul> * <li> * no parameter: see default constructor</li> * <li> * 1 parameter (i.e., filename): see default constructor + * setOutputFilename(String)</li> * <li> * 2 parameters (i.e, filenames): see constructor with String argument + * setOutputFilename(String)</li> * </ul> * * @param args the commandline arguments * @throws Exception if something goes wrong * @see #GenericPropertiesCreator() * @see #GenericPropertiesCreator(String) * @see #setOutputFilename(String) */ public static void main(String[] args) throws Exception { GenericPropertiesCreator c = null; if (args.length == 0) { c = new GenericPropertiesCreator(); } else if (args.length == 1) { c = new GenericPropertiesCreator(); c.setOutputFilename(args[0]); } else if (args.length == 2) { c = new GenericPropertiesCreator(args[0]); c.setOutputFilename(args[1]); } else { System.out.println("usage: " + GenericPropertiesCreator.class.getName() + " [<input.props>] [<output.props>]"); System.exit(1); } c.execute(true); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/HierarchyPropertyParser.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * HierarchyPropertyParser.java * Copyright (C) 2001-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.io.Serializable; import java.util.StringTokenizer; import java.util.Vector; /** * This class implements a parser to read properties that have a hierarchy(i.e. * tree) structure. Conceptually it's similar to the XML DOM/SAX parser but of * course is much simpler and uses dot as the seperator of levels instead of * back-slash.<br> * It provides interfaces to both build a parser tree and traverse the tree. <br> * Note that this implementation does not lock the tree when different threads * are traversing it simultaneously, i.e. it's NOT synchronized and multi-thread * safe. It is recommended that later implementation extending this class * provide a locking scheme and override the functions with the "synchronized" * modifier (most of them are goToXXX() and information accessing functions). * <p> * * @author Xin Xu (xx5@cs.waikato.ac.nz) * @version $Revision$ */ public class HierarchyPropertyParser implements Serializable { /** for serialization */ private static final long serialVersionUID = -4151103338506077544L; /** Keep track of the root of the tree */ private final TreeNode m_Root; /** Keep track of the current node when traversing the tree */ private TreeNode m_Current; /** The level separate in the path */ private String m_Seperator = "."; /** The depth of the tree */ private int m_Depth = 0; /** * The inner class implementing a single tree node. All fields are made public * simply for convenient access, Although a severe violation of OO Design * principle. */ private class TreeNode implements Serializable { /** For serialization */ private static final long serialVersionUID = 6495148851062003641L; /** The parent of this node */ public TreeNode parent = null; /** The value of this node. Always String */ public String value = null; /** The children of this node */ public Vector<TreeNode> children = null; /** The level of this node */ public int level = 0; /** The context of this node */ public String context = null; } /** Default constructor */ public HierarchyPropertyParser() { m_Root = new TreeNode(); m_Root.parent = null; m_Root.children = new Vector<TreeNode>(); goToRoot(); } /** * Constructor that builds a tree from the given property with the given * delimitor * * @param p the given property string * @param delim the given dilimitor */ public HierarchyPropertyParser(String p, String delim) throws Exception { this(); build(p, delim); } /** * Set the seperator between levels. Default is dot. * * @param s the seperator symbol */ public void setSeperator(String s) { m_Seperator = s; } /** * Get the seperator between levels. Default is dot. * * @return the seperator symbol */ public String getSeperator() { return m_Seperator; } /** * Build a tree from the given property with the given delimitor * * @param p the given property * @param delim the given delimitor */ public void build(String p, String delim) throws Exception { StringTokenizer st = new StringTokenizer(p, delim); // System.err.println("delim: "+delim); while (st.hasMoreTokens()) { String property = st.nextToken().trim(); if (!isHierachic(property)) { throw new Exception("The given property is not in" + "hierachy structure with seperators!"); } add(property); } goToRoot(); } /** * Add the given item of property to the tree * * @param property the given item */ public synchronized void add(String property) { String[] values = tokenize(property); if (m_Root.value == null) { m_Root.value = values[0]; } buildBranch(m_Root, values, 1); } /** * Private function to build one branch of the tree based on one property * * @param parent the parent of the node to be built * @param values the value of one property * @param lvl the level of the node to be built in the tree */ private void buildBranch(TreeNode parent, String[] values, int lvl) { // Precondition: children is not null if (lvl == values.length) { // Parent is leaf parent.children = null; return; } if (lvl > (m_Depth - 1)) { m_Depth = lvl + 1; // Depth starts from 1 } Vector<TreeNode> kids = parent.children; int index = search(kids, values[lvl]); if (index != -1) { TreeNode newParent = kids.elementAt(index); if (newParent.children == null) { newParent.children = new Vector<TreeNode>(); } buildBranch(newParent, values, lvl + 1); } else { TreeNode added = new TreeNode(); added.parent = parent; added.value = values[lvl]; added.children = new Vector<TreeNode>(); added.level = lvl; if (parent != m_Root) { added.context = parent.context + m_Seperator + parent.value; } else { added.context = parent.value; } kids.addElement(added); buildBranch(added, values, lvl + 1); } } /** * Tokenize the given string based on the seperator and put the tokens into an * array of strings * * @param rawString the given string * @return an array of strings */ public String[] tokenize(String rawString) { Vector<String> result = new Vector<String>(); StringTokenizer tk = new StringTokenizer(rawString, m_Seperator); while (tk.hasMoreTokens()) { result.addElement(tk.nextToken()); } String[] newStrings = new String[result.size()]; for (int i = 0; i < result.size(); i++) { newStrings[i] = result.elementAt(i); } return newStrings; } /** * Whether the HierarchyPropertyParser contains the given string * * @param string the given string * @return whether contains */ public boolean contains(String string) { String[] item = tokenize(string); if (!item[0].equals(m_Root.value)) { return false; } return isContained(m_Root, item, 1); } /** * Private function to decide whether one level of one branch contains the * relevant values * * @param parent the parent of the node to be searched * @param values the value of one property * @param lvl the level of the node in question * @return whether this branch contains the corresponding values */ private boolean isContained(TreeNode parent, String[] values, int lvl) { if (lvl == values.length) { return true; } else if (lvl > values.length) { return false; } else { Vector<TreeNode> kids = parent.children; int index = search(kids, values[lvl]); if (index != -1) { TreeNode newParent = kids.elementAt(index); return isContained(newParent, values, lvl + 1); } else { return false; } } } /** * Whether the given string has a hierachy structure with the seperators * * @param string the given string */ public boolean isHierachic(String string) { int index = string.indexOf(m_Seperator); // Seperator not occur or first occurance at the end if ((index == (string.length() - 1)) || (index == -1)) { return false; } return true; } /** * Helper function to search for the given target string in a given vector in * which the elements' value may hopefully is equal to the target. If such * elements are found the first index is returned, otherwise -1 * * @param vct the given vector * @param target the given target string * @return the index of the found element, -1 if not found */ public int search(Vector<TreeNode> vct, String target) { if (vct == null) { return -1; } for (int i = 0; i < vct.size(); i++) { if (target.equals(vct.elementAt(i).value)) { return i; } } return -1; } /** * Go to a certain node of the tree according to the specified path Note that * the path must be absolute path from the root. <br> * For relative path, see goDown(String path). * * @param path the given absolute path * @return whether the path exists, if false the current position does not * move */ public synchronized boolean goTo(String path) { if (!isHierachic(path)) { if (m_Root.value.equals(path)) { goToRoot(); return true; } else { return false; } } TreeNode old = m_Current; m_Current = new TreeNode(); goToRoot(); String[] nodes = tokenize(path); if (!m_Current.value.equals(nodes[0])) { return false; } for (int i = 1; i < nodes.length; i++) { int pos = search(m_Current.children, nodes[i]); if (pos == -1) { m_Current = old; return false; } m_Current = m_Current.children.elementAt(pos); } return true; } /** * Go to a certain node of the tree down from the current node according to * the specified relative path. The path does not contain the value of current * node * * @param path the given relative path * @return whether the path exists, if false the current position does not * move */ public synchronized boolean goDown(String path) { if (!isHierachic(path)) { return goToChild(path); } TreeNode old = m_Current; m_Current = new TreeNode(); String[] nodes = tokenize(path); int pos = search(old.children, nodes[0]); if (pos == -1) { m_Current = old; return false; } m_Current = old.children.elementAt(pos); for (int i = 1; i < nodes.length; i++) { pos = search(m_Current.children, nodes[i]); if (pos == -1) { m_Current = old; return false; } m_Current = m_Current.children.elementAt(pos); } return true; } /** * Go to the root of the tree */ public synchronized void goToRoot() { m_Current = m_Root; } /** * Go to the parent from the current position in the tree If the current * position is the root, it stays there and does not move */ public synchronized void goToParent() { if (m_Current.parent != null) { m_Current = m_Current.parent; } } /** * Go to one child node from the current position in the tree according to the * given value <br> * If the child node with the given value cannot be found it returns false, * true otherwise. If false, the current position does not change * * @param value the value of the given child * @return whether the child can be found */ public synchronized boolean goToChild(String value) { if (m_Current.children == null) { return false; } int pos = search(m_Current.children, value); if (pos == -1) { return false; } m_Current = m_Current.children.elementAt(pos); return true; } /** * Go to one child node from the current position in the tree according to the * given position <br> * * @param pos the position of the given child * @exception Exception if the position is out of range or leaf is reached */ public synchronized void goToChild(int pos) throws Exception { if ((m_Current.children == null) || (pos < 0) || (pos >= m_Current.children.size())) { throw new Exception("Position out of range or leaf reached"); } m_Current = m_Current.children.elementAt(pos); } /** * The number of the children nodes. If current node is leaf, it returns 0. * * @return the number of the children nodes of the current position */ public synchronized int numChildren() { if (m_Current.children == null) { return 0; } return m_Current.children.size(); } /** * The value in the children nodes. If current node is leaf, it returns null. * * @return the value in the children nodes */ public synchronized String[] childrenValues() { if (m_Current.children == null) { return null; } else { Vector<TreeNode> kids = m_Current.children; String[] values = new String[kids.size()]; for (int i = 0; i < kids.size(); i++) { values[i] = kids.elementAt(i).value; } return values; } } /** * The value in the parent node. If current node is root, it returns null. * * @return the value in the parent node */ public synchronized String parentValue() { if (m_Current.parent != null) { return m_Current.parent.value; } else { return null; } } /** * Whether the current position is a leaf * * @return whether the current position is a leaf */ public synchronized boolean isLeafReached() { return (m_Current.children == null); } /** * Whether the current position is the root * * @return whether the current position is the root */ public synchronized boolean isRootReached() { return (m_Current.parent == null); } /** * Get the value of current node * * @return value level */ public synchronized String getValue() { return m_Current.value; } /** * Get the level of current node. Note the level starts from 0 * * @return the level */ public synchronized int getLevel() { return m_Current.level; } /** * Get the depth of the tree, i.e. (the largest level)+1 * * @return the depth of the tree */ public int depth() { return m_Depth; } /** * The context of the current node, i.e. the path from the root to the parent * node of the current node, seperated by the seperator. If root, it returns * null * * @return the context path */ public synchronized String context() { return m_Current.context; } /** * The full value of the current node, i.e. its context + seperator + its * value. For root, only its value. * * @return the context path */ public synchronized String fullValue() { if (m_Current == m_Root) { return m_Root.value; } else { return (m_Current.context + m_Seperator + m_Current.value); } } /** * Show the whole tree in text format * * @return the whole tree in text format */ public String showTree() { return showNode(m_Root, null); } /** * Show one node of the tree in text format * * @param node the node in question * @return the node in text format */ private String showNode(TreeNode node, boolean[] hasBar) { StringBuffer text = new StringBuffer(); for (int i = 0; i < (node.level - 1); i++) { if (hasBar[i]) { text.append(" | "); } else { text.append(" "); } } if (node.level != 0) { text.append(" |------ "); } text.append(node.value + "(" + node.level + ")" + "[" + node.context + "]\n"); if (node.children != null) { for (int i = 0; i < node.children.size(); i++) { boolean[] newBar = new boolean[node.level + 1]; int lvl = node.level; if (hasBar != null) { for (int j = 0; j < lvl; j++) { newBar[j] = hasBar[j]; } } if ((i == (node.children.size() - 1))) { newBar[lvl] = false; } else { newBar[lvl] = true; } text.append(showNode(node.children.elementAt(i), newBar)); } } return text.toString(); } /** * Tests out the parser. * * @param args should contain nothing */ public static void main(String args[]) { StringBuffer sb = new StringBuffer(); sb.append("node1.node1_1.node1_1_1.node1_1_1_1, "); sb.append("node1.node1_1.node1_1_1.node1_1_1_2, "); sb.append("node1.node1_1.node1_1_1.node1_1_1_3, "); sb.append("node1.node1_1.node1_1_2.node1_1_2_1, "); sb.append("node1.node1_1.node1_1_3.node1_1_3_1, "); sb.append("node1.node1_2.node1_2_1.node1_2_1_1, "); sb.append("node1.node1_2.node1_2_3.node1_2_3_1, "); sb.append("node1.node1_3.node1_3_3.node1_3_3_1, "); sb.append("node1.node1_3.node1_3_3.node1_3_3_2, "); String p = sb.toString(); try { HierarchyPropertyParser hpp = new HierarchyPropertyParser(p, ", "); System.out.println("seperator: " + hpp.getSeperator()); System.out.println("depth: " + hpp.depth()); System.out.println("The tree:\n\n" + hpp.showTree()); hpp.goToRoot(); System.out.println("goto: " + hpp.goTo("node1.node1_2.node1_2_1") + ": " + hpp.getValue() + " | " + hpp.fullValue() + " leaf? " + hpp.isLeafReached()); System.out.println("go down(wrong): " + hpp.goDown("node1")); System.out.println("Stay still? " + hpp.getValue()); System.out.println("go to child: " + hpp.goToChild("node1_2_1_1") + ": " + hpp.getValue() + " | " + hpp.fullValue() + " leaf? " + hpp.isLeafReached() + " root? " + hpp.isRootReached()); System.out.println("parent: " + hpp.parentValue()); System.out.println("level: " + hpp.getLevel()); System.out.println("context: " + hpp.context()); hpp.goToRoot(); System.out.println("After gotoRoot. leaf? " + hpp.isLeafReached() + " root? " + hpp.isRootReached()); System.out.println("Go down(correct): " + hpp.goDown("node1_1.node1_1_1") + " value: " + hpp.getValue() + " | " + hpp.fullValue() + " level: " + hpp.getLevel() + " leaf? " + hpp.isLeafReached() + " root? " + hpp.isRootReached()); hpp.goToParent(); System.out.println("value: " + hpp.getValue() + " | " + hpp.fullValue()); System.out.println("level: " + hpp.getLevel()); String[] chd = hpp.childrenValues(); for (int i = 0; i < chd.length; i++) { System.out.print("children " + i + ": " + chd[i]); hpp.goDown(chd[i]); System.out.println("real value: " + hpp.getValue() + " | " + hpp.fullValue() + "(level: " + hpp.getLevel() + ")"); hpp.goToParent(); } System.out.println("Another way to go to root:" + hpp.goTo("node1") + ": " + hpp.getValue() + " | " + hpp.fullValue()); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/InstancesSummaryPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * InstancesSummaryPanel.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.BorderFactory; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; import weka.core.Instances; import weka.core.Utils; /** * This panel just displays relation name, number of instances, and number of * attributes. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public class InstancesSummaryPanel extends JPanel { /** for serialization */ private static final long serialVersionUID = -5243579535296681063L; /** Message shown when no instances have been loaded */ protected static final String NO_SOURCE = "None"; /** Displays the name of the relation */ protected JLabel m_RelationNameLab = new JLabel(NO_SOURCE); /** Displays the number of instances */ protected JLabel m_NumInstancesLab = new JLabel(NO_SOURCE); /** Displays the number of attributes */ protected JLabel m_NumAttributesLab = new JLabel(NO_SOURCE); /** Displays the sum of instance weights */ protected JLabel m_sumOfWeightsLab = new JLabel(NO_SOURCE); /** The instances we're playing with */ protected Instances m_Instances; /** * Whether to display 0 or ? for the number of instances in cases where a * dataset has only structure. Depending on where this panel is used from, the * user may have loaded a dataset with no instances or a Loader that can read * incrementally may be being used (in which case we don't know how many * instances are in the dataset... yet). */ protected boolean m_showZeroInstancesAsUnknown = false; /** * Creates the instances panel with no initial instances. */ public InstancesSummaryPanel() { GridBagLayout gbLayout = new GridBagLayout(); setLayout(gbLayout); JLabel lab = new JLabel("Relation:", SwingConstants.RIGHT); lab.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0)); GridBagConstraints gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 0; gbConstraints.gridx = 0; gbLayout.setConstraints(lab, gbConstraints); add(lab); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.WEST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 0; gbConstraints.gridx = 1; gbConstraints.weightx = 100; // gbConstraints.gridwidth = // GridBagConstraints.RELATIVE; gbLayout.setConstraints(m_RelationNameLab, gbConstraints); add(m_RelationNameLab); m_RelationNameLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 10)); lab = new JLabel("Instances:", SwingConstants.RIGHT); lab.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0)); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 1; gbConstraints.gridx = 0; gbLayout.setConstraints(lab, gbConstraints); add(lab); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.WEST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 1; gbConstraints.gridx = 1; gbConstraints.weightx = 100; gbLayout.setConstraints(m_NumInstancesLab, gbConstraints); add(m_NumInstancesLab); m_NumInstancesLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 10)); lab = new JLabel("Attributes:", SwingConstants.RIGHT); lab.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0)); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 0; gbConstraints.gridx = 2; gbLayout.setConstraints(lab, gbConstraints); add(lab); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.WEST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 0; gbConstraints.gridx = 3; // gbConstraints.weightx = 100; gbLayout.setConstraints(m_NumAttributesLab, gbConstraints); add(m_NumAttributesLab); m_NumAttributesLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 10)); lab = new JLabel("Sum of weights:", SwingConstants.RIGHT); lab.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0)); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 1; gbConstraints.gridx = 2; gbLayout.setConstraints(lab, gbConstraints); add(lab); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.WEST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 1; gbConstraints.gridx = 3; // gbConstraints.weightx = 100; gbLayout.setConstraints(m_sumOfWeightsLab, gbConstraints); add(m_sumOfWeightsLab); m_sumOfWeightsLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 10)); } /** * Set whether to show zero instances as unknown (i.e. "?" rather than zero). * This is useful if header information has been read and the instances * themselves will be loaded incrementally. * * @param zeroAsUnknown true if zero instances will be displayed as "unknown", * i.e. "?" */ public void setShowZeroInstancesAsUnknown(boolean zeroAsUnknown) { m_showZeroInstancesAsUnknown = zeroAsUnknown; } /** * Get whether to show zero instances as unknown (i.e. "?" rather than zero). * This is useful if header information has been read and the instances * themselves will be loaded incrementally. * * @return true if zero instances will be displayed as "unknown", i.e. "?" */ public boolean getShowZeroInstancesAsUnknown() { return m_showZeroInstancesAsUnknown; } /** * Tells the panel to use a new set of instances. * * @param inst a set of Instances */ public void setInstances(Instances inst) { m_Instances = inst; m_RelationNameLab.setText(m_Instances.relationName()); m_RelationNameLab.setToolTipText(m_Instances.relationName()); m_NumInstancesLab .setText("" + ((m_showZeroInstancesAsUnknown && m_Instances.numInstances() == 0) ? "?" : "" + m_Instances.numInstances())); m_NumAttributesLab.setText("" + m_Instances.numAttributes()); m_sumOfWeightsLab .setText("" + ((m_showZeroInstancesAsUnknown && m_Instances.numInstances() == 0) ? "?" : "" + Utils.doubleToString(m_Instances.sumOfWeights(), 3))); } /** * Tests out the instance summary panel from the command line. * * @param args optional name of dataset to load */ public static void main(String[] args) { try { final javax.swing.JFrame jf = new javax.swing.JFrame("Instances Panel"); jf.getContentPane().setLayout(new BorderLayout()); final InstancesSummaryPanel p = new InstancesSummaryPanel(); p.setBorder(BorderFactory.createTitledBorder("Relation")); jf.getContentPane().add(p, BorderLayout.CENTER); jf.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { jf.dispose(); System.exit(0); } }); jf.pack(); jf.setVisible(true); if (args.length == 1) { java.io.Reader r = new java.io.BufferedReader(new java.io.FileReader( args[0])); Instances i = new Instances(r); p.setInstances(i); } } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/InteractiveTableModel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * InteractiveTableModel.java * Copyright (C) 2011-2013 University of Waikato, Hamilton, New Zealand */ package weka.gui; import javax.swing.table.AbstractTableModel; import java.util.ArrayList; import java.util.List; /** * Table model that automatically adds a new row to the table on pressing enter * in the last cell of a row. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: 47640 $ */ public class InteractiveTableModel extends AbstractTableModel { /** * For serialization */ private static final long serialVersionUID = -5113873323690309667L; /** Index of the hidden column */ public int m_hidden_index; /** The names of the columns */ protected String[] m_columnNames; /** Holds the data */ protected List<List<String>> m_dataVector; /** * Constructor * * @param columnNames the names of the columns */ public InteractiveTableModel(String[] columnNames) { m_columnNames = columnNames; m_dataVector = new ArrayList<List<String>>(); m_hidden_index = columnNames.length - 1; } @Override public String getColumnName(int column) { return m_columnNames[column]; } @Override public boolean isCellEditable(int row, int column) { if (column == m_hidden_index) { return false; } return true; } @Override public Class<?> getColumnClass(int column) { return String.class; } @Override public Object getValueAt(int row, int column) { if (column >= m_columnNames.length) { return new Object(); } List<String> rowData = m_dataVector.get(row); return rowData.get(column); } @Override public void setValueAt(Object value, int row, int column) { if (column >= m_columnNames.length) { System.err.println("Invalid index"); } List<String> rowData = m_dataVector.get(row); rowData.set(column, value.toString()); fireTableCellUpdated(row, column); } @Override public int getRowCount() { return m_dataVector.size(); } @Override public int getColumnCount() { return m_columnNames.length; } /** * Returns true if the model has an empty row * * @return true if the model has an empty row */ public boolean hasEmptyRow() { if (m_dataVector.size() == 0) { return false; } List<String> dataRow = m_dataVector.get(m_dataVector.size() - 1); for (String s : dataRow) { if (s.length() != 0) { return false; } } return true; } /** * Adds an empty row to the model */ public void addEmptyRow() { ArrayList<String> empty = new ArrayList<String>(); for (int i = 0; i < m_columnNames.length; i++) { empty.add(""); } m_dataVector.add(empty); fireTableRowsInserted(m_dataVector.size() - 1, m_dataVector.size() - 1); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/InteractiveTablePanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * InteractiveTablePanel.java * Copyright (C) 2011-2013 University of Waikato, Hamilton, New Zealand */ package weka.gui; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableColumn; import java.awt.BorderLayout; import java.awt.Component; /** * Provides a panel using an interactive table model. * * @author Mark Hall (mhall{[at]}penthao{[dot]}com) * @version $Revision: 10893 $ */ public class InteractiveTablePanel extends JPanel { /** For serialization */ private static final long serialVersionUID = 4495705463732140410L; /** Holds column names */ protected String[] m_columnNames; /** The table itself */ protected JTable m_table; /** Scroll panel for the table */ protected JScrollPane m_scroller; /** Model for the table */ protected InteractiveTableModel m_tableModel; /** * Constructor * * @param colNames the names of the columns */ public InteractiveTablePanel(String[] colNames) { m_columnNames = colNames; initComponent(); } /** * Initializes the component */ public void initComponent() { m_tableModel = new InteractiveTableModel(m_columnNames); m_tableModel .addTableModelListener(new InteractiveTablePanel.InteractiveTableModelListener()); m_table = new JTable(); m_table.setModel(m_tableModel); m_table.setSurrendersFocusOnKeystroke(true); if (!m_tableModel.hasEmptyRow()) { m_tableModel.addEmptyRow(); } InteractiveTableModel model = (InteractiveTableModel) m_table.getModel(); m_scroller = new javax.swing.JScrollPane(m_table); m_table.setPreferredScrollableViewportSize(new java.awt.Dimension(500, 80)); TableColumn hidden = m_table.getColumnModel().getColumn(model.m_hidden_index); hidden.setMinWidth(2); hidden.setPreferredWidth(2); hidden.setMaxWidth(2); hidden.setCellRenderer(new InteractiveRenderer(model.m_hidden_index)); setLayout(new BorderLayout()); add(m_scroller, BorderLayout.CENTER); } /** * Get the JTable component * * @return the JTable */ public JTable getTable() { return m_table; } /** * Highlight the last row in the table * * @param row the row */ public void highlightLastRow(int row) { int lastrow = m_tableModel.getRowCount(); if (row == lastrow - 1) { m_table.setRowSelectionInterval(lastrow - 1, lastrow - 1); } else { m_table.setRowSelectionInterval(row + 1, row + 1); } m_table.setColumnSelectionInterval(0, 0); } /** * Renderer for the InteractiveTablePanel */ class InteractiveRenderer extends DefaultTableCellRenderer { private static final long serialVersionUID = 6186813827783402502L; /** The index of the interactive column */ protected int m_interactiveColumn; /** * Constructor * * @param interactiveColumn the column that is interactive (i.e. you can * press return to generate a new row from it) */ public InteractiveRenderer(int interactiveColumn) { m_interactiveColumn = interactiveColumn; } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (column == m_interactiveColumn && hasFocus) { if ((InteractiveTablePanel.this.m_tableModel.getRowCount() - 1) == row && !InteractiveTablePanel.this.m_tableModel.hasEmptyRow()) { InteractiveTablePanel.this.m_tableModel.addEmptyRow(); } highlightLastRow(row); } return c; } } /** * Listener for the InteractiveTablePanel */ public class InteractiveTableModelListener implements TableModelListener { @Override public void tableChanged(TableModelEvent evt) { if (evt.getType() == TableModelEvent.UPDATE) { int column = evt.getColumn(); int row = evt.getFirstRow(); m_table.setColumnSelectionInterval(column + 1, column + 1); m_table.setRowSelectionInterval(row, row); } } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/JListHelper.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * JListHelper.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import javax.swing.DefaultListModel; import javax.swing.JList; /** * A helper class for JList GUI elements with DefaultListModel or * derived models. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ * @see JList * @see DefaultListModel */ public class JListHelper { /** moves items up */ public final static int MOVE_UP = 0; /** moves items down */ public final static int MOVE_DOWN = 1; /** * moves the selected items by a certain amount of items in a given direction * * @param list the JList to work on * @param moveby the number of items to move by * @param direction the direction to move in * @see #MOVE_UP * @see #MOVE_DOWN */ protected static void moveItems(JList list, int moveby, int direction) { int[] indices; int i; Object o; DefaultListModel model; model = (DefaultListModel) list.getModel(); switch (direction) { case MOVE_UP: indices = list.getSelectedIndices(); for (i = 0; i < indices.length; i++) { if (indices[i] == 0) continue; o = model.remove(indices[i]); indices[i] -= moveby; model.insertElementAt(o, indices[i]); } list.setSelectedIndices(indices); break; case MOVE_DOWN: indices = list.getSelectedIndices(); for (i = indices.length - 1; i >= 0; i--) { if (indices[i] == model.getSize() - 1) continue; o = model.remove(indices[i]); indices[i] += moveby; model.insertElementAt(o, indices[i]); } list.setSelectedIndices(indices); break; default: System.err.println( JListHelper.class.getName() + ": direction '" + direction + "' is unknown!"); } } /** * moves the selected items up by 1 * * @param list the JList to work on */ public static void moveUp(JList list) { if (canMoveUp(list)) moveItems(list, 1, MOVE_UP); } /** * moves the selected item down by 1 * * @param list the JList to work on */ public static void moveDown(JList list) { if (canMoveDown(list)) moveItems(list, 1, MOVE_DOWN); } /** * moves the selected items to the top * * @param list the JList to work on */ public static void moveTop(JList list) { int[] indices; int diff; if (canMoveUp(list)) { indices = list.getSelectedIndices(); diff = indices[0]; moveItems(list, diff, MOVE_UP); } } /** * moves the selected items to the end * * @param list the JList to work on */ public static void moveBottom(JList list) { int[] indices; int diff; if (canMoveDown(list)) { indices = list.getSelectedIndices(); diff = list.getModel().getSize() - 1 - indices[indices.length - 1]; moveItems(list, diff, MOVE_DOWN); } } /** * checks whether the selected items can be moved up * * @param list the JList to work on */ public static boolean canMoveUp(JList list) { boolean result; int[] indices; result = false; indices = list.getSelectedIndices(); if (indices.length > 0) { if (indices[0] > 0) result = true; } return result; } /** * checks whether the selected items can be moved down * * @param list the JList to work on */ public static boolean canMoveDown(JList list) { boolean result; int[] indices; result = false; indices = list.getSelectedIndices(); if (indices.length > 0) { if (indices[indices.length - 1] < list.getModel().getSize() - 1) result = true; } return result; } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/JTableHelper.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * JTableHelper.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.awt.Component; import java.awt.Point; import java.awt.Rectangle; import javax.swing.JTable; import javax.swing.JViewport; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import javax.swing.table.TableModel; /** * A helper class for JTable, e.g. calculating the optimal colwidth. * * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class JTableHelper { // the table to work with private final JTable jtable; /** * initializes the object */ public JTableHelper(JTable jtable) { this.jtable = jtable; } /** * returns the JTable */ public JTable getJTable() { return jtable; } /** * calcs the optimal column width of the given column */ public int calcColumnWidth(int col) { return calcColumnWidth(getJTable(), col); } /** * Calculates the optimal width for the column of the given table. The * calculation is based on the preferred width of the header and cell * renderer. <br> * Taken from the newsgoup de.comp.lang.java with some modifications.<br> * Taken from FOPPS/EnhancedTable - http://fopps.sourceforge.net/<br> * * @param table the table to calculate the column width * @param col the column to calculate the widths * @return the width, -1 if error */ public static int calcColumnWidth(JTable table, int col) { int width = calcHeaderWidth(table, col); if (width == -1) { return width; } TableColumnModel columns = table.getColumnModel(); TableModel data = table.getModel(); int rowCount = data.getRowCount(); columns.getColumn(col); try { for (int row = rowCount - 1; row >= 0; --row) { Component c = table.prepareRenderer(table.getCellRenderer(row, col), row, col); width = Math.max(width, c.getPreferredSize().width + 10); } } catch (Exception e) { e.printStackTrace(); } return width; } /** * calcs the optimal header width of the given column */ public int calcHeaderWidth(int col) { return calcHeaderWidth(getJTable(), col); } /** * Calculates the optimal width for the header of the given table. The * calculation is based on the preferred width of the header renderer. * * @param table the table to calculate the column width * @param col the column to calculate the widths * @return the width, -1 if error */ public static int calcHeaderWidth(JTable table, int col) { if (table == null) { return -1; } if (col < 0 || col > table.getColumnCount()) { System.out.println("invalid col " + col); return -1; } JTableHeader header = table.getTableHeader(); TableCellRenderer defaultHeaderRenderer = null; if (header != null) { defaultHeaderRenderer = header.getDefaultRenderer(); } TableColumnModel columns = table.getColumnModel(); table.getModel(); TableColumn column = columns.getColumn(col); int width = -1; TableCellRenderer h = column.getHeaderRenderer(); if (h == null) { h = defaultHeaderRenderer; } if (h != null) { // Not explicitly impossible Component c = h.getTableCellRendererComponent(table, column.getHeaderValue(), false, false, -1, col); width = c.getPreferredSize().width + 5; } return width; } /** * sets the optimal column width for the given column */ public void setOptimalColumnWidth(int col) { setOptimalColumnWidth(getJTable(), col); } /** * sets the optimal column width for the given column */ public static void setOptimalColumnWidth(JTable jtable, int col) { int width; TableColumn column; JTableHeader header; if ((col >= 0) && (col < jtable.getColumnModel().getColumnCount())) { width = calcColumnWidth(jtable, col); if (width >= 0) { header = jtable.getTableHeader(); column = jtable.getColumnModel().getColumn(col); column.setPreferredWidth(width); jtable.sizeColumnsToFit(-1); header.repaint(); } } } /** * sets the optimal column width for all columns */ public void setOptimalColumnWidth() { setOptimalColumnWidth(getJTable()); } /** * sets the optimal column width for alls column if the given table */ public static void setOptimalColumnWidth(JTable jtable) { int i; for (i = 0; i < jtable.getColumnModel().getColumnCount(); i++) { setOptimalColumnWidth(jtable, i); } } /** * sets the optimal header width for the given column */ public void setOptimalHeaderWidth(int col) { setOptimalHeaderWidth(getJTable(), col); } /** * sets the optimal header width for the given column */ public static void setOptimalHeaderWidth(JTable jtable, int col) { int width; TableColumn column; JTableHeader header; if ((col >= 0) && (col < jtable.getColumnModel().getColumnCount())) { width = calcHeaderWidth(jtable, col); if (width >= 0) { header = jtable.getTableHeader(); column = jtable.getColumnModel().getColumn(col); column.setPreferredWidth(width); jtable.sizeColumnsToFit(-1); header.repaint(); } } } /** * sets the optimal header width for all columns */ public void setOptimalHeaderWidth() { setOptimalHeaderWidth(getJTable()); } /** * sets the optimal header width for alls column if the given table */ public static void setOptimalHeaderWidth(JTable jtable) { int i; for (i = 0; i < jtable.getColumnModel().getColumnCount(); i++) { setOptimalHeaderWidth(jtable, i); } } /** * Assumes table is contained in a JScrollPane. Scrolls the cell (rowIndex, * vColIndex) so that it is visible within the viewport. */ public void scrollToVisible(int row, int col) { scrollToVisible(getJTable(), row, col); } /** * Assumes table is contained in a JScrollPane. Scrolls the cell (rowIndex, * vColIndex) so that it is visible within the viewport. */ public static void scrollToVisible(JTable table, int row, int col) { if (!(table.getParent() instanceof JViewport)) { return; } JViewport viewport = (JViewport) table.getParent(); // This rectangle is relative to the table where the // northwest corner of cell (0,0) is always (0,0). Rectangle rect = table.getCellRect(row, col, true); // The location of the viewport relative to the table Point pt = viewport.getViewPosition(); // Translate the cell location so that it is relative // to the view, assuming the northwest corner of the // view is (0,0) rect.setLocation(rect.x - pt.x, rect.y - pt.y); // Scroll the area into view viewport.scrollRectToVisible(rect); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/ListSelectorDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ListSelectorDialog.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.regex.Pattern; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JScrollPane; /** * A dialog to present the user with a list of items, that the user can * make a selection from, or cancel the selection. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public class ListSelectorDialog extends JDialog { /** for serialization */ private static final long serialVersionUID = 906147926840288895L; /** Click to choose the currently selected property */ protected JButton m_SelectBut = new JButton("Select"); /** Click to cancel the property selection */ protected JButton m_CancelBut = new JButton("Cancel"); /** Click to enter a regex pattern for selection */ protected JButton m_PatternBut = new JButton("Pattern"); /** The list component */ protected JList m_List; /** Whether the selection was made or cancelled */ protected int m_Result; /** Signifies an OK property selection */ public static final int APPROVE_OPTION = 0; /** Signifies a cancelled property selection */ public static final int CANCEL_OPTION = 1; /** The current regular expression. */ protected String m_PatternRegEx = ".*"; /** * Create the list selection dialog. * * @param parentFrame the parent window of the dialog * @param userList the JList component the user will select from */ public ListSelectorDialog(Window parentFrame, JList userList) { super(parentFrame, "Select items", ModalityType.DOCUMENT_MODAL); m_List = userList; m_CancelBut.setMnemonic('C'); m_CancelBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { m_Result = CANCEL_OPTION; setVisible(false); } }); m_SelectBut.setMnemonic('S'); m_SelectBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { m_Result = APPROVE_OPTION; setVisible(false); } }); m_PatternBut.setMnemonic('P'); m_PatternBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectPattern(); } }); Container c = getContentPane(); c.setLayout(new BorderLayout()); // setBorder(BorderFactory.createTitledBorder("Select a property")); Box b1 = new Box(BoxLayout.X_AXIS); b1.add(m_SelectBut); b1.add(Box.createHorizontalStrut(10)); b1.add(m_PatternBut); b1.add(Box.createHorizontalStrut(10)); b1.add(m_CancelBut); c.add(b1, BorderLayout.SOUTH); c.add(new JScrollPane(m_List), BorderLayout.CENTER); getRootPane().setDefaultButton(m_SelectBut); pack(); // make sure, it's not bigger than the screen Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); int width = getWidth() > screen.getWidth() ? (int) screen.getWidth() : getWidth(); int height = getHeight() > screen.getHeight() ? (int) screen.getHeight() : getHeight(); setSize(width, height); setLocationRelativeTo(parentFrame); } /** * Pops up the modal dialog and waits for cancel or a selection. * * @return either APPROVE_OPTION, or CANCEL_OPTION */ public int showDialog() { m_Result = CANCEL_OPTION; int [] origSelected = m_List.getSelectedIndices(); setVisible(true); if (m_Result == CANCEL_OPTION) { m_List.setSelectedIndices(origSelected); } return m_Result; } /** * opens a separate dialog for entering a regex pattern for selecting * elements from the provided list */ protected void selectPattern() { String pattern = JOptionPane.showInputDialog( m_PatternBut.getParent(), "Enter a Perl regular expression ('.*' for all)", m_PatternRegEx); if (pattern != null) { try { Pattern.compile(pattern); m_PatternRegEx = pattern; m_List.clearSelection(); for (int i = 0; i < m_List.getModel().getSize(); i++) { if (Pattern.matches( pattern, m_List.getModel().getElementAt(i).toString())) m_List.addSelectionInterval(i, i); } } catch (Exception ex) { JOptionPane.showMessageDialog( m_PatternBut.getParent(), "'" + pattern + "' is not a valid Perl regular expression!\n" + "Error: " + ex, "Error in Pattern...", JOptionPane.ERROR_MESSAGE); } } } /** * Tests out the list selector from the command line. * * @param args ignored */ public static void main(String [] args) { try { DefaultListModel lm = new DefaultListModel(); lm.addElement("one"); lm.addElement("two"); lm.addElement("three"); lm.addElement("four"); lm.addElement("five"); JList jl = new JList(lm); final ListSelectorDialog jd = new ListSelectorDialog(null, jl); int result = jd.showDialog(); if (result == ListSelectorDialog.APPROVE_OPTION) { System.err.println("Fields Selected"); int [] selected = jl.getSelectedIndices(); for (int i = 0; i < selected.length; i++) { System.err.println("" + selected[i] + " " + lm.elementAt(selected[i])); } } else { System.err.println("Cancelled"); } System.exit(0); } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/Loader.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Loader.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; /** * This class is for loading resources from a JAR archive. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class Loader { /** the dir to use as prefix if filenames are w/o it, must have a slash * at the end (the path separator is a slash!) */ private String dir; /** * initializes the object */ public Loader(String dir) { this.dir = dir; } /** * returns the dir prefix */ public String getDir() { return dir; } /** * returns the processed filename, i.e. with the dir-prefix if it's * missing */ public String processFilename(String filename) { if (!filename.startsWith(getDir())) filename = getDir() + filename; return filename; } /** * returns a URL for the given filename, can be NULL if it fails */ public static URL getURL(String dir, String filename) { Loader loader; loader = new Loader(dir); return loader.getURL(filename); } /** * returns a URL for the given filename, can be NULL if it fails */ public URL getURL(String filename) { filename = processFilename(filename); return Loader.class.getClassLoader().getResource(filename); } /** * returns an InputStream for the given dir and filename, can be NULL if it * fails */ public static InputStream getInputStream(String dir, String filename) { Loader loader; loader = new Loader(dir); return loader.getInputStream(filename); } /** * returns an InputStream for the given filename, can be NULL if it fails */ public InputStream getInputStream(String filename) { filename = processFilename(filename); return Loader.class.getResourceAsStream(filename); } /** * returns a Reader for the given filename and dir, can be NULL if it fails */ public static Reader getReader(String dir, String filename) { Loader loader; loader = new Loader(dir); return loader.getReader(filename); } /** * returns a Reader for the given filename, can be NULL if it fails */ public Reader getReader(String filename) { InputStream in; in = getInputStream(filename); if (in == null) return null; else return new InputStreamReader(in); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/LogPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * LogPanel.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import weka.core.Utils; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.text.SimpleDateFormat; import java.util.Date; /** * This panel allows log and status messages to be posted. Log messages appear * in a scrollable text area, and status messages appear as one-line transient * messages. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public class LogPanel extends JPanel implements Logger, TaskLogger { /** for serialization */ private static final long serialVersionUID = -4072464549112439484L; /** Displays the current status */ protected JLabel m_StatusLab = new JLabel("OK"); /** Displays the log messages */ protected JTextArea m_LogText = new JTextArea(4, 20); /** The button for viewing the log */ protected JButton m_logButton = new JButton("Log"); /** An indicator for whether text has been output yet */ protected boolean m_First = true; /** The panel for monitoring the number of running tasks (if supplied) */ protected WekaTaskMonitor m_TaskMonitor = null; /** * Creates the log panel with no task monitor and the log always visible. */ public LogPanel() { this(null, false, false, true); } /** * Creates the log panel with a task monitor, where the log is hidden. * * @param tm the task monitor, or null for none */ public LogPanel(WekaTaskMonitor tm) { this(tm, true, false, true); } /** * Creates the log panel, possibly with task monitor, where the log is * optionally hidden. * * @param tm the task monitor, or null for none * @param logHidden true if the log should be hidden and acessible via a * button, or false if the log should always be visible. */ public LogPanel(WekaTaskMonitor tm, boolean logHidden) { this(tm, logHidden, false, true); } /** * Creates the log panel, possibly with task monitor, where the either the log * is optionally hidden or the status (having both hidden is not allowed). * * * @param tm the task monitor, or null for none * @param logHidden true if the log should be hidden and acessible via a * button, or false if the log should always be visible. * @param statusHidden true if the status bar should be hidden (i.e. * @param titledBorder true if the log should have a title you only want the * log part). */ public LogPanel(WekaTaskMonitor tm, boolean logHidden, boolean statusHidden, boolean titledBorder) { m_TaskMonitor = tm; m_LogText.setEditable(false); m_LogText.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); m_StatusLab.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("Status"), BorderFactory.createEmptyBorder(0, 5, 5, 5))); // create scrolling log final JScrollPane js = new JScrollPane(m_LogText); js.getViewport().addChangeListener(new ChangeListener() { private int lastHeight; public void stateChanged(ChangeEvent e) { JViewport vp = (JViewport) e.getSource(); int h = vp.getViewSize().height; if (h != lastHeight) { // i.e. an addition not just a user scrolling lastHeight = h; int x = h - vp.getExtentSize().height; vp.setViewPosition(new Point(0, x)); } } }); if (logHidden) { // create log window final JFrame jf = Utils.getWekaJFrame("Log", this); jf.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { jf.setVisible(false); } }); jf.getContentPane().setLayout(new BorderLayout()); jf.getContentPane().add(js, BorderLayout.CENTER); jf.pack(); jf.setSize(800, 600); // display log window on request m_logButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Window windowAncestor = SwingUtilities.getWindowAncestor(LogPanel.this); if (windowAncestor instanceof Frame) { jf.setIconImage(((Frame) windowAncestor).getIconImage()); } jf.setLocationRelativeTo(LogPanel.this); jf.setVisible(true); } }); // do layout setLayout(new BorderLayout()); JPanel logButPanel = new JPanel(); logButPanel.setLayout(new BorderLayout()); logButPanel.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5)); logButPanel.add(m_logButton, BorderLayout.CENTER); JPanel p1 = new JPanel(); p1.setLayout(new BorderLayout()); p1.add(m_StatusLab, BorderLayout.CENTER); p1.add(logButPanel, BorderLayout.EAST); if (tm == null) { add(p1, BorderLayout.SOUTH); } else { JPanel p2 = new JPanel(); p2.setLayout(new BorderLayout()); p2.add(p1, BorderLayout.CENTER); p2.add((java.awt.Component) m_TaskMonitor, BorderLayout.EAST); add(p2, BorderLayout.SOUTH); } } else { // log always visible JPanel p1 = new JPanel(); if (titledBorder) { p1.setBorder(BorderFactory.createTitledBorder("Log")); } p1.setLayout(new BorderLayout()); p1.add(js, BorderLayout.CENTER); setLayout(new BorderLayout()); add(p1, BorderLayout.CENTER); if (tm == null) { if (!statusHidden) { add(m_StatusLab, BorderLayout.SOUTH); } } else { if (!statusHidden) { JPanel p2 = new JPanel(); p2.setLayout(new BorderLayout()); p2.add(m_StatusLab, BorderLayout.CENTER); p2.add((java.awt.Component) m_TaskMonitor, BorderLayout.EAST); add(p2, BorderLayout.SOUTH); } } } addPopup(); } /** * Set the size of the font used in the log message area. <= 0 will use the * default for JTextArea. * * @param size the size of the font to use in the log message area */ public void setLoggingFontSize(int size) { if (size > 0) { m_LogText.setFont(new Font(null, Font.PLAIN, size)); } else { Font temp = new JTextArea().getFont(); m_LogText.setFont(temp); } } /** * adds thousand's-separators to the number * * @param l the number to print * @return the number as string with separators */ private String printLong(long l) { String result; String str; int i; int count; str = Long.toString(l); result = ""; count = 0; for (i = str.length() - 1; i >= 0; i--) { count++; result = str.charAt(i) + result; if ((count == 3) && (i > 0)) { result = "," + result; count = 0; } } return result; } /** * Add a popup menu for displaying the amount of free memory and running the * garbage collector */ private void addPopup() { addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (((e.getModifiers() & InputEvent.BUTTON1_MASK) != InputEvent.BUTTON1_MASK) || e.isAltDown()) { JPopupMenu gcMenu = new JPopupMenu(); JMenuItem availMem = new JMenuItem("Memory information"); availMem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ee) { System.gc(); Runtime currR = Runtime.getRuntime(); long freeM = currR.freeMemory(); long totalM = currR.totalMemory(); long maxM = currR.maxMemory(); logMessage("Memory (free/total/max.) in bytes: " + printLong(freeM) + " / " + printLong(totalM) + " / " + printLong(maxM)); statusMessage("Memory (free/total/max.) in bytes: " + printLong(freeM) + " / " + printLong(totalM) + " / " + printLong(maxM)); } }); gcMenu.add(availMem); JMenuItem runGC = new JMenuItem("Run garbage collector"); runGC.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ee) { statusMessage("Running garbage collector"); System.gc(); statusMessage("OK"); } }); gcMenu.add(runGC); gcMenu.show(LogPanel.this, e.getX(), e.getY()); } } }); } /** * Record the starting of a new task */ public void taskStarted() { if (m_TaskMonitor != null) { m_TaskMonitor.taskStarted(); } } /** * Record a task ending */ public void taskFinished() { if (m_TaskMonitor != null) { m_TaskMonitor.taskFinished(); } } /** * Gets a string containing current date and time. * * @return a string containing the date and time. */ protected static String getTimestamp() { return (new SimpleDateFormat("HH:mm:ss:")).format(new Date()); } /** * Sends the supplied message to the log area. The current timestamp will be * prepended. * * @param message a value of type 'String' */ public synchronized void logMessage(String message) { if (m_First) { m_First = false; } else { m_LogText.append("\n"); } m_LogText.append(LogPanel.getTimestamp() + ' ' + message); weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, message); } /** * Sends the supplied message to the status line. * * @param message the status message */ public synchronized void statusMessage(String message) { m_StatusLab.setText(message); } /** * Tests out the log panel from the command line. * * @param args ignored */ public static void main(String[] args) { try { final javax.swing.JFrame jf = new javax.swing.JFrame("Log Panel"); jf.getContentPane().setLayout(new BorderLayout()); final LogPanel lp = new LogPanel(); jf.getContentPane().add(lp, BorderLayout.CENTER); jf.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { jf.dispose(); System.exit(0); } }); jf.pack(); jf.setVisible(true); lp.logMessage("Welcome to the generic log panel!"); lp.statusMessage("Hi there"); lp.logMessage("Funky chickens"); } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/LogWindow.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * LogWindow.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.io.PrintStream; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSpinner; import javax.swing.JTextPane; import javax.swing.SpinnerNumberModel; import javax.swing.event.CaretEvent; import javax.swing.event.CaretListener; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyleContext; import javax.swing.text.StyledDocument; import weka.core.Tee; import weka.core.Utils; /** * Frame that shows the output from stdout and stderr. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class LogWindow extends JFrame implements CaretListener, ChangeListener { /** for serialization */ private static final long serialVersionUID = 5650947361381061112L; /** the name of the style for stdout */ public final static String STYLE_STDOUT = "stdout"; /** the name of the style for stderr */ public final static String STYLE_STDERR = "stderr"; /** the color of the style for stdout */ public final static Color COLOR_STDOUT = Color.BLACK; /** the Color of the style for stderr */ public final static Color COLOR_STDERR = Color.RED; /** whether we're debugging - enables output on stdout */ public final static boolean DEBUG = false; /** whether the JTextPane has wordwrap or not */ public boolean m_UseWordwrap = true; /** the output */ protected JTextPane m_Output = new JTextPane(); /** the clear button */ protected JButton m_ButtonClear = new JButton("Clear"); /** the close button */ protected JButton m_ButtonClose = new JButton("Close"); /** the current size */ protected JLabel m_LabelCurrentSize = new JLabel("currently: 0"); /** the spinner for the max number of chars */ protected JSpinner m_SpinnerMaxSize = new JSpinner(); /** whether to allow wordwrap or not */ protected JCheckBox m_CheckBoxWordwrap = new JCheckBox("Use wordwrap"); /** for redirecting stdout */ protected static Tee m_TeeOut = null; /** for redirecting stderr */ protected static Tee m_TeeErr = null; /** * inner class for printing to the window, is used instead of standard * System.out and System.err */ protected class LogWindowPrintStream extends PrintStream { /** the parent */ protected LogWindow m_Parent = null; /** the style of the printstream */ protected String m_Style = null; /** * the constructor * * @param parent the parent frame * @param stream the stream (used for constructor of superclass) * @param style the style name associated with this output */ public LogWindowPrintStream(LogWindow parent, PrintStream stream, String style) { super(stream); m_Parent = parent; m_Style = style; } /** * flushes the printstream */ @Override public synchronized void flush() { // ignored } /** * prints the given int */ @Override public synchronized void print(int x) { print(new Integer(x).toString()); } /** * prints the given boolean */ @Override public synchronized void print(boolean x) { print(new Boolean(x).toString()); } /** * prints the given string */ @Override public synchronized void print(String x) { StyledDocument doc; doc = m_Parent.m_Output.getStyledDocument(); try { // insert text doc.insertString(doc.getLength(), x, doc.getStyle(m_Style)); // move cursor to end m_Parent.m_Output.setCaretPosition(doc.getLength()); // trim size if necessary m_Parent.trim(); } catch (Exception e) { e.printStackTrace(); } } /** * prints the given object */ @Override public synchronized void print(Object x) { String line; Throwable t; StackTraceElement[] trace; int i; if (x instanceof Throwable) { t = (Throwable) x; trace = t.getStackTrace(); line = t.getMessage() + "\n"; for (i = 0; i < trace.length; i++) { line += "\t" + trace[i].toString() + "\n"; } x = line; } if (x == null) { print("null"); } else { print(x.toString()); } } /** * prints a new line */ @Override public synchronized void println() { print("\n"); } /** * prints the given int */ @Override public synchronized void println(int x) { print(x); println(); } /** * prints the given boolean */ @Override public synchronized void println(boolean x) { print(x); println(); } /** * prints the given string */ @Override public synchronized void println(String x) { print(x); println(); } /** * prints the given object (for Throwables we print the stack trace) */ @Override public synchronized void println(Object x) { print(x); println(); } } /** * creates the frame */ public LogWindow() { super("Weka - Log"); createFrame(); // styles StyledDocument doc; Style style; boolean teeDone; doc = m_Output.getStyledDocument(); style = StyleContext.getDefaultStyleContext().getStyle( StyleContext.DEFAULT_STYLE); style = doc.addStyle(STYLE_STDOUT, style); StyleConstants.setFontFamily(style, "monospaced"); StyleConstants.setForeground(style, COLOR_STDOUT); style = StyleContext.getDefaultStyleContext().getStyle( StyleContext.DEFAULT_STYLE); style = doc.addStyle(STYLE_STDERR, style); StyleConstants.setFontFamily(style, "monospaced"); StyleConstants.setForeground(style, COLOR_STDERR); // print streams (instantiate only once!) teeDone = !((m_TeeOut == null) && (m_TeeErr == null)); if (!DEBUG) { if (!teeDone) { m_TeeOut = new Tee(System.out); System.setOut(m_TeeOut); } m_TeeOut.add(new LogWindowPrintStream(this, m_TeeOut.getDefault(), STYLE_STDOUT)); } if (!teeDone) { m_TeeErr = new Tee(System.err); System.setErr(m_TeeErr); } m_TeeErr.add(new LogWindowPrintStream(this, m_TeeErr.getDefault(), STYLE_STDERR)); } /** * creates the frame and all its components */ protected void createFrame() { JPanel panel; JPanel panel2; JPanel panel3; JPanel panel4; SpinnerNumberModel model; int width; JLabel label; // set layout setSize(600, 400); width = getBounds().width; setLocation(getGraphicsConfiguration().getBounds().width - width, getLocation().y); getContentPane().setLayout(new BorderLayout()); // output getContentPane().add(new JScrollPane(m_Output), BorderLayout.CENTER); setWordwrap(m_UseWordwrap); // button(s) panel = new JPanel(new BorderLayout()); getContentPane().add(panel, BorderLayout.SOUTH); panel3 = new JPanel(new BorderLayout()); panel.add(panel3, BorderLayout.SOUTH); panel2 = new JPanel(new FlowLayout(FlowLayout.RIGHT)); panel3.add(panel2, BorderLayout.EAST); m_ButtonClear.setMnemonic('C'); m_ButtonClear.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { clear(); } }); panel2.add(m_ButtonClear); m_ButtonClose.setMnemonic('l'); m_ButtonClose.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { close(); } }); panel2.add(m_ButtonClose); // size + current size + wordwrap panel2 = new JPanel(new GridLayout(1, 3)); panel3.add(panel2, BorderLayout.WEST); // size panel4 = new JPanel(new FlowLayout()); panel2.add(panel4); model = (SpinnerNumberModel) m_SpinnerMaxSize.getModel(); model.setMinimum(new Integer(1)); model.setStepSize(new Integer(1000)); model.setValue(new Integer(100000)); model.addChangeListener(this); label = new JLabel("max. Size"); label.setDisplayedMnemonic('m'); label.setLabelFor(m_SpinnerMaxSize); panel4.add(label); panel4.add(m_SpinnerMaxSize); // current size panel4 = new JPanel(new FlowLayout()); panel2.add(panel4); panel4.add(m_LabelCurrentSize); // wordwrap panel4 = new JPanel(new FlowLayout()); panel2.add(panel4); m_CheckBoxWordwrap.setSelected(m_UseWordwrap); m_CheckBoxWordwrap.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { setWordwrap(m_CheckBoxWordwrap.isSelected()); } }); panel4.add(m_CheckBoxWordwrap); } /** * clears the output */ public void clear() { m_Output.setText(""); } /** * closes the frame */ public void close() { setVisible(false); } /** * trims the JTextPane, if too big */ public void trim() { StyledDocument doc; int size; int maxSize; int pos; doc = m_Output.getStyledDocument(); // too large? size = doc.getLength(); maxSize = ((Integer) m_SpinnerMaxSize.getValue()).intValue(); if (size > maxSize) { try { // determine EOL after which to cut pos = size - maxSize; while (!doc.getText(pos, 1).equals("\n")) { pos++; } while (doc.getText(pos, 1).equals("\n")) { pos++; } // delete text doc.remove(0, pos); } catch (Exception ex) { // don't print it, otherwise we get an endless loop! if (DEBUG) { System.out.println(ex); } } } // move cursor to end m_Output.setCaretPosition(doc.getLength()); } /** * returns a string representation (#RGB) of the given color */ protected String colorToString(Color c) { String result; result = "#" + Utils.padLeft(Integer.toHexString(c.getRed()), 2) + Utils.padLeft(Integer.toHexString(c.getGreen()), 2) + Utils.padLeft(Integer.toHexString(c.getBlue()), 2); result = result.replaceAll("\\ ", "0").toUpperCase(); return result; } /** * toggles the wordwrap<br/> * override wordwrap from: * http://forum.java.sun.com/thread.jspa?threadID=498535&messageID=2356174 */ public void setWordwrap(boolean wrap) { Container parent; JTextPane outputOld; m_UseWordwrap = wrap; if (m_CheckBoxWordwrap.isSelected() != m_UseWordwrap) { m_CheckBoxWordwrap.setSelected(m_UseWordwrap); } // create new JTextPane parent = m_Output.getParent(); outputOld = m_Output; if (m_UseWordwrap) { m_Output = new JTextPane(); } else { m_Output = new JTextPane() { private static final long serialVersionUID = -8275856175921425981L; @Override public void setSize(Dimension d) { if (d.width < getGraphicsConfiguration().getBounds().width) { d.width = getGraphicsConfiguration().getBounds().width; } super.setSize(d); } @Override public boolean getScrollableTracksViewportWidth() { return false; } }; } m_Output.setEditable(false); m_Output.addCaretListener(this); m_Output.setDocument(outputOld.getDocument()); m_Output.setCaretPosition(m_Output.getDocument().getLength()); // m_Output.setToolTipText( // "stdout = " + colorToString(COLOR_STDOUT) + ", " // + "stderr = " + colorToString(COLOR_STDERR)); parent.add(m_Output); parent.remove(outputOld); } /** * Called when the caret position is updated. */ @Override public void caretUpdate(CaretEvent e) { m_LabelCurrentSize.setText("currently: " + m_Output.getStyledDocument().getLength()); if (DEBUG) { System.out.println(e); } } /** * Invoked when the target of the listener has changed its state. */ @Override public void stateChanged(ChangeEvent e) { // check max size if Spinner is changed if (e.getSource() == m_SpinnerMaxSize.getModel()) { trim(); validate(); caretUpdate(null); } } /** * for testing only */ public static void main(String[] args) { LogWindow log; LookAndFeel.setLookAndFeel(); log = new LogWindow(); log.setVisible(true); log.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // test output System.out.print("a"); System.err.print("a"); System.out.print("a"); System.out.println(); System.err.println(new java.util.Date()); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/Logger.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Logger.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; /** * Interface for objects that display log (permanent historical) and * status (transient) messages. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public interface Logger { /** * Sends the supplied message to the log area. These message will typically * have the current timestamp prepended, and be viewable as a history. * * @param message the log message */ void logMessage(String message); /** * Sends the supplied message to the status line. These messages are * typically one-line status messages to inform the user of progress * during processing (i.e. it doesn't matter if the user doesn't happen * to look at each message) * * @param message the status message. */ void statusMessage(String message); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/LookAndFeel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * LookAndFeel.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import weka.core.Environment; import weka.core.Settings; import weka.core.Utils; import javax.swing.JOptionPane; import javax.swing.UIDefaults; import javax.swing.UIManager; import javax.swing.UIManager.LookAndFeelInfo; import java.awt.Dimension; import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.event.KeyEvent; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.Properties; /** * A little helper class for setting the Look and Feel of the user interface. * Was necessary, since Java 1.5 sometimes crashed the WEKA GUI (e.g. under * Linux/Gnome). Running this class from the commandline will print all * available Look and Feel themes. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class LookAndFeel { /** The name of the properties file */ public static String PROPERTY_FILE = "weka/gui/LookAndFeel.props"; /** Contains the look and feel properties */ protected static Properties LOOKANDFEEL_PROPERTIES; static { try { LOOKANDFEEL_PROPERTIES = Utils.readProperties(PROPERTY_FILE); } catch (Exception ex) { JOptionPane.showMessageDialog(null, "LookAndFeel: Could not read a LookAndFeel configuration file.\n" + "An example file is included in the Weka distribution.\n" + "This file should be named \"" + PROPERTY_FILE + "\" and\n" + "should be placed either in your user home (which is set\n" + "to \"" + System.getProperties().getProperty("user.home") + "\")\n" + "or the directory that java was started from\n", "LookAndFeel", JOptionPane.ERROR_MESSAGE); } } /** * Get a list of fully qualified class names of available look and feels * * @return a list of look and feel class names that are available on this * platform */ public static List<String> getAvailableLookAndFeelClasses() { List<String> lafs = new LinkedList<String>(); for (UIManager.LookAndFeelInfo i : UIManager.getInstalledLookAndFeels()) { lafs.add(i.getClassName()); } return lafs; } /** * sets the look and feel to the specified class * * @param classname the look and feel to use * @return whether setting was successful */ public static boolean setLookAndFeel(String classname) { boolean result; try { UIManager.setLookAndFeel(classname); result = true; if (System.getProperty("os.name").toLowerCase().contains("mac os x") && !classname.contains("com.apple.laf")) { KeyboardFocusManager.getCurrentKeyboardFocusManager() .addKeyEventDispatcher(new KeyEventDispatcher() { @Override public boolean dispatchKeyEvent(KeyEvent e) { if (!e.isConsumed()) { if (e.isMetaDown()) { if (e.getKeyCode() == KeyEvent.VK_V || e.getKeyCode() == KeyEvent.VK_A || e.getKeyCode() == KeyEvent.VK_C || e.getKeyCode() == KeyEvent.VK_X) { e.setModifiers(KeyEvent.CTRL_DOWN_MASK); } } } return false; } }); } // workaround for scrollbar handle disappearing bug in Nimbus LAF: // https://bugs.openjdk.java.net/browse/JDK-8134828 if (classname.toLowerCase().contains("nimbus")) { javax.swing.LookAndFeel lookAndFeel = UIManager.getLookAndFeel(); UIDefaults defaults = lookAndFeel.getDefaults(); defaults.put("ScrollBar.minimumThumbSize", new Dimension(30, 30)); } } catch (Exception e) { e.printStackTrace(); result = false; } return result; } /** * Set the look and feel from loaded settings * * @param appID the ID of the application to load settings for * @param lookAndFeelKey the key to look up the look and feel in the settings * @throws IOException if a problem occurs when loading settings */ public static void setLookAndFeel(String appID, String lookAndFeelKey, String defaultLookAndFeel) throws IOException { Settings forLookAndFeelOnly = new Settings("weka", appID); String laf = forLookAndFeelOnly.getSetting(appID, lookAndFeelKey, defaultLookAndFeel, Environment.getSystemWide()); if (laf.length() > 0 && laf.contains(".") && LookAndFeel.setLookAndFeel(laf)) { } else { LookAndFeel.setLookAndFeel(); } } /** * sets the look and feel to the one in the props-file or if not set the * default one of the system * * @return whether setting was successful */ public static boolean setLookAndFeel() { String classname; classname = LOOKANDFEEL_PROPERTIES.getProperty("Theme", ""); if (classname.equals("")) { // Java 1.5 crashes under Gnome if one sets it to the GTKLookAndFeel // theme, hence we don't set any theme by default if we're on a Linux // box. if (System.getProperty("os.name").equalsIgnoreCase("linux")) { return true; } else { classname = getSystemLookAndFeel(); } } return setLookAndFeel(classname); } /** * returns the system LnF classname * * @return the name of the System LnF class */ public static String getSystemLookAndFeel() { return UIManager.getSystemLookAndFeelClassName(); } /** * returns an array with the classnames of all the installed LnFs * * @return the installed LnFs */ public static String[] getInstalledLookAndFeels() { String[] result; LookAndFeelInfo[] laf; int i; laf = UIManager.getInstalledLookAndFeels(); result = new String[laf.length]; for (i = 0; i < laf.length; i++) result[i] = laf[i].getClassName(); return result; } /** * prints all the available LnFs to stdout * * @param args the commandline options */ public static void main(String[] args) { String[] list; int i; System.out.println("\nInstalled Look and Feel themes:"); list = getInstalledLookAndFeels(); for (i = 0; i < list.length; i++) System.out.println((i + 1) + ". " + list[i]); System.out .println("\nNote: a theme can be set in '" + PROPERTY_FILE + "'."); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/Main.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Main.java * Copyright (C) 2006-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; import java.awt.GridLayout; import java.awt.Image; import java.awt.LayoutManager; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.Reader; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.Vector; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JDesktopPane; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JInternalFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTable; import javax.swing.SwingConstants; import javax.swing.WindowConstants; import javax.swing.event.InternalFrameAdapter; import javax.swing.event.InternalFrameEvent; import weka.classifiers.bayes.net.GUI; import weka.classifiers.evaluation.ThresholdCurve; import weka.core.Copyright; import weka.core.Instances; import weka.core.Memory; import weka.core.Option; import weka.core.OptionHandler; import weka.core.SelectedTag; import weka.core.SystemInfo; import weka.core.Tag; import weka.core.Utils; import weka.core.Version; import weka.core.scripting.Groovy; import weka.core.scripting.Jython; import weka.gui.arffviewer.ArffViewerMainPanel; import weka.gui.beans.KnowledgeFlowApp; import weka.gui.beans.StartUpListener; import weka.gui.boundaryvisualizer.BoundaryVisualizer; import weka.gui.experiment.Experimenter; import weka.gui.explorer.Explorer; import weka.gui.graphvisualizer.GraphVisualizer; import weka.gui.scripting.GroovyPanel; import weka.gui.scripting.JythonPanel; import weka.gui.sql.SqlViewer; import weka.gui.treevisualizer.Node; import weka.gui.treevisualizer.NodePlace; import weka.gui.treevisualizer.PlaceNode2; import weka.gui.treevisualizer.TreeBuild; import weka.gui.treevisualizer.TreeVisualizer; import weka.gui.visualize.PlotData2D; import weka.gui.visualize.ThresholdVisualizePanel; import weka.gui.visualize.VisualizePanel; /** * Menu-based GUI for Weka, replacement for the GUIChooser. * * <!-- options-start --> Valid options are: * <p/> * * <pre> * -gui &lt;MDI|SDI&gt; * Determines the layout of the GUI: * MDI = MDI Layout * SDI = SDI Layout * (default: MDI) * </pre> * * <!-- options-end --> * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class Main extends JFrame implements OptionHandler { /** for serialization. */ private static final long serialVersionUID = 1453813254824253849L; /** * DesktopPane with background image. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public static class BackgroundDesktopPane extends JDesktopPane { /** for serialization. */ private static final long serialVersionUID = 2046713123452402745L; /** the actual background image. */ protected Image m_Background; /** * intializes the desktop pane. * * @param image the image to use as background */ public BackgroundDesktopPane(String image) { super(); try { m_Background = Toolkit.getDefaultToolkit().getImage( ClassLoader.getSystemResource(image)); } catch (Exception e) { e.printStackTrace(); } } /** * draws the background image. * * @param g the graphics context */ @Override public void paintComponent(Graphics g) { super.paintComponent(g); if (m_Background != null) { g.setColor(Color.WHITE); g.clearRect(0, 0, getWidth(), getHeight()); int width = m_Background.getWidth(null); int height = m_Background.getHeight(null); int x = (getWidth() - width) / 2; int y = (getHeight() - height) / 2; g.drawImage(m_Background, x, y, width, height, this); } } } /** * Specialized JFrame class. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public static class ChildFrameSDI extends JFrame { /** for serialization. */ private static final long serialVersionUID = 8588293938686425618L; /** the parent frame. */ protected Main m_Parent; /** * constructs a new internal frame that knows about its parent. * * @param parent the parent frame * @param title the title of the frame */ public ChildFrameSDI(Main parent, String title) { super(title); m_Parent = parent; addWindowListener(new WindowAdapter() { @Override public void windowActivated(WindowEvent e) { // update title of parent if (getParentFrame() != null) { getParentFrame().createTitle(getTitle()); } } }); // add to parent if (getParentFrame() != null) { getParentFrame().addChildFrame(this); setIconImage(getParentFrame().getIconImage()); } } /** * returns the parent frame, can be null. * * @return the parent frame */ public Main getParentFrame() { return m_Parent; } /** * de-registers the child frame with the parent first. */ @Override public void dispose() { if (getParentFrame() != null) { getParentFrame().removeChildFrame(this); getParentFrame().createTitle(""); } super.dispose(); } } /** * Specialized JInternalFrame class. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public static class ChildFrameMDI extends JInternalFrame { /** for serialization. */ private static final long serialVersionUID = 3772573515346899959L; /** the parent frame. */ protected Main m_Parent; /** * constructs a new internal frame that knows about its parent. * * @param parent the parent frame * @param title the title of the frame */ public ChildFrameMDI(Main parent, String title) { super(title, true, true, true, true); m_Parent = parent; addInternalFrameListener(new InternalFrameAdapter() { @Override public void internalFrameActivated(InternalFrameEvent e) { // update title of parent if (getParentFrame() != null) { getParentFrame().createTitle(getTitle()); } } }); // add to parent if (getParentFrame() != null) { getParentFrame().addChildFrame(this); getParentFrame().jDesktopPane.add(this); } } /** * returns the parent frame, can be null. * * @return the parent frame */ public Main getParentFrame() { return m_Parent; } /** * de-registers the child frame with the parent first. */ @Override public void dispose() { if (getParentFrame() != null) { getParentFrame().removeChildFrame(this); getParentFrame().createTitle(""); } super.dispose(); } } /** displays the GUI as MDI. */ public final static int GUI_MDI = 0; /** displays the GUI as SDI. */ public final static int GUI_SDI = 1; /** GUI tags. */ public static final Tag[] TAGS_GUI = { new Tag(GUI_MDI, "MDI", "MDI Layout"), new Tag(GUI_SDI, "SDI", "SDI Layout") }; /** the frame itself. */ protected Main m_Self; /** the type of GUI to display. */ protected int m_GUIType = GUI_MDI; /** * variable for the Main class which would be set to null by the memory * monitoring thread to free up some memory if we running out of memory. */ protected static Main m_MainCommandline; /** singleton instance of the GUI. */ protected static Main m_MainSingleton; /** * list of things to be notified when the startup process of the KnowledgeFlow * is complete. */ protected static Vector<StartUpListener> m_StartupListeners = new Vector<StartUpListener>(); /** for monitoring the Memory consumption. */ protected static Memory m_Memory = new Memory(true); /** contains the child frames (title &lt;-&gt; object). */ protected HashSet<Container> m_ChildFrames = new HashSet<Container>(); /** The frame of the LogWindow. */ protected static LogWindow m_LogWindow = new LogWindow(); /** filechooser for the TreeVisualizer. */ protected JFileChooser m_FileChooserTreeVisualizer = new JFileChooser( new File(System.getProperty("user.dir"))); /** filechooser for the GraphVisualizer. */ protected JFileChooser m_FileChooserGraphVisualizer = new JFileChooser( new File(System.getProperty("user.dir"))); /** filechooser for Plots. */ protected JFileChooser m_FileChooserPlot = new JFileChooser(new File( System.getProperty("user.dir"))); /** filechooser for ROC curves. */ protected JFileChooser m_FileChooserROC = new JFileChooser(new File( System.getProperty("user.dir"))); // GUI components private JMenu jMenuHelp; private JMenu jMenuVisualization; private JMenu jMenuTools; private JDesktopPane jDesktopPane; private JMenu jMenuApplications; private JMenuItem jMenuItemHelpSystemInfo; private JMenuItem jMenuItemHelpAbout; private JMenuItem jMenuItemHelpHomepage; private JMenuItem jMenuItemHelpWekaWiki; private JMenuItem jMenuItemHelpSourceforge; private JMenuItem jMenuItemVisualizationBoundaryVisualizer; private JMenuItem jMenuItemVisualizationGraphVisualizer; private JMenuItem jMenuItemVisualizationTreeVisualizer; private JMenuItem jMenuItemVisualizationROC; private JMenuItem jMenuItemVisualizationPlot; private JMenuItem jMenuItemToolsSqlViewer; private JMenuItem jMenuItemToolsGroovyConsole; private JMenuItem jMenuItemToolsJythonConsole; private JMenuItem jMenuItemToolsArffViewer; private JMenuItem jMenuItemApplicationsSimpleCLI; private JMenuItem jMenuItemApplicationsKnowledgeFlow; private JMenuItem jMenuItemApplicationsExperimenter; private JMenuItem jMenuItemApplicationsExplorer; private JMenuItem jMenuItemProgramExit; private JMenuItem jMenuItemProgramLogWindow; private JMenuItem jMenuItemProgramMemoryUsage; private JMenu jMenuProgram; private JMenu jMenuExtensions; private JMenu jMenuWindows; private JMenuBar jMenuBar; /** * default constructor. */ public Main() { super(); } /** * creates a frame (depending on m_GUIType) and returns it. * * @param parent the parent of the generated frame * @param title the title of the frame * @param c the component to place, can be null * @param layout the layout to use, e.g., BorderLayout * @param layoutConstraints the layout constraints, e.g., BorderLayout.CENTER * @param width the width of the frame, ignored if -1 * @param height the height of the frame, ignored if -1 * @param menu an optional menu * @param listener if true a default listener is added * @param visible if true then the frame is made visible immediately * @return the generated frame * @see #m_GUIType */ protected Container createFrame(Main parent, String title, Component c, LayoutManager layout, Object layoutConstraints, int width, int height, JMenuBar menu, boolean listener, boolean visible) { Container result = null; if (m_GUIType == GUI_MDI) { final ChildFrameMDI frame = new ChildFrameMDI(parent, title); // layout frame.setLayout(layout); if (c != null) { frame.getContentPane().add(c, layoutConstraints); } // menu frame.setJMenuBar(menu); // size frame.pack(); if ((width > -1) && (height > -1)) { frame.setSize(width, height); } frame.validate(); // listener? if (listener) { frame.addInternalFrameListener(new InternalFrameAdapter() { @Override public void internalFrameClosing(InternalFrameEvent e) { frame.dispose(); } }); } // display frame if (visible) { frame.setVisible(true); try { frame.setSelected(true); } catch (Exception e) { e.printStackTrace(); } } result = frame; } else if (m_GUIType == GUI_SDI) { final ChildFrameSDI frame = new ChildFrameSDI(parent, title); // layout frame.setLayout(layout); if (c != null) { frame.getContentPane().add(c, layoutConstraints); } // menu frame.setJMenuBar(menu); // size frame.pack(); if ((width > -1) && (height > -1)) { frame.setSize(width, height); } frame.validate(); // location int screenHeight = getGraphicsConfiguration().getBounds().height; int screenWidth = getGraphicsConfiguration().getBounds().width; frame.setLocation((screenWidth - frame.getBounds().width) / 2, (screenHeight - frame.getBounds().height) / 2); // listener? if (listener) { frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { frame.dispose(); } }); } // display frame if (visible) { frame.setVisible(true); } result = frame; } return result; } /** * insert the menu item in a sorted fashion. * * @param menu the menu to add the item to * @param menuitem the menu item to add */ protected void insertMenuItem(JMenu menu, JMenuItem menuitem) { insertMenuItem(menu, menuitem, 0); } /** * insert the menu item in a sorted fashion. * * @param menu the menu to add the item to * @param menuitem the menu item to add * @param startIndex the index in the menu to start with (0-based) */ protected void insertMenuItem(JMenu menu, JMenuItem menuitem, int startIndex) { boolean inserted; int i; JMenuItem current; String currentStr; String newStr; inserted = false; newStr = menuitem.getText().toLowerCase(); // try to find a spot inbetween for (i = startIndex; i < menu.getMenuComponentCount(); i++) { if (!(menu.getMenuComponent(i) instanceof JMenuItem)) { continue; } current = (JMenuItem) menu.getMenuComponent(i); currentStr = current.getText().toLowerCase(); if (currentStr.compareTo(newStr) > 0) { inserted = true; menu.insert(menuitem, i); break; } } // add it at the end if not yet inserted if (!inserted) { menu.add(menuitem); } } /** * initializes the GUI. */ protected void initGUI() { m_Self = this; try { // main window createTitle(""); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); this.setIconImage(new ImageIcon(getClass().getClassLoader().getResource( "weka/gui/weka_icon_new_48.png")).getImage()); // bits and pieces m_FileChooserGraphVisualizer .addChoosableFileFilter(new ExtensionFileFilter(".bif", "BIF Files (*.bif)")); m_FileChooserGraphVisualizer .addChoosableFileFilter(new ExtensionFileFilter(".xml", "XML Files (*.xml)")); m_FileChooserPlot.addChoosableFileFilter(new ExtensionFileFilter( Instances.FILE_EXTENSION, "ARFF Files (*" + Instances.FILE_EXTENSION + ")")); m_FileChooserPlot.setMultiSelectionEnabled(true); m_FileChooserROC.addChoosableFileFilter(new ExtensionFileFilter( Instances.FILE_EXTENSION, "ARFF Files (*" + Instances.FILE_EXTENSION + ")")); // Desktop if (m_GUIType == GUI_MDI) { jDesktopPane = new BackgroundDesktopPane( "weka/gui/images/weka_background.gif"); jDesktopPane.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE); setContentPane(jDesktopPane); } else { jDesktopPane = null; } // Menu jMenuBar = new JMenuBar(); setJMenuBar(jMenuBar); // Program jMenuProgram = new JMenu(); jMenuBar.add(jMenuProgram); jMenuProgram.setText("Program"); jMenuProgram.setMnemonic('P'); // Program/Preferences // TODO: read all properties from all props file and display them /* * jMenuItemProgramPreferences = new JMenuItem(); * jMenuProgram.add(jMenuItemProgramPreferences); * jMenuItemProgramPreferences.setText("Preferences"); * jMenuItemProgramPreferences.setMnemonic('P'); * jMenuItemProgramPreferences.addActionListener(new ActionListener() { * public void actionPerformed(ActionEvent evt) { * System.out.println("jMenuItemProgramPreferences.actionPerformed, event=" * +evt); //TODO add your code for * jMenuItemProgramPreferences.actionPerformed } }); */ // Program/LogWindow jMenuItemProgramLogWindow = new JMenuItem(); jMenuProgram.add(jMenuItemProgramLogWindow); jMenuItemProgramLogWindow.setText("LogWindow"); jMenuItemProgramLogWindow.setMnemonic('L'); jMenuItemProgramLogWindow.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { m_LogWindow.setVisible(true); } }); jMenuItemProgramMemoryUsage = new JMenuItem(); jMenuProgram.add(jMenuItemProgramMemoryUsage); jMenuItemProgramMemoryUsage.setText("Memory usage"); jMenuItemProgramMemoryUsage.setMnemonic('M'); jMenuItemProgramMemoryUsage.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { String title = jMenuItemProgramMemoryUsage.getText(); if (!containsWindow(title)) { final MemoryUsagePanel panel = new MemoryUsagePanel(); Container c = createFrame(m_Self, title, panel, new BorderLayout(), BorderLayout.CENTER, 400, 50, null, true, true); // optimize size Dimension size = c.getPreferredSize(); c.setSize(new Dimension((int) size.getWidth(), (int) size .getHeight())); // stop threads if (m_GUIType == GUI_MDI) { final ChildFrameMDI frame = (ChildFrameMDI) c; Point l = panel.getFrameLocation(); if ((l.x != -1) && (l.y != -1)) { frame.setLocation(l); } frame.addInternalFrameListener(new InternalFrameAdapter() { @Override public void internalFrameClosing(InternalFrameEvent e) { panel.stopMonitoring(); } }); } else { final ChildFrameSDI frame = (ChildFrameSDI) c; Point l = panel.getFrameLocation(); if ((l.x != -1) && (l.y != -1)) { frame.setLocation(l); } frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { panel.stopMonitoring(); } }); } } else { showWindow(getWindow(title)); } } }); jMenuProgram.add(new JSeparator()); // Program/Exit jMenuItemProgramExit = new JMenuItem(); jMenuProgram.add(jMenuItemProgramExit); jMenuItemProgramExit.setText("Exit"); jMenuItemProgramExit.setMnemonic('E'); jMenuItemProgramExit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { // close all children Iterator<Container> iter = getWindowList(); Vector<Container> list = new Vector<Container>(); while (iter.hasNext()) { list.add(iter.next()); } for (int i = 0; i < list.size(); i++) { Container c = list.get(i); if (c instanceof ChildFrameMDI) { ((ChildFrameMDI) c).dispose(); } else if (c instanceof ChildFrameSDI) { ((ChildFrameSDI) c).dispose(); } } // close logwindow m_LogWindow.dispose(); // close main window m_Self.dispose(); // make sure we stop System.exit(0); } }); // Applications jMenuApplications = new JMenu(); jMenuBar.add(jMenuApplications); jMenuApplications.setText("Applications"); jMenuApplications.setMnemonic('A'); // Applications/Explorer jMenuItemApplicationsExplorer = new JMenuItem(); jMenuApplications.add(jMenuItemApplicationsExplorer); jMenuItemApplicationsExplorer.setText("Explorer"); jMenuItemApplicationsExplorer.setMnemonic('E'); jMenuItemApplicationsExplorer.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { String title = jMenuItemApplicationsExplorer.getText(); if (!containsWindow(title)) { createFrame(m_Self, title, new Explorer(), new BorderLayout(), BorderLayout.CENTER, 800, 600, null, true, true); } else { showWindow(getWindow(title)); } } }); // Applications/Experimenter jMenuItemApplicationsExperimenter = new JMenuItem(); jMenuApplications.add(jMenuItemApplicationsExperimenter); jMenuItemApplicationsExperimenter.setText("Experimenter"); jMenuItemApplicationsExperimenter.setMnemonic('X'); jMenuItemApplicationsExperimenter.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { String title = jMenuItemApplicationsExperimenter.getText(); if (!containsWindow(title)) { createFrame(m_Self, title, new Experimenter(false), new BorderLayout(), BorderLayout.CENTER, 800, 600, null, true, true); } else { showWindow(getWindow(title)); } } }); // Applications/KnowledgeFlow jMenuItemApplicationsKnowledgeFlow = new JMenuItem(); jMenuApplications.add(jMenuItemApplicationsKnowledgeFlow); jMenuItemApplicationsKnowledgeFlow.setText("KnowledgeFlow"); jMenuItemApplicationsKnowledgeFlow.setMnemonic('K'); jMenuItemApplicationsKnowledgeFlow .addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { String title = jMenuItemApplicationsKnowledgeFlow.getText(); if (!containsWindow(title)) { KnowledgeFlowApp.createSingleton(new String[0]); createFrame(m_Self, title, KnowledgeFlowApp.getSingleton(), new BorderLayout(), BorderLayout.CENTER, 900, 600, null, true, true); } else { showWindow(getWindow(title)); } } }); // Applications/SimpleCLI jMenuItemApplicationsSimpleCLI = new JMenuItem(); jMenuApplications.add(jMenuItemApplicationsSimpleCLI); jMenuItemApplicationsSimpleCLI.setText("SimpleCLI"); jMenuItemApplicationsSimpleCLI.setMnemonic('S'); jMenuItemApplicationsSimpleCLI.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { String title = jMenuItemApplicationsSimpleCLI.getText(); if (!containsWindow(title)) { try { createFrame(m_Self, title, new SimpleCLIPanel(), new BorderLayout(), BorderLayout.CENTER, 600, 500, null, true, true); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(m_Self, "Error instantiating SimpleCLI:\n" + e.getMessage()); return; } } else { showWindow(getWindow(title)); } } }); // Tools jMenuTools = new JMenu(); jMenuBar.add(jMenuTools); jMenuTools.setText("Tools"); jMenuTools.setMnemonic('T'); // Tools/ArffViewer jMenuItemToolsArffViewer = new JMenuItem(); jMenuTools.add(jMenuItemToolsArffViewer); jMenuItemToolsArffViewer.setText("ArffViewer"); jMenuItemToolsArffViewer.setMnemonic('A'); jMenuItemToolsArffViewer.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { String title = jMenuItemToolsArffViewer.getText(); if (!containsWindow(title)) { ArffViewerMainPanel panel = new ArffViewerMainPanel(null); panel.setConfirmExit(false); Container frame = createFrame(m_Self, title, panel, new BorderLayout(), BorderLayout.CENTER, 800, 600, panel.getMenu(), true, true); panel.setParent(frame); } else { showWindow(getWindow(title)); } } }); // Tools/SqlViewer jMenuItemToolsSqlViewer = new JMenuItem(); jMenuTools.add(jMenuItemToolsSqlViewer); jMenuItemToolsSqlViewer.setText("SqlViewer"); jMenuItemToolsSqlViewer.setMnemonic('S'); jMenuItemToolsSqlViewer.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { String title = jMenuItemToolsSqlViewer.getText(); if (!containsWindow(title)) { final SqlViewer sql = new SqlViewer(null); final Container frame = createFrame(m_Self, title, sql, new BorderLayout(), BorderLayout.CENTER, -1, -1, null, false, true); // custom listener if (frame instanceof ChildFrameMDI) { ((ChildFrameMDI) frame) .addInternalFrameListener(new InternalFrameAdapter() { @Override public void internalFrameClosing(InternalFrameEvent e) { sql.saveSize(); ((ChildFrameMDI) frame).dispose(); } }); } else if (frame instanceof ChildFrameSDI) { ((ChildFrameSDI) frame).addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { sql.saveSize(); ((ChildFrameSDI) frame).dispose(); } }); } } else { showWindow(getWindow(title)); } } }); // Tools/Bayes net editor // Tools/Bayes net editor final JMenuItem jMenuItemBayesNet = new JMenuItem(); jMenuTools.add(jMenuItemBayesNet); jMenuItemBayesNet.setText("Bayes net editor"); jMenuItemBayesNet.setMnemonic('N'); jMenuItemBayesNet.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String title = jMenuItemBayesNet.getText(); if (!containsWindow(title)) { final GUI bayesNetGUI = new GUI(); createFrame(m_Self, title, bayesNetGUI, new BorderLayout(), BorderLayout.CENTER, 800, 600, bayesNetGUI.getMenuBar(), false, true); } else { showWindow(getWindow(title)); } } }); // Tools/Groovy console if (Groovy.isPresent()) { jMenuItemToolsGroovyConsole = new JMenuItem(); jMenuTools.add(jMenuItemToolsGroovyConsole); jMenuItemToolsGroovyConsole.setText("Groovy console"); jMenuItemToolsGroovyConsole.setMnemonic('G'); jMenuItemToolsGroovyConsole.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { String title = jMenuItemToolsGroovyConsole.getText(); if (!containsWindow(title)) { final GroovyPanel panel = new GroovyPanel(); final Container frame = createFrame(m_Self, title, panel, new BorderLayout(), BorderLayout.CENTER, 800, 600, panel.getMenuBar(), false, true); // custom listener if (frame instanceof ChildFrameMDI) { ((ChildFrameMDI) frame) .addInternalFrameListener(new InternalFrameAdapter() { @Override public void internalFrameClosing(InternalFrameEvent e) { ((ChildFrameMDI) frame).dispose(); } }); } else if (frame instanceof ChildFrameSDI) { ((ChildFrameSDI) frame).addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { ((ChildFrameSDI) frame).dispose(); } }); } } else { showWindow(getWindow(title)); } } }); } // Tools/Jython console if (Jython.isPresent()) { jMenuItemToolsJythonConsole = new JMenuItem(); jMenuTools.add(jMenuItemToolsJythonConsole); jMenuItemToolsJythonConsole.setText("Jython console"); jMenuItemToolsJythonConsole.setMnemonic('J'); jMenuItemToolsJythonConsole.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { String title = jMenuItemToolsJythonConsole.getText(); if (!containsWindow(title)) { final JythonPanel panel = new JythonPanel(); final Container frame = createFrame(m_Self, title, panel, new BorderLayout(), BorderLayout.CENTER, 800, 600, panel.getMenuBar(), false, true); // custom listener if (frame instanceof ChildFrameMDI) { ((ChildFrameMDI) frame) .addInternalFrameListener(new InternalFrameAdapter() { @Override public void internalFrameClosing(InternalFrameEvent e) { ((ChildFrameMDI) frame).dispose(); } }); } else if (frame instanceof ChildFrameSDI) { ((ChildFrameSDI) frame).addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { ((ChildFrameSDI) frame).dispose(); } }); } } else { showWindow(getWindow(title)); } } }); } // Tools/EnsembleLibrary /* * currently disabled due to bugs... FracPete * jMenuItemToolsEnsembleLibrary = new JMenuItem(); * jMenuTools.add(jMenuItemToolsEnsembleLibrary); * jMenuItemToolsEnsembleLibrary.setText("EnsembleLibrary"); * jMenuItemToolsEnsembleLibrary.setMnemonic('E'); * jMenuItemToolsEnsembleLibrary.addActionListener(new ActionListener() { * public void actionPerformed(ActionEvent evt) { String title = * jMenuItemToolsEnsembleLibrary.getText(); if (!containsWindow(title)) { * EnsembleLibrary value = new EnsembleLibrary(); EnsembleLibraryEditor * libraryEditor = new EnsembleLibraryEditor(); * libraryEditor.setValue(value); createFrame( m_Self, title, * libraryEditor.getCustomEditor(), new BorderLayout(), * BorderLayout.CENTER, 800, 600, null, true, true); } else { * showWindow(getWindow(title)); } } }); */ // Visualization jMenuVisualization = new JMenu(); jMenuBar.add(jMenuVisualization); jMenuVisualization.setText("Visualization"); jMenuVisualization.setMnemonic('V'); // Visualization/Plot jMenuItemVisualizationPlot = new JMenuItem(); jMenuVisualization.add(jMenuItemVisualizationPlot); jMenuItemVisualizationPlot.setText("Plot"); jMenuItemVisualizationPlot.setMnemonic('P'); jMenuItemVisualizationPlot.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { // choose file int retVal = m_FileChooserPlot.showOpenDialog(m_Self); if (retVal != JFileChooser.APPROVE_OPTION) { return; } // build plot VisualizePanel panel = new VisualizePanel(); String filenames = ""; File[] files = m_FileChooserPlot.getSelectedFiles(); for (int j = 0; j < files.length; j++) { String filename = files[j].getAbsolutePath(); if (j > 0) { filenames += ", "; } filenames += filename; System.err.println("Loading instances from " + filename); try { Reader r = new java.io.BufferedReader(new FileReader(filename)); Instances i = new Instances(r); i.setClassIndex(i.numAttributes() - 1); PlotData2D pd1 = new PlotData2D(i); if (j == 0) { pd1.setPlotName("Master plot"); panel.setMasterPlot(pd1); } else { pd1.setPlotName("Plot " + (j + 1)); pd1.m_useCustomColour = true; pd1.m_customColour = (j % 2 == 0) ? Color.red : Color.blue; panel.addPlot(pd1); } } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(m_Self, "Error loading file '" + files[j] + "':\n" + e.getMessage()); return; } } // create frame createFrame(m_Self, jMenuItemVisualizationPlot.getText() + " - " + filenames, panel, new BorderLayout(), BorderLayout.CENTER, 800, 600, null, true, true); } }); // Visualization/ROC // based on this Wiki article: // http://weka.sourceforge.net/wiki/index.php/Visualizing_ROC_curve jMenuItemVisualizationROC = new JMenuItem(); jMenuVisualization.add(jMenuItemVisualizationROC); jMenuItemVisualizationROC.setText("ROC"); jMenuItemVisualizationROC.setMnemonic('R'); jMenuItemVisualizationROC.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { // choose file int retVal = m_FileChooserROC.showOpenDialog(m_Self); if (retVal != JFileChooser.APPROVE_OPTION) { return; } // create plot String filename = m_FileChooserROC.getSelectedFile() .getAbsolutePath(); Instances result = null; try { result = new Instances(new BufferedReader(new FileReader(filename))); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(m_Self, "Error loading file '" + filename + "':\n" + e.getMessage()); return; } result.setClassIndex(result.numAttributes() - 1); ThresholdVisualizePanel vmc = new ThresholdVisualizePanel(); vmc.setROCString("(Area under ROC = " + Utils.doubleToString(ThresholdCurve.getROCArea(result), 4) + ")"); vmc.setName(result.relationName()); PlotData2D tempd = new PlotData2D(result); tempd.setPlotName(result.relationName()); tempd.addInstanceNumberAttribute(); try { vmc.addPlot(tempd); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(m_Self, "Error adding plot:\n" + e.getMessage()); return; } createFrame(m_Self, jMenuItemVisualizationROC.getText() + " - " + filename, vmc, new BorderLayout(), BorderLayout.CENTER, 800, 600, null, true, true); } }); // Visualization/TreeVisualizer jMenuItemVisualizationTreeVisualizer = new JMenuItem(); jMenuVisualization.add(jMenuItemVisualizationTreeVisualizer); jMenuItemVisualizationTreeVisualizer.setText("TreeVisualizer"); jMenuItemVisualizationTreeVisualizer.setMnemonic('T'); jMenuItemVisualizationTreeVisualizer .addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { // choose file int retVal = m_FileChooserTreeVisualizer.showOpenDialog(m_Self); if (retVal != JFileChooser.APPROVE_OPTION) { return; } // build tree String filename = m_FileChooserTreeVisualizer.getSelectedFile() .getAbsolutePath(); TreeBuild builder = new TreeBuild(); Node top = null; NodePlace arrange = new PlaceNode2(); try { top = builder.create(new FileReader(filename)); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(m_Self, "Error loading file '" + filename + "':\n" + e.getMessage()); return; } // create frame createFrame(m_Self, jMenuItemVisualizationTreeVisualizer.getText() + " - " + filename, new TreeVisualizer(null, top, arrange), new BorderLayout(), BorderLayout.CENTER, 800, 600, null, true, true); } }); // Visualization/GraphVisualizer jMenuItemVisualizationGraphVisualizer = new JMenuItem(); jMenuVisualization.add(jMenuItemVisualizationGraphVisualizer); jMenuItemVisualizationGraphVisualizer.setText("GraphVisualizer"); jMenuItemVisualizationGraphVisualizer.setMnemonic('G'); jMenuItemVisualizationGraphVisualizer .addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { // choose file int retVal = m_FileChooserGraphVisualizer.showOpenDialog(m_Self); if (retVal != JFileChooser.APPROVE_OPTION) { return; } // build graph String filename = m_FileChooserGraphVisualizer.getSelectedFile() .getAbsolutePath(); GraphVisualizer panel = new GraphVisualizer(); try { if (filename.toLowerCase().endsWith(".xml") || filename.toLowerCase().endsWith(".bif")) { panel.readBIF(new FileInputStream(filename)); } else { panel.readDOT(new FileReader(filename)); } } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(m_Self, "Error loading file '" + filename + "':\n" + e.getMessage()); return; } // create frame createFrame(m_Self, jMenuItemVisualizationGraphVisualizer.getText() + " - " + filename, panel, new BorderLayout(), BorderLayout.CENTER, 800, 600, null, true, true); } }); // Visualization/BoundaryVisualizer jMenuItemVisualizationBoundaryVisualizer = new JMenuItem(); jMenuVisualization.add(jMenuItemVisualizationBoundaryVisualizer); jMenuItemVisualizationBoundaryVisualizer.setText("BoundaryVisualizer"); jMenuItemVisualizationBoundaryVisualizer.setMnemonic('B'); jMenuItemVisualizationBoundaryVisualizer .addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { String title = jMenuItemVisualizationBoundaryVisualizer.getText(); if (!containsWindow(title)) { createFrame(m_Self, title, new BoundaryVisualizer(), new BorderLayout(), BorderLayout.CENTER, 800, 600, null, true, true); // dont' do a System.exit after last window got closed! BoundaryVisualizer.setExitIfNoWindowsOpen(false); } else { showWindow(getWindow(title)); } } }); // Extensions jMenuExtensions = new JMenu("Extensions"); jMenuExtensions.setMnemonic(java.awt.event.KeyEvent.VK_E); jMenuBar.add(jMenuExtensions); jMenuExtensions.setVisible(false); String extensions = GenericObjectEditor.EDITOR_PROPERTIES.getProperty( MainMenuExtension.class.getName(), ""); if (extensions.length() > 0) { jMenuExtensions.setVisible(true); String[] classnames = GenericObjectEditor.EDITOR_PROPERTIES .getProperty(MainMenuExtension.class.getName(), "").split(","); Hashtable<String, JMenu> submenus = new Hashtable<String, JMenu>(); // add all extensions for (String classname : classnames) { try { MainMenuExtension ext = (MainMenuExtension) Class .forName(classname).newInstance(); // menuitem in a submenu? JMenu submenu = null; if (ext.getSubmenuTitle() != null) { submenu = submenus.get(ext.getSubmenuTitle()); if (submenu == null) { submenu = new JMenu(ext.getSubmenuTitle()); submenus.put(ext.getSubmenuTitle(), submenu); insertMenuItem(jMenuExtensions, submenu); } } // create menu item JMenuItem menuitem = new JMenuItem(); menuitem.setText(ext.getMenuTitle()); // does the extension need a frame or does it have its own // ActionListener? ActionListener listener = ext.getActionListener(m_Self); if (listener != null) { menuitem.addActionListener(listener); } else { final JMenuItem finalMenuitem = menuitem; final MainMenuExtension finalExt = ext; menuitem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Component frame = createFrame(m_Self, finalMenuitem.getText(), null, null, null, -1, -1, null, false, false); finalExt.fillFrame(frame); frame.setVisible(true); } }); } // sorted insert of menu item if (submenu != null) { insertMenuItem(submenu, menuitem); } else { insertMenuItem(jMenuExtensions, menuitem); } } catch (Exception e) { e.printStackTrace(); } } } // Windows jMenuWindows = new JMenu("Windows"); jMenuWindows.setMnemonic(java.awt.event.KeyEvent.VK_W); jMenuBar.add(jMenuWindows); jMenuWindows.setVisible(false); // initially, there are no windows open // Help jMenuHelp = new JMenu(); jMenuBar.add(jMenuHelp); jMenuHelp.setText("Help"); jMenuHelp.setMnemonic('H'); // Help/Homepage jMenuItemHelpHomepage = new JMenuItem(); jMenuHelp.add(jMenuItemHelpHomepage); jMenuItemHelpHomepage.setText("Weka homepage"); jMenuItemHelpHomepage.setMnemonic('H'); jMenuItemHelpHomepage.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { BrowserHelper .openURL(m_Self, "http://www.cs.waikato.ac.nz/~ml/weka/"); } }); jMenuHelp.add(new JSeparator()); /* * // Help/WekaDoc jMenuItemHelpWekaDoc = new JMenuItem(); * jMenuHelp.add(jMenuItemHelpWekaDoc); * jMenuItemHelpWekaDoc.setText("Online documentation"); * jMenuItemHelpWekaDoc.setMnemonic('D'); * jMenuItemHelpWekaDoc.addActionListener(new ActionListener() { public * void actionPerformed(ActionEvent evt) { BrowserHelper.openURL(m_Self, * "http://weka.sourceforge.net/wekadoc/"); } }); */ // Help/WekaWiki jMenuItemHelpWekaWiki = new JMenuItem(); jMenuHelp.add(jMenuItemHelpWekaWiki); jMenuItemHelpWekaWiki.setText("HOWTOs, code snippets, etc."); jMenuItemHelpWekaWiki.setMnemonic('W'); jMenuItemHelpWekaWiki.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { BrowserHelper.openURL(m_Self, "http://weka.wikispaces.com/"); } }); // Help/Sourceforge jMenuItemHelpSourceforge = new JMenuItem(); jMenuHelp.add(jMenuItemHelpSourceforge); jMenuItemHelpSourceforge.setText("Weka on SourceForge"); jMenuItemHelpSourceforge.setMnemonic('F'); jMenuItemHelpSourceforge.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { BrowserHelper .openURL(m_Self, "http://sourceforge.net/projects/weka/"); } }); jMenuHelp.add(new JSeparator()); // Help/SystemInfo jMenuItemHelpSystemInfo = new JMenuItem(); jMenuHelp.add(jMenuItemHelpSystemInfo); jMenuItemHelpSystemInfo.setText("SystemInfo"); jMenuItemHelpHomepage.setMnemonic('S'); jMenuItemHelpSystemInfo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { String title = jMenuItemHelpSystemInfo.getText(); if (!containsWindow(title)) { // get info Hashtable<String, String> info = new SystemInfo().getSystemInfo(); // sort names Vector<String> names = new Vector<String>(); Enumeration<String> enm = info.keys(); while (enm.hasMoreElements()) { names.add(enm.nextElement()); } Collections.sort(names); // generate table String[][] data = new String[info.size()][2]; for (int i = 0; i < names.size(); i++) { data[i][0] = names.get(i).toString(); data[i][1] = info.get(data[i][0]).toString(); } String[] titles = new String[] { "Key", "Value" }; JTable table = new JTable(data, titles); createFrame(m_Self, title, new JScrollPane(table), new BorderLayout(), BorderLayout.CENTER, 800, 600, null, true, true); } else { showWindow(getWindow(title)); } } }); jMenuHelp.add(new JSeparator()); // Help/About jMenuItemHelpAbout = new JMenuItem(); jMenuHelp.add(jMenuItemHelpAbout); jMenuItemHelpAbout.setText("About"); jMenuItemHelpAbout.setMnemonic('A'); jMenuItemHelpAbout.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { String title = jMenuItemHelpAbout.getText(); if (!containsWindow(title)) { JPanel wekaPan = new JPanel(); wekaPan.setToolTipText("Weka, a native bird of New Zealand"); ImageIcon wii = new ImageIcon(Toolkit.getDefaultToolkit().getImage( ClassLoader.getSystemResource("weka/gui/weka3.gif"))); JLabel wekaLab = new JLabel(wii); wekaPan.add(wekaLab); Container frame = createFrame(m_Self, title, wekaPan, new BorderLayout(), BorderLayout.CENTER, -1, -1, null, true, true); JPanel titlePan = new JPanel(); titlePan.setLayout(new GridLayout(8, 1)); titlePan.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5)); titlePan.add(new JLabel("Waikato Environment for", SwingConstants.CENTER)); titlePan .add(new JLabel("Knowledge Analysis", SwingConstants.CENTER)); titlePan.add(new JLabel("")); titlePan.add(new JLabel("Version " + Version.VERSION, SwingConstants.CENTER)); titlePan.add(new JLabel("")); titlePan.add(new JLabel("(c) " + Copyright.getFromYear() + " - " + Copyright.getToYear(), SwingConstants.CENTER)); titlePan.add(new JLabel(Copyright.getOwner(), SwingConstants.CENTER)); titlePan.add(new JLabel(Copyright.getAddress(), SwingConstants.CENTER)); if (frame instanceof ChildFrameMDI) { ((ChildFrameMDI) frame).getContentPane().add(titlePan, BorderLayout.NORTH); ((ChildFrameMDI) frame).pack(); } else if (frame instanceof ChildFrameSDI) { ((ChildFrameSDI) frame).getContentPane().add(titlePan, BorderLayout.NORTH); ((ChildFrameSDI) frame).pack(); } } else { showWindow(getWindow(title)); } } }); // size + position int screenHeight = getGraphicsConfiguration().getBounds().height; int screenWidth = getGraphicsConfiguration().getBounds().width; if (m_GUIType == GUI_MDI) { int newHeight = (int) ((screenHeight) * 0.75); int newWidth = (int) ((screenWidth) * 0.75); setSize(1000 > newWidth ? newWidth : 1000, 800 > newHeight ? newHeight : 800); setLocation((screenWidth - getBounds().width) / 2, (screenHeight - getBounds().height) / 2); } else if (m_GUIType == GUI_SDI) { pack(); setSize(screenWidth, getHeight()); setLocation(0, 0); } } catch (Exception e) { e.printStackTrace(); } } /** * creates and displays the title. * * @param title the additional part of the title */ protected void createTitle(String title) { String newTitle; newTitle = "Weka " + new Version(); if (title.length() != 0) { newTitle += " - " + title; } setTitle(newTitle); } /** * adds the given child frame to the list of frames. * * @param c the child frame to add */ public void addChildFrame(Container c) { m_ChildFrames.add(c); windowListChanged(); } /** * tries to remove the child frame, it returns true if it could do such. * * @param c the child frame to remove * @return true if the child frame could be removed */ public boolean removeChildFrame(Container c) { boolean result = m_ChildFrames.remove(c); windowListChanged(); return result; } /** * brings child frame to the top. * * @param c the frame to activate * @return true if frame was activated */ public boolean showWindow(Container c) { boolean result; ChildFrameMDI mdiFrame; ChildFrameSDI sdiFrame; if (c != null) { try { if (c instanceof ChildFrameMDI) { mdiFrame = (ChildFrameMDI) c; mdiFrame.setIcon(false); mdiFrame.toFront(); createTitle(mdiFrame.getTitle()); } else if (c instanceof ChildFrameSDI) { sdiFrame = (ChildFrameSDI) c; sdiFrame.setExtendedState(JFrame.NORMAL); sdiFrame.toFront(); createTitle(sdiFrame.getTitle()); } } catch (Exception e) { e.printStackTrace(); } result = true; } else { result = false; } return result; } /** * brings the first frame to the top that is of the specified window class. * * @param windowClass the class to display the first child for * @return true, if a child was found and brought to front */ public boolean showWindow(Class<?> windowClass) { return showWindow(getWindow(windowClass)); } /** * returns all currently open frames. * * @return an iterator over all currently open frame */ public Iterator<Container> getWindowList() { return m_ChildFrames.iterator(); } /** * returns the first instance of the given window class, null if none can be * found. * * @param windowClass the class to retrieve the first instance for * @return null, if no instance can be found */ public Container getWindow(Class<?> windowClass) { Container result; Iterator<Container> iter; Container current; result = null; iter = getWindowList(); while (iter.hasNext()) { current = iter.next(); if (current.getClass() == windowClass) { result = current; break; } } return result; } /** * returns the first window with the given title, null if none can be found. * * @param title the title to look for * @return null, if no instance can be found */ public Container getWindow(String title) { Container result; Iterator<Container> iter; Container current; boolean found; result = null; iter = getWindowList(); while (iter.hasNext()) { current = iter.next(); found = false; if (current instanceof ChildFrameMDI) { found = ((ChildFrameMDI) current).getTitle().equals(title); } else if (current instanceof ChildFrameSDI) { found = ((ChildFrameSDI) current).getTitle().equals(title); } if (found) { result = current; break; } } return result; } /** * checks, whether an instance of the given window class is already in the * Window list. * * @param windowClass the class to check for an instance in the current window * list * @return true if the class is already listed in the Window list */ public boolean containsWindow(Class<?> windowClass) { return (getWindow(windowClass) != null); } /** * checks, whether a window with the given title is already in the Window * list. * * @param title the title to check for in the current window list * @return true if a window with the given title is already listed in the * Window list */ public boolean containsWindow(String title) { return (getWindow(title) != null); } /** * minimizes all windows. */ public void minimizeWindows() { Iterator<Container> iter; Container frame; iter = getWindowList(); while (iter.hasNext()) { frame = iter.next(); try { if (frame instanceof ChildFrameMDI) { ((ChildFrameMDI) frame).setIcon(true); } else if (frame instanceof ChildFrameSDI) { ((ChildFrameSDI) frame).setExtendedState(JFrame.ICONIFIED); } } catch (Exception e) { e.printStackTrace(); } } } /** * restores all windows. */ public void restoreWindows() { Iterator<Container> iter; Container frame; iter = getWindowList(); while (iter.hasNext()) { frame = iter.next(); try { if (frame instanceof ChildFrameMDI) { ((ChildFrameMDI) frame).setIcon(false); } else if (frame instanceof ChildFrameSDI) { ((ChildFrameSDI) frame).setExtendedState(JFrame.NORMAL); } } catch (Exception e) { e.printStackTrace(); } } } /** * is called when window list changed somehow (add or remove). */ public void windowListChanged() { createWindowMenu(); } /** * creates the menu of currently open windows. */ protected synchronized void createWindowMenu() { Iterator<Container> iter; JMenuItem menuItem; int startIndex; // remove all existing entries jMenuWindows.removeAll(); // minimize + restore + separator menuItem = new JMenuItem("Minimize"); menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { minimizeWindows(); } }); jMenuWindows.add(menuItem); menuItem = new JMenuItem("Restore"); menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { restoreWindows(); } }); jMenuWindows.add(menuItem); jMenuWindows.addSeparator(); // windows startIndex = jMenuWindows.getMenuComponentCount() - 1; iter = getWindowList(); jMenuWindows.setVisible(iter.hasNext()); while (iter.hasNext()) { Container frame = iter.next(); if (frame instanceof ChildFrameMDI) { menuItem = new JMenuItem(((ChildFrameMDI) frame).getTitle()); } else if (frame instanceof ChildFrameSDI) { menuItem = new JMenuItem(((ChildFrameSDI) frame).getTitle()); } insertMenuItem(jMenuWindows, menuItem, startIndex); menuItem.setActionCommand(Integer.toString(frame.hashCode())); menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { Container frame = null; Iterator<Container> iter = getWindowList(); while (iter.hasNext()) { frame = iter.next(); String hashFrame = Integer.toString(frame.hashCode()); if (hashFrame.equals(evt.getActionCommand())) { showWindow(frame); break; } } showWindow(frame); } }); } } /** * Shows or hides this component depending on the value of parameter b. * * @param b if true, shows this component; otherwise, hides this component */ @Override public void setVisible(boolean b) { super.setVisible(b); if (b) { paint(this.getGraphics()); } } /** * Create the singleton instance of the Main GUI. * * @param args commandline options */ public static void createSingleton(String[] args) { if (m_MainSingleton == null) { m_MainSingleton = new Main(); } // set options try { m_MainSingleton.setOptions(args); } catch (Exception e) { e.printStackTrace(); } // notify listeners (if any) for (int i = 0; i < m_StartupListeners.size(); i++) { m_StartupListeners.elementAt(i).startUpComplete(); } } /** * Return the singleton instance of the Main GUI. * * @return the singleton instance */ public static Main getSingleton() { return m_MainSingleton; } /** * Add a listener to be notified when startup is complete. * * @param s a listener to add */ public static void addStartupListener(StartUpListener s) { m_StartupListeners.add(s); } /** * Gets an enumeration describing the available options. * * @return an enumeration of all the available options. */ @Override public Enumeration<Option> listOptions() { Vector<Option> result; String desc; SelectedTag tag; int i; result = new Vector<Option>(); desc = ""; for (i = 0; i < TAGS_GUI.length; i++) { tag = new SelectedTag(TAGS_GUI[i].getID(), TAGS_GUI); desc += "\t" + tag.getSelectedTag().getIDStr() + " = " + tag.getSelectedTag().getReadable() + "\n"; } result.addElement(new Option("\tDetermines the layout of the GUI:\n" + desc + "\t(default: " + new SelectedTag(GUI_MDI, TAGS_GUI) + ")", "gui", 1, "-gui " + Tag.toOptionList(TAGS_GUI))); return result.elements(); } /** * returns the options of the current setup. * * @return the current options */ @Override public String[] getOptions() { Vector<String> result; result = new Vector<String>(); result.add("-gui"); result.add("" + getGUIType()); return result.toArray(new String[result.size()]); } /** * Parses the options for this object. * <p/> * * <!-- options-start --> Valid options are: * <p/> * * <pre> * -gui &lt;MDI|SDI&gt; * Determines the layout of the GUI: * MDI = MDI Layout * SDI = SDI Layout * (default: MDI) * </pre> * * <!-- options-end --> * * @param options the options to use * @throws Exception if setting of options fails */ @Override public void setOptions(String[] options) throws Exception { String tmpStr; tmpStr = Utils.getOption("gui", options); if (tmpStr.length() != 0) { setGUIType(new SelectedTag(tmpStr, TAGS_GUI)); } else { setGUIType(new SelectedTag(GUI_MDI, TAGS_GUI)); } } /** * Sets the type of GUI to use. * * @param value .the GUI type */ public void setGUIType(SelectedTag value) { if (value.getTags() == TAGS_GUI) { m_GUIType = value.getSelectedTag().getID(); initGUI(); } } /** * Gets the currently set type of GUI to display. * * @return the current GUI Type. */ public SelectedTag getGUIType() { return new SelectedTag(m_GUIType, TAGS_GUI); } /** * starts the application. * * @param args the commandline arguments - ignored */ public static void main(String[] args) { weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, "Logging started"); LookAndFeel.setLookAndFeel(); try { // uncomment the following line to disable the memory management: // m_Memory.setEnabled(false); // help? if (Utils.getFlag('h', args)) { System.out.println(); System.out.println("Help requested."); System.out.println(); System.out.println("General options:"); System.out.println(); System.out.println("-h"); System.out.println("\tprints this help screen"); System.out.println(); Enumeration<Option> enu = new Main().listOptions(); while (enu.hasMoreElements()) { Option option = enu.nextElement(); System.out.println(option.synopsis()); System.out.println(option.description()); } System.out.println(); System.exit(0); } // setup splash screen Main.addStartupListener(new weka.gui.beans.StartUpListener() { @Override public void startUpComplete() { m_MainCommandline = Main.getSingleton(); m_MainCommandline.setVisible(true); } }); Main.addStartupListener(new StartUpListener() { @Override public void startUpComplete() { SplashWindow.disposeSplash(); } }); SplashWindow.splash(ClassLoader .getSystemResource("weka/gui/images/weka_splash.gif")); // start GUI final String[] options = args.clone(); Thread nt = new Thread() { @Override public void run() { weka.gui.SplashWindow.invokeMethod(Main.class.getName(), "createSingleton", options); } }; nt.start(); Thread memMonitor = new Thread() { @Override public void run() { while (true) { // try { // Thread.sleep(10); if (m_Memory.isOutOfMemory()) { // clean up m_MainCommandline = null; System.gc(); // display error System.err.println("\ndisplayed message:"); m_Memory.showOutOfMemory(); System.err.println("\nexiting"); System.exit(-1); } // } catch (InterruptedException ex) { // ex.printStackTrace(); // } } } }; memMonitor.setPriority(Thread.MAX_PRIORITY); memMonitor.start(); } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/MainMenuExtension.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * MainMenuExtension.java * Copyright (C) 2007-2012 University of Waikato, Hamilton, New Zealand */ package weka.gui; import java.awt.Component; import java.awt.event.ActionListener; import javax.swing.JFrame; /** * Classes implementing this interface will be displayed in the "Extensions" * menu in the main GUI of Weka. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public interface MainMenuExtension { /** * Returns the name of the submenu. If there is no submenu necessary then * the return value is null. * * @return the title of the submenu or null if no submenu */ public String getSubmenuTitle(); /** * Returns the name of the menu item. * * @return the name of the menu item. */ public String getMenuTitle(); /** * If the extension has a custom ActionListener for the menu item, then it * must be returned here. Having a custom <code>ActionListener</code> also * means that the component handles any frame by itself. * * @param owner the owner of potential dialogs * @return a custom ActionListener, can be null * @see #fillFrame(Component) */ public ActionListener getActionListener(JFrame owner); /** * Fills the frame with life, like adding components, window listeners, * setting size, location, etc. The frame object can be either derived from * <code>JFrame</code> or from <code>JInternalFrame</code>. This method is * only called in case <code>getActionListener()</code> returns null. * * @param frame the frame object to embed components, etc. * @see #getActionListener(JFrame) * @see javax.swing.JFrame * @see javax.swing.JInternalFrame */ public void fillFrame(Component frame); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/MemoryUsagePanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * MemoryUsagePanel.java * Copyright (C) 2008-2012 University of Waikato, Hamilton, New Zealand */ package weka.gui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Collections; import java.util.Enumeration; import java.util.Hashtable; import java.util.Properties; import java.util.Vector; import javax.swing.JButton; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.SwingUtilities; import weka.core.Memory; import weka.core.Utils; import weka.gui.visualize.VisualizeUtils; /** * A panel for displaying the memory usage. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class MemoryUsagePanel extends JPanel { /** for serialization. */ private static final long serialVersionUID = -4812319791687471721L; /** * Specialized thread for monitoring the memory usage. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ protected class MemoryMonitor extends Thread { /** the refresh interval in msecs. */ protected int m_Interval; /** whether the thread is still running. */ protected boolean m_Monitoring; /** * default constructor. */ public MemoryMonitor() { super(); setInterval(1000); // TODO: via props file } /** * Returns the refresh interval in msecs. * * @return returns the refresh interval */ public int getInterval() { return m_Interval; } /** * Sets the refresh interval in msecs. * * @param value the refresh interval */ public void setInterval(int value) { m_Interval = value; } /** * Returns whether the thread is still running. * * @return true if the thread is still running */ public boolean isMonitoring() { return m_Monitoring; } /** * stops the monitoring thread. */ public void stopMonitoring() { m_Monitoring = false; } /** * The run method. */ @Override public void run() { m_Monitoring = true; while (m_Monitoring) { try { Thread.sleep(m_Interval); // update GUI if (m_Monitoring) { Runnable doUpdate = new Runnable() { @Override public void run() { update(); } }; SwingUtilities.invokeLater(doUpdate); } } catch (InterruptedException ex) { ex.printStackTrace(); } } } /** * Updates the GUI. */ protected void update() { double perc; Dimension size; // current usage perc = (double) m_Memory.getCurrent() / (double) m_Memory.getMax(); perc = Math.round(perc * 1000) / 10; // tool tip setToolTipText("" + perc + "% used"); // update history m_History.insertElementAt(perc, 0); size = getSize(); while (m_History.size() > size.getWidth()) { m_History.remove(m_History.size() - 1); } // display history repaint(); } } /** The name of the properties file. */ protected static String PROPERTY_FILE = "weka/gui/MemoryUsage.props"; /** Contains the properties. */ protected static Properties PROPERTIES; /** the memory usage over time. */ protected Vector<Double> m_History; /** for monitoring the memory usage. */ protected Memory m_Memory; /** the thread for monitoring the memory usage. */ protected MemoryMonitor m_Monitor; /** the button for running the garbage collector. */ protected JButton m_ButtonGC; /** the threshold percentages to change color. */ protected Vector<Double> m_Percentages; /** the corresponding colors for the thresholds. */ protected Hashtable<Double, Color> m_Colors; /** the default color. */ protected Color m_DefaultColor; /** the background color. */ protected Color m_BackgroundColor; /** the position for the dialog. */ protected Point m_FrameLocation; /** * Loads the configuration property file (USE_DYNAMIC is FALSE) or determines * the classes dynamically (USE_DYNAMIC is TRUE) * * @see #USE_DYNAMIC * @see GenericPropertiesCreator */ static { // Allow a properties file in the current directory to override try { PROPERTIES = Utils.readProperties(PROPERTY_FILE); Enumeration<?> keys = PROPERTIES.propertyNames(); if (!keys.hasMoreElements()) { throw new Exception("Failed to read a property file for the " + "memory usage panel"); } } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Could not read a configuration file for the memory usage\n" + "panel. An example file is included with the Weka distribution.\n" + "This file should be named \"" + PROPERTY_FILE + "\" and\n" + "should be placed either in your user home (which is set\n" + "to \"" + System.getProperties().getProperty("user.home") + "\")\n" + "or the directory that java was started from\n", "MemoryUsagePanel", JOptionPane.ERROR_MESSAGE); } } /** * default constructor. */ public MemoryUsagePanel() { super(); // initializes members m_Memory = new Memory(); m_History = new Vector<Double>(); m_Percentages = new Vector<Double>(); m_Colors = new Hashtable<Double, Color>(); // colors and percentages m_BackgroundColor = parseColor("BackgroundColor", Color.WHITE); m_DefaultColor = parseColor("DefaultColor", Color.GREEN); String[] percs = PROPERTIES.getProperty("Percentages", "70,80,90").split( ","); for (String perc2 : percs) { // do we have a color associated with percentage? if (PROPERTIES.getProperty(perc2) != null) { double perc; Color color; // try parsing the number try { perc = Double.parseDouble(perc2); } catch (Exception e) { System.err.println("MemoryUsagePanel: cannot parse percentage '" + perc2 + "' - ignored!"); continue; } // try parsing the color color = parseColor(perc2, null); if (color == null) { continue; } // store color and percentage m_Percentages.add(perc); m_Colors.put(perc, color); } else { System.err .println("MemoryUsagePanel: cannot find color for percentage '" + perc2 + "' - ignored!"); } } Collections.sort(m_Percentages); // layout setLayout(new BorderLayout()); JPanel panel = new JPanel(new BorderLayout()); add(panel, BorderLayout.EAST); m_ButtonGC = new JButton("GC"); m_ButtonGC.setToolTipText("Runs the garbage collector."); m_ButtonGC.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { System.gc(); } }); panel.add(m_ButtonGC, BorderLayout.NORTH); // dimensions int height; int width; try { height = Integer.parseInt(PROPERTIES.getProperty("Height", "" + (int) m_ButtonGC.getPreferredSize().getHeight())); width = Integer.parseInt(PROPERTIES.getProperty("Width", "400")); } catch (Exception e) { System.err.println("MemoryUsagePanel: Problem parsing the dimensions - " + e); height = (int) m_ButtonGC.getPreferredSize().getHeight(); width = 400; } setPreferredSize(new Dimension(width, height)); // position int top; int left; try { top = Integer.parseInt(PROPERTIES.getProperty("Top", "0")); left = Integer.parseInt(PROPERTIES.getProperty("Left", "0")); } catch (Exception e) { System.err.println("MemoryUsagePanel: Problem parsing the position - " + e); top = 0; left = 0; } m_FrameLocation = new Point(left, top); // monitoring thread int interval; try { interval = Integer.parseInt(PROPERTIES.getProperty("Interval", "1000")); } catch (Exception e) { System.err .println("MemoryUsagePanel: Problem parsing the refresh interval - " + e); interval = 1000; } m_Monitor = new MemoryMonitor(); m_Monitor.setInterval(interval); m_Monitor.setPriority(Thread.MAX_PRIORITY); m_Monitor.start(); } /** * parses the color and returns the corresponding Color object. * * @param prop the color property to read and parse * @param defValue the default color * @return the parsed color or the default color of the */ protected Color parseColor(String prop, Color defValue) { Color result; Color color; String colorStr; result = defValue; try { colorStr = PROPERTIES.getProperty(prop); color = VisualizeUtils.processColour(colorStr, result); if (color == null) { throw new Exception(colorStr); } result = color; } catch (Exception e) { System.err.println("MemoryUsagePanel: cannot parse color '" + e.getMessage() + "' - ignored!"); } return result; } /** * Returns whether the thread is still running. * * @return true if the thread is still running */ public boolean isMonitoring() { return m_Monitor.isMonitoring(); } /** * stops the monitoring thread. */ public void stopMonitoring() { m_Monitor.stopMonitoring(); } /** * Returns the default position for the dialog. * * @return the default position */ public Point getFrameLocation() { return m_FrameLocation; } /** * draws the background image. * * @param g the graphics context */ @Override public void paintComponent(Graphics g) { int i; int n; int len; double scale; double perc; Color color; super.paintComponent(g); g.setColor(m_BackgroundColor); g.fillRect(0, 0, getWidth(), getHeight()); scale = getHeight() / 100.0; for (i = 0; i < m_History.size(); i++) { perc = m_History.get(i); // determine color color = m_DefaultColor; for (n = m_Percentages.size() - 1; n >= 0; n--) { if (perc >= m_Percentages.get(n)) { color = m_Colors.get(m_Percentages.get(n)); break; } } // paint line g.setColor(color); len = (int) Math.round(perc * scale); g.drawLine(i, getHeight() - 1, i, getHeight() - len); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/PackageManager.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * PackageManager.java * Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand */ package weka.gui; import weka.core.Environment; import weka.core.Utils; import weka.core.Version; import weka.core.WekaPackageManager; import weka.core.packageManagement.Dependency; import weka.core.packageManagement.Package; import weka.core.packageManagement.PackageConstraint; import javax.swing.*; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.DefaultTableModel; import javax.swing.table.JTableHeader; import javax.swing.table.TableColumnModel; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.StringWriter; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import static weka.core.WekaPackageManager.DISABLED_KEY; import static weka.core.WekaPackageManager.DISABLE_KEY; /** * A GUI interface the the package management system. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ public class PackageManager extends JPanel { /** For serialization */ private static final long serialVersionUID = -7463821313750352385L; protected static final String PACKAGE_COLUMN = "Package"; protected static final String CATEGORY_COLUMN = "Category"; protected static final String INSTALLED_COLUMN = "Installed version"; protected static final String REPOSITORY_COLUMN = "Repository version"; protected static final String LOADED_COLUMN = "Loaded"; /** The JTable for displaying the package names and version numbers */ protected JTable m_table = new ETable(); protected JSplitPane m_splitP; // protected JTextArea m_packageDescription; /** An editor pane to display package information */ protected JEditorPane m_infoPane; /** Installed radio button */ protected JRadioButton m_installedBut = new JRadioButton("Installed"); /** Available radio button */ protected JRadioButton m_availableBut = new JRadioButton("Available"); /** All radio button */ protected JRadioButton m_allBut = new JRadioButton("All"); /** Button for installing the selected package */ protected JButton m_installBut = new JButton("Install"); protected JCheckBox m_forceBut = new JCheckBox( "Ignore dependencies/conflicts"); /** Button for uninstalling the selected package */ protected JButton m_uninstallBut = new JButton("Uninstall"); /** Button for refreshing the package meta data cache */ protected JButton m_refreshCacheBut = new JButton("Refresh repository cache"); /** Button for toggling the load status of an installed package */ protected JButton m_toggleLoad = new JButton("Toggle load"); protected JProgressBar m_progress = new JProgressBar(0, 100); protected JLabel m_detailLabel = new JLabel(); protected JButton m_backB; protected LinkedList<URL> m_browserHistory = new LinkedList<URL>(); protected static final String BROWSER_HOME = "http://www.cs.waikato.ac.nz/ml/weka/index_home_pm.html"; protected JButton m_homeB; protected JToolBar m_browserTools; protected JLabel m_newPackagesAvailableL; protected DefaultTableModel m_model; protected Map<String, List<Object>> m_packageLookupInfo; protected List<Package> m_allPackages; protected List<Package> m_installedPackages; protected List<Package> m_availablePackages; protected Map<String, String> m_packageDescriptions = new HashMap<String, String>(); protected List<Package> m_searchResults = new ArrayList<Package>(); protected JTextField m_searchField = new JTextField(15); protected JLabel m_searchHitsLab = new JLabel(""); /** The column in the table to sort the entries by */ protected int m_sortColumn = 0; /** Reverse the sort order if the user clicks the same column header twice */ protected boolean m_reverseSort = false; /** Button to pop up the file environment field widget */ protected JButton m_unofficialBut = new JButton("File/URL"); /** Widget for specifying a URL or path to an unofficial package to install */ protected FileEnvironmentField m_unofficialChooser = new FileEnvironmentField("File/URL", Environment.getSystemWide()); protected JFrame m_unofficialFrame = null; public static boolean s_atLeastOnePackageUpgradeHasOccurredInThisSession = false; protected Comparator<Package> m_packageComparator = new Comparator<Package>() { @Override public int compare(Package o1, Package o2) { String meta1 = ""; String meta2 = ""; if (m_sortColumn == 0) { meta1 = o1.getName(); meta2 = o2.getName(); } else { if (o1.getPackageMetaDataElement("Category") != null) { meta1 = o1.getPackageMetaDataElement("Category").toString(); } if (o2.getPackageMetaDataElement("Category") != null) { meta2 = o2.getPackageMetaDataElement("Category").toString(); } } int result = meta1.compareTo(meta2); if (m_reverseSort) { result = -result; } return result; } }; protected boolean m_installing = false; class ProgressPrintStream extends PrintStream { private final Progressable m_listener; public ProgressPrintStream(Progressable listener) { // have to invoke a super class constructor super(System.out); m_listener = listener; } @Override public void println(String string) { boolean messageOnly = false; if (string.startsWith("%%")) { string = string.substring(2); messageOnly = true; } if (!messageOnly) { System.out.println(string); // make sure the log picks it up m_listener.makeProgress(string); } else { m_listener.makeProgressMessageOnly(string); } } @Override public void println(Object obj) { println(obj.toString()); } @Override public void print(String string) { boolean messageOnly = false; if (string.startsWith("%%")) { string = string.substring(2); messageOnly = true; } if (!messageOnly) { System.out.print(string); // make sure the log picks it up m_listener.makeProgress(string); } else { m_listener.makeProgressMessageOnly(string); } } @Override public void print(Object obj) { print(obj.toString()); } } interface Progressable { void makeProgress(String progressMessage); void makeProgressMessageOnly(String progressMessage); } class EstablishCache extends SwingWorker<Void, Void> implements Progressable { private int m_progressCount = 0; private Exception m_error = null; private javax.swing.ProgressMonitor m_progress; @Override public void makeProgress(String progressMessage) { m_progress.setNote(progressMessage); m_progressCount++; m_progress.setProgress(m_progressCount); } @Override public void makeProgressMessageOnly(String progressMessage) { m_progress.setNote(progressMessage); } @Override public Void doInBackground() { int numPackages = WekaPackageManager.numRepositoryPackages(); if (numPackages < 0) { // there was some problem getting the file that holds this // information from the repository server - try to continue // anyway with a max value of 100 for the number of packages // (since all we use this for is setting the upper bound on // the progress bar). numPackages = 100; } m_progress = new javax.swing.ProgressMonitor(PackageManager.this, "Establising cache...", "", 0, numPackages); ProgressPrintStream pps = new ProgressPrintStream(this); m_error = WekaPackageManager.establishCacheIfNeeded(pps); m_cacheEstablished = true; return null; } @Override public void done() { m_progress.close(); if (m_error != null) { displayErrorDialog("There was a problem establishing the package\n" + "meta data cache. We'll try to use the repository" + "directly.", m_error); } } } class CheckForNewPackages extends SwingWorker<Void, Void> { @Override public Void doInBackground() { Map<String, String> localPackageNameList = WekaPackageManager.getPackageList(true); if (localPackageNameList == null) { // quietly return and see if we can continue anyway return null; } Map<String, String> repositoryPackageNameList = WekaPackageManager.getPackageList(false); if (repositoryPackageNameList == null) { // quietly return and see if we can continue anyway return null; } if (repositoryPackageNameList.keySet().size() < localPackageNameList .keySet().size()) { // package(s) have disappeared from the repository. // Force a cache refresh... RefreshCache r = new RefreshCache(true); r.execute(); return null; } StringBuffer newPackagesBuff = new StringBuffer(); StringBuffer updatedPackagesBuff = new StringBuffer(); for (String s : repositoryPackageNameList.keySet()) { if (!localPackageNameList.containsKey(s)) { newPackagesBuff.append(s + "<br>"); } } for (String localPackage : localPackageNameList.keySet()) { String localVersion = localPackageNameList.get(localPackage); String repoVersion = repositoryPackageNameList.get(localPackage); if (repoVersion == null) { continue; } // a difference here indicates a newer version on the server if (!localVersion.equals(repoVersion)) { updatedPackagesBuff.append(localPackage + " (" + repoVersion + ")<br>"); } } if (newPackagesBuff.length() > 0 || updatedPackagesBuff.length() > 0) { String information = "<html><font size=-2>New and/or updated packages: "; if (newPackagesBuff.length() > 0) { information += "<br><br><b>New:</b><br>" + newPackagesBuff.toString(); } if (updatedPackagesBuff.length() > 0) { information += "<br><br><b>Updated:</b><br>" + updatedPackagesBuff.toString() + "<br><br>"; } information += "</font></html>"; m_newPackagesAvailableL.setToolTipText(information); m_browserTools.add(m_newPackagesAvailableL); // force a cache refresh (to match command line package manager client // behaviour) RefreshCache r = new RefreshCache(false); r.execute(); m_browserTools.revalidate(); } return null; } } class RefreshCache extends SwingWorker<Void, Void> implements Progressable { private int m_progressCount = 0; private Exception m_error = null; private boolean m_removeUpdateIcon; public RefreshCache(boolean removeUpdateIcon) { m_removeUpdateIcon = removeUpdateIcon; } @Override public void makeProgress(String progressMessage) { m_detailLabel.setText(progressMessage); if (progressMessage.startsWith("[Default")) { // We're using the new refresh mechanism - extract the number // of KB read from the message String kbs = progressMessage.replace("[DefaultPackageManager] downloaded ", ""); kbs = kbs.replace(" KB\r", ""); m_progressCount = Integer.parseInt(kbs); } else { m_progressCount++; } m_progress.setValue(m_progressCount); } @Override public void makeProgressMessageOnly(String progressMessage) { m_detailLabel.setText(progressMessage); } @Override public Void doInBackground() { m_cacheRefreshInProgress = true; int progressUpper = WekaPackageManager.repoZipArchiveSize(); if (progressUpper == -1) { // revert to legacy approach progressUpper = WekaPackageManager.numRepositoryPackages(); } if (progressUpper < 0) { // there was some problem getting the file that holds this // information from the repository server - try to continue // anyway with a max value of 100 for the number of packages // (since all we use this for is setting the upper bound on // the progress bar). progressUpper = 100; } // number of KBs for the archive is approx 6 x # packages m_progress.setMaximum(progressUpper); m_refreshCacheBut.setEnabled(false); m_installBut.setEnabled(false); m_unofficialBut.setEnabled(false); m_installedBut.setEnabled(false); m_availableBut.setEnabled(false); m_allBut.setEnabled(false); ProgressPrintStream pps = new ProgressPrintStream(this); m_error = WekaPackageManager.refreshCache(pps); getAllPackages(); return null; } @Override public void done() { m_progress.setValue(m_progress.getMinimum()); if (m_error != null) { displayErrorDialog("There was a problem refreshing the package\n" + "meta data cache. We'll try to use the repository" + "directly.", m_error); m_detailLabel.setText(""); } else { m_detailLabel.setText("Cache refresh completed"); } m_installBut.setEnabled(true && !WekaPackageManager.m_offline); m_unofficialBut.setEnabled(true); m_refreshCacheBut.setEnabled(true && !WekaPackageManager.m_offline); m_installedBut.setEnabled(true); m_availableBut.setEnabled(true); m_allBut.setEnabled(true); m_availablePackages = null; updateTable(); try { if (m_removeUpdateIcon) { m_browserTools.remove(m_newPackagesAvailableL); m_browserTools.revalidate(); } } catch (Exception ex) { } m_cacheRefreshInProgress = false; } } private void pleaseCloseAppWindowsPopUp() { if (!Utils .getDontShowDialog("weka.gui.PackageManager.PleaseCloseApplicationWindows")) { JCheckBox dontShow = new JCheckBox("Do not show this message again"); Object[] stuff = new Object[2]; stuff[0] = "Please close any open Weka application windows\n" + "(Explorer, Experimenter, KnowledgeFlow, SimpleCLI)\n" + "before proceeding.\n"; stuff[1] = dontShow; JOptionPane.showMessageDialog(PackageManager.this, stuff, "Weka Package Manager", JOptionPane.OK_OPTION); if (dontShow.isSelected()) { try { Utils .setDontShowDialog("weka.gui.PackageManager.PleaseCloseApplicationWindows"); } catch (Exception ex) { // quietly ignore } } } } private void toggleLoadStatusRequiresRestartPopUp() { if (!Utils .getDontShowDialog("weka.gui.PackageManager.ToggleLoadStatusRequiresRestart")) { JCheckBox dontShow = new JCheckBox("Do not show this message again"); Object[] stuff = new Object[2]; stuff[0] = "Changing a package's load status will require a restart for the change to take affect\n"; stuff[1] = dontShow; JOptionPane.showMessageDialog(PackageManager.this, stuff, "Weka Package Manager", JOptionPane.OK_OPTION); if (dontShow.isSelected()) { try { Utils .setDontShowDialog("weka.gui.PackageManager.ToggleLoadStatusRequiresRestart"); } catch (Exception ex) { // quietly ignore } } } } class UninstallTask extends SwingWorker<Void, Void> implements Progressable { private List<String> m_packageNamesToUninstall; // private String m_packageName; // private boolean m_successfulUninstall = false; private final List<String> m_unsuccessfulUninstalls = new ArrayList<String>(); private int m_progressCount = 0; public void setPackages(List<String> packageNames) { m_packageNamesToUninstall = packageNames; } @Override public void makeProgress(String progressMessage) { m_detailLabel.setText(progressMessage); m_progressCount++; m_progress.setValue(m_progressCount); if (m_progressCount == m_progress.getMaximum()) { m_progress.setMaximum(m_progressCount + 5); } } @Override public void makeProgressMessageOnly(String progressMessage) { m_detailLabel.setText(progressMessage); } @Override public Void doInBackground() { m_installing = true; m_installBut.setEnabled(false); m_unofficialBut.setEnabled(false); m_uninstallBut.setEnabled(false); m_refreshCacheBut.setEnabled(false); m_toggleLoad.setEnabled(false); m_availableBut.setEnabled(false); m_allBut.setEnabled(false); m_installedBut.setEnabled(false); ProgressPrintStream pps = new ProgressPrintStream(this); m_progress.setMaximum(m_packageNamesToUninstall.size() * 5); for (int zz = 0; zz < m_packageNamesToUninstall.size(); zz++) { String packageName = m_packageNamesToUninstall.get(zz); boolean explorerPropertiesExist = WekaPackageManager.installedPackageResourceExists(packageName, "Explorer.props"); if (!m_forceBut.isSelected()) { List<Package> compromised = new ArrayList<Package>(); // Now check to see which other installed packages depend on this one List<Package> installedPackages; try { installedPackages = WekaPackageManager.getInstalledPackages(); } catch (Exception e) { e.printStackTrace(); displayErrorDialog("Can't determine which packages are installed!", e); // return null; // can't proceed m_unsuccessfulUninstalls.add(packageName); continue; } for (Package p : installedPackages) { List<Dependency> tempDeps; try { tempDeps = p.getDependencies(); } catch (Exception e) { e.printStackTrace(); displayErrorDialog( "Problem determining dependencies for package : " + p.getName(), e); // return null; // can't proceed m_unsuccessfulUninstalls.add(packageName); continue; } for (Dependency d : tempDeps) { if (d.getTarget().getPackage().getName().equals(packageName)) { // add this installed package to the list compromised.add(p); break; } } } if (compromised.size() > 0) { StringBuffer message = new StringBuffer(); message.append("The following installed packages depend on " + packageName + " :\n\n"); for (Package p : compromised) { message.append("\t" + p.getName() + "\n"); } message.append("\nDo you wish to proceed?"); int result = JOptionPane.showConfirmDialog(PackageManager.this, message.toString(), "Weka Package Manager", JOptionPane.YES_NO_OPTION); if (result == JOptionPane.NO_OPTION) { // bail out here // return null; continue; } } } // m_progress.setMaximum(10); try { if (explorerPropertiesExist) { // need to remove any set Explorer properties first WekaPackageManager.removeExplorerProps(packageName); } WekaPackageManager.uninstallPackage(packageName, true, pps); } catch (Exception e) { e.printStackTrace(); displayErrorDialog("Unable to uninstall package: " + packageName, e); // return null; m_unsuccessfulUninstalls.add(packageName); continue; } } WekaPackageManager.refreshGOEProperties(); // m_successfulUninstall = true; return null; } @Override public void done() { m_progress.setValue(m_progress.getMinimum()); if (m_unsuccessfulUninstalls.size() == 0) { m_detailLabel.setText("Packages removed successfully."); if (!Utils .getDontShowDialog("weka.gui.PackageManager.RestartAfterUninstall")) { JCheckBox dontShow = new JCheckBox("Do not show this message again"); Object[] stuff = new Object[2]; stuff[0] = "Weka might need to be restarted for\n" + "the changes to come into effect.\n"; stuff[1] = dontShow; JOptionPane.showMessageDialog(PackageManager.this, stuff, "Weka Package Manager", JOptionPane.OK_OPTION); if (dontShow.isSelected()) { try { Utils .setDontShowDialog("weka.gui.PackageManager.RestartAfterUninstall"); } catch (Exception ex) { // quietly ignore } } } } else { StringBuffer failedPackageNames = new StringBuffer(); for (String p : m_unsuccessfulUninstalls) { failedPackageNames.append(p + "\n"); } displayErrorDialog( "The following package(s) could not be uninstalled\n" + "for some reason (check the log)\n" + failedPackageNames.toString(), ""); m_detailLabel.setText("Finished uninstalling."); } m_unofficialBut.setEnabled(true); m_refreshCacheBut.setEnabled(true); m_availableBut.setEnabled(true); m_allBut.setEnabled(true); m_installedBut.setEnabled(true); // force refresh of installed and available packages m_installedPackages = null; m_availablePackages = null; // m_installBut.setEnabled(true); m_installing = false; updateTable(); if (m_table.getSelectedRow() >= 0) { // mainly to update the install/uninstall button status // displayPackageInfo(m_table.getSelectedRow()); updateInstallUninstallButtonEnablement(); } } } class UnofficialInstallTask extends SwingWorker<Void, Void> implements Progressable { private String m_target; private int m_progressCount = 0; private boolean m_errorOccurred = false; public void setTargetToInstall(String target) { m_target = target; } @Override public void makeProgress(String progressMessage) { m_detailLabel.setText(progressMessage); m_progressCount++; m_progress.setValue(m_progressCount); if (m_progressCount == m_progress.getMaximum()) { m_progress.setMaximum(m_progressCount + 5); } } @Override public void makeProgressMessageOnly(String progressMessage) { m_detailLabel.setText(progressMessage); } @Override public Void doInBackground() { m_installing = true; m_installBut.setEnabled(false); m_uninstallBut.setEnabled(false); m_refreshCacheBut.setEnabled(false); m_toggleLoad.setEnabled(false); m_unofficialBut.setEnabled(false); m_availableBut.setEnabled(false); m_allBut.setEnabled(false); m_installedBut.setEnabled(false); ProgressPrintStream pps = new ProgressPrintStream(this); m_progress.setMaximum(30); Package installedPackage = null; String toInstall = m_target; try { toInstall = Environment.getSystemWide().substitute(m_target); } catch (Exception ex) { } try { if (toInstall.toLowerCase().startsWith("http://") || toInstall.toLowerCase().startsWith("https://")) { String packageName = WekaPackageManager.installPackageFromURL(new URL(toInstall), pps); installedPackage = WekaPackageManager.getInstalledPackageInfo(packageName); } else if (toInstall.toLowerCase().endsWith(".zip")) { String packageName = WekaPackageManager.installPackageFromArchive(toInstall, pps); installedPackage = WekaPackageManager.getInstalledPackageInfo(packageName); } else { displayErrorDialog("Unable to install package " + "\nfrom " + toInstall + ". Unrecognized as a URL or zip archive.", (String) null); m_errorOccurred = true; pps.close(); return null; } } catch (Exception ex) { displayErrorDialog("Unable to install package " + "\nfrom " + m_target + ". Check the log for error messages.", ex); m_errorOccurred = true; return null; } if (installedPackage != null) { if (!Utils .getDontShowDialog("weka.gui.PackageManager.RestartAfterUpgrade")) { JCheckBox dontShow = new JCheckBox("Do not show this message again"); Object[] stuff = new Object[2]; stuff[0] = "Weka will need to be restared after installation for\n" + "the changes to come into effect.\n"; stuff[1] = dontShow; JOptionPane.showMessageDialog(PackageManager.this, stuff, "Weka Package Manager", JOptionPane.OK_OPTION); if (dontShow.isSelected()) { try { Utils .setDontShowDialog("weka.gui.PackageManager.RestartAfterUpgrade"); } catch (Exception ex) { // quietly ignore } } } try { File packageRoot = new File(WekaPackageManager.getPackageHome() + File.separator + installedPackage.getName()); boolean loadCheck = // WekaPackageManager.loadCheck(installedPackage, packageRoot, pps); WekaPackageManager.hasBeenLoaded(installedPackage); if (!loadCheck) { displayErrorDialog("Package was installed correctly but could not " + "be loaded. Check log for details", (String) null); } } catch (Exception ex) { displayErrorDialog("Unable to install package " + "\nfrom " + m_target + ".", ex); m_errorOccurred = true; } // since we can't determine whether an unofficial package is installed // already before performing the install/upgrade (due to the fact that // the package name isn't known until the archive is unpacked) we will // not refresh the GOE properties and make the user restart Weka in // order // to be safe and avoid any conflicts between old and new versions of // classes // for this package // WekaPackageManager.refreshGOEProperties(); } return null; } @Override public void done() { m_progress.setValue(m_progress.getMinimum()); if (m_errorOccurred) { m_detailLabel.setText("Problem installing - check log."); } else { m_detailLabel.setText("Package installed successfully."); } m_unofficialBut.setEnabled(true); m_refreshCacheBut.setEnabled(true && !WekaPackageManager.m_offline); m_availableBut.setEnabled(true); m_allBut.setEnabled(true); m_installedBut.setEnabled(true); // force refresh of installed and available packages m_installedPackages = null; m_availablePackages = null; // m_installBut.setEnabled(true); m_installing = false; updateTable(); if (m_table.getSelectedRow() >= 0) { // mainly to update the install/uninstall button status // displayPackageInfo(m_table.getSelectedRow()); updateInstallUninstallButtonEnablement(); } } } class InstallTask extends SwingWorker<Void, Void> implements Progressable { private List<String> m_packageNamesToInstall; private List<Object> m_versionsToInstall; // private boolean m_successfulInstall = false; private final List<Package> m_unsuccessfulInstalls = new ArrayList<Package>(); private int m_progressCount = 0; public void setPackages(List<String> packagesToInstall) { m_packageNamesToInstall = packagesToInstall; } public void setVersions(List<Object> versionsToInstall) { m_versionsToInstall = versionsToInstall; } @Override public void makeProgress(String progressMessage) { m_detailLabel.setText(progressMessage); m_progressCount++; m_progress.setValue(m_progressCount); if (m_progressCount == m_progress.getMaximum()) { m_progress.setMaximum(m_progressCount + 5); } } @Override public void makeProgressMessageOnly(String progressMessage) { m_detailLabel.setText(progressMessage); } /* * Main task. Executed in background thread. */ @Override public Void doInBackground() { m_installing = true; m_installBut.setEnabled(false); m_unofficialBut.setEnabled(true); m_uninstallBut.setEnabled(false); m_refreshCacheBut.setEnabled(false); m_toggleLoad.setEnabled(false); m_availableBut.setEnabled(false); m_allBut.setEnabled(false); m_installedBut.setEnabled(false); ProgressPrintStream pps = new ProgressPrintStream(this); m_progress.setMaximum(m_packageNamesToInstall.size() * 30); for (int zz = 0; zz < m_packageNamesToInstall.size(); zz++) { Package packageToInstall = null; String packageName = m_packageNamesToInstall.get(zz); Object versionToInstall = m_versionsToInstall.get(zz); try { packageToInstall = WekaPackageManager.getRepositoryPackageInfo(packageName, versionToInstall.toString()); } catch (Exception e) { e.printStackTrace(); displayErrorDialog("Unable to obtain package info for package: " + packageName, e); // return null; // bail out here m_unsuccessfulInstalls.add(packageToInstall); continue; } // check for any special installation instructions Object specialInstallMessage = packageToInstall .getPackageMetaDataElement("MessageToDisplayOnInstallation"); if (specialInstallMessage != null && specialInstallMessage.toString().length() > 0) { if (!Utils .getDontShowDialog("weka.gui.PackageManager.ShowSpecialInstallInstructions")) { String siM = specialInstallMessage.toString(); try { siM = Environment.getSystemWide().substitute(siM); } catch (Exception ex) { // quietly ignore } JCheckBox dontShow = new JCheckBox("Do not show this message again"); Object[] stuff = new Object[2]; stuff[0] = packageToInstall + "\n\n" + siM; stuff[1] = dontShow; JOptionPane.showMessageDialog(PackageManager.this, stuff, "Weka Package Manager", JOptionPane.OK_OPTION); if (dontShow.isSelected()) { try { Utils .setDontShowDialog("weka.gui.PackageManager.ShowSpecialInstallInstructions"); } catch (Exception ex) { // quietly ignore } } } } if (!m_forceBut.isSelected()) { // Check to see if it's disabled at the repository Object disabled = packageToInstall.getPackageMetaDataElement(DISABLE_KEY); if (disabled == null) { disabled = packageToInstall.getPackageMetaDataElement(DISABLED_KEY); } if (disabled != null && disabled.toString().equalsIgnoreCase("true")) { JOptionPane.showMessageDialog(PackageManager.this, "Unable to " + "install package\n" + packageName + " because it has been " + "disabled at the repository", "Weka Package Manager", JOptionPane.ERROR_MESSAGE); m_unsuccessfulInstalls.add(packageToInstall); continue; } try { if (!packageToInstall.isCompatibleBaseSystem()) { List<Dependency> baseSysDep = packageToInstall.getBaseSystemDependency(); StringBuffer depList = new StringBuffer(); for (Dependency bd : baseSysDep) { depList.append(bd.getTarget().toString() + " "); } JOptionPane.showMessageDialog(PackageManager.this, "Unable to install package " + "\n" + packageName + " because it requires" + "\n" + depList.toString(), "Weka Package Manager", JOptionPane.ERROR_MESSAGE); // bail out here // return null; m_unsuccessfulInstalls.add(packageToInstall); continue; } // Check for any os/arch constraints ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); if (!WekaPackageManager.osAndArchCheck(packageToInstall, ps)) { String probString = new String(baos.toByteArray()); probString = probString .replace("[WekaPackageManager] Skipping package ", ""); JOptionPane.showMessageDialog(PackageManager.this, "Unable to install package\n" + probString, "Weka Package Manager", JOptionPane.ERROR_MESSAGE); m_unsuccessfulInstalls.add(packageToInstall); continue; } } catch (Exception e) { e.printStackTrace(); displayErrorDialog("Problem determining dependency on base system" + " for package: " + packageName, e); // return null; // can't proceed m_unsuccessfulInstalls.add(packageToInstall); continue; } // check to see if package is already installed if (packageToInstall.isInstalled()) { Package installedVersion = null; try { installedVersion = WekaPackageManager.getInstalledPackageInfo(packageName); } catch (Exception e) { e.printStackTrace(); displayErrorDialog("Problem obtaining package info for package: " + packageName, e); // return null; // can't proceed m_unsuccessfulInstalls.add(packageToInstall); continue; } if (!packageToInstall.equals(installedVersion)) { int result = JOptionPane.showConfirmDialog(PackageManager.this, "Package " + installedVersion + " is already installed. Replace with " + packageToInstall + "?", "Weka Package Manager", JOptionPane.YES_NO_OPTION); if (result == JOptionPane.NO_OPTION) { // bail out here // return null; m_unsuccessfulInstalls.add(packageToInstall); continue; } if (!Utils .getDontShowDialog("weka.gui.PackageManager.RestartAfterUpgrade")) { JCheckBox dontShow = new JCheckBox("Do not show this message again"); Object[] stuff = new Object[2]; stuff[0] = "Weka will need to be restarted after installation for\n" + "the changes to come into effect.\n"; stuff[1] = dontShow; JOptionPane.showMessageDialog(PackageManager.this, stuff, "Weka Package Manager", JOptionPane.OK_OPTION); if (dontShow.isSelected()) { try { Utils .setDontShowDialog("weka.gui.PackageManager.RestartAfterUpgrade"); } catch (Exception ex) { // quietly ignore } } } } else { int result = JOptionPane.showConfirmDialog(PackageManager.this, "Package " + installedVersion + " is already installed. Install again?", "Weka Package Manager", JOptionPane.YES_NO_OPTION); if (result == JOptionPane.NO_OPTION) { // bail out here // return null; m_unsuccessfulInstalls.add(packageToInstall); continue; } } } // Now get a full list of dependencies for this package and // check for any conflicts Map<String, List<Dependency>> conflicts = new HashMap<String, List<Dependency>>(); List<Dependency> dependencies = null; try { dependencies = WekaPackageManager.getAllDependenciesForPackage(packageToInstall, conflicts); } catch (Exception e) { e.printStackTrace(); displayErrorDialog("Problem determining dependencies for package: " + packageToInstall.getName(), e); // return null; // can't proceed m_unsuccessfulInstalls.add(packageToInstall); continue; } if (conflicts.size() > 0) { StringBuffer message = new StringBuffer(); message.append("Package " + packageName + " requires the following packages:\n\n"); Iterator<Dependency> depI = dependencies.iterator(); while (depI.hasNext()) { Dependency d = depI.next(); message.append("\t" + d + "\n"); } message.append("\nThere are conflicting dependencies:\n\n"); Set<String> pNames = conflicts.keySet(); Iterator<String> pNameI = pNames.iterator(); while (pNameI.hasNext()) { String pName = pNameI.next(); message.append("Conflicts for " + pName + "\n"); List<Dependency> confsForPackage = conflicts.get(pName); Iterator<Dependency> confs = confsForPackage.iterator(); while (confs.hasNext()) { Dependency problem = confs.next(); message.append("\t" + problem + "\n"); } } JOptionPane .showConfirmDialog(PackageManager.this, message.toString(), "Weka Package Manager", JOptionPane.OK_OPTION); // bail out here // return null; m_unsuccessfulInstalls.add(packageToInstall); continue; } // Next check all dependencies against what is installed and // inform the user about which installed packages will be altered. // Also // build the list of only those packages that need to be installed or // upgraded (excluding those that are already installed and are OK). List<PackageConstraint> needsUpgrade = new ArrayList<PackageConstraint>(); List<Package> finalListToInstall = new ArrayList<Package>(); Iterator<Dependency> depI = dependencies.iterator(); boolean depsOk = true; while (depI.hasNext()) { Dependency toCheck = depI.next(); if (toCheck.getTarget().getPackage().isInstalled()) { String toCheckName = toCheck.getTarget().getPackage() .getPackageMetaDataElement("PackageName").toString(); try { Package installedVersion = WekaPackageManager.getInstalledPackageInfo(toCheckName); if (!toCheck.getTarget().checkConstraint(installedVersion)) { needsUpgrade.add(toCheck.getTarget()); Package mostRecent = toCheck.getTarget().getPackage(); if (toCheck.getTarget() instanceof weka.core.packageManagement.VersionPackageConstraint) { mostRecent = WekaPackageManager .mostRecentVersionWithRespectToConstraint(toCheck .getTarget()); } finalListToInstall.add(mostRecent); } } catch (Exception ex) { ex.printStackTrace(); displayErrorDialog("An error has occurred while checking " + "package dependencies", ex); // bail out here // return null; depsOk = false; break; } } else { try { Package mostRecent = toCheck.getTarget().getPackage(); if (toCheck.getTarget() instanceof weka.core.packageManagement.VersionPackageConstraint) { mostRecent = WekaPackageManager .mostRecentVersionWithRespectToConstraint(toCheck .getTarget()); } finalListToInstall.add(mostRecent); } catch (Exception ex) { ex.printStackTrace(); displayErrorDialog("An error has occurred while checking " + "package dependencies", ex); // bail out here // return null; depsOk = false; break; } } } // now check for precludes if (packageToInstall .getPackageMetaDataElement(WekaPackageManager.PRECLUDES_KEY) != null) { try { List<Package> installed = WekaPackageManager.getInstalledPackages(); Map<String, Package> packageMap = new HashMap<>(); for (Package p : installed) { packageMap.put(p.getName(), p); } for (Package p : finalListToInstall) { packageMap.put(p.getName(), p); } List<Package> precluded = packageToInstall.getPrecludedPackages(new ArrayList<Package>( packageMap.values())); if (precluded.size() > 0) { List<Package> finalPrecluded = new ArrayList<>(); for (Package p : precluded) { if (!WekaPackageManager.m_doNotLoadList.contains(p.getName())) { finalPrecluded.add(p); } } if (finalPrecluded.size() > 0) { StringBuilder temp = new StringBuilder(); for (Package fp : finalPrecluded) { temp.append("\n\t").append(fp.toString()); } JOptionPane.showMessageDialog(PackageManager.this, "Package " + packageToInstall.getName() + " cannot be " + "installed because it precludes the following packages" + ":\n\n" + temp.toString(), "Weka Package Manager", JOptionPane.ERROR_MESSAGE); m_unsuccessfulInstalls.add(packageToInstall); continue; } } } catch (Exception ex) { ex.printStackTrace(); displayErrorDialog("An error has occurred while checking " + "precluded packages", ex); // bail out here depsOk = false; break; } } if (!depsOk) { // bail out on this package m_unsuccessfulInstalls.add(packageToInstall); continue; } if (needsUpgrade.size() > 0) { StringBuffer temp = new StringBuffer(); for (PackageConstraint pc : needsUpgrade) { temp.append(pc + "\n"); } int result = JOptionPane.showConfirmDialog(PackageManager.this, "The following packages will be upgraded in order to install:\n\n" + temp.toString(), "Weka Package Manager", JOptionPane.YES_NO_OPTION); if (result == JOptionPane.NO_OPTION) { // bail out here // return null; m_unsuccessfulInstalls.add(packageToInstall); continue; } // now take a look at the other installed packages and see if // any would have a problem when these ones are upgraded boolean conflictsAfterUpgrade = false; List<Package> installed = null; try { installed = WekaPackageManager.getInstalledPackages(); } catch (Exception e) { e.printStackTrace(); displayErrorDialog( "Unable to determine what packages are installed!", e); // return null; // can't proceed m_unsuccessfulInstalls.add(packageToInstall); continue; } List<Package> toUpgrade = new ArrayList<Package>(); for (PackageConstraint pc : needsUpgrade) { toUpgrade.add(pc.getPackage()); } // add the actual package the user is wanting to install if it // is going to be an up/downgrade rather than a first install since // other installed packages may depend on the currently installed // version // and thus could be affected after the up/downgrade toUpgrade.add(packageToInstall); StringBuffer tempM = new StringBuffer(); depsOk = true; for (int i = 0; i < installed.size(); i++) { Package tempP = installed.get(i); String tempPName = tempP.getName(); boolean checkIt = true; for (int j = 0; j < needsUpgrade.size(); j++) { if (tempPName .equals(needsUpgrade.get(j).getPackage().getName())) { checkIt = false; break; } } if (checkIt) { List<Dependency> problem = null; try { problem = tempP.getIncompatibleDependencies(toUpgrade); } catch (Exception e) { e.printStackTrace(); displayErrorDialog("An error has occurred while checking " + "package dependencies", e); // return null; // can't continue depsOk = false; break; } if (problem.size() > 0) { conflictsAfterUpgrade = true; tempM .append("Package " + tempP.getName() + " will have a compatibility" + "problem with the following packages after upgrading them:\n"); Iterator<Dependency> dI = problem.iterator(); while (dI.hasNext()) { tempM.append("\t" + dI.next().getTarget().getPackage() + "\n"); } } } } if (!depsOk) { m_unsuccessfulInstalls.add(packageToInstall); continue; } if (conflictsAfterUpgrade) { JOptionPane.showConfirmDialog(PackageManager.this, tempM.toString() + "\n" + "Unable to continue with installation.", "Weka Package Manager", JOptionPane.OK_OPTION); // return null; //bail out here m_unsuccessfulInstalls.add(packageToInstall); continue; } } if (finalListToInstall.size() > 0) { StringBuffer message = new StringBuffer(); message.append("To install " + packageName + " the following packages will" + " be installed/upgraded:\n\n"); for (Package p : finalListToInstall) { message.append("\t" + p + "\n"); } int result = JOptionPane.showConfirmDialog(PackageManager.this, message.toString(), "Weka Package Manager", JOptionPane.YES_NO_OPTION); if (result == JOptionPane.NO_OPTION) { // bail out here // return null; m_unsuccessfulInstalls.add(packageToInstall); continue; } m_progress.setMaximum(m_progress.getMaximum() + (finalListToInstall.size() * 30)); } // OK, now we can download and install everything // first install the final list of dependencies try { boolean tempB = WekaPackageManager.installPackages(finalListToInstall, pps); s_atLeastOnePackageUpgradeHasOccurredInThisSession = (s_atLeastOnePackageUpgradeHasOccurredInThisSession || tempB); } catch (Exception e) { e.printStackTrace(); displayErrorDialog("An error has occurred while installing " + "dependent packages", e); // return null; m_unsuccessfulInstalls.add(packageToInstall); continue; } // Now install the package itself // m_progress.setMaximum(finalListToInstall.size() * 10 + 10); try { boolean tempB = WekaPackageManager.installPackageFromRepository(packageName, versionToInstall.toString(), pps); s_atLeastOnePackageUpgradeHasOccurredInThisSession = (s_atLeastOnePackageUpgradeHasOccurredInThisSession || tempB); } catch (Exception e) { e.printStackTrace(); displayErrorDialog("Problem installing package: " + packageName, e); // return null; m_unsuccessfulInstalls.add(packageToInstall); continue; } } else { // m_progress.setMaximum(10); // just install this package without checking/downloading dependencies // etc. try { boolean tempB = WekaPackageManager.installPackageFromRepository(packageName, versionToInstall.toString(), pps); s_atLeastOnePackageUpgradeHasOccurredInThisSession = (s_atLeastOnePackageUpgradeHasOccurredInThisSession || tempB); } catch (Exception e) { e.printStackTrace(); displayErrorDialog("Problem installing package: " + packageName, e); // return null; m_unsuccessfulInstalls.add(packageToInstall); continue; } } } // m_successfulInstall = true; // Make sure that the new stuff is available to all GUIs (as long as no // upgrades occurred). // If an upgrade has occurred then the user is told to restart Weka // anyway, so we won't // refresh in this case in order to avoid old/new class conflicts if (!s_atLeastOnePackageUpgradeHasOccurredInThisSession) { WekaPackageManager.refreshGOEProperties(); } return null; } @Override public void done() { m_progress.setValue(m_progress.getMinimum()); if (m_unsuccessfulInstalls.size() == 0) { // if (m_successfulInstall) { m_detailLabel.setText("Package(s) installed successfully."); } else { StringBuffer failedPackageNames = new StringBuffer(); for (Package p : m_unsuccessfulInstalls) { failedPackageNames.append(p.getName() + "\n"); } displayErrorDialog( "The following package(s) could not be installed\n" + "for some reason (check the log)\n" + failedPackageNames.toString(), ""); m_detailLabel.setText("Install complete."); } m_unofficialBut.setEnabled(true); m_refreshCacheBut.setEnabled(true && !WekaPackageManager.m_offline); m_availableBut.setEnabled(true); m_allBut.setEnabled(true); m_installedBut.setEnabled(true); // force refresh of installed and available packages m_installedPackages = null; m_availablePackages = null; // m_installBut.setEnabled(true); m_installing = false; updateTable(); if (m_table.getSelectedRow() >= 0) { // mainly to update the install/uninstall button status // displayPackageInfo(m_table.getSelectedRow()); updateInstallUninstallButtonEnablement(); } } } /* * public class ComboBoxRenderer extends JComboBox implements * TableCellRenderer { public ComboBoxRenderer(String[] items) { super(items); * } * * public Component getTableCellRendererComponent(JTable table, Object value, * boolean isSelected, boolean hasFocus, int row, int column) { if * (isSelected) { setForeground(table.getSelectionForeground()); * super.setBackground(table.getSelectionBackground()); } else { * setForeground(table.getForeground()); setBackground(table.getBackground()); * } * * // Select the current value setSelectedItem(value); return this; } } */ protected class ComboBoxEditor extends DefaultCellEditor { /** Added ID to avoid warning. */ private static final long serialVersionUID = 5240331667759901966L; public ComboBoxEditor() { super(new JComboBox(new String[] { "one", "two" })); } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { String packageName = m_table.getValueAt(row, getColumnIndex(PACKAGE_COLUMN)).toString(); List<Object> catAndVers = m_packageLookupInfo.get(packageName); @SuppressWarnings("unchecked") List<Object> repVersions = (List<Object>) catAndVers.get(1); String[] versions = repVersions.toArray(new String[1]); Component combo = getComponent(); if (combo instanceof JComboBox) { ((JComboBox) combo).setModel(new DefaultComboBoxModel(versions)); ((JComboBox) combo).setSelectedItem(value); } else { System.err.println("Uh oh!!!!!"); } return combo; } } protected boolean m_cacheEstablished = false; protected boolean m_cacheRefreshInProgress = false; public static String PAGE_HEADER = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n" + "<html>\n<head>\n<title>Waikato Environment for Knowledge Analysis (WEKA)</title>\n" + "<!-- CSS Stylesheet -->\n<style>body\n{\nbackground: #ededed;\ncolor: #666666;\n" + "font: 14px Tahoma, Helvetica, sans-serif;;\nmargin: 5px 10px 5px 10px;\npadding: 0px;\n" + "}\n</style>\n\n</head>\n<body bgcolor=\"#ededed\" text=\"#666666\">\n"; private static String initialPage() { StringBuffer initialPage = new StringBuffer(); initialPage.append(PAGE_HEADER); initialPage.append("<h1>WEKA Package Manager</h1>\n\n</body></html>\n"); return initialPage.toString(); } protected class HomePageThread extends Thread { @Override public void run() { try { m_homeB.setEnabled(false); m_backB.setEnabled(false); URLConnection conn = null; URL homeURL = new URL(BROWSER_HOME); weka.core.packageManagement.PackageManager pm = WekaPackageManager.getUnderlyingPackageManager(); if (pm.setProxyAuthentication(homeURL)) { conn = homeURL.openConnection(pm.getProxy()); } else { conn = homeURL.openConnection(); } // read the html for the home page - all we want to do here is make // sure that the web server is responding, so that we don't tie // up the JEditorPane indefinitely, since there seems to be no // way to set a timeout in JEditorPane conn.setConnectTimeout(10000); // 10 seconds BufferedReader bi = new BufferedReader(new InputStreamReader(conn.getInputStream())); while (bi.readLine() != null) { // } m_infoPane.setPage(BROWSER_HOME); } catch (Exception ex) { // don't make a fuss } finally { m_homeB.setEnabled(true); m_backB.setEnabled(true); } } } private int getColumnIndex(String columnName) { return m_table.getColumn(columnName).getModelIndex(); } public PackageManager() { if (WekaPackageManager.m_noPackageMetaDataAvailable) { JOptionPane .showMessageDialog( this, "The package manager is unavailable " + "due to the fact that there is no cached package meta data and we are offline", "Package manager unavailable", JOptionPane.INFORMATION_MESSAGE); return; } EstablishCache ec = new EstablishCache(); ec.execute(); while (!m_cacheEstablished) { try { Thread.sleep(1000); } catch (InterruptedException e1) { e1.printStackTrace(); } } // first try and get the full list of packages getAllPackages(); setLayout(new BorderLayout()); ButtonGroup bGroup = new ButtonGroup(); bGroup.add(m_installedBut); bGroup.add(m_availableBut); bGroup.add(m_allBut); m_installedBut.setToolTipText("Installed packages"); m_availableBut.setToolTipText("Available packages compatible with Weka " + Version.VERSION); m_allBut.setToolTipText("All packages"); JPanel butPanel = new JPanel(); butPanel.setLayout(new BorderLayout()); JPanel packageDisplayP = new JPanel(); packageDisplayP.setLayout(new BorderLayout()); JPanel packageDHolder = new JPanel(); packageDHolder.setLayout(new FlowLayout()); packageDHolder.add(m_installedBut); packageDHolder.add(m_availableBut); packageDHolder.add(m_allBut); packageDisplayP.add(packageDHolder, BorderLayout.SOUTH); packageDisplayP.add(m_refreshCacheBut, BorderLayout.NORTH); JPanel officialHolder = new JPanel(); officialHolder.setLayout(new BorderLayout()); officialHolder.setBorder(BorderFactory.createTitledBorder("Official")); officialHolder.add(packageDisplayP, BorderLayout.WEST); butPanel.add(officialHolder, BorderLayout.WEST); m_refreshCacheBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { RefreshCache r = new RefreshCache(true); r.execute(); } }); JPanel unofficialHolder = new JPanel(); unofficialHolder.setLayout(new BorderLayout()); unofficialHolder.setBorder(BorderFactory.createTitledBorder("Unofficial")); unofficialHolder.add(m_unofficialBut, BorderLayout.NORTH); butPanel.add(unofficialHolder, BorderLayout.EAST); JPanel installP = new JPanel(); JPanel buttP = new JPanel(); buttP.setLayout(new GridLayout(1, 3)); installP.setLayout(new BorderLayout()); buttP.add(m_installBut); buttP.add(m_uninstallBut); buttP.add(m_toggleLoad); m_installBut.setEnabled(false); m_uninstallBut.setEnabled(false); m_toggleLoad.setEnabled(false); installP.add(buttP, BorderLayout.NORTH); installP.add(m_forceBut, BorderLayout.SOUTH); m_forceBut.setEnabled(false); // butPanel.add(installP, BorderLayout.EAST); officialHolder.add(installP, BorderLayout.EAST); m_installBut.setToolTipText("Install the selected official package(s) " + "from the list"); m_uninstallBut .setToolTipText("Uninstall the selected package(s) from the list"); m_toggleLoad.setToolTipText("Toggle installed package(s) load status (" + "note - changes take affect after a restart)"); m_unofficialBut .setToolTipText("Install an unofficial package from a file or URL"); m_unofficialChooser.resetFileFilters(); m_unofficialChooser.addFileFilter(new ExtensionFileFilter(".zip", "Package archive file")); m_unofficialBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (m_unofficialFrame == null) { final JFrame jf = Utils.getWekaJFrame("Unofficial package install", PackageManager.this); jf.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { jf.dispose(); m_unofficialBut.setEnabled(true); m_unofficialFrame = null; } }); jf.setLayout(new BorderLayout()); JButton okBut = new JButton("OK"); JButton cancelBut = new JButton("Cancel"); JPanel butHolder = new JPanel(); butHolder.setLayout(new GridLayout(1, 2)); butHolder.add(okBut); butHolder.add(cancelBut); jf.add(m_unofficialChooser, BorderLayout.CENTER); jf.add(butHolder, BorderLayout.SOUTH); jf.pack(); jf.setSize(600, 150); jf.setLocationRelativeTo(PackageManager.this); jf.setVisible(true); m_unofficialFrame = jf; m_unofficialBut.setEnabled(false); cancelBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (m_unofficialFrame != null) { jf.dispose(); m_unofficialBut.setEnabled(true); m_unofficialFrame = null; } } }); okBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String target = m_unofficialChooser.getText(); UnofficialInstallTask t = new UnofficialInstallTask(); t.setTargetToInstall(target); t.execute(); if (m_unofficialFrame != null) { jf.dispose(); m_unofficialBut.setEnabled(true); m_unofficialFrame = null; } } }); } } }); m_toggleLoad.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int[] selectedRows = m_table.getSelectedRows(); List<Integer> alteredRows = new ArrayList<Integer>(); if (selectedRows.length > 0) { List<String> packageNames = new ArrayList<String>(); for (int selectedRow : selectedRows) { String packageName = m_table.getValueAt(selectedRow, getColumnIndex(PACKAGE_COLUMN)) .toString(); try { if (WekaPackageManager.getInstalledPackageInfo(packageName) != null) { // TODO List<Object> catAndVers = m_packageLookupInfo.get(packageName); if (!catAndVers.get(2).toString().equals("No - check log")) { packageNames.add(packageName); alteredRows.add(selectedRow); } } } catch (Exception ex) { ex.printStackTrace(); } } if (packageNames.size() > 0) { try { WekaPackageManager.toggleLoadStatus(packageNames); for (String packageName : packageNames) { List<Object> catAndVers = m_packageLookupInfo.get(packageName); String loadStatus = catAndVers.get(2).toString(); if (loadStatus.startsWith("Yes")) { loadStatus = "No - user flagged (pending restart)"; } else { loadStatus = "Yes - user flagged (pending restart)"; } catAndVers.set(2, loadStatus); } updateTable(); } catch (Exception e1) { e1.printStackTrace(); } } toggleLoadStatusRequiresRestartPopUp(); } } }); m_installBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int[] selectedRows = m_table.getSelectedRows(); if (selectedRows.length > 0) { // int selected = m_table.getSelectedRow(); // if (selected != -1) { List<String> packageNames = new ArrayList<String>(); List<Object> versions = new ArrayList<Object>(); StringBuffer confirmList = new StringBuffer(); for (int selectedRow : selectedRows) { String packageName = m_table.getValueAt(selectedRow, getColumnIndex(PACKAGE_COLUMN)) .toString(); packageNames.add(packageName); Object packageVersion = m_table .getValueAt(selectedRow, getColumnIndex(REPOSITORY_COLUMN)); versions.add(packageVersion); confirmList.append(packageName + " " + packageVersion.toString() + "\n"); } JTextArea jt = new JTextArea("The following packages will be " + "installed/upgraded:\n\n" + confirmList.toString(), 10, 40); int result = JOptionPane.showConfirmDialog(PackageManager.this, new JScrollPane( jt), "Weka Package Manager", JOptionPane.YES_NO_OPTION); if (result == JOptionPane.YES_OPTION) { pleaseCloseAppWindowsPopUp(); InstallTask task = new InstallTask(); task.setPackages(packageNames); task.setVersions(versions); task.execute(); } } } }); m_uninstallBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // int selected = m_table.getSelectedRow(); int[] selectedRows = m_table.getSelectedRows(); if (selectedRows.length > 0) { List<String> packageNames = new ArrayList<String>(); StringBuffer confirmList = new StringBuffer(); for (int selectedRow : selectedRows) { String packageName = m_table.getValueAt(selectedRow, getColumnIndex(PACKAGE_COLUMN)) .toString(); Package p = null; try { p = WekaPackageManager.getRepositoryPackageInfo(packageName); } catch (Exception e1) { // e1.printStackTrace(); // continue; // see if we can get installed package info try { p = WekaPackageManager.getInstalledPackageInfo(packageName); } catch (Exception e2) { e2.printStackTrace(); continue; } } if (p.isInstalled()) { packageNames.add(packageName); confirmList.append(packageName + "\n"); } } if (packageNames.size() > 0) { JTextArea jt = new JTextArea("The following packages will be " + "uninstalled:\n" + confirmList.toString(), 10, 40); int result = JOptionPane.showConfirmDialog(PackageManager.this, new JScrollPane(jt), "Weka Package Manager", JOptionPane.YES_NO_OPTION); if (result == JOptionPane.YES_OPTION) { pleaseCloseAppWindowsPopUp(); UninstallTask task = new UninstallTask(); task.setPackages(packageNames); task.execute(); } } } /* * if (selected != -1) { String packageName = * m_table.getValueAt(selected, * getColumnIndex(PACKAGE_COLUMN)).toString(); * * pleaseCloseAppWindowsPopUp(); UninstallTask task = new * UninstallTask(); task.setPackage(packageName); task.execute(); } */ } }); JPanel progressP = new JPanel(); progressP.setLayout(new BorderLayout()); progressP.setBorder(BorderFactory .createTitledBorder("Install/Uninstall/Refresh progress")); progressP.add(m_progress, BorderLayout.NORTH); progressP.add(m_detailLabel, BorderLayout.CENTER); butPanel.add(progressP, BorderLayout.CENTER); JPanel topPanel = new JPanel(); topPanel.setLayout(new BorderLayout()); // topPanel.setBorder(BorderFactory.createTitledBorder("Packages")); topPanel.add(butPanel, BorderLayout.NORTH); m_availableBut.setSelected(true); m_allBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_searchResults.clear(); m_searchField.setText(""); m_searchHitsLab.setText(""); m_table.clearSelection(); updateTable(); updateInstallUninstallButtonEnablement(); } }); m_availableBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_searchResults.clear(); m_searchField.setText(""); m_searchHitsLab.setText(""); m_table.clearSelection(); updateTable(); updateInstallUninstallButtonEnablement(); } }); m_installedBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_searchResults.clear(); m_searchField.setText(""); m_searchHitsLab.setText(""); m_table.clearSelection(); updateTable(); updateInstallUninstallButtonEnablement(); } }); m_model = new DefaultTableModel(new String[] { PACKAGE_COLUMN, CATEGORY_COLUMN, INSTALLED_COLUMN, REPOSITORY_COLUMN, LOADED_COLUMN }, 15) { private static final long serialVersionUID = -2886328542412471039L; @Override public boolean isCellEditable(int row, int col) { if (col != 3) { return false; } else { return true; } } }; m_table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); m_table.setColumnSelectionAllowed(false); m_table.setPreferredScrollableViewportSize(new Dimension(550, 200)); m_table.setModel(m_model); if (System.getProperty("os.name").contains("Mac")) { m_table.setShowVerticalLines(true); } else { m_table.setShowVerticalLines(false); } m_table.setShowHorizontalLines(false); m_table.getColumn("Repository version").setCellEditor(new ComboBoxEditor()); m_table.getSelectionModel().addListSelectionListener( new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting() && !m_cacheRefreshInProgress) { ListSelectionModel lm = (ListSelectionModel) e.getSource(); boolean infoDisplayed = false; for (int i = e.getFirstIndex(); i <= e.getLastIndex(); i++) { if (lm.isSelectedIndex(i)) { if (!infoDisplayed) { // display package info for the first one in the list displayPackageInfo(i); infoDisplayed = true; break; } } } updateInstallUninstallButtonEnablement(); } } }); JTableHeader header = m_table.getTableHeader(); header.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent evt) { TableColumnModel colModel = m_table.getColumnModel(); // The index of the column whose header was clicked int vColIndex = colModel.getColumnIndexAtX(evt.getX()); // Return if not clicked on any column header or // clicked on the version number cols if (vColIndex == -1 || vColIndex > 1) { return; } if (vColIndex == m_sortColumn) { // toggle the sort order m_reverseSort = !m_reverseSort; } else { m_reverseSort = false; } m_sortColumn = vColIndex; updateTable(); } }); topPanel.add(new JScrollPane(m_table), BorderLayout.CENTER); // add(topPanel, BorderLayout.NORTH); /* * m_packageDescription = new JTextArea(10,10); * m_packageDescription.setLineWrap(true); */ try { // m_infoPane = new JEditorPane(BROWSER_HOME); String initialPage = initialPage(); m_infoPane = new JEditorPane("text/html", initialPage); } catch (Exception ex) { m_infoPane = new JEditorPane(); } m_infoPane.setEditable(false); m_infoPane.addHyperlinkListener(new HyperlinkListener() { @Override public void hyperlinkUpdate(HyperlinkEvent event) { if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { try { if (event.getURL().toExternalForm().endsWith(".zip") || event.getURL().toExternalForm().endsWith(".jar")) { // don't render archives! } else { if (m_browserHistory.size() == 0) { m_backB.setEnabled(true); } m_browserHistory.add(m_infoPane.getPage()); m_infoPane.setPage(event.getURL()); } } catch (IOException ioe) { } } } }); // JScrollPane sp = new JScrollPane(m_packageDescription); // JScrollPane sp = new JScrollPane(m_infoPane); // sp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); // sp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); JPanel browserP = new JPanel(); browserP.setLayout(new BorderLayout()); m_backB = new JButton(new ImageIcon(loadImage("weka/gui/images/back.gif"))); m_backB.setToolTipText("Back"); m_backB.setEnabled(false); m_backB.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 4)); m_homeB = new JButton(new ImageIcon(loadImage("weka/gui/images/home.gif"))); m_homeB.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 4)); m_homeB.setToolTipText("Home"); m_browserTools = new JToolBar(); m_browserTools.add(m_backB); m_browserTools.add(m_homeB); m_searchField = new JTextField(15); JPanel searchHolder = new JPanel(new BorderLayout()); JPanel temp = new JPanel(new BorderLayout()); JLabel searchLab = new JLabel("Package search "); searchLab .setToolTipText("Type search terms (comma separated) and hit <Enter>"); temp.add(searchLab, BorderLayout.WEST); temp.add(m_searchField, BorderLayout.CENTER); searchHolder.add(temp, BorderLayout.WEST); JButton clearSearchBut = new JButton("Clear"); clearSearchBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_searchField.setText(""); m_searchHitsLab.setText(""); updateTable(); } }); JPanel clearAndHitsHolder = new JPanel(new BorderLayout()); clearAndHitsHolder.add(clearSearchBut, BorderLayout.WEST); clearAndHitsHolder.add(m_searchHitsLab, BorderLayout.EAST); temp.add(clearAndHitsHolder, BorderLayout.EAST); m_browserTools.addSeparator(); m_browserTools.add(searchHolder); Dimension d = m_searchField.getSize(); m_searchField.setMaximumSize(new Dimension(150, 20)); m_searchField.setEnabled(m_packageDescriptions.size() > 0); m_searchField.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { List<Package> toSearch = m_allBut.isSelected() ? m_allPackages : m_availableBut.isSelected() ? m_availablePackages : m_installedPackages; m_searchResults.clear(); String searchString = m_searchField.getText(); if (searchString != null && searchString.length() > 0) { String[] terms = searchString.split(","); for (Package p : toSearch) { String name = p.getName(); String description = m_packageDescriptions.get(name); if (description != null) { for (String t : terms) { if (description.contains(t.trim().toLowerCase())) { m_searchResults.add(p); break; } } } } m_searchHitsLab.setText(" (Search hits: " + m_searchResults.size() + ")"); } else { m_searchHitsLab.setText(""); } updateTable(); } }); m_browserTools.setFloatable(false); // create the new packages available icon m_newPackagesAvailableL = new JLabel(new ImageIcon(loadImage("weka/gui/images/information.gif"))); m_newPackagesAvailableL.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); m_browserTools.remove(m_newPackagesAvailableL); m_browserTools.revalidate(); } }); // Start loading the home page Thread homePageThread = new HomePageThread(); homePageThread.setPriority(Thread.MIN_PRIORITY); homePageThread.start(); m_backB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { URL previous = m_browserHistory.removeLast(); try { m_infoPane.setPage(previous); if (m_browserHistory.size() == 0) { m_backB.setEnabled(false); } } catch (IOException ex) { // } } }); m_homeB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { URL back = m_infoPane.getPage(); if (back != null) { m_browserHistory.add(back); } String initialPage = initialPage(); m_infoPane.setContentType("text/html"); m_infoPane.setText(initialPage); HomePageThread hp = new HomePageThread(); hp.setPriority(Thread.MIN_PRIORITY); hp.start(); } catch (Exception ex) { // don't make a fuss } } }); browserP.add(m_browserTools, BorderLayout.NORTH); browserP.add(new JScrollPane(m_infoPane), BorderLayout.CENTER); // add(browserP, BorderLayout.CENTER); m_splitP = new JSplitPane(JSplitPane.VERTICAL_SPLIT, topPanel, browserP); m_splitP.setOneTouchExpandable(true); add(m_splitP, BorderLayout.CENTER); updateTable(); // check for any new packages on the server (if possible) if (!WekaPackageManager.m_offline) { System.err.println("Checking for new packages..."); CheckForNewPackages cp = new CheckForNewPackages(); cp.execute(); } else { // disable cache refresh and install buttons m_installBut.setEnabled(false); m_refreshCacheBut.setEnabled(false); } } private void updateInstallUninstallButtonEnablement() { boolean enableInstall = false; boolean enableUninstall = false; boolean enableToggleLoadStatus = false; m_unofficialBut.setEnabled(true); if (!m_installing) { int[] selectedRows = m_table.getSelectedRows(); // check the package to see whether we should enable the // install button or uninstall button. Once we've determined // that the list contains at least one package to be installed // and uninstalled we don't have to check any further for (int selectedRow : selectedRows) { if (!enableInstall || !enableUninstall) { enableInstall = true; // we should always be able to install an // already installed package String packageName = m_table.getValueAt(selectedRow, getColumnIndex(PACKAGE_COLUMN)) .toString(); try { Package p = WekaPackageManager.getRepositoryPackageInfo(packageName); if (!enableUninstall) { enableUninstall = p.isInstalled(); } if (!enableToggleLoadStatus) { enableToggleLoadStatus = p.isInstalled(); } /* * if (!enableInstall) { enableInstall = !p.isInstalled(); } */ } catch (Exception e1) { // not a repository package - just enable the uninstall button enableUninstall = true; enableInstall = false; } } } } else { m_unofficialBut.setEnabled(false); } // now set the button enablement m_installBut.setEnabled(enableInstall && !WekaPackageManager.m_offline); m_forceBut.setEnabled(enableInstall); m_uninstallBut.setEnabled(enableUninstall); m_toggleLoad.setEnabled(enableToggleLoadStatus); } private Image loadImage(String path) { Image pic = null; URL imageURL = this.getClass().getClassLoader().getResource(path); if (imageURL == null) { // ignore } else { pic = Toolkit.getDefaultToolkit().getImage(imageURL); } return pic; } private void updateTableForPackageList(List<Package> packageList) { m_table.clearSelection(); m_model.setRowCount(packageList.size()); int row = 0; for (Package p : packageList) { m_model.setValueAt(p.getName(), row, getColumnIndex(PACKAGE_COLUMN)); String installedV = ""; if (p.isInstalled()) { try { Package installed = WekaPackageManager.getInstalledPackageInfo(p.getName()); installedV = installed.getPackageMetaDataElement("Version").toString(); } catch (Exception ex) { ex.printStackTrace(); displayErrorDialog("An error has occurred while trying to obtain" + " installed package info", ex); } } String category = ""; if (p.getPackageMetaDataElement("Category") != null) { category = p.getPackageMetaDataElement("Category").toString(); } List<Object> catAndVers = m_packageLookupInfo.get(p.getName()); Object repositoryV = "-----"; if (catAndVers != null) { // handle non-repository packages @SuppressWarnings("unchecked") List<Object> repVersions = (List<Object>) catAndVers.get(1); // repositoryV = repVersions.get(0); try { Package latestRepoV = WekaPackageManager.getLatestCompatibleVersion(p.getName()); if (latestRepoV != null) { repositoryV = latestRepoV .getPackageMetaDataElement(WekaPackageManager.VERSION_KEY); } } catch (Exception e) { e.printStackTrace(); displayErrorDialog("An error has occurred while trying to obtain" + " installed package info", e); } // p.getPackageMetaDataElement(WekaPackageManager.VERSION_KEY); } // String repString = getRepVersions(p.getName(), repositoryV); // repositoryV = repositoryV + " " + repString; m_model.setValueAt(category, row, getColumnIndex(CATEGORY_COLUMN)); m_model.setValueAt(installedV, row, getColumnIndex(INSTALLED_COLUMN)); m_model.setValueAt(repositoryV, row, getColumnIndex(REPOSITORY_COLUMN)); if (catAndVers != null) { String loadStatus = (String) catAndVers.get(2); m_model.setValueAt(loadStatus, row, getColumnIndex(LOADED_COLUMN)); } else { // handle non-repository packages File packageRoot = new File(WekaPackageManager.getPackageHome().toString() + File.separator + p.getName()); // boolean loaded = WekaPackageManager.loadCheck(p, packageRoot); boolean loaded = WekaPackageManager.hasBeenLoaded(p); String loadStatus = loaded ? "Yes" : "No - check log"; m_model.setValueAt(loadStatus, row, getColumnIndex(LOADED_COLUMN)); } row++; } } private void updateTable() { if (m_installedPackages == null || m_availablePackages == null) { // update the loaded status for (Package p : m_allPackages) { List<Object> catAndVers = m_packageLookupInfo.get(p.getName()); String loadStatus = catAndVers.get(2).toString(); if (p.isInstalled()) { try { p = WekaPackageManager.getInstalledPackageInfo(p.getName()); } catch (Exception ex) { ex.printStackTrace(); } File packageRoot = new File(WekaPackageManager.getPackageHome().toString() + File.separator + p.getName()); // boolean loaded = WekaPackageManager.loadCheck(p, packageRoot); boolean loaded = WekaPackageManager.hasBeenLoaded(p); boolean userNoLoad = WekaPackageManager.m_doNotLoadList.contains(p.getName()); if (!loadStatus.contains("pending")) { loadStatus = (loaded) ? "Yes" : userNoLoad ? "No - user flagged" : "No - check log"; } } catAndVers.set(2, loadStatus); } } if (m_searchField.getText() != null && m_searchField.getText().length() > 0) { updateTableForPackageList(m_searchResults); return; } if (m_allBut.isSelected()) { Collections.sort(m_allPackages, m_packageComparator); updateTableForPackageList(m_allPackages); } else if (m_installedBut.isSelected()) { try { if (m_installedPackages == null) { m_installedPackages = WekaPackageManager.getInstalledPackages(); } updateTableForPackageList(m_installedPackages); } catch (Exception ex) { ex.printStackTrace(); } } else { try { if (m_availablePackages == null) { m_availablePackages = WekaPackageManager.getAvailableCompatiblePackages(); } updateTableForPackageList(m_availablePackages); } catch (Exception ex) { ex.printStackTrace(); } } } private void displayPackageInfo(int i) { String packageName = m_table.getValueAt(i, getColumnIndex(PACKAGE_COLUMN)).toString(); boolean repositoryPackage = true; try { WekaPackageManager.getRepositoryPackageInfo(packageName); } catch (Exception ex) { repositoryPackage = false; } String versionURL = WekaPackageManager.getPackageRepositoryURL().toString() + "/" + packageName + "/index.html"; try { URL back = m_infoPane.getPage(); if (m_browserHistory.size() == 0 && back != null) { m_backB.setEnabled(true); } if (back != null) { m_browserHistory.add(back); } if (repositoryPackage) { m_infoPane.setPage(new URL(versionURL)); } else { // try and display something on this non-official package try { Package p = WekaPackageManager.getInstalledPackageInfo(packageName); Map<?, ?> meta = p.getPackageMetaData(); Set<?> keys = meta.keySet(); StringBuffer sb = new StringBuffer(); sb.append(weka.core.RepositoryIndexGenerator.HEADER); sb.append("<H1>" + packageName + " (Unofficial) </H1>"); for (Object k : keys) { if (!k.toString().equals("PackageName")) { Object value = meta.get(k); sb.append(k + " : " + value + "<p>"); } } sb.append("</html>\n"); m_infoPane.setText(sb.toString()); } catch (Exception e) { // ignore } } } catch (Exception ex) { ex.printStackTrace(); } updateInstallUninstallButtonEnablement(); if (m_availableBut.isSelected()) { m_uninstallBut.setEnabled(false); } /* * if (m_installing) { m_installBut.setEnabled(false); * m_uninstallBut.setEnabled(false); } else { m_installBut.setEnabled(true); * if (m_availableBut.isSelected()) { m_uninstallBut.setEnabled(false); } * else { try { Package p = * WekaPackageManager.getRepositoryPackageInfo(packageName); * m_uninstallBut.setEnabled(p.isInstalled()); } catch (Exception ex) { * m_uninstallBut.setEnabled(false); } } } */ } private void getPackagesAndEstablishLookup() throws Exception { m_allPackages = WekaPackageManager.getAllPackages(); m_installedPackages = WekaPackageManager.getInstalledPackages(); // now fill the lookup map m_packageLookupInfo = new TreeMap<String, List<Object>>(); // Iterator<Package> i = allP.iterator(); for (Package p : m_allPackages) { // Package p = i.next(); String packageName = p.getName(); String category = ""; if (p.getPackageMetaDataElement("Category") != null) { category = p.getPackageMetaDataElement("Category").toString(); } // check the load status of this package (if installed) String loadStatus = ""; if (p.isInstalled()) { p = WekaPackageManager.getInstalledPackageInfo(p.getName()); File packageRoot = new File(WekaPackageManager.getPackageHome().toString()); // boolean loaded = WekaPackageManager.loadCheck(p, packageRoot); boolean loaded = WekaPackageManager.hasBeenLoaded(p); loadStatus = (loaded) ? "Yes" : "No - check log"; } List<Object> versions = WekaPackageManager.getRepositoryPackageVersions(packageName); List<Object> catAndVers = new ArrayList<Object>(); catAndVers.add(category); catAndVers.add(versions); catAndVers.add(loadStatus); m_packageLookupInfo.put(packageName, catAndVers); } // Load all repCache package descriptions into the search lookup for (Package p : m_allPackages) { String name = p.getName(); File repLatest = new File(WekaPackageManager.WEKA_HOME.toString() + File.separator + "repCache" + File.separator + name + File.separator + "Latest.props"); if (repLatest.exists() && repLatest.isFile()) { String packageDescription = loadPropsText(repLatest); m_packageDescriptions.put(name, packageDescription); } } // Now process all installed packages and add to the search // just in case there are some unofficial packages for (Package p : m_installedPackages) { if (!m_packageDescriptions.containsKey(p.getName())) { String name = p.getName(); File instDesc = new File(WekaPackageManager.PACKAGES_DIR.toString() + File.separator + name + File.separator + "Description.props"); if (instDesc.exists() && instDesc.isFile()) { m_packageDescriptions.put(name, loadPropsText(instDesc)); } } } } private String loadPropsText(File propsToLoad) throws IOException { BufferedReader br = new BufferedReader(new FileReader(propsToLoad)); StringBuilder builder = new StringBuilder(); String line = null; try { while ((line = br.readLine()) != null) { if (!line.startsWith("#")) { builder.append(line.toLowerCase()).append("\n"); } } } finally { br.close(); } return builder.toString(); } private void getAllPackages() { try { getPackagesAndEstablishLookup(); } catch (Exception ex) { // warn the user that we were unable to get the list of packages // from the repository ex.printStackTrace(); System.err.println("A problem has occurred whilst trying to get all " + "package information. Trying a cache refresh..."); WekaPackageManager.refreshCache(System.out); try { // try again getPackagesAndEstablishLookup(); } catch (Exception e) { e.printStackTrace(); } } } private void displayErrorDialog(String message, Exception e) { java.io.StringWriter sw = new java.io.StringWriter(); e.printStackTrace(new java.io.PrintWriter(sw)); String result = sw.toString(); displayErrorDialog(message, result); } private void displayErrorDialog(String message, String stackTrace) { Object[] options = null; if (stackTrace != null && stackTrace.length() > 0) { options = new Object[2]; options[0] = "OK"; options[1] = "Show error"; } else { options = new Object[1]; options[0] = "OK"; } int result = JOptionPane.showOptionDialog(this, message, "Weka Package Manager", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[0]); if (result == 1) { JTextArea jt = new JTextArea(stackTrace, 10, 40); JOptionPane.showMessageDialog(PackageManager.this, new JScrollPane(jt), "Weka Package Manager", JOptionPane.OK_OPTION); } } /** * Setting the initial placement of the divider line on a JSplitPane is * problematic. Most of the time it positions itself just fine based on the * preferred and minimum sizes of the two things it divides. However, * sometimes it seems to set itself such that the top component is not visible * without manually setting the position. This method can be called (after the * containing frame is visible) to set the divider location to 40% of the way * down the window. */ public void setInitialSplitPaneDividerLocation() { m_splitP.setDividerLocation(0.4); } public static void main(String[] args) { weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, "Logging started"); LookAndFeel.setLookAndFeel(); PackageManager pm = new PackageManager(); if (!WekaPackageManager.m_noPackageMetaDataAvailable) { String offline = ""; if (WekaPackageManager.m_offline) { offline = " (offline)"; } final javax.swing.JFrame jf = new javax.swing.JFrame("Weka Package Manager" + offline); jf.getContentPane().setLayout(new BorderLayout()); jf.getContentPane().add(pm, BorderLayout.CENTER); jf.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { jf.dispose(); System.exit(0); } }); Dimension screenSize = jf.getToolkit().getScreenSize(); int width = screenSize.width * 8 / 10; int height = screenSize.height * 8 / 10; jf.setBounds(width / 8, height / 8, width, height); jf.setVisible(true); pm.setInitialSplitPaneDividerLocation(); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/PasswordField.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * PasswordField * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import javax.swing.*; import java.awt.*; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.beans.PropertyEditor; /** * Property editor widget that wraps and displays a JPasswordField. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ public class PasswordField extends JPanel implements PropertyEditor, CustomPanelSupplier { private static final long serialVersionUID = 8180782063577036194L; /** The password field */ protected JPasswordField m_password; /** The label for the widget */ protected JLabel m_label; protected PropertyChangeSupport m_support = new PropertyChangeSupport(this); public PasswordField() { this(""); } public PasswordField(String label) { setLayout(new BorderLayout()); m_label = new JLabel(label); if (label.length() > 0) { m_label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5)); } add(m_label, BorderLayout.WEST); m_password = new JPasswordField(); m_password.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { super.keyReleased(e); m_support.firePropertyChange("", null, null); } }); m_password.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { super.focusLost(e); m_support.firePropertyChange("", null, null); } }); add(m_password, BorderLayout.CENTER); // setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); } /** * Set the label for this widget. * * @param label the label to use */ public void setLabel(String label) { m_label.setText(label); } public String getText() { return new String(m_password.getPassword()); } public void setText(String text) { m_password.setText(text); m_support.firePropertyChange("", null, null); } @Override public JPanel getCustomPanel() { return this; } @Override public Object getValue() { return getAsText(); } @Override public void setValue(Object value) { setAsText(value.toString()); } @Override public boolean isPaintable() { return true; } @Override public void paintValue(Graphics gfx, Rectangle box) { // nothing to do } @Override public String getJavaInitializationString() { return null; } @Override public String getAsText() { return getText(); } @Override public void setAsText(String text) throws IllegalArgumentException { setText(text); } @Override public String[] getTags() { return null; } @Override public Component getCustomEditor() { return this; } @Override public boolean supportsCustomEditor() { return true; } @Override public void addPropertyChangeListener(PropertyChangeListener pcl) { if (pcl != null && m_support != null) { m_support.addPropertyChangeListener(pcl); } } @Override public void removePropertyChangeListener(PropertyChangeListener pcl) { if (pcl != null && m_support != null) { m_support.removePropertyChangeListener(pcl); } } /** * Set the enabled status of the password box * * @param enabled true if the password box is to be enabled */ @Override public void setEnabled(boolean enabled) { m_password.setEnabled(enabled); } /** * Set the editable status of the password box. * * @param editable true if the password box is editable */ public void setEditable(boolean editable) { m_password.setEditable(editable); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/PasswordProperty.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * PasswordProperty.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.lang.annotation.*; /** * Method annotation that can be used to indicate that a property is a * password. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface PasswordProperty { }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/Perspective.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Perspective.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand */ package weka.gui; import weka.core.Defaults; import weka.core.Instances; import javax.swing.Icon; import javax.swing.JMenu; import java.util.List; /** * Interface for GUI elements that can appear as a perspective in a * {@code GUIApplication}. Clients will typically extend * {@code AbstractPerspective}. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public interface Perspective { /** * Gets called when startup of the application has completed. At this point, * and only at this point, is it guaranteed that a perspective has access to * its hosting application and the PerspectiveManager. Implementations can use * this method to complete their initialization in this method if this * requires access to information from the main application and/or the * PerspectiveManager (i.e. knowledge about what other perspectives are * available). */ void instantiationComplete(); /** * Returns true if this perspective is OK with being an active perspective - * i.e. the user can click on this perspective at this time in the perspective * toolbar. For example, a Perspective might return false from this method if * it needs a set of instances to operate but none have been supplied yet. * * @return true if this perspective can be active at the current time */ boolean okToBeActive(); /** * Set active status of this perspective. True indicates that this perspective * is the visible active perspective in the application * * @param active true if this perspective is the active one */ void setActive(boolean active); /** * Set whether this perspective is "loaded" - i.e. whether or not the user has * opted to have it available in the perspective toolbar. The perspective can * make the decision as to allocating or freeing resources on the basis of * this. Note that the main application and perspective manager instances are * not available to the perspective until the instantiationComplete() method * has been called. * * @param loaded true if the perspective is available in the perspective * toolbar of the KnowledgeFlow */ void setLoaded(boolean loaded); /** * Set the main application. Gives other perspectives access to information * provided by the main application * * @param main the main application */ void setMainApplication(GUIApplication main); /** * Get the main application that this perspective belongs to * * @return the main application that this perspective belongs to */ GUIApplication getMainApplication(); /** * Get the ID of this perspective * * @return the ID of this perspective */ String getPerspectiveID(); /** * Get the title of this perspective * * @return the title of this perspective */ String getPerspectiveTitle(); /** * Get the icon for this perspective * * @return the icon for this perspective */ Icon getPerspectiveIcon(); /** * Get the tool tip text for this perspective * * @return the tool tip text for this perspective */ String getPerspectiveTipText(); /** * Get an ordered list of menus to appear in the main menu bar. Return null * for no menus * * @return a list of menus to appear in the main menu bar or null for no menus */ List<JMenu> getMenus(); /** * Get the default settings for this perspective (or null if there are none) * * @return the default settings for this perspective, or null if the * perspective does not have any settings */ Defaults getDefaultSettings(); /** * Called when the user alters settings. The settings altered by the user are * not necessarily ones related to this perspective */ void settingsChanged(); /** * Returns true if this perspective can do something meaningful with a set of * instances * * @return true if this perspective accepts instances */ boolean acceptsInstances(); /** * Set instances (if this perspective can use them) * * @param instances the instances */ void setInstances(Instances instances); /** * Whether this perspective requires a graphical log to write to * * @return true if a log is needed by this perspective */ boolean requiresLog(); /** * Set a log to use (if required by the perspective) * * @param log the graphical log to use */ void setLog(Logger log); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/PerspectiveInfo.java
package weka.gui; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface PerspectiveInfo { /** * The ID of this perspective * * @return the ID of this perspective */ String ID(); /** * The title of this perspective * * @return the title of this perspective */ String title(); /** * The tool tip text for this perspective * * @return the tool tip text */ String toolTipText(); /** * Path (as a resource on the classpath) to the icon for this perspective * * @return the path to the icon for this perspective */ String iconPath(); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/PerspectiveManager.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * PerspectiveManager.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import weka.core.Copyright; import weka.core.Defaults; import weka.core.Environment; import weka.core.Settings; import weka.core.logging.Logger; import weka.core.PluginManager; import weka.gui.knowledgeflow.MainKFPerspectiveToolBar; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import static weka.gui.knowledgeflow.StepVisual.loadIcon; /** * Manages perspectives and the main menu bar (if visible), holds the currently * selected perspective, and implements the perspective button bar. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class PerspectiveManager extends JPanel { /** Interface name of perspectives */ public static final String PERSPECTIVE_INTERFACE = Perspective.class .getCanonicalName(); /** Settings key for visible perspectives in an application */ public static final Settings.SettingKey VISIBLE_PERSPECTIVES_KEY = new Settings.SettingKey("perspective_manager.visible_perspectives", "Visible perspectives", ""); private static final long serialVersionUID = -6099806469970666208L; /** The actual perspectives toolbar */ protected JToolBar m_perspectiveToolBar = new JToolBar(JToolBar.HORIZONTAL); /** For grouping the perspectives buttons in the toolbar */ protected ButtonGroup m_perspectiveGroup = new ButtonGroup(); /** The main application that owns this perspective manager */ protected GUIApplication m_mainApp; /** Cache of perspectives */ protected Map<String, Perspective> m_perspectiveCache = new LinkedHashMap<String, Perspective>(); /** Name lookup for perspectives */ protected Map<String, String> m_perspectiveNameLookup = new HashMap<String, String>(); /** The perspectives that have a button in the toolbar */ protected List<Perspective> m_perspectives = new ArrayList<Perspective>(); /** * Names of visible perspectives (i.e. those that the user has opted to be * available via a button in the toolbar */ protected LinkedHashSet<String> m_visiblePerspectives = new LinkedHashSet<String>(); /** Allow these perspectives in the toolbar (empty list means allow all) */ protected List<String> m_allowedPerspectiveClassPrefixes = new ArrayList<String>(); /** * Disallow these perspectives (non-empty list overrides meaning of empty * allowed list) */ protected List<String> m_disallowedPerspectiveClassPrefixes = new ArrayList<String>(); /** * The main perspective for the application owning this perspective manager */ protected Perspective m_mainPerspective; /** Whether the toolbar is visible or hidden */ protected boolean m_configAndPerspectivesVisible; /** Holds the config/settings button and toolbar */ protected JPanel m_configAndPerspectivesToolBar; /** Main application menu bar */ protected JMenuBar m_appMenuBar = new JMenuBar(); /** Program menu */ protected JMenu m_programMenu; /** Menu item for toggling whether the toolbar is visible or not */ protected JMenuItem m_togglePerspectivesToolBar; /** The panel for log and status messages */ protected LogPanel m_LogPanel = new LogPanel(new WekaTaskMonitor()); /** Whether the log is visible in the current perspective */ protected boolean m_logVisible; /** * Constructor * * @param mainApp the application that owns this perspective manager * @param perspectivePrefixesToAllow a list of perspective class name prefixes * that are to be allowed in this perspective manager. Any * perspectives not covered by this list are ignored. An empty list * means allow all. */ public PerspectiveManager(GUIApplication mainApp, String... perspectivePrefixesToAllow) { this(mainApp, perspectivePrefixesToAllow, new String[0]); } /** * Constructor * * @param mainApp the application that owns this perspective manager * @param perspectivePrefixesToAllow a list of perspective class name prefixes * that are to be allowed in this perspective manager. Any * perspectives not covered by this list are ignored. An empty list * means allow all. * @param perspectivePrefixesToDisallow a list of perspective class name * prefixes that are disallowed in this perspective manager. Any * matches in this list are prevented from appearing in this * perspective manager. Overrides a successful match in the allowed * list. This enables fine-grained exclusion of perspectives (e.g. * allowed might specify all perspectives in weka.gui.funky, while * disallowed vetoes just weka.gui.funky.NonFunkyPerspective.) */ public PerspectiveManager(GUIApplication mainApp, String[] perspectivePrefixesToAllow, String[] perspectivePrefixesToDisallow) { if (perspectivePrefixesToAllow != null) { for (String prefix : perspectivePrefixesToAllow) { m_allowedPerspectiveClassPrefixes.add(prefix); } } if (perspectivePrefixesToDisallow != null) { for (String prefix : perspectivePrefixesToDisallow) { m_disallowedPerspectiveClassPrefixes.add(prefix); } } m_mainApp = mainApp; final Settings settings = m_mainApp.getApplicationSettings(); m_mainPerspective = m_mainApp.getMainPerspective(); // apply defaults for the main perspective settings.applyDefaults(m_mainPerspective.getDefaultSettings()); setLayout(new BorderLayout()); m_configAndPerspectivesToolBar = new JPanel(); m_configAndPerspectivesToolBar.setLayout(new BorderLayout()); m_perspectiveToolBar.setLayout(new WrapLayout(FlowLayout.LEFT, 0, 0)); m_configAndPerspectivesToolBar.add(m_perspectiveToolBar, BorderLayout.CENTER); m_mainPerspective.setMainApplication(m_mainApp); m_perspectives.add(m_mainPerspective); initPerspectivesCache(settings); initVisiblePerspectives(settings); add((JComponent) m_mainPerspective, BorderLayout.CENTER); // The program menu m_programMenu = initProgramMenu(); // add the main perspective's toggle button to the toolbar String titleM = m_mainPerspective.getPerspectiveTitle(); Icon icon = m_mainPerspective.getPerspectiveIcon(); JToggleButton tBut = new JToggleButton(titleM, icon, true); tBut.setToolTipText(m_mainPerspective.getPerspectiveTipText()); tBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Component[] comps = getComponents(); Perspective current = null; int pIndex = 0; for (int i = 0; i < comps.length; i++) { if (comps[i] instanceof Perspective) { pIndex = i; current = (Perspective) comps[i]; break; } } if (current == m_mainPerspective) { return; } current.setActive(false); remove(pIndex); add((JComponent) m_mainPerspective, BorderLayout.CENTER); m_perspectives.get(0).setActive(true); m_appMenuBar.removeAll(); m_appMenuBar.add(m_programMenu); List<JMenu> mainMenus = m_perspectives.get(0).getMenus(); for (JMenu m : mainMenus) { m_appMenuBar.add(m); } m_mainApp.revalidate(); } }); m_perspectiveToolBar.add(tBut); m_perspectiveGroup.add(tBut); setupUserPerspectives(); initLogPanel(settings); if (m_mainPerspective.requiresLog()) { m_mainPerspective.setLog(m_LogPanel); add(m_LogPanel, BorderLayout.SOUTH); m_logVisible = true; } // tell the main perspective that it is active (i.e. main app is now // available and it can access settings). m_mainPerspective.setActive(true); // make sure any initial general settings are applied m_mainApp.settingsChanged(); } /** * Apply settings to the log panel * * @param settings settings to apply */ protected void setLogSettings(Settings settings) { int fontSize = settings.getSetting(m_mainApp.getApplicationID(), new Settings.SettingKey(m_mainApp.getApplicationID() + ".logMessageFontSize", "", ""), -1); m_LogPanel.setLoggingFontSize(fontSize); } /** * Initialize the log panel */ protected void initLogPanel(Settings settings) { setLogSettings(settings); String date = (new SimpleDateFormat("EEEE, d MMMM yyyy")).format(new Date()); m_LogPanel.logMessage("Weka " + m_mainApp.getApplicationName()); m_LogPanel.logMessage("(c) " + Copyright.getFromYear() + "-" + Copyright.getToYear() + " " + Copyright.getOwner() + ", " + Copyright.getAddress()); m_LogPanel.logMessage("web: " + Copyright.getURL()); m_LogPanel.logMessage("Started on " + date); m_LogPanel.statusMessage("Welcome to the Weka " + m_mainApp.getApplicationName()); } /** * Set the main application on all perspectives managed by this manager */ public void setMainApplicationForAllPerspectives() { // set main application on all cached perspectives and then tell // each that instantiation is complete for (Map.Entry<String, Perspective> e : m_perspectiveCache.entrySet()) { e.getValue().setMainApplication(m_mainApp); } for (Map.Entry<String, Perspective> e : m_perspectiveCache.entrySet()) { // instantiation is complete at this point - the perspective now // has access to the main application and the PerspectiveManager e.getValue().instantiationComplete(); if (e.getValue().requiresLog()) { e.getValue().setLog(m_LogPanel); } } m_mainPerspective.setMainApplication(m_mainApp); m_mainPerspective.instantiationComplete(); } /** * Notify all perspectives of a change to the application settings */ protected void notifySettingsChanged() { m_mainApp.settingsChanged(); m_mainPerspective.settingsChanged(); for (Map.Entry<String, Perspective> e : m_perspectiveCache.entrySet()) { e.getValue().settingsChanged(); } setLogSettings(m_mainApp.getApplicationSettings()); } /** * Initialize the program menu * * @return the JMenu item for the program menu */ protected JMenu initProgramMenu() { JMenu programMenu = new JMenu(); m_togglePerspectivesToolBar = new JMenuItem("Toggle perspectives toolbar"); KeyStroke hideKey = KeyStroke.getKeyStroke(KeyEvent.VK_P, InputEvent.ALT_DOWN_MASK); m_togglePerspectivesToolBar.setAccelerator(hideKey); m_togglePerspectivesToolBar.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (m_mainApp.isPerspectivesToolBarVisible()) { m_mainApp.hidePerspectivesToolBar(); } else { m_mainApp.showPerspectivesToolBar(); } m_mainApp.revalidate(); } }); programMenu.add(m_togglePerspectivesToolBar); programMenu.setText("Program"); JMenuItem exitItem = new JMenuItem("Exit"); KeyStroke exitKey = KeyStroke.getKeyStroke(KeyEvent.VK_Q, InputEvent.CTRL_DOWN_MASK); exitItem.setAccelerator(exitKey); exitItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ((Frame) ((JComponent) m_mainApp).getTopLevelAncestor()).dispose(); System.exit(0); } }); programMenu.add(exitItem); m_appMenuBar.add(programMenu); List<JMenu> mainMenus = m_mainPerspective.getMenus(); for (JMenu m : mainMenus) { m_appMenuBar.add(m); } return programMenu; } /** * Set whether the perspectives toolbar should always be hidden. This allows * just menu-based access to the perspectives and their settings * * @param settings the settings object to set this property on */ public void setPerspectiveToolbarAlwaysHidden(Settings settings) { SelectedPerspectivePreferences userVisiblePerspectives = settings.getSetting(m_mainApp.getApplicationID(), VISIBLE_PERSPECTIVES_KEY, new SelectedPerspectivePreferences(), Environment.getSystemWide()); userVisiblePerspectives.setPerspectivesToolbarAlwaysHidden(true); setPerspectiveToolBarIsVisible(false); m_programMenu.remove(m_togglePerspectivesToolBar); } /** * Applications can call this to allow access to the settings editor from the * program menu (in addition to the toolbar widget that pops up the settings * editor) * * @param settings the settings object for the application */ public void addSettingsMenuItemToProgramMenu(final Settings settings) { if (settings != null) { JMenuItem settingsM = new JMenuItem("Settings..."); settingsM.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { popupSettingsDialog(settings); } }); m_programMenu.insert(settingsM, 0); } JButton configB = new JButton(new ImageIcon(loadIcon( MainKFPerspectiveToolBar.ICON_PATH + "cog.png").getImage())); configB.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 1)); configB.setToolTipText("Settings"); m_configAndPerspectivesToolBar.add(configB, BorderLayout.WEST); configB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { popupSettingsDialog(settings); } }); } /** * Popup the settings editor dialog * * @param settings the settings to edit */ protected void popupSettingsDialog(final Settings settings) { final SettingsEditor settingsEditor = new SettingsEditor(settings, m_mainApp); try { int result = SettingsEditor.showApplicationSettingsEditor(settings, m_mainApp); if (result == JOptionPane.OK_OPTION) { initVisiblePerspectives(settings); setupUserPerspectives(); notifySettingsChanged(); } } catch (IOException ex) { m_mainApp.showErrorDialog(ex); } } /** * Creates a button on the toolbar for each visible perspective */ protected void setupUserPerspectives() { // first clear the toolbar for (int i = m_perspectiveToolBar.getComponentCount() - 1; i > 0; i--) { m_perspectiveToolBar.remove(i); m_perspectives.remove(i); } int index = 1; for (String c : m_visiblePerspectives) { String impl = m_perspectiveNameLookup.get(c); Perspective toAdd = m_perspectiveCache.get(impl); if (toAdd instanceof JComponent) { toAdd.setLoaded(true); m_perspectives.add(toAdd); String titleM = toAdd.getPerspectiveTitle(); Icon icon = toAdd.getPerspectiveIcon(); JToggleButton tBut = null; if (icon != null) { tBut = new JToggleButton(titleM, icon, false); } else { tBut = new JToggleButton(titleM, false); } tBut.setToolTipText(toAdd.getPerspectiveTipText()); final int theIndex = index; tBut.setEnabled(toAdd.okToBeActive()); tBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setActivePerspective(theIndex); } }); m_perspectiveToolBar.add(tBut); m_perspectiveGroup.add(tBut); index++; } } Component[] comps = getComponents(); Perspective current = null; int pIndex = 0; for (int i = 0; i < comps.length; i++) { if (comps[i] instanceof Perspective) { pIndex = i; current = (Perspective) comps[i]; break; } } if (current != m_mainPerspective) { setActivePerspective(0); } m_mainApp.revalidate(); } /** * Set the active perspective * * @param theIndex the index of the perspective to make the active one */ public void setActivePerspective(int theIndex) { if (theIndex < 0 || theIndex > m_perspectives.size() - 1) { return; } Component[] comps = getComponents(); Perspective current = null; int pIndex = 0; for (int i = 0; i < comps.length; i++) { if (comps[i] instanceof Perspective) { pIndex = i; current = (Perspective) comps[i]; break; } } current.setActive(false); remove(pIndex); add((JComponent) m_perspectives.get(theIndex), BorderLayout.CENTER); m_perspectives.get(theIndex).setActive(true); ((JToggleButton) m_perspectiveToolBar.getComponent(theIndex)) .setSelected(true); if (((Perspective) m_perspectives.get(theIndex)).requiresLog() && !m_logVisible) { add(m_LogPanel, BorderLayout.SOUTH); m_logVisible = true; } else if (!((Perspective) m_perspectives.get(theIndex)).requiresLog() && m_logVisible) { remove(m_LogPanel); m_logVisible = false; } JMenu programMenu = m_appMenuBar.getMenu(0); m_appMenuBar.removeAll(); m_appMenuBar.add(programMenu); List<JMenu> mainMenus = m_perspectives.get(theIndex).getMenus(); if (mainMenus != null) { for (JMenu m : mainMenus) { m_appMenuBar.add(m); } } m_mainApp.revalidate(); } /** * Set the active perspective * * @param perspectiveID the ID of the perspective to make the active one */ public void setActivePerspective(String perspectiveID) { int index = -1; for (int i = 0; i < m_perspectives.size(); i++) { if (m_perspectives.get(i).getPerspectiveID().equals(perspectiveID)) { index = i; break; } } if (index >= 0) { setActivePerspective(index); } } /** * Get a list of all loaded perspectives. I.e. all perspectives that this * manager knows about. Note that this list does not include the main * application perspective - use getMainPerspective() to retrieve this. * * @return a list of all loaded (but not necessary visible) perspectives */ public List<Perspective> getLoadedPerspectives() { List<Perspective> available = new ArrayList<Perspective>(); for (Map.Entry<String, Perspective> e : m_perspectiveCache.entrySet()) { available.add(e.getValue()); } return available; } /** * Get a list of visible perspectives. I.e. those that are available to be * selected in the perspective toolbar * * @return a list of visible perspectives */ public List<Perspective> getVisiblePerspectives() { List<Perspective> visible = new ArrayList<Perspective>(); for (String pName : m_visiblePerspectives) { String impl = m_perspectiveNameLookup.get(pName); Perspective p = m_perspectiveCache.get(impl); if (p != null) { visible.add(p); } } return visible; } /** * Loads perspectives and initializes the cache. * * @param settings the settings object in which to store default settings from * each loaded perspective */ protected void initPerspectivesCache(Settings settings) { Set<String> pluginPerspectiveImpls = PluginManager.getPluginNamesOfType(PERSPECTIVE_INTERFACE); if (pluginPerspectiveImpls != null) { for (String impl : pluginPerspectiveImpls) { if (!impl.equals(m_mainPerspective.getClass().getCanonicalName())) { try { Object perspective = PluginManager.getPluginInstance(PERSPECTIVE_INTERFACE, impl); if (!(perspective instanceof Perspective)) { weka.core.logging.Logger.log(Logger.Level.WARNING, "[PerspectiveManager] " + impl + " is not an instance" + PERSPECTIVE_INTERFACE + ". Skipping..."); } boolean ok = true; if (m_allowedPerspectiveClassPrefixes.size() > 0) { ok = false; for (String prefix : m_allowedPerspectiveClassPrefixes) { if (impl.startsWith(prefix)) { ok = true; break; } } } if (m_disallowedPerspectiveClassPrefixes.size() > 0) { for (String prefix : m_disallowedPerspectiveClassPrefixes) { if (impl.startsWith(prefix)) { ok = false; break; } } } if (impl.equals(m_mainPerspective.getClass().getCanonicalName())) { // main perspective is always part of the application and we dont // want it to appear as an option in the list of perspectives to // choose from in the preferences dialog ok = false; } if (ok) { m_perspectiveCache.put(impl, (Perspective) perspective); String perspectiveTitle = ((Perspective) perspective).getPerspectiveTitle(); m_perspectiveNameLookup.put(perspectiveTitle, impl); settings.applyDefaults(((Perspective) perspective) .getDefaultSettings()); } } catch (Exception e) { e.printStackTrace(); m_mainApp.showErrorDialog(e); } } } } } /** * Initializes the visible perspectives. Makes sure that default settings for * each perspective get added to the application-wide settings object. * * @param settings the settings object for the owner application */ protected void initVisiblePerspectives(Settings settings) { m_visiblePerspectives.clear(); if (m_perspectiveCache.size() > 0) { Map<Settings.SettingKey, Object> defaults = new LinkedHashMap<Settings.SettingKey, Object>(); SelectedPerspectivePreferences defaultEmpty = new SelectedPerspectivePreferences(); defaults.put(VISIBLE_PERSPECTIVES_KEY, defaultEmpty); Defaults mainAppPerspectiveDefaults = new Defaults(m_mainApp.getApplicationID(), defaults); settings.applyDefaults(mainAppPerspectiveDefaults); SelectedPerspectivePreferences userVisiblePerspectives = settings.getSetting(m_mainApp.getApplicationID(), VISIBLE_PERSPECTIVES_KEY, new SelectedPerspectivePreferences(), Environment.getSystemWide()); if (userVisiblePerspectives == defaultEmpty) { // no stored settings for this yet. We should start with // all perspectives visible for (Map.Entry<String, Perspective> e : m_perspectiveCache.entrySet()) { userVisiblePerspectives.getUserVisiblePerspectives().add( e.getValue().getPerspectiveTitle()); } userVisiblePerspectives.setPerspectivesToolbarVisibleOnStartup(true); } for (String userVisPer : userVisiblePerspectives .getUserVisiblePerspectives()) { m_visiblePerspectives.add(userVisPer); } } } /** * Get the panel that contains the perspectives toolbar * * @return the panel that contains the perspecitves toolbar */ public JPanel getPerspectiveToolBar() { return m_configAndPerspectivesToolBar; } /** * Disable the tab/button for each visible perspective */ public void disableAllPerspectiveTabs() { for (int i = 0; i < m_perspectiveToolBar.getComponentCount(); i++) { m_perspectiveToolBar.getComponent(i).setEnabled(false); } } /** * Enable the tab/button for each visible perspective */ public void enableAllPerspectiveTabs() { for (int i = 0; i < m_perspectiveToolBar.getComponentCount(); i++) { m_perspectiveToolBar.getComponent(i).setEnabled(true); } } /** * Enable/disable the tab/button for each perspective in the supplied list of * perspective IDs * * @param perspectiveIDs the list of perspective IDs * @param enabled true or false to enable or disable the perspective buttons */ public void setEnablePerspectiveTabs(List<String> perspectiveIDs, boolean enabled) { for (int i = 0; i < m_perspectives.size(); i++) { Perspective p = m_perspectives.get(i); if (perspectiveIDs.contains(p.getPerspectiveID())) { m_perspectiveToolBar.getComponent(i).setEnabled(enabled); } } } /** * Enable/disable a perspective's button/tab * * @param perspectiveID the ID of the perspective to enable/disable * @param enabled true or false to enable or disable */ public void setEnablePerspectiveTab(String perspectiveID, boolean enabled) { for (int i = 0; i < m_perspectives.size(); i++) { Perspective p = m_perspectives.get(i); if (p.getPerspectiveID().equals(perspectiveID) && p.okToBeActive()) { m_perspectiveToolBar.getComponent(i).setEnabled(enabled); } } } /** * Returns true if the perspective toolbar is visible * * @return true if the perspective toolbar is visible */ public boolean perspectiveToolBarIsVisible() { return m_configAndPerspectivesVisible; } public void setPerspectiveToolBarIsVisible(boolean v) { m_configAndPerspectivesVisible = v; } /** * Get the main application perspective. This is the perspective that is * visible on startup of the application and is usually the entry point for * the application. * * @return the main perspective */ public Perspective getMainPerspective() { return m_mainPerspective; } /** * Get the perspective with the given ID * * @param ID the ID of the perspective to get * @return the perspective, or null if there is no perspective with the * supplied ID */ public Perspective getPerspective(String ID) { Perspective perspective = null; for (Perspective p : m_perspectives) { if (p.getPerspectiveID().equals(ID)) { perspective = p; break; } } return perspective; } /** * Tell the perspective manager to show the menu bar * * @param topLevelAncestor the owning application's Frame */ public void showMenuBar(JFrame topLevelAncestor) { topLevelAncestor.setJMenuBar(m_appMenuBar); } /** * Returns true if the user has requested that the perspective toolbar is * visible when the application starts up * * @param settings the settings object for the application * @return true if the user has specified that the perspective toolbar should * be visible when the application first starts up */ public boolean userRequestedPerspectiveToolbarVisibleOnStartup( Settings settings) { SelectedPerspectivePreferences perspectivePreferences = settings.getSetting(m_mainApp.getApplicationID(), VISIBLE_PERSPECTIVES_KEY, new SelectedPerspectivePreferences(), Environment.getSystemWide()); return perspectivePreferences.getPerspectivesToolbarVisibleOnStartup(); } /** * Class to manage user preferences with respect to visible perspectives and * whether the perspectives toolbar is always hidden or is visible on * application startup */ public static class SelectedPerspectivePreferences implements java.io.Serializable { private static final long serialVersionUID = -2665480123235382483L; /** List of user selected perspectives to show */ protected LinkedList<String> m_userVisiblePerspectives = new LinkedList<String>(); /** Whether the toolbar should be visible (or hidden) at startup */ protected boolean m_perspectivesToolbarVisibleOnStartup; /** * Whether the toolbar should always be hidden (and not able to be toggled * from the menu or widget. */ protected boolean m_perspectivesToolbarAlwaysHidden; /** * Set a list of perspectives that should be visible * * @param userVisiblePerspectives */ public void setUserVisiblePerspectives( LinkedList<String> userVisiblePerspectives) { m_userVisiblePerspectives = userVisiblePerspectives; } /** * Get the list of perspectives that the user has specified should be * visible in the application * * @return the list of visible perspectives */ public LinkedList<String> getUserVisiblePerspectives() { return m_userVisiblePerspectives; } /** * Set whether the perspectives toolbar should be visible in the GUI at * application startup * * @param v true if the perspectives toolbar should be visible at * application startup */ public void setPerspectivesToolbarVisibleOnStartup(boolean v) { m_perspectivesToolbarVisibleOnStartup = v; } /** * Get whether the perspectives toolbar should be visible in the GUI at * application startup * * @return true if the perspectives toolbar should be visible at application * startup */ public boolean getPerspectivesToolbarVisibleOnStartup() { return m_perspectivesToolbarVisibleOnStartup; } /** * Set whether the perspectives toolbar should always be hidden * * @param h true if the perspectives toolbar should always be hidden */ public void setPerspectivesToolbarAlwaysHidden(boolean h) { m_perspectivesToolbarAlwaysHidden = h; } /** * Get whether the perspectives toolbar should always be hidden * * @return true if the perspectives toolbar should always be hidden */ public boolean getPerspectivesToolbarAlwaysHidden() { return m_perspectivesToolbarAlwaysHidden; } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/ProgrammaticProperty.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ProgrammaticProperty.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.lang.annotation.*; /** * Method annotation that can be used with bean properties that are to be considered as * programmatic only (i.e. they should not be exposed by the GenericObjectEditor * in GUI config dialogs). * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface ProgrammaticProperty { }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/PropertyDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * PropertyDialog.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Container; import java.awt.Dialog; import java.awt.Frame; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.PropertyEditor; import javax.swing.JDialog; import javax.swing.JInternalFrame; /** * Support for PropertyEditors with custom editors: puts the editor into * a separate frame. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public class PropertyDialog extends JDialog { /** for serialization. */ private static final long serialVersionUID = -2314850859392433539L; /** The property editor. */ private PropertyEditor m_Editor; /** The custom editor component. */ private Component m_EditorComponent; /** * Creates the editor frame - only kept for backward-compatibility. * * @param pe the PropertyEditor * @param x initial x coord for the frame * @param y initial y coord for the frame * @deprecated instead of this constructor, one should use the constructors * with an explicit owner (either derived from * <code>java.awt.Dialog</code> or from * <code>java.awt.Frame</code>) or, if none available, * using <code>(Frame) null</code> as owner. */ public PropertyDialog(PropertyEditor pe, int x, int y) { this((Frame) null, pe, x, y); setVisible(true); } /** * Creates the (screen-centered) editor dialog. The dialog is automatically * modal in case the owner is non-null. * * @param owner the dialog that opens this dialog * @param pe the PropertyEditor */ public PropertyDialog(Dialog owner, PropertyEditor pe) { this(owner, pe, -1, -1); } /** * Creates the editor dialog at the given position. The dialog is automatically * modal in case the owner is non-null. * * @param owner the dialog that opens this dialog * @param pe the PropertyEditor * @param x initial x coord for the dialog * @param y initial y coord for the dialog */ public PropertyDialog(Dialog owner, PropertyEditor pe, int x, int y) { super(owner, pe.getClass().getName(), ModalityType.DOCUMENT_MODAL); initialize(pe, x, y); } /** * Creates the (screen-centered) editor dialog. The dialog is automatically * modal in case the owner is non-null. * * @param owner the frame that opens this dialog * @param pe the PropertyEditor */ public PropertyDialog(Frame owner, PropertyEditor pe) { this(owner, pe, -1, -1); } /** * Creates the editor dialog at the given position. The dialog is automatically * modal in case the owner is non-null. * * @param owner the frame that opens this dialog * @param pe the PropertyEditor * @param x initial x coord for the dialog * @param y initial y coord for the dialog */ public PropertyDialog(Frame owner, PropertyEditor pe, int x, int y) { super(owner, pe.getClass().getName(), ModalityType.DOCUMENT_MODAL); initialize(pe, x, y); } /** * Initializes the dialog. * * @param pe the PropertyEditor * @param x initial x coord for the dialog * @param y initial y coord for the dialog */ protected void initialize(PropertyEditor pe, int x, int y) { addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { e.getWindow().dispose(); } }); getContentPane().setLayout(new BorderLayout()); m_Editor = pe; m_EditorComponent = pe.getCustomEditor(); getContentPane().add(m_EditorComponent, BorderLayout.CENTER); pack(); int screenWidth = getGraphicsConfiguration().getBounds().width; int screenHeight = getGraphicsConfiguration().getBounds().height; // adjust height to a maximum of 95% of screen height if (getHeight() > (double) screenHeight * 0.95) setSize(getWidth(), (int) ((double) screenHeight * 0.95)); if ((x == -1) && (y == -1)) { setLocationRelativeTo(getOwner()); } else { // adjust position if necessary if (x + getWidth() > screenWidth) x = screenWidth - getWidth(); if (y + getHeight() > screenHeight) y = screenHeight - getHeight(); setLocation(x, y); } } /** * Gets the current property editor. * * @return a value of type 'PropertyEditor' */ public PropertyEditor getEditor() { return m_Editor; } /** * Tries to determine the frame this panel is part of. * * @param c the container to start with * @return the parent frame if one exists or null if not */ public static Frame getParentFrame(Container c) { Frame result; Container parent; result = null; parent = c; while (parent != null) { if (parent instanceof Frame) { result = (Frame) parent; break; } else { parent = parent.getParent(); } } return result; } /** * Tries to determine the internal frame this panel is part of. * * @param c the container to start with * @return the parent internal frame if one exists or null if not */ public static JInternalFrame getParentInternalFrame(Container c) { JInternalFrame result; Container parent; result = null; parent = c; while (parent != null) { if (parent instanceof JInternalFrame) { result = (JInternalFrame) parent; break; } else { parent = parent.getParent(); } } return result; } /** * Tries to determine the dialog this panel is part of. * * @param c the container to start with * @return the parent dialog if one exists or null if not */ public static Dialog getParentDialog(Container c) { Dialog result; Container parent; result = null; parent = c; while (parent != null) { if (parent instanceof Dialog) { result = (Dialog) parent; break; } else { parent = parent.getParent(); } } return result; } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/PropertyPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * PropertyPanel.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Insets; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyEditor; import java.lang.reflect.Array; import javax.swing.BorderFactory; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import weka.core.OptionHandler; import weka.core.Utils; import weka.gui.GenericObjectEditorHistory.HistorySelectionEvent; import weka.gui.GenericObjectEditorHistory.HistorySelectionListener; /** * Support for drawing a property value in a component. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @author Richard Kirkby (rkirkby@cs.waikato.ac.nz) * @version $Revision$ */ public class PropertyPanel extends JPanel { /** for serialization */ static final long serialVersionUID = 5370025273466728904L; /** The property editor */ private final PropertyEditor m_Editor; /** The currently displayed property dialog, if any */ private PropertyDialog m_PD; /** Whether the editor has provided its own panel */ private boolean m_HasCustomPanel = false; /** The custom panel (if any) */ private JPanel m_CustomPanel; /** * Create the panel with the supplied property editor. * * @param pe the PropertyEditor */ public PropertyPanel(PropertyEditor pe) { this(pe, false); } /** * Create the panel with the supplied property editor, optionally ignoring any * custom panel the editor can provide. * * @param pe the PropertyEditor * @param ignoreCustomPanel whether to make use of any available custom panel */ public PropertyPanel(PropertyEditor pe, boolean ignoreCustomPanel) { m_Editor = pe; if (!ignoreCustomPanel && m_Editor instanceof CustomPanelSupplier) { setLayout(new BorderLayout()); m_CustomPanel = ((CustomPanelSupplier) m_Editor).getCustomPanel(); add(m_CustomPanel, BorderLayout.CENTER); m_HasCustomPanel = true; } else { createDefaultPanel(); } } /** * Creates the default style of panel for editors that do not supply their * own. */ protected void createDefaultPanel() { setBorder(BorderFactory.createEtchedBorder()); setToolTipText("Left-click to edit properties for this object, right-click/Alt+Shift+left-click for menu"); setOpaque(true); final Component comp = this; addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent evt) { if (evt.getClickCount() == 1) { if ((evt.getButton() == MouseEvent.BUTTON1) && !evt.isAltDown() && !evt.isShiftDown()) { showPropertyDialog(); } else if ((evt.getButton() == MouseEvent.BUTTON3) || ((evt.getButton() == MouseEvent.BUTTON1) && evt.isAltDown() && evt .isShiftDown())) { JPopupMenu menu = new JPopupMenu(); JMenuItem item; if (m_Editor.getValue() != null) { item = new JMenuItem("Show properties..."); item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showPropertyDialog(); } }); menu.add(item); item = new JMenuItem("Copy configuration to clipboard"); item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object value = m_Editor.getValue(); String str = ""; if (value.getClass().isArray()) { str += value.getClass().getName(); Object[] arr = (Object[])value; for (Object v : arr) { String s = v.getClass().getName(); if (v instanceof OptionHandler) { s += " " + Utils.joinOptions(((OptionHandler) v).getOptions()); } str += " \"" + Utils.backQuoteChars(s.trim()) + "\""; } } else { str += value.getClass().getName(); if (value instanceof OptionHandler) { str += " " + Utils.joinOptions(((OptionHandler) value).getOptions()); } } StringSelection selection = new StringSelection(str.trim()); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(selection, selection); } }); menu.add(item); } item = new JMenuItem("Enter configuration..."); item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String str = JOptionPane.showInputDialog(comp, "Configuration (<classname> [<options>])"); if (str != null && str.length() > 0) { try { String[] options = Utils.splitOptions(str); String classname = options[0]; options[0] = ""; Class c = Utils.forName(Object.class, classname, null).getClass(); if (c.isArray()) { Object[] arr = (Object[])Array.newInstance(c.getComponentType(), options.length - 1); for (int i = 1; i < options.length; i++) { String[] ops = Utils.splitOptions(options[i]); String cname = ops[0]; ops[0] = ""; arr[i - 1] = Utils.forName(Object.class, cname, ops); } m_Editor.setValue(arr); } else { m_Editor.setValue(Utils.forName(Object.class, classname, options)); } } catch (Exception ex) { JOptionPane.showMessageDialog(comp, "Error parsing commandline:\n" + ex, "Error...", JOptionPane.ERROR_MESSAGE); } } } }); menu.add(item); if (m_Editor.getValue() instanceof OptionHandler) { item = new JMenuItem("Edit configuration..."); item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String str = m_Editor.getValue().getClass().getName(); str += " " + Utils.joinOptions(((OptionHandler) m_Editor.getValue()) .getOptions()); str = JOptionPane.showInputDialog(comp, "Configuration", str); if (str != null && str.length() > 0) { try { String[] options = Utils.splitOptions(str); String classname = options[0]; options[0] = ""; m_Editor.setValue(Utils.forName(Object.class, classname, options)); } catch (Exception ex) { JOptionPane.showMessageDialog(comp, "Error parsing commandline:\n" + ex, "Error...", JOptionPane.ERROR_MESSAGE); } } } }); menu.add(item); } if (m_Editor instanceof GenericObjectEditor) { ((GenericObjectEditor) m_Editor).getHistory().customizePopupMenu( menu, m_Editor.getValue(), new HistorySelectionListener() { @Override public void historySelected(HistorySelectionEvent e) { m_Editor.setValue(e.getHistoryItem()); } }); } menu.show(comp, evt.getX(), evt.getY()); } } } }); Dimension newPref = getPreferredSize(); newPref.height = getFontMetrics(getFont()).getHeight() * 5 / 4; newPref.width = newPref.height * 5; setPreferredSize(newPref); m_Editor.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { repaint(); } }); } /** * Displays the property edit dialog for the panel. */ public void showPropertyDialog() { if (m_Editor.getValue() != null) { if (m_PD == null) { if (PropertyDialog.getParentDialog(this) != null) m_PD = new PropertyDialog(PropertyDialog.getParentDialog(this), m_Editor, -1, -1); else m_PD = new PropertyDialog(PropertyDialog.getParentFrame(this), m_Editor, -1, -1); m_PD.setVisible(true); } else { if (PropertyDialog.getParentDialog(this) != null) { m_PD.setLocationRelativeTo(PropertyDialog.getParentDialog(this)); } else { m_PD.setLocationRelativeTo(PropertyDialog.getParentFrame(this)); } m_PD.setVisible(true); } // make sure that m_Backup is correctly initialized! m_Editor.setValue(m_Editor.getValue()); } } /** * Cleans up when the panel is destroyed. */ @Override public void removeNotify() { super.removeNotify(); if (m_PD != null) { m_PD.dispose(); m_PD = null; } } /** * Passes on enabled/disabled status to the custom panel (if one is set). * * @param enabled true if this panel (and the custom panel is enabled) */ @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); if (m_HasCustomPanel) { m_CustomPanel.setEnabled(enabled); } } /** * Paints the component, using the property editor's paint method. * * @param g the current graphics context */ @Override public void paintComponent(Graphics g) { if (!m_HasCustomPanel) { Insets i = getInsets(); Rectangle box = new Rectangle(i.left, i.top, getSize().width - i.left - i.right - 1, getSize().height - i.top - i.bottom - 1); g.clearRect(i.left, i.top, getSize().width - i.right - i.left, getSize().height - i.bottom - i.top); m_Editor.paintValue(g, box); } } /** * Adds the current editor value to the history. * * @return true if successfully added (i.e., if editor is a GOE) */ public boolean addToHistory() { return addToHistory(m_Editor.getValue()); } /** * Adds the specified value to the history. * * @param obj the object to add to the history * @return true if successfully added (i.e., if editor is a GOE) */ public boolean addToHistory(Object obj) { if ((m_Editor instanceof GenericObjectEditor) && (obj != null)) { ((GenericObjectEditor) m_Editor).getHistory().add(obj); return true; } return false; } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/PropertySelectorDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * PropertySelectorDialog.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.beans.PropertyEditor; import java.beans.PropertyEditorManager; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import weka.experiment.PropertyNode; /** * Allows the user to select any (supported) property of an object, including * properties that any of it's property values may have. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public class PropertySelectorDialog extends JDialog { /** for serialization */ private static final long serialVersionUID = -3155058124137930518L; /** Click to choose the currently selected property */ protected JButton m_SelectBut = new JButton("Select"); /** Click to cancel the property selection */ protected JButton m_CancelBut = new JButton("Cancel"); /** The root of the property tree */ protected DefaultMutableTreeNode m_Root; /** The object at the root of the tree */ protected Object m_RootObject; /** Whether the selection was made or cancelled */ protected int m_Result; /** Stores the path to the selected property */ protected Object[] m_ResultPath; /** The component displaying the property tree */ protected JTree m_Tree; /** Signifies an OK property selection */ public static final int APPROVE_OPTION = 0; /** Signifies a cancelled property selection */ public static final int CANCEL_OPTION = 1; /** * Create the property selection dialog. * * @param parentFrame the parent frame of the dialog * @param rootObject the object containing properties to select from */ public PropertySelectorDialog(Frame parentFrame, Object rootObject) { super(parentFrame, "Select a property", ModalityType.DOCUMENT_MODAL); m_CancelBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_Result = CANCEL_OPTION; setVisible(false); } }); m_SelectBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // value = path from root to selected; TreePath tPath = m_Tree.getSelectionPath(); if (tPath == null) { m_Result = CANCEL_OPTION; } else { m_ResultPath = tPath.getPath(); if ((m_ResultPath == null) || (m_ResultPath.length < 2)) { m_Result = CANCEL_OPTION; } else { m_Result = APPROVE_OPTION; } } setVisible(false); } }); m_RootObject = rootObject; m_Root = new DefaultMutableTreeNode(new PropertyNode(m_RootObject)); createNodes(m_Root); Container c = getContentPane(); c.setLayout(new BorderLayout()); // setBorder(BorderFactory.createTitledBorder("Select a property")); Box b1 = new Box(BoxLayout.X_AXIS); b1.add(m_SelectBut); b1.add(Box.createHorizontalStrut(10)); b1.add(m_CancelBut); c.add(b1, BorderLayout.SOUTH); m_Tree = new JTree(m_Root); m_Tree.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION); c.add(new JScrollPane(m_Tree), BorderLayout.CENTER); pack(); setLocationRelativeTo(parentFrame); } /** * Pops up the modal dialog and waits for cancel or a selection. * * @return either APPROVE_OPTION, or CANCEL_OPTION */ public int showDialog() { m_Result = CANCEL_OPTION; setVisible(true); return m_Result; } /** * Gets the path of property nodes to the selected property. * * @return an array of PropertyNodes */ public PropertyNode[] getPath() { PropertyNode[] result = new PropertyNode[m_ResultPath.length - 1]; for (int i = 0; i < result.length; i++) { result[i] = (PropertyNode) ((DefaultMutableTreeNode) m_ResultPath[i + 1]) .getUserObject(); } return result; } /** * Creates the property tree below the current node. * * @param localNode a value of type 'DefaultMutableTreeNode' */ protected void createNodes(DefaultMutableTreeNode localNode) { PropertyNode pNode = (PropertyNode) localNode.getUserObject(); Object localObject = pNode.value; // Find all the properties of the object in the root node PropertyDescriptor localProperties[]; try { BeanInfo bi = Introspector.getBeanInfo(localObject.getClass()); localProperties = bi.getPropertyDescriptors(); } catch (IntrospectionException ex) { System.err.println("PropertySelectorDialog: Couldn't introspect"); return; } // Put their values into child nodes. for (PropertyDescriptor localPropertie : localProperties) { // Don't display hidden or expert properties. if (localPropertie.isHidden() || localPropertie.isExpert()) { continue; } String name = localPropertie.getDisplayName(); Class<?> type = localPropertie.getPropertyType(); Method getter = localPropertie.getReadMethod(); Method setter = localPropertie.getWriteMethod(); Object value = null; // Only display read/write properties. if (getter == null || setter == null) { continue; } try { Object args[] = {}; value = getter.invoke(localObject, args); PropertyEditor editor = null; Class<?> pec = localPropertie.getPropertyEditorClass(); if (pec != null) { try { editor = (PropertyEditor) pec.newInstance(); } catch (Exception ex) { } } if (editor == null) { editor = PropertyEditorManager.findEditor(type); } if ((editor == null) || (value == null)) { continue; } } catch (InvocationTargetException ex) { System.err.println("Skipping property " + name + " ; exception on target: " + ex.getTargetException()); ex.getTargetException().printStackTrace(); continue; } catch (Exception ex) { System.err.println("Skipping property " + name + " ; exception: " + ex); ex.printStackTrace(); continue; } // Make a child node DefaultMutableTreeNode child = new DefaultMutableTreeNode( new PropertyNode(value, localPropertie, localObject.getClass())); localNode.add(child); createNodes(child); } } /** * Tests out the property selector from the command line. * * @param args ignored */ public static void main(String[] args) { try { GenericObjectEditor.registerEditors(); Object rp = new weka.experiment.AveragingResultProducer(); final PropertySelectorDialog jd = new PropertySelectorDialog(null, rp); int result = jd.showDialog(); if (result == PropertySelectorDialog.APPROVE_OPTION) { System.err.println("Property Selected"); PropertyNode[] path = jd.getPath(); for (int i = 0; i < path.length; i++) { PropertyNode pn = path[i]; System.err.println("" + (i + 1) + " " + pn.toString() + " " + pn.value.toString()); } } else { System.err.println("Cancelled"); } System.exit(0); } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/PropertySheetPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * PropertySheet.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Font; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.BeanInfo; import java.beans.Beans; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.MethodDescriptor; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.beans.PropertyDescriptor; import java.beans.PropertyEditor; import java.beans.PropertyEditorManager; import java.beans.PropertyVetoException; import java.io.File; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.SwingConstants; import weka.core.*; import weka.gui.beans.GOECustomizer; /** * Displays a property sheet where (supported) properties of the target object * may be edited. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public class PropertySheetPanel extends JPanel implements PropertyChangeListener, EnvironmentHandler { /** for serialization. */ private static final long serialVersionUID = -8939835593429918345L; /** * A specialized dialog for displaying the capabilities. */ protected class CapabilitiesHelpDialog extends JDialog implements PropertyChangeListener { /** for serialization. */ private static final long serialVersionUID = -1404770987103289858L; /** the dialog itself. */ private CapabilitiesHelpDialog m_Self; /** * default constructor. * * @param owner the owning frame */ public CapabilitiesHelpDialog(Frame owner) { super(owner); initialize(); } /** * default constructor. * * @param owner the owning dialog */ public CapabilitiesHelpDialog(Dialog owner) { super(owner); initialize(); } /** * Initializes the dialog. */ protected void initialize() { setTitle("Information about Capabilities"); m_Self = this; m_CapabilitiesText = new JTextArea(); m_CapabilitiesText.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); m_CapabilitiesText.setLineWrap(true); m_CapabilitiesText.setWrapStyleWord(true); m_CapabilitiesText.setEditable(false); updateText(); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { m_Self.dispose(); if (m_CapabilitiesDialog == m_Self) { m_CapabilitiesBut.setEnabled(true); } } }); getContentPane().setLayout(new BorderLayout()); getContentPane().add(new JScrollPane(m_CapabilitiesText), BorderLayout.CENTER); pack(); setLocationRelativeTo(getOwner()); } /** * updates the content of the capabilities help dialog. */ protected void updateText() { StringBuffer helpText = new StringBuffer(); if (m_Target instanceof CapabilitiesHandler) { helpText.append(CapabilitiesUtils.addCapabilities("CAPABILITIES", ((CapabilitiesHandler) m_Target).getCapabilities())); } if (m_Target instanceof MultiInstanceCapabilitiesHandler) { helpText.append(CapabilitiesUtils.addCapabilities("MI CAPABILITIES", ((MultiInstanceCapabilitiesHandler) m_Target) .getMultiInstanceCapabilities())); } m_CapabilitiesText.setText(helpText.toString()); m_CapabilitiesText.setCaretPosition(0); } /** * This method gets called when a bound property is changed. * * @param evt the change event */ @Override public void propertyChange(PropertyChangeEvent evt) { updateText(); } } /** The target object being edited. */ private Object m_Target; /** Whether to show the about panel */ private boolean m_showAboutPanel = true; /** Holds the customizer (if one exists) for the object being edited */ private GOECustomizer m_Customizer; /** Holds properties of the target. */ private PropertyDescriptor m_Properties[]; /** Holds the methods of the target. */ private MethodDescriptor m_Methods[]; /** Holds property editors of the object. */ private PropertyEditor m_Editors[]; /** Holds current object values for each property. */ private Object m_Values[]; /** Stores GUI components containing each editing component. */ private JComponent m_Views[]; /** The labels for each property. */ private JLabel m_Labels[]; /** The tool tip text for each property. */ private String m_TipTexts[]; /** StringBuffer containing help text for the object being edited. */ private StringBuffer m_HelpText; /** Help dialog. */ private JDialog m_HelpDialog; /** Capabilities Help dialog. */ private CapabilitiesHelpDialog m_CapabilitiesDialog; /** Button to pop up the full help text in a separate dialog. */ private JButton m_HelpBut; /** Button to pop up the capabilities in a separate dialog. */ private JButton m_CapabilitiesBut; /** the TextArea of the Capabilities help dialog. */ private JTextArea m_CapabilitiesText; /** A count of the number of properties we have an editor for. */ private int m_NumEditable = 0; /** * The panel holding global info and help, if provided by the object being * editied. */ private JPanel m_aboutPanel; /** Environment variables to pass on to any editors that can handle them */ private transient Environment m_env; /** * Whether to use EnvironmentField and FileEnvironmentField for text and * file properties respectively */ private boolean m_useEnvironmentPropertyEditors; /** * Creates the property sheet panel with an about panel. */ public PropertySheetPanel() { // setBorder(BorderFactory.createLineBorder(Color.red)); setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0)); m_env = Environment.getSystemWide(); } /** * Creates the property sheet panel * * @param showAboutPanel true if the about panel is to be shown */ public PropertySheetPanel(boolean showAboutPanel) { super(); m_showAboutPanel = showAboutPanel; } /** * Set whether to use environment property editors for string and * file properties * * @param u true to use environment property editors */ public void setUseEnvironmentPropertyEditors(boolean u) { m_useEnvironmentPropertyEditors = u; } /** * Get whether to use environment property editors for string and * file properties * * @return true to use environment property editors */ public boolean getUseEnvironmentPropertyEditors() { return m_useEnvironmentPropertyEditors; } /** * Return the panel containing global info and help for the object being * edited. May return null if the edited object provides no global info or tip * text. * * @return the about panel. */ public JPanel getAboutPanel() { return m_aboutPanel; } /** A support object for handling property change listeners. */ private final PropertyChangeSupport support = new PropertyChangeSupport(this); /** * Updates the property sheet panel with a changed property and also passed * the event along. * * @param evt a value of type 'PropertyChangeEvent' */ @Override public void propertyChange(PropertyChangeEvent evt) { wasModified(evt); // Let our panel update before guys downstream support.firePropertyChange("", null, null); } /** * Adds a PropertyChangeListener. * * @param l a value of type 'PropertyChangeListener' */ @Override public void addPropertyChangeListener(PropertyChangeListener l) { if (support != null && l != null) { support.addPropertyChangeListener(l); } } /** * Removes a PropertyChangeListener. * * @param l a value of type 'PropertyChangeListener' */ @Override public void removePropertyChangeListener(PropertyChangeListener l) { if (support != null && l != null) { support.removePropertyChangeListener(l); } } /** * Sets a new target object for customisation. * * @param targ a value of type 'Object' */ public synchronized void setTarget(Object targ) { if (m_env == null) { m_env = Environment.getSystemWide(); } // used to offset the components for the properties of targ // if there happens to be globalInfo available in targ int componentOffset = 0; // Close any child windows at this point removeAll(); setLayout(new BorderLayout()); JPanel scrollablePanel = new JPanel(); JScrollPane scrollPane = new JScrollPane(scrollablePanel); scrollPane.setBorder(BorderFactory.createEmptyBorder()); add(scrollPane, BorderLayout.CENTER); GridBagLayout gbLayout = new GridBagLayout(); scrollablePanel.setLayout(gbLayout); setVisible(false); m_NumEditable = 0; m_Target = targ; Class<?> custClass = null; try { BeanInfo bi = Introspector.getBeanInfo(m_Target.getClass()); m_Properties = bi.getPropertyDescriptors(); m_Methods = bi.getMethodDescriptors(); custClass = Introspector.getBeanInfo(m_Target.getClass()) .getBeanDescriptor().getCustomizerClass(); } catch (IntrospectionException ex) { System.err.println("PropertySheet: Couldn't introspect"); return; } JTextArea jt = new JTextArea(); m_HelpText = null; // Look for a globalInfo method that returns a string // describing the target Object args[] = {}; boolean firstTip = true; StringBuffer optionsBuff = new StringBuffer(); for (MethodDescriptor m_Method : m_Methods) { String name = m_Method.getDisplayName(); Method meth = m_Method.getMethod(); OptionMetadata o = meth.getAnnotation(OptionMetadata.class); if (name.endsWith("TipText") || o != null) { if (meth.getReturnType().equals(String.class) || o != null) { try { String tempTip = o != null ? o.description() : (String) (meth.invoke(m_Target, args)); // int ci = tempTip.indexOf('.'); name = o != null ? o.displayName() : name; if (firstTip) { optionsBuff.append("OPTIONS\n"); firstTip = false; } tempTip = tempTip.replace("<html>", "").replace("</html>", "") .replace("<br>", "\n").replace("<p>", "\n\n"); optionsBuff.append(name.replace("TipText", "")).append(" -- "); optionsBuff.append(tempTip).append("\n\n"); // jt.setText(m_HelpText.toString()); } catch (Exception ex) { } // break; } } if (name.equals("globalInfo")) { if (meth.getReturnType().equals(String.class)) { try { // Object args[] = { }; String globalInfo = (String) (meth.invoke(m_Target, args)); String summary = globalInfo; int ci = globalInfo.indexOf('.'); if (ci != -1) { summary = globalInfo.substring(0, ci + 1); } final String className = targ.getClass().getName(); m_HelpText = new StringBuffer("NAME\n"); m_HelpText.append(className).append("\n\n"); m_HelpText.append("SYNOPSIS\n").append(globalInfo).append("\n\n"); m_HelpBut = new JButton("More"); m_HelpBut.setToolTipText("More information about " + className); m_HelpBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent a) { openHelpFrame(); m_HelpBut.setEnabled(false); } }); if (m_Target instanceof CapabilitiesHandler) { m_CapabilitiesBut = new JButton("Capabilities"); m_CapabilitiesBut.setToolTipText("The capabilities of " + className); m_CapabilitiesBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent a) { openCapabilitiesHelpDialog(); m_CapabilitiesBut.setEnabled(false); } }); } else { m_CapabilitiesBut = null; } jt.setColumns(30); jt.setFont(new Font("SansSerif", Font.PLAIN, 12)); jt.setEditable(false); jt.setLineWrap(true); jt.setWrapStyleWord(true); jt.setText(summary); jt.setBackground(getBackground()); JPanel jp = new JPanel(); jp.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("About"), BorderFactory.createEmptyBorder(5, 5, 5, 5))); jp.setLayout(new BorderLayout()); jp.add(jt, BorderLayout.CENTER); JPanel p2 = new JPanel(); p2.setLayout(new BorderLayout()); p2.add(m_HelpBut, BorderLayout.NORTH); if (m_CapabilitiesBut != null) { JPanel p3 = new JPanel(); p3.setLayout(new BorderLayout()); p3.add(m_CapabilitiesBut, BorderLayout.NORTH); p2.add(p3, BorderLayout.CENTER); } jp.add(p2, BorderLayout.EAST); GridBagConstraints gbConstraints = new GridBagConstraints(); // gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.BOTH; // gbConstraints.gridy = 0; gbConstraints.gridx = 0; gbConstraints.gridwidth = 2; gbConstraints.insets = new Insets(0, 5, 0, 5); gbLayout.setConstraints(jp, gbConstraints); m_aboutPanel = jp; if (m_showAboutPanel) { scrollablePanel.add(m_aboutPanel); } componentOffset = 1; // break; } catch (Exception ex) { } } } } if (m_HelpText != null) { m_HelpText.append(optionsBuff.toString()); } if (custClass != null) { // System.out.println("**** We've found a customizer for this object!"); try { Object customizer = custClass.newInstance(); if (customizer instanceof JComponent && customizer instanceof GOECustomizer) { m_Customizer = (GOECustomizer) customizer; m_Customizer.dontShowOKCancelButtons(); m_Customizer.setObject(m_Target); GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.BOTH; gbc.gridwidth = 2; gbc.gridy = componentOffset; gbc.gridx = 0; gbc.insets = new Insets(0, 5, 0, 5); gbLayout.setConstraints((JComponent) m_Customizer, gbc); scrollablePanel.add((JComponent) m_Customizer); validate(); // sometimes, the calculated dimensions seem to be too small and the // scrollbars show up, though there is still plenty of space on the // screen. hence we increase the dimensions a bit to fix this. Dimension dim = scrollablePanel.getPreferredSize(); dim.height += 20; dim.width += 20; scrollPane.setPreferredSize(dim); validate(); setVisible(true); return; } } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } int[] propOrdering = new int[m_Properties.length]; for (int i = 0; i < propOrdering.length; i++) { propOrdering[i] = Integer.MAX_VALUE; } for (int i = 0; i < m_Properties.length; i++) { Method getter = m_Properties[i].getReadMethod(); Method setter = m_Properties[i].getWriteMethod(); if (getter == null || setter == null) { continue; } List<Annotation> annotations = new ArrayList<Annotation>(); if (setter.getDeclaredAnnotations().length > 0) { annotations.addAll(Arrays.asList(setter.getDeclaredAnnotations())); } if (getter.getDeclaredAnnotations().length > 0) { annotations.addAll(Arrays.asList(getter.getDeclaredAnnotations())); } for (Annotation a : annotations) { if (a instanceof OptionMetadata) { propOrdering[i] = ((OptionMetadata)a).displayOrder(); break; } } } int[] sortedPropOrderings = Utils.sort(propOrdering); m_Editors = new PropertyEditor[m_Properties.length]; m_Values = new Object[m_Properties.length]; m_Views = new JComponent[m_Properties.length]; m_Labels = new JLabel[m_Properties.length]; m_TipTexts = new String[m_Properties.length]; // boolean firstTip = true; for (int i = 0; i < m_Properties.length; i++) { // Don't display hidden or expert properties. if (m_Properties[sortedPropOrderings[i]].isHidden() || m_Properties[sortedPropOrderings[i]].isExpert()) { continue; } String name = m_Properties[sortedPropOrderings[i]].getDisplayName(); String origName = name; Class<?> type = m_Properties[sortedPropOrderings[i]].getPropertyType(); Method getter = m_Properties[sortedPropOrderings[i]].getReadMethod(); Method setter = m_Properties[sortedPropOrderings[i]].getWriteMethod(); // Only display read/write properties. if (getter == null || setter == null) { continue; } List<Annotation> annotations = new ArrayList<Annotation>(); if (setter.getDeclaredAnnotations().length > 0) { annotations.addAll(Arrays.asList(setter.getDeclaredAnnotations())); } if (getter.getDeclaredAnnotations().length > 0) { annotations.addAll(Arrays.asList(getter.getDeclaredAnnotations())); } boolean skip = false; boolean password = false; FilePropertyMetadata fileProp = null; for (Annotation a : annotations) { if (a instanceof ProgrammaticProperty) { skip = true; // skip property that is only supposed to be manipulated programatically break; } if (a instanceof OptionMetadata) { name = ((OptionMetadata) a).displayName(); String tempTip = ((OptionMetadata)a).description(); int ci = tempTip.indexOf( '.' ); if ( ci < 0 ) { m_TipTexts[sortedPropOrderings[i]] = tempTip; } else { m_TipTexts[sortedPropOrderings[i]] = tempTip.substring( 0, ci ); } } if (a instanceof PasswordProperty) { password = true; } if (a instanceof FilePropertyMetadata) { fileProp = (FilePropertyMetadata) a; } } if (skip) { continue; } JComponent view = null; try { // Object args[] = { }; Object value = getter.invoke(m_Target, args); m_Values[sortedPropOrderings[i]] = value; PropertyEditor editor = null; Class<?> pec = m_Properties[sortedPropOrderings[i]].getPropertyEditorClass(); if (pec != null) { try { editor = (PropertyEditor) pec.newInstance(); } catch (Exception ex) { // Drop through. } } if (editor == null) { if (password && String.class.isAssignableFrom(type)) { editor = new PasswordField(); } else if (m_useEnvironmentPropertyEditors && String.class.isAssignableFrom( type)) { editor = new EnvironmentField(); } else if ((m_useEnvironmentPropertyEditors || fileProp != null) && File.class.isAssignableFrom( type)) { if (fileProp != null) { editor = new FileEnvironmentField("", fileProp.fileChooserDialogType(), fileProp.directoriesOnly()); } else { editor = new FileEnvironmentField(); } } else { editor = PropertyEditorManager.findEditor(type); } } m_Editors[sortedPropOrderings[i]] = editor; // If we can't edit this component, skip it. if (editor == null) { // If it's a user-defined property we give a warning. // String getterClass = m_Properties[i].getReadMethod() // .getDeclaringClass().getName(); /* * System.err.println("Warning: Can't find public property editor" + * " for property \"" + name + "\" (class \"" + type.getName() + * "\"). Skipping."); */ continue; } if (editor instanceof GenericObjectEditor) { ((GenericObjectEditor) editor).setClassType(type); } if (editor instanceof EnvironmentHandler) { ((EnvironmentHandler) editor).setEnvironment(m_env); } // Don't try to set null values: if (value == null) { // If it's a user-defined property we give a warning. // String getterClass = m_Properties[i].getReadMethod() // .getDeclaringClass().getName(); /* * if (getterClass.indexOf("java.") != 0) { * System.err.println("Warning: Property \"" + name + * "\" has null initial value. Skipping."); } */ continue; } editor.setValue(value); if (m_TipTexts[sortedPropOrderings[i]] == null) { // now look for a TipText method for this property String tipName = origName + "TipText"; for ( MethodDescriptor m_Method : m_Methods ) { String mname = m_Method.getDisplayName(); Method meth = m_Method.getMethod(); if ( mname.equals( tipName ) ) { if ( meth.getReturnType().equals( String.class ) ) { try { String tempTip = (String) ( meth.invoke( m_Target, args ) ); int ci = tempTip.indexOf( '.' ); if ( ci < 0 ) { m_TipTexts[sortedPropOrderings[i]] = tempTip; } else { m_TipTexts[sortedPropOrderings[i]] = tempTip.substring( 0, ci ); } /* * if (m_HelpText != null) { if (firstTip) { * m_HelpText.append("OPTIONS\n"); firstTip = false; } * m_HelpText.append(name).append(" -- "); * m_HelpText.append(tempTip).append("\n\n"); * //jt.setText(m_HelpText.toString()); } */ } catch ( Exception ex ) { } break; } } } } // Now figure out how to display it... if (editor.isPaintable() && editor.supportsCustomEditor()) { view = new PropertyPanel(editor); } else if (editor.supportsCustomEditor() && (editor.getCustomEditor() instanceof JComponent)) { view = (JComponent) editor.getCustomEditor(); } else if (editor.getTags() != null) { view = new PropertyValueSelector(editor); } else if (editor.getAsText() != null) { view = new PropertyText(editor); } else { System.err.println("Warning: Property \"" + name + "\" has non-displayabale editor. Skipping."); continue; } editor.addPropertyChangeListener(this); } catch (InvocationTargetException ex) { System.err.println("Skipping property " + name + " ; exception on target: " + ex.getTargetException()); ex.getTargetException().printStackTrace(); continue; } catch (Exception ex) { System.err.println("Skipping property " + name + " ; exception: " + ex); ex.printStackTrace(); continue; } m_Labels[sortedPropOrderings[i]] = new JLabel(name, SwingConstants.RIGHT); m_Labels[sortedPropOrderings[i]].setBorder(BorderFactory.createEmptyBorder(10, 10, 0, 5)); m_Views[sortedPropOrderings[i]] = view; GridBagConstraints gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = i + componentOffset; gbConstraints.gridx = 0; gbLayout.setConstraints(m_Labels[sortedPropOrderings[i]], gbConstraints); scrollablePanel.add(m_Labels[sortedPropOrderings[i]]); JPanel newPanel = new JPanel(); if (m_TipTexts[sortedPropOrderings[i]] != null) { m_Views[sortedPropOrderings[i]].setToolTipText(m_TipTexts[sortedPropOrderings[i]]); m_Labels[sortedPropOrderings[i]].setToolTipText(m_TipTexts[sortedPropOrderings[i]]); } newPanel.setBorder(BorderFactory.createEmptyBorder(10, 5, 0, 10)); newPanel.setLayout(new BorderLayout()); newPanel.add(m_Views[sortedPropOrderings[i]], BorderLayout.CENTER); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.WEST; gbConstraints.fill = GridBagConstraints.BOTH; gbConstraints.gridy = i + componentOffset; gbConstraints.gridx = 1; gbConstraints.weightx = 100; gbLayout.setConstraints(newPanel, gbConstraints); scrollablePanel.add(newPanel); m_NumEditable++; } if (m_NumEditable == 0) { JLabel empty = new JLabel("No editable properties", SwingConstants.CENTER); Dimension d = empty.getPreferredSize(); empty.setPreferredSize(new Dimension(d.width * 2, d.height * 2)); empty.setBorder(BorderFactory.createEmptyBorder(10, 5, 0, 10)); GridBagConstraints gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.CENTER; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = componentOffset; gbConstraints.gridx = 0; gbLayout.setConstraints(empty, gbConstraints); scrollablePanel.add(empty); } validate(); // sometimes, the calculated dimensions seem to be too small and the // scrollbars show up, though there is still plenty of space on the // screen. hence we increase the dimensions a bit to fix this. Dimension dim = scrollablePanel.getPreferredSize(); dim.height += 20; dim.width += 20; scrollPane.setPreferredSize(dim); validate(); setVisible(true); } /** * opens the help dialog. */ protected void openHelpFrame() { JTextArea ta = new JTextArea(); ta.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); ta.setLineWrap(true); ta.setWrapStyleWord(true); // ta.setBackground(getBackground()); ta.setEditable(false); ta.setText(m_HelpText.toString()); ta.setCaretPosition(0); JDialog jdtmp; if (PropertyDialog.getParentDialog(this) != null) { jdtmp = new JDialog(PropertyDialog.getParentDialog(this), "Information"); } else if (PropertyDialog.getParentFrame(this) != null) { jdtmp = new JDialog(PropertyDialog.getParentFrame(this), "Information"); } else { jdtmp = new JDialog(PropertyDialog.getParentDialog(m_aboutPanel), "Information"); } final JDialog jd = jdtmp; jd.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { jd.dispose(); if (m_HelpDialog == jd) { m_HelpBut.setEnabled(true); } } }); jd.getContentPane().setLayout(new BorderLayout()); jd.getContentPane().add(new JScrollPane(ta), BorderLayout.CENTER); jd.pack(); jd.setSize(400, 350); jd.setLocation(m_aboutPanel.getTopLevelAncestor().getLocationOnScreen().x + m_aboutPanel.getTopLevelAncestor().getSize().width, m_aboutPanel .getTopLevelAncestor().getLocationOnScreen().y); jd.setVisible(true); m_HelpDialog = jd; } /** * opens the help dialog for the capabilities. */ protected void openCapabilitiesHelpDialog() { if (PropertyDialog.getParentDialog(this) != null) { m_CapabilitiesDialog = new CapabilitiesHelpDialog( PropertyDialog.getParentDialog(this)); } else { m_CapabilitiesDialog = new CapabilitiesHelpDialog( PropertyDialog.getParentFrame(this)); } m_CapabilitiesDialog.setSize(400, 350); m_CapabilitiesDialog.setLocation(m_aboutPanel.getTopLevelAncestor() .getLocationOnScreen().x + m_aboutPanel.getTopLevelAncestor().getSize().width, m_aboutPanel .getTopLevelAncestor().getLocationOnScreen().y); m_CapabilitiesDialog.setVisible(true); addPropertyChangeListener(m_CapabilitiesDialog); } /** * Gets the number of editable properties for the current target. * * @return the number of editable properties. */ public int editableProperties() { return m_NumEditable; } /** * Returns true if the object being edited has a customizer * * @return true if the object being edited has a customizer */ public boolean hasCustomizer() { return m_Customizer != null; } /** * Updates the propertysheet when a value has been changed (from outside the * propertysheet?). * * @param evt a value of type 'PropertyChangeEvent' */ synchronized void wasModified(PropertyChangeEvent evt) { // System.err.println("wasModified"); if (evt.getSource() instanceof PropertyEditor) { PropertyEditor editor = (PropertyEditor) evt.getSource(); for (int i = 0; i < m_Editors.length; i++) { if (m_Editors[i] == editor) { PropertyDescriptor property = m_Properties[i]; Object value = editor.getValue(); m_Values[i] = value; Method setter = property.getWriteMethod(); try { Object args[] = { value }; args[0] = value; setter.invoke(m_Target, args); } catch (InvocationTargetException ex) { if (ex.getTargetException() instanceof PropertyVetoException) { String message = "WARNING: Vetoed; reason is: " + ex.getTargetException().getMessage(); System.err.println(message); Component jf; if (evt.getSource() instanceof JPanel) { jf = ((JPanel) evt.getSource()).getParent(); } else { jf = new JFrame(); } JOptionPane.showMessageDialog(jf, message, "error", JOptionPane.WARNING_MESSAGE); if (jf instanceof JFrame) { ((JFrame) jf).dispose(); } } else { System.err.println(ex.getTargetException().getClass().getName() + " while updating " + property.getName() + ": " + ex.getTargetException().getMessage()); Component jf; if (evt.getSource() instanceof JPanel) { jf = ((JPanel) evt.getSource()).getParent(); } else { jf = new JFrame(); } JOptionPane.showMessageDialog(jf, ex.getTargetException() .getClass().getName() + " while updating " + property.getName() + ":\n" + ex.getTargetException().getMessage(), "error", JOptionPane.WARNING_MESSAGE); if (jf instanceof JFrame) { ((JFrame) jf).dispose(); } } } catch (Exception ex) { System.err.println("Unexpected exception while updating " + property.getName()); } if (m_Views[i] != null && m_Views[i] instanceof PropertyPanel) { // System.err.println("Trying to repaint the property canvas"); m_Views[i].repaint(); revalidate(); } break; } } } // Now re-read all the properties and update the editors // for any other properties that have changed. for (int i = 0; i < m_Properties.length; i++) { Object o; try { Method getter = m_Properties[i].getReadMethod(); Method setter = m_Properties[i].getWriteMethod(); if (getter == null || setter == null) { // ignore set/get only properties continue; } Object args[] = {}; o = getter.invoke(m_Target, args); } catch (Exception ex) { o = null; } if (o == m_Values[i] || (o != null && o.equals(m_Values[i]))) { // The property is equal to its old value. continue; } m_Values[i] = o; // Make sure we have an editor for this property... if (m_Editors[i] == null) { continue; } // The property has changed! Update the editor. m_Editors[i].removePropertyChangeListener(this); m_Editors[i].setValue(o); m_Editors[i].addPropertyChangeListener(this); if (m_Views[i] != null) { // System.err.println("Trying to repaint " + (i + 1)); m_Views[i].repaint(); } } // Make sure the target bean gets repainted. if (Beans.isInstanceOf(m_Target, Component.class)) { ((Component) (Beans.getInstanceOf(m_Target, Component.class))).repaint(); } } /** * Set environment variables to pass on to any editor that can use them * * @param env the variables to pass on to individual property editors */ @Override public void setEnvironment(Environment env) { m_env = env; } /** * Pass on an OK closing notification to the customizer (if one is in use) */ public void closingOK() { if (m_Customizer != null) { // pass on the notification to the customizer so that // it can copy values out of its GUI widgets into the object // being customized, if necessary m_Customizer.closingOK(); } } /** * Pass on a CANCEL closing notificiation to the customizer (if one is in * use). */ public void closingCancel() { // pass on the notification to the customizer so that // it can revert to previous settings for the object being // edited, if neccessary if (m_Customizer != null) { m_Customizer.closingCancel(); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/PropertyText.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * PropertyText.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.beans.PropertyEditor; import javax.swing.JTextField; /** * Support for a PropertyEditor that uses text. * Isn't going to work well if the property gets changed * somewhere other than this field simultaneously * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ class PropertyText extends JTextField { /** for serialization */ private static final long serialVersionUID = -3915342928825822730L; /** The property editor */ private PropertyEditor m_Editor; /** * Sets up the editing component with the supplied editor. * * @param pe the PropertyEditor */ PropertyText(PropertyEditor pe) { //super(pe.getAsText()); super((pe.getAsText().equals("null"))?"":pe.getAsText()); m_Editor = pe; /* m_Editor.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { updateUs(); } }); */ addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) { // if (e.getKeyCode() == KeyEvent.VK_ENTER) { updateEditor(); // } } }); addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent e) { updateEditor(); } }); } /** * Attempts to update the textfield value from the editor. */ protected void updateUs() { try { setText(m_Editor.getAsText()); } catch (IllegalArgumentException ex) { // Quietly ignore. } } /** * Attempts to update the editor value from the textfield. */ protected void updateEditor() { try { m_Editor.setAsText(getText()); } catch (IllegalArgumentException ex) { // Quietly ignore. } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/PropertyValueSelector.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * PropertyValueSelector.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.beans.PropertyEditor; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.JComboBox; /** * Support for any PropertyEditor that uses tags. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ class PropertyValueSelector extends JComboBox { /** for serialization */ private static final long serialVersionUID = 128041237745933212L; /** The property editor */ PropertyEditor m_Editor; /** * Sets up the editing component with the supplied editor. * * @param pe the PropertyEditor */ public PropertyValueSelector(PropertyEditor pe) { m_Editor = pe; Object value = m_Editor.getAsText(); String tags[] = m_Editor.getTags(); ComboBoxModel model = new DefaultComboBoxModel(tags) { private static final long serialVersionUID = 7942587653040180213L; public Object getSelectedItem() { return m_Editor.getAsText(); } public void setSelectedItem(Object o) { m_Editor.setAsText((String)o); } }; setModel(model); setSelectedItem(value); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/ReaderToTextPane.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ReaderToTextArea.java * Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand */ package weka.gui; import java.awt.Color; import java.io.LineNumberReader; import java.io.Reader; import javax.swing.JTextPane; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyleContext; import javax.swing.text.StyledDocument; /** * A class that sends all lines from a reader to a JTextPane component. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class ReaderToTextPane extends Thread { /** The reader being monitored. */ protected LineNumberReader m_Input; /** The output text component. */ protected JTextPane m_Output; /** the color to use. */ protected Color m_Color; /** * Sets up the thread. Using black as color for displaying the text. * * @param input the Reader to monitor * @param output the TextArea to send output to */ public ReaderToTextPane(Reader input, JTextPane output) { this(input, output, Color.BLACK); } /** * Sets up the thread. * * @param input the Reader to monitor * @param output the TextArea to send output to * @param color the color to use */ public ReaderToTextPane(Reader input, JTextPane output, Color color) { StyledDocument doc; Style style; setDaemon(true); m_Color = color; m_Input = new LineNumberReader(input); m_Output = output; doc = m_Output.getStyledDocument(); style = StyleContext.getDefaultStyleContext() .getStyle(StyleContext.DEFAULT_STYLE); style = doc.addStyle(getStyleName(), style); StyleConstants.setFontFamily(style, "monospaced"); StyleConstants.setForeground(style, m_Color); } /** * Returns the color in use. * * @return the color */ public Color getColor() { return m_Color; } /** * Returns the style name. * * @return the style name */ protected String getStyleName() { return "" + m_Color.hashCode(); } /** * Sit here listening for lines of input and appending them straight * to the text component. */ public void run() { while (true) { try { StyledDocument doc = m_Output.getStyledDocument(); doc.insertString( doc.getLength(), m_Input.readLine() + '\n', doc.getStyle(getStyleName())); m_Output.setCaretPosition(doc.getLength()); } catch (Exception ex) { try { sleep(100); } catch (Exception e) { // ignored } } } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/ResultHistoryPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ResultHistoryPanel.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.awt.*; import java.awt.event.InputEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.Serializable; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.text.JTextComponent; import weka.core.Utils; import weka.gui.visualize.PrintableComponent; /** * A component that accepts named stringbuffers and displays the name in a list * box. When a name is right-clicked, a frame is popped up that contains the * string held by the stringbuffer. Optionally a text component may be provided * that will have it's text set to the named result text on a left-click. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public class ResultHistoryPanel extends JPanel { /** for serialization */ static final long serialVersionUID = 4297069440135326829L; /** An optional component for single-click display */ protected JTextComponent m_SingleText; /** The named result being viewed in the single-click display */ protected String m_SingleName; /** The list model */ protected DefaultListModel m_Model = new DefaultListModel(); /** The list component */ protected JList m_List = new JList(m_Model); /** A Hashtable mapping names to result buffers */ protected Hashtable<String, StringBuffer> m_Results = new Hashtable<String, StringBuffer>(); /** A Hashtable mapping names to output text components */ protected Hashtable<String, JTextArea> m_FramedOutput = new Hashtable<String, JTextArea>(); /** A hashtable mapping names to arbitrary objects */ protected Hashtable<String, Object> m_Objs = new Hashtable<String, Object>(); /** * Let the result history list handle right clicks in the default manner---ie, * pop up a window displaying the buffer */ protected boolean m_HandleRightClicks = true; /** for printing the output to files */ protected PrintableComponent m_Printer = null; /** Something listening for list deletions */ protected transient RDeleteListener m_deleteListener; /** * Extension of MouseAdapter that implements Serializable. */ public static class RMouseAdapter extends MouseAdapter implements Serializable { /** for serialization */ static final long serialVersionUID = -8991922650552358669L; } /** * Extension of KeyAdapter that implements Serializable. */ public static class RKeyAdapter extends KeyAdapter implements Serializable { /** for serialization */ static final long serialVersionUID = -8675332541861828079L; } /** * Interface for something to be notified when an entry in the list is deleted */ public static interface RDeleteListener { /** * Called when an entry in the list is deleted * * @param name the name of the entry deleted * @param index the index of the entry deleted */ void entryDeleted(String name, int index); /** * @param names * @param indexes */ void entriesDeleted(List<String> names, List<Integer> indexes); } /** * Create the result history object * * @param text the optional text component for single-click display */ public ResultHistoryPanel(JTextComponent text) { m_SingleText = text; if (text != null) { m_Printer = new PrintableComponent(m_SingleText); } //m_List.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); m_List.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); m_List.addMouseListener(new RMouseAdapter() { private static final long serialVersionUID = -9015397020486290479L; @Override public void mouseClicked(MouseEvent e) { if ((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) { // if (((e.getModifiers() & InputEvent.SHIFT_DOWN_MASK) == 0) // && ((e.getModifiers() & InputEvent.CTRL_DOWN_MASK) == 0)) { // int index = m_List.locationToIndex(e.getPoint()); // if ((index != -1) && (m_SingleText != null)) { // setSingle((String) m_Model.elementAt(index)); // } // } } else { // if there are stored objects then assume that the storer // will handle popping up the text in a separate frame if (m_HandleRightClicks) { int index = m_List.locationToIndex(e.getPoint()); if (index != -1) { String name = (String) m_Model.elementAt(index); openFrame(name); } } } } }); m_List.addKeyListener(new RKeyAdapter() { private static final long serialVersionUID = 7910681776999302344L; @Override public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_DELETE) { removeResults(m_List.getSelectedIndices()); // int selected = m_List.getSelectedIndex(); // if (selected != -1) { // String element = m_Model.elementAt(selected).toString(); // removeResult(element); // if (m_deleteListener != null) { // m_deleteListener.entryDeleted(element, selected); // } // } } } }); m_List.getSelectionModel().addListSelectionListener( new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { if (m_List.getSelectedIndices().length <= 1) { ListSelectionModel lm = (ListSelectionModel) e.getSource(); for (int i = e.getFirstIndex(); i <= e.getLastIndex(); i++) { if (lm.isSelectedIndex(i)) { // m_AttSummaryPanel.setAttribute(i); if ((i != -1) && (m_SingleText != null)) { setSingle((String) m_Model.elementAt(i)); } break; } } } } } }); setLayout(new BorderLayout()); // setBorder(BorderFactory.createTitledBorder("Result history")); final JScrollPane js = new JScrollPane(m_List); js.getViewport().addChangeListener(new ChangeListener() { private int lastHeight; @Override public void stateChanged(ChangeEvent e) { JViewport vp = (JViewport) e.getSource(); int h = vp.getViewSize().height; if (h != lastHeight) { // i.e. an addition not just a user scrolling lastHeight = h; int x = h - vp.getExtentSize().height; vp.setViewPosition(new Point(0, x)); } } }); add(js, BorderLayout.CENTER); } /** * Set a listener for deletions from the list * * @param listener the listener to set */ public void setDeleteListener(RDeleteListener listener) { m_deleteListener = listener; } /** * Adds a new result to the result list. * * @param name the name to associate with the result * @param result the StringBuffer that contains the result text */ public void addResult(String name, StringBuffer result) { String nameCopy = name; int i = 0; while (m_Results.containsKey(nameCopy)) { nameCopy = name + "_" + i++; } m_Model.addElement(nameCopy); m_Results.put(nameCopy, result); } /** * Remove the entries at the specified indices in the list * * @param selectedI the entries to remove */ public void removeResults(int[] selectedI) { if (selectedI != null && selectedI.length > 0) { List<String> elsToDelete = new ArrayList<String>(); for (int i : selectedI) { elsToDelete.add(m_Model.elementAt(i).toString()); } removeResults(elsToDelete); } } /** * Remove the specified entries from the list * * @param entries the entries to remove */ public void removeResults(List<String> entries) { for (String el : entries) { removeResult(el); } } /** * Removes one of the result buffers from the history. Any windows currently * displaying the contents of the buffer are not affected. * * @param name the name of the buffer to remove. */ public void removeResult(String name) { StringBuffer buff = m_Results.get(name); if (buff != null) { m_Results.remove(name); m_Model.removeElement(name); m_Objs.remove(name); System.gc(); } } /** * Removes all of the result buffers from the history. Any windows currently * displaying the contents of the buffer are not affected. */ public void clearResults() { m_Results.clear(); m_Model.clear(); m_Objs.clear(); System.gc(); } /** * Adds an object to the results list. If an object with the same * name already exists, then a number is appended to the end of the name * to make it unique. * * @param name the name to associate with the object * @param o the object */ public void addObject(String name, Object o) { String nameCopy = name; int i = 0; while (m_Objs.containsKey(nameCopy)) { nameCopy = name + "_" + i++; } m_Objs.put(nameCopy, o); } /** * Adds an object to the result list. Overwrites any exsiting * object with the same name * * @param name the name to associate with the object * @param o the object */ public void addOrOverwriteObject(String name, Object o) { m_Objs.put(name, o); } /** * Get the named object from the list * * @param name the name of the item to retrieve the stored object for * @return the object or null if there is no object at this index */ public Object getNamedObject(String name) { Object v = null; v = m_Objs.get(name); return v; } /** * Gets the object associated with the currently selected item in the list. * * @return the object or null if there is no object corresponding to the * current selection in the list */ public Object getSelectedObject() { Object v = null; int index = m_List.getSelectedIndex(); if (index != -1) { String name = (String) (m_Model.elementAt(index)); v = m_Objs.get(name); } return v; } /** * Gets the named buffer * * @return the buffer or null if there are no items in the list */ public StringBuffer getNamedBuffer(String name) { StringBuffer b = null; b = (m_Results.get(name)); return b; } /** * Gets the buffer associated with the currently selected item in the list. * * @return the buffer or null if there are no items in the list */ public StringBuffer getSelectedBuffer() { StringBuffer b = null; int index = m_List.getSelectedIndex(); if (index != -1) { String name = (String) (m_Model.elementAt(index)); b = (m_Results.get(name)); } return b; } /** * Get the name of the currently selected item in the list * * @return the name of the currently selected item or null if no item selected */ public String getSelectedName() { int index = m_List.getSelectedIndex(); if (index != -1) { return (String) (m_Model.elementAt(index)); } return null; } /** * Gets the name of theitem in the list at the specified index * * @return the name of item or null if there is no item at that index */ public String getNameAtIndex(int index) { if (index != -1) { return (String) (m_Model.elementAt(index)); } return null; } /** * Sets the single-click display to view the named result. * * @param name the name of the result to display. */ public void setSingle(String name) { StringBuffer buff = m_Results.get(name); if (buff != null) { m_SingleName = name; m_SingleText.setText(buff.toString()); m_List.setSelectedValue(name, true); } } /** * Set the selected list entry. Note, does not update the single click display * to the corresponding named result - use setSingle() to set the selected * list entry and view the corresponding result * * @param name the name of the list entry to be selected */ public void setSelectedListValue(String name) { m_List.setSelectedValue(name, true); } /** * Opens the named result in a separate frame. * * @param name the name of the result to open. */ public void openFrame(String name) { StringBuffer buff = m_Results.get(name); JTextComponent currentText = m_FramedOutput.get(name); if ((buff != null) && (currentText == null)) { // Open the frame. JTextArea ta = new JTextArea(); ta.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); ta.setFont(new Font("Monospaced", Font.PLAIN, 12)); ta.setEditable(false); ta.setText(buff.toString()); m_FramedOutput.put(name, ta); final JFrame jf = Utils.getWekaJFrame(name, this); jf.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { m_FramedOutput.remove(jf.getTitle()); jf.dispose(); } }); jf.getContentPane().setLayout(new BorderLayout()); jf.getContentPane().add(new JScrollPane(ta), BorderLayout.CENTER); jf.pack(); jf.setSize(800, 600); jf.setLocationRelativeTo(SwingUtilities.getWindowAncestor(this)); jf.setVisible(true); } } /** * Tells any component currently displaying the named result that the contents * of the result text in the StringBuffer have been updated. * * @param name the name of the result that has been updated. */ public void updateResult(String name) { StringBuffer buff = m_Results.get(name); if (buff == null) { return; } if (m_SingleName == name) { m_SingleText.setText(buff.toString()); } JTextComponent currentText = m_FramedOutput.get(name); if (currentText != null) { currentText.setText(buff.toString()); } } /** * Gets the selection model used by the results list. * * @return a value of type 'ListSelectionModel' */ public ListSelectionModel getSelectionModel() { return m_List.getSelectionModel(); } /** * Gets the JList used by the results list * * @return the JList */ public JList getList() { return m_List; } /** * Set whether the result history list should handle right clicks or whether * the parent object will handle them. * * @param tf false if parent object will handle right clicks */ public void setHandleRightClicks(boolean tf) { m_HandleRightClicks = tf; } /** * Set the background color for this component and the list * * @param c the background color to use */ @Override public void setBackground(Color c) { super.setBackground(c); if (m_List != null) { m_List.setBackground(c); } } /** * Set the font to use in the list * * @param f the font to use */ @Override public void setFont(Font f) { super.setFont(f); if (m_List != null) { m_List.setFont(f); } } /** * Tests out the result history from the command line. * * @param args ignored */ public static void main(String[] args) { try { final javax.swing.JFrame jf = new javax.swing.JFrame("Weka Explorer: Classifier"); jf.getContentPane().setLayout(new BorderLayout()); final ResultHistoryPanel jd = new ResultHistoryPanel(null); jd.addResult("blah", new StringBuffer("Nothing to see here")); jd.addResult("blah1", new StringBuffer("Nothing to see here1")); jd.addResult("blah2", new StringBuffer("Nothing to see here2")); jd.addResult("blah3", new StringBuffer("Nothing to see here3")); jf.getContentPane().add(jd, BorderLayout.CENTER); jf.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { jf.dispose(); System.exit(0); } }); jf.pack(); jf.setVisible(true); } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/SaveBuffer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SaveBuffer.java * Copyright (C) 2000-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.awt.Component; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JOptionPane; /** * This class handles the saving of StringBuffers to files. It will pop * up a file chooser allowing the user to select a destination file. If * the file exists, the user is prompted for the correct course of action, * ie. overwriting, appending, selecting a new filename or canceling. * * @author Mark Hall (mhall@cs.waikato.ac.nz) * @version $Revision 1.0 $ */ public class SaveBuffer { /** The Logger to send messages to */ private Logger m_Log; /** The parent component requesting the save */ private Component m_parentComponent; /** Last directory selected from the file chooser */ private String m_lastvisitedDirectory=null; /** * Constructor * @param log the logger to send messages to * @param parent the parent component will be requesting a save */ public SaveBuffer(Logger log, Component parent) { m_Log = log; m_parentComponent = parent; } /** * Save a buffer * @param buf the buffer to save * @return true if the save is completed succesfully */ public boolean save(StringBuffer buf) { if (buf != null) { JFileChooser fileChooser; if (m_lastvisitedDirectory == null) { fileChooser = new JFileChooser( new File(System.getProperty("user.dir"))); } else { fileChooser = new JFileChooser(m_lastvisitedDirectory); } fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); int returnVal = fileChooser.showSaveDialog(m_parentComponent); if (returnVal == JFileChooser.APPROVE_OPTION) { File sFile = fileChooser.getSelectedFile(); m_lastvisitedDirectory = sFile.getPath(); if (sFile.exists()) { Object [] options = new String[4]; options[0] = "Append"; options[1] = "Overwrite"; options[2] = "Choose new name"; options[3] = "Cancel"; JOptionPane jop = new JOptionPane("File exists", JOptionPane.QUESTION_MESSAGE, 1, null, options); JDialog dialog = jop.createDialog(m_parentComponent, "File query"); dialog.setVisible(true); Object selectedValue = jop.getValue(); if (selectedValue == null) { } else { for(int i=0; i<4; i++) { if(options[i].equals(selectedValue)) { switch (i) { // append case 0: return saveOverwriteAppend(buf, sFile, true); // overwrite case 1: return saveOverwriteAppend(buf, sFile, false); // pick new name case 2: return save(buf); // cancel case 3: break; } } } } } else { saveOverwriteAppend(buf, sFile, false); // file does not exist } } else { return false; // file save canceled } } return false; // buffer null } /** * Saves the provided buffer to the specified file * @param buf the buffer to save * @param sFile the file to save to * @param append true if buffer is to be appended to file * @return true if save is succesful */ private boolean saveOverwriteAppend(StringBuffer buf, File sFile, boolean append) { try { String path = sFile.getPath(); if (m_Log != null) { if (append) { m_Log.statusMessage("Appending to file..."); } else { m_Log.statusMessage("Saving to file..."); } } PrintWriter out = new PrintWriter(new BufferedWriter( new FileWriter(path, append))); out.write(buf.toString(),0,buf.toString().length()); out.close(); if (m_Log != null) { m_Log.statusMessage("OK"); } } catch (Exception ex) { ex.printStackTrace(); if (m_Log != null) { m_Log.logMessage(ex.getMessage()); } return false; } return true; } /** * Main method for testing this class */ public static void main(String [] args) { try { final javax.swing.JFrame jf = new javax.swing.JFrame("SaveBuffer test"); jf.getContentPane().setLayout(new java.awt.BorderLayout()); weka.gui.LogPanel lp = new weka.gui.LogPanel(); javax.swing.JButton jb = new javax.swing.JButton("Save"); jf.getContentPane().add(jb,java.awt.BorderLayout.SOUTH); jf.getContentPane().add(lp, java.awt.BorderLayout.CENTER); final SaveBuffer svb = new SaveBuffer(lp, jf); jb.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { svb.save(new StringBuffer("A bit of test text")); } }); jf.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { jf.dispose(); System.exit(0); } }); jf.pack(); jf.setVisible(true); } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/SelectedTagEditor.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SelectedTagEditor.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.awt.BorderLayout; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.PropertyEditorSupport; import javax.swing.JFrame; import weka.core.SelectedTag; import weka.core.Tag; /** * A PropertyEditor that uses tags, where the tags are obtained from a * weka.core.SelectedTag object. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public class SelectedTagEditor extends PropertyEditorSupport { /** * Returns a description of the property value as java source. * * @return a value of type 'String' */ public String getJavaInitializationString() { SelectedTag s = (SelectedTag)getValue(); Tag [] tags = s.getTags(); String result = "new SelectedTag(" + s.getSelectedTag().getID() + ", {\n"; for (int i = 0; i < tags.length; i++) { result += "new Tag(" + tags[i].getID() + ",\"" + tags[i].getReadable() + "\")"; if (i < tags.length - 1) { result += ','; } result += '\n'; } return result + "})"; } /** * Gets the current value as text. * * @return a value of type 'String' */ public String getAsText() { SelectedTag s = (SelectedTag)getValue(); return s.getSelectedTag().getReadable(); } /** * Sets the current property value as text. * * @param text the text of the selected tag. * @exception java.lang.IllegalArgumentException if an error occurs */ public void setAsText(String text) { SelectedTag s = (SelectedTag)getValue(); Tag [] tags = s.getTags(); try { for (int i = 0; i < tags.length; i++) { if (text.equals(tags[i].getReadable())) { setValue(new SelectedTag(tags[i].getID(), tags)); return; } } } catch (Exception ex) { throw new java.lang.IllegalArgumentException(text); } } /** * Gets the list of tags that can be selected from. * * @return an array of string tags. */ public String[] getTags() { SelectedTag s = (SelectedTag)getValue(); Tag [] tags = s.getTags(); String [] result = new String [tags.length]; for (int i = 0; i < tags.length; i++) { result[i] = tags[i].getReadable(); } return result; } /** * Tests out the selectedtag editor from the command line. * * @param args ignored */ public static void main(String [] args) { try { GenericObjectEditor.registerEditors(); Tag [] tags = { new Tag(1, "First option"), new Tag(2, "Second option"), new Tag(3, "Third option"), new Tag(4, "Fourth option"), new Tag(5, "Fifth option"), }; SelectedTag initial = new SelectedTag(1, tags); SelectedTagEditor ce = new SelectedTagEditor(); ce.setValue(initial); PropertyValueSelector ps = new PropertyValueSelector(ce); JFrame f = new JFrame(); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); f.getContentPane().setLayout(new BorderLayout()); f.getContentPane().add(ps, BorderLayout.CENTER); f.pack(); f.setVisible(true); } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/SetInstancesPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SetInstancesPanel.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.File; import java.net.URL; import javax.swing.BorderFactory; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import weka.core.Attribute; import weka.core.Instances; import weka.core.converters.ConverterUtils; import weka.core.converters.FileSourcedConverter; import weka.core.converters.IncrementalConverter; import weka.core.converters.URLSourcedLoader; /** * A panel that displays an instance summary for a set of instances and lets the * user open a set of instances from either a file or URL. * * Instances may be obtained either in a batch or incremental fashion. If * incremental reading is used, then the client should obtain the Loader object * (by calling getLoader()) and read the instances one at a time. If batch * loading is used, then SetInstancesPanel will load the data into memory inside * of a separate thread and notify the client when the operation is complete. * The client can then retrieve the instances by calling getInstances(). * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public class SetInstancesPanel extends JPanel { /** for serialization. */ private static final long serialVersionUID = -384804041420453735L; /** the text denoting "no class" in the class combobox. */ public final static String NO_CLASS = "No class"; /** Click to open instances from a file. */ protected JButton m_OpenFileBut = new JButton("Open file..."); /** Click to open instances from a URL. */ protected JButton m_OpenURLBut = new JButton("Open URL..."); /** Click to close the dialog. */ protected JButton m_CloseBut = new JButton("Close"); /** The instance summary component. */ protected InstancesSummaryPanel m_Summary = new InstancesSummaryPanel(); /** the label for the class combobox. */ protected JLabel m_ClassLabel = new JLabel("Class"); /** the class combobox. */ protected JComboBox m_ClassComboBox = new JComboBox(new DefaultComboBoxModel( new String[] { NO_CLASS })); /** The file chooser for selecting arff files. */ protected ConverterFileChooser m_FileChooser = new ConverterFileChooser( new File(System.getProperty("user.dir"))); /** Stores the last URL that instances were loaded from. */ protected String m_LastURL = "http://"; /** The thread we do loading in. */ protected Thread m_IOThread; /** * Manages sending notifications to people when we change the set of working * instances. */ protected PropertyChangeSupport m_Support = new PropertyChangeSupport(this); /** The current set of instances loaded. */ protected Instances m_Instances; /** The current loader used to obtain the current instances. */ protected weka.core.converters.Loader m_Loader; /** the parent frame. if one is provided, the close-button is displayed */ protected JFrame m_ParentFrame = null; /** the panel the Close-Button is located in. */ protected JPanel m_CloseButPanel = null; /** whether to read the instances incrementally, if possible. */ protected boolean m_readIncrementally = true; /** whether to display zero instances as unknown ("?"). */ protected boolean m_showZeroInstancesAsUnknown = false; /** * whether to display a combobox that allows the user to choose the class * attribute. */ protected boolean m_showClassComboBox; /** * Default constructor. */ public SetInstancesPanel() { this(false, false, null); } /** * Create the panel. * * @param showZeroInstancesAsUnknown whether to display zero instances as * unknown (e.g., when reading data incrementally) * @param showClassComboBox whether to display a combobox allowing the user to * choose the class attribute * @param chooser the file chooser to use (may be null to use the default file * chooser) */ public SetInstancesPanel(boolean showZeroInstancesAsUnknown, boolean showClassComboBox, ConverterFileChooser chooser) { m_showZeroInstancesAsUnknown = showZeroInstancesAsUnknown; m_showClassComboBox = showClassComboBox; if (chooser != null) { m_FileChooser = chooser; } m_OpenFileBut.setToolTipText("Open a set of instances from a file"); m_OpenURLBut.setToolTipText("Open a set of instances from a URL"); m_CloseBut.setToolTipText("Closes the dialog"); m_FileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); m_OpenURLBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setInstancesFromURLQ(); } }); m_OpenFileBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setInstancesFromFileQ(); } }); m_CloseBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { closeFrame(); } }); m_Summary.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10)); m_ClassComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if ((m_Instances != null) && (m_ClassComboBox.getSelectedIndex() != -1)) { if (m_Instances.numAttributes() >= m_ClassComboBox.getSelectedIndex()) { m_Instances.setClassIndex(m_ClassComboBox.getSelectedIndex() - 1); // -1 // because // of // NO_CLASS // element m_Support.firePropertyChange("", null, null); } } } }); JPanel panelButtons = new JPanel(new FlowLayout(FlowLayout.LEFT)); panelButtons.add(m_OpenFileBut); panelButtons.add(m_OpenURLBut); JPanel panelClass = new JPanel(new FlowLayout(FlowLayout.LEFT)); panelClass.add(m_ClassLabel); panelClass.add(m_ClassComboBox); JPanel panelButtonsAndClass; if (m_showClassComboBox) { panelButtonsAndClass = new JPanel(new GridLayout(2, 1)); panelButtonsAndClass.add(panelButtons); panelButtonsAndClass.add(panelClass); } else { panelButtonsAndClass = new JPanel(new GridLayout(1, 1)); panelButtonsAndClass.add(panelButtons); } m_CloseButPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); m_CloseButPanel.add(m_CloseBut); m_CloseButPanel.setVisible(false); JPanel panelButtonsAll = new JPanel(new BorderLayout()); panelButtonsAll.add(panelButtonsAndClass, BorderLayout.CENTER); panelButtonsAll.add(m_CloseButPanel, BorderLayout.SOUTH); setLayout(new BorderLayout()); add(m_Summary, BorderLayout.CENTER); add(panelButtonsAll, BorderLayout.SOUTH); } /** * Sets the frame, this panel resides in. Used for displaying the close * button, i.e., the close-button is visible if the given frame is not null. * * @param parent the parent frame */ public void setParentFrame(JFrame parent) { m_ParentFrame = parent; m_CloseButPanel.setVisible(m_ParentFrame != null); } /** * Returns the current frame the panel knows of, that it resides in. Can be * null. * * @return the current parent frame */ public JFrame getParentFrame() { return m_ParentFrame; } /** * closes the frame, i.e., the visibility is set to false. */ public void closeFrame() { if (m_ParentFrame != null) m_ParentFrame.setVisible(false); } /** * Queries the user for a file to load instances from, then loads the * instances in a background process. This is done in the IO thread, and an * error message is popped up if the IO thread is busy. */ public void setInstancesFromFileQ() { if (m_IOThread == null) { int returnVal = m_FileChooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { final File selected = m_FileChooser.getSelectedFile(); m_IOThread = new Thread() { @Override public void run() { setInstancesFromFile(selected); m_IOThread = null; } }; m_IOThread.setPriority(Thread.MIN_PRIORITY); // UI has most priority m_IOThread.start(); } } else { JOptionPane.showMessageDialog(this, "Can't load at this time,\n" + "currently busy with other IO", "Load Instances", JOptionPane.WARNING_MESSAGE); } } /** * Queries the user for a URL to load instances from, then loads the instances * in a background process. This is done in the IO thread, and an error * message is popped up if the IO thread is busy. */ public void setInstancesFromURLQ() { if (m_IOThread == null) { try { String urlName = (String) JOptionPane.showInputDialog(this, "Enter the source URL", "Load Instances", JOptionPane.QUESTION_MESSAGE, null, null, m_LastURL); if (urlName != null) { m_LastURL = urlName; final URL url = new URL(urlName); m_IOThread = new Thread() { @Override public void run() { setInstancesFromURL(url); m_IOThread = null; } }; m_IOThread.setPriority(Thread.MIN_PRIORITY); // UI has most priority m_IOThread.start(); } } catch (Exception ex) { JOptionPane.showMessageDialog(this, "Problem with URL:\n" + ex.getMessage(), "Load Instances", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(this, "Can't load at this time,\n" + "currently busy with other IO", "Load Instances", JOptionPane.WARNING_MESSAGE); } } /** * Loads results from a set of instances contained in the supplied file. * * @param f a value of type 'File' */ protected void setInstancesFromFile(File f) { boolean incremental = m_readIncrementally; try { // m_Loader = ConverterUtils.getLoaderForFile(f); m_Loader = m_FileChooser.getLoader(); if (m_Loader == null) throw new Exception( "No suitable FileSourcedConverter found for file!\n" + f); // not an incremental loader? if (!(m_Loader instanceof IncrementalConverter)) incremental = false; // load ((FileSourcedConverter) m_Loader).setFile(f); if (incremental) { m_Summary.setShowZeroInstancesAsUnknown(m_showZeroInstancesAsUnknown); setInstances(m_Loader.getStructure()); } else { // If we are batch loading then we will know for sure that // the data has no instances m_Summary.setShowZeroInstancesAsUnknown(false); setInstances(m_Loader.getDataSet()); } } catch (Exception ex) { JOptionPane.showMessageDialog(this, "Couldn't read from file:\n" + f.getName(), "Load Instances", JOptionPane.ERROR_MESSAGE); } } /** * Loads instances from a URL. * * @param u the URL to load from. */ protected void setInstancesFromURL(URL u) { boolean incremental = m_readIncrementally; try { m_Loader = ConverterUtils.getURLLoaderForFile(u.toString()); if (m_Loader == null) throw new Exception("No suitable URLSourcedLoader found for URL!\n" + u); // not an incremental loader? if (!(m_Loader instanceof IncrementalConverter)) incremental = false; // load ((URLSourcedLoader) m_Loader).setURL(u.toString()); if (incremental) { m_Summary.setShowZeroInstancesAsUnknown(m_showZeroInstancesAsUnknown); setInstances(m_Loader.getStructure()); } else { m_Summary.setShowZeroInstancesAsUnknown(false); setInstances(m_Loader.getDataSet()); } } catch (Exception ex) { JOptionPane.showMessageDialog(this, "Couldn't read from URL:\n" + u, "Load Instances", JOptionPane.ERROR_MESSAGE); } } /** * Updates the set of instances that is currently held by the panel. * * @param i a value of type 'Instances' */ public void setInstances(Instances i) { m_Instances = i; m_Summary.setInstances(m_Instances); if (m_showClassComboBox) { DefaultComboBoxModel model = (DefaultComboBoxModel) m_ClassComboBox .getModel(); model.removeAllElements(); model.addElement(NO_CLASS); for (int n = 0; n < m_Instances.numAttributes(); n++) { Attribute att = m_Instances.attribute(n); String type = "(" + Attribute.typeToStringShort(att) + ")"; model.addElement(type + " " + att.name()); } if (m_Instances.classIndex() == -1) m_ClassComboBox.setSelectedIndex(m_Instances.numAttributes()); else m_ClassComboBox.setSelectedIndex(m_Instances.classIndex() + 1); // +1 // because // of // NO_CLASS // element } // Fire property change event for those interested. m_Support.firePropertyChange("", null, null); } /** * Gets the set of instances currently held by the panel. * * @return a value of type 'Instances' */ public Instances getInstances() { return m_Instances; } /** * Returns the currently selected class index. * * @return the class index, -1 if none selected */ public int getClassIndex() { if (m_ClassComboBox.getSelectedIndex() <= 0) return -1; else return m_ClassComboBox.getSelectedIndex() - 1; } /** * Gets the currently used Loader. * * @return a value of type 'Loader' */ public weka.core.converters.Loader getLoader() { return m_Loader; } /** * Gets the instances summary panel associated with this panel. * * @return the instances summary panel */ public InstancesSummaryPanel getSummary() { return m_Summary; } /** * Sets whether or not instances should be read incrementally by the Loader. * If incremental reading is used, then the client should obtain the Loader * object (by calling getLoader()) and read the instances one at a time. If * batch loading is used, then SetInstancesPanel will load the data into * memory inside of a separate thread and notify the client when the operation * is complete. The client can then retrieve the instances by calling * getInstances(). * * @param incremental true if instances are to be read incrementally * */ public void setReadIncrementally(boolean incremental) { m_readIncrementally = incremental; } /** * Gets whether instances are to be read incrementally or not. * * @return true if instances are to be read incrementally */ public boolean getReadIncrementally() { return m_readIncrementally; } /** * Adds a PropertyChangeListener who will be notified of value changes. * * @param l a value of type 'PropertyChangeListener' */ @Override public void addPropertyChangeListener(PropertyChangeListener l) { if (m_Support != null) { m_Support.addPropertyChangeListener(l); } } /** * Removes a PropertyChangeListener. * * @param l a value of type 'PropertyChangeListener' */ @Override public void removePropertyChangeListener(PropertyChangeListener l) { m_Support.removePropertyChangeListener(l); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/SettingsEditor.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SettingsEditor.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import weka.classifiers.Classifier; import weka.clusterers.Clusterer; import weka.core.Environment; import weka.core.Settings; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Graphics; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Rectangle; import java.awt.Window; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyEditor; import java.beans.PropertyEditorManager; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; /** * Provides a panel for editing application and perspective settings * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class SettingsEditor extends JPanel { private static final long serialVersionUID = 1453121012707399758L; protected GUIApplication m_ownerApp; protected Settings m_settings; protected JTabbedPane m_settingsTabs = new JTabbedPane(); protected PerspectiveSelector m_perspectiveSelector; List<SingleSettingsEditor> m_perspectiveEditors = new ArrayList<SingleSettingsEditor>(); public SettingsEditor(Settings settings, GUIApplication ownerApp) { setLayout(new BorderLayout()); m_settings = settings; m_ownerApp = ownerApp; GenericObjectEditor.registerEditors(); PropertyEditorManager.registerEditor(Color.class, ColorEditor.class); if (m_ownerApp.getPerspectiveManager().getLoadedPerspectives().size() > 0) { setupPerspectiveSelector(); } setupPerspectiveSettings(); add(m_settingsTabs, BorderLayout.CENTER); } public void applyToSettings() { if (m_perspectiveSelector != null) { m_perspectiveSelector.applyToSettings(); } for (SingleSettingsEditor editor : m_perspectiveEditors) { editor.applyToSettings(); } } protected void setupPerspectiveSelector() { m_perspectiveSelector = new PerspectiveSelector(); m_settingsTabs.addTab("Perspectives", m_perspectiveSelector); } protected void setupPerspectiveSettings() { // any general settings? >1 because app settings have visible perspectives // settings if (m_settings.getSettings(m_ownerApp.getApplicationID()) != null && m_settings.getSettings(m_ownerApp.getApplicationID()).size() > 1) { Map<Settings.SettingKey, Object> appSettings = m_settings.getSettings(m_ownerApp.getApplicationID()); SingleSettingsEditor appEditor = new SingleSettingsEditor(appSettings); m_settingsTabs.addTab("General", appEditor); m_perspectiveEditors.add(appEditor); } // main perspective Perspective mainPers = m_ownerApp.getMainPerspective(); String mainTitle = mainPers.getPerspectiveTitle(); String mainID = mainPers.getPerspectiveID(); SingleSettingsEditor mainEditor = new SingleSettingsEditor(m_settings.getSettings(mainID)); m_settingsTabs.addTab(mainTitle, mainEditor); m_perspectiveEditors.add(mainEditor); List<Perspective> availablePerspectives = m_ownerApp.getPerspectiveManager().getLoadedPerspectives(); List<String> availablePerspectivesIDs = new ArrayList<String>(); List<String> availablePerspectiveTitles = new ArrayList<String>(); for (int i = 0; i < availablePerspectives.size(); i++) { Perspective p = availablePerspectives.get(i); availablePerspectivesIDs.add(p.getPerspectiveID()); availablePerspectiveTitles.add(p.getPerspectiveTitle()); } Set<String> settingsIDs = m_settings.getSettingsIDs(); for (String settingID : settingsIDs) { if (availablePerspectivesIDs.contains(settingID)) { int indexOfP = availablePerspectivesIDs.indexOf(settingID); // make a tab for this one Map<Settings.SettingKey, Object> settingsForID = m_settings.getSettings(settingID); if (settingsForID != null && settingsForID.size() > 0) { SingleSettingsEditor perpEditor = new SingleSettingsEditor(settingsForID); m_settingsTabs.addTab(availablePerspectiveTitles.get(indexOfP), perpEditor); m_perspectiveEditors.add(perpEditor); } } } } /** * Creates a single stand-alone settings editor panel * * @param settingsToEdit the settings to edit * @return a single settings editor panel for the supplied settings */ public static SingleSettingsEditor createSingleSettingsEditor( Map<Settings.SettingKey, Object> settingsToEdit) { GenericObjectEditor.registerEditors(); PropertyEditorManager.registerEditor(Color.class, ColorEditor.class); return new SingleSettingsEditor(settingsToEdit); } /** * Popup a single panel settings editor dialog for one group of related * settings * * @param settings the settings object containing (potentially) many groups of * settings * @param settingsID the ID of the particular set of settings to edit * @param settingsName the name of this related set of settings * @param parent the parent window * @return the result chosen by the user (JOptionPane.OK_OPTION or * JOptionPanel.CANCEL_OPTION) * @throws IOException if saving altered settings fails */ public static int showSingleSettingsEditor(Settings settings, String settingsID, String settingsName, JComponent parent) throws IOException { return showSingleSettingsEditor(settings, settingsID, settingsName, parent, 600, 300); } /** * Popup a single panel settings editor dialog for one group of related * settings * * @param settings the settings object containing (potentially) many groups of * settings * @param settingsID the ID of the particular set of settings to edit * @param settingsName the name of this related set of settings * @param parent the parent window * @param width the width for the dialog * @param height the height for the dialog * @return the result chosen by the user (JOptionPane.OK_OPTION or * JOptionPanel.CANCEL_OPTION) * @throws IOException if saving altered settings fails */ public static int showSingleSettingsEditor(Settings settings, String settingsID, String settingsName, JComponent parent, int width, int height) throws IOException { final SingleSettingsEditor sse = createSingleSettingsEditor(settings.getSettings(settingsID)); sse.setPreferredSize(new Dimension(width, height)); final JOptionPane pane = new JOptionPane(sse, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION); // There appears to be a bug in Java > 1.6 under Linux that, more often than // not, causes a sun.awt.X11.XException to occur when the following code // to make the dialog resizable is used. A workaround is to set the // suppressSwingDropSupport property to true (but this has to be done // at JVM startup, and setting it programatically, no matter how early, // does not seem to work). The hacky workaround here is to check for // a nix OS and disable the resizing, unless the user has specifically // used the -DsuppressSwingDropSupport=true JVM flag. // // See: http://bugs.java.com/view_bug.do?bug_id=7027598 // and: http://mipav.cit.nih.gov/pubwiki/index.php/FAQ:_Why_do_I_get_an_exception_when_running_MIPAV_via_X11_forwarding_on_Linux%3F String os = System.getProperty("os.name").toLowerCase(); String suppressSwingDropSupport = System.getProperty("suppressSwingDropSupport", "false"); boolean nix = os.contains("nix") || os.contains("nux") || os.contains("aix"); if (!nix || suppressSwingDropSupport.equalsIgnoreCase("true")) { pane.addHierarchyListener(new HierarchyListener() { @Override public void hierarchyChanged(HierarchyEvent e) { Window window = SwingUtilities.getWindowAncestor(pane); if (window instanceof Dialog) { Dialog dialog = (Dialog) window; if (!dialog.isResizable()) { dialog.setResizable(true); } } } }); } JDialog dialog = pane.createDialog((JComponent) parent, settingsName + " Settings"); dialog.show(); Object resultO = pane.getValue(); /* * int result = JOptionPane.showConfirmDialog(parent, sse, settingsName + * " Settings", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, * wekaIcon); */ int result = -1; if (resultO == null) { result = JOptionPane.CLOSED_OPTION; } else if (resultO instanceof Integer) { result = (Integer) resultO; } if (result == JOptionPane.OK_OPTION) { sse.applyToSettings(); settings.saveSettings(); } if (result == JOptionPane.OK_OPTION) { sse.applyToSettings(); settings.saveSettings(); } return result; } /** * Popup a settings editor for an application * * @param settings the settings object for the application * @param application the application itself * @return the result chosen by the user (JOptionPane.OK_OPTION or * JOptionPanel.CANCEL) * @throws IOException if saving altered settings fails */ public static int showApplicationSettingsEditor(Settings settings, GUIApplication application) throws IOException { final SettingsEditor settingsEditor = new SettingsEditor(settings, application); settingsEditor.setPreferredSize(new Dimension(800, 350)); final JOptionPane pane = new JOptionPane(settingsEditor, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION); // There appears to be a bug in Java > 1.6 under Linux that, more often than // not, causes a sun.awt.X11.XException to occur when the following code // to make the dialog resizable is used. A workaround is to set the // suppressSwingDropSupport property to true (but this has to be done // at JVM startup, and setting it programatically, no matter how early, // does not seem to work). The hacky workaround here is to check for // a nix OS and disable the resizing, unless the user has specifically // used the -DsuppressSwingDropSupport=true JVM flag. // // See: http://bugs.java.com/view_bug.do?bug_id=7027598 // and: http://mipav.cit.nih.gov/pubwiki/index.php/FAQ:_Why_do_I_get_an_exception_when_running_MIPAV_via_X11_forwarding_on_Linux%3F String os = System.getProperty("os.name").toLowerCase(); String suppressSwingDropSupport = System.getProperty("suppressSwingDropSupport", "false"); boolean nix = os.contains("nix") || os.contains("nux") || os.contains("aix"); if (!nix || suppressSwingDropSupport.equalsIgnoreCase("true")) { pane.addHierarchyListener(new HierarchyListener() { @Override public void hierarchyChanged(HierarchyEvent e) { Window window = SwingUtilities.getWindowAncestor(pane); if (window instanceof Dialog) { Dialog dialog = (Dialog) window; if (!dialog.isResizable()) { dialog.setResizable(true); } } } }); } JDialog dialog = pane.createDialog((JComponent) application, application.getApplicationName() + " Settings"); dialog.show(); Object resultO = pane.getValue(); int result = -1; if (resultO == null) { result = JOptionPane.CLOSED_OPTION; } else if (resultO instanceof Integer) { result = (Integer) resultO; } if (result == JOptionPane.OK_OPTION) { settingsEditor.applyToSettings(); settings.saveSettings(); } return result; } public static class SingleSettingsEditor extends JPanel implements PropertyChangeListener { private static final long serialVersionUID = 8896265984902770239L; protected Map<Settings.SettingKey, Object> m_perspSettings; protected Map<Settings.SettingKey, PropertyEditor> m_editorMap = new LinkedHashMap<Settings.SettingKey, PropertyEditor>(); public SingleSettingsEditor(Map<Settings.SettingKey, Object> pSettings) { m_perspSettings = pSettings; setLayout(new BorderLayout()); JPanel scrollablePanel = new JPanel(); JScrollPane scrollPane = new JScrollPane(scrollablePanel); scrollPane.setBorder(BorderFactory.createEmptyBorder()); add(scrollPane, BorderLayout.CENTER); GridBagLayout gbLayout = new GridBagLayout(); scrollablePanel.setLayout(gbLayout); setVisible(false); int i = 0; for (Map.Entry<Settings.SettingKey, Object> prop : pSettings.entrySet()) { Settings.SettingKey settingName = prop.getKey(); if (settingName.getKey() .equals(PerspectiveManager.VISIBLE_PERSPECTIVES_KEY.getKey())) { // skip this as we've got a dedicated panel for this one continue; } Object settingValue = prop.getValue(); List<String> pickList = prop.getKey().getPickList(); PropertyEditor editor = null; if (settingValue instanceof String && pickList != null && pickList.size() > 0) { // special case - list of legal values to choose from PickList pEditor = new PickList(pickList); pEditor.setValue(prop.getValue()); editor = pEditor; } Class<?> settingClass = settingValue.getClass(); if (editor == null) { editor = PropertyEditorManager.findEditor(settingClass); } // hardcoded check for File here because we don't register File as the // FileEnvironmentField does not play nicely with the standard GOE // practice // of listening/updating for every key stroke on text fields if (settingValue instanceof java.io.File) { String dialogType = settingName.getMetadataElement( "java.io.File.dialogType", "" + JFileChooser.OPEN_DIALOG); String fileType = settingName.getMetadataElement("java.io.File.fileSelectionMode", "" + JFileChooser.FILES_AND_DIRECTORIES); int dType = Integer.parseInt(dialogType); int fType = Integer.parseInt(fileType); editor = new FileEnvironmentField("", Environment.getSystemWide(), dType, fType == JFileChooser.DIRECTORIES_ONLY); } if (editor == null) { // TODO check for primitive classes (need to do this it seems to be // backward // compatible with Java 1.6 - PropertyEditorManager only has built in // editors // for primitive int, float etc.) if (settingValue instanceof Integer) { settingClass = Integer.TYPE; } else if (settingValue instanceof Float) { settingClass = Float.TYPE; } else if (settingValue instanceof Double) { settingClass = Double.TYPE; } else if (settingValue instanceof Boolean) { settingClass = Boolean.TYPE; } else if (settingValue instanceof Long) { settingClass = Long.TYPE; } else if (settingValue instanceof Short) { settingClass = Short.TYPE; } else if (settingValue instanceof Byte) { settingClass = Byte.TYPE; } // TODO need an editor for enums under Java 1.6 // try again editor = PropertyEditorManager.findEditor(settingClass); } // Check a few special cases - where the following // interfaces followed by superclass approach might get // fooled (i.e. classifiers that implement multiple interfaces // that themselves have entries in GUIEditors.props) if (editor == null) { if (settingValue instanceof Classifier) { editor = PropertyEditorManager.findEditor(Classifier.class); settingClass = Classifier.class; } else if (settingValue instanceof Clusterer) { editor = PropertyEditorManager.findEditor(Clusterer.class); settingClass = Clusterer.class; } } if (editor == null) { while (settingClass != null && editor == null) { // try interfaces first Class<?>[] interfaces = settingClass.getInterfaces(); if (interfaces != null) { for (Class intf : interfaces) { editor = PropertyEditorManager.findEditor(intf); if (editor != null) { settingClass = intf; break; } } } if (editor == null) { settingClass = settingClass.getSuperclass(); if (settingClass != null) { editor = PropertyEditorManager.findEditor(settingClass); } } } } if (editor != null) { if (editor instanceof GenericObjectEditor) { ((GenericObjectEditor) editor).setClassType(settingClass); } editor.addPropertyChangeListener(this); editor.setValue(settingValue); JComponent view = null; if (editor.isPaintable() && editor.supportsCustomEditor()) { view = new PropertyPanel(editor); } else if (editor.supportsCustomEditor() && (editor.getCustomEditor() instanceof JComponent)) { view = (JComponent) editor.getCustomEditor(); } else if (editor.getTags() != null) { view = new PropertyValueSelector(editor); } else if (editor.getAsText() != null) { view = new PropertyText(editor); } else { System.err.println("Warning: Property \"" + settingName + "\" has non-displayabale editor. Skipping."); continue; } m_editorMap.put(settingName, editor); JLabel propLabel = new JLabel(settingName.getDescription(), SwingConstants.RIGHT); if (prop.getKey().getToolTip().length() > 0) { propLabel.setToolTipText(prop.getKey().getToolTip()); view.setToolTipText(prop.getKey().getToolTip()); } propLabel.setBorder(BorderFactory.createEmptyBorder(10, 10, 0, 5)); GridBagConstraints gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = i; gbConstraints.gridx = 0; gbLayout.setConstraints(propLabel, gbConstraints); scrollablePanel.add(propLabel); JPanel newPanel = new JPanel(); newPanel.setBorder(BorderFactory.createEmptyBorder(10, 5, 0, 10)); newPanel.setLayout(new BorderLayout()); newPanel.add(view, BorderLayout.CENTER); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.WEST; gbConstraints.fill = GridBagConstraints.BOTH; gbConstraints.gridy = i; gbConstraints.gridx = 1; gbConstraints.weightx = 100; gbLayout.setConstraints(newPanel, gbConstraints); scrollablePanel.add(newPanel); i++; } else { System.err.println("SettingsEditor can't find an editor for: " + settingClass.toString()); } } Dimension dim = scrollablePanel.getPreferredSize(); dim.height += 20; dim.width += 20; scrollPane.setPreferredSize(dim); validate(); setVisible(true); } public void applyToSettings() { for (Map.Entry<Settings.SettingKey, Object> e : m_perspSettings .entrySet()) { Settings.SettingKey settingKey = e.getKey(); if (settingKey.getKey() .equals(PerspectiveManager.VISIBLE_PERSPECTIVES_KEY.getKey())) { continue; } PropertyEditor editor = m_editorMap.get(settingKey); if (editor != null) { Object newSettingValue = editor.getValue(); m_perspSettings.put(settingKey, newSettingValue); } } } @Override public void propertyChange(PropertyChangeEvent evt) { repaint(); revalidate(); } } protected class PerspectiveSelector extends JPanel { private static final long serialVersionUID = -4765015948030757897L; protected List<JCheckBox> m_perspectiveChecks = new ArrayList<JCheckBox>(); protected JCheckBox m_toolBarVisibleOnStartup = new JCheckBox("Perspective toolbar visible on start up"); public PerspectiveSelector() { setLayout(new BorderLayout()); List<Perspective> availablePerspectives = m_ownerApp.getPerspectiveManager().getLoadedPerspectives(); if (availablePerspectives.size() > 0) { PerspectiveManager.SelectedPerspectivePreferences userSelected = new PerspectiveManager.SelectedPerspectivePreferences(); userSelected = m_settings.getSetting(m_ownerApp.getApplicationID(), PerspectiveManager.VISIBLE_PERSPECTIVES_KEY, userSelected, Environment.getSystemWide()); JPanel p = new JPanel(); p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS)); if (!userSelected.getPerspectivesToolbarAlwaysHidden()) { p.add(m_toolBarVisibleOnStartup); m_toolBarVisibleOnStartup .setSelected(userSelected.getPerspectivesToolbarVisibleOnStartup()); } for (Perspective perspective : availablePerspectives) { String pName = perspective.getPerspectiveTitle(); JCheckBox jb = new JCheckBox(pName); jb.setSelected( userSelected.getUserVisiblePerspectives().contains(pName)); m_perspectiveChecks.add(jb); p.add(jb); } add(p, BorderLayout.CENTER); } } public void applyToSettings() { LinkedList<String> selectedPerspectives = new LinkedList<String>(); for (JCheckBox c : m_perspectiveChecks) { if (c.isSelected()) { selectedPerspectives.add(c.getText()); } } PerspectiveManager.SelectedPerspectivePreferences newPrefs = new PerspectiveManager.SelectedPerspectivePreferences(); newPrefs.setUserVisiblePerspectives(selectedPerspectives); newPrefs.setPerspectivesToolbarVisibleOnStartup( m_toolBarVisibleOnStartup.isSelected()); m_settings.setSetting(m_ownerApp.getApplicationID(), PerspectiveManager.VISIBLE_PERSPECTIVES_KEY, newPrefs); } } /** * Simple property editor for pick lists */ protected static class PickList extends JPanel implements PropertyEditor { private static final long serialVersionUID = 3505647427533464230L; protected JComboBox<String> m_list = new JComboBox<String>(); public PickList(List<String> list) { for (String item : list) { m_list.addItem(item); } setLayout(new BorderLayout()); add(m_list, BorderLayout.CENTER); } @Override public void setValue(Object value) { m_list.setSelectedItem(value.toString()); } @Override public Object getValue() { return m_list.getSelectedItem(); } @Override public boolean isPaintable() { return false; } @Override public void paintValue(Graphics gfx, Rectangle box) { } @Override public String getJavaInitializationString() { return null; } @Override public String getAsText() { return null; } @Override public void setAsText(String text) throws IllegalArgumentException { } @Override public String[] getTags() { return null; } @Override public Component getCustomEditor() { return this; } @Override public boolean supportsCustomEditor() { return true; } @Override public void addPropertyChangeListener(PropertyChangeListener listener) { } @Override public void removePropertyChangeListener(PropertyChangeListener listener) { } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/SimpleCLI.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SimpleCLI.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.awt.BorderLayout; import javax.swing.JFrame; import weka.gui.scripting.ScriptingPanel; /** * Creates a very simple command line for invoking the main method of * classes. System.out and System.err are redirected to an output area. * Features a simple command history -- use up and down arrows to move * through previous commmands. This gui uses only AWT (i.e. no Swing). * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class SimpleCLI extends JFrame { /** for serialization. */ static final long serialVersionUID = -50661410800566036L; /** * Constructor. * * @throws Exception if an error occurs */ public SimpleCLI() throws Exception { SimpleCLIPanel panel; panel = new SimpleCLIPanel(); setLayout(new BorderLayout()); setTitle(panel.getTitle()); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setIconImage(panel.getIcon().getImage()); add(panel); pack(); setSize(600, 500); setLocationRelativeTo(null); setVisible(true); } /** * Method to start up the simple cli. * * @param args Not used. */ public static void main(String[] args) { ScriptingPanel.showPanel(new SimpleCLIPanel(), args, 600, 500); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/SimpleCLIPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SimpleCLIPanel.java * Copyright (C) 2009-2018 University of Waikato, Hamilton, New Zealand */ package weka.gui; import weka.core.ClassDiscovery; import weka.core.Defaults; import weka.core.Instances; import weka.core.Trie; import weka.core.Utils; import weka.core.WekaPackageManager; import weka.gui.knowledgeflow.StepVisual; import weka.gui.scripting.ScriptingPanel; import weka.gui.simplecli.AbstractCommand; import weka.gui.simplecli.Help; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.SwingUtilities; import java.awt.BorderLayout; import java.awt.Cursor; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.PrintStream; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Vector; /** * Creates a very simple command line for invoking the main method of classes. * System.out and System.err are redirected to an output area. Features a simple * command history -- use up and down arrows to move through previous commmands. * This gui uses only AWT (i.e. no Swing). * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @author FracPete (fracpete at waikato dot ac dot nz) */ @PerspectiveInfo(ID = "simplecli", title = "Simple CLI", toolTipText = "Simple CLI for Weka", iconPath = "weka/gui/weka_icon_new_small.png") public class SimpleCLIPanel extends ScriptingPanel implements ActionListener, Perspective { /** for serialization. */ private static final long serialVersionUID = 1089039734615114942L; /** The filename of the properties file. */ protected static String FILENAME = "SimpleCLI.props"; /** The default location of the properties file. */ protected static String PROPERTY_FILE = "weka/gui/" + FILENAME; /** Contains the SimpleCLI properties. */ protected static Properties PROPERTIES; /** Main application (if any) owning this perspective */ protected GUIApplication m_mainApp; /** The Icon for this perspective */ protected Icon m_perspectiveIcon; static { // Allow a properties file in the current directory to override try { PROPERTIES = Utils.readProperties(PROPERTY_FILE); java.util.Enumeration<?> keys = PROPERTIES.propertyNames(); if (!keys.hasMoreElements()) { throw new Exception("Failed to read a property file for the SimpleCLI"); } } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Could not read a configuration file for the SimpleCLI.\n" + "An example file is included with the Weka distribution.\n" + "This file should be named \"" + PROPERTY_FILE + "\" and\n" + "should be placed either in your user home (which is set\n" + "to \"" + System.getProperties().getProperty("user.home") + "\")\n" + "or the directory that java was started from\n", "SimpleCLI", JOptionPane.ERROR_MESSAGE); } } /** The output area canvas added to the frame. */ protected JTextPane m_OutputArea; /** The command input area. */ protected JTextField m_Input; /** The history of commands entered interactively. */ protected Vector<String> m_CommandHistory; /** The current position in the command history. */ protected int m_HistoryPos; /** The thread currently running a class main method. */ protected Thread m_RunThread; /** The commandline completion. */ protected CommandlineCompletion m_Completion; /** for storing variables. */ protected Map<String,Object> m_Variables; @Override public void instantiationComplete() { } @Override public boolean okToBeActive() { return true; } @Override public void setActive(boolean active) { } @Override public void setLoaded(boolean loaded) { } @Override public void setMainApplication(GUIApplication main) { m_mainApp = main; } @Override public GUIApplication getMainApplication() { return m_mainApp; } @Override public String getPerspectiveID() { return "simplecli"; } @Override public String getPerspectiveTitle() { return "Simple CLI"; } @Override public Icon getPerspectiveIcon() { if (m_perspectiveIcon != null) { return m_perspectiveIcon; } PerspectiveInfo perspectiveA = this.getClass().getAnnotation(PerspectiveInfo.class); if (perspectiveA != null && perspectiveA.iconPath() != null && perspectiveA.iconPath().length() > 0) { m_perspectiveIcon = StepVisual.loadIcon(perspectiveA.iconPath()); } return m_perspectiveIcon; } @Override public String getPerspectiveTipText() { return "Simple CLI interface for Weka"; } @Override public List<JMenu> getMenus() { return null; } @Override public Defaults getDefaultSettings() { return null; } @Override public void settingsChanged() { } @Override public boolean acceptsInstances() { return false; } @Override public void setInstances(Instances instances) { } @Override public boolean requiresLog() { return false; } @Override public void setLog(Logger log) { } /** * A class that handles running the main method of the class in a separate * thread. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public static class ClassRunner extends Thread { /** the owner. */ protected SimpleCLIPanel m_Owner; /** Stores the main method to call. */ protected Method m_MainMethod; /** Stores the command line arguments to pass to the main method. */ String[] m_CommandArgs; /** True if the class to be executed is weka.Run */ protected boolean m_classIsRun; /** * Sets up the class runner thread. * * @param theClass the Class to call the main method of * @param commandArgs an array of Strings to use as command line args * @throws Exception if an error occurs */ public ClassRunner(SimpleCLIPanel owner, Class<?> theClass, String[] commandArgs) throws Exception { m_Owner = owner; m_classIsRun = (theClass.getClass().getName().equals("weka.Run")); setDaemon(true); Class<?>[] argTemplate = { String[].class }; m_CommandArgs = commandArgs; if (m_classIsRun) { if (!commandArgs[0].equalsIgnoreCase("-h") && !commandArgs[0].equalsIgnoreCase("-help")) { m_CommandArgs = new String[commandArgs.length + 1]; System.arraycopy(commandArgs, 0, m_CommandArgs, 1, commandArgs.length); m_CommandArgs[0] = "-do-not-prompt-if-multiple-matches"; } } m_MainMethod = theClass.getMethod("main", argTemplate); if (((m_MainMethod.getModifiers() & Modifier.STATIC) == 0) || (m_MainMethod.getModifiers() & Modifier.PUBLIC) == 0) { throw new NoSuchMethodException("main(String[]) method of " + theClass.getName() + " is not public and static."); } } /** * Starts running the main method. */ @Override public void run() { PrintStream outOld = null; PrintStream outNew = null; String outFilename = null; // is the output redirected? if (m_CommandArgs.length > 2) { String action = m_CommandArgs[m_CommandArgs.length - 2]; if (action.equals(">")) { outOld = System.out; try { outFilename = m_CommandArgs[m_CommandArgs.length - 1]; // since file may not yet exist, command-line completion doesn't // work, hence replace "~" manually with home directory if (outFilename.startsWith("~")) { outFilename = outFilename.replaceFirst("~", System.getProperty("user.home")); } outNew = new PrintStream(new File(outFilename)); System.setOut(outNew); m_CommandArgs[m_CommandArgs.length - 2] = ""; m_CommandArgs[m_CommandArgs.length - 1] = ""; // some main methods check the length of the "args" array // -> removed the two empty elements at the end String[] newArgs = new String[m_CommandArgs.length - 2]; System.arraycopy(m_CommandArgs, 0, newArgs, 0, m_CommandArgs.length - 2); m_CommandArgs = newArgs; } catch (Exception e) { System.setOut(outOld); outOld = null; } } } try { Object[] args = { m_CommandArgs }; m_MainMethod.invoke(null, args); if (isInterrupted()) { System.err.println("[...Interrupted]"); } } catch (Exception ex) { if (ex.getMessage() == null) { System.err.println("[...Killed]"); } else { System.err.println("[Run exception] " + ex.getMessage()); } } finally { m_Owner.stopThread(); } // restore old System.out stream if (outOld != null) { outNew.flush(); outNew.close(); System.setOut(outOld); System.out.println("Finished redirecting output to '" + outFilename + "'."); } } } /** * A class for commandline completion of classnames. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public static class CommandlineCompletion { /** all the available packages. */ protected Vector<String> m_Packages; /** a trie for storing the packages. */ protected Trie m_Trie; /** debug mode on/off. */ protected boolean m_Debug = false; /** * default constructor. */ public CommandlineCompletion() { super(); // build incremental list of packages if (m_Packages == null) { // get all packages Vector<String> list = ClassDiscovery.findPackages(); // create incremental list HashSet<String> set = new HashSet<String>(); for (int i = 0; i < list.size(); i++) { String[] parts = list.get(i).split("\\."); for (int n = 1; n < parts.length; n++) { String pkg = ""; for (int m = 0; m <= n; m++) { if (m > 0) { pkg += "."; } pkg += parts[m]; } set.add(pkg); } } // init packages m_Packages = new Vector<String>(); m_Packages.addAll(set); Collections.sort(m_Packages); m_Trie = new Trie(); m_Trie.addAll(m_Packages); } } /** * returns whether debug mode is on. * * @return true if debug is on */ public boolean getDebug() { return m_Debug; } /** * sets debug mode on/off. * * @param value if true then debug mode is on */ public void setDebug(boolean value) { m_Debug = value; } /** * tests whether the given partial string is the name of a class with * classpath - it basically tests, whether the string consists only of * alphanumeric literals, underscores and dots. * * @param partial the string to test * @return true if it looks like a classname */ public boolean isClassname(String partial) { return (partial.replaceAll("[a-zA-Z0-9\\-\\.]*", "").length() == 0); } /** * returns the packages part of the partial classname. * * @param partial the partial classname * @return the package part of the partial classname */ public String getPackage(String partial) { String result; int i; boolean wasDot; char c; result = ""; wasDot = false; for (i = 0; i < partial.length(); i++) { c = partial.charAt(i); // start of classname? if (wasDot && ((c >= 'A') && (c <= 'Z'))) { break; } // package/class separator else if (c == '.') { wasDot = true; result += "" + c; } // regular char else { wasDot = false; result += "" + c; } } // remove trailing "." if (result.endsWith(".")) { result = result.substring(0, result.length() - 1); } return result; } /** * returns the classname part of the partial classname. * * @param partial the partial classname * @return the class part of the classname */ public String getClassname(String partial) { String result; String pkg; pkg = getPackage(partial); if (pkg.length() + 1 < partial.length()) { result = partial.substring(pkg.length() + 1); } else { result = ""; } return result; } /** * returns all the file/dir matches with the partial search string. * * @param partial the partial search string * @return all the matches */ public Vector<String> getFileMatches(String partial) { Vector<String> result; File file; File dir; File[] files; int i; String prefix; boolean caseSensitive; String name; boolean match; result = new Vector<String>(); // is the OS case-sensitive? caseSensitive = (File.separatorChar != '\\'); if (m_Debug) { System.out.println("case-sensitive=" + caseSensitive); } // is "~" used for home directory? -> replace with actual home directory if (partial.startsWith("~")) { partial = System.getProperty("user.home") + partial.substring(1); } // determine dir and possible prefix file = new File(partial); dir = null; prefix = null; if (file.exists()) { // determine dir to read if (file.isDirectory()) { dir = file; prefix = null; // retrieve all } else { dir = file.getParentFile(); prefix = file.getName(); } } else { dir = file.getParentFile(); prefix = file.getName(); } if (m_Debug) { System.out.println("search in dir=" + dir + ", prefix=" + prefix); } // list all files in dir if (dir != null) { files = dir.listFiles(); if (files != null) { for (i = 0; i < files.length; i++) { name = files[i].getName(); // does the name match? if ((prefix != null) && caseSensitive) { match = name.startsWith(prefix); } else if ((prefix != null) && !caseSensitive) { match = name.toLowerCase().startsWith(prefix.toLowerCase()); } else { match = true; } if (match) { if (prefix != null) { result.add(partial.substring(0, partial.length() - prefix.length()) + name); } else { if (partial.endsWith("\\") || partial.endsWith("/")) { result.add(partial + name); } else { result.add(partial + File.separator + name); } } } } } else { System.err.println("Invalid path: " + partial); } } // sort the result if (result.size() > 1) { Collections.sort(result); } // print results if (m_Debug) { System.out.println("file matches:"); for (i = 0; i < result.size(); i++) { System.out.println(result.get(i)); } } return result; } /** * returns all the class/package matches with the partial search string. * * @param partial the partial search string * @return all the matches */ public Vector<String> getClassMatches(String partial) { String pkg; String cls; Vector<String> result; Vector<String> list; int i; int index; Trie tmpTrie; HashSet<String> set; String tmpStr; pkg = getPackage(partial); cls = getClassname(partial); if (getDebug()) { System.out.println("\nsearch for: '" + partial + "' => package=" + pkg + ", class=" + cls); } result = new Vector<String>(); // find all packages that start with that string if (cls.length() == 0) { list = m_Trie.getWithPrefix(pkg); set = new HashSet<String>(); for (i = 0; i < list.size(); i++) { tmpStr = list.get(i); if (tmpStr.length() < partial.length()) { continue; } if (tmpStr.equals(partial)) { continue; } index = tmpStr.indexOf('.', partial.length() + 1); if (index > -1) { set.add(tmpStr.substring(0, index)); } else { set.add(tmpStr); } } result.addAll(set); if (result.size() > 1) { Collections.sort(result); } } // find all classes that start with that string list = ClassDiscovery.find(Object.class, pkg); tmpTrie = new Trie(); tmpTrie.addAll(list); list = tmpTrie.getWithPrefix(partial); result.addAll(list); // sort the result if (result.size() > 1) { Collections.sort(result); } // print results if (m_Debug) { System.out.println("class/package matches:"); for (i = 0; i < result.size(); i++) { System.out.println(result.get(i)); } } return result; } /** * returns all the matches with the partial search string, files or classes. * * @param partial the partial search string * @return all the matches */ public Vector<String> getMatches(String partial) { if (isClassname(partial)) { return getClassMatches(partial); } else { return getFileMatches(partial); } } /** * returns the common prefix for all the items in the list. * * @param list the list to return the common prefix for * @return the common prefix of all the items */ public String getCommonPrefix(Vector<String> list) { String result; Trie trie; trie = new Trie(); trie.addAll(list); result = trie.getCommonPrefix(); if (m_Debug) { System.out.println(list + "\n --> common prefix: '" + result + "'"); } return result; } } /** * For initializing member variables. */ @Override protected void initialize() { super.initialize(); m_CommandHistory = new Vector<String>(); m_HistoryPos = 0; m_Completion = new CommandlineCompletion(); m_Variables = new HashMap<>(); } /** * Sets up the GUI after initializing the members. */ @Override protected void initGUI() { super.initGUI(); setLayout(new BorderLayout()); m_OutputArea = new JTextPane(); m_OutputArea.setEditable(false); m_OutputArea.setFont(new Font("Monospaced", Font.PLAIN, 12)); add(new JScrollPane(m_OutputArea), "Center"); m_Input = new JTextField(); m_Input.setFont(new Font("Monospaced", Font.PLAIN, 12)); m_Input.addActionListener(this); m_Input.setFocusTraversalKeysEnabled(false); m_Input.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { doHistory(e); doCommandlineCompletion(e); } }); add(m_Input, "South"); } /** * Finishes up after initializing members and setting up the GUI. */ @Override protected void initFinish() { super.initFinish(); System.out.println("\nWelcome to the WEKA SimpleCLI\n\n" + "Enter commands in the textfield at the bottom of \n" + "the window. Use the up and down arrows to move \n" + "through previous commands.\n" + "Command completion for classnames and files is \n" + "initiated with <Tab>. In order to distinguish \n" + "between files and classnames, file names must \n" + "be either absolute or start with '." + File.separator + "' or '~/'\n" + "(the latter is a shortcut for the home directory).\n" + "<Alt+BackSpace> is used for deleting the text\n" + "in the commandline in chunks.\n" + "\n" + "Type 'help' followed by <Enter> to see an overview \n" + "of all commands."); loadHistory(); SwingUtilities.invokeLater(() -> m_Input.requestFocus()); } /** * Returns an icon to be used in a frame. * * @return the icon */ @Override public ImageIcon getIcon() { return ComponentHelper.getImageIcon("weka_icon_new_48.png"); } /** * Returns the current title for the frame/dialog. * * @return the title */ @Override public String getTitle() { return "SimpleCLI"; } /** * Returns the text area that is used for displaying output on stdout and * stderr. * * @return the JTextArea */ @Override public JTextPane getOutput() { return m_OutputArea; } /** * Not supported. * * @return always null */ @Override public JMenuBar getMenuBar() { return null; } /** * Checks whether a thread is currently running. * * @return true if thread active */ public boolean isBusy() { return (m_RunThread != null); } /** * Starts the thread. * * @param runner the thread to start */ public void startThread(ClassRunner runner) { m_RunThread = runner; m_RunThread.setPriority(Thread.MIN_PRIORITY); // UI has most priority m_RunThread.start(); } /** * Stops the currently running thread, if any. */ @SuppressWarnings("deprecation") public void stopThread() { if (m_RunThread != null) { if (m_RunThread.isAlive()) { try { m_RunThread.stop(); } catch (Throwable t) { // ignored } } m_RunThread = null; } } /** * Returns the variables. * * @return the variables */ public Map<String,Object> getVariables() { return m_Variables; } /** * The output area. * * @return the output area */ public JTextPane getOutputArea() { return m_OutputArea; } /** * Returns the command history. * * @return the history */ public List<String> getCommandHistory() { return m_CommandHistory; } /** * Executes a simple cli command. * * @param command the command string * @throws Exception if an error occurs */ public void runCommand(String command) throws Exception { System.out.println("> " + command + '\n'); System.out.flush(); String[] commandArgs = Utils.splitOptions(command); // no command if (commandArgs.length == 0) { return; } // find command AbstractCommand cmd = AbstractCommand.getCommand(commandArgs[0]); // unknown command if (cmd == null) { System.err.println("Unknown command: " + commandArgs[0]); Help help = new Help(); help.setOwner(this); help.execute(new String[0]); return; } // execute command String[] params = new String[commandArgs.length -1]; System.arraycopy(commandArgs, 1, params, 0, params.length); cmd.setOwner(this); try { cmd.execute(params); } catch (Exception e) { System.err.println("Error executing: " + command); e.printStackTrace(); } } /** * Changes the currently displayed command line when certain keys are pressed. * The up arrow moves back through history entries and the down arrow moves * forward through history entries. * * @param e a value of type 'KeyEvent' */ public void doHistory(KeyEvent e) { if (e.getSource() == m_Input) { switch (e.getKeyCode()) { case KeyEvent.VK_UP: if (m_HistoryPos > 0) { m_HistoryPos--; String command = m_CommandHistory.elementAt(m_HistoryPos); m_Input.setText(command); } break; case KeyEvent.VK_DOWN: if (m_HistoryPos < m_CommandHistory.size()) { m_HistoryPos++; String command = ""; if (m_HistoryPos < m_CommandHistory.size()) { command = m_CommandHistory.elementAt(m_HistoryPos); } m_Input.setText(command); } break; default: break; } } } /** * performs commandline completion on packages and classnames. * * @param e a value of type 'KeyEvent' */ public void doCommandlineCompletion(KeyEvent e) { if (e.getSource() == m_Input) { switch (e.getKeyCode()) { // completion case KeyEvent.VK_TAB: if (e.getModifiers() == 0) { // it might take a while before we determined all of the possible // matches (Java doesn't have an application wide cursor handling??) m_Input.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); m_OutputArea .setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); try { String txt = m_Input.getText(); // java call? if (txt.trim().startsWith("java ")) { int pos = m_Input.getCaretPosition(); int nonNameCharPos = -1; // find first character not part of a name, back from current // position // i.e., " or blank for (int i = pos - 1; i >= 0; i--) { if ((txt.charAt(i) == '"') || (txt.charAt(i) == ' ')) { nonNameCharPos = i; break; } } if (nonNameCharPos > -1) { String search = txt.substring(nonNameCharPos + 1, pos); // find matches and common prefix Vector<String> list = m_Completion.getMatches(search); String common = m_Completion.getCommonPrefix(list); // just extending by separator is not a real extension if ((search.toLowerCase() + File.separator).equals(common .toLowerCase())) { common = search; } // can we complete the string? if (common.length() > search.length()) { try { m_Input.getDocument().remove(nonNameCharPos + 1, search.length()); m_Input.getDocument().insertString(nonNameCharPos + 1, common, null); } catch (Exception ex) { ex.printStackTrace(); } } // ambigiuous? -> print matches else if (list.size() > 1) { System.out.println("\nPossible matches:"); for (int i = 0; i < list.size(); i++) { System.out.println(" " + list.get(i)); } } else { // nothing found, don't do anything } } } } finally { // set cursor back to default m_Input.setCursor(null); m_OutputArea.setCursor(null); } } break; // delete last part up to next blank or dot case KeyEvent.VK_BACK_SPACE: if (e.getModifiers() == KeyEvent.ALT_MASK) { String txt = m_Input.getText(); int pos = m_Input.getCaretPosition(); // skip whitespaces int start = pos; start--; while (start >= 0) { if ((txt.charAt(start) == '.') || (txt.charAt(start) == ' ') || (txt.charAt(start) == '\\') || (txt.charAt(start) == '/')) { start--; } else { break; } } // find first blank or dot back from position int newPos = -1; for (int i = start; i >= 0; i--) { if ((txt.charAt(i) == '.') || (txt.charAt(i) == ' ') || (txt.charAt(i) == '\\') || (txt.charAt(i) == '/')) { newPos = i; break; } } // remove string try { m_Input.getDocument().remove(newPos + 1, pos - newPos - 1); } catch (Exception ex) { ex.printStackTrace(); } } break; } } } /** * Only gets called when return is pressed in the input area, which starts the * command running. * * @param e a value of type 'ActionEvent' */ @Override public void actionPerformed(ActionEvent e) { try { if (e.getSource() == m_Input) { String command = m_Input.getText(); int last = m_CommandHistory.size() - 1; if ((last < 0) || !command.equals(m_CommandHistory.elementAt(last))) { m_CommandHistory.addElement(command); saveHistory(); } m_HistoryPos = m_CommandHistory.size(); runCommand(command); m_Input.setText(""); } } catch (Exception ex) { System.err.println(ex.getMessage()); } } /** * loads the command history from the user's properties file. */ protected void loadHistory() { int size; int i; String cmd; size = Integer.parseInt(PROPERTIES.getProperty("HistorySize", "50")); m_CommandHistory.clear(); for (i = 0; i < size; i++) { cmd = PROPERTIES.getProperty("Command" + i, ""); if (cmd.length() != 0) { m_CommandHistory.add(cmd); } else { break; } } m_HistoryPos = m_CommandHistory.size(); } /** * saves the current command history in the user's home directory. */ protected void saveHistory() { int size; int from; int i; String filename; BufferedOutputStream stream; size = Integer.parseInt(PROPERTIES.getProperty("HistorySize", "50")); // determine first command to save from = m_CommandHistory.size() - size; if (from < 0) { from = 0; } // fill properties PROPERTIES.setProperty("HistorySize", "" + size); for (i = from; i < m_CommandHistory.size(); i++) { PROPERTIES.setProperty("Command" + (i - from), m_CommandHistory.get(i)); } try { filename = WekaPackageManager.PROPERTIES_DIR.getAbsolutePath() + File.separatorChar + FILENAME; stream = new BufferedOutputStream(new FileOutputStream(filename)); PROPERTIES.store(stream, "SimpleCLI"); stream.close(); } catch (Exception e) { e.printStackTrace(); } } /** * Displays the panel in a frame. * * @param args ignored */ public static void main(String[] args) { showPanel(new SimpleCLIPanel(), args); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/SimpleDateFormatEditor.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SimpleDateFormatEditor.java * Copyright (C) 2006-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.awt.Component; import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.beans.PropertyEditor; import java.text.SimpleDateFormat; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; /** * Class for editing SimpleDateFormat strings. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ * @see SimpleDateFormat */ public class SimpleDateFormatEditor implements PropertyEditor { /** the default format */ public final static String DEFAULT_FORMAT = "yyyy-MM-dd'T'HH:mm:ss"; /** The date format being edited */ private SimpleDateFormat m_Format; /** A helper class for notifying listeners */ private PropertyChangeSupport m_propSupport; /** An instance of the custom editor */ private CustomEditor m_customEditor; /** * This class presents a GUI for editing the cost matrix, and saving and * loading from files. */ private class CustomEditor extends JPanel implements ActionListener, DocumentListener { /** for serialization */ private static final long serialVersionUID = -4018834274636309987L; /** The text field for the format */ private JTextField m_FormatText; /** The button for setting a default date format */ private JButton m_DefaultButton; /** The button for applying the format */ private JButton m_ApplyButton; /** * Constructs a new CustomEditor. */ public CustomEditor() { m_FormatText = new JTextField(20); m_DefaultButton = new JButton("Default"); m_ApplyButton = new JButton("Apply"); m_DefaultButton.setMnemonic('D'); m_ApplyButton.setMnemonic('A'); m_FormatText.getDocument().addDocumentListener(this); m_DefaultButton.addActionListener(this); m_ApplyButton.addActionListener(this); setLayout(new FlowLayout()); add(new JLabel("ISO 8601 Date format")); add(m_FormatText); add(m_DefaultButton); add(m_ApplyButton); } /** * Responds to the user perfoming an action. * * @param e the action event that occured */ public void actionPerformed(ActionEvent e) { if (e.getSource() == m_DefaultButton) defaultFormat(); else if (e.getSource() == m_ApplyButton) applyFormat(); } /** * sets the format to default */ public void defaultFormat() { m_FormatText.setText(DEFAULT_FORMAT); formatChanged(); } /** * returns true if the current format is a valid format */ protected boolean isValidFormat() { boolean result; result = false; try { new SimpleDateFormat(m_FormatText.getText()); result = true; } catch (Exception e) { // we can ignore this exception } return result; } /** * sets the format, but only if it's a valid one */ public void applyFormat() { if (isValidFormat()) { m_Format = new SimpleDateFormat(m_FormatText.getText()); m_propSupport.firePropertyChange(null, null, null); } else { throw new IllegalArgumentException( "Date format '" + m_FormatText.getText() + "' is invalid! Cannot execute applyFormat!"); } } /** * Responds to a change of the text field. */ public void formatChanged() { m_FormatText.setText(m_Format.toPattern()); m_propSupport.firePropertyChange(null, null, null); } /** * Gives notification that an attribute or set of attributes changed. */ public void changedUpdate(DocumentEvent e) { m_ApplyButton.setEnabled(isValidFormat()); } /** * Gives notification that there was an insert into the document. */ public void insertUpdate(DocumentEvent e) { m_ApplyButton.setEnabled(isValidFormat()); } /** * Gives notification that a portion of the document has been removed. */ public void removeUpdate(DocumentEvent e) { m_ApplyButton.setEnabled(isValidFormat()); } } /** * Constructs a new SimpleDateFormatEditor. * */ public SimpleDateFormatEditor() { m_propSupport = new PropertyChangeSupport(this); m_customEditor = new CustomEditor(); } /** * Sets the value of the date format to be edited. * * @param value a SimpleDateFormat object to be edited */ public void setValue(Object value) { m_Format = (SimpleDateFormat) value; m_customEditor.formatChanged(); } /** * Gets the date format that is being edited. * * @return the edited SimpleDateFormat object */ public Object getValue() { return m_Format; } /** * Indicates whether the object can be represented graphically. In this case * it can. * * @return true */ public boolean isPaintable() { return true; } /** * Paints a graphical representation of the object. It just prints the * format. * * @param gfx the graphics context to draw the representation to * @param box the bounds within which the representation should fit. */ public void paintValue(Graphics gfx, Rectangle box) { gfx.drawString(m_Format.toPattern(), box.x, box.y + box.height); } /** * Returns the Java code that generates an object the same as the one being edited. * * @return the initialization string */ public String getJavaInitializationString() { return ("new SimpleDateFormat(" + m_Format.toPattern() + ")"); } /** * Returns the date format string. * * @return the date format string */ public String getAsText() { return m_Format.toPattern(); } /** * Sets the date format string. * * @param text the date format string */ public void setAsText(String text) { m_Format = new SimpleDateFormat(text); } /** * Some objects can return tags, but a date format cannot. * * @return null */ public String[] getTags() { return null; } /** * Gets a GUI component with which the user can edit the date format. * * @return an editor GUI component */ public Component getCustomEditor() { return m_customEditor; } /** * Indicates whether the date format can be edited in a GUI, which it can. * * @return true */ public boolean supportsCustomEditor() { return true; } /** * Adds an object to the list of those that wish to be informed when the * date format changes. * * @param listener a new listener to add to the list */ public void addPropertyChangeListener(PropertyChangeListener listener) { m_propSupport.addPropertyChangeListener(listener); } /** * Removes an object from the list of those that wish to be informed when the * date format changes. * * @param listener the listener to remove from the list */ public void removePropertyChangeListener(PropertyChangeListener listener) { m_propSupport.removePropertyChangeListener(listener); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/SortedTableModel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SortedTableModel.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import weka.core.InheritanceUtils; import javax.swing.JTable; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.AbstractTableModel; import javax.swing.table.JTableHeader; import javax.swing.table.TableColumnModel; import javax.swing.table.TableModel; import java.awt.event.InputEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Collections; /** * Represents a TableModel with sorting functionality. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class SortedTableModel extends AbstractTableModel implements TableModelListener { /** for serialization */ static final long serialVersionUID = 4030907921461127548L; /** * Helper class for sorting the columns. */ public static class SortContainer implements Comparable<SortContainer> { /** the value to sort. */ protected Comparable<?> m_Value; /** the index of the value. */ protected int m_Index; /** * Initializes the container. * * @param value the value to sort on * @param index the original index */ public SortContainer(Comparable<?> value, int index) { super(); m_Value = value; m_Index = index; } /** * Returns the value to sort on. * * @return the value */ public Comparable<?> getValue() { return m_Value; } /** * Returns the original index of the item. * * @return the index */ public int getIndex() { return m_Index; } /** * Compares this object with the specified object for order. Returns a * negative integer, zero, or a positive integer as this object is less * than, equal to, or greater than the specified object. Null is considered * smallest. If both values are null, then 0 is returned. * * @param o the object to be compared. * @return a negative integer, zero, or a positive integer as this object is * less than, equal to, or greater than the specified object. * @throws ClassCastException if the specified object's type prevents it * from being compared to this object. */ @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public int compareTo(SortContainer o) { if ((m_Value == null) || (o.getValue() == null)) { if (m_Value == o.getValue()) { return 0; } if (m_Value == null) { return -1; } else { return +1; } } else { return ((Comparable) m_Value).compareTo(o.getValue()); } } /** * Indicates whether some other object is "equal to" this one. * * @param obj the reference object with which to compare. * @return true if this object is the same as the obj argument; false * otherwise. * @throws ClassCastException if the specified object's type prevents it * from being compared to this object. */ @Override public boolean equals(Object obj) { return (compareTo((SortContainer) obj) == 0); } /** * Returns a string representation of the sort container. * * @return the string representation (value + index) */ @Override public String toString() { return "value=" + m_Value + ", index=" + m_Index; } } /** the actual table model */ protected TableModel mModel; /** the mapping between displayed and actual index */ protected int[] mIndices; /** the sort column */ protected int mSortColumn; /** whether sorting is ascending or descending */ protected boolean mAscending; /** * initializes with no model */ public SortedTableModel() { this(null); } /** * initializes with the given model * * @param model the model to initialize the sorted model with */ public SortedTableModel(TableModel model) { setModel(model); } /** * sets the model to use * * @param value the model to use */ public void setModel(TableModel value) { mModel = value; // initialize indices if (mModel == null) { mIndices = null; } else { initializeIndices(); mSortColumn = -1; mAscending = true; mModel.addTableModelListener(this); } } /** * (re-)initializes the indices */ protected void initializeIndices() { int i; mIndices = new int[mModel.getRowCount()]; for (i = 0; i < mIndices.length; i++) { mIndices[i] = i; } } /** * returns the current model, can be null * * @return the current model */ public TableModel getModel() { return mModel; } /** * returns whether the table was sorted * * @return true if the table was sorted */ public boolean isSorted() { return (mSortColumn > -1); } /** * whether the model is initialized * * @return true if the model is not null and the sort indices match the number * of rows */ protected boolean isInitialized() { return (getModel() != null); } /** * Returns the actual underlying row the given visible one represents. Useful * for retrieving "non-visual" data that is also stored in a TableModel. * * @param visibleRow the displayed row to retrieve the original row for * @return the original row */ public int getActualRow(int visibleRow) { if (!isInitialized()) { return -1; } else { return mIndices[visibleRow]; } } /** * Returns the most specific superclass for all the cell values in the column. * * @param columnIndex the index of the column * @return the class of the specified column */ @Override public Class<?> getColumnClass(int columnIndex) { if (!isInitialized()) { return null; } else { return getModel().getColumnClass(columnIndex); } } /** * Returns the number of columns in the model * * @return the number of columns in the model */ @Override public int getColumnCount() { if (!isInitialized()) { return 0; } else { return getModel().getColumnCount(); } } /** * Returns the name of the column at columnIndex * * @param columnIndex the column to retrieve the name for * @return the name of the specified column */ @Override public String getColumnName(int columnIndex) { if (!isInitialized()) { return null; } else { return getModel().getColumnName(columnIndex); } } /** * Returns the number of rows in the model. * * @return the number of rows in the model */ @Override public int getRowCount() { if (!isInitialized()) { return 0; } else { return getModel().getRowCount(); } } /** * Returns the value for the cell at columnIndex and rowIndex. * * @param rowIndex the row * @param columnIndex the column * @return the value of the sepcified cell */ @Override public Object getValueAt(int rowIndex, int columnIndex) { if (!isInitialized()) { return null; } else { return getModel().getValueAt(mIndices[rowIndex], columnIndex); } } /** * Returns true if the cell at rowIndex and columnIndex is editable. * * @param rowIndex the row * @param columnIndex the column * @return true if the cell is editable */ @Override public boolean isCellEditable(int rowIndex, int columnIndex) { if (!isInitialized()) { return false; } else { return getModel().isCellEditable(mIndices[rowIndex], columnIndex); } } /** * Sets the value in the cell at columnIndex and rowIndex to aValue. * * @param aValue the new value of the cell * @param rowIndex the row * @param columnIndex the column */ @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { if (isInitialized()) { getModel().setValueAt(aValue, mIndices[rowIndex], columnIndex); } } /** * sorts the table over the given column (ascending) * * @param columnIndex the column to sort over */ public void sort(int columnIndex) { sort(columnIndex, true); } /** * sorts the table over the given column, either ascending or descending * * @param columnIndex the column to sort over * @param ascending ascending if true, otherwise descending */ public void sort(int columnIndex, boolean ascending) { int columnType; int i; ArrayList<SortContainer> sorted; SortContainer cont; Object value; // can we sort? if ((!isInitialized()) || (getModel().getRowCount() != mIndices.length)) { System.out.println(this.getClass().getName() + ": Table model not initialized!"); return; } // init mSortColumn = columnIndex; mAscending = ascending; initializeIndices(); // determine the column type: 0=string/other, 1=comparable if (InheritanceUtils.hasInterface(Comparable.class, getColumnClass(mSortColumn))) { columnType = 1; } else { columnType = 0; } // create list for sorting sorted = new ArrayList<SortContainer>(); for (i = 0; i < getRowCount(); i++) { value = mModel.getValueAt(mIndices[i], mSortColumn); if (columnType == 0) { cont = new SortContainer((value == null) ? null : value.toString(), mIndices[i]); } else { cont = new SortContainer((Comparable<?>) value, mIndices[i]); } sorted.add(cont); } Collections.sort(sorted); for (i = 0; i < sorted.size(); i++) { if (mAscending) { mIndices[i] = sorted.get(i).getIndex(); } else { mIndices[i] = sorted.get(sorted.size() - 1 - i).getIndex(); } } sorted.clear(); sorted = null; } /** * This fine grain notification tells listeners the exact range of cells, * rows, or columns that changed. * * @param e the event */ @Override public void tableChanged(TableModelEvent e) { initializeIndices(); if (isSorted()) { sort(mSortColumn, mAscending); } fireTableChanged(e); } /** * Adds a mouselistener to the header: left-click on the header sorts in * ascending manner, using shift-left-click in descending manner. * * @param table the table to add the listener to */ public void addMouseListenerToHeader(JTable table) { final SortedTableModel modelFinal = this; final JTable tableFinal = table; tableFinal.setColumnSelectionAllowed(false); JTableHeader header = tableFinal.getTableHeader(); if (header != null) { MouseAdapter listMouseListener = new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { TableColumnModel columnModel = tableFinal.getColumnModel(); int viewColumn = columnModel.getColumnIndexAtX(e.getX()); int column = tableFinal.convertColumnIndexToModel(viewColumn); if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 1 && !e.isAltDown() && column != -1) { int shiftPressed = e.getModifiers() & InputEvent.SHIFT_MASK; boolean ascending = (shiftPressed == 0); modelFinal.sort(column, ascending); } } }; header.addMouseListener(listMouseListener); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/SplashWindow.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * @(#)SplashWindow.java 2.2 2005-04-03 * * Copyright (c) 2003-2005 Werner Randelshofer * Staldenmattweg 2, Immensee, CH-6405, Switzerland. * All rights reserved. * * This software is in the public domain. * */ package weka.gui; import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Frame; import java.awt.Graphics; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.MediaTracker; import java.awt.Toolkit; import java.awt.Window; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.geom.Ellipse2D; import java.net.URL; import java.util.List; /** * A Splash window. * <p> * Usage: MyApplication is your application class. Create a Splasher class which * opens the splash window, invokes the main method of your Application class, * and disposes the splash window afterwards. Please note that we want to keep * the Splasher class and the SplashWindow class as small as possible. The less * code and the less classes must be loaded into the JVM to open the splash * screen, the faster it will appear. * * <pre> * class Splasher { * public static void main(String[] args) { * SplashWindow.splash(Startup.class.getResource(&quot;splash.gif&quot;)); * MyApplication.main(args); * SplashWindow.disposeSplash(); * } * } * </pre> * * @author Werner Randelshofer * @author Mark Hall * @version $Revision$ */ public class SplashWindow extends Window { /** for serialization */ private static final long serialVersionUID = -2685134277041307795L; /** * The current instance of the splash window. (Singleton design pattern). */ private static SplashWindow m_instance; /** * The splash image which is displayed on the splash window. */ private final Image image; /** Any message to overlay on the image */ private final List<String> message; /** * This attribute indicates whether the method paint(Graphics) has been called * at least once since the construction of this window.<br> * This attribute is used to notify method splash(Image) that the window has * been drawn at least once by the AWT event dispatcher thread.<br> * This attribute acts like a latch. Once set to true, it will never be * changed back to false again. * * @see #paint * @see #splash */ private boolean paintCalled = false; /** * Creates a new instance. * * @param parent the parent of the window. * @param image the splash image. */ private SplashWindow(Frame parent, Image image, List<String> message) { super(parent); this.image = image; this.message = message; // Load the image MediaTracker mt = new MediaTracker(this); mt.addImage(image, 0); try { mt.waitForID(0); } catch (InterruptedException ie) { } // Center the window on the screen int imgWidth = image.getWidth(this); int imgHeight = image.getHeight(this); setSize(imgWidth, imgHeight); GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); if (ge.getDefaultScreenDevice().isWindowTranslucencySupported( GraphicsDevice.WindowTranslucency.PERPIXEL_TRANSLUCENT)) { // TODO this is if we are going to move to the big blue circular icon // for the splash window setShape(new Ellipse2D.Double(0, 0, getWidth(), getHeight())); } Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize(); setLocation((screenDim.width - imgWidth) / 2, (screenDim.height - imgHeight) / 2); // Users shall be able to close the splash window by // clicking on its display area. This mouse listener // listens for mouse clicks and disposes the splash window. MouseAdapter disposeOnClick = new MouseAdapter() { @Override public void mouseClicked(MouseEvent evt) { // Note: To avoid that method splash hangs, we // must set paintCalled to true and call notifyAll. // This is necessary because the mouse click may // occur before the contents of the window // has been painted. synchronized (SplashWindow.this) { SplashWindow.this.paintCalled = true; SplashWindow.this.notifyAll(); } dispose(); } }; addMouseListener(disposeOnClick); } /** * Updates the display area of the window. */ @Override public void update(Graphics g) { // Note: Since the paint method is going to draw an // image that covers the complete area of the component we // do not fill the component with its background color // here. This avoids flickering. paint(g); } private void paintMessage(Graphics g) { int imgWidth = image.getWidth(this); int imgHeight = image.getHeight(this); g.setFont(new Font(null, Font.BOLD, 10)); g.setColor(Color.WHITE); FontMetrics fm = g.getFontMetrics(); int hf = fm.getAscent() + 1; int heightStart = 4 * (imgHeight / 5) + 5; int count = 0; for (String s : message) { int textWidth = fm.stringWidth(s); g.drawString(s, (imgWidth - textWidth) / 2, heightStart + (count * hf)); count++; } } /** * Paints the image on the window. */ @Override public void paint(Graphics g) { g.drawImage(image, 0, 0, this); if (message != null) { paintMessage(g); } // Notify method splash that the window // has been painted. // Note: To improve performance we do not enter // the synchronized block unless we have to. if (!paintCalled) { paintCalled = true; synchronized (this) { notifyAll(); } } } /** * Open's a splash window using the specified image. * * @param image The splash image. */ @SuppressWarnings("deprecation") public static void splash(Image image, List<String> message) { if (m_instance == null && image != null) { Frame f = new Frame(); // Create the splash image m_instance = new SplashWindow(f, image, message); // Show the window. m_instance.show(); // Note: To make sure the user gets a chance to see the // splash window we wait until its paint method has been // called at least once by the AWT event dispatcher thread. // If more than one processor is available, we don't wait, // and maximize CPU throughput instead. if (!EventQueue.isDispatchThread() && Runtime.getRuntime().availableProcessors() == 1) { synchronized (m_instance) { while (!m_instance.paintCalled) { try { m_instance.wait(); } catch (InterruptedException e) { } } } } } } /** * Open's a splash window using the specified image. * * @param imageURL The url of the splash image. */ public static void splash(URL imageURL) { splash(imageURL, null); } /** * Open's a splash window using the specified image and message * * @param imageURL The url of the splash image. * @param message The message to overlay on the image */ public static void splash(URL imageURL, List<String> message) { if (imageURL != null) { splash(Toolkit.getDefaultToolkit().createImage(imageURL), message); } } /** * Closes the splash window. */ public static void disposeSplash() { if (m_instance != null) { m_instance.getOwner().dispose(); m_instance = null; } } /** * Invokes the named method of the provided class name. * * @param className the name of the class * @param methodName the name of the method to invoke * @param args the command line arguments */ public static void invokeMethod(String className, String methodName, String[] args) { try { Class.forName(className) .getMethod(methodName, new Class[] { String[].class }) .invoke(null, new Object[] { args }); } catch (Exception e) { InternalError error = new InternalError("Failed to invoke method: " + methodName); error.initCause(e); throw error; } } /** * Invokes the main method of the provided class name. * * @param className the name of the class * @param args the command line arguments */ public static void invokeMain(String className, String[] args) { try { Class.forName(className).getMethod("main", new Class[] { String[].class }) .invoke(null, new Object[] { args }); } catch (Exception e) { InternalError error = new InternalError("Failed to invoke main method"); error.initCause(e); throw error; } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/SysErrLog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SysErrLog.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.text.SimpleDateFormat; import java.util.Date; /** * This Logger just sends messages to System.err. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public class SysErrLog implements Logger { /** * Gets a string containing current date and time. * * @return a string containing the date and time. */ protected static String getTimestamp() { return (new SimpleDateFormat("yyyy.MM.dd hh:mm:ss")).format(new Date()); } /** * Sends the supplied message to the log area. The current timestamp will * be prepended. * * @param message a value of type 'String' */ public void logMessage(String message) { System.err.println("LOG " + SysErrLog.getTimestamp() + ": " + message); } /** * Sends the supplied message to the status line. * * @param message the status message */ public void statusMessage(String message) { System.err.println("STATUS: " + message); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/TaskLogger.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * TaskLogger.java * Copyright (C) 2000-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; /** * Interface for objects that display log and display information on * running tasks. * * @author Mark Hall (mhall@cs.waikato.ac.nz) * @version $Revision$ */ public interface TaskLogger { /** * Tells the task logger that a new task has been started */ void taskStarted(); /** * Tells the task logger that a task has completed */ void taskFinished(); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/ViewerDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ViewerDialog.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import weka.core.Instances; import weka.gui.arffviewer.ArffPanel; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JPanel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * A downsized version of the ArffViewer, displaying only one Instances-Object. * * * @see weka.gui.arffviewer.ArffViewer * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class ViewerDialog extends JDialog implements ChangeListener { /** for serialization */ private static final long serialVersionUID = 6747718484736047752L; /** Signifies an OK property selection */ public static final int APPROVE_OPTION = 0; /** Signifies a cancelled property selection */ public static final int CANCEL_OPTION = 1; /** the result of the user's action, either OK or CANCEL */ protected int m_Result = CANCEL_OPTION; /** Click to activate the current set parameters */ protected JButton m_OkButton = new JButton("OK"); /** Click to cancel the dialog */ protected JButton m_CancelButton = new JButton("Cancel"); /** Click to undo the last action */ protected JButton m_UndoButton = new JButton("Undo"); /** Click to add a new instance to the end of the dataset */ protected JButton m_addInstanceButton = new JButton("Add instance"); /** the panel to display the Instances-object */ protected ArffPanel m_ArffPanel = new ArffPanel(); /** * initializes the dialog with the given parent * * @param parent the parent for this dialog */ public ViewerDialog(Frame parent) { super(parent, ModalityType.DOCUMENT_MODAL); createDialog(); } /** * creates all the elements of the dialog */ protected void createDialog() { JPanel panel; setTitle("Viewer"); getContentPane().setLayout(new BorderLayout()); // ArffPanel m_ArffPanel.addChangeListener(this); getContentPane().add(m_ArffPanel, BorderLayout.CENTER); // Buttons panel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); getContentPane().add(panel, BorderLayout.SOUTH); m_UndoButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { undo(); } }); getContentPane().add(panel, BorderLayout.SOUTH); m_CancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { m_Result = CANCEL_OPTION; setVisible(false); } }); m_OkButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { m_Result = APPROVE_OPTION; setVisible(false); } }); m_addInstanceButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_ArffPanel.addInstanceAtEnd(); } }); panel.add(m_addInstanceButton); panel.add(m_UndoButton); panel.add(m_OkButton); panel.add(m_CancelButton); pack(); setLocationRelativeTo(getParent()); } /** * sets the instances to display */ public void setInstances(Instances inst) { m_ArffPanel.setInstances(new Instances(inst)); } /** * returns the currently displayed instances */ public Instances getInstances() { return m_ArffPanel.getInstances(); } /** * sets the state of the buttons */ protected void setButtons() { m_OkButton.setEnabled(true); m_CancelButton.setEnabled(true); m_UndoButton.setEnabled(m_ArffPanel.canUndo()); } /** * returns whether the data has been changed * * @return true if the data has been changed */ public boolean isChanged() { return m_ArffPanel.isChanged(); } /** * undoes the last action */ private void undo() { m_ArffPanel.undo(); } /** * Invoked when the target of the listener has changed its state. */ public void stateChanged(ChangeEvent e) { setButtons(); } /** * Pops up the modal dialog and waits for Cancel or OK. * * @return either APPROVE_OPTION, or CANCEL_OPTION */ public int showDialog() { m_Result = CANCEL_OPTION; setVisible(true); setButtons(); return m_Result; } /** * Pops up the modal dialog and waits for Cancel or OK. * * @param inst the instances to display * @return either APPROVE_OPTION, or CANCEL_OPTION */ public int showDialog(Instances inst) { setInstances(inst); return showDialog(); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/WekaTaskMonitor.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * WekaTaskMonitor.java * Copyright (C) 2000-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Image; import java.awt.Toolkit; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; /** * This panel records the number of weka tasks running and displays a * simple bird animation while their are active tasks * * @author Mark Hall (mhall@cs.waikato.ac.nz) * @version $Revision$ */ public class WekaTaskMonitor extends JPanel implements TaskLogger { /** for serialization */ private static final long serialVersionUID = 508309816292197578L; /** The number of running weka threads */ private int m_ActiveTasks = 0; /** The label for displaying info */ private JLabel m_MonitorLabel; /** The icon for the stationary bird */ private ImageIcon m_iconStationary; /** The icon for the animated bird */ private ImageIcon m_iconAnimated; /** True if their are active tasks */ private boolean m_animating = false; /** * Constructor */ public WekaTaskMonitor() { java.net.URL imageURL = this.getClass().getClassLoader().getResource("weka/gui/weka_stationary.gif"); if (imageURL != null) { Image pic = Toolkit.getDefaultToolkit().getImage(imageURL); imageURL = this.getClass().getClassLoader().getResource("weka/gui/weka_animated.gif"); Image pic2 = Toolkit.getDefaultToolkit().getImage(imageURL); /* Image pic = Toolkit.getDefaultToolkit(). getImage(ClassLoader.getSystemResource("weka/gui/weka_stationary.gif")); Image pic2 = Toolkit.getDefaultToolkit(). getImage(ClassLoader.getSystemResource("weka/gui/weka_animated.gif")); */ m_iconStationary = new ImageIcon(pic); m_iconAnimated = new ImageIcon(pic2); } m_MonitorLabel = new JLabel(" x "+m_ActiveTasks,m_iconStationary,SwingConstants.CENTER); /* setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("Weka Tasks"), BorderFactory.createEmptyBorder(0, 5, 5, 5) )); */ setLayout(new BorderLayout()); Dimension d = m_MonitorLabel.getPreferredSize(); m_MonitorLabel.setPreferredSize(new Dimension(d.width+15,d.height)); m_MonitorLabel.setMinimumSize(new Dimension(d.width+15,d.height)); add(m_MonitorLabel, BorderLayout.CENTER); } /** * Tells the panel that a new task has been started */ public synchronized void taskStarted() { m_ActiveTasks++; updateMonitor(); } /** * Tells the panel that a task has completed */ public synchronized void taskFinished() { m_ActiveTasks--; if (m_ActiveTasks < 0) { m_ActiveTasks = 0; } updateMonitor(); } /** * Updates the number of running tasks an the status of the bird * image */ private void updateMonitor() { m_MonitorLabel.setText(" x "+m_ActiveTasks); if (m_ActiveTasks > 0 && !m_animating) { m_MonitorLabel.setIcon(m_iconAnimated); m_animating = true; } if (m_ActiveTasks == 0 && m_animating) { m_MonitorLabel.setIcon(m_iconStationary); m_animating = false; } } /** * Main method for testing this class */ public static void main(String [] args) { try { final javax.swing.JFrame jf = new javax.swing.JFrame(); jf.getContentPane().setLayout(new BorderLayout()); final WekaTaskMonitor tm = new WekaTaskMonitor(); tm.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("Weka Tasks"), BorderFactory.createEmptyBorder(0, 5, 5, 5) )); jf.getContentPane().add(tm, BorderLayout.CENTER); jf.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { jf.dispose(); System.exit(0); } }); jf.pack(); jf.setVisible(true); tm.taskStarted(); } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/Workbench.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Workbench.java * Copyright (C) 2016 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import weka.core.Copyright; import weka.core.Version; import java.util.Arrays; import java.util.List; /** * Launcher class for the Weka workbench. Displays a splash screen and launches * the actual Workbench app (WorkbenchApp). * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class Workbench { public static void main(String[] args) { List<String> message = Arrays.asList("WEKA Workbench", "Version " + Version.VERSION, "(c) " + Copyright.getFromYear() + " - " + Copyright.getToYear(), "The University of Waikato", "Hamilton, New Zealand"); weka.gui.SplashWindow.splash( ClassLoader.getSystemResource("weka/gui/weka_icon_new.png"), message); weka.gui.SplashWindow.invokeMain("weka.gui.WorkbenchApp", args); weka.gui.SplashWindow.disposeSplash(); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/WorkbenchApp.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * WorkbenchApp * Copyright (C) 2016 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import weka.core.Capabilities; import weka.core.Defaults; import weka.core.Environment; import weka.core.Memory; import weka.core.Settings; import weka.core.converters.AbstractFileLoader; import weka.core.converters.ConverterUtils; import weka.gui.explorer.Explorer; import weka.gui.explorer.PreprocessPanel; import javax.swing.*; import java.awt.*; import java.io.File; import java.io.IOException; import java.util.List; /** * One app to rule them all, one app to find them, one app to * bring them all and with perspectives bind them. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class WorkbenchApp extends AbstractGUIApplication { private static final long serialVersionUID = -2357486011273897728L; /** for monitoring the Memory consumption */ protected static Memory m_Memory = new Memory(true); /** * variable for the Workbench class which would be set to null by the memory * monitoring thread to free up some memory if we running out of memory */ protected static WorkbenchApp m_workbench; /** The main perspective for this application */ protected PreprocessPanel m_mainPerspective; /** Settings for the Workbench */ protected Settings m_workbenchSettings; /** * Constructor */ public WorkbenchApp() { super(true, new String[0], new String[] { weka.gui.knowledgeflow.AttributeSummaryPerspective.class .getCanonicalName(), weka.gui.knowledgeflow.ScatterPlotMatrixPerspective.class .getCanonicalName(), weka.gui.knowledgeflow.SQLViewerPerspective.class.getCanonicalName() }); m_perspectiveManager .addSettingsMenuItemToProgramMenu(getApplicationSettings()); showPerspectivesToolBar(); List<Perspective> perspectives = m_perspectiveManager.getLoadedPerspectives(); for (Perspective p : perspectives) { m_perspectiveManager.setEnablePerspectiveTab(p.getPerspectiveID(), p.okToBeActive()); } } /** * Get the name of this application * * @return the name of this application */ @Override public String getApplicationName() { return WorkbenchDefaults.APP_NAME; } /** * Get the ID of this application * * @return the ID of this application */ @Override public String getApplicationID() { return WorkbenchDefaults.APP_ID; } /** * Get the main perspective of this application. In this case the * Preprocess panel is the main perspective. * * @return the main perspective of this application */ @Override public Perspective getMainPerspective() { if (m_mainPerspective == null) { m_mainPerspective = new PreprocessPanel(); } return m_mainPerspective; } /** * Called when the user changes settings */ @Override public void settingsChanged() { GenericObjectEditor.setShowGlobalInfoToolTips(getApplicationSettings() .getSetting(WorkbenchDefaults.APP_ID, WorkbenchDefaults.SHOW_JTREE_TIP_TEXT_KEY, WorkbenchDefaults.SHOW_JTREE_GLOBAL_INFO_TIPS, Environment.getSystemWide())); } /** * Notify filter capabilities listeners of changes * * @param filter the Capabilities object relating to filters */ public void notifyCapabilitiesFilterListeners(Capabilities filter) { for (Perspective p : getPerspectiveManager().getVisiblePerspectives()) { if (p instanceof Explorer.CapabilitiesFilterChangeListener) { ((Explorer.CapabilitiesFilterChangeListener) p) .capabilitiesFilterChanged(new Explorer.CapabilitiesFilterChangeEvent( this, filter)); } } } /** * Get the default settings for this application * * @return the default settings for this application */ @Override public Defaults getApplicationDefaults() { return new WorkbenchDefaults(); } /** * Main method. * * @param args command line arguments for the Workbench */ public static void main(String[] args) { try { LookAndFeel.setLookAndFeel(WorkbenchDefaults.APP_ID, WorkbenchDefaults.APP_ID + ".lookAndFeel", WorkbenchDefaults.LAF); } catch (IOException ex) { ex.printStackTrace(); } weka.gui.GenericObjectEditor.determineClasses(); try { if (System.getProperty("os.name").contains("Mac")) { System.setProperty("apple.laf.useScreenMenuBar", "true"); } m_workbench = new WorkbenchApp(); final javax.swing.JFrame jf = new javax.swing.JFrame("Weka " + m_workbench.getApplicationName()); jf.getContentPane().setLayout(new java.awt.BorderLayout()); Image icon = Toolkit.getDefaultToolkit().getImage( WorkbenchApp.class.getClassLoader().getResource( "weka/gui/weka_icon_new_48.png")); jf.setIconImage(icon); jf.getContentPane().add(m_workbench, BorderLayout.CENTER); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.pack(); m_workbench.showMenuBar(jf); jf.setSize(1024, 768); jf.setVisible(true); if (args.length == 1) { System.err.println("Loading instances from " + args[0]); AbstractFileLoader loader = ConverterUtils.getLoaderForFile(args[0]); loader.setFile(new File(args[0])); m_workbench.getPerspectiveManager().getMainPerspective() .setInstances(loader.getDataSet()); } Thread memMonitor = new Thread() { @Override public void run() { while (true) { // try { // System.out.println("Before sleeping."); // Thread.sleep(10); if (m_Memory.isOutOfMemory()) { // clean up jf.dispose(); m_workbench = null; System.gc(); // display error System.err.println("\ndisplayed message:"); m_Memory.showOutOfMemory(); System.err.println("\nexiting"); System.exit(-1); } } } }; memMonitor.setPriority(Thread.MAX_PRIORITY); memMonitor.start(); } catch (Exception ex) { ex.printStackTrace(); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/WorkbenchDefaults.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * WorkbenchDefaults.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui; import weka.core.Defaults; import weka.core.Settings; import java.util.List; /** * Default settings for the Workbench app. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class WorkbenchDefaults extends Defaults { public static final String APP_NAME = "Workbench"; public static final String APP_ID = "workbench"; protected static final Settings.SettingKey LAF_KEY = new Settings.SettingKey( APP_ID + ".lookAndFeel", "Look and feel for UI", "Note: a restart is required for this setting to come into effect"); protected static final String LAF = "javax.swing.plaf.nimbus.NimbusLookAndFeel"; protected static final Settings.SettingKey SHOW_JTREE_TIP_TEXT_KEY = new Settings.SettingKey(APP_ID + ".showGlobalInfoTipText", "Show scheme tool tips in tree view", ""); protected static final boolean SHOW_JTREE_GLOBAL_INFO_TIPS = true; protected static final Settings.SettingKey LOG_MESSAGE_FONT_SIZE_KEY = new Settings.SettingKey(APP_ID + ".logMessageFontSize", "Size of font for log " + "messages", "Size of font for log messages (-1 = system default)"); protected static final int LOG_MESSAGE_FONT_SIZE = -1; private static final long serialVersionUID = 7881327795923189743L; /** * Constructor */ public WorkbenchDefaults() { super(APP_ID); List<String> lafs = LookAndFeel.getAvailableLookAndFeelClasses(); lafs.add(0, "<use platform default>"); LAF_KEY.setPickList(lafs); m_defaults.put(LAF_KEY, LAF); m_defaults.put(SHOW_JTREE_TIP_TEXT_KEY, SHOW_JTREE_GLOBAL_INFO_TIPS); m_defaults.put(LOG_MESSAGE_FONT_SIZE_KEY, LOG_MESSAGE_FONT_SIZE); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/WrapLayout.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * WrapLayout.java * Public domain code from Java Tips Weblog: * https://tips4java.wordpress.com/about/ */ package weka.gui; import java.awt.*; import javax.swing.JScrollPane; import javax.swing.SwingUtilities; /** * FlowLayout subclass that fully supports wrapping of components. <br> */ public class WrapLayout extends FlowLayout { private static final long serialVersionUID = 7055023419450383821L; private Dimension preferredLayoutSize; /** * Constructs a new <code>WrapLayout</code> with a left alignment and a * default 5-unit horizontal and vertical gap. */ public WrapLayout() { super(); } /** * Constructs a new <code>FlowLayout</code> with the specified alignment and a * default 5-unit horizontal and vertical gap. The value of the alignment * argument must be one of <code>WrapLayout</code>, <code>WrapLayout</code>, * or <code>WrapLayout</code>. * * @param align the alignment value */ public WrapLayout(int align) { super(align); } /** * Creates a new flow layout manager with the indicated alignment and the * indicated horizontal and vertical gaps. * <p> * The value of the alignment argument must be one of <code>WrapLayout</code>, * <code>WrapLayout</code>, or <code>WrapLayout</code>. * * @param align the alignment value * @param hgap the horizontal gap between components * @param vgap the vertical gap between components */ public WrapLayout(int align, int hgap, int vgap) { super(align, hgap, vgap); } /** * Returns the preferred dimensions for this layout given the <i>visible</i> * components in the specified target container. * * @param target the component which needs to be laid out * @return the preferred dimensions to lay out the subcomponents of the * specified container */ @Override public Dimension preferredLayoutSize(Container target) { return layoutSize(target, true); } /** * Returns the minimum dimensions needed to layout the <i>visible</i> * components contained in the specified target container. * * @param target the component which needs to be laid out * @return the minimum dimensions to lay out the subcomponents of the * specified container */ @Override public Dimension minimumLayoutSize(Container target) { Dimension minimum = layoutSize(target, false); minimum.width -= (getHgap() + 1); return minimum; } /** * Returns the minimum or preferred dimension needed to layout the target * container. * * @param target target to get layout size for * @param preferred should preferred size be calculated * @return the dimension to layout the target container */ private Dimension layoutSize(Container target, boolean preferred) { synchronized (target.getTreeLock()) { // Each row must fit with the width allocated to the containter. // When the container width = 0, the preferred width of the container // has not yet been calculated so lets ask for the maximum. int targetWidth = target.getSize().width; Container container = target; while (container.getSize().width == 0 && container.getParent() != null) { container = container.getParent(); } targetWidth = container.getSize().width; if (targetWidth == 0) targetWidth = Integer.MAX_VALUE; int hgap = getHgap(); int vgap = getVgap(); Insets insets = target.getInsets(); int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2); int maxWidth = targetWidth - horizontalInsetsAndGap; // Fit components into the allowed width Dimension dim = new Dimension(0, 0); int rowWidth = 0; int rowHeight = 0; int nmembers = target.getComponentCount(); for (int i = 0; i < nmembers; i++) { Component m = target.getComponent(i); if (m.isVisible()) { Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize(); // Can't add the component to current row. Start a new row. if (rowWidth + d.width > maxWidth) { addRow(dim, rowWidth, rowHeight); rowWidth = 0; rowHeight = 0; } // Add a horizontal gap for all components after the first if (rowWidth != 0) { rowWidth += hgap; } rowWidth += d.width; rowHeight = Math.max(rowHeight, d.height); } } addRow(dim, rowWidth, rowHeight); dim.width += horizontalInsetsAndGap; dim.height += insets.top + insets.bottom + vgap * 2; // When using a scroll pane or the DecoratedLookAndFeel we need to // make sure the preferred size is less than the size of the // target containter so shrinking the container size works // correctly. Removing the horizontal gap is an easy way to do this. Container scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane.class, target); if (scrollPane != null && target.isValid()) { dim.width -= (hgap + 1); } return dim; } } /* * A new row has been completed. Use the dimensions of this row to update the * preferred size for the container. * * @param dim update the width and height when appropriate * * @param rowWidth the width of the row to add * * @param rowHeight the height of the row to add */ private void addRow(Dimension dim, int rowWidth, int rowHeight) { dim.width = Math.max(dim.width, rowWidth); if (dim.height > 0) { dim.height += getVgap(); } dim.height += rowHeight; } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/arffviewer/ArffPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ArffPanel.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.arffviewer; import weka.core.Instances; import weka.core.Undoable; import weka.core.Utils; import weka.core.converters.AbstractFileLoader; import weka.gui.ComponentHelper; import weka.gui.JTableHelper; import weka.gui.ListSelectorDialog; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.TableModelEvent; import java.awt.BorderLayout; import java.awt.Cursor; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Vector; /** * A Panel representing an ARFF-Table and the associated filename. * * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class ArffPanel extends JPanel implements ActionListener, ChangeListener, MouseListener, Undoable { /** for serialization */ static final long serialVersionUID = -4697041150989513939L; /** the name of the tab for instances that were set directly */ public final static String TAB_INSTANCES = "Instances"; /** the underlying table */ private ArffTable m_TableArff; /** the popup menu for the header row */ private JPopupMenu m_PopupHeader; /** the popup menu for the data rows */ private JPopupMenu m_PopupRows; /** displays the relation name */ private JLabel m_LabelName; /** whether to display the attribute index in the table header. */ private boolean m_ShowAttributeIndex; // menu items private JMenuItem menuItemMean; private JMenuItem menuItemSetAllValues; private JMenuItem menuItemSetMissingValues; private JMenuItem menuItemReplaceValues; private JMenuItem menuItemRenameAttribute; private JMenuItem menuItemSetAttributeWeight; private JMenuItem menuItemAttributeAsClass; private JMenuItem menuItemDeleteAttribute; private JMenuItem menuItemDeleteAttributes; private JMenuItem menuItemSortInstances; private JMenuItem menuItemDeleteSelectedInstance; private JMenuItem menuItemDeleteAllSelectedInstances; private JMenuItem menuItemInsertInstance; private JMenuItem menuItemSetInstanceWeight; private JMenuItem menuItemSearch; private JMenuItem menuItemClearSearch; private JMenuItem menuItemUndo; private JMenuItem menuItemCopy; private JMenuItem menuItemOptimalColWidth; private JMenuItem menuItemOptimalColWidths; /** the filename used in the title */ private String m_Filename; /** the title prefix */ private String m_Title; /** the currently selected column */ private int m_CurrentCol; /** flag for whether data got changed */ private boolean m_Changed; /** the listeners that listen for modifications */ private HashSet<ChangeListener> m_ChangeListeners; /** the string used in the last search */ private String m_LastSearch; /** the string used in the last replace */ private String m_LastReplace; /** * initializes the panel with no data */ public ArffPanel() { super(); initialize(); createPanel(); } /** * initializes the panel and loads the specified file * * @param filename the file to load * @param loaders optional varargs loader to use */ public ArffPanel(String filename, AbstractFileLoader... loaders) { this(); loadFile(filename, loaders); } /** * initializes the panel with the given data * * @param data the data to use */ public ArffPanel(Instances data) { this(); m_Filename = ""; setInstances(data); } /** * any member variables are initialized here */ protected void initialize() { m_Filename = ""; m_Title = ""; m_CurrentCol = -1; m_LastSearch = ""; m_LastReplace = ""; m_ShowAttributeIndex = true; m_Changed = false; m_ChangeListeners = new HashSet<ChangeListener>(); } /** * creates all the components in the frame */ protected void createPanel() { JScrollPane pane; setLayout(new BorderLayout()); menuItemMean = new JMenuItem("Get mean..."); menuItemMean.addActionListener(this); menuItemSetAllValues = new JMenuItem("Set all values to..."); menuItemSetAllValues.addActionListener(this); menuItemSetMissingValues = new JMenuItem("Set missing values to..."); menuItemSetMissingValues.addActionListener(this); menuItemReplaceValues = new JMenuItem("Replace values with..."); menuItemReplaceValues.addActionListener(this); menuItemRenameAttribute = new JMenuItem("Rename attribute..."); menuItemRenameAttribute.addActionListener(this); menuItemSetAttributeWeight = new JMenuItem("Set attribute weight..."); menuItemSetAttributeWeight.addActionListener(this); menuItemAttributeAsClass = new JMenuItem("Attribute as class"); menuItemAttributeAsClass.addActionListener(this); menuItemDeleteAttribute = new JMenuItem("Delete attribute"); menuItemDeleteAttribute.addActionListener(this); menuItemDeleteAttributes = new JMenuItem("Delete attributes..."); menuItemDeleteAttributes.addActionListener(this); menuItemSortInstances = new JMenuItem("Sort data (ascending)"); menuItemSortInstances.addActionListener(this); menuItemOptimalColWidth = new JMenuItem("Optimal column width (current)"); menuItemOptimalColWidth.addActionListener(this); menuItemOptimalColWidths = new JMenuItem("Optimal column width (all)"); menuItemOptimalColWidths.addActionListener(this); menuItemInsertInstance = new JMenuItem("Insert new instance"); menuItemSetInstanceWeight = new JMenuItem("Set instance weight"); // row popup menuItemUndo = new JMenuItem("Undo"); menuItemUndo.addActionListener(this); menuItemCopy = new JMenuItem("Copy"); menuItemCopy.addActionListener(this); menuItemSearch = new JMenuItem("Search..."); menuItemSearch.addActionListener(this); menuItemClearSearch = new JMenuItem("Clear search"); menuItemClearSearch.addActionListener(this); menuItemDeleteSelectedInstance = new JMenuItem("Delete selected instance"); menuItemDeleteSelectedInstance.addActionListener(this); menuItemDeleteAllSelectedInstances = new JMenuItem("Delete ALL selected instances"); menuItemDeleteAllSelectedInstances.addActionListener(this); menuItemInsertInstance.addActionListener(this); menuItemSetInstanceWeight.addActionListener(this); // table m_TableArff = new ArffTable(); m_TableArff.setToolTipText("Right click (or left+alt) for context menu"); m_TableArff.getTableHeader().addMouseListener(this); m_TableArff .getTableHeader() .setToolTipText( "<html><b>Sort view:</b> left click = ascending / Shift + left click = descending<br><b>Menu:</b> right click (or left+alt)</html>"); m_TableArff.getTableHeader() .setDefaultRenderer(new ArffTableCellRenderer()); m_TableArff.addChangeListener(this); m_TableArff.addMouseListener(this); pane = new JScrollPane(m_TableArff); add(pane, BorderLayout.CENTER); // relation name m_LabelName = new JLabel(); add(m_LabelName, BorderLayout.NORTH); } /** * initializes the popup menus */ private void initPopupMenus() { // header popup m_PopupHeader = new JPopupMenu(); m_PopupHeader.addMouseListener(this); m_PopupHeader.add(menuItemMean); if (!isReadOnly()) { m_PopupHeader.addSeparator(); m_PopupHeader.add(menuItemSetAllValues); m_PopupHeader.add(menuItemSetMissingValues); m_PopupHeader.add(menuItemReplaceValues); m_PopupHeader.addSeparator(); m_PopupHeader.add(menuItemRenameAttribute); m_PopupHeader.add(menuItemSetAttributeWeight); m_PopupHeader.add(menuItemAttributeAsClass); m_PopupHeader.add(menuItemDeleteAttribute); m_PopupHeader.add(menuItemDeleteAttributes); m_PopupHeader.add(menuItemSortInstances); } m_PopupHeader.addSeparator(); m_PopupHeader.add(menuItemOptimalColWidth); m_PopupHeader.add(menuItemOptimalColWidths); // row popup m_PopupRows = new JPopupMenu(); m_PopupRows.addMouseListener(this); if (!isReadOnly()) { m_PopupRows.add(menuItemUndo); m_PopupRows.addSeparator(); } m_PopupRows.add(menuItemCopy); m_PopupRows.addSeparator(); m_PopupRows.add(menuItemSearch); m_PopupRows.add(menuItemClearSearch); if (!isReadOnly()) { m_PopupRows.addSeparator(); m_PopupRows.add(menuItemDeleteSelectedInstance); m_PopupRows.add(menuItemDeleteAllSelectedInstances); m_PopupRows.add(menuItemInsertInstance); m_PopupRows.add(menuItemSetInstanceWeight); } } /** * sets the enabled/disabled state of the menu items */ private void setMenu() { boolean isNumeric; boolean hasColumns; boolean hasRows; boolean attSelected; ArffSortedTableModel model; boolean isNull; model = (ArffSortedTableModel) m_TableArff.getModel(); isNull = (model.getInstances() == null); hasColumns = !isNull && (model.getInstances().numAttributes() > 0); hasRows = !isNull && (model.getInstances().numInstances() > 0); attSelected = hasColumns && model.isAttribute(m_CurrentCol); isNumeric = attSelected && (model.getAttributeAt(m_CurrentCol).isNumeric()); menuItemUndo.setEnabled(canUndo()); menuItemCopy.setEnabled(true); menuItemSearch.setEnabled(true); menuItemClearSearch.setEnabled(true); menuItemMean.setEnabled(isNumeric); menuItemSetAllValues.setEnabled(attSelected); menuItemSetMissingValues.setEnabled(attSelected); menuItemReplaceValues.setEnabled(attSelected); menuItemRenameAttribute.setEnabled(attSelected); menuItemSetAttributeWeight.setEnabled(attSelected); menuItemDeleteAttribute.setEnabled(attSelected); menuItemDeleteAttributes.setEnabled(attSelected); menuItemAttributeAsClass.setEnabled(attSelected); menuItemSortInstances.setEnabled(hasRows && (attSelected || m_CurrentCol == 1)); menuItemDeleteSelectedInstance.setEnabled(hasRows && m_TableArff.getSelectedRow() > -1); menuItemDeleteAllSelectedInstances.setEnabled(hasRows && (m_TableArff.getSelectedRows().length > 0)); } /** * returns the table component * * @return the table */ public ArffTable getTable() { return m_TableArff; } /** * returns the title for the Tab, i.e. the filename * * @return the title for the tab */ public String getTitle() { return m_Title; } /** * returns the filename * * @return the filename */ public String getFilename() { return m_Filename; } /** * sets the filename * * @param filename the new filename */ public void setFilename(String filename) { m_Filename = filename; createTitle(); } /** * returns the instances of the panel, if none then NULL * * @return the instances of the panel */ public Instances getInstances() { Instances result; result = null; if (m_TableArff.getModel() != null) { result = ((ArffSortedTableModel) m_TableArff.getModel()).getInstances(); } return result; } /** * displays the given instances, i.e. creates a tab with the title * TAB_INSTANCES. if one already exists it closes it.<br> * if a different instances object is used here, don't forget to clear the * undo-history by calling <code>clearUndo()</code> * * @param data the instances to display * @see #TAB_INSTANCES * @see #clearUndo() */ public void setInstances(Instances data) { ArffSortedTableModel model; m_Filename = TAB_INSTANCES; createTitle(); model = new ArffSortedTableModel(data); model.setShowAttributeIndex(m_ShowAttributeIndex); m_TableArff.setModel(model); clearUndo(); setChanged(false); createName(); } /** * returns a list with the attributes * * @return a list of the attributes */ public Vector<String> getAttributes() { Vector<String> result; int i; result = new Vector<String>(); for (i = 0; i < getInstances().numAttributes(); i++) { result.add(getInstances().attribute(i).name()); } Collections.sort(result); return result; } /** * can only reset the changed state to FALSE * * @param changed if false, resets the changed state */ public void setChanged(boolean changed) { if (!changed) { this.m_Changed = changed; createTitle(); } } /** * returns whether the content of the panel was changed * * @return true if the content was changed */ public boolean isChanged() { return m_Changed; } /** * returns whether the model is read-only * * @return true if model is read-only */ public boolean isReadOnly() { if (m_TableArff == null) { return true; } else { return ((ArffSortedTableModel) m_TableArff.getModel()).isReadOnly(); } } /** * sets whether the model is read-only * * @param value if true the model is set to read-only */ public void setReadOnly(boolean value) { if (m_TableArff != null) { ((ArffSortedTableModel) m_TableArff.getModel()).setReadOnly(value); } } /** * Sets whether to display the attribute index in the header. * * @param value if true then the attribute indices are displayed in the table * header */ public void setShowAttributeIndex(boolean value) { m_ShowAttributeIndex = value; if (m_TableArff != null) { ((ArffSortedTableModel) m_TableArff.getModel()) .setShowAttributeIndex(value); } } /** * Returns whether to display the attribute index in the header. * * @return true if the attribute indices are displayed in the table header */ public boolean getShowAttributeIndex() { return m_ShowAttributeIndex; } /** * returns whether undo support is enabled * * @return true if undo is enabled */ @Override public boolean isUndoEnabled() { return ((ArffSortedTableModel) m_TableArff.getModel()).isUndoEnabled(); } /** * sets whether undo support is enabled * * @param enabled whether to enable/disable undo support */ @Override public void setUndoEnabled(boolean enabled) { ((ArffSortedTableModel) m_TableArff.getModel()).setUndoEnabled(enabled); } /** * removes the undo history */ @Override public void clearUndo() { ((ArffSortedTableModel) m_TableArff.getModel()).clearUndo(); } /** * returns whether an undo is possible * * @return true if undo is possible */ @Override public boolean canUndo() { return ((ArffSortedTableModel) m_TableArff.getModel()).canUndo(); } /** * performs an undo action */ @Override public void undo() { if (canUndo()) { ((ArffSortedTableModel) m_TableArff.getModel()).undo(); // notify about update notifyListener(); } } /** * adds the current state of the instances to the undolist */ @Override public void addUndoPoint() { ((ArffSortedTableModel) m_TableArff.getModel()).addUndoPoint(); // update menu setMenu(); } /** * sets the title (i.e. filename) */ private void createTitle() { File file; if (m_Filename.equals("")) { m_Title = "-none-"; } else if (m_Filename.equals(TAB_INSTANCES)) { m_Title = TAB_INSTANCES; } else { try { file = new File(m_Filename); m_Title = file.getName(); } catch (Exception e) { m_Title = "-none-"; } } if (isChanged()) { m_Title += " *"; } } /** * sets the relation name */ private void createName() { ArffSortedTableModel model; model = (ArffSortedTableModel) m_TableArff.getModel(); if ((model != null) && (model.getInstances() != null)) { m_LabelName.setText("Relation: " + model.getInstances().relationName()); } else { m_LabelName.setText(""); } } /** * loads the specified file into the table * * @param filename the file to load * @param loaders optional varargs loader to use */ private void loadFile(String filename, AbstractFileLoader... loaders) { ArffSortedTableModel model; this.m_Filename = filename; createTitle(); if (filename.equals("")) { model = null; } else { model = new ArffSortedTableModel(filename, loaders); model.setShowAttributeIndex(getShowAttributeIndex()); } m_TableArff.setModel(model); setChanged(false); createName(); } /** * calculates the mean of the given numeric column */ private void calcMean() { ArffSortedTableModel model; int i; double mean; // no column selected? if (m_CurrentCol == -1) { return; } model = (ArffSortedTableModel) m_TableArff.getModel(); // not numeric? if (!model.getAttributeAt(m_CurrentCol).isNumeric()) { return; } mean = 0; for (i = 0; i < model.getRowCount(); i++) { mean += model.getInstances().instance(i).value(model.getAttributeIndex(m_CurrentCol)); } mean = mean / model.getRowCount(); // show result ComponentHelper.showMessageBox(getParent(), "Mean for attribute...", "Mean for attribute '" + m_TableArff.getPlainColumnName(m_CurrentCol) + "':\n\t" + Utils.doubleToString(mean, 3), JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); } /** * sets the specified values in a column to a new value * * @param o the menu item */ private void setValues(Object o) { String msg; String title; String value; String valueNew; int i; ArffSortedTableModel model; value = ""; valueNew = ""; if (o == menuItemSetMissingValues) { title = "Replace missing values..."; msg = "New value for MISSING values"; } else if (o == menuItemSetAllValues) { title = "Set all values..."; msg = "New value for ALL values"; } else if (o == menuItemReplaceValues) { title = "Replace values..."; msg = "Old value"; } else { return; } value = ComponentHelper.showInputBox(m_TableArff.getParent(), title, msg, m_LastSearch); // cancelled? if (value == null) { return; } m_LastSearch = value; // replacement if (o == menuItemReplaceValues) { valueNew = ComponentHelper.showInputBox(m_TableArff.getParent(), title, "New value", m_LastReplace); if (valueNew == null) { return; } m_LastReplace = valueNew; } model = (ArffSortedTableModel) m_TableArff.getModel(); model.setNotificationEnabled(false); // undo addUndoPoint(); model.setUndoEnabled(false); String valueCopy = value; String valueNewCopy = valueNew; // set value for (i = 0; i < m_TableArff.getRowCount(); i++) { if (o == menuItemSetAllValues) { if (valueCopy.equals("NaN") || valueCopy.equals("?")) { value = null; } model.setValueAt(value, i, m_CurrentCol); } else if ((o == menuItemSetMissingValues) && model.isMissingAt(i, m_CurrentCol)) { model.setValueAt(value, i, m_CurrentCol); } else if ((o == menuItemReplaceValues) && model.getValueAt(i, m_CurrentCol) != null && model.getValueAt(i, m_CurrentCol).toString().equals(value)) { if (valueNewCopy.equals("NaN") || valueNewCopy.equals("?")) { valueNew = null; } model.setValueAt(valueNew, i, m_CurrentCol); } } model.setUndoEnabled(true); model.setNotificationEnabled(true); model.notifyListener(new TableModelEvent(model, 0, model.getRowCount(), m_CurrentCol, TableModelEvent.UPDATE)); // refresh m_TableArff.repaint(); } /** * deletes the currently selected attribute */ public void deleteAttribute() { ArffSortedTableModel model; // no column selected? if (m_CurrentCol == -1) { return; } model = (ArffSortedTableModel) m_TableArff.getModel(); // really an attribute column? if (model.getAttributeAt(m_CurrentCol) == null) { return; } // really? if (ComponentHelper.showMessageBox( getParent(), "Confirm...", "Do you really want to delete the attribute '" + model.getAttributeAt(m_CurrentCol).name() + "'?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) { return; } setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); model.deleteAttributeAt(m_CurrentCol); setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } /** * deletes the chosen attributes */ public void deleteAttributes() { ListSelectorDialog dialog; ArffSortedTableModel model; Object[] atts; int[] indices; int i; JList list; int result; list = new JList(getAttributes()); dialog = new ListSelectorDialog(SwingUtilities.getWindowAncestor(this), list); result = dialog.showDialog(); if (result != ListSelectorDialog.APPROVE_OPTION) { return; } atts = list.getSelectedValues(); // really? if (ComponentHelper.showMessageBox(getParent(), "Confirm...", "Do you really want to delete these " + atts.length + " attributes?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) { return; } model = (ArffSortedTableModel) m_TableArff.getModel(); indices = new int[atts.length]; for (i = 0; i < atts.length; i++) { indices[i] = model.getAttributeColumn(atts[i].toString()); } setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); model.deleteAttributes(indices); setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } /** * sets the current attribute as class attribute, i.e. it moves it to the end * of the attributes */ public void attributeAsClass() { ArffSortedTableModel model; // no column selected? if (m_CurrentCol == -1) { return; } model = (ArffSortedTableModel) m_TableArff.getModel(); // really an attribute column? if (model.getAttributeAt(m_CurrentCol) == null) { return; } setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); model.attributeAsClassAt(m_CurrentCol); setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } /** * renames the current attribute */ public void renameAttribute() { ArffSortedTableModel model; String newName; // no column selected? if (m_CurrentCol == -1) { return; } model = (ArffSortedTableModel) m_TableArff.getModel(); // really an attribute column? if (model.getAttributeAt(m_CurrentCol) == null) { return; } newName = ComponentHelper.showInputBox(getParent(), "Rename attribute...", "Enter new Attribute name", model.getAttributeAt(m_CurrentCol).name()); if (newName == null) { return; } setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); model.renameAttributeAt(m_CurrentCol, newName); setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } /** * sets the weight for the current attribute */ public void setAttributeWeight() { ArffSortedTableModel model; double newWeight = Double.NaN; // no column selected? if (m_CurrentCol == -1) { return; } model = (ArffSortedTableModel) m_TableArff.getModel(); // really an attribute column? if (model.getAttributeAt(m_CurrentCol) == null) { return; } try { newWeight = Double.parseDouble(ComponentHelper.showInputBox(getParent(), "Set attribute weight...", "Enter a new weight for the attribute", model.getAttributeAt(m_CurrentCol).weight())); } catch (Exception ex) { // Silently ignore } if (Double.isNaN(newWeight)) { return; } setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); model.setAttributeWeightAt(m_CurrentCol, newWeight); setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } /** * deletes the currently selected instance */ public void deleteInstance() { int index; index = m_TableArff.getSelectedRow(); if (index == -1) { return; } ((ArffSortedTableModel) m_TableArff.getModel()).deleteInstanceAt(index); } /** * Add an instance at the currently selected index. If no instance is selected * then adds a new instance at the end of the dataset. */ public void addInstance() { int index = m_TableArff.getSelectedRow(); ((ArffSortedTableModel) m_TableArff.getModel()).insertInstance(index); } /** * Allows setting the weight of the instance at the selected row. */ public void setInstanceWeight() { int index = m_TableArff.getSelectedRow(); if (index == -1) { return; } String newWeight = ComponentHelper.showInputBox(getParent(), "Set instance weight...", "Enter new instance weight", ((ArffSortedTableModel) m_TableArff.getModel()).getInstances().instance(index).weight()); if (newWeight == null) { return; } double weight = 1.0; try { weight = Double.parseDouble(newWeight); } catch (Exception ex) { return; } ((ArffSortedTableModel) m_TableArff.getModel()).setInstanceWeight(index, weight); } /** * Add an instance at the end of the dataset */ public void addInstanceAtEnd() { ((ArffSortedTableModel) m_TableArff.getModel()).insertInstance(-1); } /** * deletes all the currently selected instances */ public void deleteInstances() { int[] indices; if (m_TableArff.getSelectedRow() == -1) { return; } indices = m_TableArff.getSelectedRows(); ((ArffSortedTableModel) m_TableArff.getModel()).deleteInstances(indices); } /** * sorts the instances via the currently selected column */ public void sortInstances() { if (m_CurrentCol == -1) { return; } ((ArffSortedTableModel) m_TableArff.getModel()).sortInstances(m_CurrentCol); } /** * copies the content of the selection to the clipboard */ public void copyContent() { StringSelection selection; Clipboard clipboard; selection = getTable().getStringSelection(); if (selection == null) { return; } clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(selection, selection); } /** * searches for a string in the cells */ public void search() { String searchString; // display dialog searchString = ComponentHelper.showInputBox(getParent(), "Search...", "Enter the string to search for", m_LastSearch); if (searchString != null) { m_LastSearch = searchString; } getTable().setSearchString(searchString); } /** * clears the search, i.e. resets the found cells */ public void clearSearch() { getTable().setSearchString(""); } /** * calculates the optimal column width for the current column */ public void setOptimalColWidth() { // no column selected? if (m_CurrentCol == -1) { return; } JTableHelper.setOptimalColumnWidth(getTable(), m_CurrentCol); } /** * calculates the optimal column widths for all columns */ public void setOptimalColWidths() { JTableHelper.setOptimalColumnWidth(getTable()); } /** * invoked when an action occurs * * @param e the action event */ @Override public void actionPerformed(ActionEvent e) { Object o; o = e.getSource(); if (o == menuItemMean) { calcMean(); } else if (o == menuItemSetAllValues) { setValues(menuItemSetAllValues); } else if (o == menuItemSetMissingValues) { setValues(menuItemSetMissingValues); } else if (o == menuItemReplaceValues) { setValues(menuItemReplaceValues); } else if (o == menuItemRenameAttribute) { renameAttribute(); } else if (o == menuItemSetAttributeWeight) { setAttributeWeight(); } else if (o == menuItemAttributeAsClass) { attributeAsClass(); } else if (o == menuItemDeleteAttribute) { deleteAttribute(); } else if (o == menuItemDeleteAttributes) { deleteAttributes(); } else if (o == menuItemDeleteSelectedInstance) { deleteInstance(); } else if (o == menuItemDeleteAllSelectedInstances) { deleteInstances(); } else if (o == menuItemInsertInstance) { addInstance(); } else if (o == menuItemSetInstanceWeight) { setInstanceWeight(); } else if (o == menuItemSearch) { search(); } else if (o == menuItemClearSearch) { clearSearch(); } else if (o == menuItemUndo) { undo(); } else if (o == menuItemCopy) { copyContent(); } else if (o == menuItemOptimalColWidth) { setOptimalColWidth(); } else if (o == menuItemOptimalColWidths) { setOptimalColWidths(); } } /** * Invoked when a mouse button has been pressed and released on a component * * @param e the mouse event */ @Override public void mouseClicked(MouseEvent e) { int col; boolean popup; col = m_TableArff.columnAtPoint(e.getPoint()); popup = ((e.getButton() == MouseEvent.BUTTON3) && (e.getClickCount() == 1)) || ((e.getButton() == MouseEvent.BUTTON1) && (e.getClickCount() == 1) && e.isAltDown() && !e.isControlDown() && !e.isShiftDown()); popup = popup && (getInstances() != null); if (e.getSource() == m_TableArff.getTableHeader()) { m_CurrentCol = col; // Popup-Menu if (popup) { e.consume(); setMenu(); initPopupMenus(); m_PopupHeader.show(e.getComponent(), e.getX(), e.getY()); } } else if (e.getSource() == m_TableArff) { // Popup-Menu if (popup) { e.consume(); setMenu(); initPopupMenus(); m_PopupRows.show(e.getComponent(), e.getX(), e.getY()); } } // highlihgt column if ((e.getButton() == MouseEvent.BUTTON1) && (e.getClickCount() == 1) && (!e.isAltDown()) && (col > -1)) { m_TableArff.setSelectedColumn(col); } } /** * Invoked when the mouse enters a component. * * @param e the mouse event */ @Override public void mouseEntered(MouseEvent e) { } /** * Invoked when the mouse exits a component * * @param e the mouse event */ @Override public void mouseExited(MouseEvent e) { } /** * Invoked when a mouse button has been pressed on a component * * @param e the mouse event */ @Override public void mousePressed(MouseEvent e) { } /** * Invoked when a mouse button has been released on a component. * * @param e the mouse event */ @Override public void mouseReleased(MouseEvent e) { } /** * Invoked when the target of the listener has changed its state. * * @param e the change event */ @Override public void stateChanged(ChangeEvent e) { m_Changed = true; createTitle(); notifyListener(); } /** * notfies all listener of the change */ public void notifyListener() { Iterator<ChangeListener> iter; iter = m_ChangeListeners.iterator(); while (iter.hasNext()) { iter.next().stateChanged(new ChangeEvent(this)); } } /** * Adds a ChangeListener to the panel * * @param l the listener to add */ public void addChangeListener(ChangeListener l) { m_ChangeListeners.add(l); } /** * Removes a ChangeListener from the panel * * @param l the listener to remove */ public void removeChangeListener(ChangeListener l) { m_ChangeListeners.remove(l); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/arffviewer/ArffSortedTableModel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ArffSortedTableModel.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.arffviewer; import weka.core.Attribute; import weka.core.Instances; import weka.core.Undoable; import weka.core.converters.AbstractFileLoader; import weka.gui.SortedTableModel; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.TableModel; /** * A sorter for the ARFF-Viewer - necessary because of the custom CellRenderer. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class ArffSortedTableModel extends SortedTableModel implements Undoable { /** for serialization */ static final long serialVersionUID = -5733148376354254030L; /** * initializes the sorter w/o a model, but loads the given file and creates * from that a model * * @param filename the file to load * @param loaders optional varargs loader to use */ public ArffSortedTableModel(String filename, AbstractFileLoader... loaders) { this(new ArffTableModel(filename, loaders)); } /** * initializes the sorter w/o a model, but uses the given data to create * a model from that * * @param data the data to use */ public ArffSortedTableModel(Instances data) { this(new ArffTableModel(data)); } /** * initializes the sorter with the given model * * @param model the model to use */ public ArffSortedTableModel(TableModel model) { super(model); } /** * returns whether the notification of changes is enabled * * @return true if notification of changes is enabled */ public boolean isNotificationEnabled() { return ((ArffTableModel) getModel()).isNotificationEnabled(); } /** * sets whether the notification of changes is enabled * * @param enabled enables/disables the notification */ public void setNotificationEnabled(boolean enabled) { ((ArffTableModel) getModel()).setNotificationEnabled(enabled); } /** * returns whether undo support is enabled * * @return true if undo support is enabled */ public boolean isUndoEnabled() { return ((ArffTableModel) getModel()).isUndoEnabled(); } /** * sets whether undo support is enabled * * @param enabled whether to enable/disable undo support */ public void setUndoEnabled(boolean enabled) { ((ArffTableModel) getModel()).setUndoEnabled(enabled); } /** * returns whether the model is read-only * * @return true if model is read-only */ public boolean isReadOnly() { return ((ArffTableModel) getModel()).isReadOnly(); } /** * sets whether the model is read-only * * @param value if true the model is set to read-only */ public void setReadOnly(boolean value) { ((ArffTableModel) getModel()).setReadOnly(value); } /** * Returns the attribute index for the given column index. * * @param columnIndex the column index * * @return the attribute index */ public int getAttributeIndex(int columnIndex) { return ((ArffTableModel) getModel()).getAttributeIndex(columnIndex); } /** * Check if given index is in range of column indices for attributes * * @param columnIndex the column index * * @return true if the column corresponds to attribute */ public boolean isAttribute(int columnIndex) { return ((ArffTableModel) getModel()).isAttribute(columnIndex); } /** * returns the double value of the underlying Instances object at the * given position, -1 if out of bounds * * @param rowIndex the row index * @param columnIndex the column index * @return the underlying value in the Instances object */ public double getInstancesValueAt(int rowIndex, int columnIndex) { return ((ArffTableModel) getModel()).getInstancesValueAt(mIndices[rowIndex], columnIndex); } /** * returns the value at the given position * * @param rowIndex the row index * @param columnIndex the column index * @return the value of the model at the given position */ public Object getModelValueAt(int rowIndex, int columnIndex) { Object result; result = super.getModel().getValueAt(rowIndex, columnIndex); // since this is called in the super-class we have to use the original // index! if (((ArffTableModel) getModel()).isMissingAt(rowIndex, columnIndex)) result = null; return result; } /** * returns the TYPE of the attribute at the given position * * @param columnIndex the index of the column * @return the attribute type */ public int getType(int columnIndex) { return ((ArffTableModel) getModel()).getType(mIndices.length > 0 ? mIndices[0] : -1, columnIndex); } /** * returns the TYPE of the attribute at the given position * * @param rowIndex the index of the row * @param columnIndex the index of the column * @return the attribute type */ public int getType(int rowIndex, int columnIndex) { return ((ArffTableModel) getModel()).getType(mIndices[rowIndex], columnIndex); } /** * deletes the attribute at the given col index * * @param columnIndex the index of the attribute to delete */ public void deleteAttributeAt(int columnIndex) { ((ArffTableModel) getModel()).deleteAttributeAt(columnIndex); } /** * deletes the attributes at the given indices * * @param columnIndices the column indices */ public void deleteAttributes(int[] columnIndices) { ((ArffTableModel) getModel()).deleteAttributes(columnIndices); } /** * renames the attribute at the given col index * * @param columnIndex the index of the column * @param newName the new name of the attribute */ public void renameAttributeAt(int columnIndex, String newName) { ((ArffTableModel) getModel()).renameAttributeAt(columnIndex, newName); } /** * sets the weight of the attribute at the given col index * * @param columnIndex the index of the column * @param weight the new weight of the attribute */ public void setAttributeWeightAt(int columnIndex, double weight) { ((ArffTableModel) getModel()).setAttributeWeightAt(columnIndex, weight); } /** * sets the attribute at the given col index as the new class attribute * * @param columnIndex the index of the column */ public void attributeAsClassAt(int columnIndex) { ((ArffTableModel) getModel()).attributeAsClassAt(columnIndex); } /** * deletes the instance at the given index * * @param rowIndex the index of the row */ public void deleteInstanceAt(int rowIndex) { ((ArffTableModel) getModel()).deleteInstanceAt(mIndices[rowIndex]); } /** * Insert a new instance (all values 0) at the given index. If index is < 0, * then inserts at the end of the dataset * * @param index the index to insert at */ public void insertInstance(int index) { ((ArffTableModel) getModel()).insertInstance(index); } /** * Sets the weight of the selected instance * * @param index the index of the instance * @param weight the weight */ public void setInstanceWeight(int index, double weight) { ((ArffTableModel) getModel()).setInstanceWeight(index, weight); } /** * deletes the instances at the given positions * * @param rowIndices the indices to delete */ public void deleteInstances(int[] rowIndices) { int[] realIndices; int i; realIndices = new int[rowIndices.length]; for (i = 0; i < rowIndices.length; i++) realIndices[i] = mIndices[rowIndices[i]]; ((ArffTableModel) getModel()).deleteInstances(realIndices); } /** * sorts the instances via the given attribute * * @param columnIndex the index of the column */ public void sortInstances(int columnIndex) { ((ArffTableModel) getModel()).sortInstances(columnIndex); } /** * sorts the instances via the given attribute * * @param columnIndex the index of the column * @param ascending ascending if true, otherwise descending */ public void sortInstances(int columnIndex, boolean ascending) { ((ArffTableModel) getModel()).sortInstances(columnIndex, ascending); } /** * sorts the table over the given column, either ascending or descending * * @param columnIndex the column to sort over * @param ascending ascending if true, otherwise descending */ public void sort(int columnIndex, boolean ascending) { sortInstances(columnIndex, ascending); } /** * returns the column of the given attribute name, -1 if not found * * @param name the name of the attribute * @return the column index or -1 if not found */ public int getAttributeColumn(String name) { return ((ArffTableModel) getModel()).getAttributeColumn(name); } /** * checks whether the value at the given position is missing * * @param rowIndex the row index * @param columnIndex the column index * @return true if the value at the position is missing */ public boolean isMissingAt(int rowIndex, int columnIndex) { return ((ArffTableModel) getModel()).isMissingAt(mIndices[rowIndex], columnIndex); } /** * sets the data * * @param data the data to use */ public void setInstances(Instances data) { ((ArffTableModel) getModel()).setInstances(data); } /** * returns the data * * @return the current data */ public Instances getInstances() { return ((ArffTableModel) getModel()).getInstances(); } /** * returns the attribute at the given index, can be NULL if not an attribute * column * * @param columnIndex the index of the column * @return the attribute at the position */ public Attribute getAttributeAt(int columnIndex) { return ((ArffTableModel) getModel()).getAttributeAt(columnIndex); } /** * adds a listener to the list that is notified each time a change to data * model occurs * * @param l the listener to add */ public void addTableModelListener(TableModelListener l) { if (getModel() != null) ((ArffTableModel) getModel()).addTableModelListener(l); } /** * removes a listener from the list that is notified each time a change to * the data model occurs * * @param l the listener to remove */ public void removeTableModelListener(TableModelListener l) { if (getModel() != null) ((ArffTableModel) getModel()).removeTableModelListener(l); } /** * notfies all listener of the change of the model * * @param e the event to send to the listeners */ public void notifyListener(TableModelEvent e) { ((ArffTableModel) getModel()).notifyListener(e); } /** * removes the undo history */ public void clearUndo() { ((ArffTableModel) getModel()).clearUndo(); } /** * returns whether an undo is possible, i.e. whether there are any undo points * saved so far * * @return returns TRUE if there is an undo possible */ public boolean canUndo() { return ((ArffTableModel) getModel()).canUndo(); } /** * undoes the last action */ public void undo() { ((ArffTableModel) getModel()).undo(); } /** * adds an undo point to the undo history */ public void addUndoPoint() { ((ArffTableModel) getModel()).addUndoPoint(); } /** * Sets whether to display the attribute index in the header. * * @param value if true then the attribute indices are displayed in the * table header */ public void setShowAttributeIndex(boolean value) { ((ArffTableModel) getModel()).setShowAttributeIndex(value); } /** * Returns whether to display the attribute index in the header. * * @return true if the attribute indices are displayed in the * table header */ public boolean getShowAttributeIndex() { return ((ArffTableModel) getModel()).getShowAttributeIndex(); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/arffviewer/ArffTable.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ArffTable.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.arffviewer; import java.awt.Component; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import javax.swing.AbstractCellEditor; import javax.swing.DefaultCellEditor; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.TableModelEvent; import javax.swing.table.TableCellEditor; import javax.swing.table.TableModel; import weka.core.Attribute; import weka.core.Instances; import weka.core.SerializedObject; import weka.gui.ComponentHelper; import weka.gui.JTableHelper; import weka.gui.ViewerDialog; /** * A specialized JTable for the Arff-Viewer. * * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class ArffTable extends JTable { /** for serialization */ static final long serialVersionUID = -2016200506908637967L; /** * a special Editor for editing the relation attribute. */ protected class RelationalCellEditor extends AbstractCellEditor implements TableCellEditor { /** for serialization */ private static final long serialVersionUID = 657969163293205963L; /** the button for opening the dialog */ protected JButton m_Button; /** the current instances */ protected Instances m_CurrentInst; /** the row index this editor is for */ protected int m_RowIndex; /** the column index this editor is for */ protected int m_ColumnIndex; /** * initializes the editor * * @param rowIndex the row index * @param columnIndex the column index */ public RelationalCellEditor(int rowIndex, int columnIndex) { super(); m_CurrentInst = getInstancesAt(rowIndex, columnIndex); m_RowIndex = rowIndex; m_ColumnIndex = columnIndex; m_Button = new JButton("..."); m_Button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { ViewerDialog dialog; int result; dialog = new ViewerDialog(null); dialog.setTitle("Relational attribute Viewer - " + ((ArffSortedTableModel) getModel()).getInstances() .attribute(((ArffSortedTableModel)getModel()).getAttributeIndex(columnIndex)).name()); result = dialog.showDialog(m_CurrentInst); if (result == ViewerDialog.APPROVE_OPTION) { m_CurrentInst = dialog.getInstances(); fireEditingStopped(); } else { fireEditingCanceled(); } } }); } /** * returns the underlying instances at the given position * * @param rowIndex the row index * @param columnIndex the column index * @return the corresponding instances */ protected Instances getInstancesAt(int rowIndex, int columnIndex) { Instances result; ArffSortedTableModel model; double value; model = (ArffSortedTableModel) getModel(); value = model.getInstancesValueAt(rowIndex, columnIndex); result = model.getInstances().attribute(model.getAttributeIndex(columnIndex)) .relation((int) value); return result; } /** * Sets an initial value for the editor. This will cause the editor to * stopEditing and lose any partially edited value if the editor is editing * when this method is called. * * @param table the table this editor belongs to * @param value the value to edit * @param isSelected whether the cell is selected * @param row the row index * @param column the column index * @return the */ @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { return m_Button; } /** * Returns the value contained in the editor. * * @return the value contained in the editor */ @Override public Object getCellEditorValue() { return m_CurrentInst; } } /** the search string */ private String m_SearchString; /** the listeners for changes */ private HashSet<ChangeListener> m_ChangeListeners; /** * initializes with no model */ public ArffTable() { this(new ArffSortedTableModel("")); } /** * initializes with the given model * * @param model the model to use */ public ArffTable(TableModel model) { super(model); setAutoResizeMode(JTable.AUTO_RESIZE_OFF); } /** * sets the new model * * @param model the model to use */ @Override public void setModel(TableModel model) { ArffSortedTableModel arffModel; // initialize the search m_SearchString = null; // init the listeners if (m_ChangeListeners == null) { m_ChangeListeners = new HashSet<ChangeListener>(); } super.setModel(model); if (model == null) { return; } if (!(model instanceof ArffSortedTableModel)) { return; } arffModel = (ArffSortedTableModel) model; arffModel.addMouseListenerToHeader(this); arffModel.addTableModelListener(this); arffModel.sort(0); setLayout(); setSelectedColumn(0); // disable column moving if (getTableHeader() != null) { getTableHeader().setReorderingAllowed(false); } } /** * returns the cell editor for the given cell * * @param row the row index * @param column the column index * @return the cell editor */ @Override public TableCellEditor getCellEditor(int row, int column) { TableCellEditor result; // relational attribute? if ((getModel() instanceof ArffSortedTableModel) && (((ArffSortedTableModel) getModel()).getType(column) == Attribute.RELATIONAL)) { result = new RelationalCellEditor(row, column); // default } else { result = super.getCellEditor(row, column); } return result; } /** * returns whether the model is read-only * * @return true if model is read-only */ public boolean isReadOnly() { return ((ArffSortedTableModel) getModel()).isReadOnly(); } /** * sets whether the model is read-only * * @param value if true the model is set to read-only */ public void setReadOnly(boolean value) { ((ArffSortedTableModel) getModel()).setReadOnly(value); } /** * sets the cell renderer and calcs the optimal column width */ private void setLayout() { ArffSortedTableModel arffModel; int i; JComboBox combo; Enumeration<Object> enm; arffModel = (ArffSortedTableModel) getModel(); for (i = 0; i < getColumnCount(); i++) { // optimal colwidths (only according to header!) JTableHelper.setOptimalHeaderWidth(this, i); // CellRenderer getColumnModel().getColumn(i) .setCellRenderer(new ArffTableCellRenderer()); // CellEditor if (i > 0) { if (arffModel.getType(i) == Attribute.NOMINAL) { combo = new JComboBox(); combo.addItem(null); enm = arffModel.getInstances().attribute(arffModel.getAttributeIndex(i)).enumerateValues(); while (enm.hasMoreElements()) { Object o = enm.nextElement(); if (o instanceof SerializedObject) { ((SerializedObject) o).getObject(); } combo.addItem(o); } getColumnModel().getColumn(i).setCellEditor( new DefaultCellEditor(combo)); } else { getColumnModel().getColumn(i).setCellEditor(null); } } } } /** * returns the basically the attribute name of the column and not the HTML * column name via getColumnName(int) * * @param columnIndex the column index * @return the plain name */ public String getPlainColumnName(int columnIndex) { ArffSortedTableModel arffModel; String result; result = ""; if (getModel() == null) { return result; } if (!(getModel() instanceof ArffSortedTableModel)) { return result; } arffModel = (ArffSortedTableModel) getModel(); if ((columnIndex >= 0) && (columnIndex < getColumnCount())) { if (columnIndex == 0) { result = "No."; } else { if (arffModel.getAttributeIndex(columnIndex) < 0) { result = "Weight"; } else { result = arffModel.getAttributeAt(columnIndex).name(); } } } return result; } /** * returns the selected content in a StringSelection that can be copied to the * clipboard and used in Excel, if nothing is selected the whole table is * copied to the clipboard * * @return the current selection */ public StringSelection getStringSelection() { StringSelection result; int[] indices; int i; int n; StringBuffer tmp; result = null; // nothing selected? -> all if (getSelectedRow() == -1) { // really? if (ComponentHelper.showMessageBox(getParent(), "Question...", "Do you really want to copy the whole table?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) { return result; } indices = new int[getRowCount()]; for (i = 0; i < indices.length; i++) { indices[i] = i; } } else { indices = getSelectedRows(); } // get header tmp = new StringBuffer(); for (i = 0; i < getColumnCount(); i++) { if (i > 0) { tmp.append("\t"); } tmp.append(getPlainColumnName(i)); } tmp.append("\n"); // get content for (i = 0; i < indices.length; i++) { for (n = 0; n < getColumnCount(); n++) { if (n > 0) { tmp.append("\t"); } tmp.append(getValueAt(indices[i], n).toString()); } tmp.append("\n"); } result = new StringSelection(tmp.toString()); return result; } /** * sets the search string to look for in the table, NULL or "" disables the * search * * @param searchString the search string to use */ public void setSearchString(String searchString) { this.m_SearchString = searchString; repaint(); } /** * returns the search string, can be NULL if no search string is set * * @return the current search string */ public String getSearchString() { return m_SearchString; } /** * sets the selected column * * @param index the column to select */ public void setSelectedColumn(int index) { getColumnModel().getSelectionModel().clearSelection(); getColumnModel().getSelectionModel().setSelectionInterval(index, index); resizeAndRepaint(); if (getTableHeader() != null) { getTableHeader().resizeAndRepaint(); } } /** * This fine grain notification tells listeners the exact range of cells, * rows, or columns that changed. * * @param e the table event */ @Override public void tableChanged(TableModelEvent e) { super.tableChanged(e); setLayout(); notifyListener(); } /** * notfies all listener of the change */ private void notifyListener() { Iterator<ChangeListener> iter; iter = m_ChangeListeners.iterator(); while (iter.hasNext()) { iter.next().stateChanged(new ChangeEvent(this)); } } /** * Adds a ChangeListener to the panel * * @param l the listener to add */ public void addChangeListener(ChangeListener l) { m_ChangeListeners.add(l); } /** * Removes a ChangeListener from the panel * * @param l the listener to remove */ public void removeChangeListener(ChangeListener l) { m_ChangeListeners.remove(l); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/arffviewer/ArffTableCellRenderer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ArffTableCellRenderer.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.arffviewer; import java.awt.Color; import java.awt.Component; import javax.swing.JTable; import javax.swing.SwingConstants; import javax.swing.UIManager; import javax.swing.table.DefaultTableCellRenderer; import weka.core.Attribute; /** * Handles the background colors for missing values differently than the * DefaultTableCellRenderer. * * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class ArffTableCellRenderer extends DefaultTableCellRenderer { /** for serialization */ static final long serialVersionUID = 9195794493301191171L; /** the color for missing values */ private Color missingColor; /** the color for selected missing values */ private Color missingColorSelected; /** the color for highlighted values */ private Color highlightColor; /** the color for selected highlighted values */ private Color highlightColorSelected; /** * initializes the Renderer with a standard color */ public ArffTableCellRenderer() { this( new Color(223, 223, 223), new Color(192, 192, 192) ); } /** * initializes the Renderer with the given colors * * @param missingColor the color for missing values * @param missingColorSelected the color selected missing values */ public ArffTableCellRenderer( Color missingColor, Color missingColorSelected ) { this( missingColor, missingColorSelected, Color.RED, Color.RED.darker() ); } /** * initializes the Renderer with the given colors * * @param missingColor the color for missing values * @param missingColorSelected the color selected missing values * @param highlightColor the color for highlighted values * @param highlightColorSelected the color selected highlighted values */ public ArffTableCellRenderer( Color missingColor, Color missingColorSelected, Color highlightColor, Color highlightColorSelected ) { super(); this.missingColor = missingColor; this.missingColorSelected = missingColorSelected; this.highlightColor = highlightColor; this.highlightColorSelected = highlightColorSelected; } /** * Returns the default table cell renderer. * stuff for the header is taken from <a href="http://www.chka.de/swing/table/faq.html">here</a> * * @param table the table this object belongs to * @param value the actual cell value * @param isSelected whether the cell is selected * @param hasFocus whether the cell has the focus * @param row the row in the table * @param column the column in the table * @return the rendering component */ public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column ) { ArffSortedTableModel model; Component result; String searchString; boolean found; result = super.getTableCellRendererComponent( table, value, isSelected, hasFocus, row, column); // search if (table instanceof ArffTable) searchString = ((ArffTable) table).getSearchString(); else searchString = null; if ( (searchString != null) && (!searchString.equals("")) ) found = (searchString.equals(value.toString())); else found = false; if (table.getModel() instanceof ArffSortedTableModel) { model = (ArffSortedTableModel) table.getModel(); // normal cell if (row >= 0) { if (model.isMissingAt(row, column)) { setToolTipText("missing"); if (found) { if (isSelected) result.setBackground(highlightColorSelected); else result.setBackground(highlightColor); } else { if (isSelected) result.setBackground(missingColorSelected); else result.setBackground(missingColor); } } else { setToolTipText(null); if (found) { if (isSelected) result.setBackground(highlightColorSelected); else result.setBackground(highlightColor); } else { if (isSelected) result.setBackground(table.getSelectionBackground()); else result.setBackground(Color.WHITE); } } // alignment if (model.getType(row, column) == Attribute.NUMERIC) setHorizontalAlignment(SwingConstants.RIGHT); else setHorizontalAlignment(SwingConstants.LEFT); } // header else { setBorder(UIManager.getBorder("TableHeader.cellBorder")); setHorizontalAlignment(SwingConstants.CENTER); if (table.getColumnModel().getSelectionModel().isSelectedIndex(column)) result.setBackground(UIManager.getColor("TableHeader.background").darker()); else result.setBackground(UIManager.getColor("TableHeader.background")); } } return result; } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/arffviewer/ArffTableModel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ArffTableModel.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.arffviewer; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.Vector; import javax.swing.JOptionPane; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.DefaultTableModel; import weka.core.Attribute; import weka.core.DenseInstance; import weka.core.Instance; import weka.core.Instances; import weka.core.Undoable; import weka.core.Utils; import weka.core.converters.AbstractFileLoader; import weka.core.converters.ConverterUtils; import weka.filters.Filter; import weka.filters.unsupervised.attribute.Reorder; import weka.gui.ComponentHelper; /** * The model for the Arff-Viewer. * * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class ArffTableModel extends DefaultTableModel implements Undoable { /** for serialization. */ private static final long serialVersionUID = 3411795562305994946L; /** the listeners */ protected HashSet<TableModelListener> m_Listeners; /** the data */ protected Instances m_Data; /** whether notfication is enabled */ protected boolean m_NotificationEnabled; /** whether undo is active */ protected boolean m_UndoEnabled; /** whether to ignore changes, i.e. not adding to undo history */ protected boolean m_IgnoreChanges; /** the undo list (contains temp. filenames) */ protected Vector<File> m_UndoList; /** whether the table is read-only */ protected boolean m_ReadOnly; /** whether to display the attribute index in the table header. */ protected boolean m_ShowAttributeIndex; /** whether to show attribute weights. */ protected boolean m_ShowAttributeWeights; /** whether to show instance weights. */ protected boolean m_ShowInstanceWeights; /** * for caching long relational and string values that get processed for * display. */ protected Hashtable<String, String> m_Cache; /** * performs some initialization */ private ArffTableModel() { super(); this.m_Listeners = new HashSet<TableModelListener>(); this.m_Data = null; this.m_NotificationEnabled = true; this.m_UndoList = new Vector<File>(); this.m_IgnoreChanges = false; this.m_UndoEnabled = true; this.m_ReadOnly = false; this.m_ShowAttributeIndex = false; this.m_ShowAttributeWeights = false; this.m_ShowInstanceWeights = false; this.m_Cache = new Hashtable<String, String>(); } /** * initializes the object and loads the given file * * @param filename the file to load * @param loaders optional varargs for a loader to use */ public ArffTableModel(final String filename, final AbstractFileLoader... loaders) { this(); if ((filename != null) && (!filename.equals(""))) { this.loadFile(filename, loaders); } } /** * initializes the model with the given data * * @param data the data to use */ public ArffTableModel(final Instances data) { this(); this.m_Data = data; for (int i = 0; i < data.numAttributes(); i++) { if (data.attribute(i).weight() != 1.0) { this.m_ShowAttributeWeights = true; break; } } for (int i = 0; i < data.numInstances(); i++) { if (data.instance(i).weight() != 1.0) { this.m_ShowInstanceWeights = true; break; } } } /** * returns whether the notification of changes is enabled * * @return true if notification of changes is enabled */ public boolean isNotificationEnabled() { return this.m_NotificationEnabled; } /** * sets whether the notification of changes is enabled * * @param enabled enables/disables the notification */ public void setNotificationEnabled(final boolean enabled) { this.m_NotificationEnabled = enabled; } /** * returns whether undo support is enabled * * @return true if undo support is enabled */ @Override public boolean isUndoEnabled() { return this.m_UndoEnabled; } /** * sets whether undo support is enabled * * @param enabled whether to enable/disable undo support */ @Override public void setUndoEnabled(final boolean enabled) { this.m_UndoEnabled = enabled; } /** * returns whether the model is read-only * * @return true if model is read-only */ public boolean isReadOnly() { return this.m_ReadOnly; } /** * sets whether the model is read-only * * @param value if true the model is set to read-only */ public void setReadOnly(final boolean value) { this.m_ReadOnly = value; } /** * loads the specified ARFF file * * @param filename the file to load * @param loaders optional varargs for a loader to use */ protected void loadFile(final String filename, final AbstractFileLoader... loaders) { AbstractFileLoader loader; if (loaders == null || loaders.length == 0) { loader = ConverterUtils.getLoaderForFile(filename); } else { loader = loaders[0]; } if (loader != null) { try { loader.setFile(new File(filename)); this.setInstances(loader.getDataSet()); } catch (Exception e) { ComponentHelper.showMessageBox(null, "Error loading file...", e.toString(), JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE); System.out.println(e); this.setInstances(null); } } } /** * sets the data * * @param data the data to use */ public void setInstances(final Instances data) { this.m_Data = data; this.m_ShowAttributeWeights = false; for (int i = 0; i < data.numAttributes(); i++) { if (data.attribute(i).weight() != 1.0) { this.m_ShowAttributeWeights = true; break; } } this.m_ShowInstanceWeights = false; for (int i = 0; i < data.numInstances(); i++) { if (data.instance(i).weight() != 1.0) { this.m_ShowInstanceWeights = true; break; } } this.m_Cache.clear(); this.fireTableDataChanged(); } /** * returns the data * * @return the current data */ public Instances getInstances() { return this.m_Data; } /** * Returns the attribute index for the given column index. * * @param columnIndex the column index * * @return the attribute index */ public int getAttributeIndex(final int columnIndex) { if (this.m_ShowInstanceWeights) { return columnIndex - 2; } else { return columnIndex - 1; } } /** * Check if given index is in range of column indices for attributes * * @param columnIndex the column index * * @return true if the column corresponds to attribute */ public boolean isAttribute(final int columnIndex) { if (this.m_ShowInstanceWeights) { return (columnIndex > 1) && (columnIndex < this.getColumnCount()); } else { return (columnIndex > 0) && (columnIndex < this.getColumnCount()); } } /** * returns the attribute at the given index, can be NULL if not an attribute * column * * @param columnIndex the index of the column * @return the attribute at the position */ public Attribute getAttributeAt(final int columnIndex) { if (this.isAttribute(columnIndex)) { return this.m_Data.attribute(this.getAttributeIndex(columnIndex)); } else { return null; } } /** * returns the TYPE of the attribute at the given position * * @param columnIndex the index of the column * @return the attribute type */ public int getType(final int columnIndex) { return this.getType(-1, columnIndex); } /** * returns the TYPE of the attribute at the given position * * @param rowIndex the index of the row * @param columnIndex the index of the column * @return the attribute type */ public int getType(final int rowIndex, final int columnIndex) { int result; result = Attribute.STRING; if ((rowIndex < 0) && this.isAttribute(columnIndex)) { result = this.m_Data.attribute(this.getAttributeIndex(columnIndex)).type(); } else if ((rowIndex >= 0) && (rowIndex < this.getRowCount()) && this.isAttribute(columnIndex)) { result = this.m_Data.instance(rowIndex).attribute(this.getAttributeIndex(columnIndex)).type(); } return result; } /** * deletes the attribute at the given col index. notifies the listeners. * * @param columnIndex the index of the attribute to delete */ public void deleteAttributeAt(final int columnIndex) { this.deleteAttributeAt(columnIndex, true); } /** * deletes the attribute at the given col index * * @param columnIndex the index of the attribute to delete * @param notify whether to notify the listeners */ public void deleteAttributeAt(final int columnIndex, final boolean notify) { if (this.isAttribute(columnIndex)) { if (!this.m_IgnoreChanges) { this.addUndoPoint(); } this.m_Data.deleteAttributeAt(this.getAttributeIndex(columnIndex)); if (notify) { this.notifyListener(new TableModelEvent(this, TableModelEvent.HEADER_ROW)); } } } /** * deletes the attributes at the given indices * * @param columnIndices the column indices */ public void deleteAttributes(final int[] columnIndices) { int i; Arrays.sort(columnIndices); this.addUndoPoint(); this.m_IgnoreChanges = true; for (i = columnIndices.length - 1; i >= 0; i--) { this.deleteAttributeAt(columnIndices[i], false); } this.m_IgnoreChanges = false; this.notifyListener(new TableModelEvent(this, TableModelEvent.HEADER_ROW)); } /** * renames the attribute at the given col index * * @param columnIndex the index of the column * @param newName the new name of the attribute */ public void renameAttributeAt(final int columnIndex, final String newName) { if (this.isAttribute(columnIndex)) { this.addUndoPoint(); this.m_Data.renameAttribute(this.getAttributeIndex(columnIndex), newName); this.notifyListener(new TableModelEvent(this, TableModelEvent.HEADER_ROW)); } } /** * set the attribute weight at the given col index * * @param columnIndex the index of the column * @param weight the new weight of the attribute */ public void setAttributeWeightAt(final int columnIndex, final double weight) { if (this.isAttribute(columnIndex)) { this.addUndoPoint(); this.m_Data.setAttributeWeight(this.getAttributeIndex(columnIndex), weight); if (weight != 1.0) { this.m_ShowAttributeWeights = true; } else { this.m_ShowAttributeWeights = false; for (int i = 0; i < this.m_Data.numAttributes(); i++) { if (this.m_Data.attribute(i).weight() != 1.0) { this.m_ShowAttributeWeights = true; break; } } } this.notifyListener(new TableModelEvent(this, TableModelEvent.HEADER_ROW)); } } /** * sets the attribute at the given col index as the new class attribute, i.e. * it moves it to the end of the attributes * * @param columnIndex the index of the column */ public void attributeAsClassAt(final int columnIndex) { Reorder reorder; String order; int i; if (this.isAttribute(columnIndex)) { this.addUndoPoint(); try { // build order string (1-based!) order = ""; for (i = 1; i < this.m_Data.numAttributes() + 1; i++) { // skip new class if (i - 1 == this.getAttributeIndex(columnIndex)) { continue; } if (!order.equals("")) { order += ","; } order += Integer.toString(i); } if (!order.equals("")) { order += ","; } order += Integer.toString(this.getAttributeIndex(columnIndex) + 1); // process data reorder = new Reorder(); reorder.setAttributeIndices(order); reorder.setInputFormat(this.m_Data); this.m_Data = Filter.useFilter(this.m_Data, reorder); // set class index this.m_Data.setClassIndex(this.m_Data.numAttributes() - 1); } catch (Exception e) { e.printStackTrace(); this.undo(); } this.notifyListener(new TableModelEvent(this, TableModelEvent.HEADER_ROW)); } } /** * deletes the instance at the given index * * @param rowIndex the index of the row */ public void deleteInstanceAt(final int rowIndex) { this.deleteInstanceAt(rowIndex, true); } /** * deletes the instance at the given index * * @param rowIndex the index of the row * @param notify whether to notify the listeners */ public void deleteInstanceAt(final int rowIndex, final boolean notify) { if ((rowIndex >= 0) && (rowIndex < this.getRowCount())) { if (!this.m_IgnoreChanges) { this.addUndoPoint(); } this.m_Data.delete(rowIndex); if (notify) { this.notifyListener(new TableModelEvent(this, rowIndex, rowIndex, TableModelEvent.ALL_COLUMNS, TableModelEvent.DELETE)); } } } public void setInstanceWeight(final int index, final double weight) { this.setInstanceWeight(index, weight, true); } public void setInstanceWeight(final int index, final double weight, final boolean notify) { if (!this.m_IgnoreChanges) { this.addUndoPoint(); } this.m_Data.instance(index).setWeight(weight); if (notify) { if (this.m_ShowInstanceWeights) { this.notifyListener(new TableModelEvent(this, index, 1)); } else { if (weight != 1.0) { this.m_ShowInstanceWeights = true; this.notifyListener(new TableModelEvent(this, TableModelEvent.HEADER_ROW)); } } } } public void insertInstance(final int index) { this.insertInstance(index, true); } public void insertInstance(final int index, final boolean notify) { if (!this.m_IgnoreChanges) { this.addUndoPoint(); } double[] vals = new double[this.m_Data.numAttributes()]; // set any string or relational attribute values to missing // in the new instance, just in case this is the very first // instance in the dataset. for (int i = 0; i < this.m_Data.numAttributes(); i++) { if (this.m_Data.attribute(i).isString() || this.m_Data.attribute(i).isRelationValued()) { vals[i] = Utils.missingValue(); } } Instance toAdd = new DenseInstance(1.0, vals); if (index < 0) { this.m_Data.add(toAdd); } else { this.m_Data.add(index, toAdd); } if (notify) { this.notifyListener(new TableModelEvent(this, this.m_Data.numInstances() - 1, this.m_Data.numInstances() - 1, TableModelEvent.ALL_COLUMNS, TableModelEvent.INSERT)); } } /** * deletes the instances at the given positions * * @param rowIndices the indices to delete */ public void deleteInstances(final int[] rowIndices) { int i; Arrays.sort(rowIndices); this.addUndoPoint(); this.m_IgnoreChanges = true; for (i = rowIndices.length - 1; i >= 0; i--) { this.deleteInstanceAt(rowIndices[i], false); } this.m_IgnoreChanges = false; this.notifyListener(new TableModelEvent(this, rowIndices[0], rowIndices[rowIndices.length - 1], TableModelEvent.ALL_COLUMNS, TableModelEvent.DELETE)); } /** * sorts the instances via the given attribute * * @param columnIndex the index of the column */ public void sortInstances(final int columnIndex) { this.sortInstances(columnIndex, false); } /** * sorts the instances via the given attribute * * @param columnIndex the index of the column * @param ascending ascending if true, otherwise descending */ public void sortInstances(final int columnIndex, final boolean ascending) { if (this.isAttribute(columnIndex) || (this.m_ShowInstanceWeights && columnIndex == 1)) { this.addUndoPoint(); double[] vals = new double[this.m_Data.numInstances()]; Instance[] backup = new Instance[vals.length]; for (int i = 0; i < vals.length; i++) { Instance inst = this.m_Data.instance(i); backup[i] = inst; vals[i] = this.isAttribute(columnIndex) ? inst.value(this.getAttributeIndex(columnIndex)) : inst.weight(); } int[] sortOrder; try { sortOrder = Utils.stableSort(vals); } catch (InterruptedException e) { throw new IllegalStateException("Could not sort values", e); } for (int i = 0; i < vals.length; i++) { this.m_Data.set(i, backup[sortOrder[i]]); } if (!ascending) { Instances reversedData = new Instances(this.m_Data, this.m_Data.numInstances()); int i = this.m_Data.numInstances(); while (i > 0) { i--; int equalCount = 1; if (this.isAttribute(columnIndex)) { while ((i > 0) && (this.m_Data.instance(i).value(this.getAttributeIndex(columnIndex)) == this.m_Data.instance(i - 1).value(this.getAttributeIndex(columnIndex)))) { equalCount++; i--; } } else { while ((i > 0) && (this.m_Data.instance(i).weight() == this.m_Data.instance(i - 1).weight())) { equalCount++; i--; } } int j = 0; while (j < equalCount) { reversedData.add(this.m_Data.instance(i + j)); j++; } } this.m_Data = reversedData; } this.notifyListener(new TableModelEvent(this)); } } /** * returns the column of the given attribute name, -1 if not found * * @param name the name of the attribute * @return the column index or -1 if not found */ public int getAttributeColumn(final String name) { int i; int result; result = -1; for (i = 0; i < this.m_Data.numAttributes(); i++) { if (this.m_Data.attribute(i).name().equals(name)) { result = i + (this.m_ShowInstanceWeights ? 2 : 1); break; } } return result; } /** * returns the most specific superclass for all the cell values in the column * (always String) * * @param columnIndex the column index * @return the class of the column */ @Override public Class<?> getColumnClass(final int columnIndex) { Class<?> result; result = null; if ((columnIndex >= 0) && (columnIndex < this.getColumnCount())) { if (columnIndex == 0) { result = Integer.class; } else if ((this.getType(columnIndex) == Attribute.NUMERIC) || (this.m_ShowInstanceWeights && (columnIndex == 1))) { result = Double.class; } else { result = String.class; // otherwise no input of "?"!!! } } return result; } /** * returns the number of columns in the model * * @return the number of columns */ @Override public int getColumnCount() { int result; result = 1; if (this.m_ShowInstanceWeights) { result++; } if (this.m_Data != null) { result += this.m_Data.numAttributes(); } return result; } /** * checks whether the column represents the class or not * * @param columnIndex the index of the column * @return true if the column is the class attribute */ protected boolean isClassIndex(final int columnIndex) { boolean result; int index; index = this.m_Data.classIndex(); result = ((index == -1) && (this.m_Data.numAttributes() - 1 == this.getAttributeIndex(columnIndex))) || (index == this.getAttributeIndex(columnIndex)); return result; } /** * returns the name of the column at columnIndex * * @param columnIndex the index of the column * @return the name of the column */ @Override public String getColumnName(final int columnIndex) { String result; result = ""; if ((columnIndex >= 0) && (columnIndex < this.getColumnCount())) { if (columnIndex == 0) { result = "<html><center>No.<br><font size=\"-2\">&nbsp;"; if (this.m_ShowAttributeWeights) { result += "</font><br><font size=\"-2\">&nbsp;</font>"; } result += "</center></html>"; } else if ((columnIndex == 1) && (this.m_ShowInstanceWeights)) { result = "<html><center>Weight<br><font size=\"-2\">&nbsp;"; if (this.m_ShowAttributeWeights) { result += "</font><br><font size=\"-2\">&nbsp;</font>"; } result += "</center></html>"; } else { if (this.m_Data != null) { if ((this.getAttributeIndex(columnIndex) < this.m_Data.numAttributes())) { result = "<html><center>"; // index if (this.m_ShowAttributeIndex) { result += (this.m_ShowInstanceWeights ? (columnIndex - 1) : columnIndex) + ": "; } // name if (this.isClassIndex(columnIndex)) { result += "<b>" + this.m_Data.attribute(this.getAttributeIndex(columnIndex)).name() + "</b>"; } else { result += this.m_Data.attribute(this.getAttributeIndex(columnIndex)).name(); } // attribute type switch (this.getType(columnIndex)) { case Attribute.DATE: result += "<br><font size=\"-2\">Date</font>"; break; case Attribute.NOMINAL: result += "<br><font size=\"-2\">Nominal</font>"; break; case Attribute.STRING: result += "<br><font size=\"-2\">String</font>"; break; case Attribute.NUMERIC: result += "<br><font size=\"-2\">Numeric</font>"; break; case Attribute.RELATIONAL: result += "<br><font size=\"-2\">Relational</font>"; break; default: result += "<br><font size=\"-2\">???</font>"; } if (this.m_ShowAttributeWeights) { result += "<br><font size=\"-2\">Weight : " + Utils.doubleToString(this.m_Data.attribute(this.getAttributeIndex(columnIndex)).weight(), 3) + "</font>"; } result += "</center></html>"; } } } } return result; } /** * returns the number of rows in the model * * @return the number of rows */ @Override public int getRowCount() { if (this.m_Data == null) { return 0; } else { return this.m_Data.numInstances(); } } /** * checks whether the value at the given position is missing * * @param rowIndex the row index * @param columnIndex the column index * @return true if the value at the position is missing */ public boolean isMissingAt(final int rowIndex, final int columnIndex) { boolean result; result = false; if ((rowIndex >= 0) && (rowIndex < this.getRowCount()) && this.isAttribute(columnIndex)) { result = (this.m_Data.instance(rowIndex).isMissing(this.getAttributeIndex(columnIndex))); } return result; } /** * returns the double value of the underlying Instances object at the given * position, -1 if out of bounds * * @param rowIndex the row index * @param columnIndex the column index * @return the underlying value in the Instances object */ public double getInstancesValueAt(final int rowIndex, final int columnIndex) { double result; result = -1; if ((rowIndex >= 0) && (rowIndex < this.getRowCount()) && this.isAttribute(columnIndex)) { result = this.m_Data.instance(rowIndex).value(this.getAttributeIndex(columnIndex)); } return result; } /** * returns the value for the cell at columnindex and rowIndex * * @param rowIndex the row index * @param columnIndex the column index * @return the value at the position */ @Override public Object getValueAt(final int rowIndex, final int columnIndex) { Object result; String tmp; String key; boolean modified; result = null; key = rowIndex + "-" + columnIndex; if ((rowIndex >= 0) && (rowIndex < this.getRowCount()) && (columnIndex >= 0) && (columnIndex < this.getColumnCount())) { if (columnIndex == 0) { result = new Integer(rowIndex + 1); } else if ((columnIndex == 1) && (this.m_ShowInstanceWeights)) { result = new Double(this.m_Data.instance(rowIndex).weight()); } else { if (this.isMissingAt(rowIndex, columnIndex)) { result = null; } else { if (this.m_Cache.containsKey(key)) { result = this.m_Cache.get(key); } else { switch (this.getType(columnIndex)) { case Attribute.DATE: case Attribute.NOMINAL: case Attribute.STRING: case Attribute.RELATIONAL: result = this.m_Data.instance(rowIndex).stringValue(this.getAttributeIndex(columnIndex)); break; case Attribute.NUMERIC: result = new Double(this.m_Data.instance(rowIndex).value(this.getAttributeIndex(columnIndex))); break; default: result = "-can't display-"; } if (this.getType(columnIndex) != Attribute.NUMERIC) { if (result != null) { tmp = result.toString(); modified = false; // fix html tags, otherwise Java parser hangs if ((tmp.indexOf('<') > -1) || (tmp.indexOf('>') > -1)) { tmp = tmp.replace("<", "("); tmp = tmp.replace(">", ")"); modified = true; } // does it contain "\n" or "\r"? -> replace with red html tag if ((tmp.indexOf("\n") > -1) || (tmp.indexOf("\r") > -1)) { tmp = tmp.replaceAll("\\r\\n", "<font color=\"red\"><b>\\\\r\\\\n</b></font>"); tmp = tmp.replaceAll("\\r", "<font color=\"red\"><b>\\\\r</b></font>"); tmp = tmp.replaceAll("\\n", "<font color=\"red\"><b>\\\\n</b></font>"); tmp = "<html>" + tmp + "</html>"; modified = true; } result = tmp; if (modified) { this.m_Cache.put(key, tmp); } } } } } } } return result; } /** * returns true if the cell at rowindex and columnindexis editable * * @param rowIndex the index of the row * @param columnIndex the index of the column * @return true if the cell is editable */ @Override public boolean isCellEditable(final int rowIndex, final int columnIndex) { return ((this.m_ShowInstanceWeights && (columnIndex == 1)) || this.isAttribute(columnIndex)) && !this.isReadOnly(); } /** * sets the value in the cell at columnIndex and rowIndex to aValue. but only * the value and the value can be changed * * @param aValue the new value * @param rowIndex the row index * @param columnIndex the column index */ @Override public void setValueAt(final Object aValue, final int rowIndex, final int columnIndex) { this.setValueAt(aValue, rowIndex, columnIndex, true); } /** * sets the value in the cell at columnIndex and rowIndex to aValue. but only * the value and the value can be changed * * @param aValue the new value * @param rowIndex the row index * @param columnIndex the column index * @param notify whether to notify the listeners */ public void setValueAt(final Object aValue, final int rowIndex, final int columnIndex, final boolean notify) { int type; int index; String tmp; Instance inst; Attribute att; Object oldValue; if (!this.m_IgnoreChanges) { this.addUndoPoint(); } // Is this actually an instance weight? if (this.m_ShowInstanceWeights && columnIndex == 1) { double oldWeight = this.m_Data.instance(rowIndex).weight(); try { double newWeight = Double.parseDouble(aValue.toString()); if (oldWeight != newWeight) { this.m_Data.instance(rowIndex).setWeight(newWeight); } else { return; } } catch (Exception e) { // ignore } if (notify) { this.notifyListener(new TableModelEvent(this, rowIndex, columnIndex)); } return; } oldValue = this.getValueAt(rowIndex, columnIndex); type = this.getType(rowIndex, columnIndex); index = this.getAttributeIndex(columnIndex); inst = this.m_Data.instance(rowIndex); att = inst.attribute(index); // missing? if (aValue == null) { inst.setValue(index, Utils.missingValue()); } else { tmp = aValue.toString(); switch (type) { case Attribute.DATE: try { att.parseDate(tmp); inst.setValue(index, att.parseDate(tmp)); } catch (Exception e) { // ignore } break; case Attribute.NOMINAL: if (att.indexOfValue(tmp) > -1) { inst.setValue(index, att.indexOfValue(tmp)); } break; case Attribute.STRING: inst.setValue(index, tmp); break; case Attribute.NUMERIC: try { Double.parseDouble(tmp); inst.setValue(index, Double.parseDouble(tmp)); } catch (Exception e) { // ignore } break; case Attribute.RELATIONAL: try { inst.setValue(index, inst.attribute(index).addRelation((Instances) aValue)); } catch (Exception e) { // ignore } break; default: throw new IllegalArgumentException("Unsupported Attribute type: " + type + "!"); } } // notify only if the value has changed! if (notify && (!("" + oldValue).equals("" + aValue))) { this.notifyListener(new TableModelEvent(this, rowIndex, columnIndex)); } } /** * adds a listener to the list that is notified each time a change to data * model occurs * * @param l the listener to add */ @Override public void addTableModelListener(final TableModelListener l) { this.m_Listeners.add(l); } /** * removes a listener from the list that is notified each time a change to the * data model occurs * * @param l the listener to remove */ @Override public void removeTableModelListener(final TableModelListener l) { this.m_Listeners.remove(l); } /** * notfies all listener of the change of the model * * @param e the event to send to the listeners */ public void notifyListener(final TableModelEvent e) { Iterator<TableModelListener> iter; TableModelListener l; // is notification enabled? if (!this.isNotificationEnabled()) { return; } iter = this.m_Listeners.iterator(); while (iter.hasNext()) { l = iter.next(); l.tableChanged(e); } } /** * removes the undo history */ @Override public void clearUndo() { this.m_UndoList = new Vector<File>(); } /** * returns whether an undo is possible, i.e. whether there are any undo points * saved so far * * @return returns TRUE if there is an undo possible */ @Override public boolean canUndo() { return !this.m_UndoList.isEmpty(); } /** * undoes the last action */ @Override public void undo() { File tempFile; Instances inst; ObjectInputStream ooi; if (this.canUndo()) { // load file tempFile = this.m_UndoList.get(this.m_UndoList.size() - 1); try { // read serialized data ooi = new ObjectInputStream(new BufferedInputStream(new FileInputStream(tempFile))); inst = (Instances) ooi.readObject(); ooi.close(); // set instances this.setInstances(inst); this.notifyListener(new TableModelEvent(this, TableModelEvent.HEADER_ROW)); this.notifyListener(new TableModelEvent(this)); } catch (Exception e) { e.printStackTrace(); } tempFile.delete(); // remove from undo this.m_UndoList.remove(this.m_UndoList.size() - 1); } } /** * adds an undo point to the undo history, if the undo support is enabled * * @see #isUndoEnabled() * @see #setUndoEnabled(boolean) */ @Override public void addUndoPoint() { File tempFile; ObjectOutputStream oos; // undo support currently on? if (!this.isUndoEnabled()) { return; } if (this.getInstances() != null) { try { // temp. filename tempFile = File.createTempFile("arffviewer", null); tempFile.deleteOnExit(); // serialize instances oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(tempFile))); oos.writeObject(this.getInstances()); oos.flush(); oos.close(); // add to undo list this.m_UndoList.add(tempFile); } catch (Exception e) { e.printStackTrace(); } } } /** * Sets whether to display the attribute index in the header. * * @param value if true then the attribute indices are displayed in the table * header */ public void setShowAttributeIndex(final boolean value) { this.m_ShowAttributeIndex = value; this.fireTableStructureChanged(); } /** * Returns whether to display the attribute index in the header. * * @return true if the attribute indices are displayed in the table header */ public boolean getShowAttributeIndex() { return this.m_ShowAttributeIndex; } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/arffviewer/ArffViewer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ArffViewer.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.arffviewer; import java.awt.BorderLayout; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.JFrame; import javax.swing.JOptionPane; import weka.core.Memory; import weka.gui.ComponentHelper; import weka.gui.LookAndFeel; /** * A little tool for viewing ARFF files. * * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class ArffViewer extends JFrame implements WindowListener { /** for serialization */ static final long serialVersionUID = -7455845566922685175L; /** the main panel */ private ArffViewerMainPanel m_MainPanel; /** for monitoring the Memory consumption */ private static Memory m_Memory = new Memory(true); /** the viewer if started from command line */ private static ArffViewer m_Viewer; /** whether the files were already loaded */ private static boolean m_FilesLoaded; /** the command line arguments */ private static String[] m_Args; /** * initializes the object */ public ArffViewer() { super("ARFF-Viewer"); createFrame(); } /** * creates all the components in the frame */ protected void createFrame() { // basic setup setIconImage(ComponentHelper.getImage("weka_icon.gif")); setSize(ArffViewerMainPanel.WIDTH, ArffViewerMainPanel.HEIGHT); setCenteredLocation(); setDefaultCloseOperation(DISPOSE_ON_CLOSE); // remove the listener - otherwise we get the strange behavior that one // frame receives a window-event for every single open frame! removeWindowListener(this); // add listener anew addWindowListener(this); getContentPane().setLayout(new BorderLayout()); m_MainPanel = new ArffViewerMainPanel(this); m_MainPanel.setConfirmExit(false); getContentPane().add(m_MainPanel, BorderLayout.CENTER); setJMenuBar(m_MainPanel.getMenu()); } /** * returns the left coordinate if the frame would be centered * * @return the left coordinate */ protected int getCenteredLeft() { int width; int x; width = getBounds().width; x = (getGraphicsConfiguration().getBounds().width - width) / 2; if (x < 0) { x = 0; } return x; } /** * returns the top coordinate if the frame would be centered * * @return the top coordinate */ protected int getCenteredTop() { int height; int y; height = getBounds().height; y = (getGraphicsConfiguration().getBounds().height - height) / 2; if (y < 0) { y = 0; } return y; } /** * positions the window at the center of the screen */ public void setCenteredLocation() { setLocation(getCenteredLeft(), getCenteredTop()); } /** * whether to present a MessageBox on Exit or not * * @param confirm whether a MessageBox pops up or not to confirm exit */ public void setConfirmExit(boolean confirm) { m_MainPanel.setConfirmExit(confirm); } /** * returns the setting of whether to display a confirm messagebox or not on * exit * * @return whether a messagebox is displayed or not */ public boolean getConfirmExit() { return m_MainPanel.getConfirmExit(); } /** * whether to do a System.exit(0) on close * * @param value enables/disables the System.exit(0) */ public void setExitOnClose(boolean value) { m_MainPanel.setExitOnClose(value); } /** * returns TRUE if a System.exit(0) is done on a close * * @return true if System.exit(0) is done */ public boolean getExitOnClose() { return m_MainPanel.getExitOnClose(); } /** * returns the main panel * * @return the main panel */ public ArffViewerMainPanel getMainPanel() { return m_MainPanel; } /** * validates and repaints the frame */ public void refresh() { validate(); repaint(); } /** * invoked when a window is activated * * @param e the window event */ @Override public void windowActivated(WindowEvent e) { } /** * invoked when a window is closed * * @param e the window event */ @Override public void windowClosed(WindowEvent e) { } /** * invoked when a window is in the process of closing * * @param e the window event */ @Override public void windowClosing(WindowEvent e) { int button; while (getMainPanel().getTabbedPane().getTabCount() > 0) { getMainPanel().closeFile(false); } if (getConfirmExit()) { button = ComponentHelper.showMessageBox(this, "Quit - " + getTitle(), "Do you really want to quit?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (button == JOptionPane.YES_OPTION) { dispose(); } } else { dispose(); } if (getExitOnClose()) { System.exit(0); } } /** * invoked when a window is deactivated * * @param e the window event */ @Override public void windowDeactivated(WindowEvent e) { } /** * invoked when a window is deiconified * * @param e the window event */ @Override public void windowDeiconified(WindowEvent e) { } /** * invoked when a window is iconified * * @param e the window event */ @Override public void windowIconified(WindowEvent e) { } /** * invoked when a window is has been opened * * @param e the window event */ @Override public void windowOpened(WindowEvent e) { } /** * returns only the classname * * @return the classname */ @Override public String toString() { return this.getClass().getName(); } /** * shows the frame and it tries to load all the arff files that were provided * as arguments. * * @param args the commandline parameters * @throws Exception if something goes wrong */ public static void main(String[] args) throws Exception { weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, "Logging started"); LookAndFeel.setLookAndFeel(); try { // uncomment to disable the memory management: // m_Memory.setEnabled(false); m_Viewer = new ArffViewer(); m_Viewer.setExitOnClose(true); m_Viewer.setVisible(true); m_FilesLoaded = false; m_Args = args; Thread memMonitor = new Thread() { @Override public void run() { while (true) { // try { if ((m_Args.length > 0) && (!m_FilesLoaded)) { for (int i = 0; i < m_Args.length; i++) { System.out.println("Loading " + (i + 1) + "/" + m_Args.length + ": '" + m_Args[i] + "'..."); m_Viewer.getMainPanel().loadFile(m_Args[i]); } m_Viewer.getMainPanel().getTabbedPane().setSelectedIndex(0); System.out.println("Finished!"); m_FilesLoaded = true; } // System.out.println("before sleeping"); // Thread.sleep(10); if (m_Memory.isOutOfMemory()) { // clean up m_Viewer.dispose(); m_Viewer = null; System.gc(); // display error System.err.println("\ndisplayed message:"); m_Memory.showOutOfMemory(); System.err.println("\nrestarting..."); // restart GUI System.gc(); m_Viewer = new ArffViewer(); m_Viewer.setExitOnClose(true); m_Viewer.setVisible(true); // Note: no re-loading of datasets, otherwise we could end up // in an endless loop! } // } catch (InterruptedException ex) { // ex.printStackTrace(); // } } } }; memMonitor.setPriority(Thread.NORM_PRIORITY); memMonitor.start(); } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/arffviewer/ArffViewerMainPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ArffViewerMainPanel.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.arffviewer; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Cursor; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Vector; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JInternalFrame; import javax.swing.JList; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.KeyStroke; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import weka.core.Capabilities; import weka.core.Instances; import weka.core.converters.AbstractFileLoader; import weka.core.converters.AbstractFileSaver; import weka.core.converters.AbstractSaver; import weka.core.converters.ConverterUtils; import weka.gui.ComponentHelper; import weka.gui.ConverterFileChooser; import weka.gui.JTableHelper; import weka.gui.ListSelectorDialog; /** * The main panel of the ArffViewer. It has a reference to the menu, that an * implementing JFrame only needs to add via the setJMenuBar(JMenuBar) method. * * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class ArffViewerMainPanel extends JPanel implements ActionListener, ChangeListener { /** for serialization */ static final long serialVersionUID = -8763161167586738753L; /** the default for width */ public final static int DEFAULT_WIDTH = -1; /** the default for height */ public final static int DEFAULT_HEIGHT = -1; /** the default for left */ public final static int DEFAULT_LEFT = -1; /** the default for top */ public final static int DEFAULT_TOP = -1; /** default width */ public final static int WIDTH = 800; /** default height */ public final static int HEIGHT = 600; protected Container parent; protected JTabbedPane tabbedPane; protected JMenuBar menuBar; protected JMenu menuFile; protected JMenuItem menuFileOpen; protected JMenuItem menuFileSave; protected JMenuItem menuFileSaveAs; protected JMenuItem menuFileClose; protected JMenuItem menuFileCloseAll; protected JMenuItem menuFileProperties; protected JMenuItem menuFileExit; protected JMenu menuEdit; protected JMenuItem menuEditUndo; protected JMenuItem menuEditCopy; protected JMenuItem menuEditSearch; protected JMenuItem menuEditClearSearch; protected JMenuItem menuEditDeleteAttribute; protected JMenuItem menuEditDeleteAttributes; protected JMenuItem menuEditRenameAttribute; protected JMenuItem menuEditAttributeAsClass; protected JMenuItem menuEditDeleteInstance; protected JMenuItem menuEditDeleteInstances; protected JMenuItem menuEditSortInstances; protected JMenu menuView; protected JMenuItem menuViewAttributes; protected JMenuItem menuViewValues; protected JMenuItem menuViewOptimalColWidths; protected ConverterFileChooser fileChooser; protected String frameTitle; protected boolean confirmExit; protected int width; protected int height; protected int top; protected int left; protected boolean exitOnClose; /** * initializes the object * * @param parentFrame the parent frame (JFrame or JInternalFrame) */ public ArffViewerMainPanel(final Container parentFrame) { this.parent = parentFrame; this.frameTitle = "ARFF-Viewer"; this.createPanel(); } /** * creates all the components in the panel */ protected void createPanel() { // basic setup this.setSize(WIDTH, HEIGHT); this.setConfirmExit(false); this.setLayout(new BorderLayout()); // file dialog this.fileChooser = new ConverterFileChooser(new File(System.getProperty("user.dir"))); this.fileChooser.setMultiSelectionEnabled(true); // menu this.menuBar = new JMenuBar(); this.menuFile = new JMenu("File"); this.menuFileOpen = new JMenuItem("Open...", ComponentHelper.getImageIcon("open.gif")); this.menuFileOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, KeyEvent.CTRL_MASK)); this.menuFileOpen.addActionListener(this); this.menuFileSave = new JMenuItem("Save", ComponentHelper.getImageIcon("save.gif")); this.menuFileSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_MASK)); this.menuFileSave.addActionListener(this); this.menuFileSaveAs = new JMenuItem("Save as...", ComponentHelper.getImageIcon("empty.gif")); this.menuFileSaveAs.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_MASK + KeyEvent.SHIFT_MASK)); this.menuFileSaveAs.addActionListener(this); this.menuFileClose = new JMenuItem("Close", ComponentHelper.getImageIcon("empty.gif")); this.menuFileClose.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, KeyEvent.CTRL_MASK)); this.menuFileClose.addActionListener(this); this.menuFileCloseAll = new JMenuItem("Close all", ComponentHelper.getImageIcon("empty.gif")); this.menuFileCloseAll.addActionListener(this); this.menuFileProperties = new JMenuItem("Properties", ComponentHelper.getImageIcon("empty.gif")); this.menuFileProperties.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.CTRL_MASK)); this.menuFileProperties.addActionListener(this); this.menuFileExit = new JMenuItem("Exit", ComponentHelper.getImageIcon("forward.gif")); this.menuFileExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, KeyEvent.ALT_MASK)); this.menuFileExit.addActionListener(this); this.menuFile.add(this.menuFileOpen); this.menuFile.add(this.menuFileSave); this.menuFile.add(this.menuFileSaveAs); this.menuFile.add(this.menuFileClose); this.menuFile.add(this.menuFileCloseAll); this.menuFile.addSeparator(); this.menuFile.add(this.menuFileProperties); this.menuFile.addSeparator(); this.menuFile.add(this.menuFileExit); this.menuBar.add(this.menuFile); this.menuEdit = new JMenu("Edit"); this.menuEditUndo = new JMenuItem("Undo", ComponentHelper.getImageIcon("undo.gif")); this.menuEditUndo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, KeyEvent.CTRL_MASK)); this.menuEditUndo.addActionListener(this); this.menuEditCopy = new JMenuItem("Copy", ComponentHelper.getImageIcon("copy.gif")); this.menuEditCopy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, KeyEvent.CTRL_MASK)); this.menuEditCopy.addActionListener(this); this.menuEditSearch = new JMenuItem("Search...", ComponentHelper.getImageIcon("find.gif")); this.menuEditSearch.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, KeyEvent.CTRL_MASK)); this.menuEditSearch.addActionListener(this); this.menuEditClearSearch = new JMenuItem("Clear search", ComponentHelper.getImageIcon("empty.gif")); this.menuEditClearSearch.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, KeyEvent.CTRL_MASK + KeyEvent.SHIFT_MASK)); this.menuEditClearSearch.addActionListener(this); this.menuEditRenameAttribute = new JMenuItem("Rename attribute", ComponentHelper.getImageIcon("empty.gif")); this.menuEditRenameAttribute.addActionListener(this); this.menuEditAttributeAsClass = new JMenuItem("Attribute as class", ComponentHelper.getImageIcon("empty.gif")); this.menuEditAttributeAsClass.addActionListener(this); this.menuEditDeleteAttribute = new JMenuItem("Delete attribute", ComponentHelper.getImageIcon("empty.gif")); this.menuEditDeleteAttribute.addActionListener(this); this.menuEditDeleteAttributes = new JMenuItem("Delete attributes", ComponentHelper.getImageIcon("empty.gif")); this.menuEditDeleteAttributes.addActionListener(this); this.menuEditDeleteInstance = new JMenuItem("Delete instance", ComponentHelper.getImageIcon("empty.gif")); this.menuEditDeleteInstance.addActionListener(this); this.menuEditDeleteInstances = new JMenuItem("Delete instances", ComponentHelper.getImageIcon("empty.gif")); this.menuEditDeleteInstances.addActionListener(this); this.menuEditSortInstances = new JMenuItem("Sort data (ascending)", ComponentHelper.getImageIcon("sort.gif")); this.menuEditSortInstances.addActionListener(this); this.menuEdit.add(this.menuEditUndo); this.menuEdit.addSeparator(); this.menuEdit.add(this.menuEditCopy); this.menuEdit.addSeparator(); this.menuEdit.add(this.menuEditSearch); this.menuEdit.add(this.menuEditClearSearch); this.menuEdit.addSeparator(); this.menuEdit.add(this.menuEditRenameAttribute); this.menuEdit.add(this.menuEditAttributeAsClass); this.menuEdit.add(this.menuEditDeleteAttribute); this.menuEdit.add(this.menuEditDeleteAttributes); this.menuEdit.addSeparator(); this.menuEdit.add(this.menuEditDeleteInstance); this.menuEdit.add(this.menuEditDeleteInstances); this.menuEdit.add(this.menuEditSortInstances); this.menuBar.add(this.menuEdit); this.menuView = new JMenu("View"); this.menuViewAttributes = new JMenuItem("Attributes...", ComponentHelper.getImageIcon("objects.gif")); this.menuViewAttributes.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.CTRL_MASK + KeyEvent.SHIFT_MASK)); this.menuViewAttributes.addActionListener(this); this.menuViewValues = new JMenuItem("Values...", ComponentHelper.getImageIcon("properties.gif")); this.menuViewValues.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, KeyEvent.CTRL_MASK + KeyEvent.SHIFT_MASK)); this.menuViewValues.addActionListener(this); this.menuViewOptimalColWidths = new JMenuItem("Optimal column width (all)", ComponentHelper.getImageIcon("resize.gif")); this.menuViewOptimalColWidths.addActionListener(this); this.menuView.add(this.menuViewAttributes); this.menuView.add(this.menuViewValues); this.menuView.addSeparator(); this.menuView.add(this.menuViewOptimalColWidths); this.menuBar.add(this.menuView); // tabbed pane this.tabbedPane = new JTabbedPane(); this.tabbedPane.addChangeListener(this); this.add(this.tabbedPane, BorderLayout.CENTER); this.updateMenu(); this.updateFrameTitle(); } /** * returns the parent frame, if it's a JFrame, otherwise null * * @return the parent frame */ public JFrame getParentFrame() { if (this.parent instanceof JFrame) { return (JFrame) this.parent; } else { return null; } } /** * returns the parent frame, if it's a JInternalFrame, otherwise null * * @return the parent frame */ public JInternalFrame getParentInternalFrame() { if (this.parent instanceof JInternalFrame) { return (JInternalFrame) this.parent; } else { return null; } } /** * sets the new parent frame * * @param value the parent frame */ public void setParent(final Container value) { this.parent = value; } /** * returns the menu bar to be added in a frame * * @return the menu bar */ public JMenuBar getMenu() { return this.menuBar; } /** * returns the tabbedpane instance * * @return the tabbed pane */ public JTabbedPane getTabbedPane() { return this.tabbedPane; } /** * whether to present a MessageBox on Exit or not * * @param confirm whether a MessageBox pops up or not to confirm exit */ public void setConfirmExit(final boolean confirm) { this.confirmExit = confirm; } /** * returns the setting of whether to display a confirm messagebox or not on * exit * * @return whether a messagebox is displayed or not */ public boolean getConfirmExit() { return this.confirmExit; } /** * whether to do a System.exit(0) on close * * @param value enables/disables a System.exit(0) on close */ public void setExitOnClose(final boolean value) { this.exitOnClose = value; } /** * returns TRUE if a System.exit(0) is done on a close * * @return true if a System.exit(0) is done on close */ public boolean getExitOnClose() { return this.exitOnClose; } /** * validates and repaints the frame */ public void refresh() { this.validate(); this.repaint(); } /** * returns the title (incl. filename) for the frame * * @return the frame title */ public String getFrameTitle() { if (this.getCurrentFilename().equals("")) { return this.frameTitle; } else { return this.frameTitle + " - " + this.getCurrentFilename(); } } /** * sets the title of the parent frame, if one was provided */ public void updateFrameTitle() { if (this.getParentFrame() != null) { this.getParentFrame().setTitle(this.getFrameTitle()); } if (this.getParentInternalFrame() != null) { this.getParentInternalFrame().setTitle(this.getFrameTitle()); } } /** * sets the enabled/disabled state of the menu */ protected void updateMenu() { boolean fileOpen; boolean isChanged; boolean canUndo; fileOpen = (this.getCurrentPanel() != null); isChanged = fileOpen && (this.getCurrentPanel().isChanged()); canUndo = fileOpen && (this.getCurrentPanel().canUndo()); // File this.menuFileOpen.setEnabled(true); this.menuFileSave.setEnabled(isChanged); this.menuFileSaveAs.setEnabled(fileOpen); this.menuFileClose.setEnabled(fileOpen); this.menuFileCloseAll.setEnabled(fileOpen); this.menuFileProperties.setEnabled(fileOpen); this.menuFileExit.setEnabled(true); // Edit this.menuEditUndo.setEnabled(canUndo); this.menuEditCopy.setEnabled(fileOpen); this.menuEditSearch.setEnabled(fileOpen); this.menuEditClearSearch.setEnabled(fileOpen); this.menuEditAttributeAsClass.setEnabled(fileOpen); this.menuEditRenameAttribute.setEnabled(fileOpen); this.menuEditDeleteAttribute.setEnabled(fileOpen); this.menuEditDeleteAttributes.setEnabled(fileOpen); this.menuEditDeleteInstance.setEnabled(fileOpen); this.menuEditDeleteInstances.setEnabled(fileOpen); this.menuEditSortInstances.setEnabled(fileOpen); // View this.menuViewAttributes.setEnabled(fileOpen); this.menuViewValues.setEnabled(fileOpen); this.menuViewOptimalColWidths.setEnabled(fileOpen); } /** * sets the title of the tab that contains the given component * * @param component the component to set the title for */ protected void setTabTitle(final JComponent component) { int index; if (!(component instanceof ArffPanel)) { return; } index = this.tabbedPane.indexOfComponent(component); if (index == -1) { return; } this.tabbedPane.setTitleAt(index, ((ArffPanel) component).getTitle()); this.updateFrameTitle(); } /** * returns the number of panels currently open * * @return the number of open panels */ public int getPanelCount() { return this.tabbedPane.getTabCount(); } /** * returns the specified panel, <code>null</code> if index is out of bounds * * @param index the index of the panel * @return the panel */ public ArffPanel getPanel(final int index) { if ((index >= 0) && (index < this.getPanelCount())) { return (ArffPanel) this.tabbedPane.getComponentAt(index); } else { return null; } } /** * returns the currently selected tab index * * @return the index of the currently selected tab */ public int getCurrentIndex() { return this.tabbedPane.getSelectedIndex(); } /** * returns the currently selected panel * * @return the currently selected panel */ public ArffPanel getCurrentPanel() { return this.getPanel(this.getCurrentIndex()); } /** * checks whether a panel is currently selected * * @return true if a panel is currently selected */ public boolean isPanelSelected() { return (this.getCurrentPanel() != null); } /** * returns the filename of the specified panel * * @param index the index of the panel * @return the filename for the panel */ public String getFilename(final int index) { String result; ArffPanel panel; result = ""; panel = this.getPanel(index); if (panel != null) { result = panel.getFilename(); } return result; } /** * returns the filename of the current tab * * @return the current filename */ public String getCurrentFilename() { return this.getFilename(this.getCurrentIndex()); } /** * sets the filename of the specified panel * * @param index the index of the panel * @param filename the new filename */ public void setFilename(final int index, final String filename) { ArffPanel panel; panel = this.getPanel(index); if (panel != null) { panel.setFilename(filename); this.setTabTitle(panel); } } /** * sets the filename of the current tab * * @param filename the new filename */ public void setCurrentFilename(final String filename) { this.setFilename(this.getCurrentIndex(), filename); } /** * if the file is changed it pops up a dialog whether to change the settings. * if the project wasn't changed or saved it returns TRUE * * @return true if project wasn't changed or saved */ protected boolean saveChanges() { return this.saveChanges(true); } /** * if the file is changed it pops up a dialog whether to change the settings. * if the project wasn't changed or saved it returns TRUE * * @param showCancel whether we have YES/NO/CANCEL or only YES/NO * @return true if project wasn't changed or saved */ protected boolean saveChanges(final boolean showCancel) { int button; boolean result; if (!this.isPanelSelected()) { return true; } result = !this.getCurrentPanel().isChanged(); if (this.getCurrentPanel().isChanged()) { try { if (showCancel) { button = ComponentHelper.showMessageBox(this, "Changed", "The file is not saved - Do you want to save it?", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); } else { button = ComponentHelper.showMessageBox(this, "Changed", "The file is not saved - Do you want to save it?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); } } catch (Exception e) { button = JOptionPane.CANCEL_OPTION; } switch (button) { case JOptionPane.YES_OPTION: this.saveFile(); result = !this.getCurrentPanel().isChanged(); break; case JOptionPane.NO_OPTION: result = true; break; case JOptionPane.CANCEL_OPTION: result = false; break; } } return result; } /** * loads the specified file * * @param filename the file to load * @param loaders optional varargs loader to use */ public void loadFile(final String filename, final AbstractFileLoader... loaders) { ArffPanel panel; panel = new ArffPanel(filename, loaders); panel.addChangeListener(this); this.tabbedPane.addTab(panel.getTitle(), panel); this.tabbedPane.setSelectedIndex(this.tabbedPane.getTabCount() - 1); } /** * loads the specified file into the table */ public void loadFile() { int retVal; int i; String filename; retVal = this.fileChooser.showOpenDialog(this); if (retVal != ConverterFileChooser.APPROVE_OPTION) { return; } this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); for (i = 0; i < this.fileChooser.getSelectedFiles().length; i++) { filename = this.fileChooser.getSelectedFiles()[i].getAbsolutePath(); this.loadFile(filename, this.fileChooser.getLoader()); } this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } /** * saves the current data into a file */ public void saveFile() { ArffPanel panel; String filename; AbstractSaver saver; // no panel? -> exit panel = this.getCurrentPanel(); if (panel == null) { return; } filename = panel.getFilename(); if (filename.equals(ArffPanel.TAB_INSTANCES)) { this.saveFileAs(); } else { saver = ConverterUtils.getSaverForFile(filename); try { saver.setFile(new File(filename)); saver.setInstances(panel.getInstances()); saver.writeBatch(); panel.setChanged(false); this.setCurrentFilename(filename); } catch (Exception e) { e.printStackTrace(); } } } /** * saves the current data into a new file * @throws InterruptedException */ public void saveFileAs() { int retVal; ArffPanel panel; // no panel? -> exit panel = this.getCurrentPanel(); if (panel == null) { System.out.println("nothing selected!"); return; } if (!this.getCurrentFilename().equals("")) { try { this.fileChooser.setSelectedFile(new File(this.getCurrentFilename())); } catch (Exception e) { // ignore } } // set filter for savers try { this.fileChooser.setCapabilitiesFilter(Capabilities.forInstances(panel.getInstances())); } catch (Exception e) { this.fileChooser.setCapabilitiesFilter(null); } retVal = this.fileChooser.showSaveDialog(this); if (retVal != ConverterFileChooser.APPROVE_OPTION) { return; } panel.setChanged(false); this.setCurrentFilename(this.fileChooser.getSelectedFile().getAbsolutePath()); // saveFile(); AbstractFileSaver saver = this.fileChooser.getSaver(); try { saver.setInstances(panel.getInstances()); saver.writeBatch(); panel.setChanged(false); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } /** * closes the current tab */ public void closeFile() { this.closeFile(true); } /** * closes the current tab * * @param showCancel whether to show an additional CANCEL button in the * "Want to save changes"-dialog * @see #saveChanges(boolean) */ public void closeFile(final boolean showCancel) { if (this.getCurrentIndex() == -1) { return; } if (!this.saveChanges(showCancel)) { return; } this.tabbedPane.removeTabAt(this.getCurrentIndex()); this.updateFrameTitle(); System.gc(); } /** * closes all open files */ public void closeAllFiles() { while (this.tabbedPane.getTabCount() > 0) { if (!this.saveChanges(true)) { return; } this.tabbedPane.removeTabAt(this.getCurrentIndex()); this.updateFrameTitle(); System.gc(); } } /** * displays some properties of the instances */ public void showProperties() { ArffPanel panel; ListSelectorDialog dialog; Vector<String> props; Instances inst; panel = this.getCurrentPanel(); if (panel == null) { return; } inst = panel.getInstances(); if (inst == null) { return; } if (inst.classIndex() < 0) { inst.setClassIndex(inst.numAttributes() - 1); } // get some data props = new Vector<String>(); props.add("Filename: " + panel.getFilename()); props.add("Relation name: " + inst.relationName()); props.add("# of instances: " + inst.numInstances()); props.add("# of attributes: " + inst.numAttributes()); props.add("Class attribute: " + inst.classAttribute().name()); props.add("# of class labels: " + inst.numClasses()); dialog = new ListSelectorDialog(this.getParentFrame(), new JList(props)); dialog.showDialog(); } /** * closes the window, i.e., if the parent is not null and implements the * WindowListener interface it calls the windowClosing method */ public void close() { if (this.getParentInternalFrame() != null) { this.getParentInternalFrame().doDefaultCloseAction(); } else if (this.getParentFrame() != null) { ((Window) this.getParentFrame()).dispatchEvent(new WindowEvent(this.getParentFrame(), WindowEvent.WINDOW_CLOSING)); } } /** * undoes the last action */ public void undo() { if (!this.isPanelSelected()) { return; } this.getCurrentPanel().undo(); } /** * copies the content of the selection to the clipboard */ public void copyContent() { if (!this.isPanelSelected()) { return; } this.getCurrentPanel().copyContent(); } /** * searches for a string in the cells */ public void search() { if (!this.isPanelSelected()) { return; } this.getCurrentPanel().search(); } /** * clears the search, i.e. resets the found cells */ public void clearSearch() { if (!this.isPanelSelected()) { return; } this.getCurrentPanel().clearSearch(); } /** * renames the current selected Attribute */ public void renameAttribute() { if (!this.isPanelSelected()) { return; } this.getCurrentPanel().renameAttribute(); } /** * sets the current selected Attribute as class attribute, i.e. it moves it to * the end of the attributes */ public void attributeAsClass() { if (!this.isPanelSelected()) { return; } this.getCurrentPanel().attributeAsClass(); } /** * deletes the current selected Attribute or several chosen ones * * @param multiple whether to delete myultiple attributes */ public void deleteAttribute(final boolean multiple) { if (!this.isPanelSelected()) { return; } if (multiple) { this.getCurrentPanel().deleteAttributes(); } else { this.getCurrentPanel().deleteAttribute(); } } /** * deletes the current selected Instance or several chosen ones * * @param multiple whether to delete multiple instances */ public void deleteInstance(final boolean multiple) { if (!this.isPanelSelected()) { return; } if (multiple) { this.getCurrentPanel().deleteInstances(); } else { this.getCurrentPanel().deleteInstance(); } } /** * sorts the current selected attribute */ public void sortInstances() { if (!this.isPanelSelected()) { return; } this.getCurrentPanel().sortInstances(); } /** * displays all the attributes, returns the selected item or NULL if canceled * * @return the name of the selected attribute */ public String showAttributes() { ArffSortedTableModel model; ListSelectorDialog dialog; int i; JList list; String name; int result; if (!this.isPanelSelected()) { return null; } list = new JList(this.getCurrentPanel().getAttributes()); dialog = new ListSelectorDialog(this.getParentFrame(), list); result = dialog.showDialog(); if (result == ListSelectorDialog.APPROVE_OPTION) { model = (ArffSortedTableModel) this.getCurrentPanel().getTable().getModel(); name = list.getSelectedValue().toString(); i = model.getAttributeColumn(name); JTableHelper.scrollToVisible(this.getCurrentPanel().getTable(), 0, i); this.getCurrentPanel().getTable().setSelectedColumn(i); return name; } else { return null; } } /** * displays all the distinct values for an attribute */ public void showValues() { String attribute; ArffSortedTableModel model; ArffTable table; HashSet<String> values; Vector<String> items; Iterator<String> iter; ListSelectorDialog dialog; int i; int col; // choose attribute to retrieve values for attribute = this.showAttributes(); if (attribute == null) { return; } table = this.getCurrentPanel().getTable(); model = (ArffSortedTableModel) table.getModel(); // get column index col = -1; for (i = 0; i < table.getColumnCount(); i++) { if (table.getPlainColumnName(i).equals(attribute)) { col = i; break; } } // not found? if (col == -1) { return; } // get values values = new HashSet<String>(); items = new Vector<String>(); for (i = 0; i < model.getRowCount(); i++) { values.add(model.getValueAt(i, col).toString()); } if (values.isEmpty()) { return; } iter = values.iterator(); while (iter.hasNext()) { items.add(iter.next()); } Collections.sort(items); dialog = new ListSelectorDialog(this.getParentFrame(), new JList(items)); dialog.showDialog(); } /** * sets the optimal column width for all columns */ public void setOptimalColWidths() { if (!this.isPanelSelected()) { return; } this.getCurrentPanel().setOptimalColWidths(); } /** * invoked when an action occurs * * @param e the action event */ @Override public void actionPerformed(final ActionEvent e) { Object o; o = e.getSource(); if (o == this.menuFileOpen) { this.loadFile(); } else if (o == this.menuFileSave) { this.saveFile(); } else if (o == this.menuFileSaveAs) { this.saveFileAs(); } else if (o == this.menuFileClose) { this.closeFile(); } else if (o == this.menuFileCloseAll) { this.closeAllFiles(); } else if (o == this.menuFileProperties) { this.showProperties(); } else if (o == this.menuFileExit) { this.close(); } else if (o == this.menuEditUndo) { this.undo(); } else if (o == this.menuEditCopy) { this.copyContent(); } else if (o == this.menuEditSearch) { this.search(); } else if (o == this.menuEditClearSearch) { this.clearSearch(); } else if (o == this.menuEditDeleteAttribute) { this.deleteAttribute(false); } else if (o == this.menuEditDeleteAttributes) { this.deleteAttribute(true); } else if (o == this.menuEditRenameAttribute) { this.renameAttribute(); } else if (o == this.menuEditAttributeAsClass) { this.attributeAsClass(); } else if (o == this.menuEditDeleteInstance) { this.deleteInstance(false); } else if (o == this.menuEditDeleteInstances) { this.deleteInstance(true); } else if (o == this.menuEditSortInstances) { this.sortInstances(); } else if (o == this.menuViewAttributes) { this.showAttributes(); } else if (o == this.menuViewValues) { this.showValues(); } else if (o == this.menuViewOptimalColWidths) { this.setOptimalColWidths(); } this.updateMenu(); } /** * Invoked when the target of the listener has changed its state. * * @param e the change event */ @Override public void stateChanged(final ChangeEvent e) { this.updateFrameTitle(); this.updateMenu(); // did the content of panel change? -> change title of tab if (e.getSource() instanceof JComponent) { this.setTabTitle((JComponent) e.getSource()); } } /** * returns only the classname * * @return the classname */ @Override public String toString() { return this.getClass().getName(); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/AbstractDataSink.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * AbstractDataSink.java * Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.awt.BorderLayout; import java.beans.EventSetDescriptor; import java.io.Serializable; import javax.swing.JPanel; /** * Abstract class for objects that store instances to some destination. * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ * @since 1.0 * @see JPanel * @see Serializable */ public abstract class AbstractDataSink extends JPanel implements DataSink, BeanCommon, Visible, DataSourceListener, TrainingSetListener, TestSetListener, InstanceListener, ThresholdDataListener, Serializable { /** for serialization */ private static final long serialVersionUID = 3956528599473814287L; /** * Default visual for data sources */ protected BeanVisual m_visual = new BeanVisual("AbstractDataSink", BeanVisual.ICON_PATH + "DefaultDataSink.gif", BeanVisual.ICON_PATH + "DefaultDataSink_animated.gif"); /** * Non null if this object is a target for any events. * Provides for the simplest case when only one incomming connection * is allowed. Subclasses can overide the appropriate BeanCommon methods * to change this behaviour and allow multiple connections if desired */ protected Object m_listenee = null; protected transient weka.gui.Logger m_logger = null; public AbstractDataSink() { this.useDefaultVisual(); this.setLayout(new BorderLayout()); this.add(this.m_visual, BorderLayout.CENTER); } /** * Accept a training set * * @param e a <code>TrainingSetEvent</code> value */ @Override public abstract void acceptTrainingSet(TrainingSetEvent e); /** * Accept a test set * * @param e a <code>TestSetEvent</code> value */ @Override public abstract void acceptTestSet(TestSetEvent e); /** * Accept a data set * * @param e a <code>DataSetEvent</code> value */ @Override public abstract void acceptDataSet(DataSetEvent e); /** * Accept a threshold data set * * @param e a <code>ThresholdDataEvent</code> value */ @Override public abstract void acceptDataSet(ThresholdDataEvent e); /** * Accept an instance * * @param e an <code>InstanceEvent</code> value */ @Override public abstract void acceptInstance(InstanceEvent e); /** * Set the visual for this data source * * @param newVisual a <code>BeanVisual</code> value */ @Override public void setVisual(final BeanVisual newVisual) { this.m_visual = newVisual; } /** * Get the visual being used by this data source. * */ @Override public BeanVisual getVisual() { return this.m_visual; } /** * Use the default images for a data source * */ @Override public void useDefaultVisual() { this.m_visual.loadIcons(BeanVisual.ICON_PATH + "DefaultDataSink.gif", BeanVisual.ICON_PATH + "DefaultDataSink_animated.gif"); } /** * Returns true if, at this time, * the object will accept a connection according to the supplied * EventSetDescriptor * * @param esd the EventSetDescriptor * @return true if the object will accept a connection */ @Override public boolean connectionAllowed(final EventSetDescriptor esd) { return this.connectionAllowed(esd.getName()); } /** * Returns true if, at this time, * the object will accept a connection according to the supplied * event name * * @param eventName the event * @return true if the object will accept a connection */ @Override public boolean connectionAllowed(final String eventName) { return (this.m_listenee == null); } /** * Notify this object that it has been registered as a listener with * a source with respect to the supplied event name * * @param eventName the event * @param source the source with which this object has been registered as * a listener */ @Override public synchronized void connectionNotification(final String eventName, final Object source) { if (this.connectionAllowed(eventName)) { this.m_listenee = source; } } /** * Notify this object that it has been deregistered as a listener with * a source with respect to the supplied event name * * @param eventName the event * @param source the source with which this object has been registered as * a listener */ @Override public synchronized void disconnectionNotification(final String eventName, final Object source) { if (this.m_listenee == source) { this.m_listenee = null; } } /** * Set a log for this bean * * @param logger a <code>weka.gui.Logger</code> value */ @Override public void setLog(final weka.gui.Logger logger) { this.m_logger = logger; } /** * Stop any processing that the bean might be doing. * Subclass must implement */ @Override public abstract void stop(); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/AbstractDataSinkBeanInfo.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * AbstractDataSinkBeanInfo.java * Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.beans.EventSetDescriptor; import java.beans.SimpleBeanInfo; /** * Bean info class for the AbstractDataSink * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ */ public class AbstractDataSinkBeanInfo extends SimpleBeanInfo { /** * Get the event set descriptors for this bean * * @return an <code>EventSetDescriptor[]</code> value */ public EventSetDescriptor [] getEventSetDescriptors() { // hide all gui events EventSetDescriptor [] esds = { }; return esds; } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/AbstractDataSource.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * AbstractDataSource.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.awt.BorderLayout; import java.beans.PropertyChangeListener; import java.beans.VetoableChangeListener; import java.beans.beancontext.BeanContext; import java.beans.beancontext.BeanContextChild; import java.beans.beancontext.BeanContextChildSupport; import java.io.Serializable; import java.util.EventListener; import java.util.Vector; import javax.swing.JPanel; /** * Abstract class for objects that can provide instances from some source * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ * @since 1.0 * @see JPanel * @see DataSource * @see Serializable */ public abstract class AbstractDataSource extends JPanel implements DataSource, Visible, Serializable, BeanContextChild { /** for serialization */ private static final long serialVersionUID = -4127257701890044793L; /** * True if this bean's appearance is the design mode appearance */ protected boolean m_design; /** * BeanContex that this bean might be contained within */ protected transient BeanContext m_beanContext = null; /** * BeanContextChild support */ protected BeanContextChildSupport m_bcSupport = new BeanContextChildSupport( this); /** * Default visual for data sources */ protected BeanVisual m_visual = new BeanVisual("AbstractDataSource", BeanVisual.ICON_PATH + "DefaultDataSource.gif", BeanVisual.ICON_PATH + "DefaultDataSource_animated.gif"); /** * Objects listening for events from data sources */ protected Vector<EventListener> m_listeners; /** * Creates a new <code>AbstractDataSource</code> instance. * */ public AbstractDataSource() { useDefaultVisual(); setLayout(new BorderLayout()); add(m_visual, BorderLayout.CENTER); m_listeners = new Vector<EventListener>(); } /** * Add a listener * * @param dsl a <code>DataSourceListener</code> value */ @Override public synchronized void addDataSourceListener(DataSourceListener dsl) { m_listeners.addElement(dsl); } /** * Remove a listener * * @param dsl a <code>DataSourceListener</code> value */ @Override public synchronized void removeDataSourceListener(DataSourceListener dsl) { m_listeners.remove(dsl); } /** * Add an instance listener * * @param dsl a <code>InstanceListener</code> value */ @Override public synchronized void addInstanceListener(InstanceListener dsl) { m_listeners.add(dsl); } /** * Remove an instance listener * * @param dsl a <code>InstanceListener</code> value */ @Override public synchronized void removeInstanceListener(InstanceListener dsl) { m_listeners.remove(dsl); } /** * Set the visual for this data source * * @param newVisual a <code>BeanVisual</code> value */ @Override public void setVisual(BeanVisual newVisual) { m_visual = newVisual; } /** * Get the visual being used by this data source. * */ @Override public BeanVisual getVisual() { return m_visual; } /** * Use the default images for a data source * */ @Override public void useDefaultVisual() { m_visual.loadIcons(BeanVisual.ICON_PATH + "DefaultDataSource.gif", BeanVisual.ICON_PATH + "DefaultDataSource_animated.gif"); } /** * Set a bean context for this bean * * @param bc a <code>BeanContext</code> value */ @Override public void setBeanContext(BeanContext bc) { m_beanContext = bc; m_design = m_beanContext.isDesignTime(); } /** * Return the bean context (if any) that this bean is embedded in * * @return a <code>BeanContext</code> value */ @Override public BeanContext getBeanContext() { return m_beanContext; } /** * Add a property change listener to this bean * * @param name the name of the property of interest * @param pcl a <code>PropertyChangeListener</code> value */ @Override public void addPropertyChangeListener(String name, PropertyChangeListener pcl) { m_bcSupport.addPropertyChangeListener(name, pcl); } /** * Remove a property change listener from this bean * * @param name the name of the property of interest * @param pcl a <code>PropertyChangeListener</code> value */ @Override public void removePropertyChangeListener(String name, PropertyChangeListener pcl) { m_bcSupport.removePropertyChangeListener(name, pcl); } /** * Add a vetoable change listener to this bean * * @param name the name of the property of interest * @param vcl a <code>VetoableChangeListener</code> value */ @Override public void addVetoableChangeListener(String name, VetoableChangeListener vcl) { m_bcSupport.addVetoableChangeListener(name, vcl); } /** * Remove a vetoable change listener from this bean * * @param name the name of the property of interest * @param vcl a <code>VetoableChangeListener</code> value */ @Override public void removeVetoableChangeListener(String name, VetoableChangeListener vcl) { m_bcSupport.removeVetoableChangeListener(name, vcl); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/AbstractDataSourceBeanInfo.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * AbstractDataSourceBeanInfo.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.beans.EventSetDescriptor; import java.beans.SimpleBeanInfo; /** * Bean info class for AbstractDataSource. All beans that extend * AbstractDataSource might want to extend this class * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ * @since 1.0 * @see SimpleBeanInfo */ public class AbstractDataSourceBeanInfo extends SimpleBeanInfo { /** * Get the event set descriptors pertinent to data sources * * @return an <code>EventSetDescriptor[]</code> value */ public EventSetDescriptor [] getEventSetDescriptors() { try { EventSetDescriptor [] esds = { new EventSetDescriptor(DataSource.class, "dataSet", DataSourceListener.class, "acceptDataSet"), new EventSetDescriptor(DataSource.class, "instance", InstanceListener.class, "acceptInstance") }; return esds; } catch (Exception ex) { ex.printStackTrace(); } return null; } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/AbstractEvaluator.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * AbstractEvaluator.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.awt.BorderLayout; import java.beans.EventSetDescriptor; import java.io.Serializable; import javax.swing.JPanel; import weka.gui.Logger; /** * Abstract class for objects that can provide some kind of evaluation for * classifier, clusterers etc. * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ * @since 1.0 * @see JPanel * @see Visible * @see Serializable */ public abstract class AbstractEvaluator extends JPanel implements Visible, BeanCommon, Serializable { /** for serialization */ private static final long serialVersionUID = 3983303541814121632L; /** * Default visual for evaluators */ protected BeanVisual m_visual = new BeanVisual("AbstractEvaluator", BeanVisual.ICON_PATH+"DefaultEvaluator.gif", BeanVisual.ICON_PATH+"DefaultEvaluator_animated.gif"); protected Object m_listenee = null; protected transient Logger m_logger = null; /** * Constructor */ public AbstractEvaluator() { setLayout(new BorderLayout()); add(m_visual, BorderLayout.CENTER); } /** * Set the visual * * @param newVisual a <code>BeanVisual</code> value */ public void setVisual(BeanVisual newVisual) { m_visual = newVisual; } /** * Get the visual * * @return a <code>BeanVisual</code> value */ public BeanVisual getVisual() { return m_visual; } /** * Use the default images for an evaluator */ public void useDefaultVisual() { m_visual.loadIcons(BeanVisual.ICON_PATH+"DefaultEvaluator.gif", BeanVisual.ICON_PATH+"DefaultEvaluator_animated.gif"); } /** * Returns true if, at this time, * the object will accept a connection according to the supplied * event name * * @param eventName the event name * @return true if the object will accept a connection */ public boolean connectionAllowed(String eventName) { return (m_listenee == null); } /** * Returns true if, at this time, * the object will accept a connection according to the supplied * EventSetDescriptor * * @param esd the EventSetDescriptor * @return true if the object will accept a connection */ public boolean connectionAllowed(EventSetDescriptor esd) { return connectionAllowed(esd.getName()); } /** * Notify this object that it has been registered as a listener with * a source with respect to the supplied event name * * @param eventName the event name * @param source the source with which this object has been registered as * a listener */ public synchronized void connectionNotification(String eventName, Object source) { if (connectionAllowed(eventName)) { m_listenee = source; } } /** * Notify this object that it has been deregistered as a listener with * a source with respect to the supplied event named * * @param eventName the event name * @param source the source with which this object has been registered as * a listener */ public synchronized void disconnectionNotification(String eventName, Object source) { if (m_listenee == source) { m_listenee = null; } } /** * Set a logger * * @param logger a <code>weka.gui.Logger</code> value */ public void setLog(weka.gui.Logger logger) { m_logger = logger; } /** * Stop any processing that the bean might be doing. * Subclass must implement */ public abstract void stop(); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/AbstractOffscreenChartRenderer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * AbstractOffscreenChartRenderer.java * Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.util.ArrayList; import java.util.List; import weka.core.Attribute; import weka.core.Instance; import weka.core.Instances; /** * Abstract base class for offscreen chart renderers. Provides a method * for retrieving options and a convenience method for getting the * index of an attribute given its name. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ public abstract class AbstractOffscreenChartRenderer implements OffscreenChartRenderer { /** * Utility method that splits the supplied Instances out to a list * of Instances, where each Instances object contains just the instances * of one nominal class value. Does not check whether the supplied class * index is a nominal attribute. * * @param insts the instances to split * @param classIndex the index of the nominal class attribute * @return a list of instances */ protected List<Instances> splitToClasses(Instances insts, int classIndex) { List<Instances> newSeries = new ArrayList<Instances>(); Instances[] classes = new Instances[insts.attribute(classIndex).numValues()]; for (int i = 0; i < classes.length; i++) { classes[i] = new Instances(insts, 0); classes[i].setRelationName(insts.attribute(classIndex).value(i)); } for (int i = 0; i < insts.numInstances(); i++) { Instance current = insts.instance(i); classes[(int)current.value(classIndex)].add((Instance)current.copy()); } for (int i = 0; i < classes.length; i++) { newSeries.add(classes[i]); } return newSeries; } /** * Gets a short list of additional options (if any), * suitable for displaying in a tip text, in HTML form. Concrete * subclasses should override this if they can actually process * additional options. * * @return additional options description in simple HTML form */ public String optionsTipTextHTML() { return "<html><ul><li>No options for this renderer</li></ul></html>"; } /** * Utility method for retrieving the value of an option from a * list of options. Returns null if the option to get isn't * present in the list, an empty string if it is but no value * has been specified (i.e. option is a flag) or the value * of the option.<p> * * Format is:<p> * <code>optionName=optionValue</code> * * @param options a list of options * @param toGet the option to get the value of * @return */ protected String getOption(List<String> options, String toGet) { String value = null; if (options == null) { return null; } for (String option : options) { if (option.startsWith(toGet)) { String[] parts = option.split("="); if (parts.length != 2) { return ""; // indicates a flag } value = parts[1]; break; } } return value; } /** * Get the index of a named attribute in a set of Instances. * * @param insts the Instances * @param attName the name of the attribute. * * @return the index of the attribute or -1 if the attribute is * not in the Instances. */ protected int getIndexOfAttribute(Instances insts, String attName) { if (attName == null) { return -1; } // special first and last strings if (attName.equalsIgnoreCase("/last")) { return insts.numAttributes() - 1; } if (attName.equalsIgnoreCase("/first")) { return 0; } if (attName.startsWith("/")) { // try and parse remainder as a number String numS = attName.replace("/", ""); try { int index = Integer.parseInt(numS); index--; // from 1-based to 0-based if (index >= 0 && index < insts.numAttributes()) { return index; } } catch (NumberFormatException e) { } } Attribute att = insts.attribute(attName); if (att != null) { return att.index(); } return -1; // not found } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/AbstractTestSetProducer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * AbstractTestSetProducer.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.awt.BorderLayout; import java.beans.EventSetDescriptor; import java.io.Serializable; import java.util.EventListener; import java.util.Vector; import javax.swing.JPanel; /** * Abstract class for TestSetProducers that contains default implementations of * add/remove listener methods and defualt visual representation. * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ * @since 1.0 * @see TestSetProducer */ public abstract class AbstractTestSetProducer extends JPanel implements TestSetProducer, Visible, BeanCommon, Serializable { /** for serialization */ private static final long serialVersionUID = -7905764845789349839L; /** * Objects listening to us */ protected Vector<EventListener> m_listeners = new Vector<EventListener>(); protected BeanVisual m_visual = new BeanVisual("AbstractTestSetProducer", BeanVisual.ICON_PATH + "DefaultTrainTest.gif", BeanVisual.ICON_PATH + "DefaultTrainTest_animated.gif"); /** * non null if this object is a target for any events. */ protected Object m_listenee = null; /** * Logger */ protected transient weka.gui.Logger m_logger = null; /** * Creates a new <code>AbstractTestSetProducer</code> instance. */ public AbstractTestSetProducer() { setLayout(new BorderLayout()); add(m_visual, BorderLayout.CENTER); } /** * Add a listener for test sets * * @param tsl a <code>TestSetListener</code> value */ @Override public synchronized void addTestSetListener(TestSetListener tsl) { m_listeners.addElement(tsl); } /** * Remove a listener for test sets * * @param tsl a <code>TestSetListener</code> value */ @Override public synchronized void removeTestSetListener(TestSetListener tsl) { m_listeners.removeElement(tsl); } /** * Set the visual for this bean * * @param newVisual a <code>BeanVisual</code> value */ @Override public void setVisual(BeanVisual newVisual) { m_visual = newVisual; } /** * Get the visual for this bean * * @return a <code>BeanVisual</code> value */ @Override public BeanVisual getVisual() { return m_visual; } /** * Use the default visual for this bean */ @Override public void useDefaultVisual() { m_visual.loadIcons(BeanVisual.ICON_PATH + "DefaultTrainTest.gif", BeanVisual.ICON_PATH + "DefaultTrainTest_animated.gif"); } /** * Returns true if, at this time, the object will accept a connection * according to the supplied event name * * @param eventName the event name * @return true if the object will accept a connection */ @Override public boolean connectionAllowed(String eventName) { return (m_listenee == null); } /** * Returns true if, at this time, the object will accept a connection * according to the supplied EventSetDescriptor * * @param esd the EventSetDescriptor * @return true if the object will accept a connection */ @Override public boolean connectionAllowed(EventSetDescriptor esd) { return connectionAllowed(esd.getName()); } /** * Notify this object that it has been registered as a listener with a source * with respect to the supplied event name * * @param eventName the event name * @param source the source with which this object has been registered as a * listener */ @Override public synchronized void connectionNotification(String eventName, Object source) { if (connectionAllowed(eventName)) { m_listenee = source; } } /** * Notify this object that it has been deregistered as a listener with a * source with respect to the supplied event name * * @param eventName the event name * @param source the source with which this object has been registered as a * listener */ @Override public synchronized void disconnectionNotification(String eventName, Object source) { if (m_listenee == source) { m_listenee = null; } } /** * Set a logger * * @param logger a <code>weka.gui.Logger</code> value */ @Override public void setLog(weka.gui.Logger logger) { m_logger = logger; } /** * Stop any processing that the bean might be doing. Subclass must implement */ @Override public abstract void stop(); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/AbstractTestSetProducerBeanInfo.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * AbstractTestSetProducerBeanInfo.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.beans.EventSetDescriptor; import java.beans.SimpleBeanInfo; /** * BeanInfo class for AbstractTestSetProducer * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ */ public class AbstractTestSetProducerBeanInfo extends SimpleBeanInfo { public EventSetDescriptor [] getEventSetDescriptors() { try { EventSetDescriptor [] esds = { new EventSetDescriptor(TestSetProducer.class, "testSet", TestSetListener.class, "acceptTestSet") }; return esds; } catch (Exception ex) { ex.printStackTrace(); } return null; } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/AbstractTrainAndTestSetProducer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * AbstractTrainAndTestSetProducer.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.awt.BorderLayout; import java.beans.EventSetDescriptor; import java.io.Serializable; import java.util.EventListener; import java.util.Vector; import javax.swing.JPanel; /** * Abstract base class for TrainAndTestSetProducers that contains default * implementations of add/remove listener methods and defualt visual * representation. * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ */ public abstract class AbstractTrainAndTestSetProducer extends JPanel implements Visible, TrainingSetProducer, TestSetProducer, BeanCommon, Serializable, DataSourceListener { /** for serialization */ private static final long serialVersionUID = -1809339823613492037L; /** * Objects listening for trainin set events */ protected Vector<EventListener> m_trainingListeners = new Vector<EventListener>(); /** * Objects listening for test set events */ protected Vector<EventListener> m_testListeners = new Vector<EventListener>(); protected BeanVisual m_visual = new BeanVisual("AbstractTrainingSetProducer", BeanVisual.ICON_PATH + "DefaultTrainTest.gif", BeanVisual.ICON_PATH + "DefaultTrainTest_animated.gif"); /** * non null if this object is a target for any events. */ protected Object m_listenee = null; protected transient weka.gui.Logger m_logger = null; /** * Creates a new <code>AbstractTrainAndTestSetProducer</code> instance. */ public AbstractTrainAndTestSetProducer() { setLayout(new BorderLayout()); add(m_visual, BorderLayout.CENTER); } /** * Subclass must implement * * @param e a <code>DataSetEvent</code> value */ @Override public abstract void acceptDataSet(DataSetEvent e); /** * Add a training set listener * * @param tsl a <code>TrainingSetListener</code> value */ @Override public synchronized void addTrainingSetListener(TrainingSetListener tsl) { m_trainingListeners.addElement(tsl); } /** * Remove a training set listener * * @param tsl a <code>TrainingSetListener</code> value */ @Override public synchronized void removeTrainingSetListener(TrainingSetListener tsl) { m_trainingListeners.removeElement(tsl); } /** * Add a test set listener * * @param tsl a <code>TestSetListener</code> value */ @Override public synchronized void addTestSetListener(TestSetListener tsl) { m_testListeners.addElement(tsl); } /** * Remove a test set listener * * @param tsl a <code>TestSetListener</code> value */ @Override public synchronized void removeTestSetListener(TestSetListener tsl) { m_testListeners.removeElement(tsl); } /** * Set the visual for this bean * * @param newVisual a <code>BeanVisual</code> value */ @Override public void setVisual(BeanVisual newVisual) { m_visual = newVisual; } /** * Get the visual for this bean * * @return a <code>BeanVisual</code> value */ @Override public BeanVisual getVisual() { return m_visual; } /** * Use the default visual for this bean */ @Override public void useDefaultVisual() { m_visual.loadIcons(BeanVisual.ICON_PATH + "DefaultTrainTest.gif", BeanVisual.ICON_PATH + "DefaultTrainTest_animated.gif"); } /** * Returns true if, at this time, the object will accept a connection * according to the supplied event name * * @param eventName the event * @return true if the object will accept a connection */ @Override public boolean connectionAllowed(String eventName) { return (m_listenee == null); } /** * Returns true if, at this time, the object will accept a connection * according to the supplied EventSetDescriptor * * @param esd the EventSetDescriptor * @return true if the object will accept a connection */ @Override public boolean connectionAllowed(EventSetDescriptor esd) { return connectionAllowed(esd.getName()); } /** * Notify this object that it has been registered as a listener with a source * with respect to the supplied event name * * @param eventName the event * @param source the source with which this object has been registered as a * listener */ @Override public synchronized void connectionNotification(String eventName, Object source) { if (connectionAllowed(eventName)) { m_listenee = source; } } /** * Notify this object that it has been deregistered as a listener with a * source with respect to the supplied event name * * @param eventName the event * @param source the source with which this object has been registered as a * listener */ @Override public synchronized void disconnectionNotification(String eventName, Object source) { if (m_listenee == source) { m_listenee = null; } } /** * Set a log for this bean * * @param logger a <code>weka.gui.Logger</code> value */ @Override public void setLog(weka.gui.Logger logger) { m_logger = logger; } /** * Stop any processing that the bean might be doing. Subclass must implement */ @Override public abstract void stop(); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/AbstractTrainAndTestSetProducerBeanInfo.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * AbstractTrainAndTestSetProducerBeanInfo.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.beans.EventSetDescriptor; import java.beans.SimpleBeanInfo; /** * Bean info class for AbstractTrainAndTestSetProducers * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ */ public class AbstractTrainAndTestSetProducerBeanInfo extends SimpleBeanInfo { public EventSetDescriptor [] getEventSetDescriptors() { try { EventSetDescriptor [] esds = { new EventSetDescriptor(TrainingSetProducer.class, "trainingSet", TrainingSetListener.class, "acceptTrainingSet"), new EventSetDescriptor(TestSetProducer.class, "testSet", TestSetListener.class, "acceptTestSet") }; return esds; } catch (Exception ex) { ex.printStackTrace(); } return null; } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/AbstractTrainingSetProducer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * AbstractTrainingSetProducer.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.awt.BorderLayout; import java.beans.EventSetDescriptor; import java.io.Serializable; import java.util.EventListener; import java.util.Vector; import javax.swing.JPanel; /** * Abstract class for TrainingSetProducers that contains default implementations * of add/remove listener methods and default visual representation * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ * @since 1.0 * @see TrainingSetProducer */ public abstract class AbstractTrainingSetProducer extends JPanel implements TrainingSetProducer, Visible, BeanCommon, Serializable { /** for serialization */ private static final long serialVersionUID = -7842746199524591125L; /** * Objects listening for training set events */ protected Vector<EventListener> m_listeners = new Vector<EventListener>(); protected BeanVisual m_visual = new BeanVisual("AbstractTraingSetProducer", BeanVisual.ICON_PATH + "DefaultTrainTest.gif", BeanVisual.ICON_PATH + "DefaultTrainTest_animated.gif"); /** * non null if this object is a target for any events. */ protected Object m_listenee = null; protected transient weka.gui.Logger m_logger = null; /** * Creates a new <code>AbstractTrainingSetProducer</code> instance. */ public AbstractTrainingSetProducer() { setLayout(new BorderLayout()); add(m_visual, BorderLayout.CENTER); } /** * Add a training set listener * * @param tsl a <code>TrainingSetListener</code> value */ @Override public synchronized void addTrainingSetListener(TrainingSetListener tsl) { m_listeners.addElement(tsl); } /** * Remove a training set listener * * @param tsl a <code>TrainingSetListener</code> value */ @Override public synchronized void removeTrainingSetListener(TrainingSetListener tsl) { m_listeners.removeElement(tsl); } /** * Set the visual for this bean * * @param newVisual a <code>BeanVisual</code> value */ @Override public void setVisual(BeanVisual newVisual) { m_visual = newVisual; } /** * Get the visual for this bean * * @return a <code>BeanVisual</code> value */ @Override public BeanVisual getVisual() { return m_visual; } /** * Use the default visual for this bean */ @Override public void useDefaultVisual() { m_visual.loadIcons(BeanVisual.ICON_PATH + "DefaultTrainTest.gif", BeanVisual.ICON_PATH + "DefaultTrainTest_animated.gif"); } /** * Returns true if, at this time, the object will accept a connection * according to the supplied event name * * @param eventName the event * @return true if the object will accept a connection */ @Override public boolean connectionAllowed(String eventName) { return (m_listenee == null); } /** * Returns true if, at this time, the object will accept a connection * according to the supplied EventSetDescriptor * * @param esd the EventSetDescriptor * @return true if the object will accept a connection */ @Override public boolean connectionAllowed(EventSetDescriptor esd) { return connectionAllowed(esd.getName()); } /** * Notify this object that it has been registered as a listener with a source * with respect to the supplied event name * * @param eventName * @param source the source with which this object has been registered as a * listener */ @Override public synchronized void connectionNotification(String eventName, Object source) { if (connectionAllowed(eventName)) { m_listenee = source; } } /** * Notify this object that it has been deregistered as a listener with a * source with respect to the supplied event name * * @param eventName the event name * @param source the source with which this object has been registered as a * listener */ @Override public synchronized void disconnectionNotification(String eventName, Object source) { if (m_listenee == source) { m_listenee = null; } } /** * Set a logger * * @param logger a <code>weka.gui.Logger</code> value */ @Override public void setLog(weka.gui.Logger logger) { m_logger = logger; } /** * Stop any processing that the bean might be doing. Subclass must implement */ @Override public abstract void stop(); }