List of usage examples for java.beans PropertyChangeListener PropertyChangeListener
PropertyChangeListener
From source file:org.tinymediamanager.ui.movies.MoviePanel.java
/** * further initializations.// w w w.j av a2 s . com */ private void init() { // build menu buildMenu(); // moviename column table.getColumnModel().getColumn(0).setCellRenderer(new BorderCellRenderer()); table.getColumnModel().getColumn(0).setIdentifier("title"); //$NON-NLS-1$ // year column int width = table.getFontMetrics(table.getFont()).stringWidth(" 2000"); int titleWidth = table.getFontMetrics(table.getFont()).stringWidth(BUNDLE.getString("metatag.year")); //$NON-NLS-1$ if (titleWidth > width) { width = titleWidth; } table.getTableHeader().getColumnModel().getColumn(1).setPreferredWidth(width); table.getTableHeader().getColumnModel().getColumn(1).setMinWidth(width); table.getTableHeader().getColumnModel().getColumn(1).setMaxWidth((int) (width * 1.5)); table.getTableHeader().getColumnModel().getColumn(1).setIdentifier("year"); //$NON-NLS-1$ // rating column width = table.getFontMetrics(table.getFont()).stringWidth(" 10.0"); titleWidth = table.getFontMetrics(table.getFont()).stringWidth(BUNDLE.getString("metatag.rating")); //$NON-NLS-1$ if (titleWidth > width) { width = titleWidth; } table.getTableHeader().getColumnModel().getColumn(2).setPreferredWidth((int) (width * 1.2)); table.getTableHeader().getColumnModel().getColumn(2).setMinWidth((int) (width * 1.2)); table.getTableHeader().getColumnModel().getColumn(2).setMaxWidth((int) (width * 1.5)); table.getTableHeader().getColumnModel().getColumn(2).setIdentifier("rating"); //$NON-NLS-1$ // date added column width = table.getFontMetrics(table.getFont()).stringWidth("01. Jan. 2000"); titleWidth = table.getFontMetrics(table.getFont()).stringWidth(BUNDLE.getString("metatag.dateadded")); //$NON-NLS-1$ if (titleWidth > width) { width = titleWidth; } table.getTableHeader().getColumnModel().getColumn(3).setPreferredWidth((int) (width * 1.2)); table.getTableHeader().getColumnModel().getColumn(3).setMinWidth((int) (width * 1.2)); table.getTableHeader().getColumnModel().getColumn(3).setMaxWidth((int) (width * 1.2)); table.getTableHeader().getColumnModel().getColumn(3).setIdentifier("dateadded"); //$NON-NLS-1$ // NFO column table.getTableHeader().getColumnModel().getColumn(4) .setHeaderRenderer(new IconRenderer(BUNDLE.getString("tmm.nfo"))); //$NON-NLS-1$ table.getTableHeader().getColumnModel().getColumn(4).setMaxWidth(20); table.getColumnModel().getColumn(4).setHeaderValue(IconManager.INFO); table.getTableHeader().getColumnModel().getColumn(4).setIdentifier("nfo"); //$NON-NLS-1$ // Meta data column table.getTableHeader().getColumnModel().getColumn(5) .setHeaderRenderer(new IconRenderer(BUNDLE.getString("tmm.metadata"))); //$NON-NLS-1$ table.getTableHeader().getColumnModel().getColumn(5).setMaxWidth(20); table.getColumnModel().getColumn(5).setHeaderValue(IconManager.SEARCH); table.getTableHeader().getColumnModel().getColumn(5).setIdentifier("metadata"); //$NON-NLS-1$ // Images column table.getTableHeader().getColumnModel().getColumn(6) .setHeaderRenderer(new IconRenderer(BUNDLE.getString("tmm.images"))); //$NON-NLS-1$ table.getTableHeader().getColumnModel().getColumn(6).setMaxWidth(20); table.getColumnModel().getColumn(6).setHeaderValue(IconManager.IMAGE); table.getTableHeader().getColumnModel().getColumn(6).setIdentifier("images"); //$NON-NLS-1$ // trailer column table.getTableHeader().getColumnModel().getColumn(7) .setHeaderRenderer(new IconRenderer(BUNDLE.getString("tmm.trailer"))); //$NON-NLS-1$ table.getTableHeader().getColumnModel().getColumn(7).setMaxWidth(20); table.getColumnModel().getColumn(7).setHeaderValue(IconManager.CLAPBOARD); table.getTableHeader().getColumnModel().getColumn(7).setIdentifier("trailer"); //$NON-NLS-1$ // subtitles column table.getTableHeader().getColumnModel().getColumn(8) .setHeaderRenderer(new IconRenderer(BUNDLE.getString("tmm.subtitles"))); //$NON-NLS-1$ table.getTableHeader().getColumnModel().getColumn(8).setMaxWidth(20); table.getColumnModel().getColumn(8).setHeaderValue(IconManager.SUBTITLE); table.getTableHeader().getColumnModel().getColumn(8).setIdentifier("subtitle"); //$NON-NLS-1$ // watched column table.getTableHeader().getColumnModel().getColumn(9) .setHeaderRenderer(new IconRenderer(BUNDLE.getString("metatag.watched"))); //$NON-NLS-1$ table.getTableHeader().getColumnModel().getColumn(9).setMaxWidth(20); table.getColumnModel().getColumn(9).setHeaderValue(IconManager.PLAY_SMALL); table.getTableHeader().getColumnModel().getColumn(9).setIdentifier("watched"); //$NON-NLS-1$ table.setSelectionModel(movieSelectionModel.getSelectionModel()); // selecting first movie at startup if (movieList.getMovies() != null && movieList.getMovies().size() > 0) { ListSelectionModel selectionModel = table.getSelectionModel(); if (selectionModel.isSelectionEmpty()) { selectionModel.setSelectionInterval(0, 0); } } // hide columns if needed if (!MovieModuleManager.MOVIE_SETTINGS.isYearColumnVisible()) { table.hideColumn("year"); //$NON-NLS-1$ } if (!MovieModuleManager.MOVIE_SETTINGS.isRatingColumnVisible()) { table.hideColumn("rating"); //$NON-NLS-1$ } if (!MovieModuleManager.MOVIE_SETTINGS.isDateAddedColumnVisible()) { table.hideColumn("dateadded"); //$NON-NLS-1$ } if (!MovieModuleManager.MOVIE_SETTINGS.isNfoColumnVisible()) { table.hideColumn("nfo"); //$NON-NLS-1$ } if (!MovieModuleManager.MOVIE_SETTINGS.isMetadataColumnVisible()) { table.hideColumn("metadata"); //$NON-NLS-1$ } if (!MovieModuleManager.MOVIE_SETTINGS.isImageColumnVisible()) { table.hideColumn("images"); //$NON-NLS-1$ } if (!MovieModuleManager.MOVIE_SETTINGS.isTrailerColumnVisible()) { table.hideColumn("trailer"); //$NON-NLS-1$ } if (!MovieModuleManager.MOVIE_SETTINGS.isSubtitleColumnVisible()) { table.hideColumn("subtitle"); //$NON-NLS-1$ } if (!MovieModuleManager.MOVIE_SETTINGS.isWatchedColumnVisible()) { table.hideColumn("watched"); //$NON-NLS-1$ } // and add a propertychangelistener to the columnhider PropertyChangeListener settingsPropertyChangeListener = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getSource() instanceof MovieSettings) { if ("yearColumnVisible".equals(evt.getPropertyName())) { setColumnVisibility("year", (Boolean) evt.getNewValue()); //$NON-NLS-1$ } if ("ratingColumnVisible".equals(evt.getPropertyName())) { setColumnVisibility("rating", (Boolean) evt.getNewValue()); //$NON-NLS-1$ } if ("nfoColumnVisible".equals(evt.getPropertyName())) { setColumnVisibility("nfo", (Boolean) evt.getNewValue()); } if ("metadataColumnVisible".equals(evt.getPropertyName())) { setColumnVisibility("metadata", (Boolean) evt.getNewValue()); } if ("dateAddedColumnVisible".equals(evt.getPropertyName())) { setColumnVisibility("dateadded", (Boolean) evt.getNewValue()); } if ("imageColumnVisible".equals(evt.getPropertyName())) { setColumnVisibility("images", (Boolean) evt.getNewValue()); //$NON-NLS-1$ } if ("trailerColumnVisible".equals(evt.getPropertyName())) { setColumnVisibility("trailer", (Boolean) evt.getNewValue()); //$NON-NLS-1$ } if ("subtitleColumnVisible".equals(evt.getPropertyName())) { setColumnVisibility("subtitle", (Boolean) evt.getNewValue()); //$NON-NLS-1$ } if ("watchedColumnVisible".equals(evt.getPropertyName())) { setColumnVisibility("watched", (Boolean) evt.getNewValue()); //$NON-NLS-1$ } } } private void setColumnVisibility(Object identifier, Boolean visible) { if (visible) { table.showColumn(identifier); } else { table.hideColumn(identifier); } } }; MovieModuleManager.MOVIE_SETTINGS.addPropertyChangeListener(settingsPropertyChangeListener); // initialize filteredCount lblMovieCountFiltered.setText(String.valueOf(movieTableModel.getRowCount())); addKeyListener(); }
From source file:pcgui.SetupParametersPanel.java
private void runModel() { //retrieve master configuration ArrayList<ArrayList<Object>> mod = model.getData(); //create a new list and check for dependencies ArrayList<Symbol> list = new ArrayList<Symbol>(); //independent variable list ArrayList<Symbol> ivList = new ArrayList<Symbol>(); //step variable list ArrayList<Symbol> stepList = new ArrayList<Symbol>(); //dependent list ArrayList<Symbol> depList = new ArrayList<Symbol>(); //output tracking ArrayList<Symbol> trackedSymbols = new ArrayList<Symbol>(); Symbol tempSym = null;/*from www. j a va 2 s .c o m*/ //step variable counter to be used for making combinations int stepVarCount = 0; long stepCombinations = 1; TextParser textParser = new TextParser(); compileSuccess = true; for (ArrayList<Object> rowData : mod) { tempSym = paramList.get(mod.indexOf(rowData)); if ("Manual".equals((String) rowData.get(2))) { System.out.println("Found Customized Symbol : " + rowData.get(0)); System.out.println("Value : " + rowData.get(3) + ": type=" + rowData.get(3).getClass()); tempSym.mode = "Manual"; String data = (String) rowData.get(3); //checking dependent variables if (data != null && !data.isEmpty()) { //dependent if (hashTable.containsKey(data)) { tempSym.setDependent(true); depList.add(tempSym); } else { //independents tempSym.setDependent(false); tempSym.set(data); ivList.add(tempSym); } } } else if ("External".equals((String) rowData.get(2))) { System.out.println("Found External Symbol : " + rowData.get(0)); System.out.println("External : " + rowData.get(3) + ": type=" + rowData.get(3).getClass()); if (!(((String) rowData.get(4)).isEmpty())) { tempSym.externalFile = (String) rowData.get(4); tempSym.set(tempSym.externalFile); tempSym.mode = "External"; if (tempSym.externalFile.endsWith(".xls") || tempSym.externalFile.endsWith(".xlsx")) { if (tempSym.excelFileRange.isEmpty()) { // TODO show an error dialog System.err.println("Error user missed excel range arguments"); JOptionPane.showMessageDialog(new JFrame(), "Error user missed excel range arguments"); return; } else { tempSym.excelFileRange = (String) rowData.get(5); //'[Daten_10$B'+(i)+':B'+(5+n)+']' //user has to add quote before the 1st + and after the last + //the data file used should be inside Models/Data folder tempSym.set("Models//Data//" + tempSym.externalFile + "::" + tempSym.excelFileRange); } } else { //for non excel files tempSym.set("Models//Data//" + tempSym.externalFile); } } else { System.err.println("Error user missed excel file"); JOptionPane.showMessageDialog(new JFrame(), "Please enter external file for variable : " + tempSym.name); return; } ivList.add(tempSym); list.add(tempSym); } else if ("Randomized".equals((String) rowData.get(2))) { System.out.println("Found Randomized Symbol : " + rowData.get(0)); System.out.println("Value : " + rowData.get(6)); boolean isValid = textParser.validate((String) rowData.get(6)); if (isValid) { //saving the array declaration parameters if (((String) rowData.get(1)).trim().startsWith("array")) { System.out.println("Found randomized array : " + tempSym.name); //found an array tempSym.isArray = true; List<String> arrayParams = parseArrayParam((String) rowData.get(1)); tempSym.arrayParams = arrayParams; System.out.println("Param list : "); for (Object obj : tempSym.arrayParams) { //check if any of the param is symbol if (hashTable.containsKey((String) obj)) { tempSym.isDependentDimension = true; depList.add(tempSym); break; } System.out.println((String) obj); } //add to independent variable list if none of the dimension is based on variable if (!tempSym.isDependentDimension) { ivList.add(tempSym); } } Distribution dist = textParser.getDistribution((String) rowData.get(6)); if ("Step".equalsIgnoreCase(dist.getDistribution())) { System.err.println("Error: User entered step distribution in Randomized variable"); JOptionPane.showMessageDialog(new JFrame(), "Please enter random distribution only" + " for variable : " + tempSym.name); return; } tempSym.setDistribution(dist); tempSym.mode = "Randomized"; //check dependent variables List<String> distParamList = dist.getParamList(); for (String param : distParamList) { //TODO: if .contains work on Symbol if (hashTable.containsKey(param) && !depList.contains(tempSym)) { tempSym.setDependent(true); depList.add(tempSym); break; } } //generate apache distribution object for independent vars if (!tempSym.isDependent()) { Object apacheDist = generateDistribution(tempSym); tempSym.setApacheDist(apacheDist); if ("StepDistribution".equals(apacheDist.getClass().getSimpleName())) { stepVarCount++; StepDistribution stepDist = (StepDistribution) apacheDist; stepCombinations *= stepDist.getStepCount(); tempSym.isStepDist = true; tempSym.setStepDist(stepDist); stepList.add(tempSym); } else if (!ivList.contains(tempSym) && !tempSym.isDependentDimension) { ivList.add(tempSym); } } list.add(tempSym); } else { System.err.println("Error: User entered unknown distribution for randomized variable"); JOptionPane.showMessageDialog(new JFrame(), "Please enter random distribution only" + " for variable : " + tempSym.name); return; } } else if ("Step".equals((String) rowData.get(2))) { System.out.println("Found Step Symbol : " + rowData.get(0)); System.out.println("Value : " + rowData.get(6)); Distribution dist = textParser.getStepDistribution((String) rowData.get(6)); if (dist == null || !"Step".equalsIgnoreCase(dist.getDistribution())) { System.err.println("Error: User entered unknown distribution for step variable"); JOptionPane.showMessageDialog(new JFrame(), "Please enter random distribution only" + " for variable : " + tempSym.name); return; } boolean isValid = textParser.validateStepDist((String) rowData.get(6)); if (isValid) { //saving the array declaration parameters if (((String) rowData.get(1)).trim().startsWith("array")) { //TODO: if this can work for step arrays System.out.println("Found step array : " + tempSym.name); //found an array tempSym.isArray = true; List<String> arrayParams = parseArrayParam((String) rowData.get(1)); tempSym.arrayParams = arrayParams; System.out.println("Param list : "); for (Object obj : tempSym.arrayParams) { //check if any of the param is symbol if (hashTable.containsKey((String) obj)) { tempSym.isDependentDimension = true; depList.add(tempSym); break; } System.out.println((String) obj); } //add to independent variable list if none of the dimension is based on variable if (!tempSym.isDependentDimension) { ivList.add(tempSym); } } tempSym.setDistribution(dist); tempSym.mode = "Randomized"; //check dependent variables List<String> distParamList = dist.getParamList(); for (String param : distParamList) { if (hashTable.containsKey(param) && !depList.contains(tempSym)) { tempSym.setDependent(true); depList.add(tempSym); break; } } //generate apache distribution object for independent vars if (!tempSym.isDependent()) { Object apacheDist = generateDistribution(tempSym); tempSym.setApacheDist(apacheDist); //dual safe check if ("StepDistribution".equals(apacheDist.getClass().getSimpleName())) { stepVarCount++; StepDistribution stepDist = (StepDistribution) apacheDist; stepCombinations *= stepDist.getStepCount(); tempSym.isStepDist = true; tempSym.setStepDist(stepDist); stepList.add(tempSym); } else if (!ivList.contains(tempSym) && !tempSym.isDependentDimension) { ivList.add(tempSym); } } list.add(tempSym); } else { System.err.println("Error: User entered unknown distribution for randomized variable"); JOptionPane.showMessageDialog(new JFrame(), "Please enter random distribution only" + " for variable : " + tempSym.name); return; } } //add symbol to trackedSymbol list for output tracking if (tempSym != null && rowData.get(7) != null && (boolean) rowData.get(7)) { trackedSymbols.add(tempSym); } } System.out.println("Total step distribution variables =" + stepVarCount); System.out.println("Total step combinations =" + stepCombinations); System.out.println("====STEP VARIABLES===="); for (Symbol sym : stepList) { System.out.println(sym.name); } //resolve dependencies and generate random distributions object //list for an instance of execution HashMap<String, Integer> map = new HashMap<String, Integer>(); for (int i = 0; i < stepList.size(); i++) { map.put(stepList.get(i).name, getSteppingCount(stepList, i)); System.out.println(stepList.get(i).name + " has stepping count =" + map.get(stepList.get(i).name)); } int repeatitions = 0; try { repeatitions = Integer.parseInt(repeatCount.getText()); } catch (NumberFormatException e) { System.err.println("Invalid repeat count"); JOptionPane.showMessageDialog(new JFrame(), "Please enter integer value for repeat count"); return; } //generate instances showProgressBar(); final long totalIterations = repeatitions * stepCombinations; final long repeatitionsFinal = repeatitions; final long combinations = stepCombinations; SwingWorker<Void, Void> executionTask = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { long itNum = 1; int itCount = 1; System.out.println("Total iterations: " + totalIterations); // TODO Auto-generated method stub for (int c = 1; c <= repeatitionsFinal; c++) { for (int i = 1; i <= combinations; i++) { setProgress((int) (itNum * 100 / totalIterations)); //step variables first for (Symbol sym : stepList) { if (map.get(sym.name) == 1 || i % map.get(sym.name) - 1 == 0 || i == 1) { sym.set(sym.getStepDist().sample()); hashTable.put(sym.name, sym); } //System.out.println(sym.name+" = "+sym.get()); } //independent randomized variables for (Symbol sym : ivList) { if (sym.mode.equals("Randomized")) { Object distObj = sym.getApacheDist(); switch (sym.getApacheDist().getClass().getSimpleName()) { case "UniformIntegerDistribution": //case "GeometricDistribution" : // case "BinomialDistribution"://not implemented yet IntegerDistribution intDist = (IntegerDistribution) distObj; if (sym.isArray) { //generate Stringified array String val = generateIndependentArray(sym, intDist); sym.set(val); hashTable.put(sym.name, sym); } break; case "LogisticDistribution": case "UniformRealDistribution": case "ExponentialDistribution": case "GammaDistribution": case "NormalDistribution": RealDistribution realDist = (RealDistribution) distObj; if (sym.isArray) { //generate Stringified array String val = generateIndependentArray(sym, realDist); sym.set(val); hashTable.put(sym.name, sym); } break; default: System.err.println("Unknown distribution"); JOptionPane.showMessageDialog(new JFrame(), "Error occurred : Unknown distribution"); return null; } } //System.out.println(sym.name+" = "+sym.get()); //other types of independent variable already have values } for (Symbol sym : depList) { if (sym.mode != null && "Manual".equals(sym.mode)) { //value depends on some other value String ref = (String) sym.get(); Object val = (Object) hashTable.get(ref); sym.set(val); hashTable.put(sym.name, sym); } else if (sym.mode != null && "Randomized".equals(sym.mode)) { Object distObj = null; //when a random distribution depends on another variable Distribution dist = sym.getDistribution(); StringBuilder sb = new StringBuilder(); sb.append(dist.getDistribution()); sb.append("("); for (String s : dist.getParamList()) { //replacing a dependency by actual value of that variable if (hashTable.containsKey(s)) { Symbol val = (Symbol) hashTable.get(s); sb.append((String) val.get()); } else { //this param is a number itself sb.append(s); } sb.append(","); } //check if param list length = 0 if (dist.getParamList() != null && dist.getParamList().size() >= 1) { sb.deleteCharAt(sb.length() - 1); } sb.append(")"); if (sym.typeString != null && sym.typeString.contains("integer")) { try { distObj = textParser.parseText(sb.toString(), TextParser.INTEGER); sym.setApacheDist(distObj); } catch (Exception e) { System.err.println( "Exception occured when trying to get Random distribution for variable" + sym.name + "\n" + e.getMessage()); e.printStackTrace(); JOptionPane.showMessageDialog(new JFrame(), "Error occurred : " + e.getMessage()); return null; } } else { try { distObj = textParser.parseText(sb.toString(), TextParser.REAL); sym.setApacheDist(distObj); } catch (Exception e) { System.err.println( "Exception occured when trying to get Random distribution for variable" + sym.name + "\n" + e.getMessage()); e.printStackTrace(); JOptionPane.showMessageDialog(new JFrame(), "Error occurred : " + e.getMessage()); return null; } } //generation of actual apache distribution objects switch (distObj.getClass().getSimpleName()) { case "UniformIntegerDistribution": //case "GeometricDistribution" : //case "BinomialDistribution": IntegerDistribution intDist = (IntegerDistribution) distObj; if (sym.isArray) { //generate Stringified array String val = generateDependentArray(sym, intDist); sym.set(val); hashTable.put(sym.name, sym); } break; case "LogisticDistribution": case "UniformRealDistribution": case "ExponentialDistribution": case "GammaDistribution": case "NormalDistribution": RealDistribution realDist = (RealDistribution) distObj; if (sym.isArray) { //generate Stringified array String val = generateDependentArray(sym, realDist); sym.set(val); hashTable.put(sym.name, sym); } break; default: System.err.println("Unknown distribution"); JOptionPane.showMessageDialog(new JFrame(), "Error occurred : Unknown distribution"); } } //System.out.println(sym.name+" = "+sym.get()); } ArrayList<Symbol> instanceList = new ArrayList<Symbol>(); instanceList.addAll(stepList); instanceList.addAll(ivList); instanceList.addAll(depList); System.out.println("=======ITERATION " + itCount++ + "======="); System.out.println("=======instanceList.size =" + instanceList.size() + " ======="); for (Symbol sym : instanceList) { System.out.println(sym.name + " = " + sym.get()); } //runModel here try { //TODO anshul: pass output variables to be written to excel System.out.println("Tracked output symbols"); for (Symbol sym : trackedSymbols) { System.out.println(sym.name); } HashMap<String, OutputParams> l = parser.changeModel(instanceList, trackedSymbols, itNum); if (l == null) { compileSuccess = false; break; } } catch (/*XPRMCompileException | */XPRMLicenseError | IOException e) { e.printStackTrace(); JOptionPane.showMessageDialog(new JFrame(), "Error occurred : " + e.getMessage()); compileSuccess = false; break; } itNum++; } } this.notifyAll(); done(); return null; } @Override protected void done() { super.done(); //check if compilation was successful if (compileSuccess) { ModelSaver.saveModelResult(); visPanel.setTrackedVariables(trackedSymbols); mapVisPanel.setTrackedVariables(trackedSymbols); JOptionPane.showMessageDialog(new JFrame("Success"), "Model execution completed.\nOutput written to excel file : " + outputFile); } else { //Error popup should have been shown by ModelParser System.err.println("There was an error while running the model."); return; } if (progressFrame != null) { progressFrame.dispose(); } } }; executionTask.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if ("progress" == evt.getPropertyName()) { int progress = (Integer) evt.getNewValue(); if (pbar != null) pbar.setValue(progress); if (taskOutput != null) taskOutput.append(String.format("Completed %d%% of task.\n", executionTask.getProgress())); } } }); executionTask.execute(); }
From source file:org.micromanager.asidispim.AcquisitionPanel.java
public AcquisitionPanel(ScriptInterface gui, Devices devices, Properties props, Cameras cameras, Prefs prefs, StagePositionUpdater posUpdater, Positions positions, ControllerUtils controller, AutofocusUtils autofocus) {/*from w w w. j a v a 2s .co m*/ super(MyStrings.PanelNames.ACQUSITION.toString(), new MigLayout("", "[center]0[center]0[center]", "0[top]0")); gui_ = gui; devices_ = devices; props_ = props; cameras_ = cameras; prefs_ = prefs; posUpdater_ = posUpdater; positions_ = positions; controller_ = controller; autofocus_ = autofocus; core_ = gui_.getMMCore(); numTimePointsDone_ = 0; sliceTiming_ = new SliceTiming(); lastAcquisitionPath_ = ""; lastAcquisitionName_ = ""; acq_ = null; channelNames_ = null; resetXaxisSpeed_ = true; acquisitionPanel_ = this; PanelUtils pu = new PanelUtils(prefs_, props_, devices_); // added to spinner controls where we should re-calculate the displayed // slice period, volume duration, and time lapse duration ChangeListener recalculateTimingDisplayCL = new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if (advancedSliceTimingCB_.isSelected()) { // need to update sliceTiming_ from property values sliceTiming_ = getTimingFromAdvancedSettings(); } updateDurationLabels(); } }; // added to combobox controls where we should re-calculate the displayed // slice period, volume duration, and time lapse duration ActionListener recalculateTimingDisplayAL = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateDurationLabels(); } }; // start volume sub-panel volPanel_ = new JPanel(new MigLayout("", "[right]10[center]", "4[]8[]")); volPanel_.setBorder(PanelUtils.makeTitledBorder("Volume Settings")); if (!ASIdiSPIM.oSPIM) { } else { props_.setPropValue(Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_NUM_SIDES, "1"); } volPanel_.add(new JLabel("Number of sides:")); String[] str12 = { "1", "2" }; numSides_ = pu.makeDropDownBox(str12, Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_NUM_SIDES, str12[1]); numSides_.addActionListener(recalculateTimingDisplayAL); if (!ASIdiSPIM.oSPIM) { } else { numSides_.setEnabled(false); } volPanel_.add(numSides_, "wrap"); volPanel_.add(new JLabel("First side:")); String[] ab = { Devices.Sides.A.toString(), Devices.Sides.B.toString() }; if (!ASIdiSPIM.oSPIM) { } else { props_.setPropValue(Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_FIRST_SIDE, Devices.Sides.A.toString()); } firstSide_ = pu.makeDropDownBox(ab, Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_FIRST_SIDE, Devices.Sides.A.toString()); firstSide_.addActionListener(recalculateTimingDisplayAL); if (!ASIdiSPIM.oSPIM) { } else { firstSide_.setEnabled(false); } volPanel_.add(firstSide_, "wrap"); volPanel_.add(new JLabel("Delay before side [ms]:")); // used to read/write directly to galvo/micro-mirror firmware, but want different stage scan behavior delaySide_ = pu.makeSpinnerFloat(0, 10000, 0.25, Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_DELAY_BEFORE_SIDE, 50); pu.addListenerLast(delaySide_, recalculateTimingDisplayCL); volPanel_.add(delaySide_, "wrap"); volPanel_.add(new JLabel("Slices per side:")); numSlices_ = pu.makeSpinnerInteger(1, 65000, Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_NUM_SLICES, 20); pu.addListenerLast(numSlices_, recalculateTimingDisplayCL); volPanel_.add(numSlices_, "wrap"); volPanel_.add(new JLabel("Slice step size [\u00B5m]:")); stepSize_ = pu.makeSpinnerFloat(0, 100, 0.1, Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_SLICE_STEP_SIZE, 1.0); pu.addListenerLast(stepSize_, recalculateTimingDisplayCL); // needed only for stage scanning b/c acceleration time related to speed volPanel_.add(stepSize_, "wrap"); // end volume sub-panel // start slice timing controls, have 2 options with advanced timing checkbox shared slicePanel_ = new JPanel(new MigLayout("", "[right]10[center]", "0[]0[]")); slicePanel_.setBorder(PanelUtils.makeTitledBorder("Slice Settings")); // start light sheet controls lightSheetPanel_ = new JPanel(new MigLayout("", "[right]10[center]", "4[]8")); lightSheetPanel_.add(new JLabel("Scan reset time [ms]:")); JSpinner lsScanReset = pu.makeSpinnerFloat(1, 100, 0.25, // practical lower limit of 1ms Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_LS_SCAN_RESET, 3); lsScanReset.addChangeListener(PanelUtils.coerceToQuarterIntegers(lsScanReset)); pu.addListenerLast(lsScanReset, recalculateTimingDisplayCL); lightSheetPanel_.add(lsScanReset, "wrap"); lightSheetPanel_.add(new JLabel("Scan settle time [ms]:")); JSpinner lsScanSettle = pu.makeSpinnerFloat(0.25, 100, 0.25, Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_LS_SCAN_SETTLE, 1); lsScanSettle.addChangeListener(PanelUtils.coerceToQuarterIntegers(lsScanSettle)); pu.addListenerLast(lsScanSettle, recalculateTimingDisplayCL); lightSheetPanel_.add(lsScanSettle, "wrap"); lightSheetPanel_.add(new JLabel("Shutter width [\u00B5m]:")); JSpinner lsShutterWidth = pu.makeSpinnerFloat(0.1, 100, 1, Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_LS_SHUTTER_WIDTH, 5); pu.addListenerLast(lsShutterWidth, recalculateTimingDisplayCL); lightSheetPanel_.add(lsShutterWidth); // lightSheetPanel_.add(new JLabel("1 / (shutter speed):")); // JSpinner lsShutterSpeed = pu.makeSpinnerInteger(1, 10, // Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_LS_SHUTTER_SPEED, 1); // lightSheetPanel_.add(lsShutterSpeed, "wrap"); // end light sheet controls // start "normal" (not light sheet) controls normalPanel_ = new JPanel(new MigLayout("", "[right]10[center]", "4[]8")); // out of order so we can reference it desiredSlicePeriod_ = pu.makeSpinnerFloat(1, 1000, 0.25, Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_DESIRED_SLICE_PERIOD, 30); minSlicePeriodCB_ = pu.makeCheckBox("Minimize slice period", Properties.Keys.PREFS_MINIMIZE_SLICE_PERIOD, panelName_, false); minSlicePeriodCB_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { boolean doMin = minSlicePeriodCB_.isSelected(); desiredSlicePeriod_.setEnabled(!doMin); desiredSlicePeriodLabel_.setEnabled(!doMin); recalculateSliceTiming(false); } }); normalPanel_.add(minSlicePeriodCB_, "span 2, wrap"); // special field that is enabled/disabled depending on whether advanced timing is enabled desiredSlicePeriodLabel_ = new JLabel("Slice period [ms]:"); normalPanel_.add(desiredSlicePeriodLabel_); normalPanel_.add(desiredSlicePeriod_, "wrap"); desiredSlicePeriod_.addChangeListener(PanelUtils.coerceToQuarterIntegers(desiredSlicePeriod_)); desiredSlicePeriod_.addChangeListener(recalculateTimingDisplayCL); // special field that is enabled/disabled depending on whether advanced timing is enabled desiredLightExposureLabel_ = new JLabel("Sample exposure [ms]:"); normalPanel_.add(desiredLightExposureLabel_); desiredLightExposure_ = pu.makeSpinnerFloat(1.0, 1000, 0.25, Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_DESIRED_EXPOSURE, 8.5); desiredLightExposure_.addChangeListener(PanelUtils.coerceToQuarterIntegers(desiredLightExposure_)); desiredLightExposure_.addChangeListener(recalculateTimingDisplayCL); normalPanel_.add(desiredLightExposure_); // end normal simple slice timing controls slicePanelContainer_ = new JPanel(new MigLayout("", "0[center]0", "0[]0")); slicePanelContainer_.add( getSPIMCameraMode() == CameraModes.Keys.LIGHT_SHEET ? lightSheetPanel_ : normalPanel_, "growx"); slicePanel_.add(slicePanelContainer_, "span 2, center, wrap"); // special checkbox to use the advanced timing settings // action handler added below after defining components it enables/disables advancedSliceTimingCB_ = pu.makeCheckBox("Use advanced timing settings", Properties.Keys.PREFS_ADVANCED_SLICE_TIMING, panelName_, false); slicePanel_.add(advancedSliceTimingCB_, "span 2, left"); // end slice sub-panel // start advanced slice timing frame // visibility of this frame is controlled from advancedTiming checkbox // this frame is separate from main plugin window sliceFrameAdvanced_ = new MMFrame(); sliceFrameAdvanced_.setTitle("Advanced timing"); sliceFrameAdvanced_.loadPosition(100, 100); sliceAdvancedPanel_ = new JPanel(new MigLayout("", "[right]10[center]", "[]8[]")); sliceFrameAdvanced_.add(sliceAdvancedPanel_); class SliceFrameAdapter extends WindowAdapter { @Override public void windowClosing(WindowEvent e) { advancedSliceTimingCB_.setSelected(false); sliceFrameAdvanced_.savePosition(); } } sliceFrameAdvanced_.addWindowListener(new SliceFrameAdapter()); JLabel scanDelayLabel = new JLabel("Delay before scan [ms]:"); sliceAdvancedPanel_.add(scanDelayLabel); delayScan_ = pu.makeSpinnerFloat(0, 10000, 0.25, new Devices.Keys[] { Devices.Keys.GALVOA, Devices.Keys.GALVOB }, Properties.Keys.SPIM_DELAY_SCAN, 0); delayScan_.addChangeListener(PanelUtils.coerceToQuarterIntegers(delayScan_)); delayScan_.addChangeListener(recalculateTimingDisplayCL); sliceAdvancedPanel_.add(delayScan_, "wrap"); JLabel lineScanLabel = new JLabel("Lines scans per slice:"); sliceAdvancedPanel_.add(lineScanLabel); numScansPerSlice_ = pu.makeSpinnerInteger(1, 1000, new Devices.Keys[] { Devices.Keys.GALVOA, Devices.Keys.GALVOB }, Properties.Keys.SPIM_NUM_SCANSPERSLICE, 1); numScansPerSlice_.addChangeListener(recalculateTimingDisplayCL); sliceAdvancedPanel_.add(numScansPerSlice_, "wrap"); JLabel lineScanPeriodLabel = new JLabel("Line scan duration [ms]:"); sliceAdvancedPanel_.add(lineScanPeriodLabel); lineScanDuration_ = pu.makeSpinnerFloat(1, 10000, 0.25, new Devices.Keys[] { Devices.Keys.GALVOA, Devices.Keys.GALVOB }, Properties.Keys.SPIM_DURATION_SCAN, 10); lineScanDuration_.addChangeListener(PanelUtils.coerceToQuarterIntegers(lineScanDuration_)); lineScanDuration_.addChangeListener(recalculateTimingDisplayCL); sliceAdvancedPanel_.add(lineScanDuration_, "wrap"); JLabel delayLaserLabel = new JLabel("Delay before laser [ms]:"); sliceAdvancedPanel_.add(delayLaserLabel); delayLaser_ = pu.makeSpinnerFloat(0, 10000, 0.25, new Devices.Keys[] { Devices.Keys.GALVOA, Devices.Keys.GALVOB }, Properties.Keys.SPIM_DELAY_LASER, 0); delayLaser_.addChangeListener(PanelUtils.coerceToQuarterIntegers(delayLaser_)); delayLaser_.addChangeListener(recalculateTimingDisplayCL); sliceAdvancedPanel_.add(delayLaser_, "wrap"); JLabel durationLabel = new JLabel("Laser trig duration [ms]:"); sliceAdvancedPanel_.add(durationLabel); durationLaser_ = pu.makeSpinnerFloat(0, 10000, 0.25, new Devices.Keys[] { Devices.Keys.GALVOA, Devices.Keys.GALVOB }, Properties.Keys.SPIM_DURATION_LASER, 1); durationLaser_.addChangeListener(PanelUtils.coerceToQuarterIntegers(durationLaser_)); durationLaser_.addChangeListener(recalculateTimingDisplayCL); sliceAdvancedPanel_.add(durationLaser_, "span 2, wrap"); JLabel delayLabel = new JLabel("Delay before camera [ms]:"); sliceAdvancedPanel_.add(delayLabel); delayCamera_ = pu.makeSpinnerFloat(0, 10000, 0.25, new Devices.Keys[] { Devices.Keys.GALVOA, Devices.Keys.GALVOB }, Properties.Keys.SPIM_DELAY_CAMERA, 0); delayCamera_.addChangeListener(PanelUtils.coerceToQuarterIntegers(delayCamera_)); delayCamera_.addChangeListener(recalculateTimingDisplayCL); sliceAdvancedPanel_.add(delayCamera_, "wrap"); JLabel cameraLabel = new JLabel("Camera trig duration [ms]:"); sliceAdvancedPanel_.add(cameraLabel); durationCamera_ = pu.makeSpinnerFloat(0, 1000, 0.25, new Devices.Keys[] { Devices.Keys.GALVOA, Devices.Keys.GALVOB }, Properties.Keys.SPIM_DURATION_CAMERA, 0); durationCamera_.addChangeListener(PanelUtils.coerceToQuarterIntegers(durationCamera_)); durationCamera_.addChangeListener(recalculateTimingDisplayCL); sliceAdvancedPanel_.add(durationCamera_, "wrap"); JLabel exposureLabel = new JLabel("Camera exposure [ms]:"); sliceAdvancedPanel_.add(exposureLabel); exposureCamera_ = pu.makeSpinnerFloat(0, 1000, 0.25, Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_ADVANCED_CAMERA_EXPOSURE, 10f); exposureCamera_.addChangeListener(recalculateTimingDisplayCL); sliceAdvancedPanel_.add(exposureCamera_, "wrap"); alternateBeamScanCB_ = pu.makeCheckBox("Alternate scan direction", Properties.Keys.PREFS_SCAN_OPPOSITE_DIRECTIONS, panelName_, false); sliceAdvancedPanel_.add(alternateBeamScanCB_, "center, span 2, wrap"); simpleTimingComponents_ = new JComponent[] { desiredLightExposure_, minSlicePeriodCB_, desiredSlicePeriodLabel_, desiredLightExposureLabel_ }; final JComponent[] advancedTimingComponents = { delayScan_, numScansPerSlice_, lineScanDuration_, delayLaser_, durationLaser_, delayCamera_, durationCamera_, exposureCamera_, alternateBeamScanCB_ }; PanelUtils.componentsSetEnabled(advancedTimingComponents, advancedSliceTimingCB_.isSelected()); PanelUtils.componentsSetEnabled(simpleTimingComponents_, !advancedSliceTimingCB_.isSelected()); // this action listener takes care of enabling/disabling inputs // of the advanced slice timing window // we call this to get GUI looking right ItemListener sliceTimingDisableGUIInputs = new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { boolean enabled = advancedSliceTimingCB_.isSelected(); // set other components in this advanced timing frame PanelUtils.componentsSetEnabled(advancedTimingComponents, enabled); // also control some components in main volume settings sub-panel PanelUtils.componentsSetEnabled(simpleTimingComponents_, !enabled); desiredSlicePeriod_.setEnabled(!enabled && !minSlicePeriodCB_.isSelected()); desiredSlicePeriodLabel_.setEnabled(!enabled && !minSlicePeriodCB_.isSelected()); updateDurationLabels(); } }; // this action listener shows/hides the advanced timing frame ActionListener showAdvancedTimingFrame = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { boolean enabled = advancedSliceTimingCB_.isSelected(); if (enabled) { sliceFrameAdvanced_.setVisible(enabled); } } }; sliceFrameAdvanced_.pack(); sliceFrameAdvanced_.setResizable(false); // end slice Frame // start repeat (time lapse) sub-panel timepointPanel_ = new JPanel(new MigLayout("", "[right]10[center]", "[]8[]")); useTimepointsCB_ = pu.makeCheckBox("Time points", Properties.Keys.PREFS_USE_TIMEPOINTS, panelName_, false); useTimepointsCB_.setToolTipText("Perform a time-lapse acquisition"); useTimepointsCB_.setEnabled(true); useTimepointsCB_.setFocusPainted(false); ComponentTitledBorder componentBorder = new ComponentTitledBorder(useTimepointsCB_, timepointPanel_, BorderFactory.createLineBorder(ASIdiSPIM.borderColor)); timepointPanel_.setBorder(componentBorder); ChangeListener recalculateTimeLapseDisplay = new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { updateActualTimeLapseDurationLabel(); } }; useTimepointsCB_.addChangeListener(recalculateTimeLapseDisplay); timepointPanel_.add(new JLabel("Number:")); numTimepoints_ = pu.makeSpinnerInteger(1, 100000, Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_NUM_ACQUISITIONS, 1); numTimepoints_.addChangeListener(recalculateTimeLapseDisplay); numTimepoints_.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent arg0) { // update nrRepeats_ variable so the acquisition can be extended or shortened // as long as we have separate timepoints if (acquisitionRunning_.get() && getSavingSeparateFile()) { nrRepeats_ = getNumTimepoints(); } } }); timepointPanel_.add(numTimepoints_, "wrap"); timepointPanel_.add(new JLabel("Interval [s]:")); acquisitionInterval_ = pu.makeSpinnerFloat(0.1, 32000, 0.1, Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_ACQUISITION_INTERVAL, 60); acquisitionInterval_.addChangeListener(recalculateTimeLapseDisplay); timepointPanel_.add(acquisitionInterval_, "wrap"); // enable/disable panel elements depending on checkbox state useTimepointsCB_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { PanelUtils.componentsSetEnabled(timepointPanel_, useTimepointsCB_.isSelected()); } }); PanelUtils.componentsSetEnabled(timepointPanel_, useTimepointsCB_.isSelected()); // initialize // end repeat sub-panel // start savePanel // TODO for now these settings aren't part of acquisition settings // TODO consider whether that should be changed final int textFieldWidth = 16; savePanel_ = new JPanel(new MigLayout("", "[right]10[center]8[left]", "[]4[]")); savePanel_.setBorder(PanelUtils.makeTitledBorder("Data Saving Settings")); separateTimePointsCB_ = pu.makeCheckBox("Separate viewer / file for each time point", Properties.Keys.PREFS_SEPARATE_VIEWERS_FOR_TIMEPOINTS, panelName_, false); saveCB_ = pu.makeCheckBox("Save while acquiring", Properties.Keys.PREFS_SAVE_WHILE_ACQUIRING, panelName_, false); // make sure that when separate viewer is enabled then saving gets enabled too separateTimePointsCB_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (separateTimePointsCB_.isSelected() && !saveCB_.isSelected()) { saveCB_.doClick(); // setSelected() won't work because need to call its listener } } }); savePanel_.add(separateTimePointsCB_, "span 3, left, wrap"); savePanel_.add(saveCB_, "skip 1, span 2, center, wrap"); JLabel dirRootLabel = new JLabel("Directory root:"); savePanel_.add(dirRootLabel); DefaultFormatter formatter = new DefaultFormatter(); formatter.setOverwriteMode(false); rootField_ = new JFormattedTextField(formatter); rootField_.setText(prefs_.getString(panelName_, Properties.Keys.PLUGIN_DIRECTORY_ROOT, "")); rootField_.addPropertyChangeListener(new PropertyChangeListener() { // will respond to commitEdit() as well as GUI edit on commit @Override public void propertyChange(PropertyChangeEvent evt) { prefs_.putString(panelName_, Properties.Keys.PLUGIN_DIRECTORY_ROOT, rootField_.getText()); } }); rootField_.setColumns(textFieldWidth); savePanel_.add(rootField_, "span 2"); JButton browseRootButton = new JButton(); browseRootButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { setRootDirectory(rootField_); prefs_.putString(panelName_, Properties.Keys.PLUGIN_DIRECTORY_ROOT, rootField_.getText()); } }); browseRootButton.setMargin(new Insets(2, 5, 2, 5)); browseRootButton.setText("..."); savePanel_.add(browseRootButton, "wrap"); JLabel namePrefixLabel = new JLabel(); namePrefixLabel.setText("Name prefix:"); savePanel_.add(namePrefixLabel); prefixField_ = new JFormattedTextField(formatter); prefixField_.setText(prefs_.getString(panelName_, Properties.Keys.PLUGIN_NAME_PREFIX, "acq")); prefixField_.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { prefs_.putString(panelName_, Properties.Keys.PLUGIN_NAME_PREFIX, prefixField_.getText()); } }); prefixField_.setColumns(textFieldWidth); savePanel_.add(prefixField_, "span 2, wrap"); // since we use the name field even for acquisitions in RAM, // we only need to gray out the directory-related components final JComponent[] saveComponents = { browseRootButton, rootField_, dirRootLabel }; PanelUtils.componentsSetEnabled(saveComponents, saveCB_.isSelected()); saveCB_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { PanelUtils.componentsSetEnabled(saveComponents, saveCB_.isSelected()); } }); // end save panel // start duration report panel durationPanel_ = new JPanel(new MigLayout("", "[right]6[left, 40%!]", "[]5[]")); durationPanel_.setBorder(PanelUtils.makeTitledBorder("Durations")); durationPanel_.setPreferredSize(new Dimension(125, 0)); // fix width so it doesn't constantly change depending on text durationPanel_.add(new JLabel("Slice:")); actualSlicePeriodLabel_ = new JLabel(); durationPanel_.add(actualSlicePeriodLabel_, "wrap"); durationPanel_.add(new JLabel("Volume:")); actualVolumeDurationLabel_ = new JLabel(); durationPanel_.add(actualVolumeDurationLabel_, "wrap"); durationPanel_.add(new JLabel("Total:")); actualTimeLapseDurationLabel_ = new JLabel(); durationPanel_.add(actualTimeLapseDurationLabel_, "wrap"); // end duration report panel buttonTestAcq_ = new JButton("Test Acquisition"); buttonTestAcq_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { runTestAcquisition(Devices.Sides.NONE); } }); buttonStart_ = new JToggleButton(); buttonStart_.setIconTextGap(6); buttonStart_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (isAcquisitionRequested()) { stopAcquisition(); } else { runAcquisition(); } } }); updateStartButton(); // call once to initialize, isSelected() will be false // make the size of the test button match the start button (easier on the eye) Dimension sizeStart = buttonStart_.getPreferredSize(); Dimension sizeTest = buttonTestAcq_.getPreferredSize(); sizeTest.height = sizeStart.height; buttonTestAcq_.setPreferredSize(sizeTest); acquisitionStatusLabel_ = new JLabel(""); acquisitionStatusLabel_.setBackground(prefixField_.getBackground()); acquisitionStatusLabel_.setOpaque(true); updateAcquisitionStatus(AcquisitionStatus.NONE); // Channel Panel (separate file for code) multiChannelPanel_ = new MultiChannelSubPanel(gui, devices_, props_, prefs_); multiChannelPanel_.addDurationLabelListener(this); // Position Panel final JPanel positionPanel = new JPanel(); positionPanel.setLayout(new MigLayout("flowx, fillx", "[right]10[left][10][]", "[]8[]")); usePositionsCB_ = pu.makeCheckBox("Multiple positions (XY)", Properties.Keys.PREFS_USE_MULTIPOSITION, panelName_, false); usePositionsCB_.setToolTipText("Acquire datasest at multiple postions"); usePositionsCB_.setEnabled(true); usePositionsCB_.setFocusPainted(false); componentBorder = new ComponentTitledBorder(usePositionsCB_, positionPanel, BorderFactory.createLineBorder(ASIdiSPIM.borderColor)); positionPanel.setBorder(componentBorder); usePositionsCB_.addChangeListener(recalculateTimingDisplayCL); final JButton editPositionListButton = new JButton("Edit position list..."); editPositionListButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { gui_.showXYPositionList(); } }); positionPanel.add(editPositionListButton); gridButton_ = new JButton("XYZ grid..."); positionPanel.add(gridButton_, "wrap"); // start XYZ grid frame // visibility of this frame is controlled from XYZ grid button // this frame is separate from main plugin window gridXPanel_ = new JPanel(new MigLayout("", "[right]10[center]", "[]8[]")); useXGridCB_ = pu.makeCheckBox("Slices from stage coordinates", Properties.Keys.PREFS_USE_X_GRID, panelName_, true); useXGridCB_.setEnabled(true); useXGridCB_.setFocusPainted(false); componentBorder = new ComponentTitledBorder(useXGridCB_, gridXPanel_, BorderFactory.createLineBorder(ASIdiSPIM.borderColor)); gridXPanel_.setBorder(componentBorder); // enable/disable panel elements depending on checkbox state useXGridCB_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { PanelUtils.componentsSetEnabled(gridXPanel_, useXGridCB_.isSelected()); } }); gridXPanel_.add(new JLabel("X start [um]:")); gridXStartField_ = pu.makeFloatEntryField(panelName_, "Grid_X_Start", -400, 5); gridXStartField_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { updateGridXCount(); } }); gridXPanel_.add(gridXStartField_); JButton tmp_but = new JButton("Set"); tmp_but.setBackground(Color.red); tmp_but.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { gridXStartField_.setValue(positions_.getUpdatedPosition(Devices.Keys.XYSTAGE, Directions.X)); updateGridXCount(); } }); gridXPanel_.add(tmp_but, "wrap"); gridXPanel_.add(new JLabel("X stop [um]:")); gridXStopField_ = pu.makeFloatEntryField(panelName_, "Grid_X_Stop", 400, 5); gridXStopField_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { updateGridXCount(); } }); gridXPanel_.add(gridXStopField_); tmp_but = new JButton("Set"); tmp_but.setBackground(Color.red); tmp_but.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { gridXStopField_.setValue(positions_.getUpdatedPosition(Devices.Keys.XYSTAGE, Directions.X)); updateGridXCount(); } }); gridXPanel_.add(tmp_but, "wrap"); gridXPanel_.add(new JLabel("X delta [um]:")); gridXDeltaField_ = pu.makeFloatEntryField(panelName_, "Grid_X_Delta", 3, 5); gridXDeltaField_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { updateGridXCount(); } }); gridXPanel_.add(gridXDeltaField_, "wrap"); // tmp_but = new JButton("Set"); // tmp_but.setBackground(Color.red); // tmp_but.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent arg0) { // // TODO figure out spacing, maybe to make reslicing trivial // updateGridXCount(); // } // }); // gridPanel_.add(tmp_but, "wrap"); gridXPanel_.add(new JLabel("Slice count:")); gridXCount_ = new JLabel(""); gridXPanel_.add(gridXCount_, "wrap"); updateGridXCount(); PanelUtils.componentsSetEnabled(gridXPanel_, useXGridCB_.isSelected()); // initialize gridYPanel_ = new JPanel(new MigLayout("", "[right]10[center]", "[]8[]")); useYGridCB_ = pu.makeCheckBox("Grid in Y", Properties.Keys.PREFS_USE_Y_GRID, panelName_, true); useYGridCB_.setEnabled(true); useYGridCB_.setFocusPainted(false); componentBorder = new ComponentTitledBorder(useYGridCB_, gridYPanel_, BorderFactory.createLineBorder(ASIdiSPIM.borderColor)); gridYPanel_.setBorder(componentBorder); // enable/disable panel elements depending on checkbox state useYGridCB_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { PanelUtils.componentsSetEnabled(gridYPanel_, useYGridCB_.isSelected()); } }); gridYPanel_.add(new JLabel("Y start [um]:")); gridYStartField_ = pu.makeFloatEntryField(panelName_, "Grid_Y_Start", -1200, 5); gridYStartField_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { updateGridYCount(); } }); gridYPanel_.add(gridYStartField_); tmp_but = new JButton("Set"); tmp_but.setBackground(Color.red); tmp_but.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { gridYStartField_.setValue(positions_.getUpdatedPosition(Devices.Keys.XYSTAGE, Directions.Y)); updateGridYCount(); } }); gridYPanel_.add(tmp_but, "wrap"); gridYPanel_.add(new JLabel("Y stop [um]:")); gridYStopField_ = pu.makeFloatEntryField(panelName_, "Grid_Y_Stop", 1200, 5); gridYStopField_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { updateGridYCount(); } }); gridYPanel_.add(gridYStopField_); tmp_but = new JButton("Set"); tmp_but.setBackground(Color.red); tmp_but.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { gridYStopField_.setValue(positions_.getUpdatedPosition(Devices.Keys.XYSTAGE, Directions.Y)); updateGridYCount(); } }); gridYPanel_.add(tmp_but, "wrap"); gridYPanel_.add(new JLabel("Y delta [um]:")); gridYDeltaField_ = pu.makeFloatEntryField(panelName_, "Grid_Y_Delta", 700, 5); gridYDeltaField_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { updateGridYCount(); } }); gridYPanel_.add(gridYDeltaField_); tmp_but = new JButton("Set"); tmp_but.setBackground(Color.red); tmp_but.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { Devices.Keys camKey = isFirstSideA() ? Devices.Keys.CAMERAA : Devices.Keys.CAMERAB; int height; try { height = core_.getROI(devices_.getMMDevice(camKey)).height; } catch (Exception e) { height = 1; } float pixelSize = (float) core_.getPixelSizeUm(); double delta = height * pixelSize; double overlap = props_.getPropValueFloat(Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_GRID_OVERLAP_PERCENT); delta *= (1 - overlap / 100); // sanity checks, would be better handled with exceptions or more formal checks if (height > 4100 || height < 4 || pixelSize < 1e-6) { return; } gridYDeltaField_.setValue(Math.round(delta)); updateGridYCount(); } }); gridYPanel_.add(tmp_but, "wrap"); gridYPanel_.add(new JLabel("Y count:")); gridYCount_ = new JLabel(""); gridYPanel_.add(gridYCount_, "wrap"); updateGridYCount(); PanelUtils.componentsSetEnabled(gridYPanel_, useYGridCB_.isSelected()); // initialize gridZPanel_ = new JPanel(new MigLayout("", "[right]10[center]", "[]8[]")); useZGridCB_ = pu.makeCheckBox("Grid in Z", Properties.Keys.PREFS_USE_Z_GRID, panelName_, true); useZGridCB_.setEnabled(true); useZGridCB_.setFocusPainted(false); componentBorder = new ComponentTitledBorder(useZGridCB_, gridZPanel_, BorderFactory.createLineBorder(ASIdiSPIM.borderColor)); gridZPanel_.setBorder(componentBorder); // enable/disable panel elements depending on checkbox state useZGridCB_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { PanelUtils.componentsSetEnabled(gridZPanel_, useZGridCB_.isSelected()); } }); gridZPanel_.add(new JLabel("Z start [um]:")); gridZStartField_ = pu.makeFloatEntryField(panelName_, "Grid_Z_Start", 0, 5); gridZStartField_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { updateGridZCount(); } }); gridZPanel_.add(gridZStartField_); tmp_but = new JButton("Set"); tmp_but.setBackground(Color.red); tmp_but.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { gridZStartField_.setValue(positions_.getUpdatedPosition(Devices.Keys.UPPERZDRIVE)); updateGridZCount(); } }); gridZPanel_.add(tmp_but, "wrap"); gridZPanel_.add(new JLabel("Z stop [um]:")); gridZStopField_ = pu.makeFloatEntryField(panelName_, "Grid_Z_Stop", -800, 5); gridZStopField_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { updateGridZCount(); } }); gridZPanel_.add(gridZStopField_); tmp_but = new JButton("Set"); tmp_but.setBackground(Color.red); tmp_but.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { gridZStopField_.setValue(positions_.getUpdatedPosition(Devices.Keys.UPPERZDRIVE)); updateGridZCount(); } }); gridZPanel_.add(tmp_but, "wrap"); gridZPanel_.add(new JLabel("Z delta [um]:")); gridZDeltaField_ = pu.makeFloatEntryField(panelName_, "Grid_Z_Delta", 400, 5); gridZDeltaField_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { updateGridZCount(); } }); gridZPanel_.add(gridZDeltaField_); tmp_but = new JButton("Set"); tmp_but.setBackground(Color.red); tmp_but.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { Devices.Keys camKey = isFirstSideA() ? Devices.Keys.CAMERAA : Devices.Keys.CAMERAB; int width; try { width = core_.getROI(devices_.getMMDevice(camKey)).width; } catch (Exception e) { width = 1; } float pixelSize = (float) core_.getPixelSizeUm(); // sanity checks, would be better handled with exceptions or more formal checks if (width > 4100 || width < 4 || pixelSize < 1e-6) { return; } double delta = width * pixelSize / Math.sqrt(2); double overlap = props_.getPropValueFloat(Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_GRID_OVERLAP_PERCENT); delta *= (1 - overlap / 100); gridZDeltaField_.setValue(Math.round(delta)); updateGridZCount(); } }); gridZPanel_.add(tmp_but, "wrap"); gridZPanel_.add(new JLabel("Z count:")); gridZCount_ = new JLabel(""); gridZPanel_.add(gridZCount_, "wrap"); updateGridZCount(); PanelUtils.componentsSetEnabled(gridZPanel_, useZGridCB_.isSelected()); // initialize gridSettingsPanel_ = new JPanel(new MigLayout("", "[right]10[center]", "[]8[]")); gridSettingsPanel_.setBorder(PanelUtils.makeTitledBorder("Grid settings")); gridSettingsPanel_.add(new JLabel("Overlap (Y and Z) [%]:")); JSpinner tileOverlapPercent = pu.makeSpinnerFloat(0, 100, 1, Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_GRID_OVERLAP_PERCENT, 10); gridSettingsPanel_.add(tileOverlapPercent, "wrap"); clearYZGridCB_ = pu.makeCheckBox("Clear position list if YZ unused", Properties.Keys.PREFS_CLEAR_YZ_GRID, panelName_, true); gridSettingsPanel_.add(clearYZGridCB_, "span 2"); computeGridButton_ = new JButton("Compute grid"); computeGridButton_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { final boolean useX = useXGridCB_.isSelected(); final boolean useY = useYGridCB_.isSelected(); final boolean useZ = useZGridCB_.isSelected(); final int numX = useX ? updateGridXCount() : 1; final int numY = useY ? updateGridYCount() : 1; final int numZ = useZ ? updateGridZCount() : 1; double centerX = (((Double) gridXStartField_.getValue()) + ((Double) gridXStopField_.getValue())) / 2; double centerY = (((Double) gridYStartField_.getValue()) + ((Double) gridYStopField_.getValue())) / 2; double centerZ = (((Double) gridZStartField_.getValue()) + ((Double) gridZStopField_.getValue())) / 2; double deltaX = (Double) gridXDeltaField_.getValue(); double deltaY = (Double) gridYDeltaField_.getValue(); double deltaZ = (Double) gridZDeltaField_.getValue(); double startY = centerY - deltaY * (numY - 1) / 2; double startZ = centerZ - deltaZ * (numZ - 1) / 2; String xy_device = devices_.getMMDevice(Devices.Keys.XYSTAGE); String z_device = devices_.getMMDevice(Devices.Keys.UPPERZDRIVE); if (useX) { try { setVolumeSliceStepSize(Math.abs(deltaX) / Math.sqrt(2)); setVolumeSlicesPerVolume(numX); if (!useY && !useZ) { // move to X center if we aren't generating position list with it positions_.setPosition(Devices.Keys.XYSTAGE, Directions.X, centerX); } } catch (Exception ex) { // not sure what to do in case of error so ignore } } else { // use current X value as center; this was original behavior centerX = positions_.getUpdatedPosition(Devices.Keys.XYSTAGE, Directions.X); } // if we aren't using one axis, use the current position instead of GUI position if (useY && !useZ) { startZ = positions_.getUpdatedPosition(Devices.Keys.UPPERZDRIVE); } if (useZ && !useY) { startY = positions_.getUpdatedPosition(Devices.Keys.XYSTAGE, Directions.Y); } if (!useY && !useZ && !clearYZGridCB_.isSelected()) { return; } PositionList pl; try { pl = gui_.getPositionList(); } catch (MMScriptException e) { pl = new PositionList(); } boolean isPositionListEmpty = pl.getNumberOfPositions() == 0; if (!isPositionListEmpty) { boolean overwrite = MyDialogUtils.getConfirmDialogResult( "Do you really want to overwrite the existing position list?", JOptionPane.YES_NO_OPTION); if (!overwrite) { return; // nothing to do } } pl = new PositionList(); if (useY || useZ) { for (int iZ = 0; iZ < numZ; ++iZ) { for (int iY = 0; iY < numY; ++iY) { MultiStagePosition msp = new MultiStagePosition(); StagePosition s = new StagePosition(); s.stageName = xy_device; s.numAxes = 2; s.x = centerX; s.y = startY + iY * deltaY; msp.add(s); StagePosition s2 = new StagePosition(); s2.stageName = z_device; s2.x = startZ + iZ * deltaZ; msp.add(s2); msp.setLabel("Pos_" + iZ + "_" + iY); pl.addPosition(msp); } } } try { gui_.setPositionList(pl); } catch (MMScriptException ex) { MyDialogUtils.showError(ex, "Couldn't overwrite position list with generated YZ grid"); } } }); gridFrame_ = new MMFrame(); gridFrame_.setTitle("XYZ Grid"); gridFrame_.loadPosition(100, 100); gridPanel_ = new JPanel(new MigLayout("", "[right]10[center]", "[]8[]")); gridFrame_.add(gridPanel_); class GridFrameAdapter extends WindowAdapter { @Override public void windowClosing(WindowEvent e) { gridButton_.setSelected(false); gridFrame_.savePosition(); } } gridFrame_.addWindowListener(new GridFrameAdapter()); gridButton_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { gridFrame_.setVisible(true); } }); gridPanel_.add(gridYPanel_); gridPanel_.add(gridZPanel_, "wrap"); gridPanel_.add(gridXPanel_, "spany 2"); gridPanel_.add(gridSettingsPanel_, "growx, wrap"); gridPanel_.add(computeGridButton_, "growx, growy"); gridFrame_.pack(); gridFrame_.setResizable(false); // end YZ grid frame positionPanel.add(new JLabel("Post-move delay [ms]:")); positionDelay_ = pu.makeSpinnerFloat(0.0, 10000.0, 100.0, Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_POSITION_DELAY, 0.0); positionPanel.add(positionDelay_, "wrap"); // enable/disable panel elements depending on checkbox state usePositionsCB_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { PanelUtils.componentsSetEnabled(positionPanel, usePositionsCB_.isSelected()); gridButton_.setEnabled(true); // leave this always enabled } }); PanelUtils.componentsSetEnabled(positionPanel, usePositionsCB_.isSelected()); // initialize gridButton_.setEnabled(true); // leave this always enabled // end of Position panel // checkbox to use navigation joystick settings or not // an "orphan" UI element navigationJoysticksCB_ = new JCheckBox("Use Navigation joystick settings"); navigationJoysticksCB_ .setSelected(prefs_.getBoolean(panelName_, Properties.Keys.PLUGIN_USE_NAVIGATION_JOYSTICKS, false)); navigationJoysticksCB_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateJoysticks(); prefs_.putBoolean(panelName_, Properties.Keys.PLUGIN_USE_NAVIGATION_JOYSTICKS, navigationJoysticksCB_.isSelected()); } }); // checkbox to signal that autofocus should be used during acquisition // another orphan UI element useAutofocusCB_ = new JCheckBox("Autofocus periodically"); useAutofocusCB_ .setSelected(prefs_.getBoolean(panelName_, Properties.Keys.PLUGIN_ACQUSITION_USE_AUTOFOCUS, false)); useAutofocusCB_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { prefs_.putBoolean(panelName_, Properties.Keys.PLUGIN_ACQUSITION_USE_AUTOFOCUS, useAutofocusCB_.isSelected()); } }); // checkbox to signal that movement should be corrected during acquisition // Yet another orphan UI element useMovementCorrectionCB_ = new JCheckBox("Motion correction"); useMovementCorrectionCB_.setSelected( prefs_.getBoolean(panelName_, Properties.Keys.PLUGIN_ACQUSITION_USE_MOVEMENT_CORRECTION, false)); useMovementCorrectionCB_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { prefs_.putBoolean(panelName_, Properties.Keys.PLUGIN_ACQUSITION_USE_MOVEMENT_CORRECTION, useMovementCorrectionCB_.isSelected()); } }); // set up tabbed panels for GUI // make 3 columns as own JPanels to get vertical space right // in each column without dependencies on other columns leftColumnPanel_ = new JPanel(new MigLayout("", "[]", "[]6[]10[]10[]")); leftColumnPanel_.add(durationPanel_, "split 2"); leftColumnPanel_.add(timepointPanel_, "wrap, growx"); leftColumnPanel_.add(savePanel_, "wrap"); leftColumnPanel_.add(new JLabel("Acquisition mode: "), "split 2, right"); AcquisitionModes acqModes = new AcquisitionModes(devices_, prefs_); spimMode_ = acqModes.getComboBox(); spimMode_.addActionListener(recalculateTimingDisplayAL); leftColumnPanel_.add(spimMode_, "left, wrap"); leftColumnPanel_.add(buttonStart_, "split 3, left"); leftColumnPanel_.add(new JLabel(" ")); leftColumnPanel_.add(buttonTestAcq_, "wrap"); leftColumnPanel_.add(new JLabel("Status:"), "split 2, left"); leftColumnPanel_.add(acquisitionStatusLabel_); centerColumnPanel_ = new JPanel(new MigLayout("", "[]", "[]")); centerColumnPanel_.add(positionPanel, "growx, wrap"); centerColumnPanel_.add(multiChannelPanel_, "wrap"); centerColumnPanel_.add(navigationJoysticksCB_, "wrap"); centerColumnPanel_.add(useAutofocusCB_, "split 2"); centerColumnPanel_.add(useMovementCorrectionCB_); rightColumnPanel_ = new JPanel(new MigLayout("", "[center]0", "[]0[]")); rightColumnPanel_.add(volPanel_, "growx, wrap"); rightColumnPanel_.add(slicePanel_, "growx"); // add the column panels to the main panel super.add(leftColumnPanel_); super.add(centerColumnPanel_); super.add(rightColumnPanel_); // properly initialize the advanced slice timing advancedSliceTimingCB_.addItemListener(sliceTimingDisableGUIInputs); sliceTimingDisableGUIInputs.itemStateChanged(null); advancedSliceTimingCB_.addActionListener(showAdvancedTimingFrame); // included is calculating slice timing updateDurationLabels(); // update local variables zStepUm_ = PanelUtils.getSpinnerFloatValue(stepSize_); refreshXYZPositions(); }
From source file:edu.ku.brc.specify.tools.StrLocalizerApp.java
/** * /*from w ww . j av a 2 s. c o m*/ */ private void translateNewItems() { //writeGlassPaneMsg(getResourceString("StrLocalizerApp.TranslatingNew"), 24); final String STATUSBAR_NAME = "STATUS"; final JStatusBar statusBar = UIRegistry.getStatusBar(); statusBar.setProgressRange(STATUSBAR_NAME, 0, 100); startTransMenuItem.setEnabled(false); stopTransMenuItem.setEnabled(true); final double total = newKeyList.size(); SwingWorker<Integer, Integer> translator = new SwingWorker<Integer, Integer>() { @Override protected Integer doInBackground() throws Exception { int count = 0; for (String key : newKeyList) { StrLocaleEntry entry = srcFile.getItemHash().get(key); //if (StringUtils.contains(entry.getSrcStr(), "%") || StringUtils.contains(entry.getSrcStr(), "\n")) { String transText = translate(entry.getSrcStr()); if (transText != null) { entry.setDstStr(transText); //writeGlassPaneMsg(String.format("%d / %d", count, newKeyList.size()), 18); //System.out.println(String.format("%s - %d / %d", key, count, newKeyList.size())); } } try { Thread.sleep(100 + (int) (Math.random() * 100.0)); } catch (InterruptedException ex) { } setProgress((int) (((double) count / total) * 100.0)); System.out.println(entry.getSrcStr() + " " + count); //glassPane.setProgress((int)( (100.0 * count) / total)); count++; if (!contTrans.get()) { return null; } } return null; } /* (non-Javadoc) * @see javax.swing.SwingWorker#done() */ @Override protected void done() { //glassPane.setProgress(100); //clearGlassPaneMsg(); //statusBar.setIndeterminate(STATUSBAR_NAME, false); statusBar.setText(""); statusBar.setProgressDone(STATUSBAR_NAME); UIRegistry.showLocalizedMsg("Done Localizing"); startTransMenuItem.setEnabled(true); stopTransMenuItem.setEnabled(false); } }; statusBar.setIndeterminate(STATUSBAR_NAME, true); translator.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(final PropertyChangeEvent evt) { //System.out.println(evt.getPropertyName()); if ("progress".equals(evt.getPropertyName())) { statusBar.setText(String.format("%d / 100 ", (Integer) evt.getNewValue()) + "%"); } } }); translator.execute(); }
From source file:org.photovault.imginfo.PhotoInfo.java
public void setShotLocation(Location l) { if (shotLocation != null) { shotLocation.removePropertyChangeListener(shotLocationListener); }//from w ww . j a v a 2 s . co m shotLocation = l; if (shotLocation != null) { final PhotoInfo staticThis = this; shotLocationListener = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { staticThis.modified(); } }; shotLocation.addPropertyChangeListener(shotLocationListener); } modified(); }
From source file:de.bfs.radon.omsimulation.gui.OMPanelTesting.java
/** * Initialises the interface of the results panel. *///from w w w. jav a 2s. c o m protected void initialize() { setLayout(null); isSimulated = false; lblExportChartTo = new JLabel("Export chart to ..."); lblExportChartTo.setBounds(436, 479, 144, 14); lblExportChartTo.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 11)); lblExportChartTo.setVisible(false); add(lblExportChartTo); btnCsv = new JButton("CSV"); btnCsv.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser fileDialog = new JFileChooser(); fileDialog.setFileFilter(new FileNameExtensionFilter("*.csv", "csv")); fileDialog.showSaveDialog(getParent()); final File file = fileDialog.getSelectedFile(); if (file != null) { String csv; String[] tmpFileName = file.getAbsolutePath().split("\\."); if (tmpFileName[tmpFileName.length - 1].equals("csv")) { csv = ""; } else { csv = ".csv"; } String csvPath = file.getAbsolutePath() + csv; double[] selectedValues; OMRoom[] rooms = new OMRoom[7]; rooms[0] = (OMRoom) comboBoxRoom1.getSelectedItem(); rooms[1] = (OMRoom) comboBoxRoom2.getSelectedItem(); rooms[2] = (OMRoom) comboBoxRoom3.getSelectedItem(); rooms[3] = (OMRoom) comboBoxRoom4.getSelectedItem(); rooms[4] = (OMRoom) comboBoxRoom5.getSelectedItem(); rooms[5] = (OMRoom) comboBoxRoom6.getSelectedItem(); rooms[6] = (OMRoom) comboBoxRoom7.getSelectedItem(); int start = sliderStartTime.getValue(); final int day = 24; File csvFile = new File(csvPath); try { OMCampaign campaign; if (isResult) { campaign = getResultCampaign(); } else { campaign = new OMCampaign(start, rooms, 0); } FileWriter logWriter = new FileWriter(csvFile); BufferedWriter csvOutput = new BufferedWriter(logWriter); csvOutput.write("\"ID\";\"Room\";\"Radon\""); csvOutput.newLine(); selectedValues = campaign.getValueChain(); int x = 0; for (int i = start; i < start + day; i++) { csvOutput.write("\"" + i + "\";\"" + rooms[0].getId() + "\";\"" + (int) selectedValues[x] + "\""); csvOutput.newLine(); x++; } start = start + day; for (int i = start; i < start + day; i++) { csvOutput.write("\"" + i + "\";\"" + rooms[1].getId() + "\";\"" + (int) selectedValues[x] + "\""); csvOutput.newLine(); x++; } start = start + day; for (int i = start; i < start + day; i++) { csvOutput.write("\"" + i + "\";\"" + rooms[2].getId() + "\";\"" + (int) selectedValues[x] + "\""); csvOutput.newLine(); x++; } start = start + day; for (int i = start; i < start + day; i++) { csvOutput.write("\"" + i + "\";\"" + rooms[3].getId() + "\";\"" + (int) selectedValues[x] + "\""); csvOutput.newLine(); x++; } start = start + day; for (int i = start; i < start + day; i++) { csvOutput.write("\"" + i + "\";\"" + rooms[4].getId() + "\";\"" + (int) selectedValues[x] + "\""); csvOutput.newLine(); x++; } start = start + day; for (int i = start; i < start + day; i++) { csvOutput.write("\"" + i + "\";\"" + rooms[5].getId() + "\";\"" + (int) selectedValues[x] + "\""); csvOutput.newLine(); x++; } start = start + day; for (int i = start; i < start + day; i++) { csvOutput.write("\"" + i + "\";\"" + rooms[6].getId() + "\";\"" + (int) selectedValues[x] + "\""); csvOutput.newLine(); x++; } JOptionPane.showMessageDialog(null, "CSV saved successfully!\n" + csvPath, "Success", JOptionPane.INFORMATION_MESSAGE); csvOutput.close(); } catch (IOException ioe) { JOptionPane.showMessageDialog(null, "Failed to write CSV. Please check permissions!\n" + ioe.getMessage(), "Failed", JOptionPane.ERROR_MESSAGE); ioe.printStackTrace(); } } else { JOptionPane.showMessageDialog(null, "Failed to write CSV. Please check the file path!", "Failed", JOptionPane.ERROR_MESSAGE); } } }); btnCsv.setBounds(590, 475, 70, 23); btnCsv.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 11)); btnCsv.setVisible(false); add(btnCsv); btnPdf = new JButton("PDF"); btnPdf.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser fileDialog = new JFileChooser(); fileDialog.setFileFilter(new FileNameExtensionFilter("*.pdf", "pdf")); fileDialog.showSaveDialog(getParent()); final File file = fileDialog.getSelectedFile(); if (file != null) { String pdf; String[] tmpFileName = file.getAbsolutePath().split("\\."); if (tmpFileName[tmpFileName.length - 1].equals("pdf")) { pdf = ""; } else { pdf = ".pdf"; } String pdfPath = file.getAbsolutePath() + pdf; OMRoom[] rooms = new OMRoom[7]; rooms[0] = (OMRoom) comboBoxRoom1.getSelectedItem(); rooms[1] = (OMRoom) comboBoxRoom2.getSelectedItem(); rooms[2] = (OMRoom) comboBoxRoom3.getSelectedItem(); rooms[3] = (OMRoom) comboBoxRoom4.getSelectedItem(); rooms[4] = (OMRoom) comboBoxRoom5.getSelectedItem(); rooms[5] = (OMRoom) comboBoxRoom6.getSelectedItem(); rooms[6] = (OMRoom) comboBoxRoom7.getSelectedItem(); int start = sliderStartTime.getValue(); OMCampaign campaign; try { if (isResult) { campaign = getResultCampaign(); } else { campaign = new OMCampaign(start, rooms, 0); } JFreeChart chart = OMCharts.createCampaignChart(campaign, false); String title = "Campaign: " + rooms[0].getId() + rooms[1].getId() + rooms[2].getId() + rooms[3].getId() + rooms[4].getId() + rooms[5].getId() + rooms[6].getId() + ", Start: " + start; int height = (int) PageSize.A4.getWidth(); int width = (int) PageSize.A4.getHeight(); try { OMExports.exportPdf(pdfPath, chart, width, height, new DefaultFontMapper(), title); JOptionPane.showMessageDialog(null, "PDF saved successfully!\n" + pdfPath, "Success", JOptionPane.INFORMATION_MESSAGE); } catch (IOException ioe) { JOptionPane.showMessageDialog(null, "Failed to write PDF. Please check permissions!\n" + ioe.getMessage(), "Failed", JOptionPane.ERROR_MESSAGE); ioe.printStackTrace(); } } catch (IOException ioe) { JOptionPane.showMessageDialog(null, "Failed to create chart!\n" + ioe.getMessage(), "Failed", JOptionPane.ERROR_MESSAGE); ioe.printStackTrace(); } } else { JOptionPane.showMessageDialog(null, "Failed to write PDF. Please check the file path!", "Failed", JOptionPane.ERROR_MESSAGE); } } }); btnPdf.setBounds(670, 475, 70, 23); btnPdf.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 11)); btnPdf.setVisible(false); add(btnPdf); lblSelectProject = new JLabel("Select Project"); lblSelectProject.setBounds(10, 65, 132, 14); lblSelectProject.setFont(new Font("SansSerif", Font.PLAIN, 11)); add(lblSelectProject); lblSelectRooms = new JLabel("Select Rooms"); lblSelectRooms.setBounds(10, 94, 132, 14); lblSelectRooms.setFont(new Font("SansSerif", Font.PLAIN, 11)); add(lblSelectRooms); lblStartTime = new JLabel("Start Time"); lblStartTime.setBounds(10, 123, 132, 14); lblStartTime.setFont(new Font("SansSerif", Font.PLAIN, 11)); add(lblStartTime); lblWarning = new JLabel("Select 6 rooms and 1 cellar!"); lblWarning.setForeground(Color.RED); lblWarning.setBounds(565, 123, 175, 14); lblWarning.setFont(new Font("SansSerif", Font.PLAIN, 11)); lblWarning.setVisible(false); add(lblWarning); sliderStartTime = new JSlider(); sliderStartTime.setMaximum(0); sliderStartTime.setBounds(152, 119, 285, 24); sliderStartTime.setFont(new Font("SansSerif", Font.PLAIN, 11)); add(sliderStartTime); spnrStartTime = new JSpinner(); spnrStartTime.setModel(new SpinnerNumberModel(0, 0, 0, 1)); spnrStartTime.setBounds(447, 120, 108, 22); spnrStartTime.setFont(new Font("SansSerif", Font.PLAIN, 11)); add(spnrStartTime); btnRefresh = new JButton("Load"); btnRefresh.setBounds(616, 61, 124, 23); btnRefresh.setFont(new Font("SansSerif", Font.PLAIN, 11)); add(btnRefresh); btnMaximize = new JButton("Fullscreen"); btnMaximize.setBounds(10, 475, 124, 23); btnMaximize.setFont(new Font("SansSerif", Font.PLAIN, 11)); add(btnMaximize); panelCampaign = new JPanel(); panelCampaign.setBounds(10, 150, 730, 315); panelCampaign.setFont(new Font("SansSerif", Font.PLAIN, 11)); add(panelCampaign); progressBar = new JProgressBar(); progressBar.setBounds(10, 475, 730, 23); progressBar.setFont(new Font("SansSerif", Font.PLAIN, 11)); progressBar.setVisible(false); add(progressBar); lblOpenOmbfile = new JLabel("Open OMB-File"); lblOpenOmbfile.setFont(new Font("SansSerif", Font.PLAIN, 11)); lblOpenOmbfile.setBounds(10, 36, 132, 14); add(lblOpenOmbfile); lblHelp = new JLabel("Select an OMB-Object file to manually simulate virtual campaigns."); lblHelp.setForeground(Color.GRAY); lblHelp.setFont(new Font("SansSerif", Font.PLAIN, 11)); lblHelp.setBounds(10, 10, 730, 14); add(lblHelp); txtOmbFile = new JTextField(); txtOmbFile.setFont(new Font("SansSerif", Font.PLAIN, 11)); txtOmbFile.setColumns(10); txtOmbFile.setBounds(152, 33, 454, 20); add(txtOmbFile); btnBrowse = new JButton("Browse"); btnBrowse.setFont(new Font("SansSerif", Font.PLAIN, 11)); btnBrowse.setBounds(616, 32, 124, 23); add(btnBrowse); comboBoxRoom1 = new JComboBox<OMRoom>(); comboBoxRoom1.setBounds(152, 90, 75, 22); comboBoxRoom1.setFont(new Font("SansSerif", Font.PLAIN, 11)); add(comboBoxRoom1); comboBoxRoom2 = new JComboBox<OMRoom>(); comboBoxRoom2.setBounds(237, 90, 75, 22); comboBoxRoom2.setFont(new Font("SansSerif", Font.PLAIN, 11)); add(comboBoxRoom2); comboBoxRoom3 = new JComboBox<OMRoom>(); comboBoxRoom3.setBounds(323, 90, 75, 22); comboBoxRoom3.setFont(new Font("SansSerif", Font.PLAIN, 11)); add(comboBoxRoom3); comboBoxRoom4 = new JComboBox<OMRoom>(); comboBoxRoom4.setBounds(408, 90, 75, 22); comboBoxRoom4.setFont(new Font("SansSerif", Font.PLAIN, 11)); add(comboBoxRoom4); comboBoxRoom5 = new JComboBox<OMRoom>(); comboBoxRoom5.setBounds(494, 90, 75, 22); comboBoxRoom5.setFont(new Font("SansSerif", Font.PLAIN, 11)); add(comboBoxRoom5); comboBoxRoom6 = new JComboBox<OMRoom>(); comboBoxRoom6.setBounds(579, 90, 75, 22); comboBoxRoom6.setFont(new Font("SansSerif", Font.PLAIN, 11)); add(comboBoxRoom6); comboBoxRoom7 = new JComboBox<OMRoom>(); comboBoxRoom7.setBounds(665, 90, 75, 22); comboBoxRoom7.setFont(new Font("SansSerif", Font.PLAIN, 11)); add(comboBoxRoom7); comboBoxProjects = new JComboBox<OMBuilding>(); comboBoxProjects.setBounds(152, 61, 454, 22); comboBoxProjects.setFont(new Font("SansSerif", Font.PLAIN, 11)); add(comboBoxProjects); comboBoxRoom1.addActionListener(this); comboBoxRoom1.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { validateCampaign(); } }); comboBoxRoom2.addActionListener(this); comboBoxRoom2.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { validateCampaign(); } }); comboBoxRoom3.addActionListener(this); comboBoxRoom3.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { validateCampaign(); } }); comboBoxRoom4.addActionListener(this); comboBoxRoom4.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { validateCampaign(); } }); comboBoxRoom5.addActionListener(this); comboBoxRoom5.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { validateCampaign(); } }); comboBoxRoom6.addActionListener(this); comboBoxRoom6.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { validateCampaign(); } }); comboBoxRoom7.addActionListener(this); comboBoxRoom7.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { validateCampaign(); } }); sliderStartTime.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { if (comboBoxProjects.isEnabled() || isResult) { if (comboBoxProjects.getSelectedItem() != null) { spnrStartTime.setValue((int) sliderStartTime.getValue()); updateChart(); } } } }); spnrStartTime.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent arg0) { if (comboBoxProjects.isEnabled() || isResult) { if (comboBoxProjects.getSelectedItem() != null) { sliderStartTime.setValue((Integer) spnrStartTime.getValue()); updateChart(); } } } }); btnRefresh.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (txtOmbFile.getText() != null && !txtOmbFile.getText().equals("") && !txtOmbFile.getText().equals(" ")) { txtOmbFile.setBackground(Color.WHITE); String ombPath = txtOmbFile.getText(); String omb; String[] tmpFileName = ombPath.split("\\."); if (tmpFileName[tmpFileName.length - 1].equals("omb")) { omb = ""; } else { omb = ".omb"; } txtOmbFile.setText(ombPath + omb); setOmbFile(ombPath + omb); File ombFile = new File(ombPath + omb); if (ombFile.exists()) { txtOmbFile.setBackground(Color.WHITE); btnRefresh.setEnabled(false); comboBoxProjects.setEnabled(false); setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); progressBar.setVisible(true); btnPdf.setVisible(false); btnCsv.setVisible(false); btnMaximize.setVisible(false); lblExportChartTo.setVisible(false); progressBar.setIndeterminate(true); progressBar.setStringPainted(true); refreshTask = new Refresh(); refreshTask.execute(); } else { txtOmbFile.setBackground(new Color(255, 222, 222, 128)); JOptionPane.showMessageDialog(null, "OMB-file not found, please check the file path!", "Error", JOptionPane.ERROR_MESSAGE); } } else { txtOmbFile.setBackground(new Color(255, 222, 222, 128)); JOptionPane.showMessageDialog(null, "Please select an OMB-file!", "Warning", JOptionPane.WARNING_MESSAGE); } } }); btnMaximize.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { OMRoom[] rooms = new OMRoom[7]; rooms[0] = (OMRoom) comboBoxRoom1.getSelectedItem(); rooms[1] = (OMRoom) comboBoxRoom2.getSelectedItem(); rooms[2] = (OMRoom) comboBoxRoom3.getSelectedItem(); rooms[3] = (OMRoom) comboBoxRoom4.getSelectedItem(); rooms[4] = (OMRoom) comboBoxRoom5.getSelectedItem(); rooms[5] = (OMRoom) comboBoxRoom6.getSelectedItem(); rooms[6] = (OMRoom) comboBoxRoom7.getSelectedItem(); int start = sliderStartTime.getValue(); String title = "Campaign: " + rooms[0].getId() + rooms[1].getId() + rooms[2].getId() + rooms[3].getId() + rooms[4].getId() + rooms[5].getId() + rooms[6].getId() + ", Start: " + start; OMCampaign campaign; if (isResult) { campaign = getResultCampaign(); } else { campaign = new OMCampaign(start, rooms, 0); } JPanel campaignChart = createCampaignPanel(campaign, false, true); JFrame chartFrame = new JFrame(); chartFrame.getContentPane().add(campaignChart); chartFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); chartFrame.setBounds(0, 0, (int) dim.getWidth(), (int) dim.getHeight()); chartFrame.setTitle(title); chartFrame.setResizable(true); chartFrame.setExtendedState(JFrame.MAXIMIZED_BOTH); chartFrame.setVisible(true); } catch (IOException ioe) { ioe.printStackTrace(); } } }); txtOmbFile.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent arg0) { setOmbFile(txtOmbFile.getText()); } }); btnBrowse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { JFileChooser fileDialog = new JFileChooser(); fileDialog.setFileFilter(new FileNameExtensionFilter("*.omb", "omb")); fileDialog.showOpenDialog(getParent()); final File file = fileDialog.getSelectedFile(); if (file != null) { String omb; String[] tmpFileName = file.getAbsolutePath().split("\\."); if (tmpFileName[tmpFileName.length - 1].equals("omb")) { omb = ""; } else { omb = ".omb"; } txtOmbFile.setText(file.getAbsolutePath() + omb); setOmbFile(file.getAbsolutePath() + omb); } } }); }
From source file:edu.ku.brc.specify.tools.l10nios.StrLocalizerAppForiOS.java
private void scanSources() { scanMI.setEnabled(false);//from ww w . ja v a2s .c om final String STATUSBAR_NAME = "STATUS"; final JStatusBar statusBar = UIRegistry.getStatusBar(); statusBar.setProgressRange(STATUSBAR_NAME, 0, 100); SwingWorker<Integer, Integer> translator = new SwingWorker<Integer, Integer>() { @Override protected Integer doInBackground() throws Exception { doScanSources(); return null; } @Override protected void done() { scanMI.setEnabled(false); } }; translator.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(final PropertyChangeEvent evt) { if ("progress".equals(evt.getPropertyName())) { statusBar.setText(String.format("%d / 100 ", (Integer) evt.getNewValue()) + "%"); } } }); translator.execute(); }
From source file:org.photovault.imginfo.PhotoInfo.java
/** * Set the usage rights for the image//from w w w . j a v a2s. com * @param l */ public void setUsageRights(UsageRights l) { if (usageRights != null) { usageRights.removePropertyChangeListener(usageRightsListener); } usageRights = l; if (usageRights != null) { final PhotoInfo staticThis = this; usageRightsListener = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { staticThis.modified(); } }; usageRights.addPropertyChangeListener(usageRightsListener); } modified(); }
From source file:ca.uhn.hl7v2.testpanel.ui.TestPanelWindow.java
private void initializeLocal() { myMessagesListModel = new MyMessagesListModel(); myMessagesList.setModel(myMessagesListModel); myMessagesList.setCellRenderer(new MyMessagesListCellRencerer()); myController.getMessagesList().addPropertyChangeListener(MessagesList.PROP_LIST, myMessagesListModel); updateMessagesList();/*from w ww .j a v a 2 s . c o m*/ myOutboundConnectionsListModel = new MyOutboundConnectionsListModel(); myOutboundConnectionsList.setModel(myOutboundConnectionsListModel); myOutboundConnectionsList.setCellRenderer(new MyOutboundConnectionsListCellRenderer()); updateOutboundConnectionsList(); myOutboundConnectionsListListener = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent theEvt) { updateOutboundConnectionsList(); } }; myController.getOutboundConnectionList().addPropertyChangeListener(OutboundConnectionList.PROP_LIST, myOutboundConnectionsListListener); myInboundConnectionsListModel = new MyInboundConnectionsListModel(); myInboundConnectionsList.setModel(myInboundConnectionsListModel); myInboundConnectionsList.setCellRenderer(new MyInboundConnectionsListCellRenderer()); updateInboundConnectionsList(); myInboundConnectionsListListener = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent theEvt) { updateInboundConnectionsList(); } }; myController.getInboundConnectionList().addPropertyChangeListener(InboundConnectionList.PROP_LIST, myInboundConnectionsListListener); updateLeftToolbarInboundStatusButtons(); updateLeftToolbarOutboundStatusButtons(); }
From source file:org.openmicroscopy.shoola.agents.metadata.editor.EditorComponent.java
/** * Implemented as specified by the {@link Editor} interface. * @see Editor#analysisResultsLoaded(AnalysisResultsItem) *///from ww w . j a va2 s . co m public void analysisResultsLoaded(AnalysisResultsItem analysis) { if (analysis == null) return; analysis.notifyLoading(false); model.removeAnalysisResultsLoading(analysis); //now display results. String name = analysis.getNameSpace(); if (FileAnnotationData.FLIM_NS.equals(name)) { DataObject data = analysis.getData(); if (data instanceof ImageData) { /* FLIMResultsEvent event = new FLIMResultsEvent((ImageData) data, analysis.getResults()); EventBus bus = MetadataViewerAgent.getRegistry().getEventBus(); bus.post(event); */ ImageData image = (ImageData) data; IconManager icons = IconManager.getInstance(); FLIMResultsDialog d = new FLIMResultsDialog(null, EditorUtil.getPartialName(image.getName()), icons.getIcon(IconManager.FLIM_48), analysis.getResults()); d.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { String name = evt.getPropertyName(); if (FLIMResultsDialog.SAVED_FLIM_RESULTS_PROPERTY.equals(name)) { boolean b = ((Boolean) evt.getNewValue()).booleanValue(); UserNotifier un = MetadataViewerAgent.getRegistry().getUserNotifier(); if (b) { un.notifyInfo("Saving Results", "The file has " + "successfully been saved."); } else { un.notifyInfo("Saving Results", "An error " + "occurred while saving the results."); } } } }); UIUtilities.centerAndShow(d); } } }