file_name stringlengths 6 86 | file_path stringlengths 45 249 | content stringlengths 47 6.26M | file_size int64 47 6.26M | language stringclasses 1 value | extension stringclasses 1 value | repo_name stringclasses 767 values | repo_stars int64 8 14.4k | repo_forks int64 0 1.17k | repo_open_issues int64 0 788 | repo_created_at stringclasses 767 values | repo_pushed_at stringclasses 767 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
ProgramDataDB.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibDataBase/src/lib/database/ProgramDataDB.java | package lib.database;
import lib.huvud.RedirectedFrame;
/** Class to store information on the "DataBase" program.
* The class is used to retrieve data in diverse methods.
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class ProgramDataDB {
/** the temperature (Celsius), used both to extrapolate equilibrium constants,
* to calculate ionic strength effects (that is, to calculate activity
* coefficients), and to calculate values of the redox potential, Eh,
* from the pe-values */
public double temperature_C = 25;
/** the pressure (bar), used to calculate values of the
* equilibrium constants */
public double pressure_bar = 25;
/** if <code>true</code> then it will be possible to choose temperatures
* above 100 C in Database. Default is <code>true</code>. */
public boolean temperatureAllowHigher = true;
public boolean redoxAsk = false;
public boolean redoxN = true;
public boolean redoxS = true;
public boolean redoxP = true;
/** if <code>true</code> then it will be possible to choose which solid phases
* are selected in the program Database. */
public boolean allSolidsAsk = false;
/** 0=include all solids; 1=exclude (cr); 2=exclude (c); 3=exclude (cr)&(c) */
public int allSolids = 0;
/** include water (H2O) as a component in the output data file?
* @see ProgramDataDB#foundH2O foundH2O
* @see ProgramDataDB#elemComp elemComp */
public boolean includeH2O = false;
/** the program to make diagrams ("Spana") including directory */
public String diagramProgr;
/** the path where new data files will be stored */
public StringBuffer pathAddData = new StringBuffer();
/** the default path where database files will searched */
public StringBuffer pathDatabaseFiles = new StringBuffer();
public java.awt.Point addDataLocation = new java.awt.Point(-1000,-1000);
/** the databases that will be searched */
public java.util.ArrayList<String> dataBasesList = new java.util.ArrayList<String>();
/** array list of String[3] objects<br>
* [0] contains the element name (e.g. "C"),<br>
* [1] the component formula ("CN-" or "Fe+2"),<br>
* [2] the component name ("cyanide" or null), which is not really needed,
* but used to help the user */
public java.util.ArrayList<String[]> elemComp = new java.util.ArrayList<String[]>();
/** is water (H2O) found in elemComp? This is set when reading the element files.
* @see ProgramDataDB#includeH2O includeH2O
* @see ProgramDataDB#elemComp elemComp */
public boolean foundH2O = false;
/** an instance of the class References
* @see References References */
public References references = null;
/** a redirected frame for output and error messages */
public RedirectedFrame msgFrame = null;
public ProgramDataDB() {}
}
| 3,546 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
References.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibDataBase/src/lib/database/References.java | package lib.database;
import lib.huvud.SortedProperties;
/** The objects of this class store the citations and corresponding references
* contained in a references file (text file in "ini" properties format).
* The keys and references are stored in a SortedProperties object.
* Methods for reading and saving the file are provided.
* References may be displayed through a dialog window.
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @see lib.huvud.SortedProperties SortedProperties
* @author Ignasi Puigdomenech */
public class References {
private final boolean dbg;
private String referenceFileName;
/** the list with references found in "refFile" */
private SortedProperties propertiesRefs = null;
private final java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
private final String line = "- - - - -";
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
public References() {dbg = false;}
public References(boolean dbg) {this.dbg = dbg;}
//<editor-fold defaultstate="collapsed" desc="readRefsFile()">
/** Read a text file containing references in properties "ini" format, and
* store the citation-references in this class instance.
* @param refFileName a file name, including path and extension
* @param dbg if true some debug output has to be printed
* @return <code>false</code> if the text file can not be read for any reason
* @see References#saveRefsFile saveRefsFile
*/
public boolean readRefsFile(String refFileName, boolean dbg) {
if(refFileName == null || refFileName.trim().length() <=0) {
referenceFileName = null;
propertiesRefs = null;
return false;
}
if(propertiesRefs == null) {
propertiesRefs = new SortedProperties();
} else {
propertiesRefs.clear();
}
referenceFileName = refFileName.trim();
java.io.File rf = new java.io.File(referenceFileName);
if(!rf.exists()) {
System.out.println(
line+nl+
"Warning - file not found:"+nl+
"\""+rf.getAbsolutePath()+"\""+nl+
line);
rf = null;
} else {
if(!rf.canRead()) {
System.out.println(
line+nl+
"Warning - can not read from file:"+nl+
"\""+rf.getAbsolutePath()+"\""+nl+
line);
rf = null;
}
}
if(rf == null) {return false;}
if(dbg) {System.out.println("Reading file \""+rf.getAbsolutePath()+"\"");}
java.io.FileInputStream fis = null;
java.io.BufferedReader r = null;
try {
fis = new java.io.FileInputStream(rf);
r = new java.io.BufferedReader(new java.io.InputStreamReader(fis,"UTF8"));
propertiesRefs.load(r);
} //try
catch (java.io.FileNotFoundException e) {
System.out.println("Warning: file Not found: \""+rf.getAbsolutePath()+"\"");
propertiesRefs = null;
} //catch FileNotFoundException
catch (java.io.IOException e) {
String msg = line+nl+"Error: \""+e.toString()+"\""+nl+
" while loading REF-file:"+nl+
" \""+rf.getAbsolutePath()+"\""+nl+line;
System.err.println(msg);
propertiesRefs = null;
referenceFileName = null;
} // catch loading-exception
finally {
try {if(r != null) {r.close();} if(fis != null) {fis.close();}}
catch (java.io.IOException e) {
String msg = line+nl+"Error: \""+e.toString()+"\""+nl+
" while closing REF-file:"+nl+
" \""+rf.getAbsolutePath()+"\""+nl+line;
System.err.println(msg);
} // catch close-exception
}
return propertiesRefs != null;
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="saveRefsFile()">
/** Save the references and their citation codes (stored in this object)
* into the file previously read. If there are no references to save,
* an empty file is created.
* @param parent used to display warnings and errors.
* @param warning if <code>true</code> and if the file exists (normally it should)
* then a warning is issued asking the user if it is OK to replace the file.
* @see References#readRefsFile readRefsFile
* @see References#setRef setRef
*/
public void saveRefsFile(java.awt.Frame parent, boolean warning) {
if(propertiesRefs == null) {
propertiesRefs = new SortedProperties();
System.err.println(line+nl+"Warning in \"saveRefsFile\" - propertiesRefs is empty."+nl+line);
}
if(referenceFileName == null || referenceFileName.trim().length() <=0) {
System.err.println(line+nl+"Error in \"saveRefsFile\" - empty file name."+nl+line);
return;
}
java.io.File rf = new java.io.File(referenceFileName);
if(rf.exists()) {
if(warning) {
Object[] opt = {"OK", "Cancel"};
int m = javax.swing.JOptionPane.showOptionDialog(parent,
"Warning - file:"+nl+" "+rf.getName()+nl+
"will be overwritten."+nl+" ",
"Save reerences", javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[1]);
if(m != javax.swing.JOptionPane.YES_OPTION) {return;}
}
if(!rf.canWrite() || !rf.setWritable(true)) {
javax.swing.JOptionPane.showMessageDialog(parent,
"Error - Can not write to file:"+nl+
rf.getAbsolutePath()+nl+" ",
"Save reerences", javax.swing.JOptionPane.ERROR_MESSAGE);
return;
}
}
java.io.FileOutputStream fos = null;
java.io.Writer w = null;
System.out.println("Saving file \""+rf.getAbsolutePath()+"\"");
try{
fos = new java.io.FileOutputStream(rf);
w = new java.io.BufferedWriter(new java.io.OutputStreamWriter(fos,"UTF8"));
propertiesRefs.store(w,null);
System.out.println("Written: \""+rf.getAbsolutePath()+"\"");
} catch (java.io.IOException e) {
String msg = "Error: \""+e.toString()+"\""+nl+
" while writing the References file:"+nl+
" \""+rf.getAbsolutePath()+"\"";
System.err.println(msg);
javax.swing.JOptionPane.showMessageDialog(parent, msg,
"Save references",javax.swing.JOptionPane.ERROR_MESSAGE);
}
finally {
try {if(w != null) {w.close();} if(fos != null) {fos.close();}}
catch (java.io.IOException e) {
String msg = "Error: \""+e.toString()+"\""+nl+
" while closing the References file:"+nl+
" \""+rf.getAbsolutePath()+"\"";
System.err.println(msg);
javax.swing.JOptionPane.showMessageDialog(parent,msg,
"Save references",javax.swing.JOptionPane.ERROR_MESSAGE);
}
} //finally
}
// </editor-fold>
/** Returns the name of the references-file that has been read and
* stored into this instance.
* @return the name of the file. It will be null if no file has been read yet. */
public String referencesFileName() {
return referenceFileName;
}
//<editor-fold defaultstate="collapsed" desc="splitRefs(text)">
/** Split a <code>text</code>, containing reference citations, into a
* list of citations. Citations are expected to be separated either by
* a comma (,) or by a semicolon (;) or by a "plus" (+). For example, either of: "Yu 95,Li" or
* "Yu 95, Li" or "Yu 95+Li" will return the array {"Yu 95", "Li"}.
* To include a "+" or "," into a reference citation, include the citation
* in parentheses (either "()", "[]" or "{}"), for example the text
* "1996H (estimate based in La+3)" will return an array with two citations:
* {"1996H", "(estimate based in La+3)"}.
* @param txt containing reference citations separated by "+", semicolons or commas.
* @return array list of reference citations. Returns null if <code>text</code> is null,
* Returns the array {""} if <code>text</code> is empty */
public static java.util.ArrayList<String> splitRefs(String txt) {
if(txt == null) {return null;}
final boolean debug = false;
// Regex delimiter:
// Delimiter is either:
// "zero or more whitespace followed by "+" followed by zero or more whitespace" or
// "zero or more whitespace followed by "," followed by zero or more whitespace" or
// "zero or more whitespace followed by ";" followed by zero or more whitespace" or
String delimiter = "\\s*\\+\\s*|\\s*,\\s*|\\s*;\\s*";
java.util.Scanner scanner;
String text = txt.trim();
java.util.ArrayList<String> rfs = new java.util.ArrayList<String>();
if(text.length() <=0) {rfs.add(""); return rfs;}
String token, left;
// open parenthesis, square brackets, curly braces
int open, openP,openS,openC,close;
char openChar, closeChar;
// ---- get a list of references ----
if(debug) {System.out.println("text = \""+text+"\"");}
//
// ---- 1st find and remove texts within "([{}])"
openP = text.indexOf("(");
openS = text.indexOf("[");
openC = text.indexOf("{");
open = openP;
if(openP >=0) {
if(openS >=0) {open = Math.min(openP, openS);}
if(openC >=0) {open = Math.min(open, openC);}
} else if(openS >=0) {
open = openS;
if(openC >=0) {open = Math.min(openS, openC);}
} else {open = openC;}
if(debug) {System.out.println("open = "+open+", (="+openP+", [="+openS+", {="+openC);}
while (open >=0) {
openChar = '('; closeChar = ')';
if(open == openS) {openChar = '['; closeChar = ']';}
if(open == openC) {openChar = '{'; closeChar = '}';}
close = findClosingParen(text.toCharArray(), openChar, closeChar, open);
if(close <= open) {break;}
left = text.substring(0, open).trim();
if(debug) {System.out.println("left of () = \""+left+"\"");}
if(left.length() >0) { // add any tokens before "("
scanner = new java.util.Scanner(left);
scanner.useDelimiter(delimiter);
scanner.useLocale(java.util.Locale.ENGLISH);
while (scanner.hasNext()) {
token = scanner.next();
if(token.trim().length() >0) {
if(debug) {System.out.println("token = \""+token+"\"");}
rfs.add(token);
}
} //while
scanner.close();
} // tokens before "("
token = text.substring(open,close+1);
rfs.add(token);
text = text.substring(close+1);
if(debug) {System.out.println("(token) = \""+token+"\", new text = \""+text+"\"");}
openP = text.indexOf("(");
openS = text.indexOf("[");
openC = text.indexOf("{");
open = openP;
if(openP >=0) {
if(openS >=0) {open = Math.min(openP, openS);}
if(openC >=0) {open = Math.min(open, openC);}
} else if(openS >=0) {
open = openS;
if(openC >=0) {open = Math.min(openS, openC);}
} else {open = openC;}
if(debug) {System.out.println("open = "+open+", (="+openP+", [="+openS+", {="+openC);}
} // while (open >=0)
scanner = new java.util.Scanner(text.trim());
scanner.useDelimiter(delimiter);
scanner.useLocale(java.util.Locale.ENGLISH);
while (scanner.hasNext()) {
token = scanner.next();
if(token.trim().length() >0) {
if(debug) {System.out.println("token = \""+token+"\"");}
rfs.add(token);
}
} //while
scanner.close();
if(debug) {System.out.println(java.util.Arrays.toString(rfs.toArray()));}
return rfs;
}
private static int findClosingParen(char[] text, char openParenthesis, char closeParenthesis, int openPos) {
if(openPos < 0 || text == null || openPos >= text.length) {return -1;}
int closePos = openPos;
int counter = 1, pos;
while (counter > 0) {
pos = ++closePos;
if(pos >= text.length) {return -1;}
char c = text[pos];
if (c == openParenthesis) {counter++;} else if(c == closeParenthesis) {counter--;}
}
return closePos;
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="referenceKeys()">
/** Returns the reference keys
* @return the keys. It will be null if no file has been read yet. */
public String[] referenceKeys() {
if(propertiesRefs == null || propertiesRefs.size() <=0) {
System.out.println(line+nl+"Warning in \"referenceKeys()\": there are no reference keys"+nl+line);
return null;
}
//return propertiesRefs.keySet().toArray();
String[] s = propertiesRefs.stringPropertyNames().toArray(new String[0]);
return s;
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="isRefThere(ref)">
/** Returns a reference text if the key (citation) is found (ignoring case)
* @param key the reference citation
* @return a reference text if <code>key</code> is found;
* returns null if <code>key</code> is null or empty or if the reference <code>key</code>
* is not found (even when ignoring case).
* @see References#setRef setRef
* @see References#readRefsFile readRefsFile
* @see References#saveRefsFile saveRefsFile
*/
public String isRefThere(String key) {
if(key == null || key.trim().length() <=0) {return null;}
if(propertiesRefs == null || propertiesRefs.size() <=0) {
System.out.println(line+nl+"Warning in \"isRefThere\": the reference file has not yet been read."+nl+line);
return null;
}
String refText = propertiesRefs.getProperty(key.trim());
if(refText != null && refText.length() >0) {return refText.trim();}
// Not found, try case insensitive
java.util.Set<java.util.Map.Entry<Object, Object>> s = propertiesRefs.entrySet();
java.util.Iterator<java.util.Map.Entry<Object, Object>> it = s.iterator();
while (it.hasNext()) {
java.util.Map.Entry<Object, Object> entry = it.next();
if (key.equalsIgnoreCase((String) entry.getKey())) {
return ((String) entry.getValue()).trim();
}
}
// not found anyway...
return null;
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="setRef(key, txt)">
/** Set a reference text corresponding to a reference citation (key). If <code>key</code>
* was not previously there, it is added; otherwise <code>txt</code> replaces
* the reference corresponding to <code>key</code>. Note that the change is
* performed in memory. The user must save the file afterwards if needed.
* @param key a reference citation
* @param txt the text corresponding to the reference citation. If null or empty
* the citation <code>key</code> will be deleted.
* @return <code>true</code> if successful; <code>false</code> if a problem occurs
* @see References#readRefsFile readRefsFile
* @see References#saveRefsFile saveRefsFile
*/
public synchronized boolean setRef(String key, String txt) {
if(propertiesRefs == null || propertiesRefs.size() <=0) {
System.out.println(line+nl+"Warning in \"setRef\": there are no references yet."+nl+line);
if(propertiesRefs == null) {propertiesRefs = new SortedProperties();}
}
if(key == null || key.trim().length() <=0) {return false;}
if(txt == null || txt.trim().length() <=0) {
propertiesRefs.remove(key.trim());
} else {
propertiesRefs.setProperty(key.trim(), txt.trim());
}
return true;
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="refsAsString(ArrayList)">
/** Returns a text string containing the references corresponding to a list
* of reference citations (ignoring case)
*
* @param refKeys the citation keys for the references to display
* @return a text string containing the references
*/
public String refsAsString(java.util.ArrayList<String> refKeys) {
if(dbg) {
System.out.println("\"refsAsString\" - References read from file:");
propertiesRefs.list(System.out);
}
if(refKeys == null || refKeys.isEmpty()) {return "(no references)";}
StringBuilder allReferences = new StringBuilder();
String refText;
StringBuilder refKey = new StringBuilder();
for(int i=0; i < refKeys.size(); i++) {
if(refKeys.get(i) == null || refKeys.get(i).trim().length() <=0) {continue;}
refKey.delete(0, refKey.length());
refKey.append(refKeys.get(i).trim());
if(allReferences.length()>0) {allReferences.append("- - - - - - - - - - - - - - -"); allReferences.append(nl);}
allReferences.append(refKey.toString()); allReferences.append(":"); allReferences.append(nl); allReferences.append(nl);
if(dbg) {System.out.println(" looking for \""+refKey.toString()+"\"");}
if(refKey.toString().length() <=0) {continue;}
refText = isRefThere(refKey.toString());
if(refText == null || refText.length() <=0) {refText = "reference not found in file"+nl+" \""+referenceFileName+"\"";}
allReferences.append(refText);
if(allReferences.charAt(allReferences.length()-1) != '\n'
&& allReferences.charAt(allReferences.length()-1) != '\r') {allReferences.append(nl);}
}
return allReferences.toString();
} // refsAsString
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="refsAsString(String)">
/** Returns the references (a text string) corresponding to
* citations contained in an imput string.
* Citations are expected to be separated by either a comma, or a "+".
* For example, any of: "Yu 95,Li" or "Yu 95, Li" or "Yu 95+Li" , etc.
*
* @param refs the citation keys for the references to display
* @return a text string containing the references
*/
public String refsAsString(String refs) {
return refsAsString(splitRefs(refs));
} // refsAsString
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="displayRefs()">
/** Display a dialog with references
* @param parent
* @param modal
* @param species a name for the reaction product (chemical species) whose
* reference will be displayed. Used in the title of the dialog. May be null or empty.
* @param refKeys the citation keys for the references to be displayed
*/
public void displayRefs(java.awt.Frame parent, boolean modal,
String species, java.util.ArrayList<String> refKeys) {
if(propertiesRefs == null || propertiesRefs.size() <=0) {
System.out.println(line+nl+"Error in \"displayRefs\":"+nl+"the reference file has not yet been read."+nl+line);
return;
}
if(refKeys == null || refKeys.isEmpty()) {
String msg = "There are no references ";
if(species == null || species.trim().length() <=0) {msg = msg + "to show";}
else {msg = msg +"for "+species+".";}
javax.swing.JOptionPane.showMessageDialog(parent, msg, "No references", javax.swing.JOptionPane.INFORMATION_MESSAGE);
return;
}
ReferenceDisplayDialog dr = new ReferenceDisplayDialog(parent, true,
species, refKeys);
dr.setVisible(true);
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="private ReferenceDisplayDialog">
/** Display the references associated with a reaction product (chemical species)
* @author Ignasi Puigdomenech
*/
private class ReferenceDisplayDialog extends javax.swing.JDialog {
private javax.swing.JButton jButtonClose;
private javax.swing.JLabel jLabelRef;
private javax.swing.JPanel jPanel;
private javax.swing.JScrollPane jScrollPane;
private javax.swing.JTextArea jTextArea;
private java.awt.Dimension windowSize = new java.awt.Dimension(280,170);
private boolean loading = true;
//<editor-fold defaultstate="collapsed" desc="Constructor">
/** Creates new form ReferenceDisplayDialog */
/** Display a dialog with some references
* @param parent
* @param modal
* @param species the name of the species for which the reference will be displayed
* @param refKeys the citation keys for the references to display */
private ReferenceDisplayDialog(java.awt.Frame parent, boolean modal,
String species,
java.util.ArrayList<String> refKeys
) {
super(parent, modal);
initComponents();
if(species == null || species.trim().length() <=0) {
if(dbg) {System.out.println("Warning in \"ReferenceDisplayDialog\": empty species name.");}
species = "";
}
//--- Close window on ESC key
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE");
javax.swing.Action escAction = new javax.swing.AbstractAction() {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
closeWindow();
}};
getRootPane().getActionMap().put("ESCAPE", escAction);
//--- Alt-Q quit
javax.swing.KeyStroke altQKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altQKeyStroke,"ALT_Q");
getRootPane().getActionMap().put("ALT_Q", escAction);
//--- Alt-X eXit
javax.swing.KeyStroke altXKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altXKeyStroke,"ALT_X");
getRootPane().getActionMap().put("ALT_X", escAction);
//---- Title, etc
if(species.trim().length() > 0) {
this.setTitle("Reference(s) for \""+species+"\"");
} else {this.setTitle("Reference(s)");}
//---- Centre window on parent/screen
int left,top;
if(parent != null) {
left = Math.max(0,(parent.getX() + (parent.getWidth()/2) - this.getWidth()/2));
top = Math.max(0,(parent.getY()+(parent.getHeight()/2)-this.getHeight()/2));
} else {
left = Math.max(0,(screenSize.width-this.getWidth())/2);
top = Math.max(0,(screenSize.height-this.getHeight())/2);
}
this.setLocation(Math.min(screenSize.width-this.getWidth()-20,left),
Math.min(screenSize.height-this.getHeight()-20, top));
//----
if(refKeys == null || refKeys.isEmpty()) {
jScrollPane.setVisible(false);
jLabelRef.setText("(No reference(s))");
return;
}
if(dbg) {
System.out.println("References read from file:");
propertiesRefs.list(System.out);
}
jTextArea.setText("");
jTextArea.append(refsAsString(refKeys));
jTextArea.setCaretPosition(0);
jButtonClose.requestFocusInWindow();
windowSize = this.getSize();
loading = false;
} //constructor
//</editor-fold>
/** This method is called from within the constructor to
* initialize the form. */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel = new javax.swing.JPanel();
jLabelRef = new javax.swing.JLabel();
jButtonClose = new javax.swing.JButton();
jScrollPane = new javax.swing.JScrollPane();
jTextArea = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
addComponentListener(new java.awt.event.ComponentAdapter() {
@Override
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
jPanel.setLayout(new java.awt.BorderLayout());
jLabelRef.setText("Reference(s):");
jPanel.add(jLabelRef, java.awt.BorderLayout.WEST);
jButtonClose.setMnemonic('c');
jButtonClose.setText("Close");
jButtonClose.setMargin(new java.awt.Insets(1, 2, 1, 2));
jButtonClose.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonCloseActionPerformed(evt);
}
});
jPanel.add(jButtonClose, java.awt.BorderLayout.EAST);
getContentPane().add(jPanel, java.awt.BorderLayout.PAGE_START);
jTextArea.addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
jTextAreaKeyPressed(evt);
}
@Override
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextAreaKeyTyped(evt);
}
});
jTextArea.setLineWrap(true);
jTextArea.setWrapStyleWord(true);
jTextArea.setColumns(40);
jTextArea.setRows(9);
jScrollPane.setViewportView(jTextArea);
//jScrollPane.setPreferredSize(new java.awt.Dimension(450, 200));
getContentPane().add(jScrollPane, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="events">
private void jTextAreaKeyPressed(java.awt.event.KeyEvent evt) {
int ctrl = java.awt.event.InputEvent.CTRL_DOWN_MASK;
if(((evt.getModifiersEx() & ctrl) == ctrl) &&
(evt.getKeyCode() == java.awt.event.KeyEvent.VK_V
|| evt.getKeyCode() == java.awt.event.KeyEvent.VK_X)) {evt.consume(); return;}
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {closeWindow(); evt.consume(); return;}
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_TAB) {evt.consume(); return;}
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_DELETE) {evt.consume(); return;}
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_BACK_SPACE) {evt.consume();}
}
private void jTextAreaKeyTyped(java.awt.event.KeyEvent evt) {
evt.consume();
}
private void formWindowClosing(java.awt.event.WindowEvent evt) {
closeWindow();
}
private void formComponentResized(java.awt.event.ComponentEvent evt) {
if(loading || windowSize == null) {return;}
int x = this.getX(); int y = this.getY();
int w = this.getWidth(); int h = this.getHeight();
int nw = Math.max(w, Math.round((float)windowSize.getWidth()));
int nh = Math.max(h, Math.round((float)windowSize.getHeight()));
int nx=x, ny=y;
if(x+nw > screenSize.width) {nx = screenSize.width - nw;}
if(y+nh > screenSize.height) {ny = screenSize.height -nh;}
if(x!=nx || y!=ny) {this.setLocation(nx, ny);}
if(w!=nw || h!=nh) {this.setSize(nw, nh);}
}
private void jButtonCloseActionPerformed(java.awt.event.ActionEvent evt) {
closeWindow();
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="methods">
//<editor-fold defaultstate="collapsed" desc="closeWindow()">
private void closeWindow() {
this.dispose();
} // closeWindow()
// </editor-fold>
// </editor-fold>
} //class ReferenceDisplayDialog
// </editor-fold>
}
| 29,305 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
CSVparser.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibDataBase/src/lib/database/CSVparser.java | package lib.database;
/** Get a list of texts from a CSV line (= <i>comma</i>-separated values)<br>
* - <code>Separator</code> = either comma (,) or semicolon (;)<br>
* - <code>Quote</code> = either single (') or double (")<br>
* - To include <code>separators</code> in a token, enclose the token in <code>quotes</code>: "a,b"<br>
* - To include either trailing or preceeding white space, enclose the token in <code>quotes</code><br>
* - It is OK to include <code>quotes</code> in a text, if it has no <code>separator</code> in it,
* and if the <code>quote</code> is not the first character, for example: someone's<br>
* - To include <code>quotes</code> in a text that needs to be quoted
* (either because the <code>quote</code> is the first character, or because the text
* also contains a <code>separator</code>):<br>
* -- either have two quotes after each other, for example "he said, ""hello"","<br>
* -- or use single quotes to enclose double quotes, as in 'a,b";', or use double
* quotes to enclose a single quote: "this is 'ok',".
* <br>
* Copyright (C) 2014 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class CSVparser {
//adapted from
// http://publib.boulder.ibm.com/infocenter/pim/v6r0m0/topic/com.ibm.wpc.dev.doc/code/java/wpc_con_CSVParserjava.html
private static final String nl = System.getProperty("line.separator");
/** Get a list of texts from a CSV line (= <i>comma</i>-separated values)<br>
* - <code>Separator</code> = either comma (,) or semicolon (;)<br>
* - <code>Quote</code> = either single (') or double (")<br>
* - To include <code>separators</code> in a token, enclose the token in <code>quotes</code>: "a,b"<br>
* - To include either trailing or preceeding white space, enclose the token in <code>quotes</code><br>
* - It is OK to include <code>quotes</code> in a text, if it has no <code>separator</code> in it,
* and if the <code>quote</code> is not the first character, for example: someone's<br>
* - To include <code>quotes</code> in a text that needs to be quoted
* (either because the <code>quote</code> is the first character, or because the text
* also contains a <code>separator</code>):<br>
* .-. either have two quotes after each other, for example "said, ""hello"","<br>
* .-. or use single quotes to enclose double quotes, as in 'a,b";', or use double
* quotes to enclose a single quote: "this is 'ok',"
* @param line to be parsed into tokens (Strings)
* @return a list of Strings
* @see CSVparser#splitLine_N splitLine_N
* @throws CSVdataException */
public static java.util.ArrayList<String> splitLine(String line) throws CSVdataException {
if(line == null) {return null;}
java.util.ArrayList<String> al = new java.util.ArrayList<String>();
OneRes or = new OneRes();
int pos = 0;
while (pos < line.length()) {
pos = findNextComma(pos, line, or);
al.add(or.oneRes);
//System.out.println("token "+al.size()+" = "+al.get(al.size()-1)+" pos = "+pos+" ("+line.length()+")");
pos++;
} //while
if(line.length() > 0 &&
(line.charAt(line.length() - 1) == ',' || line.charAt(line.length() - 1) == ';'))
{al.add("");}
return al;
} //splitLine(line)
/** Get a list of texts from a CSV line (= <i>comma</i>-separated values)<br>
* @param line to be parsed into tokens (Strings)
* @param n the size of the returned array list. If not enough data are found in <code>line</code>
* then empty Strings are added. If too many data are found, then the the remainder of the line
* is returned in the last item of the array list.
* @return array list of Strings
* @see CSVparser#splitLine splitLine
* @see CSVparser#splitLine_1 splitLine_1
* @throws CSVdataException */
public static java.util.ArrayList<String> splitLine_N(String line, int n) throws CSVdataException {
if(line == null || n <=0) {return null;}
java.util.ArrayList<String> al = new java.util.ArrayList<String>(n);
if(n == 1) {al.add(splitLine_1(line)); return al;}
OneRes or = new OneRes();
int pos = 0;
int size = 0;
while (pos < line.length()) {
pos = findNextComma(pos, line, or);
al.add(or.oneRes); size++;
pos++;
if(size >= n) {break;}
} //while
if(size <= (n-1)) {for(int i =size; i < n; i++) {al.add("");}}
return al;
} //splitLine_N(line, n)
/** Get the first text from a CSV line (= <i>comma</i>-separated values)<br>
* @param line to be parsed
* @return the first String token from the line
* @see CSVparser#splitLine splitLine
* @see CSVparser#splitLine_N splitLine_N
* @throws CSVdataException */
public static String splitLine_1(String line) throws CSVdataException {
if(line == null) {return null;}
OneRes or = new OneRes();
findNextComma(0, line, or);
return or.oneRes;
} //splitLine_N(line, n)
//<editor-fold defaultstate="collapsed" desc="private">
private static int findNextComma(int p, String line, OneRes or) throws CSVdataException {
char c;
int i,j,k;
or.oneRes = "";
c = line.charAt(p);
// remove white space at the beginning
while (Character.isWhitespace(c)) {
p++;
if(p>=line.length()) {or.oneRes = ""; return p;}
c = line.charAt(p);
}
//System.out.println("findNextComma 1st char = ("+c+") p="+p);
if(c == ',' || c == ';') { // --- empty field
or.oneRes = "";
return p;
}
if(c != '"' && c != '\'') { // --- not a quote char
// find next separator
i = line.length();
j = line.indexOf(',', p);
k = line.indexOf(';', p);
if(j > -1 && j < i) {i = j;}
if(k > -1 && k < i) {i = k;}
or.oneRes = line.substring(p, i).trim();
return i;
}
k = p;
char quote = c; // --- starts with quote (either " or ')
p++;
StringBuilder sb = new StringBuilder(200);
while (true) {
if(p >= line.length()) {
throw new CSVdataException("Error: missing closing quote in line"+nl+" "+line+nl+
"in text: "+quote+sb.toString()+" (starting at position "+(k+1)+")");
}
c = line.charAt(p);
p++;
//System.out.println(" p="+p+" char = ("+c+")");
// if this is not a quote
if(c != quote) {sb.append(c); continue;}
// this is a quote and last char -> ok
if(p == line.length()) {or.oneRes = sb.toString(); return p;}
c = line.charAt(p);
p++;
//System.out.println(" p="+p+" char = ("+c+")");
// "" -> just get one
if(c == quote) {
sb.append(quote);
continue;
}
// remove white space after a closing quote
while (Character.isWhitespace(c)) {
if(p>=line.length()) {or.oneRes = sb.toString(); return p;}
c = line.charAt(p);
p++;
}
//System.out.println(" p="+p+" char = ("+c+")");
// closing quote followed by separator -> return
if(c == ',' || c == ';') {
or.oneRes = sb.toString();
return p - 1;
}
throw new CSVdataException("Unexpected token found in line:"+nl+" "+line+nl+
"token: "+quote+sb.toString()+quote+" (starting at position "+(k+1)+")");
} //while
} //findNextComma(p)
/** A class of objects that contain <code>String oneRes</code>.
* May be used as pointer when calling procedures. */
private static class OneRes {
/** The only field of class "OneRes"; the objects of this class may be
* used as pointers to Strings when calling procedures. */
String oneRes = "";
/** creates an object that contains <code>String oneRes</code>.
* A reference to this instance can be used when calling procedures */
public OneRes() {}
}
//</editor-fold>
public static class CSVdataException extends Exception {
public CSVdataException() {super();}
public CSVdataException(String txt) {super(txt);}
} //AddDataInternalException
}
| 9,248 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
README_javaHelp.txt | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Chem_Diagr_Help/README_javaHelp.txt | Chemical Equilibrium Diagrams
-----------------------------
This software has been developed using Netbeans (v.8.0.2 portable).
The help system is found in folder "Chem_Diagr_Help", and it uses
JavaHelp version 2. The java source-code is in sub-folder
"src\chemicalDiagramsHelp", while the help contents is located
in sub-folder "src\html". The JavaHelp system requires the also
following files in sub-folder "src\javahelp":
- helpset.hs
- index.xml
- map.jhm
- toc.xml
In order to add "search" functionality, it is necessary to create
search indexes with "jhindexer". This may be performed with the
script "!_index.cmd". The log-file "indexer_output.log" is created.
If the log-file is newer than the help-contents in "src\html", then
the re-indexing is not needed. The search indexes are stored in
sub-folder "src\javahelp\JavaHelpSearch".
For Chem_Diagr_Help it is convenient to include the help contents
in the jar-file, so that the help system is a single file.
To package all dependent lib/jars and other files (the help
contents etc) into a single jar-file, the file "build.xml" has been
modified by adding a target named "Package-for-Store". To build
this target, select the "Files" tab (next to the "Projects" tab),
then select the file "build.xml", right-click, and on the menu
that appears select "Run Target" and "Package-for-Store".
Netbeans will then generate the sub-folder "store" containing
"Chem_Diagr_Help.jar" which includes the java program and all
dependent libraries, the help contents, the search indexes, etc.
Changes in the help contents
============================
If you change an image or add or change a htm-file, then you
will also need to change:
- The map list ("map.jhm") which contains all the links used in the
help contents.
- The table of contents (file "toc.xml") that appears on the left
panel of the help window at start.
- The index that appears on the left panel when the user selects
the index tab (file "index.xml").
- Update the search indexes with the script "!_index.cmd" mentioned
above.
- Update the "store" jar-file with the added or changed files.
This may be performed with script "!_update_store.cmd".
| 2,240 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
ClassLocator.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Chem_Diagr_Help/src/chemicalDiagramsHelp/ClassLocator.java | package chemicalDiagramsHelp;
/** Adapted from http://jroller.com/eu/entry/looking_who_is_calling
* <br>
* Copyright (C) 2014-2018 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class ClassLocator extends SecurityManager {
/** Adapted by Ignasi Puigdomenech<br>
* from http://jroller.com/eu/entry/looking_who_is_calling<br>
* To use:<pre>
* public class Demo {
* public static void main(String[] args) {
* A.aa();
* }
* }
* class A {
* static void aa() {
* System.err.println(ClassLocator.getCallerClass().getName());
* }
* }</pre>
* This method (getCallerClass()) is about six times faster than to do:<pre>
* Throwable stack = new Throwable();
* stack.fillInStackTrace();
* StackTraceElement[] stackTE = stack.getStackTrace();
* String msg = stackTE[1].getClassName();</pre>
* @return the class that called this method
*/
public static Class getCallerClass() {
Class[] classes = new ClassLocator().getClassContext();
if(classes.length >0) {return classes[classes.length-1];}
return null;
}
public static String getCallerClassName() {
Class[] classes = new ClassLocator().getClassContext();
if(classes.length >0) {
int i = Math.min(classes.length-1, 2);
return classes[i].getName();
}
return null;
}
} | 1,948 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
OneInstance.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Chem_Diagr_Help/src/chemicalDiagramsHelp/OneInstance.java | package chemicalDiagramsHelp;
/** The method <b>findOtherInstance</b> returns true if another instance
* of the application is already running in another JVM.
* <p>
* A server socket is used. The application tries to connect to the socket.
* If a server is not found, the socket is free and the server socket is
* constructed. If a server is found and a connection is made, it means that
* the application is already running. In that case the command line arguments
* are sent to other instance.
* <p>
* Modify the code after lines containing <code>"==="</code>.
* <p>
* Use "getInstance()" instead of creating a new OneInstance()!
* <p>
* Copyright (C) 2014-2018 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class OneInstance {
private static OneInstance one = null;
private static final String knockKnock = "Ett skepp kommer lastad";
private boolean dbg;
private int port;
private java.net.ServerSocket serverSocket = null;
private java.net.Socket socket;
private java.io.BufferedReader socketIn;
private java.io.PrintWriter socketOut;
private String whosThere;
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
/** Find out if another instance of the application is already running in another JVM.
* <p>
* A server socket is used. The application tries to connect to the socket.
* If a server is not found, the socket is free and the server socket is
* constructed. If a server is found and a connection is made, it means that
* the application is already running. In that case the command line arguments
* are sent to other instance.
* <p>
* Modify the code after lines containing <code>"==="</code>.
* <p>
* Use "getInstance()" instead of creating a new OneInstance()!
* @param args the command line arguments to the main method of the application.
* The arguments are sent to the other instance through the server socket.
* Not used if no other instance of the application is found.
* @param portDef a port to search for a server socket.
* If no other application is found, at least five additional sockets are tried.
* @param prgName the application's name, used for message and error reporting.
* @param debg true if performance messages are wished.
* @return true if another instance is found, false otherwise. */
public boolean findOtherInstance(
final String[] args,
final int portDef,
final String prgName,
final boolean debg) {
if(one != null) {
String msg;
if(prgName != null && prgName.trim().length() >0) {msg = prgName;} else {msg = "OneInstance";}
if(debg) {HelpWindow.OutMsg("findOtherInstance already running.");}
return false;
} else {
one = this;
}
dbg = debg;
String progName;
if(prgName != null && prgName.trim().length() >0) {progName = prgName;} else {progName = "OneInstance";}
whosThere = progName;
// loop though sockets numbers, if a socket is busy check if it is
// another instance of this application
//<editor-fold defaultstate="collapsed" desc="first loop">
port = portDef;
int portNbrMax = portDef + 5;
java.net.InetAddress address = null;
do{
// note: testing a client socket (creating a stream socket and connecting it)
// would be much more time consuming
try{
serverSocket = new java.net.ServerSocket(port);
if(dbg){HelpWindow.OutMsg("socket "+port+" is not used.");}
serverSocket.close();
serverSocket = null;
port++;
} catch (java.net.BindException ex) {
if(dbg){HelpWindow.OutMsg("socket "+port+" busy. Another instance already running?");}
if(address == null) {
try {
address = java.net.InetAddress.getLocalHost();
if(dbg){HelpWindow.OutMsg("Local machine address: "+address.toString());}
}
catch (java.net.UnknownHostException e) {
HelpWindow.ErrMsg(e.getMessage()+" using getLocalHost().");
address = null;
} //catch
}
if (!isOtherInstance(address, port)) {
//Not another instance. It means some software is using
// this socket port number; continue looking...
if(socketOut != null) {socketOut.close(); socketOut = null;}
if(socketIn != null) {
try{socketIn.close();} catch (java.io.IOException ioe) {}
socketIn = null;
}
socket = null;
port++;
} else {
//Another instance of this software is already running:
// send args[] and end the program (exit from "main")
sendArgsToOtherInstance(args);
return true;
}
} catch (java.io.IOException ex) { // there should be no error...
HelpWindow.ErrMsg(ex.getMessage()+nl+" while creating a stream Socket.");
break;
} // catch
} while (port < portNbrMax); // do-while
if(socketOut != null) {socketOut.close(); socketOut = null;}
if(socketIn != null) {
try{socketIn.close();} catch (java.io.IOException ioe) {}
socketIn = null;
}
socket = null;
//address = null;
//</editor-fold>
// Another instance not found: create a server socket on the first free port
//<editor-fold defaultstate="collapsed" desc="create server socket">
port = portDef;
do{
try{
serverSocket = new java.net.ServerSocket(port);
if(dbg){HelpWindow.OutMsg("Created server socket on port "+port);}
break;
} catch (java.net.BindException ex) {
if(dbg){HelpWindow.OutMsg("socket "+port+" is busy.");}
port++;
} //Socket busy
catch (java.io.IOException ex) { // there should be no error...
HelpWindow.ErrMsg(ex.getMessage()+nl+" while creating a Server Socket.");
break;
}
} while (port < portNbrMax); // do-while
//</editor-fold>
if(port == portNbrMax) {
HelpWindow.ErrMsg("Error: could not create a server socket.");
return false;
}
// A Server Socket has been created.
// Wait for new connections on the serverSocket on a separate thread.
// The program will continue execution simultaenously...
//<editor-fold defaultstate="collapsed" desc="accept clients thread">
Thread t = new Thread(){@Override public void run(){
while(true){
final java.net.Socket client;
try{ // Wait until we get a client in serverSocket
if(dbg){HelpWindow.OutMsg("waiting for a connection to serverSocket("+port+").");}
// this will block until a connection is made:
client = serverSocket.accept();
}
catch (java.net.SocketException ex) {break;}
catch (java.io.IOException ex) {
HelpWindow.ErrMsg(ex.getMessage()+nl+" Accept failed on server port: "+port);
break; //while
}
//Got a connection, wait for lines of text from the new connection (client)
//<editor-fold defaultstate="collapsed" desc="deal with a client thread">
if(dbg){HelpWindow.OutMsg("connection made to serverSocket in port "+port);}
Thread t = new Thread(){@Override public void run(){
String line;
boolean clientNewInstance = false;
boolean connected = true;
java.io.BufferedReader in = null;
java.io.PrintWriter out = null;
try{
client.setSoTimeout(3000); // avoid socket.readLine() lock
in = new java.io.BufferedReader(new java.io.InputStreamReader(client.getInputStream()));
out = new java.io.PrintWriter(client.getOutputStream(), true);
if(dbg){HelpWindow.OutMsg("while (connected)");}
while(connected){
if(dbg){HelpWindow.OutMsg("(waiting for text line from client)");}
// wait for a line of text from the client
// note: client.setSoTimeout(3000) means
// SocketTimeoutException after 3 sec
line = in.readLine();
if(line == null) {break;}
if(dbg){HelpWindow.OutMsg("got text line from client (in port "+port+"): "+line);}
// is this another instance asking who am I?
if(line.toLowerCase().equals(knockKnock.toLowerCase())) {
// yes: another instance calling!
// === add code here to bring this instance to front ===
// --- for HelpWindow.java:
if(HelpWindow.getInstance() != null) {
HelpWindow.getInstance().bringToFront();
if(dbg) {HelpWindow.OutMsg("bringToFront()");}
}
// --- for Spana:
//if(SpanaFrame.getInstance() != null) {SpanaFrame.getInstance().bringToFront();}
// --- for Database:
//if(FrameDBmain.getInstance() != null) {FrameDBmain.getInstance().bringToFront();}
// ---
//answer to client with program identity
if(dbg){HelpWindow.OutMsg("sending text line to client (at port "+port+"): "+whosThere);}
out.println(whosThere);
clientNewInstance=true;
} else {// line != knockKnock
if(clientNewInstance) {
// === add code here to deal with the command-line arguments ===
// from the new instance sendt to this instance
// --- for HelpWindow.java:
if(HelpWindow.getInstance() != null) {
HelpWindow.getInstance().bringToFront();
HelpWindow.getInstance().setHelpID(line);
}
// --- for Spana:
//if(SpanaFrame.getInstance() != null) {SpanaFrame.getInstance().dispatchArg(line);}
// --- for Database:
//if(FrameDBmain.getInstance() != null) {FrameDBmain.getInstance().dispatchArg(line);}
// ---
} else { //not clientNewInstance
if(dbg){HelpWindow.ErrMsg("Warning: got garbage in port "+port+" from another application; text line = \""+line+"\"");}
connected = false; // close the connection
}
} //line = knockKnock ?
} // while(connected)
out.close(); out = null;
in.close(); in = null;
client.close();
} catch (java.io.IOException ioe) {
HelpWindow.ErrMsg(ioe.getMessage()+nl+" Closing socket connection in port "+port);
} finally {
if(dbg){HelpWindow.OutMsg("Connection to serverSocket("+port+") closed ");}
if(out != null) {out.close();}
try{ if(in != null) {in.close();} client.close(); }
catch (java.io.IOException ioe) {}
}
}};
t.start(); // "start" returns inmediately without waiting.
//</editor-fold>
// wait for next connection....
} // while(true)
}};
t.start(); // "start" returns inmediately without waiting.
//</editor-fold>
//-------------------------------------------------------------
// Finished checking for another instance
//-------------------------------------------------------------
return false; // found no other instance
}
//<editor-fold defaultstate="collapsed" desc="isOtherInstanceInSocket">
// -------------------------------
/** Checking for another instance:<br>
* The first instance of this program opens a server socket connection and
* listens for other instances of this program to send messages. The
* first instance also creates a "lock" file containing the socket number.
* This method tries to send a message to a socket, and checks if the
* response corresponds to that expected from the first instance of this
* application. If the response is correct, it returns true.
* @param port the socket number to try
* @return <code>true</code> if another instance of this program is
* listening at this socket number; <code>false</code> if either
* an error occurs, no response is obtained from this socket within one sec,
* or if the answer received is not the one expected from the first instance.
*/
private boolean isOtherInstance(final java.net.InetAddress address, final int port) {
if (port <= 0) {return false;}
if(dbg){HelpWindow.OutMsg("isOtherInstance("+port+") ?");}
// Create socket connection
String line;
boolean ok;
try{
socket = new java.net.Socket(address, port);
socket.setSoTimeout(1000); // avoid socket.readLine() lock
socketOut = new java.io.PrintWriter(socket.getOutputStream(), true);
socketIn = new java.io.BufferedReader(
new java.io.InputStreamReader(socket.getInputStream()));
//Send data over socket
if(dbg){HelpWindow.OutMsg("Sending text:\""+knockKnock+"\" to port "+port);}
socketOut.println(knockKnock);
//Receive text from server.
if(dbg){HelpWindow.OutMsg("Reading answer from socket "+port);}
// note: socket.setSoTimeout(1000) means
// SocketTimeoutException after 1 sec
try{
line = socketIn.readLine();
if(dbg){HelpWindow.OutMsg("Text received: \"" + line + "\" from port "+port);}
} catch (java.io.IOException ex){
line = null;
HelpWindow.ErrMsg(ex.getMessage()+nl+" in socket("+port+").readLine()");
} //catch
// did we get the correct answer?
if(line != null && line.toLowerCase().startsWith(whosThere.toLowerCase())) {
if(dbg){HelpWindow.OutMsg("isOtherInstance("+port+") = true");}
ok = true;
} else {
if(dbg){HelpWindow.OutMsg("isOtherInstance("+port+") = false");}
ok = false;
}
} catch (java.io.IOException ex) {
HelpWindow.OutMsg(ex.getMessage()+", isOtherInstance("+port+") = false");
ok = false;
}
return ok;
// -------------------------------------
} // isOtherInstance(port)
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="sendArgsToOtherInstance">
// -------------------------------
/** Checking for another instance:<br>
* The first instance of this program opens a server socket connection and
* listens for other instances of this program to send messages. The
* first instance also creates a "lock" file containing the socket number.
* This method assumes that this is a "2nd" instance of this program
* and it sends the command-line arguments from this instance to the
* first instance, through the socket connetion.
*
* <p>The connection is closed and the program ends after sending the
* arguments.</p>
*
* @param args <code>String[]</code> contains the command-line
* arguments given to this instance of the program.
*/
private void sendArgsToOtherInstance(String args[]) {
if(socketOut == null) {return;}
if(args != null && args.length >0) {
for(String arg : args) {
if(dbg){HelpWindow.OutMsg("sending command-line arg to other instance: \"" + arg + "\"");}
socketOut.println(arg);
} // for arg : args
} // if args.length >0
try {
if(socketIn != null) {socketIn.close(); socketIn = null;}
if(socketOut != null) {socketOut.close(); socketOut = null;}
socket = null;
} catch (java.io.IOException ex) {
HelpWindow.OutMsg(ex.getMessage()+", while closing streams.");
}
// --------------------------------
} //sendArgsToOtherInstance(args[])
// </editor-fold>
/** Use this method to get the instance of this class to start
* a the server socket thread, instead of constructing a new object.
* @return an instance of this class
* @see OneInstance#endCheckOtherInstances() endCheckOtherInstances */
public static OneInstance getInstance() {return one;}
/** Stops the server socket thread. */
public static void endCheckOtherInstances() {
if(one != null) {
try{one.serverSocket.close(); one.serverSocket = null; one = null;} catch (java.io.IOException ex) {}
}
}
}
| 18,500 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
ExternalLinkContentViewerUI.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Chem_Diagr_Help/src/chemicalDiagramsHelp/ExternalLinkContentViewerUI.java | package chemicalDiagramsHelp;
/** a UI subclass that will open external links (website or ftp links)
* in an external browser.
* Adapted from examples in the internet.
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class ExternalLinkContentViewerUI extends javax.help.plaf.basic.BasicContentViewerUI {
private final javax.swing.JComponent me;
public ExternalLinkContentViewerUI(javax.help.JHelpContentViewer x) {
super(x);
me = (javax.swing.JComponent) x;
} // constructor
public static javax.swing.plaf.ComponentUI createUI(javax.swing.JComponent x) {
return new ExternalLinkContentViewerUI((javax.help.JHelpContentViewer)x);
} // createUI
@Override
public void hyperlinkUpdate(javax.swing.event.HyperlinkEvent he){
if(he.getEventType()== javax.swing.event.HyperlinkEvent.EventType.ACTIVATED){
try{
final java.net.URL u = he.getURL();
if(u != null) {
if(u.getProtocol().equalsIgnoreCase("http")
||u.getProtocol().equalsIgnoreCase("ftp")) {
Thread t = new Thread() {@Override public void run(){
BareBonesBrowserLaunch.openURL(u.toString(),me);
}};
t.start(); // Note: t.start() returns inmediately.
return;
}
}
} catch(Throwable t){}
} // if(eventType.ACTIVATED)
super.hyperlinkUpdate(he);
} // hyperlinkUpdate
//<editor-fold defaultstate="collapsed" desc="class BareBonesBrowserLaunch">
/**
* <b>Bare Bones Browser Launch for Java</b><br>
* Utility class to open a web page from a Swing application
* in the user's default browser.<br>
* Supports: Mac OS X, GNU/Linux, Unix, Windows XP/Vista/7<br>
* Example Usage:<code><br>
* String url = "http://www.google.com/";<br>
* BareBonesBrowserLaunch.openURL(url);<br></code>
* Latest Version: <a href=http://centerkey.com/java/browser>centerkey.com/java/browser</a><br>
* Author: Dem Pilafian<br>
* WTFPL -- Free to use as you like
* @author Dem Pilafian
* @version 3.2, October 24, 2010
*/
private static class BareBonesBrowserLaunch {
static final String[] browsers = { "x-www-browser", "google-chrome",
"firefox", "opera", "epiphany", "konqueror", "conkeror", "midori",
"kazehakase", "mozilla", "chromium" }; // modified by Ignasi (added "chromium")
static final String errMsg = "Error attempting to launch web browser";
/**
* Opens the specified web page in the user's default browser
* @param url A web address (URL) of a web page (ex: "http://www.google.com/")
*/
public static void openURL(String url, javax.swing.JComponent parent) { // modified by Ignasi (added "parent")
try { //attempt to use Desktop library from JDK 1.6+
Class<?> d = Class.forName("java.awt.Desktop");
d.getDeclaredMethod("browse", new Class<?>[] {java.net.URI.class}).invoke(
d.getDeclaredMethod("getDesktop").invoke(null),
new Object[] {java.net.URI.create(url)});
//above code mimicks: java.awt.Desktop.getDesktop().browse()
}
catch (Exception ignore) { //library not available or failed
String osName = System.getProperty("os.name");
try {
if (osName.startsWith("Mac OS")) {
Class.forName("com.apple.eio.FileManager").getDeclaredMethod(
"openURL", new Class<?>[] {String.class}).invoke(null,new Object[] {url});
}
else if (osName.startsWith("Windows"))
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
else { //assume Unix or Linux
String browser = null;
for (String b : browsers)
if (browser == null && Runtime.getRuntime().exec(new String[]
{"which", b}).getInputStream().read() != -1)
Runtime.getRuntime().exec(new String[] {browser = b, url});
if (browser == null)
throw new Exception(java.util.Arrays.toString(browsers));
}
}
catch (Exception e) {
HelpWindow.ErrMsg(errMsg + "\n" + e.getMessage()); // added by Ignasi
javax.swing.JOptionPane.showMessageDialog(parent, errMsg + "\n" + e.getMessage(), // modified by Ignasi (added "parent")
"Chemical Equilibrium Diagrams", javax.swing.JOptionPane.ERROR_MESSAGE); // added by Ignasi
}
}
}
}
//</editor-fold>
}
| 5,412 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
ProgramConf.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Chem_Diagr_Help/src/chemicalDiagramsHelp/ProgramConf.java | package chemicalDiagramsHelp;
/** Class to store "configuration" information about the DataBase and Spana programs.
* These data are stored in the configuration file.
* The class is used to retrieve data in diverse methods
*
* Copyright (C) 2015-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class ProgramConf {
/** The name of the program, either "Spana" or "DataBase" */
public String progName = null;
/** true if debug printout is to be made. Messages and errors are directed
* to a message frame */
public boolean dbg = false;
/** <code>true</code> if the ini-file is to be saved (or read) in the
* applications path only, for example if running from a USB-memory
* (or a portable drive). Note: if the application directory is
* write-protected, then if this parameter is <code>true</code> an ini-file
* will NOT be written, while if <code>false</code> the ini-file will be written
* elsewhere (for example in the user's home directory).*/
public boolean saveIniFileToApplicationPathOnly = false;
private static final String nl = System.getProperty("line.separator");
public ProgramConf() {dbg = false; saveIniFileToApplicationPathOnly = false;}
public ProgramConf(String pgName) {
progName = pgName;
dbg = false;
saveIniFileToApplicationPathOnly = false;
}
//<editor-fold defaultstate="collapsed" desc="Cfg-file">
/** Read program options (configuration file)<br>
* Exceptions are reported only to the console:
* The program's functionality is not affected if this method fails
* @param fileNameCfg
* @param pc */
public static void read_cfgFile(java.io.File fileNameCfg, ProgramConf pc) {
if(fileNameCfg == null) {HelpWindow.ErrMsg("Error: fileNameCfg = null in routine \"read_cfgFile\""); return;}
if(pc == null) {HelpWindow.ErrMsg("Error: pc = null in routine \"read_cfgFile\""); return;}
java.util.Properties cfg = new java.util.Properties();
java.io.FileInputStream fis = null;
java.io.BufferedReader r = null;
boolean loadedOK = false;
try {
fis = new java.io.FileInputStream(fileNameCfg);
r = new java.io.BufferedReader(new java.io.InputStreamReader(fis,"UTF8"));
cfg.load(r);
loadedOK = true;
} //try
catch (java.io.FileNotFoundException e) {
HelpWindow.OutMsg("Warning: file Not found: \""+fileNameCfg.getPath()+"\""+nl+
" using default program options.");
write_cfgFile(fileNameCfg, pc);
return;
} //catch FileNotFoundException
catch (java.io.IOException e) {
HelpWindow.ErrMsg(e.getMessage()+nl+
" while loading config.-file:"+nl+
" \""+fileNameCfg.getPath()+"\"");
loadedOK = false;
} // catch Exception
try {if(r != null) {r.close();} if(fis != null) {fis.close();}}
catch (java.io.IOException e) {
HelpWindow.ErrMsg(e.getMessage()+nl+
" while closing config.-file:"+nl+
" \""+fileNameCfg.getPath()+"\"");
} // catch
if(loadedOK) {
try {
HelpWindow.OutMsg("Reading file: \""+fileNameCfg.getPath()+"\"");
if(cfg.getProperty("Debug") != null &&
cfg.getProperty("Debug").equalsIgnoreCase("true")) {
pc.dbg = true;
}
pc.saveIniFileToApplicationPathOnly = cfg.getProperty("SaveIniFileToApplicationPathOnly") != null &&
cfg.getProperty("SaveIniFileToApplicationPathOnly").equalsIgnoreCase("true");
}
catch (Exception ex) {
HelpWindow.ErrMsg(ex.getMessage()+nl+
" while reading file: \""+fileNameCfg.getPath()+"\"");
write_cfgFile(fileNameCfg, pc);
}
} // if (loadedOK)
} // read_cfgFile()
/** Write program options (configuration file).<br>
* Exceptions are reported to the console. */
private static void write_cfgFile(java.io.File fileNameCfg, ProgramConf pc) {
java.io.FileOutputStream fos = null;
java.io.Writer w = null;
try {
fos = new java.io.FileOutputStream(fileNameCfg);
w = new java.io.BufferedWriter(new java.io.OutputStreamWriter(fos,"UTF8"));
}
catch (java.io.IOException e) {
HelpWindow.ErrMsg(e.getMessage()+nl+
" trying to write config.-file: \""+fileNameCfg.toString()+"\"");
try{if(w != null) {w.close();} if(fos != null) {fos.close();}}
catch (Exception e1) {
HelpWindow.ErrMsg(e1.getMessage()+nl+
" trying to close config.-file: \""+fileNameCfg.toString()+"\"");
}
return;
} //catch
try{
w.write(
"# Next parameter should be \"true\" if running from a USB-memory"+nl+
"# (or a portable drive): then the ini-file will ONLY be saved in"+nl+
"# the application directory. If the application directory"+nl+
"# is write-protected, then no ini-file will be written."+nl+
"# If not \"true\" then the ini-file is saved in one of the"+nl+
"# following paths (depending on which environment variables"+nl+
"# are defined and if the paths are not write-protected):"+nl+
"# The installation directory"+nl+
"# %HOMEDRIVE%%HOMEPATH%"+nl+
"# %HOME%"+nl+
"# the user's home directory (system dependent)."+nl+
"# Except for the installation directory, the ini-file will"+nl+
"# be writen in a sub-folder named \".config\\eq-diagr\"."+nl);
if(pc.saveIniFileToApplicationPathOnly) {
w.write("SaveIniFileToApplicationPathOnly=true"+nl);
} else {
w.write("SaveIniFileToApplicationPathOnly=false"+nl);
}
w.write(
"# Change next to \"true\" to output debugging information"+nl+
"# to the messages window."+nl);
if(pc.dbg) {w.write("Debug=true"+nl);}
else {w.write("Debug=false"+nl);}
w.close(); fos.close();
if(pc.dbg) {HelpWindow.OutMsg("Written: \""+fileNameCfg.toString()+"\"");}
}
catch (Exception ex) {
HelpWindow.ErrMsg(ex.getMessage()+nl+
" trying to write config.-file: \""+fileNameCfg.toString()+"\"");
}
} // write_cfgFile()
//</editor-fold>
} | 7,126 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
HelpWindow.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Chem_Diagr_Help/src/chemicalDiagramsHelp/HelpWindow.java | package chemicalDiagramsHelp;
/** This java program will display a JavaHelp helpset.
* I may be run as stand alone to provide help information, or it can
* act as a "slave" of another application. If another "master" application
* (e.g. Spana or DataBase) wants to display help using this HelpWindow, it can:
* <ul><li> either start another independent Java Virtual Machine
* (java -jar jarFileName.jar "helpID"); or<br>
* <li> use JarClassLoader to execute the main method with the "helpID" as argument; or<br>
* <li> if this jar-file is made accessible through CLASSPATH at run-time
* (and as a library at compile time), then the "master" application can
* have direct access to the public methods in order to bring the help
* window forward and to change the "help ID". For example:</ul>
*<pre> chemicalDiagramsHelp.HelpWindow hw = null;
* hw = chemicalDiagramsHelp.HelpWindow.getInstance();
* if(hw == null || hw.hFrame == null) {
* String[] argsHW = {"M_Working_with_htm"};
* chemicalDiagramsHelp.HelpWindow.main(argsHW);}
* else {
* hw.hFrame.setVisible(true);
* hw.setHelpID("M_Working_with_htm");}</pre>
* The helpset to display must be found either:<ul>
* <li> first the file "javahelp/helpset.hs" (external to the jar-file) is searched.
* <li> if the external helpset is not found, then the jar-file of this program
* is searched: first in a location specified by the entry "Helpset" in the
* jar-file's manifest ("META-INF/MANIFEST.MF").
* <li> if there is no Manifest-entry in the jar file of this program,
* then the helpset is searched inside the jar-file at: "javahelp/helpset.hs".</ul>
* Many ideas taken from the QuickHelp class available at www.halogenware.com
* <br>
* Copyright (C) 2015-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class HelpWindow {
private static final String VERS = "2020-June-10";
private final ProgramConf pc;
private static boolean started = false;
/** Because the program checks for other instances and exits if there is
* another instance, "helpWindow" is a reference to the only instance of
* this class. Used for example in "main" to decide if an object instance
* needs to be created */
private static HelpWindow helpWindow;
private static String jarName = null;
/** a reference to the helpWindow frame */
public javax.swing.JFrame hFrame = null;
private javax.help.HelpSet hs = null;
javax.help.HelpBroker hb;
private javax.swing.JPanel jPanel_font_size;
private javax.swing.JComboBox jComboBox_font;
private javax.swing.JComboBox jComboBox_size;
private javax.swing.JLabel jLabel_status;
private boolean isSlave = false;
// variables used for user messages:
private String helpSetFileNameWithPath;
private java.io.File fileINI = null;
private static final String FileINI_NAME = ".ChemDiagrHelp.ini";
private int left;
private int top;
private int width;
private int height;
private String hbFont;
private int hbSize;
private int windowState;
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
private static final String line = "-----";
private static final String SLASH = java.io.File.separator;
//<editor-fold defaultstate="collapsed" desc="main">
/** Displays a JavaHelp system
* @param args the command line arguments: at most two arguments are read.
* If one of the first two arguments is "-dbg" or "/dbg" then debug information
* is printed. The other argument may be a "helpID" from the helpSet. */
public static void main(String args[]) {
boolean dbg = false;
// --- debug?
if(args.length >0) {
if(args[0].equalsIgnoreCase("-dbg") || args[0].equalsIgnoreCase("/dbg")) {
dbg = true;
args[0] = "";
//if 2 arguments given: move the second argument to be the first
if(args.length >1) {args[0] = args[1]; args[1] = "";}
}
if(args.length >1) {
if(args[1].equalsIgnoreCase("-dbg") || args[1].equalsIgnoreCase("/dbg")) {
dbg = true; args[1] = "";
}
}
}
String progName = HelpWindow.class.getPackage().getName();
if(dbg) {System.out.println(line+" "+progName+" - (version "+VERS+") - Starting...");}
try { Class c = Class.forName("javax.help.HelpSet"); }
catch (ClassNotFoundException ex) {
String t = "Error - file \"jh.jar\" not found. Can Not show help.";
OutMsg(t);
ErrMsgBx mb = new ErrMsgBx(t,progName);
return;
}
//---- is there another instance already running?
if(new OneInstance().findOtherInstance(args, 56100, progName, dbg)) {
OutMsg("Already running.");
return;
}
// ---- get jar file name
java.util.jar.JarFile jarFile = getRunningJarFile();
if(jarFile != null) {
jarName = getRunningJarFile().getName();
java.io.File jf = new java.io.File(jarName);
jarName = jf.getName();
}
if(jarName != null) {
if(jarName.toLowerCase().endsWith(".jar"))
{progName = jarName.substring(0,jarName.lastIndexOf("."));}
else {progName = jarName;}
}
//---- create a local instance of ProgramConf.
// Contains information read from the configuration file.
final ProgramConf pc = new ProgramConf(progName);
pc.dbg = dbg;
// --- set SystemLookAndFeel
try{
OutMsg("setting look-and-feel: \"System\"");
javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {OutMsg(e.getMessage());}
//---- read the CFG-file
java.io.File fileNameCfg;
String dir = getPathApp();
if(dir != null && dir.trim().length()>0) {
if(dir.endsWith(SLASH)) {dir = dir.substring(0, dir.length()-1);}
fileNameCfg = new java.io.File(dir + SLASH + pc.progName+".cfg");
} else {fileNameCfg = new java.io.File(pc.progName+".cfg");}
ProgramConf.read_cfgFile(fileNameCfg, pc);
if(!pc.dbg) {pc.dbg=dbg;}
// --- helpID?
final String helpID;
if(args.length >0) {
if(args[0].trim().length()>1) {helpID = args[0];} else {helpID = null;}
} else {helpID = null;}
// --- If the Java Help is already "alive" just bring it to front
if(helpWindow != null && helpWindow.hb != null) {
if(pc.dbg){
String msg = "helpWindow not null";
if(helpID != null) {msg = msg + "; helpID=\""+helpID+"\"";}
OutMsg(msg);
}
if(helpID != null && helpID.length() >0) {
java.awt.EventQueue.invokeLater(new Runnable() {@Override public void run() {
if(pc.dbg){OutMsg("helpWindow.setHelpID("+helpID+")");}
helpWindow.setHelpID(helpID);
}}); // invokeLater (new Runnable)
}
} // if helpWindow !=null
if(pc.dbg){
String msg = "Starting HelpWindow - (version "+VERS+")";
if(helpID != null) {msg = msg + "; helpID=\""+helpID+"\"";}
OutMsg(msg);
}
// ----- Construct a new HelpWindow
// --- Is this executed stand-alone (starting a Java Virtual Machine),
// or is it called from another Java application?
String callingClass = ClassLocator.getCallerClassName();
if(pc.dbg){OutMsg("Has been called from: "+callingClass);}
boolean standAlone = true;
if(!callingClass.contains("HelpWindow")) { // called from another application
if(pc.dbg){OutMsg("Stand alone = false");}
standAlone = false;
} else {if(pc.dbg){OutMsg("Stand alone = true");}}
final boolean isSlave0 = !standAlone;
java.awt.EventQueue.invokeLater(new Runnable() {@Override public void run() {
HelpWindow hw = HelpWindow.getInstance();
if(hw == null) {
if(pc.dbg){OutMsg("No previous instance found. Constructing.");}
HelpWindow hw1 = new HelpWindow(isSlave0, pc);
} else {
if(pc.dbg){OutMsg("Previous instance found. bringToFront();");}
hw.bringToFront();
}
if(helpID != null && helpID.length() >0) {
// put the "setHelpID(helpID)" in the Event queue
java.awt.EventQueue.invokeLater(new Runnable() {@Override public void run() {
HelpWindow hw = HelpWindow.getInstance();
if(hw != null && hw.hb != null) {
if(pc.dbg){OutMsg("HelpWindow.main: setHelpID("+helpID+")");}
hw.setHelpID(helpID);
} else {
if(pc.dbg){OutMsg("HelpWindow.main: getInstance() is null");}
}
}});
} // if helpID !=null
}}); // invokeLater (new Runnable)
//return;
} // main(args[])
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Constructor">
private HelpWindow(final boolean isSlave0, ProgramConf pc0){ // show a HelpSet
isSlave = isSlave0;
pc = pc0;
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
helpWindow = HelpWindow.this;
}});
// ---- next line must be *BEFORE* starting JavaHelp
javax.help.SwingHelpUtilities.setContentViewerUI("chemicalDiagramsHelp.ExternalLinkContentViewerUI");
// ---- read the INI-file
readIni();
// ---- get the Helpset in variable "hs"
ClassLoader cl = HelpWindow.class.getClassLoader();
final String def_HelpSetFileName = "helpset.hs";
// ---- get the name of the HelpSet from the Jar-Manifest (if any)
String helpSetFileName = null;
if(jarName == null) {
helpSetFileName = "javahelp/"+def_HelpSetFileName;
}else {
try {
for(java.util.Enumeration e = cl.getResources(java.util.jar.JarFile.MANIFEST_NAME);
e.hasMoreElements();) {
java.net.URL url = (java.net.URL)e.nextElement();
helpSetFileName = new java.util.jar.Manifest(url.openStream()).getMainAttributes().getValue("Helpset");
if(helpSetFileName != null) {break;}
} //for Enumeration e
} // try
catch (java.io.IOException ex) {
String msg = "Error \""+ex.toString()+"\"";
ErrMsgBx mb = new ErrMsgBx(msg, pc.progName);
} //catch
} //if jarName !=null
if(helpSetFileName == null) {
if(pc.dbg && jarName != null) {
OutMsg("Warning: value \"Helpset\" not found"+nl+
"in jar-file manifest: \""+
jarName+SLASH+java.util.jar.JarFile.MANIFEST_NAME+"\"");
}
// no manifest value; assume it is there in any case
helpSetFileName = "javahelp/"+def_HelpSetFileName;
}
// ---- try to get a helpset in the jar-file
if(!getHelpSet(cl, helpSetFileName)) {end_program(); return;}
if(hs != null) {
}
if(hs != null) {
if(jarName != null) {
helpSetFileNameWithPath = jarName+"$"+helpSetFileName;
} else {
helpSetFileNameWithPath = hs.getHelpSetURL().getFile();
}
if(pc.dbg) {
OutMsg("Found helpset URL=\""+helpSetFileNameWithPath+"\"");
}
} else {
String msg = "Error: HelpSet \""+def_HelpSetFileName+"\" not found!";
if(jarName != null) {msg = msg +nl+ "in jar-file: "+jarName;}
ErrMsgBx mb = new ErrMsgBx(msg, pc.progName);
end_program();
return;
} // if hs = null
// ---- create HelpBroker
String msgEx = null;
try {
if(hb == null) {
if(pc.dbg) {OutMsg("creating helpBroker");}
hb = hs.createHelpBroker();
}
} catch (Exception e) {
hb = null;
msgEx = e.toString();
} //catch
if(hb == null){
String msg;
if(msgEx == null) {msg = "Error: Could not create HelpBroker for HelpSet:"+nl+
"\""+helpSetFileNameWithPath+"\".";
} else {msg = "Error: "+msgEx+nl+
"Can not create HelpBroker for HelpSet:"+nl+
"\""+helpSetFileNameWithPath+"\".";}
ErrMsgBx mb = new ErrMsgBx(msg, pc.progName);
end_program();
return;
}
// ---- get the WindowPresentation and the JFrame
javax.help.DefaultHelpBroker dhb = (javax.help.DefaultHelpBroker)hb;
try{
if(hb.getCurrentView() == null) {
if(pc.dbg) {OutMsg("initPresentation();");}
hb.initPresentation();
}
} catch (javax.help.UnsupportedOperationException ex) {
ErrMsgBx mb = new ErrMsgBx(ex.toString(), pc.progName);
}
javax.help.WindowPresentation wp = ((javax.help.DefaultHelpBroker)hb).getWindowPresentation();
if(wp == null) {
if(pc.dbg) {OutMsg("initPresentation()");}
hb.initPresentation();
wp = ((javax.help.DefaultHelpBroker)hb).getWindowPresentation();
}
hFrame = (javax.swing.JFrame)wp.getHelpWindow();
hFrame.setDefaultCloseOperation(javax.swing.JFrame.DO_NOTHING_ON_CLOSE);
hFrame.addWindowListener(
new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent evt) {end_program();}
}
);
// ---- change the Icon
String iconName = "images/help_16x16.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
java.awt.Image icon;
if (imgURL != null) {
icon = new javax.swing.ImageIcon(imgURL).getImage();
hFrame.setIconImage(icon);
//com.apple.eawt.Application.getApplication().setDockIconImage(new javax.swing.ImageIcon("Football.png").getImage());
if(System.getProperty("os.name").startsWith("Mac OS")) {
try {
Class<?> c = Class.forName("com.apple.eawt.Application");
//Class params[] = new Class[] {java.awt.Image.class};
java.lang.reflect.Method m =
c.getDeclaredMethod("setDockIconImage",new Class[] { java.awt.Image.class });
Object i = c.newInstance();
java.net.URL iconURL = this.getClass().getResource("images/help_48x48.gif");
if (iconURL != null) {icon = new javax.swing.ImageIcon(iconURL).getImage();}
Object paramsObj[] = new Object[]{icon};
m.invoke(i, paramsObj);
} catch (Exception e) {OutMsg("Error: "+e.getMessage());}
}
} else {
OutMsg("Error: Could not load image = \""+iconName+"\"");
}
// ---- create a Panel with 2 Combo Boxes
// for the Font and the Font-Size
jPanel_font_size = new javax.swing.JPanel();
//--- Create a Combo Box and add the font list
jComboBox_font = new javax.swing.JComboBox<String>( // jComboBox_font = new javax.swing.JComboBox( // java 1.6
java.awt.GraphicsEnvironment.
getLocalGraphicsEnvironment().
getAvailableFontFamilyNames());
//--- Create a Combo Box and add the size list
jComboBox_size = new javax.swing.JComboBox<>( // jComboBox_size = new javax.swing.JComboBox( // java 1.6
new String[] {"8","9","10","11","12","14","16","18","20",
"22","24","26","28","36","48","72"});
//--- Arrange the Combo Boxes in the Panel
java.awt.FlowLayout jPanel_Layout = new java.awt.FlowLayout(java.awt.FlowLayout.LEADING);
jPanel_font_size.setLayout(jPanel_Layout);
jPanel_font_size.add(jComboBox_font);
jPanel_font_size.add(jComboBox_size);
jPanel_font_size.add(javax.swing.Box.createHorizontalGlue());
// ---- add the Panel at the top of the help window
hFrame.getContentPane().add(jPanel_font_size, java.awt.BorderLayout.PAGE_START);
// Events/Action/ActionPerformed
jComboBox_font.addActionListener(
new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
hbFont = jComboBox_font.getSelectedItem().toString();
java.awt.Font f = hb.getFont();
hb.setFont(new java.awt.Font(hbFont, java.awt.Font.PLAIN, f.getSize()));
} // actionPerformed
} // new ActionListener
); // addActionListener
// Events/Action/ActionPerformed
jComboBox_size.addActionListener(
new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
hbSize = Integer.parseInt(jComboBox_size.getSelectedItem().toString());
float fSize = (float) hbSize;
// force a font change even if the the size is the same as before:
hb.setFont(hb.getFont().deriveFont(fSize - 0.5f));
hb.setFont(hb.getFont().deriveFont(fSize));
} // actionPerformed
} // new ActionListener
); // addActionListener
// ---- add a status bar at the bottom of the window
jLabel_status = new javax.swing.JLabel(" ");
jLabel_status.setBorder(javax.swing.BorderFactory.createCompoundBorder(
javax.swing.BorderFactory.createLoweredBevelBorder(),
javax.swing.BorderFactory.createEmptyBorder(0,5,0,5))); // leave space to the left and right
hFrame.getContentPane().add(jLabel_status, java.awt.BorderLayout.PAGE_END);
jLabel_status.setText("Helpset: "+helpSetFileNameWithPath);
// ---- display the HelpBroker
hb.setDisplayed(true);
// ---- set the window location
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
hFrame.setLocation(Math.min(screenSize.width-100, Math.max(0,left)), Math.min(screenSize.height-100, Math.max(0,top)));
hFrame.setSize(Math.max(325,width), Math.max(215,height));
hFrame.validate();
hFrame.setExtendedState(windowState);
// ---- change the font and font-size
int found = -1;
for(int i = 0; i < jComboBox_font.getItemCount(); i++)
{if(jComboBox_font.getItemAt(i).toString().toLowerCase().startsWith(hbFont.toLowerCase()))
{jComboBox_font.setSelectedIndex(i); found = i; break;}} //for
if(found < 0) {hbFont = "Tahoma";
for(int i = 0; i < jComboBox_font.getItemCount(); i++) {
if(jComboBox_font.getItemAt(i).toString().toLowerCase().startsWith(hbFont.toLowerCase()))
{jComboBox_font.setSelectedIndex(i); break;}} //for
} // if(found < 0)
found = -1;
for(int i = 0; i < jComboBox_size.getItemCount(); i++) {
if(Float.parseFloat(jComboBox_size.getItemAt(i).toString()) == hbSize) {
jComboBox_size.setSelectedIndex(i);
found = i; break;
}
} // for
if(found < 0) {
hbSize = 14;
for(int i = 0; i < jComboBox_size.getItemCount(); i++) {
if(Float.parseFloat(jComboBox_size.getItemAt(i).toString()) == hbSize) {
jComboBox_size.setSelectedIndex(i); break;
}
} // for
} //if(found < 0)
// ---- change the status bar when the ID changes
wp.setTitleFromDocument(true);
java.beans.PropertyChangeListener pcl = new java.beans.PropertyChangeListener() {
@Override
public void propertyChange(java.beans.PropertyChangeEvent event) {
String property = event.getPropertyName();
if ("title".equals(property)) {
try{
if(hb != null && hb.getCurrentID() != null)
{jLabel_status.setText(hb.getCurrentID().getURL().getPath());}
} catch (java.net.MalformedURLException ex) {
jLabel_status.setText(hb.getCurrentID().getIDString());
}
}
}
};
hFrame.addPropertyChangeListener(pcl);
} // Constructor for: HelpWindow(isSlave)
//</editor-fold>
/** Return a reference to this instance
* @return this instance */
public static HelpWindow getInstance() {return helpWindow;}
//<editor-fold defaultstate="collapsed" desc="setHelpID">
public void setHelpID(String startHelpID) {
if(startHelpID == null || startHelpID.length() <=0) {return;}
bringToFront();
if(helpWindow != null && helpWindow.hb != null) {
if(pc.dbg){OutMsg("setHelpID using \""+startHelpID+"\"");}
try{helpWindow.hb.setCurrentID(startHelpID);}
catch (javax.help.BadIDException ex) {
String msg = "Error: can not set help ID to: \""+startHelpID+"\"";
OutMsg(msg);
if(this.hFrame != null) {
javax.swing.JOptionPane.showMessageDialog(this.hFrame,msg,pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE);
} else {
ErrMsgBx mb = new ErrMsgBx(msg, pc.progName);
}
} // catch
} else {
String msg = "Warning: in setHelpID ";
if(helpWindow == null) {msg = msg + "helpWindow = \"null\".";}
else if(helpWindow.hb == null) {msg = msg + "HelpBroker = \"null\".";}
OutMsg(msg);
}
//return;
} // setHelpID
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="bringToFront">
public void bringToFront(){
if(helpWindow != null && helpWindow.hFrame != null) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override public void run() {
helpWindow.hFrame.setVisible(true);
if((helpWindow.hFrame.getExtendedState() & javax.swing.JFrame.ICONIFIED) // minimised?
== javax.swing.JFrame.ICONIFIED) {
helpWindow.hFrame.setExtendedState(javax.swing.JFrame.NORMAL);
} // if minimized
helpWindow.hFrame.setAlwaysOnTop(true);
helpWindow.hFrame.toFront();
helpWindow.hFrame.requestFocus();
helpWindow.hFrame.setAlwaysOnTop(false);
}
});
}
} // bringToFront()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="end_program">
private void end_program() {
if(isSlave) {
if(hFrame == null) {return;}
if(pc.dbg) {OutMsg("- - - - setVisible(false) - - - -");}
hFrame.setVisible(false);
return;
}
if(fileINI != null) {saveIni(fileINI);}
if(pc.dbg) {OutMsg("- - - - end_program - - - -");}
if(hFrame != null) {hFrame.dispose();}
hFrame = null;
helpWindow = null;
OneInstance.endCheckOtherInstances();
} // end_program()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="getHelpSet">
private boolean getHelpSet(ClassLoader cl, String HelpSetFileName) {
java.net.URL hs_Url;
try{hs_Url = javax.help.HelpSet.findHelpSet(cl, HelpSetFileName);}
catch (java.lang.NoClassDefFoundError ex) {
String msg = "Serious Error: \"" + ex.toString()+"\""+nl+
"Library \"lib"+java.io.File.separator+"jh.jar\" not found!";
ErrMsgBx mb = new ErrMsgBx(msg, pc.progName);
return false;
}
if(hs_Url != null) {
try{hs = new javax.help.HelpSet(cl, hs_Url);}
catch (javax.help.HelpSetException ex) {
String msg = "HelpSet error: \"" + ex.toString()+"\""+nl+
"for HelpSet URL = \""+hs_Url.getPath()+"\"";
OutMsg(msg);
ErrMsgBx mb = new ErrMsgBx(msg, pc.progName);
hs = null;
return true;
}
} // if(hs_Url != null)
if(hs == null) {
if(pc.dbg){OutMsg("Note: HelpSet \""+HelpSetFileName+
"\" not found in class loader.");}
}
return true;
} // getHelpSet_in_jarFile
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Read_Write_INI">
/** Read program variables saved when the program was previously closed */
private void readIni() {
iniDefaults(); // needed to initialise arrays etc.
if(pc.dbg) {OutMsg("--- readIni() --- reading ini-file(s)");}
fileINI = null;
java.io.File p = null, fileRead = null, fileINInotRO = null;
boolean ok, readOk = false;
//--- check the application path ---//
String pathAPP = getPathApp();
if(pathAPP == null || pathAPP.trim().length() <=0) {
if(pc.saveIniFileToApplicationPathOnly) {
String name = "\"null\"" + SLASH + FileINI_NAME;
String msg = "Error: can not read ini file"+nl+
" "+name+nl+
" (application path is \"null\")";
OutMsg(msg);
ErrMsgBx mb = new ErrMsgBx(msg, pc.progName);
return;
}
} else { //pathApp is defined
String dir = pathAPP;
if(dir.endsWith(SLASH)) {dir = dir.substring(0, dir.length()-1);}
fileINI = new java.io.File(dir + SLASH + FileINI_NAME);
p = new java.io.File(dir);
if(!p.exists()) {
p = null; fileINI = null;
if(pc.saveIniFileToApplicationPathOnly) {
String msg = "Error: can not read ini file:"+nl+
" "+fileINI.getPath()+nl+
" (application path does not exist)";
OutMsg(msg);
ErrMsgBx mb = new ErrMsgBx(msg, pc.progName);
return;
}
}
}
success: {
// --- first read the ini-file from the application path, if possible
if(pc.saveIniFileToApplicationPathOnly && fileINI != null) {
// If the ini-file must be written to the application path,
// then try to read this file, even if the file is write-protected
fileINInotRO = fileINI;
if(fileINI.exists()) {
readOk = readIni2(fileINI);
if(readOk) {fileRead = fileINI;}
}
break success;
} else { // not saveIniFileToApplicationPathOnly or fileINI does not exist
if(fileINI != null && fileINI.exists()) {
readOk = readIni2(fileINI);
if(readOk) {fileRead = fileINI;}
if(fileINI.canWrite() && fileINI.setWritable(true)) {
fileINInotRO = fileINI;
if(readOk) {break success;}
}
} else { //ini-file null or does not exist
if(fileINI != null && p != null) {
try{ // can we can write to this directory?
java.io.File tmp = java.io.File.createTempFile("eqHelp",".tmp", p);
ok = tmp.exists();
if(ok) {tmp.delete();}
} catch (java.io.IOException ex) {ok = false;}
// file does not exist, but the path is not write-protected
if(ok && fileINInotRO == null) {fileINInotRO = fileINI;}
}
}
}
// --- an ini-file has not been read in the application path
// and saveIniFileToApplicationPathOnly = false. Read the ini-file from
// the user's path, if possible
java.util.ArrayList<String> dirs = new java.util.ArrayList<String>(5);
String homeDrv = System.getenv("HOMEDRIVE");
String homePath = System.getenv("HOMEPATH");
if(homePath != null && homePath.trim().length() >0 && !homePath.startsWith(SLASH)) {
homePath = SLASH + homePath;
}
if(homeDrv != null && homeDrv.trim().length() >0 && homeDrv.endsWith(SLASH)) {
homeDrv = homeDrv.substring(0, homeDrv.length()-1);
}
if((homeDrv != null && homeDrv.trim().length() >0)
&& (homePath != null && homePath.trim().length() >0)) {
p = new java.io.File(homeDrv+homePath);
if(p.exists()) {dirs.add(p.getAbsolutePath());}
}
String home = System.getenv("HOME");
if(home != null && home.trim().length() >0) {
p = new java.io.File(home);
if(p.exists()) {dirs.add(p.getAbsolutePath());}
}
home = System.getProperty("user.home");
if(home != null && home.trim().length() >0) {
p = new java.io.File(home);
if(p.exists()) {dirs.add(p.getAbsolutePath());}
}
for(String t : dirs) {
if(t.endsWith(SLASH)) {t = t.substring(0, t.length()-1);}
fileINI = new java.io.File(t+SLASH+".config"+SLASH+"eq-diagr"+SLASH+FileINI_NAME);
if(fileINI.exists()) {
readOk = readIni2(fileINI);
if(readOk) {fileRead = fileINI;}
if(fileINI.canWrite() && fileINI.setWritable(true)) {
if(fileINInotRO == null) {fileINInotRO = fileINI;}
if(readOk) {break success;}
}
} else { //ini-file does not exist
try{ // can we can write to this directory?
p = new java.io.File(t);
java.io.File tmp = java.io.File.createTempFile("eqHelp",".tmp", p);
ok = tmp.exists();
if(ok) {tmp.delete();}
} catch (java.io.IOException ex) {ok = false;}
// file does not exist, but the path is not write-protected
if(ok && fileINInotRO == null) {fileINInotRO = fileINI;}
}
} // for(dirs)
} //--- success?
if(!readOk) {OutMsg("Could not read any INI-file.");}
if(fileINInotRO != null && fileINInotRO != fileRead) {
ok = saveIni(fileINInotRO);
if(ok) {fileINI = fileINInotRO;} else {fileINI = null;}
}
} // Read_ini()
private boolean readIni2(java.io.File f) {
System.out.flush();
OutMsg("Reading ini-file: \""+f.getPath()+"\"");
java.util.Properties ini= new java.util.Properties();
java.io.FileInputStream fis = null;
java.io.BufferedReader r = null;
boolean ok = true;
try {
fis = new java.io.FileInputStream(f);
r = new java.io.BufferedReader(new java.io.InputStreamReader(fis, "UTF8"));
ini.load(r);
} catch (java.io.FileNotFoundException e) {
OutMsg("Warning: file Not found: \""+f.getPath()+"\""+nl+
" using default parameter values.");
ok = false;
}
catch (java.io.IOException e) {
String msg = "Error: \""+e.toString()+"\""+nl+
" while loading INI-file:"+nl+
" \""+f.getPath()+"\"";
OutMsg(msg);
ErrMsgBx mb = new ErrMsgBx(msg, pc.progName);
ok = false;
} // catch loading-exception
try {if(r != null) {r.close();} if(fis != null) {fis.close();}}
catch (java.io.IOException e) {
String msg ="Error: \""+e.toString()+"\""+nl+
" while closing INI-file:"+nl+
" \""+f.getPath()+"\"";
ErrMsgBx mb = new ErrMsgBx(msg, pc.progName);
ok = false;
}
finally {
try {if(r != null) {r.close();} if(fis != null) {fis.close();}}
catch (java.io.IOException e) {
String msg = "Error: \""+e.toString()+"\""+nl+
" while closing INI-file:"+nl+
" \""+f.getPath()+"\"";
ErrMsgBx mb = new ErrMsgBx(msg, pc.progName);
}
}
if(!ok) {return ok;}
try {
left = Integer.parseInt(ini.getProperty("left"));
top = Integer.parseInt(ini.getProperty("top"));
width = Integer.parseInt(ini.getProperty("width"));
height = Integer.parseInt(ini.getProperty("height"));
hbFont = ini.getProperty("font");
hbSize = Integer.parseInt(ini.getProperty("font_size"));
windowState = Integer.parseInt(ini.getProperty("window_state"));
} catch (java.lang.NumberFormatException e) {
String msg = "Error: \""+e.toString()+"\""+nl+
" while reading INI-file:"+nl+
" \""+f.getPath()+"\""+nl+nl+
"Setting default program parameters.";
ErrMsgBx mb = new ErrMsgBx(msg, pc.progName);
ok = false;
}
if(pc.dbg) {OutMsg("Finished reading ini-file");}
System.out.flush();
checkIniValues();
return ok;
}
private void checkIniValues() {
left = Math.max(0,left); top = Math.max(0,top);
width = Math.max(325,width); height = Math.max(215,height);
hbSize = Math.max(8,Math.min(hbSize,72));
// do not start with windowState = JFrame.ICONIFIED
if(windowState != javax.swing.JFrame.NORMAL &&
windowState != javax.swing.JFrame.MAXIMIZED_BOTH) {
windowState = javax.swing.JFrame.NORMAL;}
//return;
} // checkIniValues()
/** Set default values for program variables */
private void iniDefaults() {
left = 60; top = 0; width = 600; height = 550;
hbFont = "Tahoma"; hbSize = 14;
windowState = javax.swing.JFrame.NORMAL;
//return;
} // iniDefaults()
/** Save program variables (when the program ends, etc) */
private boolean saveIni(java.io.File f) {
if(f == null) {return false;} // this will not happen
if(pc.dbg) {OutMsg("Writing ini-file "+f.getAbsolutePath());}
boolean ok = true;
String msg = null;
if(f.exists() && (!f.canWrite() || !f.setWritable(true))) {
msg = "Error - can not write ini-file:"+nl+
" \""+f.getAbsolutePath()+"\""+nl+
" The file is read-only.";
}
if(!f.exists() && !f.getParentFile().exists()) {
ok = f.getParentFile().mkdirs();
if(!ok) {
msg = "Error - can not create directory:"+nl+
" \""+f.getParent()+"\""+nl+
" Can not write ini-file.";
}
}
if(msg != null) {
OutMsg(msg);
if(hFrame != null && hFrame.isVisible()) {
javax.swing.JOptionPane.showMessageDialog(hFrame, msg, pc.progName,
javax.swing.JOptionPane.WARNING_MESSAGE);
} else {
ErrMsgBx mb = new ErrMsgBx(msg, pc.progName);
}
return false;
}
if(helpWindow != null && helpWindow.hFrame != null) {
if((helpWindow.hFrame.getExtendedState() &
javax.swing.JFrame.MAXIMIZED_BOTH)
!= javax.swing.JFrame.MAXIMIZED_BOTH) {
left = helpWindow.hFrame.getX();
top = helpWindow.hFrame.getY();
width = helpWindow.hFrame.getWidth();
height = helpWindow.hFrame.getHeight();
} // if getExtendedState
windowState = helpWindow.hFrame.getExtendedState();
// hbFont and hbSize are set in the ActionListeners
}
java.util.Properties ini = new java.util.Properties();
ini.setProperty("width", String.valueOf(width));
ini.setProperty("height", String.valueOf(height));
ini.setProperty("left", String.valueOf(left));
ini.setProperty("top", String.valueOf(top));
ini.setProperty("font", hbFont);
ini.setProperty("font_size", String.valueOf(hbSize));
ini.setProperty("window_state", String.valueOf(windowState));
java.io.FileOutputStream fos = null;
java.io.Writer w = null;
try{
fos = new java.io.FileOutputStream(f);
w = new java.io.BufferedWriter(new java.io.OutputStreamWriter(fos, "UTF8"));
ini.store(w, null);
}
catch (java.io.IOException ex) {
msg = "Error \""+ex.toString()+"\""+nl+
"while writing INI-file: \""+f.toString()+"\"";
OutMsg(msg);
ErrMsgBx mb = new ErrMsgBx(msg, pc.progName);
ok = false;
} // catch store-exception
finally {
try{if(w != null) {w.close();} if(fos != null) {fos.close();}}
catch (java.io.IOException e) {ok = false;}
}
return ok;
} // Save_ini
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="getPathApp">
/** Get the path where an application is located.
* @return the directory where the application is located,
* or "user.dir" if an error occurs
* @version 2014-Jan-17 */
private static class C {private static void C(){}}
public static String getPathApp() {
C c = new C();
String path;
java.net.URI dir;
try{
dir = c.getClass().
getProtectionDomain().
getCodeSource().
getLocation().
toURI();
if(dir != null) {
String d = dir.toString();
if(d.startsWith("jar:") && d.endsWith("!/")) {
d = d.substring(4, d.length()-2);
dir = new java.net.URI(d);
}
path = (new java.io.File(dir.getPath())).getParent();
} else {path = System.getProperty("user.dir");}
}
catch (java.net.URISyntaxException e) {
if(!started) {
ErrMsgBx emb = new ErrMsgBx("Error: "+e.toString()+nl+
" trying to get the application's directory.", "Help Window");
}
path = System.getProperty("user.dir");
} // catch
started = true;
return path;
} //getPathApp()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="getRunningJarFile()">
/** Find out the jar file that contains this class
* @return a File object of the jar file containing the enclosing class "Main",
* or null if it is not containing inside a jar file. */
public static java.util.jar.JarFile getRunningJarFile() {
//from http://www.rgagnon.com/javadetails/
//and the JarClassLoader class
C c = new C();
String className = c.getClass().getName().replace('.', '/');
// class = "progPackage.Main"; className = "progPackage/Main"
java.net.URL url = c.getClass().getResource("/" + className + ".class");
// url = "jar:file:/C:/Eq-Calc_Java/dist/Prog.jar!/progPackage/Main.class"
if(url.toString().startsWith("jar:")) {
java.net.JarURLConnection jUrlC;
try{
jUrlC = (java.net.JarURLConnection)url.openConnection();
return jUrlC.getJarFile();
} catch(java.io.IOException ex) {
ErrMsgBx mb = new ErrMsgBx("Error "+ex.toString(), "Help Window");
return null;
}
}
return null;
} //getRunningJarFile()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="OutMsg and ErrMsg">
/** Prints a message to System.out surrounded by a lines:<br>
* ---------- Chemical Diagrams Help:<br>
* The error message here<br>
* ----------<br>
* If the msessage is short (less than 50 chars) then the format is:<br>
* ---------- Chemical Diagrams Help: The error message here<br>
* This is useful if the Help is called from within DataBase or Spana,
* so that messages from the Help may be differenciated from messages
* by the calling program.
* @param txt the message to print */
static void OutMsg(String txt) {
String msg;
if(txt.length()>=50) {msg = line+" Chemical Diagrams Help:"+nl+txt+nl+line;}
else {msg = line+" Chemical Diagrams Help: "+txt;}
System.out.println(msg);
System.out.flush();
}
/** Prints a message to System.err surrounded by a lines:<br>
* ---------- Chemical Diagrams Help:<br>
* The error message here<br>
* ----------<br>
* If the msessage is short (less than 50 chars) then the format is:<br>
* ---------- Chemical Diagrams Help: The error message here<br>
* This is useful if the Help is called from within DataBase or Spana,
* so that messages from the Help may be differenciated from messages
* by the calling program.
* @param txt the message to print */
static void ErrMsg(String txt) {
String msg;
if(txt.length()>=50) {msg = line+" Chemical Diagrams Help:"+nl+txt+nl+line;}
else {msg = line+" Chemical Diagrams Help: "+txt;}
System.err.println(msg);
System.err.flush();
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="ErrMsgBx">
/** Displays a "message box" modal dialog with an "OK" button.<br>
* Why is this needed? For any java console application: if started using
* javaw.exe (on Windows) or through a ProcessBuilder, no console will appear.
* Error messages are then "lost" unless a log-file is generated and the user
* reads it. This class allows the program to stop running and wait for the user
* to confirm that the error message has been read.
* <br>
* A small frame (window) is first created and made visible. This frame is
* the parent to the modal "message box" dialog, and it has an icon on the
* task bar (Windows). Then the modal dialog is displayed on top of the
* small parent frame.
* <br>
* Copyright (C) 2015-2018 I.Puigdomenech.
* @author Ignasi Puigdomenech
* @version 2015-July-14 */
static class ErrMsgBx {
/** Displays a "message box" modal dialog with an "OK" button and a title.
* The message is displayed in a text area (non-editable),
* which can be copied and pasted elsewhere.
* @param msg will be displayed in a text area, and line breaks may be
* included, for example: <code>new MsgBox("Very\nbad!",""); </code>
* If null or empty nothing is done.
* @param title for the dialog. If null or empty, "Error:" is used
* @version 2018-May-13 */
public ErrMsgBx(String msg, String title) {
if(msg == null || msg.trim().length() <=0) {
System.err.println("--- ErrMsgBx: null or empty \"message\".");
return;
}
//--- Title
if(title == null || title.length() <=0) {title = " Error:";}
java.awt.Frame frame = new java.awt.Frame(title);
//--- Icon
String iconName = "images/ErrMsgBx.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
if(imgURL != null) {frame.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());}
else {System.err.println("--- Error in ErrMsgBx constructor: Could not load image = \""+iconName+"\"");}
frame.pack();
//--- centre Window frame on Screen
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int left; int top;
left = Math.max(55, (screenSize.width - frame.getWidth() ) / 2);
top = Math.max(10, (screenSize.height - frame.getHeight()) / 2);
frame.setLocation(Math.min(screenSize.width-100, left), Math.min(screenSize.height-100, top));
//---
final String msgText = wrapString(msg.trim(),80);
//System.out.println("--- MsgBox:"+nl+msgText+nl+"---");
frame.setVisible(true);
//javax.swing.JOptionPane.showMessageDialog(frame, msg, title, javax.swing.JOptionPane.ERROR_MESSAGE);
MsgBoxDialog msgBox = new MsgBoxDialog(frame, msgText, title, true);
msgBox.setVisible(true); // becase the dialog is modal, statements below will wait
msgBox.dispose();
frame.setVisible(false);
frame.dispose();
}
/** Returns an input string, with lines that are longer than <code>maxLength</code>
* word-wrapped and indented. *
* @param s input string
* @param maxLength if an input line is longer than this length,
* the line will be word-wrapped at the first white space after <code>maxLength</code>
* and indented with 4 spaces
* @return string with long-lines word-wrapped
*/
public static String wrapString(String s, int maxLength) {
String deliminator = "\n";
StringBuilder result = new StringBuilder();
StringBuffer wrapLine;
int lastdelimPos;
for (String line : s.split(deliminator, -1)) {
if(line.length()/(maxLength+1) < 1) {
result.append(line).append(deliminator);
}
else { //line too long, try to split it
wrapLine = new StringBuffer();
lastdelimPos = 0;
for (String token : line.trim().split("\\s+", -1)) {
if (wrapLine.length() - lastdelimPos + token.length() > maxLength) {
if(wrapLine.length()>0) {wrapLine.append(deliminator);}
wrapLine.append(" ").append(token);
lastdelimPos = wrapLine.length() + 1;
} else {
if(wrapLine.length() <=0) {wrapLine.append(token);}
else {wrapLine.append(" ").append(token);}
}
}
result.append(wrapLine).append(deliminator);
}
}
return result.toString();
}
//<editor-fold defaultstate="collapsed" desc="MsgBoxDialog">
private static class MsgBoxDialog extends java.awt.Dialog {
private java.awt.Button ok;
private java.awt.Panel p;
private final java.awt.TextArea text;
/** Creates new form NewDialog */
public MsgBoxDialog(java.awt.Frame parent, String msg, String title, boolean modal) {
super(parent, (" "+title), modal);
addWindowListener(new java.awt.event.WindowAdapter() {
@Override public void windowClosing(java.awt.event.WindowEvent evt) {
MsgBoxDialog.this.setVisible(false);
}
});
setLayout(new java.awt.BorderLayout());
p = new java.awt.Panel();
p.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER));
ok = new java.awt.Button();
// find out the size of the message (width and height)
final int wMax = 85; final int hMax=20;
final int wMin = 5; final int hMin = 1;
int w = wMin;
int h=hMin; int i=0; int j=wMin;
final String eol = "\n"; char c;
final String nl = System.getProperty("line.separator");
while (true) {
c = msg.charAt(i);
String s = String.valueOf(c);
if(s.equals(eol) || s.equals(nl)) {
h++; j=wMin;
} else {
j++; w = Math.max(j,w);
}
i++;
if(i >= msg.length()-1) {break;}
}
// create a text area
int scroll = java.awt.TextArea.SCROLLBARS_NONE;
if(w > wMax && h <= hMax) {scroll = scroll & java.awt.TextArea.SCROLLBARS_HORIZONTAL_ONLY;}
if(h > hMax && w <= wMax) {scroll = scroll & java.awt.TextArea.SCROLLBARS_VERTICAL_ONLY;}
if(w > wMax && h > hMax) {scroll = java.awt.TextArea.SCROLLBARS_BOTH;}
w = Math.min(Math.max(w,10),wMax);
h = Math.min(h,hMax);
text = new java.awt.TextArea(msg, h, w, scroll);
text.setEditable(false);
//text.setBackground(java.awt.Color.white);
text.addKeyListener(new java.awt.event.KeyAdapter() {
@Override public void keyPressed(java.awt.event.KeyEvent evt) {
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER
|| evt.getKeyCode() == java.awt.event.KeyEvent.VK_ESCAPE) {closeDialog();}
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_TAB) {ok.requestFocusInWindow();}
}
});
text.setBackground(java.awt.Color.WHITE);
text.setFont(new java.awt.Font("monospaced", java.awt.Font.PLAIN, 12));
add(text, java.awt.BorderLayout.CENTER);
ok.setLabel("OK");
ok.addActionListener(new java.awt.event.ActionListener() {
@Override public void actionPerformed(java.awt.event.ActionEvent evt) {
closeDialog();
}
});
ok.addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER
|| evt.getKeyCode() == java.awt.event.KeyEvent.VK_ESCAPE) {closeDialog();}
}
});
p.add(ok);
add(p, java.awt.BorderLayout.SOUTH);
pack();
ok.requestFocusInWindow();
//--- centre Window frame on Screen
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int left; int top;
left = Math.max(55, (screenSize.width - getWidth() ) / 2);
top = Math.max(10, (screenSize.height - getHeight()) / 2);
setLocation(Math.min(screenSize.width-100, left), Math.min(screenSize.height-100, top));
}
private void closeDialog() {this.setVisible(false);}
} // private static class MsgBoxDialog
//</editor-fold>
} // static class ErrMsgBx
//</editor-fold>
}
| 48,848 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
Disp.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Spana/src/spana/Disp.java | package spana;
import lib.common.MsgExceptn;
import lib.common.Util;
import lib.huvud.Div;
import lib.huvud.ProgramConf;
import lib.kemi.graph_lib.DiagrPaintUtility;
import lib.kemi.graph_lib.GraphLib;
/** Displays a "plt"-file. The user coordinate units are in 0.01 cm.
* The diagram is displayed in a JPanel using the method
* <code>lib.kemi.graph_lib.DiagrPaintUtility.paintDiagram</code>
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class Disp extends javax.swing.JFrame {
private ProgramConf pc;
private final ProgramDataSpana pd;
private java.io.File plotFile;
private int icon_type = 1;
/** containts the info in the plot. Instantiated in "readThePlotFile" */
private GraphLib.PltData dd;
/** the methods in DiagrPaintUtility are used to paint the diagram */
private final DiagrPaintUtility diagrPaintUtil;
/** The name of the plot file. This is just the last name in the pathname's name sequence. */
public String diagrName;
/** The absolute path name for the plot file. */
public String diagrFullName;
/** The size of this object (JFrame) in the form of a Dimension object. */
public java.awt.Dimension diagrSize;
private boolean loading = true;
private DiagrExport dExp = null;
private DiagrConvert dConv = null;
private final static java.text.NumberFormat nf =
java.text.NumberFormat.getNumberInstance(java.util.Locale.ENGLISH);
private static final java.text.DecimalFormat myFormatter = (java.text.DecimalFormat)nf;
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
private final javax.swing.JPanel jPanelDispPlot;
//<editor-fold defaultstate="collapsed" desc="Disp Constructor">
/** Creates new form Disp
* @param dPaintUtil
* @param pc0
* @param pd0 */
public Disp(
DiagrPaintUtility dPaintUtil,
ProgramConf pc0,
ProgramDataSpana pd0) {
initComponents();
// ------ the methods in DiagrPaintUtility are used to paint the diagram
diagrPaintUtil = dPaintUtil;
this.pc = pc0;
this.pd = pd0;
loading = true;
// ------ the JPanel where the diagram is painted
jPanelDispPlot = new javax.swing.JPanel(){
@Override public void paint(java.awt.Graphics g){
super.paint(g);
// org.freehep.graphics2d.VectorGraphics g2D = org.freehep.graphics2d.VectorGraphics.create(g);
java.awt.Graphics2D g2D = (java.awt.Graphics2D)g;
diagrPaintUtil.paintDiagram(g2D, jPanelDispPlot.getSize(), dd, false);
}
};
jPanelDispPlot.addMouseListener(new java.awt.event.MouseAdapter() {
@Override public void mousePressed(java.awt.event.MouseEvent evt) {
if(dd.axisInfo) {maybeShowPopup(evt);}
}
@Override public void mouseReleased(java.awt.event.MouseEvent evt) {
if(dd.axisInfo) {maybeHidePopup(evt);}
}
});
jPanelDispPlot.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
@Override public void mouseDragged(java.awt.event.MouseEvent evt) {
if(dd.axisInfo) {maybeMovePopup(evt);}
}
});
jPanelDispPlot.setBackground(new java.awt.Color(255, 255, 255));
this.add(jPanelDispPlot);
// ------
// ------ Set up Drag-and-Drop
jPanelDispPlot.setTransferHandler(MainFrame.tHandler);
jMenuBar.setTransferHandler(MainFrame.tHandler);
jPanelDispPlot.setLocation(0, 0);
jPanelDispPlot.setSize(getContentPane().getSize());
// Note: the size of the panel is also set in "formComponentResized"
this.pack();
// ------ Set the size and location of the window in the screen
MainFrame.dispSize.width = Math.max(120,Math.min(MainFrame.screenSize.width,MainFrame.dispSize.width));
MainFrame.dispSize.height = Math.max(100,Math.min(MainFrame.screenSize.height,MainFrame.dispSize.height));
MainFrame.dispLocation.x = Math.max(60,Math.min(MainFrame.dispLocation.x,(MainFrame.screenSize.width-MainFrame.dispSize.width)));
MainFrame.dispLocation.y = Math.max(10,Math.min(MainFrame.dispLocation.y,(MainFrame.screenSize.height-MainFrame.dispSize.height)));
this.setLocation(MainFrame.dispLocation);
this.setSize(MainFrame.dispSize);
diagrSize = this.getSize();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
//--- Alt-Q quit
javax.swing.KeyStroke altQKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altQKeyStroke,"ALT_Q");
javax.swing.Action escAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
closeWindow();
}};
getRootPane().getActionMap().put("ALT_Q", escAction);
//--- F1 for help
javax.swing.KeyStroke f1KeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(f1KeyStroke,"F1");
javax.swing.Action f1Action = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jMenuHelp.doClick();
}};
getRootPane().getActionMap().put("F1", f1Action);
//--- Title, etc
//getContentPane().setBackground(new java.awt.Color(255, 255, 153));
jMenuBar.add(javax.swing.Box.createHorizontalGlue(),1); //move "Help" menu to the right
this.setTitle("Plot file display");
jPanel_XY.setVisible(false);
setAdvancedFeatures(pd.advancedVersion);
// ------
this.setVisible(true);
this.toFront();
this.requestFocus();
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
java.io.File f;
if(pc.pathAPP != null && pc.pathAPP.trim().length() >0) {
f = new java.io.File(pc.pathAPP+java.io.File.separator+"PlotPS.jar");
if(f.exists()) {jMenuItemPS.setEnabled(true);}
f = new java.io.File(pc.pathAPP+java.io.File.separator+"PlotPDF.jar");
if(f.exists()) {jMenuItemPDF.setEnabled(true);}
}
if(!jMenuItemPS.isEnabled() && !jMenuItemPDF.isEnabled()) {jMenuConvert.setEnabled(false);}
}}); //invokeLater(Runnable)
} // Disp
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="startPlotFile(plotFile)">
/** Reads a plot file and displays it in this object.
* If there is a problem while reading the file, the variable "this.diagrName"
* will be null.
* @param plotFile0 */
public void startPlotFile(java.io.File plotFile0) {
this.plotFile = plotFile0;
diagrName = null; diagrFullName = null;
if(plotFile != null) {
if(pc.dbg) {System.out.println("Disp("+plotFile.getAbsolutePath()+")");}
if(!readThePlotFile(plotFile)) {MsgExceptn.exception("Error reading plot file");}
else {
diagrName = plotFile.getName();
diagrFullName = plotFile.getAbsolutePath();
}
} else {MsgExceptn.exception("Error in \"Disp\": plot file is null.");}
if(diagrName == null || diagrName.trim().length() <=0) {
this.setVisible(false);
this.dispose();
return;
}
this.setTitle(dd.pltFile_Name);
loading = false;
jPanelDispPlot.repaint();
} // start(args)
// </editor-fold>
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel_XY = new javax.swing.JPanel();
jLabel_XY = new javax.swing.JLabel();
jMenuBar = new javax.swing.JMenuBar();
jMenu = new javax.swing.JMenu();
jMenuCopyAs = new javax.swing.JMenu();
jMenu_Copy_EMF = new javax.swing.JMenuItem();
jMenu_Copy_WMF_RTF = new javax.swing.JMenuItem();
jMenu_Copy_EMF_RTF = new javax.swing.JMenuItem();
jMenu_Copy_MacPict = new javax.swing.JMenuItem();
jMenu_Copy_Image = new javax.swing.JMenuItem();
jMenuExport = new javax.swing.JMenuItem();
jMenuConvert = new javax.swing.JMenu();
jMenuItemPDF = new javax.swing.JMenuItem();
jMenuItemPS = new javax.swing.JMenuItem();
jMenuPrint = new javax.swing.JMenuItem();
jSeparator1 = new javax.swing.JSeparator();
jMenuRefresh = new javax.swing.JMenuItem();
jMenuWSize = new javax.swing.JMenuItem();
jSeparator2 = new javax.swing.JPopupMenu.Separator();
jMenuMainW = new javax.swing.JMenuItem();
jMenu_Exit = new javax.swing.JMenuItem();
jMenuHlp = new javax.swing.JMenu();
jMenuHelp = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowActivated(java.awt.event.WindowEvent evt) {
formWindowActivated(evt);
}
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentMoved(java.awt.event.ComponentEvent evt) {
formComponentMoved(evt);
}
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
getContentPane().setLayout(null);
jPanel_XY.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel_XY.setText("<html> x:0.00000<br> y:-8.00E+00 </html>");
jLabel_XY.setFocusable(false);
jLabel_XY.setPreferredSize(new java.awt.Dimension(70, 30));
javax.swing.GroupLayout jPanel_XYLayout = new javax.swing.GroupLayout(jPanel_XY);
jPanel_XY.setLayout(jPanel_XYLayout);
jPanel_XYLayout.setHorizontalGroup(
jPanel_XYLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel_XYLayout.createSequentialGroup()
.addComponent(jLabel_XY, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(23, Short.MAX_VALUE))
);
jPanel_XYLayout.setVerticalGroup(
jPanel_XYLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel_XYLayout.createSequentialGroup()
.addComponent(jLabel_XY, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
getContentPane().add(jPanel_XY);
jPanel_XY.setBounds(10, 10, 90, 43);
jMenu.setMnemonic('m');
jMenu.setText("Menu");
jMenuCopyAs.setMnemonic('c');
jMenuCopyAs.setText("Copy as ...");
jMenu_Copy_EMF.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
jMenu_Copy_EMF.setText("EMF (Enhanced MetaFile)");
jMenu_Copy_EMF.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu_Copy_EMFActionPerformed(evt);
}
});
jMenuCopyAs.add(jMenu_Copy_EMF);
jMenu_Copy_WMF_RTF.setText("WMF (Windows MetaFile) RTF-embedded");
jMenu_Copy_WMF_RTF.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu_Copy_WMF_RTFActionPerformed(evt);
}
});
jMenuCopyAs.add(jMenu_Copy_WMF_RTF);
jMenu_Copy_EMF_RTF.setText("EMF embedded in RTF");
jMenu_Copy_EMF_RTF.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu_Copy_EMF_RTFActionPerformed(evt);
}
});
jMenuCopyAs.add(jMenu_Copy_EMF_RTF);
jMenu_Copy_MacPict.setText("MacPict embedded in RTF");
jMenu_Copy_MacPict.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu_Copy_MacPictActionPerformed(evt);
}
});
jMenuCopyAs.add(jMenu_Copy_MacPict);
jMenu_Copy_Image.setText("Image (bitmap)");
jMenu_Copy_Image.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu_Copy_ImageActionPerformed(evt);
}
});
jMenuCopyAs.add(jMenu_Copy_Image);
jMenu.add(jMenuCopyAs);
jMenuExport.setMnemonic('e');
jMenuExport.setText("Export to bitmap file");
jMenuExport.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuExportActionPerformed(evt);
}
});
jMenu.add(jMenuExport);
jMenuConvert.setMnemonic('n');
jMenuConvert.setText("convert to ...");
jMenuItemPDF.setMnemonic('d');
jMenuItemPDF.setText("PDF");
jMenuItemPDF.setEnabled(false);
jMenuItemPDF.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItemPDFActionPerformed(evt);
}
});
jMenuConvert.add(jMenuItemPDF);
jMenuItemPS.setMnemonic('s');
jMenuItemPS.setText("PS (or EPS)");
jMenuItemPS.setEnabled(false);
jMenuItemPS.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItemPSActionPerformed(evt);
}
});
jMenuConvert.add(jMenuItemPS);
jMenu.add(jMenuConvert);
jMenuPrint.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.ALT_MASK));
jMenuPrint.setMnemonic('p');
jMenuPrint.setText("Print");
jMenuPrint.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuPrintActionPerformed(evt);
}
});
jMenu.add(jMenuPrint);
jMenu.add(jSeparator1);
jMenuRefresh.setMnemonic('r');
jMenuRefresh.setText("Refresh");
jMenuRefresh.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuRefreshActionPerformed(evt);
}
});
jMenu.add(jMenuRefresh);
jMenuWSize.setMnemonic('s');
jMenuWSize.setText("window Size");
jMenuWSize.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuWSizeActionPerformed(evt);
}
});
jMenu.add(jMenuWSize);
jMenu.add(jSeparator2);
jMenuMainW.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_W, java.awt.event.InputEvent.ALT_MASK));
jMenuMainW.setMnemonic('w');
jMenuMainW.setText("main Window");
jMenuMainW.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuMainWActionPerformed(evt);
}
});
jMenu.add(jMenuMainW);
jMenu_Exit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK));
jMenu_Exit.setMnemonic('x');
jMenu_Exit.setText("eXit");
jMenu_Exit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu_ExitActionPerformed(evt);
}
});
jMenu.add(jMenu_Exit);
jMenuBar.add(jMenu);
jMenuHlp.setMnemonic('H');
jMenuHlp.setText("Help");
jMenuHlp.setToolTipText("Help");
jMenuHelp.setMnemonic('D');
jMenuHelp.setText("Diagram Windows");
jMenuHelp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuHelpActionPerformed(evt);
}
});
jMenuHlp.add(jMenuHelp);
jMenuBar.add(jMenuHlp);
setJMenuBar(jMenuBar);
pack();
}// </editor-fold>//GEN-END:initComponents
//<editor-fold defaultstate="collapsed" desc="Events">
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
closeWindow();
}//GEN-LAST:event_formWindowClosing
private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
if(this.getExtendedState()==javax.swing.JFrame.ICONIFIED) {return;} // minimised?
if(this.getExtendedState()!=javax.swing.JFrame.MAXIMIZED_BOTH) {
if(this.getHeight()<100){this.setSize(this.getWidth(), 100);}
if(this.getWidth()<120){this.setSize(120,this.getHeight());}
diagrSize = this.getSize();
if(!loading) {MainFrame.dispSize = diagrSize;}
}
if(this.isVisible()) {jPanelDispPlot.setSize(getContentPane().getSize());}
}//GEN-LAST:event_formComponentResized
private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
setAdvancedFeatures(pd.advancedVersion);
// Icon
String iconName;
if (icon_type == 1) {iconName = "images/PlotLog256_32x32_whiteBckgr.gif";}
else {iconName = "images/PlotPred256_32x32_whiteBckgr.gif";}
java.net.URL imgURL = this.getClass().getResource(iconName);
if (imgURL != null) {
this.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());}
else {System.out.println("Could not load image = \""+iconName+"\"");}
jPanel_XY.setVisible(false);
pc.setPathDef(plotFile);
}//GEN-LAST:event_formWindowActivated
private void jMenuPrintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuPrintActionPerformed
printDiagram(false);
}//GEN-LAST:event_jMenuPrintActionPerformed
private void jMenu_Copy_WMF_RTFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu_Copy_WMF_RTFActionPerformed
copyWith_jVectClipboard(2);
}//GEN-LAST:event_jMenu_Copy_WMF_RTFActionPerformed
private void jMenu_Copy_EMF_RTFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu_Copy_EMF_RTFActionPerformed
copyWith_jVectClipboard(1);
}//GEN-LAST:event_jMenu_Copy_EMF_RTFActionPerformed
private void jMenu_Copy_MacPictActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu_Copy_MacPictActionPerformed
copyWith_jVectClipboard(4);
}//GEN-LAST:event_jMenu_Copy_MacPictActionPerformed
private void jMenu_Copy_ImageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu_Copy_ImageActionPerformed
setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
double h0 = (double)Math.max(10,Math.abs(dd.userSpaceMax.y-dd.userSpaceMin.y));
double w0 = (double)Math.max(10,Math.abs(dd.userSpaceMax.x-dd.userSpaceMin.x));
double h2w = h0/w0;
ClipboardCopy_Image.setClipboard_Image(h2w, dd, diagrPaintUtil);
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
}//GEN-LAST:event_jMenu_Copy_ImageActionPerformed
private void jMenu_ExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu_ExitActionPerformed
closeWindow();
}//GEN-LAST:event_jMenu_ExitActionPerformed
private void jMenuMainWActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuMainWActionPerformed
if(MainFrame.getInstance().getExtendedState()==javax.swing.JFrame.ICONIFIED // minimised?
|| MainFrame.getInstance().getExtendedState()==javax.swing.JFrame.MAXIMIZED_BOTH)
{MainFrame.getInstance().setExtendedState(javax.swing.JFrame.NORMAL);}
MainFrame.getInstance().setEnabled(true);
MainFrame.getInstance().requestFocus();
}//GEN-LAST:event_jMenuMainWActionPerformed
private void jMenuExportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuExportActionPerformed
exportImage();
}//GEN-LAST:event_jMenuExportActionPerformed
private void formComponentMoved(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentMoved
if(!loading) {MainFrame.dispLocation = this.getLocation();}
}//GEN-LAST:event_formComponentMoved
private void jMenuHelpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuHelpActionPerformed
setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
Thread hlp = new Thread() {@Override public void run(){
String[] a = {"S_Diagram_Window_htm"};
lib.huvud.RunProgr.runProgramInProcess(Disp.this,ProgramConf.HELP_JAR,a,false,pc.dbg,pc.pathAPP);
try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec
catch (InterruptedException e) {}
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
}};//new Thread
hlp.start();
}//GEN-LAST:event_jMenuHelpActionPerformed
private void jMenuRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuRefreshActionPerformed
reloadPlotFile();
this.repaint();
}//GEN-LAST:event_jMenuRefreshActionPerformed
private void jMenuWSizeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuWSizeActionPerformed
DiagrWSize d = new DiagrWSize(this, true, this);
d.setVisible(true);
this.setSize(diagrSize);
}//GEN-LAST:event_jMenuWSizeActionPerformed
private void jMenuItemPDFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemPDFActionPerformed
pltConvertFile(plotFile.getAbsolutePath(), "pdf");
}//GEN-LAST:event_jMenuItemPDFActionPerformed
private void jMenuItemPSActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemPSActionPerformed
String type;
if(pd.diagrConvertEPS) {type = "eps";} else {type = "ps";}
pltConvertFile(plotFile.getAbsolutePath(), type);
}//GEN-LAST:event_jMenuItemPSActionPerformed
private void jMenu_Copy_EMFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu_Copy_EMFActionPerformed
copyWith_jVectClipboard(3);
}//GEN-LAST:event_jMenu_Copy_EMFActionPerformed
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Methods">
// --- Public methods:
//<editor-fold defaultstate="collapsed" desc="reloadPlotFile()">
/** does what the name hints: reloads the plot file from the file
* into this object (useful if the file has been modified). */
public void reloadPlotFile() {
if(dd.pltFile_Name == null) {return;}
java.io.File f = new java.io.File(dd.pltFile_Name);
if(!readThePlotFile(f)) {
String t = "Error reading plot file";
MsgExceptn.msg(t);
javax.swing.JOptionPane.showMessageDialog(this, t, pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE);
this.dispose(); return;}
String iconName;
if(icon_type == 1) {iconName = "images/PlotLog256_32x32_whiteBckgr.gif";}
else {iconName = "images/PlotPred256_32x32_whiteBckgr.gif";}
java.net.URL imgURL = this.getClass().getResource(iconName);
if (imgURL != null) {
//System.out.println("Icon image = "+(new java.io.File(imgURL.getPath())).toString());
this.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());}
else {System.out.println("Could not load image = \""+iconName+"\"");}
} // reloadPlotFile
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="printDiagram()">
/**
* @param defaultPrinter if false, a printer dialog is used to allow the user to select a printer
*/
public void printDiagram(boolean defaultPrinter) {
setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
jPanel_XY.setVisible(false);
jPanelDispPlot.requestFocus();
jMenuPrint.setEnabled(false);
jMenuCopyAs.setEnabled(false);
jMenuExport.setEnabled(false);
DiagrPrintUtility.printComponent(jPanelDispPlot, dd, defaultPrinter,
diagrPaintUtil, pc.progName);
jMenuPrint.setEnabled(true);
jMenuCopyAs.setEnabled(true);
jMenuExport.setEnabled(true);
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
} // printDiagram()
//</editor-fold>
// --- Private methods:
//<editor-fold defaultstate="collapsed" desc="copyWith_jVectClipboard">
private void copyWith_jVectClipboard (int i) {
if (i<1 || i>4) {return;}
this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
org.qenherkhopeshef.graphics.vectorClipboard.SimpleClipGraphics
clipGraphics =
new org.qenherkhopeshef.graphics.vectorClipboard.SimpleClipGraphics(
jPanelDispPlot.getWidth(),
jPanelDispPlot.getHeight());
if(i==1) {
clipGraphics.setPictureFormat(
org.qenherkhopeshef.graphics.vectorClipboard.PictureFormat.EMF);
} else if(i==2) {
clipGraphics.setPictureFormat(
org.qenherkhopeshef.graphics.vectorClipboard.PictureFormat.WMF);
} else if(i==3) {
clipGraphics.setPictureFormat(
org.qenherkhopeshef.graphics.vectorClipboard.PictureFormat.DIRECT_EMF);
} else if(i==4) {
clipGraphics.setPictureFormat(
org.qenherkhopeshef.graphics.vectorClipboard.PictureFormat.MACPICT);
}
java.awt.Graphics2D g = clipGraphics.getGraphics();
boolean printing = false;
diagrPaintUtil.paintDiagram(g, jPanelDispPlot.getSize(), dd, printing);
g.dispose();
clipGraphics.copyToClipboard();
this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
System.out.println("Copied to clipboard");
} //copyWith_jVectClipboard
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="closeWindow">
private void closeWindow() {
if(dExp != null) {dExp.closeWindow();}
if(dConv != null) {dConv.closeWindow();}
if(this.getExtendedState()==javax.swing.JFrame.ICONIFIED // minimised?
|| this.getExtendedState()==javax.swing.JFrame.MAXIMIZED_BOTH)
{this.setExtendedState(javax.swing.JFrame.NORMAL);}
MainFrame.dispSize.width = this.getWidth();
MainFrame.dispSize.height = this.getHeight();
MainFrame.dispLocation.x = this.getX();
MainFrame.dispLocation.y = this.getY();
MainFrame.getInstance().setEnabled(true);
MainFrame.getInstance().requestFocus();
this.dispose();
} // closeWindow()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Popup Label_XY">
private void maybeShowPopup(java.awt.event.MouseEvent e) {
if (e.getID() == java.awt.event.MouseEvent.MOUSE_CLICKED ||
e.getID() == java.awt.event.MouseEvent.MOUSE_PRESSED) {
//it is important that the container (jPanel) has "Null Layout"
maybeMovePopup(e);
}
} // maybeShowPopup
private void maybeMovePopup(java.awt.event.MouseEvent e) {
set_jLabel_XY(e.getX(), e.getY());
jPanel_XY.setLocation(e.getX()+5, e.getY()-jLabel_XY.getHeight()-5);
} // maybeMovePopup
private void maybeHidePopup(java.awt.event.MouseEvent e) {
if (e.getID() == java.awt.event.MouseEvent.MOUSE_RELEASED) {
jPanel_XY.setVisible(false);
e.consume();
}
} // maybeHidePopup
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="set_jLabel_XY">
private void set_jLabel_XY(int x, int y) {
float xCoord, yCoord;
java.awt.Dimension windowSize = jPanelDispPlot.getSize();
xCoord = dd.xAxisMin +
((0.01f*(dd.userSpaceMin.x + x *
(dd.userSpaceMax.x - dd.userSpaceMin.x) / windowSize.width)) - dd.xAxis0) * dd.xAxisScale;
yCoord = dd.yAxisMin +
((0.01f*(dd.userSpaceMax.y - y *
(dd.userSpaceMax.y - dd.userSpaceMin.y) /windowSize.height)) - dd.yAxis0) * dd.yAxisScale;
if (xCoord > dd.xAxisMax_true || xCoord < dd.xAxisMin_true)
{jPanel_XY.setVisible(false);return;}
if (yCoord > dd.yAxisMax_true || yCoord < dd.yAxisMin_true)
{jPanel_XY.setVisible(false);return;}
jPanel_XY.setVisible(true);
String tXformat; String tYformat;
float abs = Math.abs(xCoord);
if(abs >1 && abs <=9999.9) {tXformat="####0.00";}
else if(abs >0.1 && abs <=1) {tXformat="#0.000";}
else if(abs >0.01 && abs <=0.1) {tXformat="#0.0000";}
else if(abs >0.001 && abs <=0.01) {tXformat="#0.00000";}
else {tXformat="#1.00E00";} // if(abs >9999.9 || abs <=0.0001)
abs = Math.abs(yCoord);
if(abs >1 && abs <=9999.9) {tYformat="####0.00";}
else if(abs >0.1 && abs <=1) {tYformat="#0.000";}
else if(abs >0.01 && abs <=0.1) {tYformat="#0.0000";}
else if(abs >0.001 && abs <=0.01) {tYformat="#0.00000";}
else {tYformat="#1.00E00";} // if(abs >9999.9 || abs <=0.0001)
myFormatter.applyPattern(tXformat);
String txt = "<html> x:" + myFormatter.format(xCoord);
myFormatter.applyPattern(tYformat);
txt = txt + "<br> y:" + myFormatter.format(yCoord) + "</html>";
jLabel_XY.setText(txt);
//jLabel_XY.setText("<html> x:"+dfp(tXformat,x_coord)+
// "<br> y:"+dfp(tYformat,y_coord)+"</html>");
jPanel_XY.setSize((int)jLabel_XY.getSize().width, 3+(int)jLabel_XY.getSize().height);
} //set_jLabel_XY
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="readThePlotFile">
private boolean readThePlotFile(java.io.File f) {
// read the plot file and store the information in an instance of
// DiagrData, which will be used to repaint the diagram from memory
this.dd = new GraphLib.PltData();
dd.pltFile_Name = f.getPath();
dd.fileLastModified = new java.util.Date(f.lastModified());
java.io.BufferedReader bufReader;
try{bufReader = new java.io.BufferedReader(
new java.io.InputStreamReader(
new java.io.FileInputStream(f),"UTF8"));
} catch (Exception e) {
String msg = "Error: \""+e.toString()+"\""+nl+nl+
"For plot file:"+f.getPath();
MsgExceptn.exception(msg);
javax.swing.JOptionPane.showMessageDialog(this, msg,
pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE);
return false;}
dd.axisInfo = false;
dd.xAxisL=0f; dd.yAxisL=0f;
dd.xAxis0=0f; dd.yAxis0=0f;
boolean readingText = false;
int align = 0;
icon_type = 1;
boolean axisInfo1 = false; boolean axisInfo2 = false;
int i0, i1, i2;
StringBuilder line = new StringBuilder();
String comment;
int penColour = 5; int currentColour = 1;
// ----- read all lines
String l;
do {
try {l = bufReader.readLine();}
catch (java.io.IOException e) {
String msg = "Error: \""+e.toString()+"\""+nl+nl+
"For plot file:"+f.getPath();
javax.swing.JOptionPane.showMessageDialog(this,msg,
pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE);
return false;} //catch
if (line.length()>0) {line.delete(0, line.length());}
if (l != null) {
line.append(l);
String s0, s1, s2;
if (line.length() > 0) {s0= line.substring(0,1).trim();} else {s0 = "";}
if (line.length() > 4) {s1= line.substring(1,5).trim();} else {s1 = "";}
if (line.length() > 8) {s2= line.substring(5,9).trim();} else {s2 = "";}
// get comments
if (line.length() > 9) {
comment= line.substring(9).trim();
if (comment.length()>12 && (comment.substring(0, 12).equals("-- PREDOM DI") ||
comment.substring(0, 12).equals("-- PREDOM2 D")))
{icon_type = 2;}
} else {comment = "";}
if (s0.length() > 0) {i0 = readInt(s0);} else {i0 = -1;}
if (s1.length() > 0) {i1 = readInt(s1);} else {i1 = 0;}
if (s2.length() > 0) {i2 = readInt(s2);} else {i2 = 0;}
if (i0==0 || i0==1) {
if(i1<dd.userSpaceMin.x) {dd.userSpaceMin.x = i1;}
if(i1>dd.userSpaceMax.x) {dd.userSpaceMax.x = i1;}
if(i2<dd.userSpaceMin.y) {dd.userSpaceMin.y = i2;}
if(i2>dd.userSpaceMax.y) {dd.userSpaceMax.y = i2;}
if (!diagrPaintUtil.textWithFonts || !readingText)
{dd.pltFileAList.add(new GraphLib.PltData.PlotStep(i0, i1, i2));
// for non-static class use:
//dd.plt_fileAList.add(dd.new PlotStep(I0, I1, I2));
}
} // if draw/move line
if (i0==5 || i0==8) {
penColour = i0; currentColour = i1;
dd.pltFileAList.add(new GraphLib.PltData.PlotStep(i0,i1,i2));
} // if colour/pen change
//---- read axis information if available
if (comment.equals("-- AXIS --")) {axisInfo1 = true;}
if (axisInfo1 && i0 == 8 &&
comment.length()>64 &&
comment.substring(0,9).equals("Size, X/Y"))
{axisInfo2 = true;
dd.xAxisL = readFloat(comment.substring(34,42));
dd.yAxisL = readFloat(comment.substring(42,50));
dd.xAxis0 = readFloat(comment.substring(50,58));
dd.yAxis0 = readFloat(comment.substring(58,comment.length()));
}
if (axisInfo1 && axisInfo2 && i0 == 0 &&
comment.length()>60 &&
comment.substring(0,9).equals("X/Y low a"))
{dd.axisInfo = true;
//these are used when displaying the xy-label
// when the user click the mouse button on a diagram
dd.xAxisMin = readFloat(comment.substring(18,29));
dd.xAxisMax = readFloat(comment.substring(29,40));
dd.yAxisMin = readFloat(comment.substring(40,51));
dd.yAxisMax = readFloat(comment.substring(51,comment.length()));
float tmp;
dd.xAxisMin_true = dd.xAxisMin;
dd.xAxisMax_true = dd.xAxisMax;
if (dd.xAxisMin_true > dd.xAxisMax_true)
{tmp = dd.xAxisMax_true;
dd.xAxisMax_true = dd.xAxisMin_true;
dd.xAxisMin_true = tmp;}
dd.yAxisMin_true = dd.yAxisMin;
dd.yAxisMax_true = dd.yAxisMax;
if (dd.yAxisMin_true > dd.yAxisMax_true)
{tmp = dd.yAxisMax_true;
dd.yAxisMax_true = dd.yAxisMin_true;
dd.yAxisMin_true = tmp;}
float x = Math.abs(dd.xAxisMax - dd.xAxisMin) * 0.01f;
dd.xAxisMin_true = dd.xAxisMin_true - x;
dd.xAxisMax_true = dd.xAxisMax_true + x;
float y = Math.abs(dd.yAxisMax - dd.yAxisMin) * 0.01f;
dd.yAxisMin_true = dd.yAxisMin_true - y;
dd.yAxisMax_true = dd.yAxisMax_true + y;
dd.xAxisScale = (dd.xAxisMax - dd.xAxisMin) / dd.xAxisL;
dd.yAxisScale = (dd.yAxisMax - dd.yAxisMin) / dd.yAxisL;
} // axisInfo
//---- end of reading axis information
if (diagrPaintUtil.textWithFonts) {
// read a TextBegin-TextEnd
boolean isFormula; float txtSize; float txtAngle;
if (comment.equals("-- HEADING --")) {align = -1;}
if (i0 == 0 && comment.length()>41 && comment.startsWith("TextBegin")) {
isFormula = comment.substring(9,10).equals("C");
txtSize = readFloat(comment.substring(17,24));
txtAngle = readFloat(comment.substring(35,42));
//get angles between +180 and -180
while (txtAngle>360) {txtAngle=txtAngle-360f;}
while (txtAngle<-360) {txtAngle=txtAngle+360f;}
if(txtAngle>180) {txtAngle=txtAngle-360f;}
if(txtAngle<-180) {txtAngle=txtAngle+360f;}
// get alignment
if(comment.length() > 42) {
String t = comment.substring(55,56);
if(t.equalsIgnoreCase("L")) {align = -1;}
else if(t.equalsIgnoreCase("R")) {align = 1;}
else if(t.equalsIgnoreCase("C")) {align = 0;}
}
// the text is in next line
if(line.length()>0) {line.delete(0, line.length());}
try {l = bufReader.readLine();}
catch (java.io.IOException e) {
String msg = "Error: \""+e.toString()+"\""+nl+nl+
"For plot file:"+f.getPath();
javax.swing.JOptionPane.showMessageDialog(this, msg,
pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE);
return false;
} //catch
if(l != null) {line.append(l);} else {line.append("null");}
if(!line.toString().equals("null")) {
if (line.length()>9) {
comment= Util.rTrim(line.substring(9));
if(comment.startsWith(" ")) {comment = comment.substring(1);}
} else {comment = "";}
// addjust userSpaceMax and userSpaceMin
textBoxMinMax(i1, i2, (txtSize * 100f),
(txtSize*100f*comment.length()), txtAngle, dd);
// exchange "-" for minus sign
if(isFormula) {comment = replaceMinusSign(comment);}
// save the text to print
dd.pltTextAList.add(new GraphLib.PltData.PlotText(i1, i2,
isFormula, align, txtSize,txtAngle, comment,
penColour, currentColour));
} // if line != null
// ------ read all lines until "TextEnd"
readingText = true;
} // end reading a TextBegin - TextEnd
if (comment.equals("TextEnd")) {readingText = false;}
} // if textWithFonts
} // if line != null
} while (l != null); // do-while
try {bufReader.close();}
catch (java.io.IOException ex) {
String msg = "Error: \""+ex.toString()+"\""+nl+nl+"For plot file: "+f.getPath();
javax.swing.JOptionPane.showMessageDialog(this, msg,
pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE);
}
// set the "UserSpace" dimensions
if (dd.userSpaceMax.x == Integer.MIN_VALUE) {dd.userSpaceMax.x = 2100;}
if (dd.userSpaceMin.x == Integer.MAX_VALUE) {dd.userSpaceMin.x = 0;}
if (dd.userSpaceMax.y == Integer.MIN_VALUE) {dd.userSpaceMax.y = 1500;}
if (dd.userSpaceMin.y == Integer.MAX_VALUE) {dd.userSpaceMin.y = 0;}
float xtra = 0.02f; //add 1% extra space all around
float userSpace_w = Math.abs(dd.userSpaceMax.x - dd.userSpaceMin.x);
int xShift = Math.round(Math.max( (100f-userSpace_w)/2f, userSpace_w*xtra ) );
dd.userSpaceMax.x = dd.userSpaceMax.x + xShift;
dd.userSpaceMin.x = dd.userSpaceMin.x - xShift;
userSpace_w = Math.abs(dd.userSpaceMax.y - dd.userSpaceMin.y);
int yShift = Math.round(Math.max( (100f-userSpace_w)/2f, userSpace_w*xtra ) );
dd.userSpaceMax.y = dd.userSpaceMax.y + yShift;
dd.userSpaceMin.y = dd.userSpaceMin.y - yShift;
//these are used when displaying the xy-label
// when the user click the mouse button on a diagram
return true;
} // readThePlotFile (File)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="textBoxMinMax">
/** Finds out the bounding box around a text, (adding some margins on top and bottom
* to allow for super- and sub-scripts). Adjusts dd.userSpaceMin and dd.userSpaceMax
* using this bounding box.
* @param i1 the x-value for the bottom-left corner
* @param i2 the y-value for the bottom-left corner
* @param height the height of the letters of the text in the same coordinates
* as "i1" and "i2"
* @param width the width of the text in the same coordinates
* as "i1" and "i2"
* @param angle the angle in degrees
* @param dd */
private static void textBoxMinMax (int i1, int i2,
float height, float width, float angle,
GraphLib.PltData dd) {
final double DEG_2_RAD = 0.017453292519943;
final double a0 = angle * DEG_2_RAD;
final double a1 = (angle + 90) * DEG_2_RAD;
final float h = height * 2f;
final float w = width;
java.awt.Point p0 = new java.awt.Point();
java.awt.Point p1 = new java.awt.Point();
p0.x = i1 - (int)((height) * (float)Math.cos(a1));
p0.y = i2 - (int)((height) * (float)Math.sin(a1));
if(p0.x<dd.userSpaceMin.x) {dd.userSpaceMin.x = p0.x;}
if(p0.x>dd.userSpaceMax.x) {dd.userSpaceMax.x = p0.x;}
if(p0.y<dd.userSpaceMin.y) {dd.userSpaceMin.y = p0.y;}
if(p0.y>dd.userSpaceMax.y) {dd.userSpaceMax.y = p0.y;}
p0.x = i1 + (int)(w * (float)Math.cos(a0));
p0.y = i2 + (int)(w * (float)Math.sin(a0));
if(p0.x<dd.userSpaceMin.x) {dd.userSpaceMin.x = p0.x;}
if(p0.x>dd.userSpaceMax.x) {dd.userSpaceMax.x = p0.x;}
if(p0.y<dd.userSpaceMin.y) {dd.userSpaceMin.y = p0.y;}
if(p0.y>dd.userSpaceMax.y) {dd.userSpaceMax.y = p0.y;}
p1.x = p0.x + (int)(h * (float)Math.cos(a1));
p1.y = p0.y + (int)(h * (float)Math.sin(a1));
if(p1.x<dd.userSpaceMin.x) {dd.userSpaceMin.x = p1.x;}
if(p1.x>dd.userSpaceMax.x) {dd.userSpaceMax.x = p1.x;}
if(p1.y<dd.userSpaceMin.y) {dd.userSpaceMin.y = p1.y;}
if(p1.y>dd.userSpaceMax.y) {dd.userSpaceMax.y = p1.y;}
p0.x = i1 + (int)(h * (float)Math.cos(a1));
p0.y = i2 + (int)(h * (float)Math.sin(a1));
if(p0.x<dd.userSpaceMin.x) {dd.userSpaceMin.x = p0.x;}
if(p0.x>dd.userSpaceMax.x) {dd.userSpaceMax.x = p0.x;}
if(p0.y<dd.userSpaceMin.y) {dd.userSpaceMin.y = p0.y;}
if(p0.y>dd.userSpaceMax.y) {dd.userSpaceMax.y = p0.y;}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="readInt(String)">
private static int readInt(String t) {
int i;
try{i = Integer.parseInt(t);}
catch (NumberFormatException ex) {
MsgExceptn.exception("Error: "+ex.toString()+nl+
" while reading an integer from String: \""+t+"\"");
i = 0;}
return i;
} //readFloat(T)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="readFloat(String)">
private static float readFloat(String t) {
float f;
try{f = Float.parseFloat(t);}
catch (NumberFormatException ex) {
MsgExceptn.exception("Error: "+ex.toString()+nl+
" while reading a \"float\" from String: \""+t+"\"");
f = 0f;}
return f;
} //readFloat(T)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="replaceMinusSign (String)">
/** replace hyphen "-" by minus, except betwen two letters */
private static String replaceMinusSign (String t) {
// change "-" for Unicode minus sign
final char M='\u2013'; // Unicode En Dash = \u2013; Minus Sign = \u2212
int tLength = t.length();
if (tLength<=1 || t.indexOf('-')<0) {return t;}
StringBuilder sb = new StringBuilder();
sb.append(t);
int l, now, n; //last, now and next characters
// check for a minus at the beginning
now = sb.charAt(0);
if(now =='-') {sb.setCharAt(0, M);}
// loop
for (int i=1; i<tLength; i++) {
now = sb.charAt(i);
if(now !='-') {continue;}
l = sb.charAt(i-1);
if(i<=(tLength-2)) {n = sb.charAt(i+1);} else {n = 32;} // next character
if( ((l>=65 && l<=90) // upper case letter
|| (l>=97 && l<=122)) // lower case letter
&&
((n>=65 && n<=90) // upper case letter
|| (n>=97 && n<=122)) ) // lower case letter)
{continue;}
sb.setCharAt(i, M);
} // for i
return sb.toString();
} // replaceMinusSign
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="pltConvertFile">
/** Convert a plot file to another vector graphics format.
* @param pltFile
* @param type a text specifying the new graphic format.
* Must be one of: ps, eps, pdf.
*/
private void pltConvertFile(String pltFile, String type) {
if(dConv != null) {
MsgExceptn.exception("Error: \"dConv\" is not null.");
return;
}
if(pltFile == null || pltFile.trim().length() <=0) {
MsgExceptn.exception("Programming Error in \"pltConvertFile\": empty file name.");
return;
}
String t = null;
if(type != null) {t = type.toLowerCase();}
if(t == null || t.length()<2 || t.length() >3 ||
(!t.equals("pdf") && !t.equals("ps") && !t.equals("eps"))) {
MsgExceptn.exception("Programming Error in \"pltConvertFile\""+nl+
" type = \""+type+"\""+nl+
" must be one of: pdf, ps or eps.");
return;
}
jMenuConvert.setEnabled(false);
jMenuItemPDF.setEnabled(false);
jMenuItemPS.setEnabled(false);
pc.setPathDef(pltFile);
final String pltName = pltFile;
final int typ;
if(t.equals("pdf")) {typ = 1;}
else if(t.equals("ps")) {typ = 2;}
else if(t.equals("eps")) {typ = 3;}
else {typ = -1;}
//---- do the conversion
Thread c = new Thread() {@Override public void run(){
dConv = new DiagrConvert(pc,pd, dd);
dConv.start(typ, pltName);
dConv.waitFor();
//dConv.dispose();
dConv = null;
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
jMenuConvert.setEnabled(true);
jMenuItemPDF.setEnabled(true);
jMenuItemPS.setEnabled(true);
}}); //invokeLater(Runnable)
}};//new Thread
c.start();
} //pltConvertFile
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="exportImage(type)">
private void exportImage() {
if(dExp != null) {
MsgExceptn.exception("Error: dExp is not null.");
return;
}
jMenuExport.setEnabled(false);
Thread c = new Thread() {@Override public void run(){
double h0 = (double)Math.max(10,Math.abs(dd.userSpaceMax.y-dd.userSpaceMin.y));
double w0 = (double)Math.max(10,Math.abs(dd.userSpaceMax.x-dd.userSpaceMin.x));
double h2w = h0/w0;
dExp = new DiagrExport(pc, pd, h2w);
boolean cancel;
if(dExp.start(plotFile.getAbsolutePath())) {
cancel = dExp.waitFor();
} else {
cancel = true;
}
dExp = null;
if(!cancel) {export(pd.diagrExportType, true);}
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
jMenuExport.setEnabled(true);
}}); //invokeLater(Runnable)
}};//new Thread
c.start();
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="export(type)">
/** Export the plot file to some pixel format.
* The size of the image is the size selected by the user in the last export,
* or the default value if the user has not yet made any manual export.
* @param type one of the supported formats (bmp, jpg, png, etc)
* @param showMsgBox show a message box at the end?
*/
public void export(String type, boolean showMsgBox) {
if(type == null || type.length() <= 0) {
MsgExceptn.exception("Error in \"export(type)\": empty type.");
return;
}
boolean fnd = false;
for(String t : MainFrame.FORMAT_NAMES) {if(type.equalsIgnoreCase(t)) {fnd = true; break;}}
if(!fnd) {
String msg = "Error in \"export(\""+type+"\")\":"+nl+
"Type not supported."+nl+"Should be one of: ";
for(String t : MainFrame.FORMAT_NAMES) {msg = " "+msg + t + ", ";}
msg = msg.substring(0,msg.length()-2);
msg = msg + ".";
MsgExceptn.exception(msg);
return;
}
//---- get the file name after conversion
String pltFileFullName;
try{pltFileFullName = plotFile.getCanonicalPath();}
catch (java.io.IOException ex) {
try{pltFileFullName = plotFile.getAbsolutePath();}
catch (Exception e) {pltFileFullName = plotFile.getPath();}
}
String convertedFileFullN = Div.getFileNameWithoutExtension(pltFileFullName)+"."+type.toLowerCase();
java.io.File convertedFile = new java.io.File(convertedFileFullN);
if(pc.dbg) {System.out.println("Exporting file \""+plotFile.getName()+"\" to "+type.toUpperCase()+"-format");}
int w, h;
double h0 = (double)Math.max(10,Math.abs(dd.userSpaceMax.y-dd.userSpaceMin.y));
double w0 = (double)Math.max(10,Math.abs(dd.userSpaceMax.x-dd.userSpaceMin.x));
if((h0/w0) < 1) {
w = pd.diagrExportSize;
h = (int)((double)pd.diagrExportSize * (h0/w0));
} else {
h = pd.diagrExportSize;
w = (int)((double)pd.diagrExportSize / (h0/w0));
}
int i = java.awt.image.BufferedImage.TYPE_INT_RGB;
if(type.equalsIgnoreCase("wbmp")) {i = java.awt.image.BufferedImage.TYPE_BYTE_BINARY;}
java.awt.image.BufferedImage bi = new java.awt.image.BufferedImage(w, h, i);
java.awt.Graphics2D ig2 = bi.createGraphics();
if(diagrPaintUtil.useBackgrndColour) {
ig2.setColor(diagrPaintUtil.backgrnd);
} else {
ig2.setColor(java.awt.Color.WHITE);
}
ig2.fillRect(0, 0, w, h);
diagrPaintUtil.paintDiagram(ig2, new java.awt.Dimension(w,h), dd, false);
long fileDate0 = convertedFile.lastModified();
try{
javax.imageio.ImageIO.write(bi, type.toLowerCase(), convertedFile);
} catch (java.io.IOException ioe) {
MsgExceptn.exception(ioe.toString()+nl+Util.stack2string(ioe));
}
ig2.dispose();
// bi = null; // garbage collect
long fileDate = convertedFile.lastModified();
if(fileDate > fileDate0) {
System.out.println("Created "+type+"-file: \""+convertedFile.getName()+"\"");
if(showMsgBox) {
String msg = "<html>Created "+type+"-file:<br>"+
"<b>\""+convertedFile.getName()+"\"</b></html>";
javax.swing.JOptionPane.showMessageDialog(Disp.this, msg,
pc.progName,javax.swing.JOptionPane.INFORMATION_MESSAGE);
}
System.out.flush();
} else {
if(showMsgBox) {
javax.swing.JOptionPane.showMessageDialog(Disp.this,
"<html>Failed to create file:<br>"+
"<b>\""+convertedFile.getName()+"\"</b></html>",
pc.progName,javax.swing.JOptionPane.ERROR_MESSAGE);
} else {
System.err.println("---- Failed to create "+type+"-file: \""+convertedFile.getName()+"\" !");
System.err.flush();
}
}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="setAdvancedFeatures(boolean)">
final void setAdvancedFeatures(boolean advanced) {
jMenuWSize.setVisible(advanced);
} //readFloat(T)
//</editor-fold>
//</editor-fold>
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel_XY;
private javax.swing.JMenu jMenu;
private javax.swing.JMenuBar jMenuBar;
private javax.swing.JMenu jMenuConvert;
private javax.swing.JMenu jMenuCopyAs;
private javax.swing.JMenuItem jMenuExport;
private javax.swing.JMenuItem jMenuHelp;
private javax.swing.JMenu jMenuHlp;
private javax.swing.JMenuItem jMenuItemPDF;
private javax.swing.JMenuItem jMenuItemPS;
private javax.swing.JMenuItem jMenuMainW;
private javax.swing.JMenuItem jMenuPrint;
private javax.swing.JMenuItem jMenuRefresh;
private javax.swing.JMenuItem jMenuWSize;
private javax.swing.JMenuItem jMenu_Copy_EMF;
private javax.swing.JMenuItem jMenu_Copy_EMF_RTF;
private javax.swing.JMenuItem jMenu_Copy_Image;
private javax.swing.JMenuItem jMenu_Copy_MacPict;
private javax.swing.JMenuItem jMenu_Copy_WMF_RTF;
private javax.swing.JMenuItem jMenu_Exit;
private javax.swing.JPanel jPanel_XY;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JPopupMenu.Separator jSeparator2;
// End of variables declaration//GEN-END:variables
} // public class Disp
| 55,511 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
OneInstance.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Spana/src/spana/OneInstance.java | package spana;
/** The method <b>findOtherInstance</b> returns true if another instance
* of the application is already running in another JVM.
* <p>
* A server socket is used. The application tries to connect to the socket.
* If a server is not found, the socket is free and the server socket is
* constructed. If a server is found and a connection is made, it means that
* the application is already running. In that case the command line arguments
* are sent to other instance.
* <p>
* Modify the code after lines containing <code>"==="</code>.
* <p>
* <b>Use "getInstance()" instead of creating a new OneInstance()!</b>
* <p>
* Copyright (C) 2014-2016 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class OneInstance {
private static OneInstance one = null;
private static final String knockKnock = "Ett skepp kommer lastad";
private boolean dbg;
private String progName;
private int port;
private java.net.ServerSocket serverSocket = null;
private java.net.Socket socket;
private java.io.BufferedReader socketIn;
private java.io.PrintWriter socketOut;
private String whosThere;
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
/** Find out if another instance of the application is already running in another JVM.
* <p>
* A server socket is used. The application tries to connect to the socket.
* If a server is not found, the socket is free and the server socket is
* constructed. If a server is found and a connection is made, it means that
* the application is already running. In that case the command line arguments
* are sent to other instance.
* <p>
* Modify the code after lines containing <code>"==="</code>.
* <p>
* Use "getInstance()" instead of creating a new OneInstance()!
* @param args the command line arguments to the main method of the application.
* The arguments are sent to the other instance through the server socket.
* Not used if no other instance of the application is found.
* @param portDef a port to search for a server socket.
* If no other application is found, at least five additional sockets are tried.
* @param prgName the application's name, used for message and error reporting.
* @param debg true if performance messages are wished.
* @return true if another instance is found, false otherwise. */
public boolean findOtherInstance(
final String[] args,
final int portDef,
final String prgName,
final boolean debg) {
if(one != null) {
String msg;
if(prgName != null && prgName.trim().length() >0) {msg = prgName;} else {msg = "OneInstance";}
if(debg) {System.out.println(msg+"- findOtherInstance already running.");}
return false;
} else {
one = this;
}
dbg = debg;
if(prgName != null && prgName.trim().length() >0) {progName = prgName;} else {progName = "OneInstance";}
whosThere = progName;
// loop though sockets numbers, if a socket is busy check if it is
// another instance of this application
//<editor-fold defaultstate="collapsed" desc="first loop">
port = portDef;
int portNbrMax = portDef + 5;
java.net.InetAddress address = null;
do{
// note: testing a client socket (creating a stream socket and connecting it)
// would be much more time consuming
try{
serverSocket = new java.net.ServerSocket(port);
if(dbg){System.out.println(progName+"- socket "+port+" is not used.");}
serverSocket.close();
serverSocket = null;
port++;
} catch (java.net.BindException ex) {
if(dbg){System.out.println(progName+"- socket "+port+" busy. Another instance already running?");}
if(address == null) {
try {
address = java.net.InetAddress.getLocalHost();
if(dbg){System.out.println(progName+"- Local machine address: "+address.toString());}
}
catch (java.net.UnknownHostException e) {
System.out.println(progName+"- "+e.toString()+" using getLocalHost().");
address = null;
} //catch
}
if(!isOtherInstance(address, port)) {
//Not another instance. It means some software is using
// this socket port number; continue looking...
if(socketOut != null) {socketOut.close(); socketOut = null;}
if(socketIn != null) {
try{socketIn.close();} catch (java.io.IOException ioe) {}
socketIn = null;
}
socket = null;
port++;
} else {
//Another instance of this software is already running:
// send args[] and end the program (exit from "main")
sendArgsToOtherInstance(args);
return true;
}
} catch (java.io.IOException ex) { // there should be no error...
System.err.println(progName+"- "+ex.toString()+nl+" while creating a stream Socket.");
break;
} // catch
} while (port < portNbrMax); // do-while
if(socketOut != null) {socketOut.close(); socketOut = null;}
if(socketIn != null) {
try{socketIn.close();} catch (java.io.IOException ioe) {}
socketIn = null;
}
socket = null;
// address = null; // garbage collect
//</editor-fold>
// Another instance not found: create a server socket on the first free port
//<editor-fold defaultstate="collapsed" desc="create server socket">
port = portDef;
do{
try{
serverSocket = new java.net.ServerSocket(port);
if(dbg){System.out.println(progName+"- Created server socket on port "+port);}
break;
} catch (java.net.BindException ex) {
if(dbg){System.out.println(progName+"- socket "+port+" is busy.");}
port++;
} //Socket busy
catch (java.io.IOException ex) { // there should be no error...
System.err.println(progName+"- "+ex.toString()+nl+" while creating a Server Socket.");
break;
}
} while (port < portNbrMax); // do-while
//</editor-fold>
if(port == portNbrMax) {
System.out.println(progName+"- Error: could not create a server socket.");
return false;
}
// A Server Socket has been created.
// Wait for new connections on the serverSocket on a separate thread.
// The program will continue execution simultaenously...
//<editor-fold defaultstate="collapsed" desc="accept clients thread">
Thread t = new Thread(){@Override public void run(){
while(true){
final java.net.Socket client;
try{ // Wait until we get a client in serverSocket
if(dbg){System.out.println(progName+"- waiting for a connection to serverSocket("+port+").");}
// this will block until a connection is made:
client = serverSocket.accept();
}
catch (java.net.SocketException ex) {break;}
catch (java.io.IOException ex) {
System.err.println(progName+"- "+ex.toString()+nl+" Accept failed on server port: "+port);
break; //while
}
//Got a connection, wait for lines of text from the new connection (client)
//<editor-fold defaultstate="collapsed" desc="deal with a client thread">
if(dbg){System.out.println(progName+"- connection made to serverSocket in port "+port);}
Thread t = new Thread(){@Override public void run(){
String line;
boolean clientNewInstance = false;
boolean connected = true;
java.io.BufferedReader in = null;
java.io.PrintWriter out = null;
try{
client.setSoTimeout(3000); // avoid socket.readLine() lock
in = new java.io.BufferedReader(new java.io.InputStreamReader(client.getInputStream()));
out = new java.io.PrintWriter(client.getOutputStream(), true);
if(dbg){System.out.println(progName+"- while (connected)");}
while(connected){
if(dbg){System.out.println(progName+"- (waiting for line from client)");}
// wait for a line of text from the client
// note: client.setSoTimeout(3000) means
// SocketTimeoutException after 3 sec
line = in.readLine();
if(line == null) {break;}
if(dbg){System.out.println(progName+"- got line from client (in port "+port+"): "+line);}
// is this another instance asking who am I?
if(line.toLowerCase().equals(knockKnock.toLowerCase())) {
// yes: another instance calling!
// === add code here to bring this instance to front ===
// --- for HelpWindow.java:
//if(HelpWindow.getInstance() != null) {
// HelpWindow.getInstance().bringToFront();
// if(dbg) {System.out.println(progName+"- bringToFront()");}
//}
// --- for Spana:
if(MainFrame.getInstance() != null) {MainFrame.getInstance().bringToFront();}
// --- for Database:
//if(FrameDBmain.getInstance() != null) {FrameDBmain.getInstance().bringToFront();}
// ---
//answer to client with program identity
if(dbg){System.out.println(progName+"- sending line to client (at port "+port+"): "+whosThere);}
out.println(whosThere);
clientNewInstance=true;
} else {// line != knockKnock
if(clientNewInstance) {
// === add code here to deal with the command-line arguments ===
// from the new instance sendt to this instance
// --- for HelpWindow.java:
//if(HelpWindow.getInstance() != null) {
// HelpWindow.getInstance().bringToFront();
// HelpWindow.getInstance().setHelpID(line);
//}
// --- for Spana:
if(MainFrame.getInstance() != null) {MainFrame.getInstance().dispatchArg(line);}
// --- for Database:
//if(FrameDBmain.getInstance() != null) {FrameDBmain.getInstance().dispatchArg(line);}
// ---
} else { //not clientNewInstance
if(dbg){System.err.println(progName+"- Warning: got garbage in port "+port+" from another application; line = \""+line+"\"");}
connected = false; // close the connection
}
} //line = knockKnock ?
} // while(connected)
out.close(); out = null;
in.close(); in = null;
client.close();
} catch (java.io.IOException ioe) {
System.err.println(progName+"- Note: "+ioe.toString()+nl+" Closing socket connection in port "+port);
} finally {
if(dbg){System.out.println(progName+"- Connection to serverSocket("+port+") closed ");}
if(out != null) {out.close();}
try{ if(in != null) {in.close();} client.close(); }
catch (java.io.IOException ioe) {}
}
}};
t.start(); // "start" returns inmediately without waiting.
//</editor-fold>
// wait for next connection....
} // while(true)
}};
t.start(); // "start" returns inmediately without waiting.
//</editor-fold>
//-------------------------------------------------------------
// Finished checking for another instance
//-------------------------------------------------------------
return false; // found no other instance
}
//<editor-fold defaultstate="collapsed" desc="isOtherInstanceInSocket">
// -------------------------------
/** Checking for another instance:<br>
* The first instance of this program opens a server socket connection and
* listens for other instances of this program to send messages. The
* first instance also creates a "lock" file containing the socket number.
* This method tries to send a message to a socket, and checks if the
* response corresponds to that expected from the first instance of this
* application. If the response is correct, it returns true.
* @param port the socket number to try
* @return <code>true</code> if another instance of this program is
* listening at this socket number; <code>false</code> if either
* an error occurs, no response is obtained from this socket within one sec,
* or if the answer received is not the one expected from the first instance.
*/
private boolean isOtherInstance(final java.net.InetAddress address, final int port) {
if (port <= 0) {return false;}
if(dbg){System.out.println(progName+"- isOtherInstance("+port+") ?");}
// Create socket connection
String line;
boolean ok;
try{
socket = new java.net.Socket(address, port);
socket.setSoTimeout(1000); // avoid socket.readLine() lock
socketOut = new java.io.PrintWriter(socket.getOutputStream(), true);
socketIn = new java.io.BufferedReader(
new java.io.InputStreamReader(socket.getInputStream()));
//Send data over socket
if(dbg){System.out.println(progName+"- Sending text:\""+knockKnock+"\" to port "+port);}
socketOut.println(knockKnock);
//Receive text from server.
if(dbg){System.out.println(progName+"- Reading answer from socket "+port);}
// note: socket.setSoTimeout(1000) means
// SocketTimeoutException after 1 sec
try{
line = socketIn.readLine();
if(dbg){System.out.println(progName+"- Text received: \"" + line + "\" from port "+port);}
} catch (java.io.IOException ex){
line = null;
System.err.println(progName+"- Note: "+ex.toString()+nl+" in socket("+port+").readLine()");
} //catch
// did we get the correct answer?
if(line != null && line.toLowerCase().startsWith(whosThere.toLowerCase())) {
if(dbg){System.out.println(progName+"- isOtherInstance("+port+") = true");}
ok = true;
} else {
if(dbg){System.out.println(progName+"- isOtherInstance("+port+") = false");}
ok = false;
}
} catch (java.io.IOException ex) {
System.out.println(progName+"- "+ex.toString()+", isOtherInstance("+port+") = false");
ok = false;
}
return ok;
// -------------------------------------
} // isOtherInstance(port)
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="sendArgsToOtherInstance">
// -------------------------------
/** Checking for another instance:<br>
* The first instance of this program opens a server socket connection and
* listens for other instances of this program to send messages. The
* first instance also creates a "lock" file containing the socket number.
* This method assumes that this is a "2nd" instance of this program
* and it sends the command-line arguments from this instance to the
* first instance, through the socket connetion.
*
* <p>The connection is closed and the program ends after sending the
* arguments.</p>
*
* @param args <code>String[]</code> contains the command-line
* arguments given to this instance of the program.
*/
private void sendArgsToOtherInstance(String args[]) {
if(socketOut == null) {return;}
if(args != null && args.length >0) {
for (String arg : args) {
if(dbg){System.out.println(progName+"- sending command-line arg to other instance: \"" + arg + "\"");}
socketOut.println(arg);
} // for arg
} // if args.length >0
try {
if(socketIn != null) {socketIn.close(); socketIn = null;}
if(socketOut != null) {socketOut.close(); socketOut = null;}
socket = null;
} catch (java.io.IOException ex) {
System.out.println(progName+"- "+ex.toString()+", while closing streams.");
}
// --------------------------------
} //sendArgsToOtherInstance(args[])
// </editor-fold>
/** Use this method to get the instance of this class to start
* a the server socket thread, instead of constructing a new object.
* @return an instance of this class
* @see OneInstance#endCheckOtherInstances() endCheckOtherInstances */
public static OneInstance getInstance() {return one;}
/** Stops the server socket thread. */
public static void endCheckOtherInstances() {
if(one != null) {
try{one.serverSocket.close(); one.serverSocket = null; one = null;} catch (java.io.IOException ex) {}
}
}
}
| 18,886 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
DiagrPrintUtility.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Spana/src/spana/DiagrPrintUtility.java | package spana;
import lib.common.MsgExceptn;
import lib.kemi.graph_lib.DiagrPaintUtility;
import lib.kemi.graph_lib.GraphLib;
/** Prints a java.awt.Component (in this case a JPanel).
* <br>
* Adapted from
* http://aplcenmp.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-Printing.html
* <br>
* without restrictions as specified on their web site. To quote the link above:
* <i>All source code freely available for unrestricted use.</i>
* <p>
* Copyright (C) 2014-2018 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class DiagrPrintUtility implements java.awt.print.Printable {
private final java.awt.Component componentToBePrinted;
private final GraphLib.PltData dd; // contains the info in the plt-file;
// the methods in DiagrPaintUtility are used to paint the diagram
private final DiagrPaintUtility diagrPaintUtil;
private boolean defaultPrinter = false;
private final String prgName;
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
private DiagrPrintUtility(java.awt.Component componentToBePrinted,
GraphLib.PltData dD,
boolean defaultPrinter,
DiagrPaintUtility dPaintUtil,
String progName) {
this.componentToBePrinted = componentToBePrinted;
this.dd = dD;
this.defaultPrinter = defaultPrinter;
this.diagrPaintUtil = dPaintUtil;
this.prgName = progName;
}
/** Constructs an instance of DiagrPrintUtility and starts printing
*
* @param c the component to be printed
* @param dD data needed for the paint method
* @param defaultPrinter if false, a printer dialog is used to allow the user to select a printer
* @param dPaintUtil the object that does the painting
* @param progName title for dialogs
*/
public static void printComponent(java.awt.Component c,
GraphLib.PltData dD,
boolean defaultPrinter,
DiagrPaintUtility dPaintUtil,
String progName) {
new DiagrPrintUtility(c, dD, defaultPrinter, dPaintUtil, progName).print();
}
private void print() {
componentToBePrinted.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
java.awt.print.PrinterJob printJob = java.awt.print.PrinterJob.getPrinterJob();
if(printJob.getPrintService() == null) {
javax.swing.JOptionPane.showMessageDialog(componentToBePrinted,
"Error: No printers found."+nl, prgName, javax.swing.JOptionPane.ERROR_MESSAGE);
return;
}
//get printer names and loop through them
//javax.print.PrintService[] printServices =
// javax.print.PrintServiceLookup.lookupPrintServices(null, null);
//for (javax.print.PrintService service : printServices)
// {System.out.println("printer="+service.getName());}
printJob.setPrintable(this);
javax.print.attribute.PrintRequestAttributeSet attrSet =
new javax.print.attribute.HashPrintRequestAttributeSet();
//Letter: 216x279; A4 210x297
javax.print.attribute.standard.MediaSizeName mediaSizeName =
javax.print.attribute.standard.MediaSize.findMedia(210f, 279f, javax.print.attribute.standard.MediaSize.MM);
if(mediaSizeName != null) {attrSet.add(mediaSizeName);}
javax.print.attribute.standard.MediaPrintableArea mediaPrintableArea =
new javax.print.attribute.standard.MediaPrintableArea(15f, 5f, 190f, 269f, javax.print.attribute.standard.MediaPrintableArea.MM);
attrSet.add(mediaPrintableArea);
boolean ok;
if(defaultPrinter) {ok = true;}
else {ok = printJob.printDialog();}
if (ok)
try {
printJob.print(attrSet);
} catch(java.awt.print.PrinterException ex) {
String t = "Error: "+ex.toString()+nl+"While printing plot file:"+nl+dd.pltFile_Name;
MsgExceptn.exception(t);
javax.swing.JOptionPane.showMessageDialog(componentToBePrinted, t, prgName,
javax.swing.JOptionPane.ERROR_MESSAGE);
}
componentToBePrinted.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
}
@Override
public int print(java.awt.Graphics g, java.awt.print.PageFormat pf, int pageIndex) {
if (pageIndex > 0) {
return(NO_SUCH_PAGE);
} else {
java.awt.Graphics2D g2d = (java.awt.Graphics2D)g;
int x0 = Math.round((float)pf.getImageableX());
int y0 = Math.round((float)pf.getImageableY());
g2d.translate(x0, y0);
disableDoubleBuffering(componentToBePrinted);
int w = Math.round((float)pf.getImageableWidth());
int h = Math.round((float)pf. getImageableHeight());
java.awt.Dimension pageDim = new java.awt.Dimension(w,h);
boolean printing = true;
diagrPaintUtil.paintDiagram(g2d, pageDim, dd, printing);
//componentToBePrinted.paint(g2d);
enableDoubleBuffering(componentToBePrinted);
return(PAGE_EXISTS);
}
}
private static void disableDoubleBuffering(java.awt.Component c) {
javax.swing.RepaintManager currentManager = javax.swing.RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(false);
}
private static void enableDoubleBuffering(java.awt.Component c) {
javax.swing.RepaintManager currentManager = javax.swing.RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(true);
}
} | 6,148 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
LogKchange.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Spana/src/spana/LogKchange.java | package spana;
import lib.common.Util;
import lib.huvud.ProgramConf;
import lib.kemi.chem.Chem;
/** Dialog to change logK.
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class LogKchange extends javax.swing.JFrame {
private ProgramConf pc;
private final java.awt.Dimension windowSize;
private boolean finished = false;
private Chem.ChemSystem cs = null;
private Chem.ChemSystem.NamesEtc namn = null;
private final int species;
private boolean deactivated_old;
private double lBeta_old;
private boolean modified;
/** when a jTextField containing a number is edited,
* the old text is saved in this variable. If the user makes a mistake, for example
* enters "0.7e", then the old text is restored from this variable. */
private String oldTextLogK = "0";
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
//<editor-fold defaultstate="collapsed" desc="Constructor">
/** Creates new form logKchange
* @param chemS
* @param complex
* @param pc0 */
public LogKchange(Chem.ChemSystem chemS, int complex, ProgramConf pc0) {
initComponents();
this.cs = chemS;
this.namn = cs.namn;
this.species = complex;
this.pc = pc0;
modified = false;
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
//center Window on Screen
windowSize = this.getSize();
int left; int top;
left = Math.max(0, (MainFrame.screenSize.width - windowSize.width ) / 2);
top = Math.max(0, (MainFrame.screenSize.height - windowSize.height) / 2);
this.setLocation(Math.min(MainFrame.screenSize.width-100, left),
Math.min(MainFrame.screenSize.height-100, top));
//--- close window on ESC key
javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE");
javax.swing.Action escAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
quitDialog();
}};
getRootPane().getActionMap().put("ESCAPE", escAction);
//--- Alt-X eXit
javax.swing.KeyStroke altXKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altXKeyStroke,"ALT_X");
javax.swing.Action altXAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jButtonOK.doClick();
}};
getRootPane().getActionMap().put("ALT_X", altXAction);
//--- F1 for help
javax.swing.KeyStroke f1KeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(f1KeyStroke,"F1");
javax.swing.Action f1Action = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jButtonHelp.doClick();
}};
getRootPane().getActionMap().put("F1", f1Action);
//--- Title
this.setTitle("Change logK");
//---- Icon
String iconName = "images/LogK_32x32.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
if (imgURL != null) {this.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());}
else {System.out.println("Error: Could not load image = \""+iconName+"\"");}
// --- set up frame
jLabelReaction.setText(spana.ModifyChemSyst.reactionText(cs, species, false));
lBeta_old = cs.lBeta[species];
jLabelLogKOld.setText(Util.formatDbl4(lBeta_old));
jTextFieldLogK.setText(Util.formatDbl4(lBeta_old));
setCheckBox(namn.ident[cs.Na + species]);
deactivated_old = jRadioButtonDeact.isSelected();
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
this.setVisible(true);
}
//</editor-fold>
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabelReaction = new javax.swing.JLabel();
jLabelWarning = new javax.swing.JLabel();
jPanel4 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jLabelLogKOld = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jTextFieldLogK = new javax.swing.JTextField();
jPanel3 = new javax.swing.JPanel();
jRadioButtonAct = new javax.swing.JRadioButton();
jRadioButtonDeact = new javax.swing.JRadioButton();
jPanelButtons = new javax.swing.JPanel();
jButtonQuit = new javax.swing.JButton();
jButtonOK = new javax.swing.JButton();
jButtonHelp = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel1.setForeground(new java.awt.Color(0, 0, 204));
jLabel1.setText("Reaction:"); // NOI18N
jLabelReaction.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabelReaction.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabelReaction.setText("8 Cu 2+ + 8 H3(urid) = Cu8(urid)8 + 24 H+"); // NOI18N
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelReaction, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelReaction)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jLabelWarning.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabelWarning.setIcon(new javax.swing.ImageIcon(getClass().getResource("/spana/images/Warn_RedTriangl.gif"))); // NOI18N
jLabelWarning.setText("<html>Warning! This species is not active.<br>This may result in wrong diagrams!</html>"); // NOI18N
jLabelWarning.setAlignmentY(0.0F);
jLabelWarning.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel2.setForeground(new java.awt.Color(0, 0, 204));
jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel2.setText("old logK = "); // NOI18N
jLabelLogKOld.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabelLogKOld.setText("jLabel5"); // NOI18N
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel3.setForeground(new java.awt.Color(0, 0, 204));
jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel3.setText("Enter new logK:"); // NOI18N
jTextFieldLogK.setText("-999.999"); // NOI18N
jTextFieldLogK.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextFieldLogKActionPerformed(evt);
}
});
jTextFieldLogK.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextFieldLogKFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jTextFieldLogKFocusLost(evt);
}
});
jTextFieldLogK.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTextFieldLogKKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextFieldLogKKeyTyped(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 99, Short.MAX_VALUE)
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 33, Short.MAX_VALUE)
);
buttonGroup.add(jRadioButtonAct);
jRadioButtonAct.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jRadioButtonAct.setForeground(new java.awt.Color(0, 0, 204));
jRadioButtonAct.setMnemonic('a');
jRadioButtonAct.setText("activate");
jRadioButtonAct.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonActActionPerformed(evt);
}
});
buttonGroup.add(jRadioButtonDeact);
jRadioButtonDeact.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jRadioButtonDeact.setForeground(new java.awt.Color(0, 0, 204));
jRadioButtonDeact.setMnemonic('d');
jRadioButtonDeact.setText("deactivate");
jRadioButtonDeact.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonDeactActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(157, 157, 157)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jRadioButtonDeact)
.addComponent(jRadioButtonAct))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 117, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelLogKOld)
.addComponent(jTextFieldLogK, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jLabelLogKOld))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jTextFieldLogK, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(4, 4, 4)
.addComponent(jRadioButtonAct)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jRadioButtonDeact)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jButtonQuit.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButtonQuit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/spana/images/Quit_32x32.gif"))); // NOI18N
jButtonQuit.setMnemonic('Q');
jButtonQuit.setText("<html><u>Q</u>uit</html>"); // NOI18N
jButtonQuit.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonQuit.setHorizontalAlignment(javax.swing.SwingConstants.LEADING);
jButtonQuit.setIconTextGap(8);
jButtonQuit.setMargin(new java.awt.Insets(2, 2, 2, 2));
jButtonQuit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonQuitActionPerformed(evt);
}
});
jButtonOK.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButtonOK.setIcon(new javax.swing.ImageIcon(getClass().getResource("/spana/images/Save_32x32.gif"))); // NOI18N
jButtonOK.setMnemonic('O');
jButtonOK.setText("OK"); // NOI18N
jButtonOK.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonOK.setHorizontalAlignment(javax.swing.SwingConstants.LEADING);
jButtonOK.setIconTextGap(8);
jButtonOK.setMargin(new java.awt.Insets(2, 2, 2, 2));
jButtonOK.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonOKActionPerformed(evt);
}
});
jButtonHelp.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButtonHelp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/spana/images/Help_32x32.gif"))); // NOI18N
jButtonHelp.setMnemonic('H');
jButtonHelp.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonHelp.setMargin(new java.awt.Insets(2, 2, 2, 2));
jButtonHelp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonHelpActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanelButtonsLayout = new javax.swing.GroupLayout(jPanelButtons);
jPanelButtons.setLayout(jPanelButtonsLayout);
jPanelButtonsLayout.setHorizontalGroup(
jPanelButtonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelButtonsLayout.createSequentialGroup()
.addGroup(jPanelButtonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanelButtonsLayout.createSequentialGroup()
.addGap(93, 93, 93)
.addComponent(jButtonHelp))
.addGroup(jPanelButtonsLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jButtonOK, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButtonQuit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelButtonsLayout.setVerticalGroup(
jPanelButtonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelButtonsLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelButtonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonOK)
.addComponent(jButtonQuit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButtonHelp)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanelButtons, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanelButtons, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
.addGap(2, 2, 2))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelWarning, javax.swing.GroupLayout.PREFERRED_SIZE, 354, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jLabelWarning, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
//<editor-fold defaultstate="collapsed" desc="Events">
private void jButtonQuitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonQuitActionPerformed
quitDialog();
}//GEN-LAST:event_jButtonQuitActionPerformed
private void jButtonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOKActionPerformed
validateLogK();
lBeta_old = cs.lBeta[species];
deactivated_old = jRadioButtonDeact.isSelected();
quitDialog();
}//GEN-LAST:event_jButtonOKActionPerformed
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
quitDialog();
}//GEN-LAST:event_formWindowClosing
private void jTextFieldLogKFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldLogKFocusLost
validateLogK();
}//GEN-LAST:event_jTextFieldLogKFocusLost
private void jTextFieldLogKKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldLogKKeyPressed
if(evt.getKeyChar() == java.awt.event.KeyEvent.VK_ENTER) {
validateLogK();
}
}//GEN-LAST:event_jTextFieldLogKKeyPressed
private void jTextFieldLogKKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldLogKKeyTyped
char key = evt.getKeyChar();
if(!isCharOKforNumberInput(key)) {evt.consume();}
}//GEN-LAST:event_jTextFieldLogKKeyTyped
private void jTextFieldLogKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldLogKActionPerformed
validateLogK();
}//GEN-LAST:event_jTextFieldLogKActionPerformed
private void jTextFieldLogKFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldLogKFocusGained
oldTextLogK = jTextFieldLogK.getText();
jTextFieldLogK.selectAll();
}//GEN-LAST:event_jTextFieldLogKFocusGained
private void jRadioButtonActActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonActActionPerformed
if(jRadioButtonAct.isSelected()) {
if(namn.ident[cs.Na+species].startsWith("*")) {
namn.ident[cs.Na+species] = namn.ident[cs.Na+species].substring(1);
}
} else { // radiobutton not selected
if(!namn.ident[cs.Na+species].startsWith("*")) {
namn.ident[cs.Na+species] = "*"+namn.ident[cs.Na+species];
}
}
jLabelReaction.setText(spana.ModifyChemSyst.reactionText(cs, species, false));
setCheckBox(namn.ident[cs.Na+species]);
}//GEN-LAST:event_jRadioButtonActActionPerformed
private void jRadioButtonDeactActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonDeactActionPerformed
if(jRadioButtonDeact.isSelected()) {
if(!namn.ident[cs.Na+species].startsWith("*")) {
namn.ident[cs.Na+species] = "*"+namn.ident[cs.Na+species];
}
} else { // radiobutton not selected
if(namn.ident[cs.Na+species].startsWith("*")) {
namn.ident[cs.Na+species] = namn.ident[cs.Na+species].substring(1);
}
}
jLabelReaction.setText(spana.ModifyChemSyst.reactionText(cs, species, false));
setCheckBox(namn.ident[cs.Na+species]);
}//GEN-LAST:event_jRadioButtonDeactActionPerformed
private void jButtonHelpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonHelpActionPerformed
setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
Thread hlp = new Thread() {@Override public void run(){
String[] a = {"S_Modify_Chem_System_htm_Deactivate"};
lib.huvud.RunProgr.runProgramInProcess(LogKchange.this,ProgramConf.HELP_JAR,a,false,pc.dbg,pc.pathAPP);
try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec
catch (InterruptedException e) {}
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
}};//new Thread
hlp.start();
}//GEN-LAST:event_jButtonHelpActionPerformed
private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
if(windowSize != null) {
int w = windowSize.width;
int h = windowSize.height;
if(this.getHeight()<h){this.setSize(this.getWidth(), h);}
if(this.getWidth()<w){this.setSize(w,this.getHeight());}
}
}//GEN-LAST:event_formComponentResized
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Methods">
private void quitDialog() {
if(Math.abs(cs.lBeta[species] - lBeta_old) > 1e-8 ||
deactivated_old != jRadioButtonDeact.isSelected()) {modified = true;}
if(modified) {
int n;
Object[] options = {"Cancel", "Yes"};
n = javax.swing.JOptionPane.
showOptionDialog(this,"Discard your changes?",
"Modify Chemical System", javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE, null, options, null);
if(n != javax.swing.JOptionPane.NO_OPTION) { // second button = "yes"
return; // oops!
} else { // yes: discard changes
cs.lBeta[species] = lBeta_old;
if(deactivated_old) {
if(!namn.ident[cs.Na + species].startsWith("*")) {
namn.ident[cs.Na + species] = "*"+namn.ident[cs.Na + species];
}
} else {
if(namn.ident[cs.Na + species].startsWith("*")) {
namn.ident[cs.Na + species] = namn.ident[cs.Na + species].substring(1);
}
}
} // discard changes?
} //if modified
finished = true;
this.notify_All();
this.dispose();
} // quitForm_Gen_Options
private synchronized void notify_All() {notifyAll();}
/** this method will wait for this dialog frame to be closed
* @return "modified"
*/
public synchronized boolean waitForLogKchange() {
while(!finished) {
try {wait();} catch (InterruptedException ex) {}
} // while
return modified;
} // waitForLogKchange()
private void setCheckBox(String name) {
if(name.startsWith("*")) {
jRadioButtonDeact.setSelected(true);
jRadioButtonDeact.setText("deactivated");
jRadioButtonAct.setText("activate");
jLabelWarning.setVisible(true);
} else {
jRadioButtonAct.setSelected(true);
jRadioButtonDeact.setText("deactivate");
jRadioButtonAct.setText("activated");
jLabelWarning.setVisible(false);
}
}
private void validateLogK(){
cs.lBeta[species] = readLogK();
String t = Util.formatNum(cs.lBeta[species]);
if(Double.parseDouble(t) != cs.lBeta[species]) {
jTextFieldLogK.setText(t);
}
}
private double readLogK() {
String t = jTextFieldLogK.getText().trim();
if(t.length() <= 0) {return 0;}
double w;
try{w = Double.valueOf(t);
w = Math.min(1e50,Math.max(w, -1e50));
} catch (NumberFormatException ex) {
try{w = Double.valueOf(oldTextLogK); jTextFieldLogK.setText(oldTextLogK);}
catch (NumberFormatException e) {w = 0.;}
String msg = "Error (NumberFormatException)";
msg = msg +nl+"with text: \""+t+"\"";
System.out.println("---- "+msg);
javax.swing.JOptionPane.showMessageDialog(this, msg,
pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE);
}
return w;
} //readLogK()
/** @param key a character
* @return true if the character is ok, that is, it is either a number,
* or a dot, or a minus sign, or an "E" (such as in "2.5e-6") */
private boolean isCharOKforNumberInput(char key) {
return Character.isDigit(key)
|| key == '-' || key == '+' || key == '.' || key == 'E' || key == 'e';
} // isCharOKforNumberInput(char)
//</editor-fold>
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup;
private javax.swing.JButton jButtonHelp;
private javax.swing.JButton jButtonOK;
private javax.swing.JButton jButtonQuit;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabelLogKOld;
private javax.swing.JLabel jLabelReaction;
private javax.swing.JLabel jLabelWarning;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanelButtons;
private javax.swing.JRadioButton jRadioButtonAct;
private javax.swing.JRadioButton jRadioButtonDeact;
private javax.swing.JTextField jTextFieldLogK;
// End of variables declaration//GEN-END:variables
}
| 31,866 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
ErrMsgBox.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Spana/src/spana/ErrMsgBox.java | package spana;
/** Displays a "message box" modal dialog with an "OK" button and a title.
* The message is displayed in a text area (non-editable),
* which can be copied and pasted elsewhere.
*
* Copyright (C) 2014-2016 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class ErrMsgBox {
private static final String nl = System.getProperty("line.separator");
//<editor-fold defaultstate="collapsed" desc="ErrMsgBox(msg, title)">
/** Displays a "message box" modal dialog with an "OK" button and a title.
* The message is displayed in a text area (non-editable),
* which can be copied and pasted elsewhere.
* @param msg will be displayed in a text area, and line breaks may be
* included, for example: <code>new MsgBox("Very\nbad!",""); </code>
* If null or empty nothing is done.
* @param title for the dialog. If null or empty, "Error:" is used
* @see #showErrMsg(java.awt.Component, java.lang.String, int) showErrMsg
* @version 2015-July-14 */
public ErrMsgBox(String msg, String title) {
if(msg == null || msg.trim().length() <=0) {
System.out.println("--- MsgBox: null or empty \"message\".");
return;
}
//--- Title
if(title == null || title.length() <=0) {title = " Error:";}
java.awt.Frame frame = new java.awt.Frame(title);
//--- Icon
String iconName = "images/ErrMsgBx.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
if(imgURL != null) {frame.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());}
else {System.out.println("--- Error in MsgBox constructor: Could not load image = \""+iconName+"\"");}
frame.pack();
//--- centre Window frame on Screen
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int left; int top;
left = Math.max(55, (screenSize.width - frame.getWidth() ) / 2);
top = Math.max(10, (screenSize.height - frame.getHeight()) / 2);
frame.setLocation(Math.min(screenSize.width-100, left), Math.min(screenSize.height-100, top));
//---
final String msgText = wrapString(msg.trim(),80);
//System.out.println("--- MsgBox:"+nl+msgText+nl+"---");
frame.setVisible(true);
//javax.swing.JOptionPane.showMessageDialog(frame, msg, title, javax.swing.JOptionPane.ERROR_MESSAGE);
MsgBoxDialog msgBox = new MsgBoxDialog(frame, msgText, title, true);
msgBox.setVisible(true); // becase the dialog is modal, statements below will wait
msgBox.dispose();
frame.setVisible(false);
frame.dispose();
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="private class MsgBoxDialog">
private static class MsgBoxDialog extends java.awt.Dialog {
private java.awt.Button ok;
private java.awt.Panel p;
private final java.awt.TextArea text;
/** Creates new form NewDialog */
public MsgBoxDialog(java.awt.Frame parent, String msg, String title, boolean modal) {
super(parent, (" "+title), modal);
addWindowListener(new java.awt.event.WindowAdapter() {
@Override public void windowClosing(java.awt.event.WindowEvent evt) {
MsgBoxDialog.this.setVisible(false);
}
});
setLayout(new java.awt.BorderLayout());
p = new java.awt.Panel();
p.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER));
ok = new java.awt.Button();
// find out the size of the message (width and height)
final int wMax = 85; final int hMax=20;
final int wMin = 5; final int hMin = 1;
int w = wMin;
int h=hMin; int i=0; int j=wMin;
final String eol = "\n"; char c;
final String nl = System.getProperty("line.separator");
while (true) {
c = msg.charAt(i);
String s = String.valueOf(c);
if(s.equals(eol) || s.equals(nl)) {
h++; j=wMin;
} else {
j++; w = Math.max(j,w);
}
i++;
if(i >= msg.length()-1) {break;}
}
// create a text area
int scroll = java.awt.TextArea.SCROLLBARS_NONE;
if(w > wMax && h <= hMax) {scroll = scroll & java.awt.TextArea.SCROLLBARS_HORIZONTAL_ONLY;}
if(h > hMax && w <= wMax) {scroll = scroll & java.awt.TextArea.SCROLLBARS_VERTICAL_ONLY;}
if(w > wMax && h > hMax) {scroll = java.awt.TextArea.SCROLLBARS_BOTH;}
w = Math.min(Math.max(w,10),wMax);
h = Math.min(h,hMax);
text = new java.awt.TextArea(msg, h, w, scroll);
text.setEditable(false);
//text.setBackground(java.awt.Color.white);
text.addKeyListener(new java.awt.event.KeyAdapter() {
@Override public void keyPressed(java.awt.event.KeyEvent evt) {
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER
|| evt.getKeyCode() == java.awt.event.KeyEvent.VK_ESCAPE) {closeDialog();}
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_TAB) {ok.requestFocusInWindow();}
}
});
text.setBackground(java.awt.Color.WHITE);
text.setFont(new java.awt.Font("monospaced", java.awt.Font.PLAIN, 12));
add(text, java.awt.BorderLayout.CENTER);
ok.setLabel("OK");
ok.addActionListener(new java.awt.event.ActionListener() {
@Override public void actionPerformed(java.awt.event.ActionEvent evt) {
closeDialog();
}
});
ok.addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER
|| evt.getKeyCode() == java.awt.event.KeyEvent.VK_ESCAPE) {closeDialog();}
}
});
p.add(ok);
add(p, java.awt.BorderLayout.SOUTH);
pack();
ok.requestFocusInWindow();
//--- centre Window frame on Screen
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int left; int top;
left = Math.max(55, (screenSize.width - getWidth() ) / 2);
top = Math.max(10, (screenSize.height - getHeight()) / 2);
setLocation(Math.min(screenSize.width-100, left), Math.min(screenSize.height-100, top));
}
private void closeDialog() {this.setVisible(false);}
} // private static class MsgBoxDialog
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="private wrapString">
/** Returns an input string, with lines that are longer than <code>maxLength</code>
* word-wrapped and indented. *
* @param s input string
* @param maxLength if an input line is longer than this length,
* the line will be word-wrapped at the first white space after <code>maxLength</code>
* and indented with 4 spaces
* @return string with long-lines word-wrapped
*/
private static String wrapString(String s, int maxLength) {
String deliminator = "\n";
StringBuilder result = new StringBuilder();
StringBuffer wrapLine;
int lastdelimPos;
for (String line : s.split(deliminator, -1)) {
if(line.length()/(maxLength+1) < 1) {
result.append(line).append(deliminator);
}
else { //line too long, try to split it
wrapLine = new StringBuffer();
lastdelimPos = 0;
for (String token : line.trim().split("\\s+", -1)) {
if (wrapLine.length() - lastdelimPos + token.length() > maxLength) {
if(wrapLine.length()>0) {wrapLine.append(deliminator);}
wrapLine.append(" ").append(token);
lastdelimPos = wrapLine.length() + 1;
} else {
if(wrapLine.length() <=0) {wrapLine.append(token);}
else {wrapLine.append(" ").append(token);}
}
}
result.append(wrapLine).append(deliminator);
}
}
return result.toString();
}
// </editor-fold>
}
| 8,975 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
FileAssociation.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Spana/src/spana/FileAssociation.java | package spana;
/** Windows registry: Associates a program with file extensions.
* Copyright (C) 2014 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class FileAssociation {
private static final String PROGNAME = "Eq-Diagr";
private static final String BACKUP = "Backup_by_"+PROGNAME;
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
//<editor-fold defaultstate="collapsed" desc="associateFileExtension">
/**
* Associates a file extension with an exe-file in the Windows registry
* @param ext extension is a three letter string without a ".": must be either "plt" or "dat"
* @param pathToExecute is full path to exe file
* @throws IllegalAccessException
* @throws java.lang.reflect.InvocationTargetException
* @throws IllegalArgumentException
* @throws java.io.IOException
* @throws java.net.URISyntaxException
*/
public static void associateFileExtension(
String ext,
String pathToExecute)
throws IllegalAccessException,
java.lang.reflect.InvocationTargetException,
IllegalArgumentException,
java.io.IOException,
java.net.URISyntaxException {
String msg = "Error in \"associateFileExtension\""+nl;
if(ext == null || ext.length() <=0) {throw new IllegalArgumentException(msg+
"\"ext\" is null or empty.");}
if(pathToExecute == null || pathToExecute.length() <=0) {throw new IllegalArgumentException(msg+
"\"pathToExecute\" is null or empty.");}
if(ext.contains(".")) {throw new IllegalArgumentException(msg+
"\"ext\" = "+ext+" (must not contain a \".\")");}
java.io.File fileToExecute = new java.io.File(pathToExecute);
if(!fileToExecute.exists()) {throw new IllegalArgumentException(msg+
" \"pathToExecute\" = \""+pathToExecute+"\""+nl+" file does not exist.");}
String appName = PROGNAME+"_"+ext.toUpperCase()+"_File";
String value;
//--- Create a root entry called 'appName'
// appName = either "PROGNAME_DAT_File" or "PROGNAME_PLT_File"
WinRegistry.createKey("Software\\Classes\\"+appName);
WinRegistry.writeStringValue("Software\\Classes\\"+appName, "",appName);
WinRegistry.createKey("Software\\Classes\\"+appName+"\\shell\\open\\command");
//Set the command line for 'appName'.
WinRegistry.writeStringValue("Software\\Classes\\"+appName+"\\shell\\open\\command", "",
pathToExecute+" \"%1\"");
//Set the default icon
String path;
path = fileToExecute.getParent();
java.io.File pathF = new java.io.File(path);
try{path = pathF.getCanonicalPath();}
catch (java.io.IOException ex) {}
String iconFileName = null;
if(ext.equalsIgnoreCase("dat") || ext.equalsIgnoreCase("plt")) {
iconFileName = path + java.io.File.separator +
"Icon_" + ext.toLowerCase().trim() + ".ico";}
if(iconFileName != null) {
java.io.File iconFile = new java.io.File(iconFileName);
if(iconFile.exists()) {
WinRegistry.createKey("Software\\Classes\\"+appName+"\\DefaultIcon");
WinRegistry.writeStringValue("Software\\Classes\\"+appName+"\\DefaultIcon", "",
iconFileName);
}
}
//--- Create a root entry for the extension to be associated with "appName".
final String dotExt = "."+ext;
//Make a backup of existing association, if any
value = WinRegistry.readString("Software\\Classes\\"+dotExt, "");
if(value != null && value.length() > 0 && !value.equals(appName)) {
WinRegistry.createKey("Software\\Classes\\"+dotExt+"\\"+BACKUP);
WinRegistry.writeStringValue("Software\\Classes\\"+dotExt+"\\"+BACKUP, "", value);
} //end of backup
else {
WinRegistry.createKey("Software\\Classes\\"+dotExt);
}
//Now create the association
WinRegistry.writeStringValue("Software\\Classes\\"+dotExt, "", appName);
//return;
} //associateFileExtension
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="unAssociateFileExtension">
/** Un-associates a file extension with an exe-file in the Windows registry
* @param ext extension is a three letter string without the "."
* @throws IllegalAccessException
* @throws java.lang.reflect.InvocationTargetException
* @throws IllegalArgumentException
* @throws java.io.IOException
* @throws java.net.URISyntaxException
*/
public static void unAssociateFileExtension(
String ext)
throws IllegalAccessException, java.lang.reflect.InvocationTargetException,
IllegalArgumentException, java.io.IOException, java.net.URISyntaxException {
String msg = "Error in \"unAssociateFileExtension\""+nl;
if(ext == null || ext.length() <=0) {throw new IllegalArgumentException(msg+
"\"ext\" is null or empty.");}
if(ext.contains(".")) {throw new IllegalArgumentException(msg+
"\"ext\" = "+ext+" (must not contain a \".\")");}
String appName = PROGNAME+"_"+ext.toUpperCase()+"_File";
String value;
java.util.List<String> lst;
//--- Delete the "appName" key
// appName = either "PROGNAME_Data_File" or "PROGNAME_Plot_File"
//- Delete the default iconFileName
value = WinRegistry.readString("Software\\Classes\\"+appName+"\\DefaultIcon", "");
if(value != null) { //not empty: possible to delete
WinRegistry.deleteValue("Software\\Classes\\"+appName+"\\DefaultIcon", "");
lst = WinRegistry.readStringSubKeys("Software\\Classes\\"+appName+"\\DefaultIcon");
if(lst == null || lst.isEmpty()) { //empty: delete key
WinRegistry.deleteKey("Software\\Classes\\"+appName+"\\DefaultIcon");
}
}
//- Delete the command
value = WinRegistry.readString("Software\\Classes\\"+appName+"\\shell\\open\\command", "");
if(value != null) { //not empty: possible to delete
WinRegistry.deleteValue("Software\\Classes\\"+appName+"\\shell\\open\\command", "");
lst = WinRegistry.readStringSubKeys("Software\\Classes\\"+appName+"\\shell\\open\\command");
if(lst == null || lst.isEmpty()) { //empty: delete key
WinRegistry.deleteKey("Software\\Classes\\"+appName+"\\shell\\open\\command");
lst = WinRegistry.readStringSubKeys("Software\\Classes\\"+appName+"\\shell\\open");
if(lst == null || lst.isEmpty()) { //empty: delete key
WinRegistry.deleteKey("Software\\Classes\\"+appName+"\\shell\\open");
lst = WinRegistry.readStringSubKeys("Software\\Classes\\"+appName+"\\shell");
if(lst == null || lst.isEmpty()) { //empty: delete key
WinRegistry.deleteKey("Software\\Classes\\"+appName+"\\shell");
// finally remove the key itself
lst = WinRegistry.readStringSubKeys("Software\\Classes\\"+appName);
if(lst == null || lst.isEmpty()) { //empty: delete key
// an error will occur if the key does not exist
WinRegistry. deleteKey("Software\\Classes\\"+appName);
}
} //deleteKey appName + \shell
} //deleteKey appName + \shell\open
} //deleteKey appName + \shell\open\command
}
//--- Delete ".ext": the entry for the extension associated with "appName".
//First check if ".ext" it is associated to "appName"; if not do nothing
final String dotExt = "."+ext;
value = WinRegistry.readString("Software\\Classes\\"+dotExt, "");
if(value != null && value.length() >0 && value.equals(appName)) {
//".ext" is associated to the software
WinRegistry.deleteValue("Software\\Classes\\"+dotExt, "");
// because "readStringValues" not always works: do not delete key
//try { // an error will occur if the key does not exist
// java.util.Map<String,String> res = WinRegistry.readStringValues(HKC,dotExt);
// lst = WinRegistry.readStringSubKeys(HKC,dotExt);
// if((lst == null || lst.isEmpty()) && (res == null || res.isEmpty())) { //empty: delete key
// WinRegistry.deleteKey(HKC, dotExt);
// }
//} catch (Exception ex) {}
} //".ext" is associated to the software
//check if there is an association backup
value = WinRegistry.readString("Software\\Classes\\"+dotExt+"\\"+BACKUP, "");
if(value != null && value.length() >0) {
//there is backup data: put the backup data into ".ext"
WinRegistry.writeStringValue("Software\\Classes\\"+dotExt, "", value);
//get rid of the backup
WinRegistry.deleteValue("Software\\Classes\\"+dotExt+"\\"+BACKUP, "");
lst = WinRegistry.readStringSubKeys("Software\\Classes\\"+dotExt+"\\"+BACKUP);
if(lst == null || lst.isEmpty()) { //empty: delete key
WinRegistry.deleteKey("Software\\Classes\\"+dotExt+"\\"+BACKUP);
}
} //backup?
//Delete HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion
// \Explorer\FileExts\.ext\OpenWithProgids
WinRegistry.deleteValue(
"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\" + dotExt +
"\\OpenWithProgids", appName);
//return;
} //unAssociateFileExtension
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="isAssociated">
/**
* @param ext extension is a three letter string without a "."
* @param pathToExecute is full path to exe file
* @return true if files with extension "ext" are associated with application "pathToExecute"
* @throws IllegalArgumentException
* @throws java.lang.reflect.InvocationTargetException
* @throws IllegalAccessException
*/
public static boolean isAssociated(
String ext,
String pathToExecute)
throws IllegalArgumentException, java.lang.reflect.InvocationTargetException,
IllegalAccessException {
String msg = "Error in \"isAssociated\""+nl;
if(ext == null || ext.length() <=0) {throw new IllegalArgumentException(msg+
"\"ext\" is null or empty.");}
if(pathToExecute == null || pathToExecute.length() <=0) {throw new IllegalArgumentException(msg+
"\"pathToExecute\" is null or empty.");}
if(ext.contains(".")) {throw new IllegalArgumentException(msg+
"\"ext\" = "+ext+" (must not contain a \".\")");}
String appName = PROGNAME+"_"+ext.toUpperCase()+"_File";
String value;
value = WinRegistry.readString("Software\\Classes\\"+appName+"\\shell\\open\\command", "");
if(value == null || value.length() <=0) {return false;}
if(!value.toLowerCase().startsWith(pathToExecute.toLowerCase())) {return false;}
final String dotExt = "."+ext;
value = WinRegistry.readString("Software\\Classes\\"+dotExt, "");
return value != null && value.length() > 0 && value.equalsIgnoreCase(appName);
}
//</editor-fold>
}
| 11,149 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
DiagrExport.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Spana/src/spana/DiagrExport.java | package spana;
import lib.common.MsgExceptn;
import lib.huvud.Div;
import lib.huvud.ProgramConf;
/** Asks the user for parameters to export a "plt"-file to pixel format.
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class DiagrExport extends javax.swing.JFrame {
// Note: for java 1.6 jComboBox must not have type,
// for java 1.7 jComboBox must be <String>
private ProgramConf pc;
private ProgramDataSpana pd;
private boolean finished = false;
private java.awt.Dimension windowSize;
private String pltFileFullName;
private String convertedFileFullN;
private java.io.File convertedFile;
private double height2width = Double.NaN;
private boolean loading = true;
private boolean cancel = true;
private String exportType = "png";
private int exportSize = 1000;
private javax.swing.border.Border scrollBorder;
private static final String nl = System.getProperty("line.separator");
//<editor-fold defaultstate="collapsed" desc="Constructor">
/** Displays a frame to allow the user to change the settings and perform the
* conversion of a "plt" file into "pdf", "ps" or "eps". *
* @param pc0 program configuration parameters
* @param pd0 program data
* @param heightToWidth the height to width ratio of the original diagram in the plt file
*/
public DiagrExport(
ProgramConf pc0,
ProgramDataSpana pd0,
double heightToWidth) {
initComponents();
pc = pc0; pd = pd0;
height2width = heightToWidth;
finished = false; cancel = true;
loading = true;
//--- close window on ESC key
javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_ESCAPE,0, false);
javax.swing.Action escAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
closeWindow();
}};
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE");
getRootPane().getActionMap().put("ESCAPE", escAction);
//--- alt-Q quit
javax.swing.KeyStroke altQKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altQKeyStroke,"ALT_Q");
getRootPane().getActionMap().put("ALT_Q", escAction);
//--- Alt-X eXit
javax.swing.KeyStroke altXKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altXKeyStroke,"ALT_X");
javax.swing.Action altXAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jButtonDoIt.doClick();
}};
getRootPane().getActionMap().put("ALT_X", altXAction);
//--- F1 for help
javax.swing.KeyStroke f1KeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(f1KeyStroke,"F1");
javax.swing.Action f1Action = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
DiagrExport.this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
Thread hlp = new Thread() {@Override public void run(){
String[] a = {"S_Printing_htm_BMP"};
lib.huvud.RunProgr.runProgramInProcess(DiagrExport.this,ProgramConf.HELP_JAR,a,false,pc.dbg,pc.pathAPP);
try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec
catch (InterruptedException e) {}
DiagrExport.this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
}};//new Thread
hlp.start();
}};
getRootPane().getActionMap().put("F1", f1Action);
//--- Alt-H help
javax.swing.KeyStroke altHKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_H, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altHKeyStroke,"ALT_H");
getRootPane().getActionMap().put("ALT_H", f1Action);
//--- center Window on Screen
windowSize = this.getSize();
int left; int top;
left = Math.max(55, (MainFrame.screenSize.width - windowSize.width ) / 2);
top = Math.max(10, (MainFrame.screenSize.height - windowSize.height) / 2);
this.setLocation(Math.min(MainFrame.screenSize.width-100, left),
Math.min(MainFrame.screenSize.height-100, top));
scrollBorder = jScrollBarWidth.getBorder(); // get the default scroll bar border
this.setTitle("Export a diagram:");
//--- Icon
String iconName = "images/Icon-Export_24x24.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
if(imgURL != null) {
this.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());
}
else {System.out.println("--- Error in DiagrExport constructor: Could not load image = \""+iconName+"\"");}
//javax.swing.DefaultComboBoxModel dcbm = new javax.swing.DefaultComboBoxModel(); // java 1.6
javax.swing.DefaultComboBoxModel<String> dcbm = new javax.swing.DefaultComboBoxModel<>();
for(String ex : MainFrame.FORMAT_NAMES) {
if(ex.length() >0) {dcbm.addElement(ex);}
}
jComboBoxType.setModel(dcbm);
exportType = pd.diagrExportType;
exportSize = pd.diagrExportSize;
for(int i = 0; i < dcbm.getSize(); i++) {
if(dcbm.getElementAt(i).toString().equalsIgnoreCase(exportType)) {
jComboBoxType.setSelectedIndex(i);
break;
}
}
jButtonDoIt.setText("export to "+exportType.toUpperCase());
jLabelPltFileName.setText(" ");
jLabelDirName.setText(pc.pathDef.toString());
exportSize = Math.max(5,
Math.min(jScrollBarWidth.getMaximum(),exportSize));
jScrollBarWidth.setValue(exportSize);
if(height2width < 1) {
jScrollBarWidth.setMinimum((int)(11d/height2width));
jLabel_W.setText(String.valueOf((int)((double)exportSize)));
jLabel_H.setText(String.valueOf((int)((double)exportSize*height2width)));
} else {
jScrollBarWidth.setMinimum((int)(11d*height2width));
jLabel_W.setText(String.valueOf((int)((double)exportSize/height2width)));
jLabel_H.setText(String.valueOf((int)((double)exportSize)));
}
jScrollBarWidth.setFocusable(true);
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="start(type, plotFile)">
/** Displays this window frame (after making some checks)
* to allow the user to change the settings and perform the
* conversion of a "plt" file into "pdf", "ps" or "eps".
* @param pltFileN name (with full path) of the plt file to be converted
* @return false if an error occurs */
public boolean start(String pltFileN) {
if(pc.dbg) {System.out.println(" - - - - - - DiagrExport");}
this.setVisible(true);
if(pltFileN == null || pltFileN.trim().length() <=0) {
String msg = "Programming Error: empty or null file name in DiagrExport.";
MsgExceptn.exception(msg);
javax.swing.JOptionPane.showMessageDialog(this, msg, "Programming error",
javax.swing.JOptionPane.ERROR_MESSAGE);
closeWindow();
return false;
}
//---- get the full name, with path
java.io.File pltFile = new java.io.File(pltFileN);
String msg = null;
if(!pltFile.exists()) {msg = "the file does not exist.";}
if(!pltFile.canRead()) {msg = "can not open file for reading.";}
if(msg != null) {
String t = "Error: \""+pltFileN+"\""+nl+msg;
MsgExceptn.exception(t);
javax.swing.JOptionPane.showMessageDialog(this, t, pc.progName,
javax.swing.JOptionPane.ERROR_MESSAGE);
closeWindow();
return false;
}
try{pltFileFullName = pltFile.getCanonicalPath();}
catch (java.io.IOException ex) {
try{pltFileFullName = pltFile.getAbsolutePath();}
catch (Exception e) {pltFileFullName = pltFile.getPath();}
}
this.setTitle(pltFile.getName());
jLabelPltFileName.setText(pltFile.getName());
jLabelDirName.setText(pltFile.getParent());
//---- get the file name after conversion
convertedFileFullN = Div.getFileNameWithoutExtension(pltFileFullName)+"."+exportType.toLowerCase();
convertedFile = new java.io.File(convertedFileFullN);
jLabelOutputName.setText(convertedFile.getName());
int k = this.getWidth() - jPanelBottom.getWidth();
DiagrExport.this.validate();
int j = Math.max(jPanelBottom.getWidth(), jPanelTop.getWidth());
java.awt.Dimension d = new java.awt.Dimension(k+j, DiagrExport.this.getHeight());
DiagrExport.this.setSize(d);
loading = false;
return true;
} // start
//</editor-fold>
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroupO = new javax.swing.ButtonGroup();
jPanelTop = new javax.swing.JPanel();
jLabelPltFile = new javax.swing.JLabel();
jLabelPltFileName = new javax.swing.JLabel();
jLabelDir = new javax.swing.JLabel();
jLabelDirName = new javax.swing.JLabel();
jPanelType = new javax.swing.JPanel();
jLabelFont = new javax.swing.JLabel();
jComboBoxType = new javax.swing.JComboBox<>();
jPanelSize = new javax.swing.JPanel();
jLabelSize = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jLabel_h = new javax.swing.JLabel();
jLabel_w = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jLabel_H = new javax.swing.JLabel();
jLabel_W = new javax.swing.JLabel();
jScrollBarWidth = new javax.swing.JScrollBar();
jPanelBottom = new javax.swing.JPanel();
jLabelOut = new javax.swing.JLabel();
jLabelOutputName = new javax.swing.JLabel();
jButtonDoIt = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jLabelPltFile.setText("Plot file:");
jLabelPltFileName.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabelPltFileName.setText("Hello.plt");
jLabelDir.setText("Directory: ");
jLabelDirName.setText("\"D:\\myfiles\\subdir");
javax.swing.GroupLayout jPanelTopLayout = new javax.swing.GroupLayout(jPanelTop);
jPanelTop.setLayout(jPanelTopLayout);
jPanelTopLayout.setHorizontalGroup(
jPanelTopLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelTopLayout.createSequentialGroup()
.addGroup(jPanelTopLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelTopLayout.createSequentialGroup()
.addComponent(jLabelPltFile)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelPltFileName))
.addGroup(jPanelTopLayout.createSequentialGroup()
.addComponent(jLabelDir)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelDirName)))
.addGap(0, 0, Short.MAX_VALUE))
);
jPanelTopLayout.setVerticalGroup(
jPanelTopLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelTopLayout.createSequentialGroup()
.addGroup(jPanelTopLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelPltFile)
.addComponent(jLabelPltFileName))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelTopLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelDir)
.addComponent(jLabelDirName)))
);
jLabelFont.setText("Export image as:");
jComboBoxType.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBoxTypeActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanelTypeLayout = new javax.swing.GroupLayout(jPanelType);
jPanelType.setLayout(jPanelTypeLayout);
jPanelTypeLayout.setHorizontalGroup(
jPanelTypeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelTypeLayout.createSequentialGroup()
.addComponent(jLabelFont)
.addGap(0, 20, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelTypeLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jComboBoxType, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jPanelTypeLayout.setVerticalGroup(
jPanelTypeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelTypeLayout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jLabelFont)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBoxType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jLabelSize.setText("Image size (pixels):");
jLabel_h.setText("height:");
jLabel_w.setText("widtht:");
jLabel_H.setText("2000");
jLabel_W.setText("3000");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel_W, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 65, Short.MAX_VALUE)
.addComponent(jLabel_H, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel_H)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 7, Short.MAX_VALUE)
.addComponent(jLabel_W))
);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel_h)
.addComponent(jLabel_w))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel_h)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel_w))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
jScrollBarWidth.setMaximum(2010);
jScrollBarWidth.setMinimum(20);
jScrollBarWidth.setOrientation(javax.swing.JScrollBar.HORIZONTAL);
jScrollBarWidth.setValue(1000);
jScrollBarWidth.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jScrollBarWidth.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jScrollBarWidthFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jScrollBarWidthFocusLost(evt);
}
});
jScrollBarWidth.addAdjustmentListener(new java.awt.event.AdjustmentListener() {
public void adjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {
jScrollBarWidthAdjustmentValueChanged(evt);
}
});
javax.swing.GroupLayout jPanelSizeLayout = new javax.swing.GroupLayout(jPanelSize);
jPanelSize.setLayout(jPanelSizeLayout);
jPanelSizeLayout.setHorizontalGroup(
jPanelSizeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelSize)
.addGroup(jPanelSizeLayout.createSequentialGroup()
.addGap(32, 32, 32)
.addGroup(jPanelSizeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollBarWidth, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
jPanelSizeLayout.setVerticalGroup(
jPanelSizeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelSizeLayout.createSequentialGroup()
.addComponent(jLabelSize)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollBarWidth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jLabelOut.setText("Output file:");
jLabelOutputName.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabelOutputName.setText("Hello.pdf");
javax.swing.GroupLayout jPanelBottomLayout = new javax.swing.GroupLayout(jPanelBottom);
jPanelBottom.setLayout(jPanelBottomLayout);
jPanelBottomLayout.setHorizontalGroup(
jPanelBottomLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelBottomLayout.createSequentialGroup()
.addComponent(jLabelOut)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelOutputName)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelBottomLayout.setVerticalGroup(
jPanelBottomLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelBottomLayout.createSequentialGroup()
.addGroup(jPanelBottomLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelOutputName)
.addComponent(jLabelOut))
.addGap(8, 8, 8))
);
jButtonDoIt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/spana/images/Icon-Export_24x24.gif"))); // NOI18N
jButtonDoIt.setMnemonic('e');
jButtonDoIt.setText("export to ...");
jButtonDoIt.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonDoIt.setIconTextGap(8);
jButtonDoIt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonDoItActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanelBottom, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanelTop, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButtonDoIt)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanelType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jPanelSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanelTop, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanelSize, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanelType, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanelBottom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButtonDoIt)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
//<editor-fold defaultstate="collapsed" desc="Events">
private void jButtonDoItActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDoItActionPerformed
cancel = false;
pd.diagrExportType = exportType;
pd.diagrExportSize = exportSize;
closeWindow();
}//GEN-LAST:event_jButtonDoItActionPerformed
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
closeWindow();
}//GEN-LAST:event_formWindowClosing
private void jScrollBarWidthAdjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {//GEN-FIRST:event_jScrollBarWidthAdjustmentValueChanged
exportSize = jScrollBarWidth.getValue();
if(height2width < 1) {
jLabel_W.setText(String.valueOf((int)((double)exportSize)));
jLabel_H.setText(String.valueOf((int)((double)exportSize*height2width)));
} else {
jLabel_W.setText(String.valueOf((int)((double)exportSize/height2width)));
jLabel_H.setText(String.valueOf((int)((double)exportSize)));
}
}//GEN-LAST:event_jScrollBarWidthAdjustmentValueChanged
private void jComboBoxTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxTypeActionPerformed
if(!loading) {
exportType = jComboBoxType.getSelectedItem().toString();
jButtonDoIt.setText("export to "+exportType.toUpperCase());
//---- get the file name after conversion
convertedFileFullN = Div.getFileNameWithoutExtension(pltFileFullName)+"."+exportType.toLowerCase();
convertedFile = new java.io.File(convertedFileFullN);
jLabelOutputName.setText(convertedFile.getName());
}
}//GEN-LAST:event_jComboBoxTypeActionPerformed
private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
if(windowSize != null) {
int w = windowSize.width;
int h = windowSize.height;
if(this.getHeight()<h){this.setSize(this.getWidth(), h);}
if(this.getWidth()<w){this.setSize(w,this.getHeight());}
}
}//GEN-LAST:event_formComponentResized
private void jScrollBarWidthFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jScrollBarWidthFocusGained
jScrollBarWidth.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0,0,0)));
}//GEN-LAST:event_jScrollBarWidthFocusGained
private void jScrollBarWidthFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jScrollBarWidthFocusLost
jScrollBarWidth.setBorder(scrollBorder);
}//GEN-LAST:event_jScrollBarWidthFocusLost
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Methods">
public final void closeWindow() {
finished = true;
this.setVisible(false);
this.dispose();
this.notify_All();
} // closeWindow()
private synchronized void notify_All() {notifyAll();}
/** this method will wait for this dialog frame to be closed
* @return "cancel" */
public synchronized boolean waitFor() {
while(!finished) {try {wait();} catch (InterruptedException ex) {}}
return cancel;
} // waitFor()
//</editor-fold>
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroupO;
private javax.swing.JButton jButtonDoIt;
private javax.swing.JComboBox<String> jComboBoxType;
private javax.swing.JLabel jLabelDir;
private javax.swing.JLabel jLabelDirName;
private javax.swing.JLabel jLabelFont;
private javax.swing.JLabel jLabelOut;
private javax.swing.JLabel jLabelOutputName;
private javax.swing.JLabel jLabelPltFile;
private javax.swing.JLabel jLabelPltFileName;
private javax.swing.JLabel jLabelSize;
private javax.swing.JLabel jLabel_H;
private javax.swing.JLabel jLabel_W;
private javax.swing.JLabel jLabel_h;
private javax.swing.JLabel jLabel_w;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanelBottom;
private javax.swing.JPanel jPanelSize;
private javax.swing.JPanel jPanelTop;
private javax.swing.JPanel jPanelType;
private javax.swing.JScrollBar jScrollBarWidth;
// End of variables declaration//GEN-END:variables
}
| 29,817 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
ProgramDataSpana.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Spana/src/spana/ProgramDataSpana.java | package spana;
import lib.kemi.chem.Chem;
/** Class to store information on the "Spana" program.
* The class is used to retrieve data in diverse methods
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class ProgramDataSpana {
/** true if advanced options should be shown to the user */
public boolean advancedVersion = false;
/** true if reversed concentration ranges are to be allowed */
public boolean reversedConcs = false;
/** true if the frame of SED or PREDOM is to be kept once the
* calculations are finished */
public boolean keepFrame = false;
/** number of calculation steps for program SED.
* The number of calculation points is the number of steps plus one. */
public int SED_nbrSteps = 50;
/** true if SED should also create a table with output data */
public boolean SED_tableOutput = false;
/** number of calculation steps for program PREDOM.
* The number of calculation points is the number of steps plus one. */
public int Predom_nbrSteps = 50;
/** true if PRDOM should only show aqueous species in the predominance area diagram */
public boolean aquSpeciesOnly = false;
/** the ionic strength for the calculations */
public double ionicStrength = 0;
/** the temperature in degrees Celsius, used both to calculate ionic strength effects, that is,
* to calculate activity coefficients, and to calculate values of the
* redox potential (Eh) from pe-values */
public double temperature = 25;
/** the pressure in bar, displayed in the diagram */
public double pressure = 1;
/** Model to calculate activity coefficents:<ul>
* <li> <0 for ideal solutions (all activity coefficients = 1)
* <li> =0 Davies eqn.
* <li> =1 SIT (Specific Ion interaction "Theory")
* <li> =2 Simplified HKF (Helson, Kirkham and Flowers)
* </ul> */
public int actCoeffsMethod = 0;
/** Max tolerance when solving mass-balance equations in HaltaFall. Should
* be between 0.01 and 1e-9 */
public double tolHalta = Chem.TOL_HALTA_DEF;
/** the path for a file containing parameters needed for the specific
* ion interaction model of calculation of activity coefficients (ionic
* strength effects) */
public String pathSIT = null;
/** level of debug output in HaltaFall:<br>
* 0 - none<br>
* 1 - errors only<br>
* 2 - errors + results<br>
* 3 - errors + results + input<br>
* 4 = 3 + output from Fasta<br>
* 5 = 4 + output from activity coeffs<br>
* 6 = 5 + lots of output.<br>
* Default = Chem.DBGHALTA_DEF =1 (output errors only)
* @see Chem#DBGHALTA_DEF Chem.DBGHALTA_DEF
* @see Chem.ChemSystem.ChemConcs#dbg Chem.ChemSystem.ChemConcs.dbg */
public int calcDbgHalta = Chem.DBGHALTA_DEF;
/** debug output in SED/Predom */
public boolean calcDbg = false;
/** true if values of redox potential (Eh) should be displayed in the
* diagrams, rather than values of pe */
public boolean useEh = true;
/** The file name extension for the table output from the program SED */
public String tblExtension = "csv";
/** Choices for <code>tblExtension</code>
* @see ProgramDataSpana#tblExtension tblExtension */
public String[] tblExtension_types = {"csv","dta","lst","txt","out","prn"};
/** The character separating data for the table output from the program SED */
public char tblFieldSeparator = ',';
/** Choices for <code>tblFieldSeparator</code>
* @see ProgramDataSpana#tblFieldSeparator tblFieldSeparator */
public char[] tblFieldSeparator_types = {';',',','\u0009',' '};
/** A string to be inserted at the beginning of comment-lines in the
* table output from program SED */
public String tblCommentLineStart = "\"";
/** A string to be appended at the end of comment-lines in the
* table output from program SED */
public String tblCommentLineEnd = "\"";
public boolean diagrConvertHeader = true;
public boolean diagrConvertColors = true;
public boolean diagrConvertPortrait = true;
/** Font type: 0=draw; 1=Times; 2=Helvetica; 3=Courier. */
public int diagrConvertFont = 2;
/** the size factor (%) in the X-direction */
public int diagrConvertSizeX = 100;
/** the size factor (%) in the Y-direction */
public int diagrConvertSizeY = 100;
/** margin in cm */
public float diagrConvertMarginB = 1;
/** margin in cm */
public float diagrConvertMarginL = 1;
public boolean diagrConvertEPS = false;
/** size in pixels */
public int diagrExportSize = 1000;
/** For example: bmp gif jpg png. */
public String diagrExportType = "png";
/** the minimum fraction value that a species must reach
* to be displayed in a fraction diagram. A value of 0.03 means that
* a species must have a fraction above 3% in order to be displayed
* in a fraction diagram. */
public float fractionThreshold = 0.03f;
/** if <code>true</code> a neutral pH line (at pH=7 for 25°C)
* will be drawn in Pourbaix diagrams (Eh/pH diagram) */
public boolean drawNeutralPHinPourbaix = false;
/** used to direct SED and Predom to draw concentration units
* as either:<ul><li>0="molal"</li><li>1="mol/kg_w"</li><li>2="M"</li><li>-1=""</li></ul> */
public int concentrationUnits = 0;
/** used to direct SED and Predom to draw concentrations
* as either scientific notation or engineering notation:<ul><li>0 = no choice
* (default, means scientific for "molar" and engineering for "M")</li>
* <li>1 = scientific notation</li><li>2 = engineering notation</li></ul> */
public int concentrationNotation = 0;
/** if <code>true</code> special settings will be "on" for students at
* the school of chemistry at the Royal Institute of Technology (KTH)
* in Stockholm, Sweden. */
public boolean kth = false;
/** if <code>true</code> then calculations are run by loading the jar-files
* (SED and Predom) into the Java Virtual Machine; if <code>false</code>
* the calculations are run as a separate system process. Used in class
* "Select_Diagram" */
public boolean jarClassLd = true;
public ProgramDataSpana() {}
}
| 6,834 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
ClipboardCopy_Image.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Spana/src/spana/ClipboardCopy_Image.java | package spana;
import lib.common.MsgExceptn;
import lib.kemi.graph_lib.DiagrPaintUtility;
import lib.kemi.graph_lib.GraphLib;
/** Copies to the clipboard (as an RGB image) a graphics stored in a GraphLib.PltData object.
* <br>
* With contributions from the code posted by "perpetuum" on 2008-mar-29 at:
* "http://forums.sun.com/thread.jspa?threadID=5129602"
* <br>
* Copyright (C) 2014-2016 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class ClipboardCopy_Image {
/** Inner class used to hold an image while on the clipboard. */
private static class ImageSelection implements java.awt.datatransfer.Transferable {
/** The size is 4/5 of the user's screen size. */
private final int width = (4*java.awt.Toolkit.getDefaultToolkit().getScreenSize().width)/5;
private final int height;
private final GraphLib.PltData dd; // contains the info in the plt-file;
private final DiagrPaintUtility diagrPaintUtil;
private static final java.awt.datatransfer.DataFlavor[] supportedFlavors
= {java.awt.datatransfer.DataFlavor.imageFlavor};
//Constructor
public ImageSelection(double height2width,
GraphLib.PltData dD,
DiagrPaintUtility diagrPU) {
height = (int)((double)width * height2width);
dd = dD;
diagrPaintUtil = diagrPU;
}
@Override
public java.awt.datatransfer.DataFlavor[] getTransferDataFlavors() {
return supportedFlavors;
}
@Override
public boolean isDataFlavorSupported(java.awt.datatransfer.DataFlavor flavor) {
for(java.awt.datatransfer.DataFlavor f : supportedFlavors) {
if (f.equals(flavor)) return true;
}
return false;
} // isDataFlavorSupported
/** Returns Image object housed by Transferable object */
@Override
public Object getTransferData(java.awt.datatransfer.DataFlavor flavor)
throws java.awt.datatransfer.UnsupportedFlavorException, java.io.IOException {
if (java.awt.datatransfer.DataFlavor.imageFlavor.equals(flavor)) {
//System.out.println("Mime type imageFlavor recognized");
try{
//Create an empty BufferedImage to paint
java.awt.image.BufferedImage buff_image =
new java.awt.image.BufferedImage(width, height,
java.awt.image.BufferedImage.TYPE_INT_RGB);
//get a graphics context
java.awt.Graphics2D g2D = buff_image.createGraphics();
if(diagrPaintUtil.useBackgrndColour) {
g2D.setColor(diagrPaintUtil.backgrnd);
} else {
g2D.setColor(java.awt.Color.WHITE);
}
g2D.fillRect(0, 0, width, height);
diagrPaintUtil.paintDiagram(g2D,
new java.awt.Dimension(width, height), dd, false);
return buff_image;
} catch(Exception ex) {
MsgExceptn.exception("getTransferData - Error: "+ex.getMessage());
return null;
}
} else {
//throw new UnsupportedFlavorException(flavor);
MsgExceptn.exception("UnsupportedFlavorException; flavor = "+flavor.toString());
return null;
}
} //getTransferData
} // class ImageSelection
/** Set the Clipboard contents to the plotting data in dD.
* The clipboard contents will be in RGB image format.
* The size is 4/5 of the user's screen size.
* @param heightToWidth height to width ratio of the image to be stored on the clipboard.
* @param dD information from the plt-file
* @param diagrPU contains parameters an methods to do the painting */
public static void setClipboard_Image(double heightToWidth,
GraphLib.PltData dD,
DiagrPaintUtility diagrPU) {
ImageSelection imageSelection = new ImageSelection(heightToWidth, dD, diagrPU);
java.awt.Toolkit.getDefaultToolkit().getSystemClipboard().setContents(imageSelection, null);
} // setClipboard
} // class ClipboardCopy_Image
| 4,794 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
Main.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Spana/src/spana/Main.java | package spana;
/** Checks for all the jar-libraries needed.
* <br>
* Copyright (C) 2014-2016 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class Main {
public static final String progName = "Program Spana";
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
private static boolean started = false;
private static final String SLASH = java.io.File.separator;
/** Check that all the jar-libraries needed do exist.
* @param args the command line arguments */
public static void main(String[] args) {
// ---- are all jar files needed there?
if(!doJarFilesExist()) {return;}
// ---- ok!
MainFrame.main(args);
}
//<editor-fold defaultstate="collapsed" desc="doJarFilesExist">
/** Look in the running jar file's classPath Manifest for any other "library"
* jar-files listed under "Class-path".
* If any of these jar files does not exist display an error message
* (and an error Frame) and continue.
* @return true if all needed jar files exist; false otherwise.
* @version 2016-Aug-03 */
private static boolean doJarFilesExist() {
java.io.File libJarFile, libPathJarFile;
java.util.jar.JarFile runningJar = getRunningJarFile();
// runningJar.getName() = C:\Eq-Calc_Java\dist\Prog.jar
if(runningJar != null) { // if running within Netbeans there will be no jar-file
java.util.jar.Manifest manifest;
try {manifest = runningJar.getManifest();}
catch (java.io.IOException ex) {
manifest = null;
String msg = "Warning: no manifest found in the application's jar file:"+nl+
"\""+runningJar.getName()+"\"";
ErrMsgBox emb = new ErrMsgBox(msg, progName);
//this will return true;
}
if(manifest != null) {
String classPath = manifest.getMainAttributes().getValue("Class-Path");
if(classPath != null && classPath.length() > 0) {
// this will be a list of space-separated names
String[] jars = classPath.split("\\s+"); //regular expression to match one or more spaces
if(jars.length >0) {
java.io.File[] rootNames = java.io.File.listRoots();
boolean isPathAbsolute;
String pathJar;
String p = getPathApp(); // get the application's path
for(String jar : jars) { // loop through all jars needed
libJarFile = new java.io.File(jar);
if(libJarFile.exists()) {continue;}
isPathAbsolute = false;
for(java.io.File f : rootNames) {
if(jar.toLowerCase().startsWith(f.getAbsolutePath().toLowerCase())) {
isPathAbsolute = true;
break;}
}
if(!isPathAbsolute) { // add the application's path
if(!p.endsWith(SLASH) && !jar.startsWith(SLASH)) {p = p+SLASH;}
pathJar = p + jar;
} else {pathJar = jar;}
libPathJarFile = new java.io.File(pathJar);
if(libPathJarFile.exists()) {continue;}
libPathJarFile = new java.io.File(libPathJarFile.getAbsolutePath());
ErrMsgBox emb = new ErrMsgBox(progName+" - Error:"+nl+
" File: \""+jar+"\" NOT found."+nl+
" And file: \""+libPathJarFile.getName()+"\" is NOT in folder:"+nl+
" \""+libPathJarFile.getParent()+"\""+nl+
" either!"+nl+nl+
" This file is needed by the program."+nl, progName);
return false;
}
}
}//if classPath != null
} //if Manifest != null
} //if runningJar != null
return true;
} //doJarFilesExist()
//<editor-fold defaultstate="collapsed" desc="getRunningJarFile()">
/** Find out the jar file that contains this class
* @return a File object of the jar file containing the enclosing class "Main",
* or null if the main class is not inside a jar file.
* @version 2014-Jan-17 */
public static java.util.jar.JarFile getRunningJarFile() {
//from http://www.rgagnon.com/javadetails/
//and the JarClassLoader class
C c = new C();
String className = c.getClass().getName().replace('.', '/');
// class = "progPackage.Main"; className = "progPackage/Main"
java.net.URL url = c.getClass().getResource("/" + className + ".class");
// url = "jar:file:/C:/Eq-Calc_Java/dist/Prog.jar!/progPackage/Main.class"
if(url.toString().startsWith("jar:")) {
java.net.JarURLConnection jUrlC;
try{
jUrlC = (java.net.JarURLConnection)url.openConnection();
return jUrlC.getJarFile();
} catch(java.io.IOException ex) {
ErrMsgBox emb = new ErrMsgBox("Error "+ex.toString(), progName);
return null;
}
} else {
// it might not be a jar file if running within NetBeans
return null;
}
} //getRunningJarFile()
//</editor-fold>
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="getPathApp">
/** Get the path where an application is located.
* @return the directory where the application is located,
* or "user.dir" if an error occurs
* @version 2014-Jan-17 */
private static class C {private static void C(){}}
public static String getPathApp() {
C c = new C();
String path;
java.net.URI dir;
try{
dir = c.getClass().
getProtectionDomain().
getCodeSource().
getLocation().
toURI();
if(dir != null) {
String d = dir.toString();
if(d.startsWith("jar:") && d.endsWith("!/")) {
d = d.substring(4, d.length()-2);
dir = new java.net.URI(d);
}
path = (new java.io.File(dir.getPath())).getParent();
} else {path = System.getProperty("user.dir");}
}
catch (java.net.URISyntaxException e) {
if(!started) {
ErrMsgBox emb = new ErrMsgBox("Error: "+e.toString()+nl+
" trying to get the application's directory.", progName);
}
path = System.getProperty("user.dir");
} // catch
started = true;
return path;
} //getPathApp()
//</editor-fold>
}
| 7,251 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
Select_Diagram.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Spana/src/spana/Select_Diagram.java | package spana;
import lib.common.MsgExceptn;
import lib.common.Util;
import lib.huvud.Div;
import lib.huvud.ProgramConf;
import lib.kemi.chem.Chem;
import lib.kemi.readDataLib.ReadDataLib;
import lib.kemi.readWriteDataFiles.DefaultPlotAndConcs;
import lib.kemi.readWriteDataFiles.ReadChemSyst;
import lib.kemi.readWriteDataFiles.WriteChemSyst;
import static spana.MainFrame.LINE;
/** Perhaps the most important part of the program: it allows the user to
* make changes to the input file without a text editor. A lot of
* "intelligence" is used to make life easy for the user.
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class Select_Diagram extends javax.swing.JFrame {
// classes used to store data
private final ProgramConf pc;
private final spana.ProgramDataSpana pd;
private Chem ch = null;
private Chem.ChemSystem cs = null;
private Chem.ChemSystem.NamesEtc namn = null;
private Chem.Diagr diag = null;
/** the diagram data originally found in the input data file.
* Used to check if the file needs to be saved because changes have been made. */
private Chem.Diagr diag0 = null;
private Chem.DiagrConcs dgrC = null;
/** the diagram concentrations originally found in the input data file.
* Used to check if the file needs to be saved because changes have been made. */
private Chem.DiagrConcs dgrC0 = null;
//
private final java.awt.Dimension windowSize;
private boolean finished = false;
private java.io.File dataFile;
private java.io.File pltFile;
private boolean cancel = false;
private int nbrGases;
/** the species equal to "e-" if it exists, otherwise =-1.
* It may be a component or a reaction product. */
private int ePresent;
/** the species equal to "H+" if it exists, otherwise =-1.
* It may be a component or a reaction product. */
private int hPresent;
//---- these local fields are discarded if the user does not save them as default
/** 0 = loading frame (starting); 1 = Predom diagram; 2 = SED diagram*/
private int runPredomSED;
/** number of calculation steps for SED diagram.
* The number of calculation points is the number of steps plus one. */
private int runNbrStepsSED;
/** number of calculation steps for Predom diagram.
* The number of calculation points is the number of steps plus one. */
private int runNbrStepsPred;
/** output a table with results (for SED obly)? */
private boolean runTbl;
/** aqueous species only? */
private boolean runAqu;
/** allow reverse concentration ranges in the axes? */
private boolean runRevs;
/** use "Eh" (if true) or "pe" (if false) as variable in diagram */
private boolean runUseEh;
/** model to calculate activity coefficients<ul>
* <li> <0 for ideal solutions (all activity coefficients = 1)
* <li> =0 Davies eqn.
* <li> =1 SIT (Specific Ion interaction "Theory")
* <li> =2 Simplified HKF (Helson, Kirkham and Flowers)
* </ul> */
private int runActCoeffsMethod;
/** draw pH line in Pourbaix diagrams? */
private boolean runPHline;
/** concentration units when drawing diagrams
* (may be 0="molal", 1="mol/kg_w", 2="M" or -1="") */
private int runConcUnits;
/** concentration notation when drawing diagrams
* (may be 0="no choice", 1="scientific", 2="engineering") */
private int runConcNottn;
/** true if SED/Predom are from the Medusa-32 package, that is, they are Fortran programs */
private boolean oldProg = false;
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
private final double ln10 = Math.log(10);
/** <pre>concTypes[]:
* [0]= "Total conc." [1]= "Total conc. varied"
* [2]= "log (Total conc.) varied"
* [3]= "log (activity)" [4]= "log (activity) varied"
* [5]= "pH" [6]= "pH varied"
* [7]= "pe" [8]= "pe varied"
* [9]= "Eh" [10]= "Eh varied"
* [11]= "log P" [12]= "log P varied"</pre>
* @see Select_Diagram#componentConcType componentConcType */
private final String[] concTypes = {"Total conc.","Total conc. varied",
"log (Total conc.) varied","log (activity)","log (activity) varied",
"pH","pH varied","pe","pe varied","Eh","Eh varied",
"log P","log P varied"};
/** for each component it indicates which of concTypes is used:<pre>
* 0 = Total conc. 1 = Total conc. varied
* 2 = log (Total conc.) varied
* 3 = log (activity) 4 = log (activity) varied
* 5 = pH 6 = pH varied
* 7 = pe 8 = pe varied
* 9 = Eh 10 = Eh varied
* 11 = log P 12 = log P varied</pre>
* Used in <code>updateAxes()</code> to determine <code>mustChange</code>.
* @see Select_Diagram#concTypes concTypes */
private int[] componentConcType;
private boolean loading, changingComp, updatingAxes;
private boolean getConcLoading;
private String xAxisType0, yAxisType0;
/** the species-number for H+ or e- if its activity will be plotted in the
* Y-axis. If neither calculated pH nor pe/Eh is plotted in the Y-axis,
* then Ycalc = -1. Note that Ycalc may be a component or a reaction product.
* @see chem.Chem.Diagr#compY compY
* @see chem.Chem.Diagr#compX compX */
private int Ycalc;
private final javax.swing.DefaultListModel<String> listCompConcModel = new javax.swing.DefaultListModel<>();
//private final javax.swing.DefaultListModel listCompConcModel = new javax.swing.DefaultListModel(); // java 1.6
private final java.awt.Color backg;
/** when a jTextField containing a number is edited,
* the old text is saved in this variable. If the user makes a mistake, for example
* enters "0.7e", then the old text is restored from this variable. */
private String oldTextCLow = "0";
/** when a jTextField containing a number is edited,
* the old text is saved in this variable. If the user makes a mistake, for example
* enters "0.7e", then the old text is restored from this variable. */
private String oldTextCHigh = "0";
/** when a jTextField containing a number is edited,
* the old text is saved in this variable. If the user makes a mistake, for example
* enters "0.7e", then the old text is restored from this variable. */
private String oldTextI = "0";
/** when a jTextField containing a number is edited,
* the old text is saved in this variable. If the user makes a mistake, for example
* enters "0.7e", then the old text is restored from this variable. */
private String oldTextT = "25";
/** when a jTextField containing a number is edited,
* the old text is saved in this variable. If the user makes a mistake, for example
* enters "0.7e", then the old text is restored from this variable. */
private String oldTextXmin = "0";
/** when a jTextField containing a number is edited,
* the old text is saved in this variable. If the user makes a mistake, for example
* enters "0.7e", then the old text is restored from this variable. */
private String oldTextXmax = "0";
/** when a jTextField containing a number is edited,
* the old text is saved in this variable. If the user makes a mistake, for example
* enters "0.7e", then the old text is restored from this variable. */
private String oldTextYmin = "0";
/** when a jTextField containing a number is edited,
* the old text is saved in this variable. If the user makes a mistake, for example
* enters "0.7e", then the old text is restored from this variable. */
private String oldTextYmax = "0";
private static String lastDataFileName = null;
private static String lastPlotFileName = null;
private boolean plotAndConcsNotGiven;
/** true if the temperature is written as a comment in the first line of the input file */
private boolean temperatureGivenInInputFile;
private double ionicStrOld;
/** the concentration type in <code>jComboBoxConcType</code> when the user clicks
* on <code>jListCompConc</code> */
private String comboBoxConcType0;
/** do not fire the action event when adding an item to the combo box
* or when setting the selected item within the program */
private boolean diagramType_doNothing = false;
/** the selected component index in the concentrations list */
private int getConc_idx;
/** command line arguments passed to the program (SED or Predom) that calculates the diagram */
private String[] args;
/** a class that loads a jar file and executes its "main" method. Used to
* run the program (SED or Predom) that calculates the diagram */
private lib.huvud.RunJar rj;
private static final java.text.DecimalFormat myFormatter =
(java.text.DecimalFormat)java.text.NumberFormat.getNumberInstance(java.util.Locale.ENGLISH);
private static final String SLASH = java.io.File.separator;
private final javax.swing.border.Border scrollBorder;
private final javax.swing.border.Border defBorder;
private final javax.swing.border.Border highlightedBorder = javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED, java.awt.Color.gray, java.awt.Color.black);
//<editor-fold defaultstate="collapsed" desc="Constructor">
public Select_Diagram(java.io.File datFile,
ProgramConf pc0,
spana.ProgramDataSpana pd0) {
this.pc = pc0;
this.pd = pd0;
dataFile = datFile;
// ---- compose the jFrame
initComponents();
//move jTextFieldYmax and jTextFieldYmin to the right of their jPanels
jPanelYmax.add(javax.swing.Box.createHorizontalGlue(),0);
jPanelYmax.validate();
jPanelYmin.add(javax.swing.Box.createHorizontalGlue(),0);
jPanelYmin.validate();
//move jTextFieldXmax and jTextFieldXmin to the right and left of their jPanel
jPanelXaxis.add(javax.swing.Box.createHorizontalGlue(),1);
jPanelXaxis.validate();
//
myFormatter.setGroupingUsed(false);
// ---- center Window on Screen
windowSize = this.getSize();
int left; int top;
left = Math.max(0, (MainFrame.screenSize.width - windowSize.width ) / 2);
top = Math.max(0, (MainFrame.screenSize.height - windowSize.height) / 2);
left = Math.min(MainFrame.screenSize.width-100, left);
top = Math.min(MainFrame.screenSize.height-100, top);
if(MainFrame.locationSDFrame.x >= 0) {
this.setLocation(MainFrame.locationSDFrame);
} else {this.setLocation(left,top);}
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
//--- close window on ESC key / exit jPanelGetConc
javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_ESCAPE,0, false);
javax.swing.Action escAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jPanelGetConc.isShowing()) {getConc_Unload();}
else {cancel =true; quitFrame();}
}};
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE");
getRootPane().getActionMap().put("ESCAPE", escAction);
//--- F1 for help
javax.swing.KeyStroke f1KeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_F1,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(f1KeyStroke,"F1");
javax.swing.Action f1Action = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jButton_Help.doClick();
}};
getRootPane().getActionMap().put("F1", f1Action);
//--- F2 to edit a concentration
javax.swing.KeyStroke f2KeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_F2,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(f2KeyStroke,"F2");
javax.swing.Action f2Action = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jListCompConc.isVisible()) {
compConcList_Click(jListCompConc.getSelectedIndex());
}
}};
getRootPane().getActionMap().put("F2", f2Action);
// ---- Define Alt-keys
// Alt-M, Alt-Q, Alt-H and Alt-S are mnemonics to the 4 buttons
// Alt-E, R, T, W are shortcuts for check-boxes
// Define Alt-Enter, -X, -O, -C, -F, -N, -D, -I
//--- Alt-X = Make diagram
javax.swing.KeyStroke altXKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altXKeyStroke,"ALT_X");
javax.swing.Action altXAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jButton_OK.doClick();
}};
getRootPane().getActionMap().put("ALT_X", altXAction);
//--- Alt-Enter = Make diagram
javax.swing.KeyStroke altEnterKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_ENTER, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altEnterKeyStroke,"ALT_ENTER");
getRootPane().getActionMap().put("ALT_ENTER", altXAction);
//--- Alt-O concentration-ok/make diagram
javax.swing.KeyStroke altOKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altOKeyStroke,"ALT_O");
javax.swing.Action altOAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jPanelGetConc.isShowing()) {jButtonGetConcOK.doClick();}
else {jButton_OK.doClick();}
}};
getRootPane().getActionMap().put("ALT_O", altOAction);
//--- Alt-C focus to concentration/cancel
javax.swing.KeyStroke altCKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altCKeyStroke,"ALT_C");
javax.swing.Action altCAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jPanelGetConc.isShowing()) {getConc_Unload();}
else {
jListCompConc.requestFocus();
jListCompConc.clearSelection();
}
}};
getRootPane().getActionMap().put("ALT_C", altCAction);
//--- Alt-F = File name text box
javax.swing.KeyStroke altFKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_F, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altFKeyStroke,"ALT_F");
javax.swing.Action altFAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jTextFieldDataFile.requestFocusInWindow();
}};
getRootPane().getActionMap().put("ALT_F", altFAction);
//--- Alt-N = Diagram name text box
javax.swing.KeyStroke altNKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altNKeyStroke,"ALT_N");
javax.swing.Action altNAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jTextFieldDiagName.requestFocusInWindow();
}};
getRootPane().getActionMap().put("ALT_N", altNAction);
//--- Alt-A = activity coefficient method
javax.swing.KeyStroke altAKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altAKeyStroke,"ALT_A");
javax.swing.Action altAAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jPanelModel.isVisible()) {jComboBoxActCoeff.requestFocusInWindow();}
}};
getRootPane().getActionMap().put("ALT_A", altAAction);
//--- Alt-D diagram
javax.swing.KeyStroke altDKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_D, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altDKeyStroke,"ALT_D");
javax.swing.Action altDAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jComboBoxDiagType.requestFocus();
}};
getRootPane().getActionMap().put("ALT_D", altDAction);
//--- Alt-I ionic strength
javax.swing.KeyStroke altIKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_I, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altIKeyStroke,"ALT_I");
javax.swing.Action altIAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jTextFieldIonicStr.requestFocus();
}};
getRootPane().getActionMap().put("ALT_I", altIAction);
// ---- Title
this.setTitle(" Select Diagram Type: "+datFile.getName());
// ---- Icon
String iconName = "images/SelDiagr.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
if (imgURL != null) {this.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());}
else {System.out.println("--- Error: Could not load image = \""+iconName+"\"");}
// ---- Set main things
defBorder = jScrollPaneCompConcList.getBorder();
scrollBorder = jScrollBarSEDNbrP.getBorder();
backg = jPanelDiagrType.getBackground();
loading = true;
updatingAxes = false;
changingComp = false;
if(!pd.advancedVersion) {
jLabelTitle.setText("");
jTextFieldTitle.setVisible(false);
}
} // constructor
public void start() {
if(pc.dbg) {System.out.println("---- starting \"Select_Diagram\" ----");}
if(!readDataFile(pc.dbg)) {
cancel =true;
quitFrame();
return;
}
// --- set default values
jComboBoxActCoeff.setSelectedIndex(pd.actCoeffsMethod);
jLabelModel.setVisible(pd.advancedVersion);
jComboBoxActCoeff.setVisible(pd.advancedVersion);
runNbrStepsPred = pd.Predom_nbrSteps;
jLabelPredNbrP.setText(String.valueOf(runNbrStepsPred));
jScrollBarPredNbrP.setValue(runNbrStepsPred);
jScrollBarPredNbrP.setFocusable(true);
runNbrStepsSED = pd.SED_nbrSteps;
jLabelSEDNbrP.setText(String.valueOf(runNbrStepsSED));
jScrollBarSEDNbrP.setValue(runNbrStepsSED);
jScrollBarSEDNbrP.setFocusable(true);
runAqu = pd.aquSpeciesOnly; jCheckBoxAqu.setSelected(runAqu);
runPHline = pd.drawNeutralPHinPourbaix; jCheckBoxDrawPHline.setSelected(runPHline);
runConcUnits = Math.max(-1,Math.min(pd.concentrationUnits, 2));
runConcNottn = Math.max(0,Math.min(pd.concentrationNotation, 2));
runTbl = pd.SED_tableOutput; jCheckBoxTableOut.setSelected(runTbl);
runRevs = pd.reversedConcs; jCheckBoxRev.setSelected(runRevs);
runUseEh = pd.useEh; jCheckBoxUseEh.setSelected(runUseEh);
runPredomSED = 0;
diag.ionicStrength = pd.ionicStrength;
ionicStrOld = diag.ionicStrength;
jTextFieldIonicStr.setText(Util.formatNum(diag.ionicStrength));
if(diag.ionicStrength >= 0) {jRadioButtonFixed.doClick();} else {jRadioButtonCalc.doClick();}
this.pack();
setUpFrame();
loading = false;
updateAxes();
updateConcList();
updateUseEhCheckBox();
updateDrawPHlineBox();
//focusLostYmin(); focusLostYmax();
//focusLostXmin(); focusLostXmax();
resizeXMinMax(); resizeYMax(); resizeYMin();
this.setVisible(true);
windowSize.width = getWidth();
windowSize.height = getHeight();
if(plotAndConcsNotGiven) {missingPlotAndConcsMessage();}
if(pc.dbg) {System.out.println("---- \"Select_Diagram\" started! ----");}
} // start()
private void missingPlotAndConcsMessage() {
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override
public void run() {
String msg= "Warning: plot/concentration data missing or not correct"+nl+
" in input data file:"+nl+
" \""+dataFile+"\""+nl+
" Default values will be used.";
System.out.println(msg);
if(diag.databaseSpanaFile != 1) {
javax.swing.JOptionPane.showMessageDialog(Select_Diagram.this, msg,
pc.progName+" - Missing data", javax.swing.JOptionPane.WARNING_MESSAGE);
}
}}); //invokeLater(Runnable)
}
//</editor-fold>
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroupActCoef = new javax.swing.ButtonGroup();
jPanelButtons = new javax.swing.JPanel();
jButton_OK = new javax.swing.JButton();
jButton_Cancel = new javax.swing.JButton();
jButton_Help = new javax.swing.JButton();
jPanelFileNames = new javax.swing.JPanel();
jLabelDataFile = new javax.swing.JLabel();
jLabelDFileName = new javax.swing.JLabel();
jTextFieldDataFile = new javax.swing.JTextField();
jLabelOFile = new javax.swing.JLabel();
jTextFieldDiagName = new javax.swing.JTextField();
jPanelDiagram = new javax.swing.JPanel();
jPanelTitle = new javax.swing.JPanel();
jLabelTitle = new javax.swing.JLabel();
jTextFieldTitle = new javax.swing.JTextField();
jPanelDiagrType = new javax.swing.JPanel();
jPanelAxes = new javax.swing.JPanel()
{
@Override
public void paint(java.awt.Graphics g)
{
super.paint(g);
paintDiagPanel(g);
}
};
jLabelDiagrType = new javax.swing.JLabel();
jComboBoxDiagType = new javax.swing.JComboBox<>();
jPanelMainComp = new javax.swing.JPanel();
jComboBoxMainComp = new javax.swing.JComboBox<>();
jPanelXaxis = new javax.swing.JPanel();
jTextFieldXmin = new javax.swing.JTextField();
jTextFieldXmax = new javax.swing.JTextField();
jPanelYaxis = new javax.swing.JPanel();
jLabelYaxis = new javax.swing.JLabel();
jPanelYmax = new javax.swing.JPanel();
jTextFieldYmax = new javax.swing.JTextField();
jPanelYaxInner = new javax.swing.JPanel();
jPanelYcombo = new javax.swing.JPanel();
jComboBoxYaxType = new javax.swing.JComboBox<>();
jPanelYlogC = new javax.swing.JPanel();
jLabelYlogC = new javax.swing.JLabel();
jPanelYlogA = new javax.swing.JPanel();
jLabelYlogA = new javax.swing.JLabel();
jPanelYlogS = new javax.swing.JPanel();
jLabelYlogS = new javax.swing.JLabel();
jPanelYRef = new javax.swing.JPanel();
jLabelYRef = new javax.swing.JLabel();
jPanelYfraction = new javax.swing.JPanel();
jLabelYFract = new javax.swing.JLabel();
jPanelYcalc = new javax.swing.JPanel();
jLabelYcalc = new javax.swing.JLabel();
jPanelYHaff = new javax.swing.JPanel();
jLabelHaff = new javax.swing.JLabel();
jPanelYaxComp = new javax.swing.JPanel();
jComboBoxYaxComp = new javax.swing.JComboBox<>();
jPanelEmptyYax = new javax.swing.JPanel();
jPanelYmin = new javax.swing.JPanel();
jTextFieldYmin = new javax.swing.JTextField();
jPanelXComponent = new javax.swing.JPanel();
jLabelXaxis = new javax.swing.JLabel();
jComboBoxXaxType = new javax.swing.JComboBox<>();
jComboBoxXaxComp = new javax.swing.JComboBox<>();
jPanelEmptyDiagram = new javax.swing.JPanel();
jPanelParams = new javax.swing.JPanel();
jPanelActCoef = new javax.swing.JPanel();
jLabelIS = new javax.swing.JLabel();
jRadioButtonFixed = new javax.swing.JRadioButton();
jRadioButtonCalc = new javax.swing.JRadioButton();
jLabelIonicS = new javax.swing.JLabel();
jTextFieldIonicStr = new javax.swing.JTextField();
jLabelM = new javax.swing.JLabel();
jLabelT = new javax.swing.JLabel();
jTextFieldT = new javax.swing.JTextField();
jLabelTC = new javax.swing.JLabel();
jPanelModel = new javax.swing.JPanel();
jLabelModel = new javax.swing.JLabel();
jComboBoxActCoeff = new javax.swing.JComboBox<>();
jPanelSedPredom = new javax.swing.JPanel();
jPanelPredom = new javax.swing.JPanel();
jLabelPredNbr = new javax.swing.JLabel();
jLabelPredNbrP = new javax.swing.JLabel();
jScrollBarPredNbrP = new javax.swing.JScrollBar();
jPanelTotCalcs = new javax.swing.JPanel();
jLabelTotNbr = new javax.swing.JLabel();
jLabelNbrCalcs = new javax.swing.JLabel();
jCheckBoxAqu = new javax.swing.JCheckBox();
jCheckBoxDrawPHline = new javax.swing.JCheckBox();
jLabelSpaceP = new javax.swing.JLabel();
jPanelSED = new javax.swing.JPanel();
jCheckBoxTableOut = new javax.swing.JCheckBox();
jLabelSEDNbr = new javax.swing.JLabel();
jLabelSEDNbrP = new javax.swing.JLabel();
jScrollBarSEDNbrP = new javax.swing.JScrollBar();
jPanelEmptyParameters = new javax.swing.JPanel();
jPanelLow = new javax.swing.JPanel();
jCheckBoxRev = new javax.swing.JCheckBox();
jCheckBoxUseEh = new javax.swing.JCheckBox();
jLabelSpace = new javax.swing.JLabel();
jButtonSaveDef = new javax.swing.JButton();
jPanelConcs = new javax.swing.JPanel();
jScrollPaneCompConcList = new javax.swing.JScrollPane();
jListCompConc = new javax.swing.JList();
jPanelGetConc = new javax.swing.JPanel();
jLabelEnterConc = new javax.swing.JLabel();
jPanelConcInner = new javax.swing.JPanel();
jLabel_GetConcCompName = new javax.swing.JLabel();
jComboBoxConcType = new javax.swing.JComboBox<>();
jLabelEqual = new javax.swing.JLabel();
jLabelFrom = new javax.swing.JLabel();
jTextFieldCLow = new javax.swing.JTextField();
jLabelTo = new javax.swing.JLabel();
jTextFieldCHigh = new javax.swing.JTextField();
jButtonGetConcOK = new javax.swing.JButton();
jButtonGetConcCancel = new javax.swing.JButton();
jPanelLabl = new javax.swing.JPanel();
jLabl1 = new javax.swing.JLabel();
jLabl2 = new javax.swing.JLabel();
jLabl3 = new javax.swing.JLabel();
jLabl4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jPanelButtons.setMaximumSize(new java.awt.Dimension(169, 61));
jPanelButtons.setMinimumSize(new java.awt.Dimension(100, 61));
jButton_OK.setIcon(new javax.swing.ImageIcon(getClass().getResource("/spana/images/Spana_icon_32x32.gif"))); // NOI18N
jButton_OK.setMnemonic('m');
jButton_OK.setToolTipText("<html><u>M</u>ake Diagram (Alt-X or Alt-M)</html>"); // NOI18N
jButton_OK.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButton_OK.setMargin(new java.awt.Insets(2, 2, 2, 2));
jButton_OK.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_OKActionPerformed(evt);
}
});
jButton_Cancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/spana/images/Trash.gif"))); // NOI18N
jButton_Cancel.setMnemonic('q');
jButton_Cancel.setToolTipText("Cancel (Alt-Q, Esc)"); // NOI18N
jButton_Cancel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButton_Cancel.setMargin(new java.awt.Insets(2, 2, 2, 2));
jButton_Cancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_CancelActionPerformed(evt);
}
});
jButton_Help.setIcon(new javax.swing.ImageIcon(getClass().getResource("/spana/images/Help_32x32.gif"))); // NOI18N
jButton_Help.setMnemonic('h');
jButton_Help.setToolTipText("<html><u>H</u>elp</html>"); // NOI18N
jButton_Help.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButton_Help.setMargin(new java.awt.Insets(2, 2, 2, 2));
jButton_Help.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_HelpActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanelButtonsLayout = new javax.swing.GroupLayout(jPanelButtons);
jPanelButtons.setLayout(jPanelButtonsLayout);
jPanelButtonsLayout.setHorizontalGroup(
jPanelButtonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelButtonsLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton_OK)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton_Cancel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton_Help)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelButtonsLayout.setVerticalGroup(
jPanelButtonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelButtonsLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelButtonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton_OK)
.addComponent(jButton_Cancel)
.addComponent(jButton_Help))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jLabelDataFile.setText("<html>Input Data <u>F</u>ile</html>"); // NOI18N
jLabelDFileName.setLabelFor(jTextFieldDataFile);
jLabelDFileName.setText("<html>name:</html>"); // NOI18N
jTextFieldDataFile.setText("jTextFieldDataFile"); // NOI18N
jTextFieldDataFile.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTextFieldDataFileMouseClicked(evt);
}
});
jTextFieldDataFile.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextFieldDataFileActionPerformed(evt);
}
});
jTextFieldDataFile.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextFieldDataFileFocusGained(evt);
}
});
jTextFieldDataFile.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTextFieldDataFileKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextFieldDataFileKeyTyped(evt);
}
});
jLabelOFile.setLabelFor(jTextFieldDiagName);
jLabelOFile.setText("<html>Diagram <u>n</u>ame:</html>"); // NOI18N
jTextFieldDiagName.setText("jTextFieldDiagName"); // NOI18N
jTextFieldDiagName.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextFieldDiagNameFocusGained(evt);
}
});
javax.swing.GroupLayout jPanelFileNamesLayout = new javax.swing.GroupLayout(jPanelFileNames);
jPanelFileNames.setLayout(jPanelFileNamesLayout);
jPanelFileNamesLayout.setHorizontalGroup(
jPanelFileNamesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelFileNamesLayout.createSequentialGroup()
.addGroup(jPanelFileNamesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanelFileNamesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelFileNamesLayout.createSequentialGroup()
.addGap(4, 4, 4)
.addComponent(jLabelOFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabelDataFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabelDFileName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelFileNamesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextFieldDataFile)
.addComponent(jTextFieldDiagName))
.addContainerGap())
);
jPanelFileNamesLayout.setVerticalGroup(
jPanelFileNamesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelFileNamesLayout.createSequentialGroup()
.addGroup(jPanelFileNamesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelDataFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanelFileNamesLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelFileNamesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextFieldDataFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelDFileName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelFileNamesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelOFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextFieldDiagName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
jPanelDiagram.setBorder(javax.swing.BorderFactory.createTitledBorder(null, " Diagram: ", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12), new java.awt.Color(153, 0, 153))); // NOI18N
jLabelTitle.setLabelFor(jTextFieldTitle);
jLabelTitle.setText("Title:"); // NOI18N
jTextFieldTitle.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextFieldTitleFocusGained(evt);
}
});
javax.swing.GroupLayout jPanelTitleLayout = new javax.swing.GroupLayout(jPanelTitle);
jPanelTitle.setLayout(jPanelTitleLayout);
jPanelTitleLayout.setHorizontalGroup(
jPanelTitleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelTitleLayout.createSequentialGroup()
.addComponent(jLabelTitle)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextFieldTitle)
.addGap(0, 0, 0))
);
jPanelTitleLayout.setVerticalGroup(
jPanelTitleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelTitleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(jLabelTitle)
.addComponent(jTextFieldTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jPanelDiagrType.setMaximumSize(new java.awt.Dimension(179, 131));
jPanelAxes.setBackground(new java.awt.Color(236, 236, 236));
jPanelAxes.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jPanelAxes.setMaximumSize(new java.awt.Dimension(179, 105));
jLabelDiagrType.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabelDiagrType.setForeground(new java.awt.Color(0, 0, 255));
jLabelDiagrType.setLabelFor(jComboBoxDiagType);
jLabelDiagrType.setText("<html><u>D</u>iagram type:</html>"); // NOI18N
jComboBoxDiagType.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Predominance Area", "Logarithmic", "log Activities", "Fraction", "log Solubilities", "Relative activities", "Calculated Eh", "Calculated pH", "H+ affinity spectrum" }));
jComboBoxDiagType.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBoxDiagTypeActionPerformed(evt);
}
});
jPanelMainComp.setOpaque(false);
javax.swing.GroupLayout jPanelMainCompLayout = new javax.swing.GroupLayout(jPanelMainComp);
jPanelMainComp.setLayout(jPanelMainCompLayout);
jPanelMainCompLayout.setHorizontalGroup(
jPanelMainCompLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 10, Short.MAX_VALUE)
);
jPanelMainCompLayout.setVerticalGroup(
jPanelMainCompLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 21, Short.MAX_VALUE)
);
jComboBoxMainComp.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBoxMainComp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBoxMainCompActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanelAxesLayout = new javax.swing.GroupLayout(jPanelAxes);
jPanelAxes.setLayout(jPanelAxesLayout);
jPanelAxesLayout.setHorizontalGroup(
jPanelAxesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelAxesLayout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(jPanelAxesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelDiagrType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBoxDiagType, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanelAxesLayout.createSequentialGroup()
.addComponent(jComboBoxMainComp, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanelMainComp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(20, Short.MAX_VALUE))
);
jPanelAxesLayout.setVerticalGroup(
jPanelAxesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelAxesLayout.createSequentialGroup()
.addGap(7, 7, 7)
.addComponent(jLabelDiagrType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBoxDiagType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelAxesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jComboBoxMainComp, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanelMainComp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(23, Short.MAX_VALUE))
);
jPanelXaxis.setLayout(new javax.swing.BoxLayout(jPanelXaxis, javax.swing.BoxLayout.LINE_AXIS));
jTextFieldXmin.setText("-5"); // NOI18N
jTextFieldXmin.setName("Xmin"); // NOI18N
jTextFieldXmin.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextFieldXminFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jTextFieldXminFocusLost(evt);
}
});
jTextFieldXmin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextFieldXminActionPerformed(evt);
}
});
jTextFieldXmin.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jTextFieldXminKeyReleased(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextFieldXminKeyTyped(evt);
}
});
jPanelXaxis.add(jTextFieldXmin);
jTextFieldXmax.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
jTextFieldXmax.setText("-5"); // NOI18N
jTextFieldXmax.setName("Xmax"); // NOI18N
jTextFieldXmax.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextFieldXmaxFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jTextFieldXmaxFocusLost(evt);
}
});
jTextFieldXmax.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextFieldXmaxActionPerformed(evt);
}
});
jTextFieldXmax.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jTextFieldXmaxKeyReleased(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextFieldXmaxKeyTyped(evt);
}
});
jPanelXaxis.add(jTextFieldXmax);
javax.swing.GroupLayout jPanelDiagrTypeLayout = new javax.swing.GroupLayout(jPanelDiagrType);
jPanelDiagrType.setLayout(jPanelDiagrTypeLayout);
jPanelDiagrTypeLayout.setHorizontalGroup(
jPanelDiagrTypeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanelAxes, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanelXaxis, javax.swing.GroupLayout.DEFAULT_SIZE, 181, Short.MAX_VALUE)
);
jPanelDiagrTypeLayout.setVerticalGroup(
jPanelDiagrTypeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelDiagrTypeLayout.createSequentialGroup()
.addComponent(jPanelAxes, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanelXaxis, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jLabelYaxis.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabelYaxis.setLabelFor(jPanelYaxInner);
jLabelYaxis.setText("Y-axis:"); // NOI18N
jPanelYmax.setLayout(new javax.swing.BoxLayout(jPanelYmax, javax.swing.BoxLayout.LINE_AXIS));
jTextFieldYmax.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
jTextFieldYmax.setText("-999"); // NOI18N
jTextFieldYmax.setName("Ymax"); // NOI18N
jTextFieldYmax.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextFieldYmaxActionPerformed(evt);
}
});
jTextFieldYmax.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextFieldYmaxFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jTextFieldYmaxFocusLost(evt);
}
});
jTextFieldYmax.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jTextFieldYmaxKeyReleased(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextFieldYmaxKeyTyped(evt);
}
});
jPanelYmax.add(jTextFieldYmax);
jPanelYaxInner.setLayout(new java.awt.CardLayout());
jComboBoxYaxType.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "jComboBoxYaxType", "Item 2", "Item 3", "Item 4" }));
jComboBoxYaxType.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBoxYaxTypeActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanelYcomboLayout = new javax.swing.GroupLayout(jPanelYcombo);
jPanelYcombo.setLayout(jPanelYcomboLayout);
jPanelYcomboLayout.setHorizontalGroup(
jPanelYcomboLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jComboBoxYaxType, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanelYcomboLayout.setVerticalGroup(
jPanelYcomboLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelYcomboLayout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jComboBoxYaxType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanelYaxInner.add(jPanelYcombo, "cardYcombo");
jLabelYlogC.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabelYlogC.setText("log Concs."); // NOI18N
javax.swing.GroupLayout jPanelYlogCLayout = new javax.swing.GroupLayout(jPanelYlogC);
jPanelYlogC.setLayout(jPanelYlogCLayout);
jPanelYlogCLayout.setHorizontalGroup(
jPanelYlogCLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelYlogCLayout.createSequentialGroup()
.addGap(50, 50, 50)
.addComponent(jLabelYlogC)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelYlogCLayout.setVerticalGroup(
jPanelYlogCLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelYlogCLayout.createSequentialGroup()
.addComponent(jLabelYlogC)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelYaxInner.add(jPanelYlogC, "cardYlogC");
jLabelYlogA.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabelYlogA.setText("log Activities"); // NOI18N
javax.swing.GroupLayout jPanelYlogALayout = new javax.swing.GroupLayout(jPanelYlogA);
jPanelYlogA.setLayout(jPanelYlogALayout);
jPanelYlogALayout.setHorizontalGroup(
jPanelYlogALayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelYlogALayout.createSequentialGroup()
.addGap(50, 50, 50)
.addComponent(jLabelYlogA)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelYlogALayout.setVerticalGroup(
jPanelYlogALayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelYlogALayout.createSequentialGroup()
.addComponent(jLabelYlogA)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelYaxInner.add(jPanelYlogA, "cardYlogA");
jLabelYlogS.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabelYlogS.setText("log Solubilities"); // NOI18N
javax.swing.GroupLayout jPanelYlogSLayout = new javax.swing.GroupLayout(jPanelYlogS);
jPanelYlogS.setLayout(jPanelYlogSLayout);
jPanelYlogSLayout.setHorizontalGroup(
jPanelYlogSLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelYlogSLayout.createSequentialGroup()
.addGap(50, 50, 50)
.addComponent(jLabelYlogS)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelYlogSLayout.setVerticalGroup(
jPanelYlogSLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelYlogSLayout.createSequentialGroup()
.addComponent(jLabelYlogS)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelYaxInner.add(jPanelYlogS, "cardYlogS");
jLabelYRef.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabelYRef.setText("log {i}/{ref}, ref="); // NOI18N
javax.swing.GroupLayout jPanelYRefLayout = new javax.swing.GroupLayout(jPanelYRef);
jPanelYRef.setLayout(jPanelYRefLayout);
jPanelYRefLayout.setHorizontalGroup(
jPanelYRefLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelYRefLayout.createSequentialGroup()
.addComponent(jLabelYRef)
.addGap(0, 59, Short.MAX_VALUE))
);
jPanelYRefLayout.setVerticalGroup(
jPanelYRefLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelYRef, javax.swing.GroupLayout.DEFAULT_SIZE, 21, Short.MAX_VALUE)
);
jPanelYaxInner.add(jPanelYRef, "cardYRef");
jLabelYFract.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabelYFract.setText("Fraction for:"); // NOI18N
javax.swing.GroupLayout jPanelYfractionLayout = new javax.swing.GroupLayout(jPanelYfraction);
jPanelYfraction.setLayout(jPanelYfractionLayout);
jPanelYfractionLayout.setHorizontalGroup(
jPanelYfractionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelYfractionLayout.createSequentialGroup()
.addComponent(jLabelYFract)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelYfractionLayout.setVerticalGroup(
jPanelYfractionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelYFract, javax.swing.GroupLayout.DEFAULT_SIZE, 21, Short.MAX_VALUE)
);
jPanelYaxInner.add(jPanelYfraction, "cardYFract");
jLabelYcalc.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabelYcalc.setText("calculated Eh"); // NOI18N
javax.swing.GroupLayout jPanelYcalcLayout = new javax.swing.GroupLayout(jPanelYcalc);
jPanelYcalc.setLayout(jPanelYcalcLayout);
jPanelYcalcLayout.setHorizontalGroup(
jPanelYcalcLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelYcalcLayout.createSequentialGroup()
.addGap(50, 50, 50)
.addComponent(jLabelYcalc)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelYcalcLayout.setVerticalGroup(
jPanelYcalcLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelYcalcLayout.createSequentialGroup()
.addComponent(jLabelYcalc)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelYaxInner.add(jPanelYcalc, "cardYcalc");
jLabelHaff.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabelHaff.setText("d(H-h) / d(-pH)"); // NOI18N
javax.swing.GroupLayout jPanelYHaffLayout = new javax.swing.GroupLayout(jPanelYHaff);
jPanelYHaff.setLayout(jPanelYHaffLayout);
jPanelYHaffLayout.setHorizontalGroup(
jPanelYHaffLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelYHaffLayout.createSequentialGroup()
.addGap(50, 50, 50)
.addComponent(jLabelHaff)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelYHaffLayout.setVerticalGroup(
jPanelYHaffLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelYHaffLayout.createSequentialGroup()
.addComponent(jLabelHaff)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelYaxInner.add(jPanelYHaff, "cardYHaff");
jPanelYaxComp.setPreferredSize(new java.awt.Dimension(132, 33));
jPanelYaxComp.setLayout(new java.awt.CardLayout());
jComboBoxYaxComp.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "jComboBxYaxC", "Item 2", "Item 3", "Item 4" }));
jComboBoxYaxComp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBoxYaxCompActionPerformed(evt);
}
});
jPanelYaxComp.add(jComboBoxYaxComp, "cardYaxComp1");
javax.swing.GroupLayout jPanelEmptyYaxLayout = new javax.swing.GroupLayout(jPanelEmptyYax);
jPanelEmptyYax.setLayout(jPanelEmptyYaxLayout);
jPanelEmptyYaxLayout.setHorizontalGroup(
jPanelEmptyYaxLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 161, Short.MAX_VALUE)
);
jPanelEmptyYaxLayout.setVerticalGroup(
jPanelEmptyYaxLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 25, Short.MAX_VALUE)
);
jPanelYaxComp.add(jPanelEmptyYax, "cardYaxComp0");
jPanelYmin.setLayout(new javax.swing.BoxLayout(jPanelYmin, javax.swing.BoxLayout.LINE_AXIS));
jTextFieldYmin.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
jTextFieldYmin.setText("-999"); // NOI18N
jTextFieldYmin.setName("Ymin"); // NOI18N
jTextFieldYmin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextFieldYminActionPerformed(evt);
}
});
jTextFieldYmin.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextFieldYminFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jTextFieldYminFocusLost(evt);
}
});
jTextFieldYmin.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jTextFieldYminKeyReleased(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextFieldYminKeyTyped(evt);
}
});
jPanelYmin.add(jTextFieldYmin);
javax.swing.GroupLayout jPanelYaxisLayout = new javax.swing.GroupLayout(jPanelYaxis);
jPanelYaxis.setLayout(jPanelYaxisLayout);
jPanelYaxisLayout.setHorizontalGroup(
jPanelYaxisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelYaxisLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanelYaxisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelYaxisLayout.createSequentialGroup()
.addComponent(jLabelYaxis)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanelYmax, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jPanelYmin, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanelYaxisLayout.createSequentialGroup()
.addGroup(jPanelYaxisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jPanelYaxComp, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanelYaxInner, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())))
);
jPanelYaxisLayout.setVerticalGroup(
jPanelYaxisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelYaxisLayout.createSequentialGroup()
.addGroup(jPanelYaxisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelYaxis)
.addComponent(jPanelYmax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanelYaxInner, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(5, 5, 5)
.addComponent(jPanelYaxComp, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanelYmin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0))
);
jLabelXaxis.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabelXaxis.setLabelFor(jComboBoxXaxType);
jLabelXaxis.setText("X-axis:"); // NOI18N
jComboBoxXaxType.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "jComboBoxXaxType", "Item 2", "Item 3", "Item 4" }));
jComboBoxXaxType.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBoxXaxTypeActionPerformed(evt);
}
});
jComboBoxXaxComp.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2" }));
jComboBoxXaxComp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBoxXaxCompActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanelXComponentLayout = new javax.swing.GroupLayout(jPanelXComponent);
jPanelXComponent.setLayout(jPanelXComponentLayout);
jPanelXComponentLayout.setHorizontalGroup(
jPanelXComponentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelXComponentLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabelXaxis)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelXComponentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBoxXaxComp, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBoxXaxType, 0, 156, Short.MAX_VALUE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelXComponentLayout.setVerticalGroup(
jPanelXComponentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelXComponentLayout.createSequentialGroup()
.addGroup(jPanelXComponentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelXaxis)
.addComponent(jComboBoxXaxType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBoxXaxComp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(3, 3, 3))
);
jPanelEmptyDiagram.setMinimumSize(new java.awt.Dimension(94, 50));
jPanelEmptyDiagram.setPreferredSize(new java.awt.Dimension(94, 50));
javax.swing.GroupLayout jPanelEmptyDiagramLayout = new javax.swing.GroupLayout(jPanelEmptyDiagram);
jPanelEmptyDiagram.setLayout(jPanelEmptyDiagramLayout);
jPanelEmptyDiagramLayout.setHorizontalGroup(
jPanelEmptyDiagramLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 94, Short.MAX_VALUE)
);
jPanelEmptyDiagramLayout.setVerticalGroup(
jPanelEmptyDiagramLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 50, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanelDiagramLayout = new javax.swing.GroupLayout(jPanelDiagram);
jPanelDiagram.setLayout(jPanelDiagramLayout);
jPanelDiagramLayout.setHorizontalGroup(
jPanelDiagramLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelDiagramLayout.createSequentialGroup()
.addGroup(jPanelDiagramLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelDiagramLayout.createSequentialGroup()
.addGap(129, 129, 129)
.addComponent(jPanelTitle, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanelDiagramLayout.createSequentialGroup()
.addComponent(jPanelEmptyDiagram, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(40, 40, 40)
.addComponent(jPanelXComponent, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanelDiagramLayout.createSequentialGroup()
.addComponent(jPanelYaxis, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanelDiagrType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
jPanelDiagramLayout.setVerticalGroup(
jPanelDiagramLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelDiagramLayout.createSequentialGroup()
.addComponent(jPanelTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelDiagramLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanelDiagrType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanelYaxis, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(6, 6, 6)
.addGroup(jPanelDiagramLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanelEmptyDiagram, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanelXComponent, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(14, Short.MAX_VALUE))
);
jPanelParams.setBorder(javax.swing.BorderFactory.createTitledBorder(null, " Parameters: ", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12), new java.awt.Color(153, 0, 153))); // NOI18N
jLabelIS.setText("Ionic strength: ");
buttonGroupActCoef.add(jRadioButtonFixed);
jRadioButtonFixed.setSelected(true);
jRadioButtonFixed.setText("fixed");
jRadioButtonFixed.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonFixedActionPerformed(evt);
}
});
buttonGroupActCoef.add(jRadioButtonCalc);
jRadioButtonCalc.setText("calculated");
jRadioButtonCalc.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonCalcActionPerformed(evt);
}
});
jLabelIonicS.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jLabelIonicS.setLabelFor(jTextFieldIonicStr);
jLabelIonicS.setText("<html><u>I</u> = </html>"); // NOI18N
jLabelIonicS.setToolTipText("Ionic strength =");
jTextFieldIonicStr.setText("0.0"); // NOI18N
jTextFieldIonicStr.setToolTipText("ionic strength value");
jTextFieldIonicStr.setName("IonicStr"); // NOI18N
jTextFieldIonicStr.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextFieldIonicStrFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jTextFieldIonicStrFocusLost(evt);
}
});
jTextFieldIonicStr.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextFieldIonicStrActionPerformed(evt);
}
});
jTextFieldIonicStr.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTextFieldIonicStrKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextFieldIonicStrKeyTyped(evt);
}
});
jLabelM.setText("<html>mol/(kg H<sub>2</sub>O)</html>"); // NOI18N
jLabelT.setLabelFor(jTextFieldT);
jLabelT.setText("t ="); // NOI18N
jLabelT.setToolTipText("Temperature =");
jLabelT.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabelTMouseClicked(evt);
}
});
jTextFieldT.setText("25"); // NOI18N
jTextFieldT.setToolTipText("temperature");
jTextFieldT.setName("T"); // NOI18N
jTextFieldT.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextFieldTFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jTextFieldTFocusLost(evt);
}
});
jTextFieldT.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextFieldTActionPerformed(evt);
}
});
jTextFieldT.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTextFieldTKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextFieldTKeyTyped(evt);
}
});
jLabelTC.setText("°C"); // NOI18N
jPanelModel.setMinimumSize(new java.awt.Dimension(220, 136));
jPanelModel.setPreferredSize(new java.awt.Dimension(220, 136));
jLabelModel.setLabelFor(jComboBoxActCoeff);
jLabelModel.setText("<html><u>A</u>ctivity coefficient model:</html>"); // NOI18N
jComboBoxActCoeff.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Davies eqn.", "SIT (Specific Ion-interaction)", "simpl. Helgeson-Krikham-Flowers" }));
jComboBoxActCoeff.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBoxActCoeffActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanelModelLayout = new javax.swing.GroupLayout(jPanelModel);
jPanelModel.setLayout(jPanelModelLayout);
jPanelModelLayout.setHorizontalGroup(
jPanelModelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelModelLayout.createSequentialGroup()
.addGap(5, 5, 5)
.addGroup(jPanelModelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jComboBoxActCoeff, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanelModelLayout.createSequentialGroup()
.addComponent(jLabelModel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())))
);
jPanelModelLayout.setVerticalGroup(
jPanelModelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelModelLayout.createSequentialGroup()
.addComponent(jLabelModel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBoxActCoeff, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanelActCoefLayout = new javax.swing.GroupLayout(jPanelActCoef);
jPanelActCoef.setLayout(jPanelActCoefLayout);
jPanelActCoefLayout.setHorizontalGroup(
jPanelActCoefLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelActCoefLayout.createSequentialGroup()
.addGroup(jPanelActCoefLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelActCoefLayout.createSequentialGroup()
.addGap(5, 5, 5)
.addGroup(jPanelActCoefLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelActCoefLayout.createSequentialGroup()
.addComponent(jLabelIS)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jRadioButtonFixed)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jRadioButtonCalc))
.addGroup(jPanelActCoefLayout.createSequentialGroup()
.addGroup(jPanelActCoefLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelIonicS, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelT, javax.swing.GroupLayout.Alignment.TRAILING))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanelActCoefLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelActCoefLayout.createSequentialGroup()
.addComponent(jTextFieldT, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelTC))
.addGroup(jPanelActCoefLayout.createSequentialGroup()
.addComponent(jTextFieldIonicStr, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelM, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jPanelModel, javax.swing.GroupLayout.DEFAULT_SIZE, 229, Short.MAX_VALUE))
.addGap(4, 4, 4))
);
jPanelActCoefLayout.setVerticalGroup(
jPanelActCoefLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelActCoefLayout.createSequentialGroup()
.addGroup(jPanelActCoefLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelIS)
.addComponent(jRadioButtonFixed)
.addComponent(jRadioButtonCalc))
.addGap(6, 6, 6)
.addGroup(jPanelActCoefLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextFieldIonicStr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelM, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelIonicS, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelActCoefLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextFieldT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelTC)
.addComponent(jLabelT))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanelModel, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jPanelSedPredom.setPreferredSize(new java.awt.Dimension(230, 104));
jPanelSedPredom.setLayout(new java.awt.CardLayout());
jLabelPredNbr.setText("<html>Nbr. of calc. steps in each axis:</html>"); // NOI18N
jLabelPredNbrP.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabelPredNbrP.setLabelFor(jScrollBarPredNbrP);
jLabelPredNbrP.setText("50"); // NOI18N
jLabelPredNbrP.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabelPredNbrPMouseClicked(evt);
}
});
jScrollBarPredNbrP.setMaximum(spana.MainFrame.MXSTP+1);
jScrollBarPredNbrP.setMinimum(spana.MainFrame.MNSTP);
jScrollBarPredNbrP.setOrientation(javax.swing.JScrollBar.HORIZONTAL);
jScrollBarPredNbrP.setVisibleAmount(1);
jScrollBarPredNbrP.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jScrollBarPredNbrP.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jScrollBarPredNbrPFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jScrollBarPredNbrPFocusLost(evt);
}
});
jScrollBarPredNbrP.addAdjustmentListener(new java.awt.event.AdjustmentListener() {
public void adjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {
jScrollBarPredNbrPAdjustmentValueChanged(evt);
}
});
jPanelTotCalcs.setBackground(new java.awt.Color(226, 225, 225));
jPanelTotCalcs.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabelTotNbr.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabelTotNbr.setText("<html><center>Total number<br>of calculations<br>in Predom:</center></html>"); // NOI18N
jLabelNbrCalcs.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabelNbrCalcs.setText("2500"); // NOI18N
javax.swing.GroupLayout jPanelTotCalcsLayout = new javax.swing.GroupLayout(jPanelTotCalcs);
jPanelTotCalcs.setLayout(jPanelTotCalcsLayout);
jPanelTotCalcsLayout.setHorizontalGroup(
jPanelTotCalcsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelTotNbr, javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanelTotCalcsLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabelNbrCalcs, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jPanelTotCalcsLayout.setVerticalGroup(
jPanelTotCalcsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelTotCalcsLayout.createSequentialGroup()
.addComponent(jLabelTotNbr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jLabelNbrCalcs)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jCheckBoxAqu.setMnemonic('w');
jCheckBoxAqu.setText("<html>sho<u>w</u> only aqueous species</html>"); // NOI18N
jCheckBoxAqu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxAquActionPerformed(evt);
}
});
jCheckBoxDrawPHline.setMnemonic('L');
jCheckBoxDrawPHline.setText("draw neutral pH line");
jCheckBoxDrawPHline.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxDrawPHlineActionPerformed(evt);
}
});
jLabelSpaceP.setText(" ");
javax.swing.GroupLayout jPanelPredomLayout = new javax.swing.GroupLayout(jPanelPredom);
jPanelPredom.setLayout(jPanelPredomLayout);
jPanelPredomLayout.setHorizontalGroup(
jPanelPredomLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelPredomLayout.createSequentialGroup()
.addGroup(jPanelPredomLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jCheckBoxAqu)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanelPredomLayout.createSequentialGroup()
.addComponent(jCheckBoxDrawPHline, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabelSpaceP)
.addGap(0, 24, Short.MAX_VALUE))
.addGroup(jPanelPredomLayout.createSequentialGroup()
.addGroup(jPanelPredomLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelPredomLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollBarPredNbrP, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanelPredomLayout.createSequentialGroup()
.addGap(49, 49, 49)
.addComponent(jLabelPredNbrP, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanelPredomLayout.createSequentialGroup()
.addGap(5, 5, 5)
.addComponent(jLabelPredNbr, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanelTotCalcs, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGap(4, 4, 4))
);
jPanelPredomLayout.setVerticalGroup(
jPanelPredomLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelPredomLayout.createSequentialGroup()
.addGroup(jPanelPredomLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanelPredomLayout.createSequentialGroup()
.addComponent(jLabelPredNbr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(4, 4, 4)
.addComponent(jLabelPredNbrP)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollBarPredNbrP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanelTotCalcs, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jCheckBoxAqu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelPredomLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jCheckBoxDrawPHline)
.addComponent(jLabelSpaceP)))
);
jPanelSedPredom.add(jPanelPredom, "Predom");
jCheckBoxTableOut.setMnemonic('T');
jCheckBoxTableOut.setText("<html>write a file with <u>t</u>able of results</html>"); // NOI18N
jCheckBoxTableOut.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxTableOutActionPerformed(evt);
}
});
jLabelSEDNbr.setText("Number of calculation steps:"); // NOI18N
jLabelSEDNbrP.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabelSEDNbrP.setLabelFor(jScrollBarSEDNbrP);
jLabelSEDNbrP.setText("50"); // NOI18N
jLabelSEDNbrP.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabelSEDNbrPMouseClicked(evt);
}
});
jScrollBarSEDNbrP.setMaximum(spana.MainFrame.MXSTP+1);
jScrollBarSEDNbrP.setMinimum(spana.MainFrame.MNSTP);
jScrollBarSEDNbrP.setOrientation(javax.swing.JScrollBar.HORIZONTAL);
jScrollBarSEDNbrP.setVisibleAmount(1);
jScrollBarSEDNbrP.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jScrollBarSEDNbrP.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jScrollBarSEDNbrPFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jScrollBarSEDNbrPFocusLost(evt);
}
});
jScrollBarSEDNbrP.addAdjustmentListener(new java.awt.event.AdjustmentListener() {
public void adjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {
jScrollBarSEDNbrPAdjustmentValueChanged(evt);
}
});
javax.swing.GroupLayout jPanelSEDLayout = new javax.swing.GroupLayout(jPanelSED);
jPanelSED.setLayout(jPanelSEDLayout);
jPanelSEDLayout.setHorizontalGroup(
jPanelSEDLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelSEDLayout.createSequentialGroup()
.addGap(39, 39, 39)
.addComponent(jLabelSEDNbrP, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE)
.addGap(123, 123, 123))
.addGroup(jPanelSEDLayout.createSequentialGroup()
.addGroup(jPanelSEDLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jCheckBoxTableOut, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanelSEDLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabelSEDNbr))
.addGroup(jPanelSEDLayout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jScrollBarSEDNbrP, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelSEDLayout.setVerticalGroup(
jPanelSEDLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelSEDLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jCheckBoxTableOut, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabelSEDNbr)
.addGap(2, 2, 2)
.addComponent(jLabelSEDNbrP)
.addGap(2, 2, 2)
.addComponent(jScrollBarSEDNbrP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(33, Short.MAX_VALUE))
);
jPanelSedPredom.add(jPanelSED, "SED");
javax.swing.GroupLayout jPanelEmptyParametersLayout = new javax.swing.GroupLayout(jPanelEmptyParameters);
jPanelEmptyParameters.setLayout(jPanelEmptyParametersLayout);
jPanelEmptyParametersLayout.setHorizontalGroup(
jPanelEmptyParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 233, Short.MAX_VALUE)
);
jPanelEmptyParametersLayout.setVerticalGroup(
jPanelEmptyParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 118, Short.MAX_VALUE)
);
jPanelSedPredom.add(jPanelEmptyParameters, "Empty");
jCheckBoxRev.setMnemonic('R');
jCheckBoxRev.setText("<html>allow <u>r</u>eversed conc. ranges</html>"); // NOI18N
jCheckBoxRev.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxRevActionPerformed(evt);
}
});
jCheckBoxUseEh.setMnemonic('E');
jCheckBoxUseEh.setText("<html>use <u>E</u>h for e-</html>"); // NOI18N
jCheckBoxUseEh.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxUseEhActionPerformed(evt);
}
});
jLabelSpace.setText(" ");
javax.swing.GroupLayout jPanelLowLayout = new javax.swing.GroupLayout(jPanelLow);
jPanelLow.setLayout(jPanelLowLayout);
jPanelLowLayout.setHorizontalGroup(
jPanelLowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelLowLayout.createSequentialGroup()
.addGroup(jPanelLowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelLowLayout.createSequentialGroup()
.addComponent(jCheckBoxUseEh, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabelSpace))
.addComponent(jCheckBoxRev, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelLowLayout.setVerticalGroup(
jPanelLowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelLowLayout.createSequentialGroup()
.addComponent(jCheckBoxRev, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelLowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jCheckBoxUseEh, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelSpace)))
);
jButtonSaveDef.setMnemonic('S');
jButtonSaveDef.setText("<html><u>S</u>ave as defaults</html>"); // NOI18N
jButtonSaveDef.setMargin(new java.awt.Insets(0, 2, 0, 2));
jButtonSaveDef.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonSaveDefActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanelParamsLayout = new javax.swing.GroupLayout(jPanelParams);
jPanelParams.setLayout(jPanelParamsLayout);
jPanelParamsLayout.setHorizontalGroup(
jPanelParamsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelParamsLayout.createSequentialGroup()
.addGroup(jPanelParamsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelParamsLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jButtonSaveDef, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanelParamsLayout.createSequentialGroup()
.addGap(3, 3, 3)
.addGroup(jPanelParamsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jPanelSedPredom, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanelActCoef, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanelLow, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(4, 4, 4))
);
jPanelParamsLayout.setVerticalGroup(
jPanelParamsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelParamsLayout.createSequentialGroup()
.addComponent(jPanelActCoef, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanelSedPredom, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jPanelLow, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButtonSaveDef, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelConcs.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Concentrations:", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12), new java.awt.Color(153, 0, 153))); // NOI18N
jPanelConcs.setMinimumSize(new java.awt.Dimension(396, 156));
jPanelConcs.setLayout(new java.awt.CardLayout());
jScrollPaneCompConcList.setMinimumSize(new java.awt.Dimension(260, 132));
jListCompConc.setModel(listCompConcModel);
jListCompConc.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jListCompConc.setToolTipText("Click on a line or press F2 to edit concentration"); // NOI18N
jListCompConc.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jListCompConcMouseClicked(evt);
}
});
jListCompConc.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jListCompConcFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jListCompConcFocusLost(evt);
}
});
jListCompConc.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
jListCompConcKeyTyped(evt);
}
});
jScrollPaneCompConcList.setViewportView(jListCompConc);
jPanelConcs.add(jScrollPaneCompConcList, "panelCompConcList");
jPanelGetConc.setMinimumSize(new java.awt.Dimension(260, 132));
jPanelGetConc.setPreferredSize(new java.awt.Dimension(260, 132));
jLabelEnterConc.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabelEnterConc.setText("Enter concentration for component:"); // NOI18N
jLabel_GetConcCompName.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel_GetConcCompName.setText("SO4-2"); // NOI18N
jComboBoxConcType.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "jComboBoxConcType", "Item 2", "Item 3", "Item 4" }));
jComboBoxConcType.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBoxConcTypeActionPerformed(evt);
}
});
jLabelEqual.setText("="); // NOI18N
jLabelFrom.setText("from:"); // NOI18N
jTextFieldCLow.setText("jTextFieldCLow"); // NOI18N
jTextFieldCLow.setName("CLow"); // NOI18N
jTextFieldCLow.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextFieldCLowFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jTextFieldCLowFocusLost(evt);
}
});
jTextFieldCLow.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextFieldCLowActionPerformed(evt);
}
});
jTextFieldCLow.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTextFieldCLowKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextFieldCLowKeyTyped(evt);
}
});
jLabelTo.setText("to:"); // NOI18N
jTextFieldCHigh.setText("jTextFieldCHigh"); // NOI18N
jTextFieldCHigh.setName("CHigh"); // NOI18N
jTextFieldCHigh.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextFieldCHighActionPerformed(evt);
}
});
jTextFieldCHigh.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextFieldCHighFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jTextFieldCHighFocusLost(evt);
}
});
jTextFieldCHigh.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTextFieldCHighKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextFieldCHighKeyTyped(evt);
}
});
javax.swing.GroupLayout jPanelConcInnerLayout = new javax.swing.GroupLayout(jPanelConcInner);
jPanelConcInner.setLayout(jPanelConcInnerLayout);
jPanelConcInnerLayout.setHorizontalGroup(
jPanelConcInnerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelConcInnerLayout.createSequentialGroup()
.addGroup(jPanelConcInnerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanelConcInnerLayout.createSequentialGroup()
.addComponent(jComboBoxConcType, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelEqual))
.addGroup(jPanelConcInnerLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel_GetConcCompName, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelConcInnerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextFieldCLow, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelFrom))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelConcInnerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelTo)
.addComponent(jTextFieldCHigh, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelConcInnerLayout.setVerticalGroup(
jPanelConcInnerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelConcInnerLayout.createSequentialGroup()
.addGroup(jPanelConcInnerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel_GetConcCompName)
.addComponent(jLabelFrom)
.addComponent(jLabelTo))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelConcInnerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jComboBoxConcType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelEqual)
.addComponent(jTextFieldCLow, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextFieldCHigh, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
jButtonGetConcOK.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButtonGetConcOK.setMnemonic('O');
jButtonGetConcOK.setText("<html><u>O</u>K</html>"); // NOI18N
jButtonGetConcOK.setToolTipText("Alt-O"); // NOI18N
jButtonGetConcOK.setMargin(new java.awt.Insets(2, 10, 2, 10));
jButtonGetConcOK.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonGetConcOKActionPerformed(evt);
}
});
jButtonGetConcCancel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButtonGetConcCancel.setMnemonic('C');
jButtonGetConcCancel.setText("<html><u>C</u>ancel</html>"); // NOI18N
jButtonGetConcCancel.setToolTipText("Alt-C"); // NOI18N
jButtonGetConcCancel.setMargin(new java.awt.Insets(2, 2, 2, 2));
jButtonGetConcCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonGetConcCancelActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanelGetConcLayout = new javax.swing.GroupLayout(jPanelGetConc);
jPanelGetConc.setLayout(jPanelGetConcLayout);
jPanelGetConcLayout.setHorizontalGroup(
jPanelGetConcLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelGetConcLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelGetConcLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jPanelConcInner, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanelGetConcLayout.createSequentialGroup()
.addComponent(jLabelEnterConc)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButtonGetConcOK, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButtonGetConcCancel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
jPanelGetConcLayout.setVerticalGroup(
jPanelGetConcLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelGetConcLayout.createSequentialGroup()
.addGroup(jPanelGetConcLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonGetConcOK, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButtonGetConcCancel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelEnterConc))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanelConcInner, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jPanelConcs.add(jPanelGetConc, "panelGetConc");
jLabl1.setText("jLabl1"); // NOI18N
jLabl2.setText("jLabl2"); // NOI18N
jLabl3.setText("jLabl3"); // NOI18N
jLabl4.setText("jLabl4"); // NOI18N
javax.swing.GroupLayout jPanelLablLayout = new javax.swing.GroupLayout(jPanelLabl);
jPanelLabl.setLayout(jPanelLablLayout);
jPanelLablLayout.setHorizontalGroup(
jPanelLablLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelLablLayout.createSequentialGroup()
.addGroup(jPanelLablLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabl2)
.addComponent(jLabl3)
.addComponent(jLabl4)
.addComponent(jLabl1))
.addGap(356, 356, 356))
);
jPanelLablLayout.setVerticalGroup(
jPanelLablLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelLablLayout.createSequentialGroup()
.addComponent(jLabl1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabl2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabl3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabl4)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelConcs.add(jPanelLabl, "panelJLabl");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(1, 1, 1)
.addComponent(jPanelButtons, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanelFileNames, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanelConcs, 0, 0, Short.MAX_VALUE)
.addComponent(jPanelDiagram, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanelParams, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanelFileNames, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanelButtons, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanelDiagram, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanelConcs, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
.addComponent(jPanelParams, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
pack();
}// </editor-fold>//GEN-END:initComponents
//<editor-fold defaultstate="collapsed" desc="Events">
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
quitFrame();
}//GEN-LAST:event_formWindowClosing
private void jButton_OKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_OKActionPerformed
// --- this will call "runSedPredom()"
cancel = true;
double w = readTextField(jTextFieldXmax);
String t = Util.formatNum(w);
if(Double.parseDouble(t) != w) {jTextFieldXmax.setText(t);}
w = readTextField(jTextFieldXmin);
t = Util.formatNum(w);
if(Double.parseDouble(t) != w) {jTextFieldXmin.setText(t);}
w = readTextField(jTextFieldYmax);
t = Util.formatNum(w);
if(Double.parseDouble(t) != w) {jTextFieldYmax.setText(t);}
w = readTextField(jTextFieldYmin);
t = Util.formatNum(w);
if(Double.parseDouble(t) != w) {jTextFieldYmin.setText(t);}
updateConcs();
if(dataFile == null || dataFile.getPath().length() <=0) {
MsgExceptn.exception("Error in \"Select_Diagram\": the data file name is empty.");
} else {
setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
MainFrame.getInstance().setCursorWait();
if(checkChanges()) {
// make the calculations and draw the diagram
boolean ok = runSedPredom();
Thread wt = new Thread() {@Override public void run(){
try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec
catch (InterruptedException e) {}
}};//new Thread
wt.start();
if(ok) {cancel = false; quitFrame();}
} // if there was an error while saving the file(s): return
}
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
}//GEN-LAST:event_jButton_OKActionPerformed
private void jButton_CancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_CancelActionPerformed
cancel = true;
quitFrame();
}//GEN-LAST:event_jButton_CancelActionPerformed
private void jTextFieldDataFileFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldDataFileFocusGained
jTextFieldDataFile.selectAll();
}//GEN-LAST:event_jTextFieldDataFileFocusGained
private void jTextFieldDataFileKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldDataFileKeyPressed
if(!Util.isKeyPressedOK(evt)) {evt.consume();}
}//GEN-LAST:event_jTextFieldDataFileKeyPressed
private void jTextFieldDataFileKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldDataFileKeyTyped
char c = Character.toUpperCase(evt.getKeyChar());
if(evt.getKeyChar() != java.awt.event.KeyEvent.VK_ESCAPE &&
!(evt.isAltDown() && ((c == 'X') || (c == 'A') ||
(c == 'H') ||
(evt.getKeyChar() == java.awt.event.KeyEvent.VK_ENTER))
) //isAltDown
) { // if not ESC or Alt-something
evt.consume(); // remove the typed key
dataFile_Click();
} // if char ok
}//GEN-LAST:event_jTextFieldDataFileKeyTyped
private void jTextFieldDataFileMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFieldDataFileMouseClicked
dataFile_Click();
}//GEN-LAST:event_jTextFieldDataFileMouseClicked
private void jTextFieldDataFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldDataFileActionPerformed
dataFile_Click();
}//GEN-LAST:event_jTextFieldDataFileActionPerformed
private void jScrollBarPredNbrPFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jScrollBarPredNbrPFocusGained
jScrollBarPredNbrP.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0,0,0)));
}//GEN-LAST:event_jScrollBarPredNbrPFocusGained
private void jScrollBarPredNbrPFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jScrollBarPredNbrPFocusLost
jScrollBarPredNbrP.setBorder(scrollBorder);
}//GEN-LAST:event_jScrollBarPredNbrPFocusLost
private void jScrollBarSEDNbrPFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jScrollBarSEDNbrPFocusGained
jScrollBarSEDNbrP.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0,0,0)));
}//GEN-LAST:event_jScrollBarSEDNbrPFocusGained
private void jScrollBarSEDNbrPFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jScrollBarSEDNbrPFocusLost
jScrollBarSEDNbrP.setBorder(scrollBorder);
}//GEN-LAST:event_jScrollBarSEDNbrPFocusLost
private void jScrollBarPredNbrPAdjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {//GEN-FIRST:event_jScrollBarPredNbrPAdjustmentValueChanged
int nStep = (int)((float)jScrollBarPredNbrP.getValue()/1f);
jLabelPredNbrP.setText(String.valueOf(nStep));
jLabelNbrCalcs.setText(String.valueOf((nStep+1)*(nStep+1)));
}//GEN-LAST:event_jScrollBarPredNbrPAdjustmentValueChanged
private void jScrollBarSEDNbrPAdjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {//GEN-FIRST:event_jScrollBarSEDNbrPAdjustmentValueChanged
int nStep = (int)((float)jScrollBarSEDNbrP.getValue()/1f);
jLabelSEDNbrP.setText(String.valueOf(nStep));
}//GEN-LAST:event_jScrollBarSEDNbrPAdjustmentValueChanged
private void jCheckBoxAquActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxAquActionPerformed
runAqu = jCheckBoxAqu.isSelected();
}//GEN-LAST:event_jCheckBoxAquActionPerformed
private void jCheckBoxRevActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxRevActionPerformed
runRevs = jCheckBoxRev.isSelected();
}//GEN-LAST:event_jCheckBoxRevActionPerformed
private void jTextFieldIonicStrFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldIonicStrFocusLost
validateIonicStrength();
}//GEN-LAST:event_jTextFieldIonicStrFocusLost
private void jTextFieldIonicStrKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldIonicStrKeyPressed
if(evt.getKeyChar() == java.awt.event.KeyEvent.VK_ENTER) {
validateIonicStrength();}
}//GEN-LAST:event_jTextFieldIonicStrKeyPressed
private void jTextFieldIonicStrKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldIonicStrKeyTyped
char key = evt.getKeyChar();
if(!isCharOKforNumberInput(key)) {evt.consume();}
}//GEN-LAST:event_jTextFieldIonicStrKeyTyped
private void jTextFieldTKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldTKeyTyped
char key = evt.getKeyChar();
if(!isCharOKforNumberInput(key)) {evt.consume();}
}//GEN-LAST:event_jTextFieldTKeyTyped
private void jComboBoxDiagTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxDiagTypeActionPerformed
if(jComboBoxDiagType.getSelectedIndex() >=0) {
diagramType_Click();
}
}//GEN-LAST:event_jComboBoxDiagTypeActionPerformed
private void jTextFieldXminActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldXminActionPerformed
if(loading || updatingAxes) {return;}
focusLostXmin();
}//GEN-LAST:event_jTextFieldXminActionPerformed
private void jTextFieldXmaxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldXmaxActionPerformed
if(loading || updatingAxes) {return;}
focusLostXmax();
}//GEN-LAST:event_jTextFieldXmaxActionPerformed
private void jTextFieldYmaxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldYmaxActionPerformed
if(loading || updatingAxes) {return;}
focusLostYmax();
}//GEN-LAST:event_jTextFieldYmaxActionPerformed
private void jTextFieldXminKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldXminKeyTyped
char key = evt.getKeyChar();
if(!isCharOKforNumberInput(key)) {evt.consume();}
}//GEN-LAST:event_jTextFieldXminKeyTyped
private void jTextFieldXminFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldXminFocusLost
if(loading) {return;}
focusLostXmin();
}//GEN-LAST:event_jTextFieldXminFocusLost
private void jTextFieldXmaxFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldXmaxFocusLost
if(loading) {return;}
focusLostXmax();
}//GEN-LAST:event_jTextFieldXmaxFocusLost
private void jTextFieldYmaxFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldYmaxFocusLost
if(loading) {return;}
focusLostYmax();
}//GEN-LAST:event_jTextFieldYmaxFocusLost
private void jTextFieldXminFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldXminFocusGained
oldTextXmin = jTextFieldXmin.getText();
jTextFieldXmin.selectAll();
}//GEN-LAST:event_jTextFieldXminFocusGained
private void jTextFieldXmaxFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldXmaxFocusGained
oldTextXmax = jTextFieldXmax.getText();
jTextFieldXmax.selectAll();
}//GEN-LAST:event_jTextFieldXmaxFocusGained
private void jTextFieldYmaxFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldYmaxFocusGained
oldTextYmax = jTextFieldYmax.getText();
jTextFieldYmax.selectAll();
}//GEN-LAST:event_jTextFieldYmaxFocusGained
private void jComboBoxConcTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxConcTypeActionPerformed
if(getConcLoading) {return;}
getConc_ComboConcType_Click();
}//GEN-LAST:event_jComboBoxConcTypeActionPerformed
private void jTextFieldCLowKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldCLowKeyTyped
char key = evt.getKeyChar();
if(!isCharOKforNumberInput(key)) {evt.consume();}
}//GEN-LAST:event_jTextFieldCLowKeyTyped
private void jTextFieldCHighKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldCHighKeyTyped
char key = evt.getKeyChar();
if(evt.getKeyCode()==java.awt.event.KeyEvent.VK_ENTER) {jButtonGetConcOK.doClick(); evt.consume();}
else if(!isCharOKforNumberInput(key)) {evt.consume();}
}//GEN-LAST:event_jTextFieldCHighKeyTyped
private void jTextFieldDiagNameFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldDiagNameFocusGained
jTextFieldDiagName.selectAll();
}//GEN-LAST:event_jTextFieldDiagNameFocusGained
private void jListCompConcKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jListCompConcKeyTyped
char c = Character.toUpperCase(evt.getKeyChar());
if(evt.getKeyChar() != java.awt.event.KeyEvent.VK_ESCAPE &&
!(evt.isAltDown() && ((c == 'X') || (c == 'A') ||
(c == 'H') || (c == 'M') ||
(evt.getKeyChar() == java.awt.event.KeyEvent.VK_ENTER))
) //isAltDown
) { // if not ESC or Alt-something
evt.consume(); // remove the typed key
compConcList_Click(jListCompConc.getSelectedIndex());
} // if char ok
}//GEN-LAST:event_jListCompConcKeyTyped
private void jListCompConcMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListCompConcMouseClicked
java.awt.Point p = evt.getPoint();
int i = jListCompConc.locationToIndex(p);
if(i>=0) {
java.awt.Rectangle r = jListCompConc.getCellBounds(i, i);
if(p.y < r.y || p.y > r.y+r.height) {return;}
jListCompConc.setSelectedIndex(i);
compConcList_Click(i);
}
}//GEN-LAST:event_jListCompConcMouseClicked
private void jListCompConcFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListCompConcFocusGained
if(jListCompConc.isFocusOwner()) {jScrollPaneCompConcList.setBorder(highlightedBorder);}
}//GEN-LAST:event_jListCompConcFocusGained
private void jListCompConcFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListCompConcFocusLost
if(!jListCompConc.isFocusOwner()) {jScrollPaneCompConcList.setBorder(defBorder);}
jListCompConc.clearSelection();
}//GEN-LAST:event_jListCompConcFocusLost
private void jButtonGetConcCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGetConcCancelActionPerformed
getConc_Unload();
}//GEN-LAST:event_jButtonGetConcCancelActionPerformed
private void jButtonGetConcOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGetConcOKActionPerformed
if(jComboBoxConcType.getSelectedItem().toString().startsWith("?")) {
MsgExceptn.exception("Programming error in \"jButtonGetConcOK\" - jComboBoxConcType = \"?...\"");
getConc_Unload(); return;
}
if(getConc_idx < 0) {getConc_Unload(); return;}
int use_pHpe = 0;
String concType = jComboBoxConcType.getSelectedItem().toString();
int jc = -1;
for(int j=0; j < concTypes.length; j++) {
if(concTypes[j].equals(concType)) {
jc = j+1;
if(j>=3) {
if(getConc_idx == hPresent) {use_pHpe =1;}
else if(getConc_idx == ePresent) {use_pHpe =2; if(runUseEh) {use_pHpe =3;}}
jc = j+1 - use_pHpe * 2;
if(j == 11) {jc = 4;} // "log P"
if(j == 12) {jc = 5;} // "log P varied"
} //if j>4
dgrC.hur[getConc_idx] = jc;
break;
}
} //for j
if(jc < 0) {MsgExceptn.exception("Programming error in \"jButtonGetConcOK\" - jc<0"); getConc_Unload();}
double fEh = Double.NaN;
if(use_pHpe == 3) {
fEh = (MainFrame.Rgas * ln10 * (diag.temperature +273.15)) / MainFrame.Faraday;
}
double w;
w = readTextField(jTextFieldCLow);
if(use_pHpe ==1 || use_pHpe ==2) {w = -w;}
if(use_pHpe == 3) {w = -w / fEh;}
dgrC.cLow[getConc_idx] = w;
if(concType.toLowerCase().contains("varied")) {
w = readTextField(jTextFieldCHigh);
if(use_pHpe ==1 || use_pHpe ==2) {w = -w;}
if(use_pHpe == 3) {w = -w / fEh;}
dgrC.cHigh[getConc_idx] = w;
} //if varied
getConc_Unload();
}//GEN-LAST:event_jButtonGetConcOKActionPerformed
private void jTextFieldIonicStrActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldIonicStrActionPerformed
validateIonicStrength();
}//GEN-LAST:event_jTextFieldIonicStrActionPerformed
private void jTextFieldTActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldTActionPerformed
validateTemperature();
}//GEN-LAST:event_jTextFieldTActionPerformed
private void jTextFieldIonicStrFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldIonicStrFocusGained
oldTextI = jTextFieldIonicStr.getText();
jTextFieldIonicStr.selectAll();
}//GEN-LAST:event_jTextFieldIonicStrFocusGained
private void jTextFieldTFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldTFocusGained
oldTextT = jTextFieldT.getText();
jTextFieldT.selectAll();
}//GEN-LAST:event_jTextFieldTFocusGained
private void jTextFieldTKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldTKeyPressed
if(evt.getKeyChar() == java.awt.event.KeyEvent.VK_ENTER) {
validateTemperature();
}
}//GEN-LAST:event_jTextFieldTKeyPressed
private void jTextFieldTFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldTFocusLost
validateTemperature();
}//GEN-LAST:event_jTextFieldTFocusLost
private void jLabelSEDNbrPMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelSEDNbrPMouseClicked
jScrollBarSEDNbrP.setValue(MainFrame.NSTEPS_DEF);
}//GEN-LAST:event_jLabelSEDNbrPMouseClicked
private void jLabelPredNbrPMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelPredNbrPMouseClicked
jScrollBarPredNbrP.setValue(MainFrame.NSTEPS_DEF);
}//GEN-LAST:event_jLabelPredNbrPMouseClicked
private void jCheckBoxTableOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxTableOutActionPerformed
runTbl = jCheckBoxTableOut.isSelected();
}//GEN-LAST:event_jCheckBoxTableOutActionPerformed
private void jLabelTMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelTMouseClicked
if(jTextFieldT.isEnabled()) {jTextFieldT.setText("25");}
}//GEN-LAST:event_jLabelTMouseClicked
private void jCheckBoxUseEhActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxUseEhActionPerformed
if(pc.dbg) {System.out.println("jCheckBoxUseEh_Action_Performed");}
runUseEh = jCheckBoxUseEh.isSelected();
int oldDiagType = jComboBoxDiagType.getSelectedIndex();
String dt = jComboBoxDiagType.getSelectedItem().toString();
boolean old = diagramType_doNothing;
diagramType_doNothing = true;
if(runUseEh) {
// change "calculated pe" to "calculated Eh"
for(int j=0; j < jComboBoxDiagType.getItemCount(); j++) {
if(jComboBoxDiagType.getItemAt(j).toString().equalsIgnoreCase("calculated pe")) {
jComboBoxDiagType.removeItemAt(j);
jComboBoxDiagType.insertItemAt("Calculated Eh", j);
break;
}
} //for j
if(jLabelYcalc.getText().equalsIgnoreCase("calculated pe")) {
jLabelYcalc.setText("calculated Eh");
}
} else {
//change "calculated Eh" to "calculated pe"
for(int j=0; j < jComboBoxDiagType.getItemCount(); j++) {
if(jComboBoxDiagType.getItemAt(j).toString().equalsIgnoreCase("calculated Eh")) {
jComboBoxDiagType.removeItemAt(j);
jComboBoxDiagType.insertItemAt("Calculated pe", j);
break;
}
} //for j
if(jLabelYcalc.getText().equalsIgnoreCase("calculated Eh")) {
jLabelYcalc.setText("calculated pe");
}
} //if not selected
diagramType_doNothing = old;
if(oldDiagType >=0) {jComboBoxDiagType.setSelectedIndex(oldDiagType);}
if(dt.equalsIgnoreCase("calculated Eh")) {
double fEh = (MainFrame.Rgas * ln10 * (diag.temperature +273.15)) / MainFrame.Faraday;
double w1 = readTextField(jTextFieldYmin);
double w2 = readTextField(jTextFieldYmax);
if(runUseEh) { // change "calculated pe" to "calculated Eh"
w1 = -w1 *fEh; w2 = -w2 *fEh;
} else { // change "calculated Eh" to "calculated pe"
w1 = -w1 /fEh; w2 = -w2 /fEh;
}
jTextFieldYmin.setText(Util.formatDbl3(Math.round(w1)));
jTextFieldYmax.setText(Util.formatDbl3(Math.round(w2)));
resizeYMin(); resizeYMax();
}
enableTemperature();
updateAxes();
resizeXMinMax(); resizeYMin(); resizeYMin();
updateConcList();
}//GEN-LAST:event_jCheckBoxUseEhActionPerformed
private void jButtonSaveDefActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSaveDefActionPerformed
pd.SED_nbrSteps = (int)((float)jScrollBarSEDNbrP.getValue()/1f);
pd.Predom_nbrSteps = (int)((float)jScrollBarPredNbrP.getValue()/1f);
pd.SED_tableOutput = jCheckBoxTableOut.isSelected();
pd.ionicStrength = diag.ionicStrength;
if(jTextFieldT.isEnabled()) {pd.temperature = diag.temperature;}
pd.pressure = diag.pressure;
pd.aquSpeciesOnly = jCheckBoxAqu.isSelected();
pd.reversedConcs = jCheckBoxRev.isSelected();
pd.drawNeutralPHinPourbaix = jCheckBoxDrawPHline.isSelected();
pd.useEh = jCheckBoxUseEh.isSelected();
pd.actCoeffsMethod = jComboBoxActCoeff.getSelectedIndex();
}//GEN-LAST:event_jButtonSaveDefActionPerformed
private void jTextFieldTitleFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldTitleFocusGained
jTextFieldTitle.selectAll();
}//GEN-LAST:event_jTextFieldTitleFocusGained
private void jButton_HelpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_HelpActionPerformed
setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
Thread hlp = new Thread() {@Override public void run(){
String[] a = {"S_Making_Diagrams_htm"};
lib.huvud.RunProgr.runProgramInProcess(Select_Diagram.this,ProgramConf.HELP_JAR,a,false,pc.dbg,pc.pathAPP);
try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec
catch (InterruptedException e) {}
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
}};//new Thread
hlp.start();
}//GEN-LAST:event_jButton_HelpActionPerformed
private void jTextFieldXmaxKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldXmaxKeyTyped
char key = evt.getKeyChar();
if(!isCharOKforNumberInput(key)) {evt.consume();}
}//GEN-LAST:event_jTextFieldXmaxKeyTyped
private void jTextFieldYmaxKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldYmaxKeyTyped
char key = evt.getKeyChar();
if(!isCharOKforNumberInput(key)) {evt.consume();}
}//GEN-LAST:event_jTextFieldYmaxKeyTyped
private void jComboBoxActCoeffActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxActCoeffActionPerformed
runActCoeffsMethod = jComboBoxActCoeff.getSelectedIndex();
}//GEN-LAST:event_jComboBoxActCoeffActionPerformed
private void jTextFieldYminActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldYminActionPerformed
if(loading || updatingAxes) {return;}
focusLostYmin();
}//GEN-LAST:event_jTextFieldYminActionPerformed
private void jTextFieldYminFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldYminFocusGained
oldTextYmin = jTextFieldYmin.getText();
jTextFieldYmin.selectAll();
}//GEN-LAST:event_jTextFieldYminFocusGained
private void jTextFieldYminFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldYminFocusLost
if(loading) {return;}
focusLostYmin();
}//GEN-LAST:event_jTextFieldYminFocusLost
private void jTextFieldYminKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldYminKeyTyped
char key = evt.getKeyChar();
if(!isCharOKforNumberInput(key)) {evt.consume();}
}//GEN-LAST:event_jTextFieldYminKeyTyped
private void jTextFieldYminKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldYminKeyReleased
resizeYMin();
}//GEN-LAST:event_jTextFieldYminKeyReleased
private void jTextFieldYmaxKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldYmaxKeyReleased
resizeYMax();
}//GEN-LAST:event_jTextFieldYmaxKeyReleased
private void jTextFieldXminKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldXminKeyReleased
resizeXMinMax();
}//GEN-LAST:event_jTextFieldXminKeyReleased
private void jTextFieldXmaxKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldXmaxKeyReleased
resizeXMinMax();
}//GEN-LAST:event_jTextFieldXmaxKeyReleased
private void jComboBoxMainCompActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxMainCompActionPerformed
if(loading || updatingAxes) {return;}
if(pc.dbg) {System.out.println("jComboBoxMainComp_Action_Performed");}
// --- Get the new compMain
for(int ic = 0; ic < cs.Na; ic++) {
if(jComboBoxMainComp.getSelectedItem().toString().
equalsIgnoreCase(namn.identC[ic])) {diag.compMain = ic; break;}
} // for ic
// ---- if Main-component does not belong to an axis,
// set the concentration to not varied
if(diag.compMain != diag.compX && diag.compMain != diag.compY) {
if(dgrC.hur[diag.compMain] ==2 || dgrC.hur[diag.compMain] ==3 ||
dgrC.hur[diag.compMain] ==5) { //if "*V" (conc varied)
// set a concentration-type not varied
if(Util.isGas(namn.identC[diag.compMain])) {
dgrC.hur[diag.compMain] = 4; //"LA" = "log P"
} else { //not Gas
if(dgrC.hur[diag.compMain] ==2 || dgrC.hur[diag.compMain] ==3) { //"TV" or "LTV"
if(dgrC.hur[diag.compMain] ==3) { //"LTV"
dgrC.cLow[diag.compMain] = logToNoLog(dgrC.cLow[diag.compMain]);
dgrC.cHigh[diag.compMain] = logToNoLog(dgrC.cHigh[diag.compMain]);
} // "LTV"
dgrC.hur[diag.compMain] = 1; //"T"
} //if "TV" or "LTV"
else { //"LAV"
dgrC.hur[diag.compMain] = 4; //"LA"
} //"T"?
} //not Gas
} //if conc varied
} //if Main comp. not in axis (if Main != compX & Main != compY)
changingComp = true;
updateAxes();
changingComp = false;
updateUseEhCheckBox();
updateDrawPHlineBox();
enableTemperature();
}//GEN-LAST:event_jComboBoxMainCompActionPerformed
private void jComboBoxXaxTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxXaxTypeActionPerformed
if(loading || changingComp || updatingAxes) {return;}
if(pc.dbg) {System.out.println("jComboBoxXaxType_Action_performed");}
if(jPanelGetConc.isShowing()) {jButtonGetConcCancel.doClick();}
String xAxisType = jComboBoxXaxType.getSelectedItem().toString();
comboBoxAxisType(xAxisType, xAxisType0, jTextFieldXmin, jTextFieldXmax);
xAxisType0 = xAxisType;
resizeXMinMax();
updateConcs();
updateConcList();
updateUseEhCheckBox();
updateDrawPHlineBox();
enableTemperature();
}//GEN-LAST:event_jComboBoxXaxTypeActionPerformed
private void jComboBoxXaxCompActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxXaxCompActionPerformed
if(loading) {return;}
if(jPanelGetConc.isShowing()) {jButtonGetConcCancel.doClick();}
int iX;
boolean predomDgr = jComboBoxDiagType.getSelectedItem().toString().equals("Predominance Area");
if(diag.compX >=0) {
// Change the concentration of the component that was in the X-axis:
iX = diag.compX;
if(!jComboBoxXaxComp.getSelectedItem().toString().equals(namn.identC[iX]) &&
(!predomDgr || iX != diag.compY)) {
if(iX == ePresent &&
(dgrC.hur[iX] !=1 && dgrC.hur[iX] !=2 && dgrC.hur[iX] !=3)) { //not "T"
dgrC.cLow[iX] = -8.5;
dgrC.hur[iX] = 4; // "LA" = "pe"
} else if(iX == hPresent &&
(dgrC.hur[iX] !=1 && dgrC.hur[iX] !=2 && dgrC.hur[iX] !=3)) { //not "T"
dgrC.cLow[iX] = -7;
dgrC.hur[iX] = 4; // "LA" = "pH"
} else if(Util.isWater(namn.identC[iX])) {
dgrC.cLow[iX] = 0;
dgrC.hur[iX] = 4; // "LA"
} else if(dgrC.hur[iX] ==1 || dgrC.hur[iX] ==2 || dgrC.hur[iX] ==3) { //"T"
if(dgrC.hur[iX] ==3) { // "LTV"
dgrC.cLow[iX] = logToNoLog(dgrC.cLow[iX]);
dgrC.cHigh[iX] = logToNoLog(dgrC.cHigh[iX]);
} // "LTV"
dgrC.hur[iX] = 1; // "T"
if(dgrC.cLow[iX] == 0 && dgrC.cHigh[iX] !=0 && !Double.isNaN(dgrC.cHigh[iX])) {dgrC.cLow[iX] = dgrC.cHigh[iX];}
} else {
dgrC.hur[iX] = 4; // "LA"
if(Util.isGas(namn.identC[iX])) {dgrC.cLow[iX] = -3.5;}
}
} // if there was a component change
} // compX >=0
// --- Get the new compX
for(int ic = 0; ic < cs.Na; ic++) {
if(jComboBoxXaxComp.getSelectedItem().toString().
equalsIgnoreCase(namn.identC[ic])) {diag.compX = ic; break;}
} // for ic
// -- for a Predom diagram: the concentrations in the axis
// must be log-scale: change concentration if needed
iX = diag.compX;
if(predomDgr && (dgrC.hur[iX] ==1 || dgrC.hur[iX] ==2)) { //"T" or "TV"
// "hur[iX]" will be changed in updateAxes()
}
changingComp = true;
updateAxes();
changingComp = false;
resizeXMinMax();
updateConcList();
updateUseEhCheckBox();
updateDrawPHlineBox();
enableTemperature();
}//GEN-LAST:event_jComboBoxXaxCompActionPerformed
private void jComboBoxYaxTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxYaxTypeActionPerformed
if(loading || changingComp || updatingAxes) {return;}
if(pc.dbg) {System.out.println("jComboBoxYaxType_Action_performed");}
if(jPanelGetConc.isShowing()) {jButtonGetConcCancel.doClick();}
String yAxisType = jComboBoxYaxType.getSelectedItem().toString();
comboBoxAxisType(yAxisType, yAxisType0, jTextFieldYmin, jTextFieldYmax);
yAxisType0 = yAxisType;
resizeYMin(); resizeYMax();
updateConcs();
updateUseEhCheckBox();
updateDrawPHlineBox();
enableTemperature();
}//GEN-LAST:event_jComboBoxYaxTypeActionPerformed
private void jComboBoxYaxCompActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxYaxCompActionPerformed
if(loading || updatingAxes) {return;}
if(pc.dbg) {System.out.println("jComboBoxYaxComp_Action_Performed");}
if(jPanelGetConc.isShowing()) {jButtonGetConcCancel.doClick();}
if(jComboBoxDiagType.getSelectedItem().toString().equals("Predominance Area")) {
//Change the concentration of the component that was in the Y-axis:
if(diag.compY >=0) {
int iY = diag.compY;
if(!jComboBoxYaxComp.getSelectedItem().toString().equals(namn.identC[iY])
&& (iY != diag.compX)) {
if(iY == ePresent &&
dgrC.hur[iY] !=1 && dgrC.hur[iY] !=2 && dgrC.hur[iY] !=3) { //not "T"
dgrC.cLow[iY] = -8.5;
dgrC.hur[iY] = 4; // "LA" = "pe"
} else if(iY == hPresent &&
dgrC.hur[iY] !=1 && dgrC.hur[iY] !=2 && dgrC.hur[iY] !=3) { //not "T"
dgrC.cLow[iY] = -7;
dgrC.hur[iY] = 4; // "LA" = "pH"
} else if(Util.isWater(namn.identC[iY])) {
dgrC.cLow[iY] = 0;
dgrC.hur[iY] = 4; // "LA"
} else if(dgrC.hur[iY] ==1 || dgrC.hur[iY] ==2 || dgrC.hur[iY] ==3) { //"T", "TV", "LTV"
if(dgrC.hur[iY] ==3) { // "LTV"
dgrC.cLow[iY] = logToNoLog(dgrC.cLow[iY]);
dgrC.cHigh[iY] = logToNoLog(dgrC.cHigh[iY]);
} // "LT"
dgrC.hur[iY] = 1; // "T"
} else {
dgrC.hur[iY] = 4; // "LA"
if(Util.isGas(namn.identC[iY])) {dgrC.cLow[iY] = -3.5;}
}
} // if there was a component change
} // if compY >=0
} // if diagram type = "Predominance Area"
// --- Get the new compY
for(int ic = 0; ic < cs.Na; ic++) {
if(jComboBoxYaxComp.getSelectedItem().toString().
equalsIgnoreCase(namn.identC[ic])) {diag.compY = ic; break;}
} // for ic
changingComp = true;
updateAxes();
changingComp = false;
resizeYMin(); resizeYMax();
updateUseEhCheckBox();
updateDrawPHlineBox();
enableTemperature();
}//GEN-LAST:event_jComboBoxYaxCompActionPerformed
private void jRadioButtonFixedActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonFixedActionPerformed
if(loading) {return;}
diag.ionicStrength = ionicStrOld;
jTextFieldIonicStr.setText(Util.formatNum(diag.ionicStrength));
jTextFieldIonicStr.setEnabled(true);
jLabelIonicS.setText("<html><u>I</u> =</html>");
jLabelIonicS.setEnabled(true);
jLabelM.setEnabled(true);
if(diag.ionicStrength == 0) {
jComboBoxActCoeff.setVisible(false);
jLabelModel.setVisible(false);
} else {
if(pd.advancedVersion) {
jLabelModel.setVisible(true);
jComboBoxActCoeff.setVisible(true);
}
}
enableTemperature();
}//GEN-LAST:event_jRadioButtonFixedActionPerformed
private void jRadioButtonCalcActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonCalcActionPerformed
ionicStrOld = Math.max(0,readTextField(jTextFieldIonicStr));
jTextFieldIonicStr.setEnabled(false);
jLabelIonicS.setText("I =");
jLabelIonicS.setEnabled(false);
jLabelM.setEnabled(false);
diag.ionicStrength = -1;
if(pd.advancedVersion) {
jLabelModel.setVisible(true);
jComboBoxActCoeff.setVisible(true);
}
enableTemperature();
}//GEN-LAST:event_jRadioButtonCalcActionPerformed
private void jTextFieldCLowKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldCLowKeyPressed
if(evt.getKeyCode()==java.awt.event.KeyEvent.VK_ENTER) {jButtonGetConcOK.doClick(); evt.consume();}
}//GEN-LAST:event_jTextFieldCLowKeyPressed
private void jTextFieldCHighKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldCHighKeyPressed
if(evt.getKeyCode()==java.awt.event.KeyEvent.VK_ENTER) {jButtonGetConcOK.doClick(); evt.consume();}
}//GEN-LAST:event_jTextFieldCHighKeyPressed
private void jTextFieldCLowFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldCLowFocusGained
oldTextCLow = jTextFieldCLow.getText();
jTextFieldCLow.selectAll();
}//GEN-LAST:event_jTextFieldCLowFocusGained
private void jTextFieldCHighFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldCHighFocusGained
oldTextCHigh = jTextFieldCHigh.getText();
jTextFieldCHigh.selectAll();
}//GEN-LAST:event_jTextFieldCHighFocusGained
private void jTextFieldCLowFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldCLowFocusLost
focusLostCLow();
}//GEN-LAST:event_jTextFieldCLowFocusLost
private void jTextFieldCHighFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldCHighFocusLost
focusLostCHigh();
}//GEN-LAST:event_jTextFieldCHighFocusLost
private void jTextFieldCLowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldCLowActionPerformed
focusLostCLow();
}//GEN-LAST:event_jTextFieldCLowActionPerformed
private void jTextFieldCHighActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldCHighActionPerformed
focusLostCHigh();
}//GEN-LAST:event_jTextFieldCHighActionPerformed
private void jCheckBoxDrawPHlineActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxDrawPHlineActionPerformed
runPHline = jCheckBoxDrawPHline.isSelected();
}//GEN-LAST:event_jCheckBoxDrawPHlineActionPerformed
private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
if(windowSize != null) {
int w = windowSize.width;
int h = windowSize.height;
if(this.getHeight()<h){this.setSize(this.getWidth(), h);}
if(this.getWidth()<w){this.setSize(w,this.getHeight());}
}
}//GEN-LAST:event_formComponentResized
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Methods">
private void quitFrame() {
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
MainFrame.locationSDFrame = this.getLocation();
this.setVisible(false);
finished = true;
this.notify_All();
this.dispose();
} // quitFrame()
/** this method will wait for this frame to be closed
* @return "cancel", true if no calculations performed,
* false = "ok", the calculations performed */
public synchronized boolean waitForSelectDiagram() {
while(!finished) {
try {wait();} catch (InterruptedException ex) {}
} // while
return cancel;
} // waitForSelectDiagram()
private synchronized void notify_All() {notifyAll();}
/** @param key a character
* @return true if the character is ok, that is, it is either a number,
* or a dot, or a minus sign, or an "E" (such as in "2.5e-6") */
private boolean isCharOKforNumberInput(char key) {
return Character.isDigit(key)
|| key == '-' || key == '+' || key == '.' || key == 'E' || key == 'e';
} // isCharOKforNumberInput(char)
//<editor-fold defaultstate="collapsed" desc="checkChanges()">
/** Is there a need to save the input data file? If so the file is saved here.
* @return <code>=false</code> if the data file needed to be saved but an error
* occurred while trying to save the changes; otherwise it returns <code>=true</code>
* indicating that there was no need to save the file, or that the user
* made changes that required saving the data file and no errors
* occurred while saving the data file. */
private boolean checkChanges() {
boolean changed = false;
if(pc.dbg) {System.out.println("Checking changes in data file: \""+dataFile.getName()+"\"");}
if(!dgrC.isEqualTo(dgrC0)) {
if(pc.dbg) {System.out.println("Concentrations changed.");}
changed = true;
}
if(!changed && diag.plotType != diag0.plotType) {
if(pc.dbg) {System.out.println("Plot type changed.");}
changed = true;
}
if(!changed) {
if(diag.plotType ==0) { //Predom
if(diag.compX != diag0.compX ||
diag.compY != diag0.compY ||
diag.compMain != diag0.compMain) {
if(pc.dbg) {System.out.println("Axis and/or main components changed.");}
changed = true;
}
} //if Predom
} //if not changed
if(!changed) {
if(diag.plotType >0) { //SED
if(diag.compX != diag0.compX ||
((diag.plotType ==1 || diag.plotType ==4) && //Fraction or Relative act.
diag.compY != diag0.compY)) {
if(pc.dbg) {System.out.println("Axis components changed.");}
changed = true;
}
} //if SED
} //if not changed
if(!changed) {
if(((diag.plotType >=2 && diag.plotType <=7) && // log scale in Y-axis?
(diag.yLow != diag0.yLow || diag.yHigh != diag0.yHigh))) {
if(pc.dbg) {System.out.println("Y-axis range changed.");}
changed = true;
}
} //if not changed
diag.title = Util.rTrim(jTextFieldTitle.getText());
if(!changed) {
// check if one is null and the other not
if((diag.title != null & diag0.title == null) ||
(diag.title == null & diag0.title != null)) {
if(pc.dbg) {System.out.println("Title changed from (or to) \"null\".");}
changed = true;
} else {
if(diag.title != null & diag0.title != null) {
if(diag.title.length() != diag0.title.length()) {
if(pc.dbg) {System.out.println("Title changed: different lengths.");}
changed = true;
} else {
if(!diag.title.equals(diag0.title)) {
if(pc.dbg) {System.out.println("Title changed.");}
changed = true;
}
}
}
}
} //if not changed
if(!changed) {
if(!Double.isNaN(diag.temperature) || !Double.isNaN(diag0.temperature)) {
if((!Double.isNaN(diag.temperature) && Double.isNaN(diag0.temperature)) ||
(Double.isNaN(diag.temperature) && !Double.isNaN(diag0.temperature)) ||
diag.temperature != diag0.temperature) {
if(pc.dbg) {System.out.println("Temperature changed.");}
changed = true;
}
}
} //if not change
if(!changed) {
if(!Double.isNaN(diag.pressure) || !Double.isNaN(diag0.pressure)) {
if((!Double.isNaN(diag.pressure) && Double.isNaN(diag0.pressure)) ||
(Double.isNaN(diag.pressure) && !Double.isNaN(diag0.pressure)) ||
diag.pressure != diag0.pressure) {
if(pc.dbg) {System.out.println("Pressure changed.");}
changed = true;
}
}
} //if not change
// are there "e-" in the chemical system?
if(ePresent >= 0) {
diag.Eh = runUseEh;
if(!changed) {
if(diag.Eh != diag0.Eh) {
if(pc.dbg) {System.out.println("\"Eh\" changed.");}
changed = true;
}
} //if not changed
}
if(changed) {
System.out.println("--- Saving changes to input file.");
try {WriteChemSyst.writeChemSyst(ch, dataFile);}
catch (Exception ex) {
MsgExceptn.showErrMsg(this,ex.getMessage(),1);
return false;
}
return true;
} //if changed
else {
System.out.println("--- No changes need to be saved to the input file.");
return true;
} //not changed
} //checkChanges();
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="checkComponentsInAxes()">
/** Check that compX >=0, and for a PREDOM, Fraction or Relative diagrams
* check that compY is >=0. Set default values otherwise. */
private void checkComponentsInAxes() {
//--- X-axis: Check that there is a valid component.
// Take a default otherwise
if(diag.compX < 0) {
// select a default X-component: e-, H+, the 1st anion, or the 1st gas
if(hPresent >= 0 && hPresent < cs.Na) {
diag.compX = hPresent;
dgrC.cLow[diag.compX] = -12;
dgrC.cHigh[diag.compX] = -1;
dgrC.hur[diag.compX] = 5; // "LAV" = "pH varied"
} else
if(ePresent >= 0 && ePresent < cs.Na) {
diag.compX = ePresent;
dgrC.cLow[diag.compX] = -17;
dgrC.cHigh[diag.compX] = 17;
dgrC.hur[diag.compX] = 5; // "LAV" = "pe varied"
}
} // if compX < 0
if(diag.compX < 0) {
for(int ic =0; ic < cs.Na; ic++) {
if(ic != ePresent && Util.isAnion(namn.identC[ic])) {
diag.compX = ic;
dgrC.cLow[ic] = -6;
dgrC.cHigh[ic] = 0.5;
if(dgrC.hur[ic] == 1 || dgrC.hur[ic] == 2 || dgrC.hur[ic] == 3) { // "T"
dgrC.hur[ic] = 3; // "LTV" = "log (Total conc.) varied"
} else { // not "T"
dgrC.hur[ic] = 5; // "LAV" = "log (activity) varied"
}
break;
} // if isAnion
} // for ic
} // if compX < 0
if(diag.compX < 0) {
for(int ic =0; ic < cs.Na; ic++) {
if(Util.isGas(namn.identC[ic])) {
diag.compX = ic;
dgrC.cLow[ic] = -4;
dgrC.cHigh[ic] = 2;
if(dgrC.hur[ic] == 1 || dgrC.hur[ic] == 2 ||
dgrC.hur[ic] == 3) { // "T"
dgrC.hur[ic] = 3; // "LTV" = "log (Total conc.) varied"
} // "T"
else
{
dgrC.hur[ic] = 5; // "LAV" = "log P varied"
}
break;
}
} // for ic
} // if compX < 0
//--- Y-axis: Check that there is a valid component.
// Take a default otherwise
if(diag.plotType == 0 || //PREDOM
diag.plotType == 1 || //fraction
diag.plotType == 4) { //relative diagram
if(diag.compY < 0) {
// select a default Y-component: e-, H+, the 1st anion, or the 1st gas
if(hPresent >= 0 && hPresent < cs.Na && diag.compX != hPresent) {
diag.compY = hPresent;
dgrC.cLow[diag.compY] = -12;
dgrC.cHigh[diag.compY] = -1;
dgrC.hur[diag.compY] = 5; // "LAV" = "pH varied"
} else
if(ePresent >= 0 && ePresent < cs.Na && diag.compX != ePresent) {
diag.compY = ePresent;
dgrC.cLow[diag.compY] = -17;
dgrC.cHigh[diag.compY] = 17;
dgrC.hur[diag.compY] = 5; // "LAV" = "pe varied"
}
} // if compY < 0
if(diag.compY < 0) { //take an anion
for(int ic =0; ic < cs.Na; ic++) {
if(ic != ePresent && Util.isAnion(namn.identC[ic])
&& diag.compX != ic) {
diag.compY = ic;
dgrC.cLow[ic] = -6;
dgrC.cHigh[ic] = 0.5;
if(dgrC.hur[ic] == 1 || dgrC.hur[ic] == 2 ||
dgrC.hur[ic] == 3) { // "T"
dgrC.hur[ic] = 3; // "LTV" = "log (Total conc.) varied"
} // "T"
else
{
dgrC.hur[ic] = 5; // "LAV" = "log (activity) varied"
}
break;
} // if isAnion
} // for ic
} // if compY < 0
if(diag.compY < 0) { //take a gas
for(int ic =0; ic < cs.Na; ic++) {
if(Util.isGas(namn.identC[ic]) && diag.compX != ic) {
diag.compY = ic;
dgrC.cLow[ic] = -4;
dgrC.cHigh[ic] = 2;
if(dgrC.hur[ic] == 1 || dgrC.hur[ic] == 2 ||
dgrC.hur[ic] == 3) { // "T"
dgrC.hur[ic] = 3; // "LTV" = "log (Total conc.) varied"
} // "T"
else
{
dgrC.hur[ic] = 5; // "LAV" = "log P varied"
}
break;
}
} // for ic
} // if compY < 0
} //if PREDOM etc
//--- the end
} //checkComponentsInAxes()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="checkForEqual(w1,w2)">
private static class TwoDoubles {
double x1, x2;
//public twoDoubles() {x1 = Double.NaN; x2 = Double.NaN;}
public TwoDoubles(double w1, double w2) {x1 = w1; x2 = w2;}
}
private void checkForEqual(TwoDoubles td) {
boolean done = false;
if(Double.isNaN(td.x1)) {td.x1 = 0;}
if(Double.isNaN(td.x2)) {td.x2 = 0;}
if(td.x1 != 0) {
if(td.x2 != 0 && Math.abs((td.x1-td.x2)/td.x1) <= 0.00001) {
td.x2 = td.x1 + td.x1*0.001; done = true;}
}
if(!done && td.x2 != 0) {
if(td.x1 != 0 && Math.abs((td.x1-td.x2)/td.x2) <= 0.00001) {
td.x2 = td.x1 + td.x1*0.001; done = true;}
}
if(!done) {
if(Math.abs(td.x1-td.x2) <= 1e-26) {td.x2 = 1;}
}
} // checkForEqual(TwoDoubles)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="checkInputConcs()">
/** Check that the components in the axes have varied concentrations, and that
* for PREDOM, check also that all components not belonging to an axes have
* not varied concentrations. Fix the problem with default choices if a
* problem is found. */
private void checkInputConcs() {
if(pc.dbg) {System.out.println("checkInputConcs()");}
String component;
boolean inAxis;
for(int i = 0; i < cs.Na; i++) {
// ------------------------------
// For SED and PREDOM: set default concs. for all comps. not in an axis
// (this is perhaps not needed, but included for robustness)
component = namn.identC[i];
inAxis = false;
if(diag.plotType == 0) {//PREDOM
if(i == diag.compX || i == diag.compY) {inAxis = true;}
} else if(diag.plotType >= 1) { //SED
if(i == diag.compX) {inAxis = true;}
}
if(diag.plotType == 0 && !inAxis) { //PREDOM
//in PREDOM only components in the axes can have conc. varied
if(dgrC.hur[i] ==2 || dgrC.hur[i] ==3 || dgrC.hur[i] ==5) {
// conc. varied: must change to fixed
MsgExceptn.showErrMsg(this, "Warning: the concentration for \""+component+"\" is varied,"+nl+
"but it does not belong to an axes."+nl+"It will be changed to non-varied.", 2);
if(i == ePresent && dgrC.hur[i] ==5) { // not "T"?
dgrC.cLow[i] = -8.5;
dgrC.hur[i] = 4; // "LA"
} else
if(i == hPresent && dgrC.hur[i] ==5) {
dgrC.cLow[i] = -7;
dgrC.hur[i] = 4; // "LA" = "pH"
} else
if(Util.isWater(component)) {
dgrC.cLow[i] = 0;
dgrC.hur[i] = 4; // "LA" = "log (activity)"
} else
if(dgrC.hur[i] ==2 || dgrC.hur[i] ==3) { //"TV" or "LTV"
if(dgrC.hur[i] ==3) { //"LTV"
if(dgrC.cLow[i] <= 20) {
dgrC.cLow[i] = logToNoLog(dgrC.cLow[i]);
} else {
if(pd.kth) {dgrC.cLow[i] = 0.01;} else {dgrC.cLow[i] = 1e-5;}
} // if < 20
} // if "LTV"
dgrC.hur[i] = 1; // "T" = "Total conc."
} // if "TV" or "LTV"
else {
dgrC.hur[i] = 4; // "LA" = "log (activity)"
if(Util.isGas(component)) {dgrC.cLow[i] = -3.5;}
} // if not "T..."
} // if conc. varied
} //if PREDOM and !inAxis
if((diag.plotType == 0 && inAxis) || (diag.plotType >= 1 && inAxis)) {
// ------------------------------
// For SED and PREDOM: set varied concs. for all comps. in the axis
// (this is perhaps not needed, but included for robustness)
if(dgrC.hur[i] ==1 || dgrC.hur[i] ==4) { //not varied ("T" or "LA")
// conc. not varied: must change
MsgExceptn.showErrMsg(this, "Warning: the concentration for \""+component+"\" is not varied,"+nl+
"but it belongs to an axes."+nl+"It will be changed to varied.",2);
if(i == ePresent && dgrC.hur[i] ==4) {// "LA"?
dgrC.cLow[i] = -16.9034;
dgrC.cHigh[i] = +16.9034;
dgrC.hur[i] = 5; // "LAV"
} else
if(i == hPresent && dgrC.hur[i] ==4) {// "LA"?
dgrC.cLow[i] = -12;
dgrC.cHigh[i] = -1;
dgrC.hur[i] = 5; // "LAV" = "pH varied"
} else
if(Util.isWater(component)) {
dgrC.cLow[i] = -2;
dgrC.cHigh[i] = 0;
dgrC.hur[i] = 5; // "LAV" = "log (activity) varied"
} else
if(dgrC.hur[i] ==1) { //"T"?
if(dgrC.cLow[i]>0) {
if(dgrC.cLow[i] <=0.001) {
dgrC.cLow[i] = Math.log(dgrC.cLow[i]);
dgrC.cHigh[i] = dgrC.cLow[i]+3;
} else {
dgrC.cHigh[i] = Math.log(dgrC.cLow[i]);
dgrC.cLow[i] = dgrC.cHigh[i]-3;
}
} else {
dgrC.cLow[i] = -6;
dgrC.cHigh[i] = 0;
}
dgrC.hur[i] = 3; // "LTV" = "log (Total conc.) varied"
} // if "T..."
else { //"LA"
dgrC.hur[i] = 5; // "LAV" = "log (activity) varied"
if(dgrC.cLow[i] <=-3) {
dgrC.cHigh[i] = dgrC.cLow[i]+3;
} else {
dgrC.cHigh[i] = dgrC.cLow[i];
dgrC.cLow[i] = dgrC.cHigh[i]-3;
}
} // if "LA"
} //if con. not varied
} //if SED or PREDOM and inAxis
if(diag.plotType == 0 && inAxis) {
// ------------------------------
// For PREDOM: if the concentration is "TV" for a comp. in an axis
// change to "LTV"
if(dgrC.hur[i] ==2) {
// Tot. conc. varied: must change to log (Tot. conc.) varied
MsgExceptn.showErrMsg(this, "Warning: the total concentration for \""+component+"\" is varied."+nl+
"It will be changed to log(Tot.Conc.) varied.",2);
dgrC.hur[i] = 3; // "LTV" = "log (Total conc.) varied"
dgrC.cLow[i] = Math.max(-50, Math.log10(Math.max(1e-51, Math.abs(dgrC.cLow[i]))));
dgrC.cHigh[i] = Math.max(-45, Math.log10(Math.max(1e-46, Math.abs(dgrC.cHigh[i]))));
} //if "TV"
} //if PREDOM and inAxis
// ------------------------------
} // for i = 0 to ca.Na-1
} //checkInputConcs()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="checkMainComponent()">
private void checkMainComponent() {
if(diag.plotType == 0) { //PREDOM
if(diag.compMain < 0) {
for(int ic =0; ic < cs.Na; ic++) {
if(ic != hPresent && Util.isCation(namn.identC[ic])) {
diag.compMain = ic; break;
}
}
}
}
} //checkMainComponent()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="compConcList_Click(i)">
private void compConcList_Click(int i) {
if(i < 0) {return;}
getConc_idx = i;
// --- get the component name
String comp = namn.identC[getConc_idx];
if(Util.isWater(comp)) { // is it H2O?
String msg = "<html>The calculations are made for 1kg H<sub>2</sub>O<br> <br>";
if(dgrC.hur[getConc_idx] < 4) { // total conc. for H2O given
msg = msg + "The input for <b>water</b> will be changed to activity = 1.";
} else { // log A given
msg = msg + "The activity of <b>water</b> is calculated when<br>"+
"the ionic strength is <i>not</i> zero.";
}
javax.swing.JOptionPane.showMessageDialog(this, msg, pc.progName, javax.swing.JOptionPane.INFORMATION_MESSAGE);
dgrC.cLow[getConc_idx] = 0;
dgrC.hur[getConc_idx] = 4; // "LA" = "log (activity)"
return;
} // for H2O
getConcLoading = true;
// disable buttons and things
jButton_OK.setEnabled(false);
jButton_Cancel.setEnabled(false);
jButtonSaveDef.setEnabled(false);
if(getConc_idx == ePresent) {
if(jCheckBoxUseEh.isVisible()) {
jCheckBoxUseEh.setText("use Eh for e-");
jCheckBoxUseEh.setEnabled(false);
}
jLabelT.setEnabled(false);
jTextFieldT.setEnabled(false);
jLabelTC.setEnabled(false);
}
java.awt.CardLayout cl = (java.awt.CardLayout)jPanelConcs.getLayout();
cl.show(jPanelConcs, "panelGetConc");
//cl.show(jPanelConcs, "panelCompConcList");
double fEh = (MainFrame.Rgas * ln10 * (diag.temperature +273.15)) / MainFrame.Faraday;
boolean isGas = Util.isGas(comp);
boolean isSolid = (Util.isSolid(comp) || getConc_idx >= (cs.Na-cs.solidC));
jLabel_GetConcCompName.setText(comp);
// --- get the value of the concentration(s)
jLabelFrom.setText(" "); jLabelTo.setText(" ");
jTextFieldCHigh.setVisible(false);
int use_pHpe = 0;
if(dgrC.hur[getConc_idx] ==4 || dgrC.hur[getConc_idx] ==5) { // "A"
if(getConc_idx == hPresent) {use_pHpe =1;}
else if(getConc_idx == ePresent) {use_pHpe =2; if(runUseEh) {use_pHpe =3;}}
}
double w1 = dgrC.cLow[getConc_idx];
double w2 = dgrC.cHigh[getConc_idx];
if(use_pHpe ==1 || use_pHpe ==2) {w1 =-w1; w2 =-w2;}
if(use_pHpe == 3) {w1 = -w1 *fEh; w2 = -w2 *fEh;}
// rounding for logarithmic concs.
if(dgrC.hur[getConc_idx] ==2 || dgrC.hur[getConc_idx] ==3 ||
dgrC.hur[getConc_idx] ==5) { // "V"
jLabelFrom.setText("from:"); jLabelTo.setText("to:");
jTextFieldCHigh.setVisible(true);
if(!runRevs) {if(w2 < w1) {double w = w1; w1 = w2; w2 = w;}}
jTextFieldCHigh.setText(Util.formatDbl6(w2));
} // if conc. varied
else {jTextFieldCHigh.setText("0");}
jTextFieldCLow.setText(Util.formatDbl6(w1));
int jc = dgrC.hur[getConc_idx]-1 + (use_pHpe * 2);
if(isGas) {
if(jc==3) {jc = 11;} // LA = "log P"
if(jc==4) {jc = 12;} // LAV = "log P varied"
}
String conc2 = concTypes[jc];
// --- fill in the conc. combo-box
boolean inXaxis = false;
boolean inYaxis = false;
boolean inAxis;
if(namn.identC[getConc_idx].
equalsIgnoreCase(jComboBoxXaxComp.getSelectedItem().toString())) {inXaxis = true;}
if(namn.identC[getConc_idx].
equalsIgnoreCase(jComboBoxYaxComp.getSelectedItem().toString())) {inYaxis = true;}
inAxis = (inXaxis | inYaxis);
if(getConc_idx == hPresent) {use_pHpe =1;}
else if(getConc_idx == ePresent) {use_pHpe =2; if(runUseEh) {use_pHpe =3;}}
jComboBoxConcType.removeAllItems();
int ic;
if(!inXaxis && !(runPredomSED==1 && (inYaxis || (isSolid && cs.nx ==0 && dgrC.hur[getConc_idx] !=4)))) {
ic = 3 + use_pHpe * 2;
if(isGas) {ic = 11;} // "log P"
jComboBoxConcType.addItem(concTypes[ic]); //pH/pe/Eh/log(activity)
}
if(!(runPredomSED==1 && (!inAxis || (isSolid && cs.nx ==0 && dgrC.hur[getConc_idx] !=5)))) {
ic = 4 + use_pHpe * 2;
if(isGas) {ic = 12;} // "log P varied"
jComboBoxConcType.addItem(concTypes[ic]); //pH/pe/Eh/log(activity) varied
}
if(!inXaxis && !(runPredomSED==1 && inYaxis)) {
jComboBoxConcType.addItem(concTypes[0]); // Total conc.
}
if(runPredomSED!=1) {
jComboBoxConcType.addItem(concTypes[1]); // Total conc. varied
}
if(!(runPredomSED==1 && !inAxis)) {
jComboBoxConcType.addItem(concTypes[2]); // log Total conc. varied
}
// select the conc. type in the combo box
jComboBoxConcType.setSelectedIndex(-1);
for(int k=0; k < jComboBoxConcType.getItemCount(); k++) {
if(conc2.equalsIgnoreCase(jComboBoxConcType.getItemAt(k).toString())) {
jComboBoxConcType.setSelectedIndex(k);
break;
}
} //for k
// if the original conc is of unknown type:
if(jComboBoxConcType.getSelectedIndex() <0) {
jComboBoxConcType.addItem("? unknown conc. type");
jComboBoxConcType.setSelectedIndex(jComboBoxConcType.getItemCount()-1);
}
comboBoxConcType0 = jComboBoxConcType.getSelectedItem().toString();
getConcLoading = false;
jTextFieldCLow.requestFocusInWindow();
// msgBox
//javax.swing.JOptionPane.showMessageDialog(null,"hej",pc.progName, javax.swing.JOptionPane.INFORMATION_MESSAGE);
} // compConcList_Click(i)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="logToNoLog(w)">
/** coverts "x" to 10^(x). If x is larger than 307, 10^(307) is returned.
* If x is less than -300, or if x is NaN, zero is returned.
* @param x
* @return 10^(x) */
private double logToNoLog (double x) {
// Convert -10 to 1E-10
double r = 0;
if(!Double.isNaN(x)) {
if(x > 307) {
r = 1E+307;
} else
if(x > -300) {r = Math.pow(10,x);}
}
return r;
} // logToNoLog(w)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="dataFile_Click()">
private void dataFile_Click() {
// get a file name
jTextFieldDataFile.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
String fileName = Util.getOpenFileName(this, pc.progName, true,
"Enter Data file name", 5, null, dataFile.getPath());
if(fileName == null) {
jTextFieldDataFile.requestFocusInWindow();
jTextFieldDataFile.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
return;}
if(MainFrame.getInstance().addDatFile(fileName)) {
setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
dataFile = new java.io.File(fileName);
if(!readDataFile(pc.dbg)) {
jTextFieldDataFile.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
return;}
if(pc.dbg) {System.out.println(" ------------------------ change of data file to \""+dataFile.getName()+"\"");}
boolean b = loading; loading = true;
setUpFrame();
loading = b;
updateAxes();
updateConcList();
resizeXMinMax(); resizeYMin(); resizeYMax();
updateUseEhCheckBox();
updateDrawPHlineBox();
enableTemperature();
if(plotAndConcsNotGiven) {missingPlotAndConcsMessage();}
}
// bringToFront
java.awt.EventQueue.invokeLater(new Runnable() {
@Override public void run() {
setAlwaysOnTop(true);
toFront();
requestFocus();
setAlwaysOnTop(false);
jTextFieldDataFile.requestFocusInWindow();
jTextFieldDataFile.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
}
});
} // dataFile_Click()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="diagramType_Click()">
/** Take the actions necessary when the diagram type in "jComboBoxDiagType"
* is changed */
private void diagramType_Click() {
if(diagramType_doNothing) {return;}
if(pc.dbg) {System.out.println("--- diagramType_Click() --- (loading="+loading+")");}
updatingAxes = true;
java.awt.CardLayout cl;
String dt = jComboBoxDiagType.getSelectedItem().toString();
if(ch != null && loading) {
if(diag.plotType == 0) {dt = "Predominance Area";}
else if(diag.plotType == 1) {dt = "Fraction";}
else if(diag.plotType == 2) {dt = "log Solubilities";}
else if(diag.plotType == 3) {dt = "Logarithmic";}
else if(diag.plotType == 4) {dt = "Relative activities";}
else if(diag.plotType == 5) {
if(runUseEh) {dt = "calculated Eh";}
else {dt = "calculated pe";}}
else if(diag.plotType == 6) {dt = "calculated pH";}
else if(diag.plotType == 7) {dt = "log Activities";}
else if(diag.plotType == 8) {dt = "H+ affinity spectrum";}
}
if(pc.dbg) {System.out.println("diagram type: "+dt);}
int oldPlotType = diag.plotType;
// ---------------------------------------------------------------------------
// ----- PREDOM:
// ---------------
if(dt.equalsIgnoreCase("Predominance Area")) {
cl = (java.awt.CardLayout)jPanelSedPredom.getLayout();
if(pd.advancedVersion) {
cl.show(jPanelSedPredom, "Predom");
} else {
cl.show(jPanelSedPredom, "Empty"); //.setVisible(false);
}
cl = (java.awt.CardLayout)jPanelYaxInner.getLayout();
cl.show(jPanelYaxInner, "cardYcombo");
cl = (java.awt.CardLayout)jPanelYaxComp.getLayout();
cl.show(jPanelYaxComp, "cardYaxComp1"); //.setVisible(true);
enableYminYmax(true);
jComboBoxMainComp.setVisible(true);
setOKButtonIcon("images/PlotPred16_32x32_transpBckgr.gif");
if(!loading) {
if(runPredomSED == 2) {
// --- The user changes from a SED to a PREDOM-diagram:
// (it is possible that the user selects "predominance diagram" twice in a row)
// select a default Y-component: e-, H+, the 1st anion, or the 1st gas
diag.compY = -1;
diag.compMain = -1;
boolean includeSpecies = false;
updateYcomp(includeSpecies);
updatingAxes = true;
} //if it was SED
// --- Select a component for the Y-axis if missing
if(diag.compY < 0) {
if(diag.compX == hPresent) {
if(ePresent >=0 && ePresent < cs.Na) { // pH in X-axis: select Eh in Y-axis
diag.compY = ePresent;
dgrC.cLow[diag.compY] = -17;
dgrC.cHigh[diag.compY] = 17;
dgrC.hur[diag.compY] = 5; // "LAV" = "pe varied"
}
} else if(hPresent >=0 && hPresent < cs.Na) {
diag.compY = hPresent; // otherwise, pH in Y-axis
dgrC.cLow[diag.compY] = -12;
dgrC.cHigh[diag.compY] = -1;
dgrC.hur[diag.compY] = 5; // "LAV" = "pH varied"
}
} //if compY < 0
if(diag.compY < 0) { // take an anion
for(int ic =0; ic < cs.Na; ic++) {
if(ic != ePresent && Util.isAnion(namn.identC[ic])) {
diag.compY = ic;
if(diag.compY != diag.compX) {
if(dgrC.hur[ic] ==3 || dgrC.hur[ic] ==5) { // "L*V"
dgrC.cLow[ic] = -6; dgrC.cHigh[ic] = 0;
} else if(dgrC.hur[ic] ==2) { // "TV"
dgrC.cLow[ic] = 0; dgrC.cHigh[ic] = 1;
}
} //if not = X-axis
break;
} //isAnion
} //for ic
} //if compY < 0
if(diag.compY < 0) { // take a gas
for(int ic =0; ic < cs.Na; ic++) {
if(Util.isGas(namn.identC[ic])) {
diag.compY = ic;
if(diag.compY != diag.compX) {
if(dgrC.hur[ic] ==3 || dgrC.hur[ic] ==5) { // "L*V"
dgrC.cLow[ic] = -4; dgrC.cHigh[ic] = 2;
} else if(dgrC.hur[ic] ==2) { // "TV"
dgrC.cLow[ic] = 0; dgrC.cHigh[ic] = 1;
}
} //if not = X-axis
break;
} //isGas
} //for ic
} //if compY < 0
if(diag.compY < 0) { //nothing fits, get the 1st one on the list
int j=0;
if(diag.compX == 0 && jComboBoxYaxComp.getItemCount() >1) {j=1;}
for(int ic=0; ic < cs.Na; ic++) {
if(namn.identC[ic].equalsIgnoreCase(jComboBoxYaxComp.getItemAt(j).toString())) {
diag.compY = ic;
if(diag.compY != diag.compX) {
if(dgrC.hur[ic] ==3 || dgrC.hur[ic] ==5) { // "L*V"
dgrC.cLow[ic] = -6; dgrC.cHigh[ic] = 0;
} else if(dgrC.hur[ic] ==2) { // "TV"
dgrC.cLow[ic] = 0; dgrC.cHigh[ic] = 1;
}
} //if not = X-axis
break;
}
} //for ic
} //if compY < 0
// ---- Set the concentration for the Y-component varied:
if(dgrC.hur[diag.compY] !=2 && dgrC.hur[diag.compY] !=3 && dgrC.hur[diag.compY] !=5) {
// not "*V"
if(Util.isGas(namn.identC[diag.compY])) {
dgrC.hur[diag.compY] = 5; //"LAV" = "log P varied"
} //if isGas
else
if(dgrC.hur[diag.compY] ==1 || dgrC.hur[diag.compY] ==2 || dgrC.hur[diag.compY] ==3) {
//"*T*": total conc.
dgrC.hur[diag.compY] = 3; //"LTV" = "log (Total conc.) varied"
} else { // not "*T*": activity
dgrC.hur[diag.compY] = 5; //"LAV" = "log (activity) varied"
}
} //if conc. not varied
// ---- Set a default Main-component: the 1st cation, or 1st solid, gas, aqu.
if(diag.compMain < 0) {
// first get a cation which is dos not begin with either "NH" or "N(" to skip ammonium
for(int ic =0; ic < cs.Na; ic++) {
if(ic != hPresent && Util.isCation(namn.identC[ic])
&& !namn.ident[ic].startsWith("NH") && !namn.ident[ic].startsWith("N(")) {
diag.compMain = ic; break;
} // isCation
} //for ic
} //if compMain < 0
if(diag.compMain < 0 && cs.solidC >0) { // get the first solid component
diag.compMain = (cs.Na - cs.solidC);
} //if compMain < 0
if(diag.compMain < 0) { // get a gas
for(int ic =0; ic < cs.Na; ic++) {
if(Util.isGas(namn.identC[ic])) {
diag.compMain = ic; break;
} // isGas
} //for ic
} //if compMain < 0
if(diag.compMain < 0) { // get an aqueous species
for(int ic =0; ic < cs.Na; ic++) {
if(namn.identC[ic].length() >4 &&
namn.identC[ic].toUpperCase().endsWith("(AQ)")) {
diag.compMain = ic; break;
} // is aqueous
} //for ic
} //if compMain < 0
if(diag.compMain < 0) { // get a cation even if it begin with either "NH" or "N("
for(int ic =0; ic < cs.Na; ic++) {
if(ic != hPresent && Util.isCation(namn.identC[ic])) {
diag.compMain = ic; break;
} // isCation
} //for ic
} //if compMain < 0
if(diag.compMain < 0) { // nothing fits, get the 1st one on the list
for(int ic=0; ic < cs.Na; ic++) {
if(namn.identC[ic].equalsIgnoreCase(jComboBoxMainComp.getItemAt(0).toString())) {
diag.compMain = ic;
break;
}
} //for ic
} //if compMain < 0
}//--- if not loading
// --- select the component in the Y-axis ComboBox
if(diag.compY >=0) {
for(int j=0; j < jComboBoxYaxComp.getItemCount(); j++) {
if(namn.identC[diag.compY].equalsIgnoreCase(jComboBoxYaxComp.getItemAt(j).toString())) {
jComboBoxYaxComp.setSelectedIndex(j);
break;
}
} //for j
}
// --- select the component in the Main-comp ComboBox
if(diag.compMain >=0) {
for(int j=0; j < jComboBoxMainComp.getItemCount(); j++) {
if(namn.identC[diag.compMain].equalsIgnoreCase(jComboBoxMainComp.getItemAt(j).toString())) {
jComboBoxMainComp.setSelectedIndex(j);
break;
}
} //for j
}
// ---- if Main-component does not belong to an axis,
// set the concentration to not varied
if(diag.compMain != diag.compX && diag.compMain != diag.compY) {
if(dgrC.hur[diag.compMain] ==2 || dgrC.hur[diag.compMain] ==3 ||
dgrC.hur[diag.compMain] ==5) { //if "*V" (conc varied)
// set a concentration-type not varied
if(Util.isGas(namn.identC[diag.compMain])) {
dgrC.hur[diag.compMain] = 4; //"LA" = "log P"
} else { //not Gas
if(dgrC.hur[diag.compMain] ==2 || dgrC.hur[diag.compMain] ==3) { //"TV" or "LTV"
if(dgrC.hur[diag.compMain] ==3) { //"LTV"
dgrC.cLow[diag.compMain] = logToNoLog(dgrC.cLow[diag.compMain]);
dgrC.cHigh[diag.compMain] = logToNoLog(dgrC.cLow[diag.compMain]);
} // "LTV"
dgrC.hur[diag.compMain] = 1; //"T" = "Total conc."
} //if "TV" or "LTV"
else { //"LAV"
dgrC.hur[diag.compMain] = 4; //"LA" = "log (activity)"
} //"T"?
} //not Gas
} //if conc varied
} //if Main comp. not in axis (if Main != compX & Main != compY)
runPredomSED = 1; // flag for a Predom diagram
diag.plotType = 0;
} //if user selected a Predom diagram
else { //user selected a SED diagram
// ---------------------------------------------------------------------------
// ----- SED:
// -----------
setOKButtonIcon("images/PlotLog256_32x32_traspBckgr.gif");
if(!loading) {
if(runPredomSED == 1) {
// --- The user changes from a PREDOM to a SED-diagram:
// --- select a default concentration
// for the component that was in the Y-axis
if(diag.compY >=0) {
if(diag.compY == ePresent
&& (dgrC.hur[diag.compY] ==4 || dgrC.hur[diag.compY] ==5)) { // "A"
dgrC.cLow[diag.compY] = -8.5;
dgrC.hur[diag.compY] = 4; // "LA" = "pe"
} //if "e-" & "A"
else
if(diag.compY == hPresent
&& (dgrC.hur[diag.compY] ==4 || dgrC.hur[diag.compY] ==5)) { // "A"
dgrC.cLow[diag.compY] = -7;
dgrC.hur[diag.compY] = 4; // "LA" = "pH"
} //if "H+" & "A"
else
if(Util.isWater(namn.identC[diag.compY])) {
dgrC.cLow[diag.compY] = 0;
dgrC.hur[diag.compY] = 4; // "LA" = "log (activity)"
} //if is H2O
else
if(dgrC.hur[diag.compY] ==4 || dgrC.hur[diag.compY] ==5) { //"LA"
dgrC.hur[diag.compY] = 4; // "LA" = "log (activity)"
} //if "LA*"
else { //must be "LTV" or "TV"
if(dgrC.hur[diag.compY] ==3) { // "LTV"
dgrC.cLow[diag.compY] = logToNoLog(dgrC.cLow[diag.compY]);
dgrC.cHigh[diag.compY] = logToNoLog(dgrC.cHigh[diag.compY]);
} //"LTV"
dgrC.hur[diag.compY] = 1; // "T" = "Total conc."
} //"LTV" or "TV"
} //if compY >=0
diag.compY = -1; diag.compMain = -1;
// --- for logarithmic plot: set default axes range
if(dt.equalsIgnoreCase("Logarithmic") || dt.equalsIgnoreCase("log Solubilities")
|| dt.equalsIgnoreCase("log Activities")) {
if(!diag.inputYMinMax) {
jTextFieldYmin.setText("-9");
jTextFieldYmax.setText("1");
} else {
jTextFieldYmin.setText(String.valueOf(diag.yLow));
jTextFieldYmax.setText(String.valueOf(diag.yHigh));
}
} //if "log"
} //if the user changes from PREDOM to SED
if(dt.equalsIgnoreCase("Fraction")) {diag.plotType = 1;}
if(dt.equalsIgnoreCase("log Solubilities")) {diag.plotType = 2;}
if(dt.equalsIgnoreCase("Logarithmic")) {diag.plotType = 3;}
if(dt.equalsIgnoreCase("Relative activities")) {diag.plotType = 4;}
if(dt.equalsIgnoreCase("calculated pe") || dt.equalsIgnoreCase("calculated Eh")) {diag.plotType = 5;}
if(dt.equalsIgnoreCase("calculated pH")) {diag.plotType = 6;}
if(dt.equalsIgnoreCase("log Activities")) {diag.plotType = 7;}
if(dt.equalsIgnoreCase("H+ affinity spectrum")) {diag.plotType = 8;}
} //if not loading
cl = (java.awt.CardLayout)jPanelSedPredom.getLayout();
if(pd.advancedVersion) {
cl.show(jPanelSedPredom, "SED");
} else {
cl.show(jPanelSedPredom, "Empty"); //.setVisible(false);
}
//cl = (java.awt.CardLayout)jPanelMainComp.getLayout();
//cl.show(jPanelMainComp, "cardMainComp0"); //.setVisible(false);
enableYminYmax(true);
jComboBoxMainComp.setVisible(false);
// Calculated-pH or calculated-pe/Eh ?
if(Ycalc >= 0) {
if(Ycalc == ePresent &&
(!dt.equalsIgnoreCase("calculated pe") &&
!dt.equalsIgnoreCase("calculated Eh"))) {Ycalc = -1;} //not calc pe/Eh
if(Ycalc == hPresent && !dt.equalsIgnoreCase("calculated pH")) {Ycalc = -1;} //not calc pH
}
if(dt.equalsIgnoreCase("calculated pH") || //calc pH
dt.equalsIgnoreCase("calculated pe") ||
dt.equalsIgnoreCase("calculated Eh")) { //calc pe/Eh
diag.compY = -1;
cl = (java.awt.CardLayout)jPanelYaxComp.getLayout();
cl.show(jPanelYaxComp, "cardYaxComp0"); // .setVisible(false);
if(dt.equalsIgnoreCase("calculated pe") || dt.equalsIgnoreCase("calculated Eh")) {
Ycalc = ePresent;
} else {
Ycalc = hPresent;
}
if(Ycalc >=0 && Ycalc < cs.Na) { //select default conc-type
if(dgrC.hur[Ycalc] ==4) { //"LA"
dgrC.hur[Ycalc] =1; //"T" = "Total conc."
dgrC.cLow[Ycalc] = logToNoLog(dgrC.cLow[Ycalc]);
} else if(dgrC.hur[Ycalc] ==5) { //"LAV"
dgrC.hur[Ycalc] =3; //"LTV" = "log (Total conc.) varied"
}
}
jLabelYcalc.setText(dt);
cl = (java.awt.CardLayout)jPanelYaxInner.getLayout();
cl.show(jPanelYaxInner, "cardYcalc");
cl = (java.awt.CardLayout)jPanelYaxComp.getLayout();
cl.show(jPanelYaxComp, "cardYaxComp0"); // .setVisible(false);
setOKButtonIcon("images/PlotPHpe256_32x32_transpBckgr.gif");
if(dt.equalsIgnoreCase("calculated pH")) { //calc pH
if(!jTextFieldYmin.isVisible()
|| jTextFieldYmin.getText().contains("%") || jTextFieldYmax.getText().contains("%")
|| readTextField(jTextFieldYmin)<0
|| readTextField(jTextFieldYmax)<0 || readTextField(jTextFieldYmax)>14) {
jTextFieldYmin.setText("0");
jTextFieldYmax.setText("14");
}
} //if "calc pH"
if(dt.equalsIgnoreCase("calculated pe")) {
if(!jTextFieldYmin.isVisible()
|| jTextFieldYmin.getText().contains("%") || jTextFieldYmax.getText().contains("%")
|| readTextField(jTextFieldYmin)>=0 || readTextField(jTextFieldYmax)<=0) {
jTextFieldYmin.setText("-17");
jTextFieldYmax.setText("17");
}
} //if "calc pe"
if(dt.equalsIgnoreCase("calculated Eh")) {
System.out.println("## calculated Eh");
if(!jTextFieldYmin.isVisible()
|| jTextFieldYmin.getText().contains("%") || jTextFieldYmax.getText().contains("%")
|| readTextField(jTextFieldYmin)>0 || readTextField(jTextFieldYmin)<-2
|| readTextField(jTextFieldYmax)<0 || readTextField(jTextFieldYmax)>2) {
jTextFieldYmin.setText("-1");
jTextFieldYmax.setText("1");
}
} //if "calc Eh"
} //if "calc pH/pe/Eh"
if(dt.equalsIgnoreCase("Logarithmic") || //logarithmic
dt.equalsIgnoreCase("log Solubilities") || //log Solubilities
dt.equalsIgnoreCase("log Activities")) {//log Activities
diag.compY = -1;
cl = (java.awt.CardLayout)jPanelYaxComp.getLayout();
cl.show(jPanelYaxComp, "cardYaxComp0"); // .setVisible(false);
cl = (java.awt.CardLayout)jPanelYaxInner.getLayout();
if(dt.equalsIgnoreCase("Logarithmic")) { //logarithmic
cl.show(jPanelYaxInner, "cardYlogC");
} else if(dt.equalsIgnoreCase("log Solubilities")) { //log solub.
cl.show(jPanelYaxInner, "cardYlogS");
} else if(dt.equalsIgnoreCase("log Activities")) { //log activities
cl.show(jPanelYaxInner, "cardYlogA");
}
if(readTextField(jTextFieldYmin) >=-1) {
if(!diag.inputYMinMax || (oldPlotType !=3 && oldPlotType !=7) ) {
jTextFieldYmin.setText("-9");
} else {jTextFieldYmin.setText(String.valueOf(diag.yLow));}
}
if(readTextField(jTextFieldYmax) >= 1) {
if(!diag.inputYMinMax || (oldPlotType !=3 && oldPlotType !=7) ) {
jTextFieldYmax.setText("1");
} else {jTextFieldYmax.setText(String.valueOf(diag.yHigh));}
}
} // if "log / logSolub / logAct"
if(dt.equalsIgnoreCase("H+ affinity spectrum")) {
diag.compY = -1;
cl = (java.awt.CardLayout)jPanelYaxComp.getLayout();
cl.show(jPanelYaxComp, "cardYaxComp0"); // .setVisible(false);
cl = (java.awt.CardLayout)jPanelYaxInner.getLayout();
cl.show(jPanelYaxInner, "cardYHaff"); // .setVisible(false);
setOKButtonIcon("images/PlotPHpe256_32x32_transpBckgr.gif");
jTextFieldYmin.setVisible(false);
jTextFieldYmax.setVisible(false);
} // if "H+ affinity spectrum"
else {
jTextFieldYmin.setVisible(true);
jTextFieldYmax.setVisible(true);
jPanelYaxis.validate();
}
if(dt.equalsIgnoreCase("Relative activities")) { //Relative activities
boolean includeSpecies = true; //both components and reaction products in Y-axis
updateYcomp(includeSpecies);
updatingAxes = true;
if(readTextField(jTextFieldYmin) >= -1) {jTextFieldYmin.setText("-6");}
if(readTextField(jTextFieldYmax) < 1.1) {jTextFieldYmax.setText("6");}
setOKButtonIcon("images/PlotRel256_32x32_transpBckgr.gif");
cl = (java.awt.CardLayout)jPanelYaxInner.getLayout();
cl.show(jPanelYaxInner, "cardYRef");
cl = (java.awt.CardLayout)jPanelYaxComp.getLayout();
cl.show(jPanelYaxComp, "cardYaxComp1"); // .setVisible(true);
} // if "Relative activities"
else { // not "Relative activities"
boolean includeSpecies = false; //only components in Y-axis
updateYcomp(includeSpecies);
updatingAxes = true;
}
if(dt.equalsIgnoreCase("Fraction")) { //Fraction
cl = (java.awt.CardLayout)jPanelYaxInner.getLayout();
cl.show(jPanelYaxInner, "cardYFract");
jLabelYFract.setText("Fractions for:");
cl = (java.awt.CardLayout)jPanelYaxComp.getLayout();
cl.show(jPanelYaxComp, "cardYaxComp1"); // .setVisible(true);
setOKButtonIcon("images/PlotFrctn16_32x32_transpBckgr.gif");
// change from non-Fraction to Faction:
// set a default component and set its conc. value
// select the 1st cation, or 1st solid, gas, aqu.
if(diag.compY < 0) {
for(int ic = 0; ic < cs.Na; ic++) {
if(ic != hPresent && Util.isCation(namn.identC[ic])
&& !namn.ident[ic].startsWith("NH") && !namn.ident[ic].startsWith("N(")) {
diag.compY = ic; break;
}
} // for ic
} // if compY < 0
if(diag.compY < 0 && cs.solidC >0) { // get the first solid component
diag.compY = (cs.Na - cs.solidC);
} // if compY < 0
if(diag.compY < 0) { // get a gas
for(int ic = 0; ic < cs.Na; ic++) {
if(Util.isGas(namn.identC[ic])) {diag.compY = ic; break;}
} // for ic
} // if compY < 0
if(diag.compY < 0) { // get an aqueous species
for(int ic = 0; ic < cs.Na; ic++) {
if(Util.isNeutralAqu(namn.identC[ic])) {diag.compY = ic; break;}
} // for ic
} // if compY < 0
if(diag.compY < 0) { //get a cation, even if it is ammonium
for(int ic = 0; ic < cs.Na; ic++) {
if(ic != hPresent && Util.isCation(namn.identC[ic])) {diag.compY = ic; break;}
} // for ic
} // if compY < 0
if(diag.compY < 0) {
int j=0;
if(diag.compX == 0 && jComboBoxYaxComp.getItemCount() >1) {j=1;}
for(int ic=0; ic < cs.Na; ic++) {
if(namn.identC[ic].equalsIgnoreCase(jComboBoxYaxComp.getItemAt(j).toString())) {
diag.compY = ic; break;
}
} //for ic
} // if compY < 0
// set the selected item
for(int j = 0; j < jComboBoxYaxComp.getItemCount(); j++) {
if(namn.identC[diag.compY].equalsIgnoreCase(jComboBoxYaxComp.getItemAt(j).toString())) {
jComboBoxYaxComp.setSelectedIndex(j); break;
}
} // for j
} // if "Fraction"
runPredomSED = 2; // flag for a SED diagram
} //if user selected a SED diagram
// -------------------------------------------------------------
// check for "%" in min/max Y-values
if(!dt.equalsIgnoreCase("Fraction")) { //not Fraction?
if(jTextFieldYmin.getText().contains("%") ||
jTextFieldYmax.getText().contains("%")) {
jTextFieldYmin.setText("-9");
jTextFieldYmax.setText("1");
}
} else {
jTextFieldYmax.setText("100 %");
jTextFieldYmin.setText("0 %");
resizeYMin();
resizeYMax();
enableYminYmax(false);
} // Fraction?
updateAxes(); // set concentration types
updatingAxes = false;
updateUseEhCheckBox();
updateDrawPHlineBox();
enableTemperature();
updateConcs(); // Change the concentration type and Min/Max values
resizeXMinMax();
resizeYMin(); resizeYMax();
if(pc.dbg) {System.out.println("--- diagramType_Click() -- ends");}
} // diagramType_Click()
/** Change the icon displayed by the OK-button.
* @param iconName the name of the file containing the icon in "gif" format */
private void setOKButtonIcon(String iconName) {
java.net.URL imgURL = this.getClass().getResource(iconName);
if (imgURL != null) {jButton_OK.setIcon(new javax.swing.ImageIcon(imgURL));}
else {System.out.println("--- Error: Could not load image = \""+iconName+"\"");}
} // setOKButtonIcon(iconName)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="enable Ymin/Ymax">
/** Enables or disables the Y-axes min and max boxes
* @param action if true, the Y-min and max boxes are enabled, if false they are disabled
*/
private synchronized void enableYminYmax(boolean action) {
enableYmin(action);
enableYmax(action);
} // enableYminYmax(b)
private synchronized void enableYmin(boolean action) {
if(action) {
jTextFieldYmin.setBackground(java.awt.Color.WHITE);
}
else { // do not enable
jTextFieldYmin.setBackground(backg);
}
jTextFieldYmin.setEditable(action);
jTextFieldYmin.setFocusable(action);
} // enableYmin(b)
private synchronized void enableYmax(boolean action) {
if(action) {
jTextFieldYmax.setBackground(java.awt.Color.WHITE);
}
else { // do not enable
jTextFieldYmax.setBackground(backg);
}
jTextFieldYmax.setEditable(action);
jTextFieldYmax.setFocusable(action);
} // enableYmax(b)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="focusLost() CLow/CHigh">
private void focusLostCLow() {
double w = readTextField(jTextFieldCLow);
if(w == -0.0) {w = 0;}
String t = Util.formatNum(w);
if(Double.parseDouble(t) != w) {jTextFieldCLow.setText(t);}
}
private void focusLostCHigh() {
double w = readTextField(jTextFieldCHigh);
if(w == -0.0) {w = 0;}
String t = Util.formatNum(w);
if(Double.parseDouble(t) != w) {jTextFieldCHigh.setText(t);}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="focusLost X/Y Max/Min">
private void focusLostXmax() {
double w = readTextField(jTextFieldXmax);
if(w == -0.0) {w = 0;}
String t = Util.formatNum(w); //String.valueOf(w);
if(Double.parseDouble(t) != w) {jTextFieldXmax.setText(t);}
resizeXMinMax();
updateConcs();
} // focusLostXmax()
private void focusLostXmin() {
double w = readTextField(jTextFieldXmin);
if(w == -0.0) {w = 0;}
String t = Util.formatNum(w);
if(Double.parseDouble(t) != w) {jTextFieldXmin.setText(t);}
resizeXMinMax();
updateConcs();
} // focusLostXmin()
private void focusLostYmax() {
if(!jTextFieldYmax.isEditable()) {return;}
double w = readTextField(jTextFieldYmax);
if(w == -0.0) {w = 0;}
String t = Util.formatNum(w);
if(Double.parseDouble(t) != w) {jTextFieldYmax.setText(t);}
resizeYMax();
updateConcs();
} // focusLostYmax()
private void focusLostYmin() {
if(!jTextFieldYmin.isEditable()) {return;}
double w = readTextField(jTextFieldYmin);
if(w == -0.0) {w = 0;}
String t = Util.formatNum(w);
if(Double.parseDouble(t) != w) {jTextFieldYmin.setText(t);}
resizeYMin();
updateConcs();
} // focusLostYmin()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="getConc_ComboConcType_Click()">
private void getConc_ComboConcType_Click() {
if(jComboBoxConcType.getSelectedIndex() < 0) {return;}
//if(pc.dbg) {System.out.println("getConc_ComboConcType_Click()");}
int k = jComboBoxConcType.getItemCount() -1;
if(jComboBoxConcType.getItemAt(k).toString().startsWith("?")) {
if(jComboBoxConcType.getSelectedIndex() == k) {jComboBoxConcType.setSelectedIndex(-1);}
jComboBoxConcType.removeItemAt(k);
}
String tn = jComboBoxConcType.getSelectedItem().toString();
String t0 = comboBoxConcType0;
boolean vary = tn.toLowerCase().contains("varied");
double w1 = readTextField(jTextFieldCLow);
double w2 = readTextField(jTextFieldCHigh);
boolean nowTot = tn.toLowerCase().startsWith("tot");
boolean nowLog = tn.toLowerCase().startsWith("log");
boolean now_pHpe = (tn.startsWith("pH") || tn.startsWith("pe"));
//boolean nowEh = tn.toLowerCase().startsWith("Eh");
boolean tot0 = t0.toLowerCase().startsWith("tot");
boolean log0 = t0.toLowerCase().startsWith("log");
boolean pHpe0 = (t0.startsWith("pH") || t0.startsWith("pe"));
boolean Eh0 = t0.toLowerCase().startsWith("Eh");
if(!vary) {
jTextFieldCHigh.setText(" ");
jTextFieldCHigh.setVisible(false);
jLabelTo.setText(" "); jLabelFrom.setText(" ");
} else { //vary
jTextFieldCHigh.setVisible(true);
jLabelTo.setText("to:"); jLabelFrom.setText("from:");
if(jTextFieldCHigh.getText().equals(" ")) {
if(nowTot) {
if(log0) {w2 = w1 +2;}
else if(pHpe0) {w2 = w1 -2;}
else {w2 = w1 +100;}
} //if nowTot
else { //now: log / pH /pe /Eh
if(log0 || pHpe0) {w2 = w1 +2;}
else if(Eh0) {
if(w1 >0) {w2 = -0.5;} else {w2 = +0.5;}
} else {
w2 = w1 * 100;
}
}
} //if text = " "
} //vary?
if(!t0.equalsIgnoreCase(tn)) { // conc. type has been changed
if(nowLog && tot0) {
if(vary && w2>0) {w2 = Math.log10(w2);} else {w2 = 0;}
if(w1>0) {w1 = Math.log10(readTextField(jTextFieldCLow));}
else {
if(vary && w2>0) {w1 = Math.log10(w2) -2d;} else {w1 = -6;}
}
} else if((nowLog && pHpe0) || (now_pHpe && log0)) {
w1 = -w1;
if(vary) {w2 = -w2;}
} else if(now_pHpe && tot0) {
if(w1>0) {w1 = -Math.log10(w1);}
if(vary && w2>0) {w2 = -Math.log10(w2);}
} else if(nowTot && log0) {
if(w1<20) {w1 = logToNoLog(w1);}
if(vary && w2<20) {w2 = logToNoLog(w2);}
} else if(nowTot && pHpe0) {
if(w1>-20) {w1 = logToNoLog(-w1);}
if(vary && w2>-20) {w2 = logToNoLog(-w2);}
} else if(nowTot && tot0) {
if(vary) {
if(Math.abs(w1) > 1e-10) {
if(w1 >0) {w2 = w1; w1 = 0;}
else if(w1 < 0) {w2 = 0;}
} else {if(w1 !=0) {w2 = Math.signum(w1)*0.01;} else {w2 = 0.01;}}
} else {
if(Math.abs(w1) < 1e-10) {w1 = w2;}
}
}
comboBoxConcType0 = tn;
} //if t0 != tn
if(vary && !runRevs) {
if(w2 < w1) {double w = w1; w1 = w2; w2 = w;}
}
if(!vary && nowLog
&& getConc_idx > (cs.Na - cs.solidC -1)) { // solid component
// if the concentration type starts with "log" and it is not varied, then it must be "log Ativity"
w1 = 0; // set log Activity for a solid = 0 (activity = 1)
}
jTextFieldCLow.setText(Util.formatNum(w1));
if(vary) {jTextFieldCHigh.setText(Util.formatNum(w2));}
jPanelConcInner.validate();
} //getConc_ComboConcType_Click()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="getConc_Unload()">
private void getConc_Unload() {
if(pc.dbg) {System.out.println("getConc_Unload()");}
jButton_OK.setEnabled(true);
jButton_Cancel.setEnabled(true);
jButtonSaveDef.setEnabled(true);
updateUseEhCheckBox();
updateDrawPHlineBox();
enableTemperature();
java.awt.CardLayout cl = (java.awt.CardLayout)jPanelConcs.getLayout();
cl.show(jPanelConcs, "panelCompConcList");
if(getConc_idx >= 0) {
String compConcText = setConcText(getConc_idx);
listCompConcModel.set(getConc_idx, compConcText);
jListCompConc.setSelectedIndex(getConc_idx);
}
// set Xmin/max, Ymin/max and conc. types in axes
// from the values given in the "Conc. List Box"
updateAxes();
resizeXMinMax(); resizeYMin(); resizeYMax();
jListCompConc.requestFocus();
if(getConc_idx >= 0) {
jListCompConc.setSelectedIndex(getConc_idx);
jListCompConc.ensureIndexIsVisible(getConc_idx);
}
getConc_idx = -1;
} // getConc_Unload()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="paintDiagrPanel">
private void paintDiagPanel(java.awt.Graphics g) {
// add tick marks to the diagram panel
java.awt.Graphics2D g2D = (java.awt.Graphics2D)g;
java.awt.Dimension ps = jPanelAxes.getSize();
g.setColor(java.awt.Color.BLACK);
// the length of the tick marks
int d = Math.min((int)(ps.getWidth() / 15),(int)(ps.getHeight() / 15));
for(int i=1; i<=5; i++) {
int y = (int)ps.getHeight() - (int)((double)i * ps.getHeight()/6);
g.drawLine(0,y,d,y);
}
int y = (int)ps.getHeight();
for(int i=1; i<=5; i++) {
int x = (int)((double)i * ps.getWidth()/6);
g.drawLine(x,y,x,(y-d));
}
} // paintDiagPanel(Graphics g)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="readDataFile()">
private boolean readDataFile(boolean dbg){
if(dbg) {System.out.println("readDataFile("+dbg+")");}
//--- create a ReadData instance
ReadDataLib rd;
try {rd = new ReadDataLib(dataFile);}
catch (ReadDataLib.DataFileException ex) {
MsgExceptn.exception(ex.getMessage()); return false;}
if(dbg) {
System.out.println("- - - - - - - - - - - - - - - - - - - - - - - - - - -");
System.out.println("Reading input data file \""+dataFile+"\"");
}
//--- read the chemical system (names, equilibrium constants, stoichiometry)
// report missing plot data as a warning (do not throw an exception)
boolean warn = true;
try {
ch = ReadChemSyst.readChemSystAndPlotInfo(rd, dbg, warn, System.out);
}
catch (ReadChemSyst.DataLimitsException ex) {
MsgExceptn.exception(ex.getMessage());
ch = null;}
catch (ReadChemSyst.ReadDataFileException ex) {
MsgExceptn.exception(ex.getMessage());
ch = null;}
catch (ReadChemSyst.PlotDataException ex) {}
catch (ReadChemSyst.ConcDataException ex) {
MsgExceptn.exception(ex.getMessage()+nl+Util.stack2string(ex));
ch = null;
}
if(ch == null) {
try {rd.close();}
catch (ReadDataLib.ReadDataLibException ex) {MsgExceptn.exception(ex.getMessage());}
MsgExceptn.showErrMsg(spana.MainFrame.getInstance(),
"Error while reading file"+nl+"\""+dataFile+"\"", 1);
return false;}
//--- set the references pointing to the instances of the storage classes
cs = ch.chemSystem;
namn = cs.namn;
diag = ch.diag;
dgrC = ch.diagrConcs;
componentConcType = new int[cs.Na];
//--- temperature written as a comment in the data file?
double w;
try {w = rd.getTemperature();}
catch (ReadDataLib.DataReadException ex) {
MsgExceptn.exception(nl+ex.getMessage());
w = 25.;
}
temperatureGivenInInputFile = !Double.isNaN(w);
if(Double.isNaN(w)) {w = 25;}
w = Math.min(1000., Math.max(-50, w));
diag.temperature = w;
jTextFieldT.setText(Util.formatNum(diag.temperature));
//--- pressure written as a comment in the data file?
try {w = rd.getPressure();}
catch (ReadDataLib.DataReadException ex) {
MsgExceptn.exception(nl+ex.getMessage());
w = 1.;
}
if(Double.isNaN(w)) {w = 1.;}
w = Math.min(10000., Math.max(1., w));
diag.pressure = w;
// get number of gases
nbrGases = 0;
for(int i=0; i < cs.Ms-cs.mSol; i++) {if(Util.isGas(namn.ident[i])) {nbrGases++;}}
// which components are "H+" and "e-"
hPresent = -1; ePresent = -1;
for(int i=0; i < cs.Na; i++) {
if(Util.isProton(namn.identC[i])) {hPresent = i; if(ePresent >-1) {break;}}
if(Util.isElectron(namn.identC[i])) {ePresent = i; if(hPresent >-1) {break;}}
}
for(int i=0; i < cs.nx; i++) {
if(Util.isProton(namn.ident[i+cs.Na])) {hPresent = i; if(ePresent >-1) {break;}}
if(Util.isElectron(namn.ident[i+cs.Na])) {ePresent = i; if(hPresent >-1) {break;}}
}
// is the plot information or concentrations missing?
plotAndConcsNotGiven = false;
if(diag.plotType < 0 || dgrC.hur[0] <1) {
// make sure a message box is displayed
plotAndConcsNotGiven = true;
diag.Eh = runUseEh; // use default
// set default plot type and X-axis component
DefaultPlotAndConcs.setDefaultPlot(cs, diag, dgrC);
// set default concentrations for each component
DefaultPlotAndConcs.setDefaultConcs(cs, dgrC, pd.kth);
DefaultPlotAndConcs.checkConcsInAxesAndMain(namn, diag, dgrC, dbg, pd.kth);
} // plot information or concentrations missing?
if(diag.title == null) {diag.title = "";} else {diag.title = Util.rTrim(diag.title);}
try {rd.close();}
catch (ReadDataLib.ReadDataLibException ex) {MsgExceptn.exception(ex.getMessage());}
if(dbg) {System.out.println("Finished reading the input data file");
System.out.println("- - - - - - - - - - - - - - - - - - - - - - - - - - -");
}
checkComponentsInAxes();
checkMainComponent();
checkInputConcs();
// make a backup copy of the original data
try {diag0 = (Chem.Diagr)diag.clone(); }
catch(CloneNotSupportedException ex) { MsgExceptn.exception("Error: "+ex.getMessage()); }
try {dgrC0 = (Chem.DiagrConcs)dgrC.clone(); }
catch(CloneNotSupportedException ex) { MsgExceptn.exception("Error: "+ex.getMessage()); }
return true;
} // readDataFile()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="readTextField (X/Y Min/Max)">
/** Returns a value contained in a text field, catching any errors
* @param textField the text field to read
* @return the value found in the text field, or Not_a_Number
* if the text field is not visible or if an error occurs.
*/
private double readTextField(javax.swing.JTextField textField) {
double w;
if(!textField.isVisible()) {w = 0.;}
else {
String t = textField.getText().trim();
if(t.length() <= 0) {return 0;}
if(t.endsWith("%")) {t = t.substring(0,t.length()-1).trim();}
try{w = Double.valueOf(t);}
catch(NumberFormatException ex) {
String type;
if(textField.getName().endsWith("Xmin")) {
type = "X-min";
try{w = Double.valueOf(oldTextXmin); textField.setText(oldTextXmin);}
catch (NumberFormatException ex2) {w = 0.;}
}
else if(textField.getName().endsWith("Xmax")) {
type = "X-max";
try{w = Double.valueOf(oldTextXmax); textField.setText(oldTextXmax);}
catch (NumberFormatException ex2) {w = 0.;}
}
else if(textField.getName().endsWith("Ymin")) {
type = "Y-min";
try{w = Double.valueOf(oldTextYmin); textField.setText(oldTextYmin);}
catch (NumberFormatException ex2) {w = 0.;}
}
else if(textField.getName().endsWith("Y-max")) {
type = "Y-max";
try{w = Double.valueOf(oldTextYmax); textField.setText(oldTextYmax);}
catch (NumberFormatException ex2) {w = 0.;}
}
else if(textField.getName().endsWith("CLow")) {
type = "C-low";
try{w = Double.valueOf(oldTextCLow); textField.setText(oldTextCLow);}
catch (NumberFormatException ex2) {w = 0.;}
}
else if(textField.getName().endsWith("CHigh")) {
type = "C-high";
try{w = Double.valueOf(oldTextCHigh); textField.setText(oldTextCHigh);}
catch (NumberFormatException ex2) {w = 0.;}
}
else if(textField.getName().endsWith("IonicStr")) {
type = "ionic strength";
try{w = Double.valueOf(oldTextI); textField.setText(oldTextI);}
catch (NumberFormatException ex2) {w = 0.;}
}
else if(textField.getName().endsWith("T")) {
type = "temperature";
try{w = Double.valueOf(oldTextT); textField.setText(oldTextT);}
catch (NumberFormatException ex2) {w = 0.;}
}
else {type = ""; w = 0.;}
String msg = "Error (NumberFormatException)";
if(type.trim().length() >0) {msg = msg+nl+"reading "+type;}
msg = msg +nl+"with text: \""+t+"\"";
System.out.println(LINE+nl+msg+nl+LINE);
javax.swing.JOptionPane.showMessageDialog(this, msg,
pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE);
}
}
return w;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="resize X/Y Max/Min ()">
private synchronized void resizeXMinMax() {
String t;
t = jTextFieldXmin.getText();
if(t == null || t.length() <= 1) {t = "m";}
jLabl1.setText(t);
jLabl1.invalidate();
t = jTextFieldXmax.getText();
if(t == null || t.length() <= 1) {t = "m";}
jLabl2.setText(t);
jLabl2.invalidate();
jPanelLabl.validate();
// find out how large can each field be
int m = jPanelXaxis.getWidth()-10; int h = m/2;
int ixMin = Math.max(jLabl1.getWidth()+10,20);
int ixMax = Math.max(jLabl2.getWidth()+10,20);
if(ixMin > h && ixMax > h) {ixMin = h; ixMax = h;} // both are wider than half the space available
else if((ixMin+ixMax) >= m) {
// the sum of both widths is larger than the total available,
// but one of them is smaller than half
if(ixMin > ixMax) {ixMin = m - ixMax;} else {ixMax = m - ixMin;}
}
java.awt.Dimension dL1 = new java.awt.Dimension(ixMin, jTextFieldXmin.getHeight());
java.awt.Dimension dL2 = new java.awt.Dimension(ixMax, jTextFieldXmax.getHeight());
jTextFieldXmin.setMaximumSize(dL1); jTextFieldXmax.setMaximumSize(dL2);
jTextFieldXmin.setPreferredSize(dL1); jTextFieldXmax.setPreferredSize(dL2);
jTextFieldXmin.invalidate(); jTextFieldXmin.invalidate();
jPanelXaxis.validate();
} // resizeXMinMax()
private synchronized void resizeYMin() {
if(!jTextFieldYmin.isEditable()) {return;}
//java.awt.CardLayout cl = (java.awt.CardLayout)jPanelConcs.getLayout();
//cl.show(jPanelConcs, "panelJLabl");
//new java.lang.Exception().printStackTrace();
String t = jTextFieldYmin.getText();
if(t == null || t.length() <= 1) {t="m";}
jLabl3.setText(t);
jLabl3.invalidate();
jPanelLabl.validate();
java.awt.Dimension dL1 = new java.awt.Dimension(Math.max(jLabl3.getWidth()+10,20), jTextFieldYmin.getHeight());
jTextFieldYmin.setMaximumSize(dL1);
jTextFieldYmin.setPreferredSize(dL1);
jTextFieldYmin.invalidate();
jPanelYmin.validate();
} // resizeYMin()
private synchronized void resizeYMax() {
if(!jTextFieldYmax.isEditable()) {return;}
String t = jTextFieldYmax.getText();
if(t == null || t.length() <= 1) {t="m";}
jLabl4.setText(t);
jLabl4.invalidate();
jPanelLabl.validate();
java.awt.Dimension dL1 = new java.awt.Dimension(Math.max(jLabl4.getWidth()+10,20), jTextFieldYmax.getHeight());
jTextFieldYmax.setMaximumSize(dL1);
jTextFieldYmax.setPreferredSize(dL1);
jTextFieldYmax.invalidate();
jPanelYmax.validate();
} // resizeYMax()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="runSedPredom()">
private boolean runSedPredom() {
// ===========================
// Make a SED/Predom diagram
// ===========================
if(pc.dbg) {System.out.println("runSedPredom()");}
if(MainFrame.pathSedPredom == null) {
MsgExceptn.exception("Programming error in runSedPredom(): \"pathSedPredom\" is null.");
return false;
}
pc.setPathDef(dataFile);
lastPlotFileName = jTextFieldDiagName.getText();
lastDataFileName = jTextFieldDataFile.getText();
String dir = pc.pathDef.toString();
if(dir.endsWith(SLASH)) {dir = dir.substring(0,dir.length()-1);}
if(dir.trim().length() >0) {
pltFile = new java.io.File(dir + SLASH + lastPlotFileName.concat(".plt"));
} else {pltFile = new java.io.File(lastPlotFileName.concat(".plt"));}
if(pltFile.exists() && (!pltFile.canWrite() || !pltFile.setWritable(true))) {
String msg = "Warning: Can NOT overwrite the plot file:"+nl+
" \""+pltFile.getName()+"\""+nl+
"Is this file (or folder) write-protected?"+nl+nl+
"Please choose another plot-file name.";
System.out.println(LINE+nl+msg+nl+LINE);
javax.swing.JOptionPane.showMessageDialog(this, msg,
pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE);
return false;
}
if(runPredomSED ==2) { // SED diagram
if(!Div.progSEDexists(new java.io.File(MainFrame.pathSedPredom))) {
javax.swing.JOptionPane.showMessageDialog(this, "Error: Program SED not found in path:"+nl+
"\""+MainFrame.pathSedPredom+"\""+nl+nl+
"The calculations can not be performed."+nl+nl+
"Please select a correct path in menu \"Preferences / General\"",
pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE);
return false;
}
oldProg = isOldSED();
}
else if(runPredomSED ==1) { // Predom diagram
if(!Div.progPredomExists(new java.io.File(MainFrame.pathSedPredom))) {
javax.swing.JOptionPane.showMessageDialog(this, "Error: Predom not found in path:"+nl+
"\""+MainFrame.pathSedPredom+"\""+nl+nl+
"The calculations can not be performed."+nl+nl+
"Please select a correct path in menu \"Preferences / General\"",
pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE);
return false;
}
if(diag.compMain < 0) { // check main chemical component
MsgExceptn.showErrMsg(this, "Programming error in runSedPredom(): diag.compMain < 0!", 1);
return false;
}
if(dgrC.hur[diag.compMain] != 4
&& (dgrC.hur[diag.compMain] == 1 && Math.abs(dgrC.cLow[diag.compMain]) <= 0 )) {
Object[] opt = {"Make the diagram anyway", "Cancel"};
String msg = "The concentration for the"+nl+
"main component ("+namn.identC[diag.compMain]+") is "+nl+
"less or equal to zero!";
System.out.println("----- "+msg);
int n= javax.swing.JOptionPane.showOptionDialog(this,msg,pc.progName,
javax.swing.JOptionPane.OK_CANCEL_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[1]);
if(n != javax.swing.JOptionPane.OK_OPTION) {
System.out.println("----- [Cancel]");
return false;
}
System.out.println("----- [Make the diagram anyway]");
}
oldProg = isOldPredom();
}
final String prog_name;
if(runPredomSED ==1) {
if(oldProg && Div.progExists(new java.io.File(MainFrame.pathSedPredom), "Predom2", "exe")) {
prog_name = "Predom2";
} else {
prog_name = "Predom";
}
} else if(runPredomSED ==2) {
prog_name= "SED";
} else {prog_name= "(error?)";}
// ===========================
// command-line options
// ===========================
java.util.ArrayList<String> options = new java.util.ArrayList<String>();
options.add("\"-d="+dataFile.getPath()+"\"");
options.add("\"-p="+pltFile.getPath()+"\"");
if(!Double.isNaN(diag.temperature)) {options.add("-t="+diag.temperature);}
if(!Double.isNaN(diag.ionicStrength) && diag.ionicStrength != 0) {
options.add("-i="+diag.ionicStrength);
if(!oldProg) {
if(runActCoeffsMethod >=0 && runActCoeffsMethod <=2) {options.add("-m="+runActCoeffsMethod);}
}
}
if(!Double.isNaN(pd.tolHalta) && pd.tolHalta != Chem.TOL_HALTA_DEF) {
options.add("-tol="+Math.min(1e-2,Math.max(pd.tolHalta, 1e-9)));
}
if(runPredomSED ==2 && runTbl) { // SED table output
options.add("-tbl");
if(!oldProg) {
if(pd.tblExtension != null && pd.tblExtension.length() >0) {options.add("-tble:"+pd.tblExtension);}
if(pd.tblFieldSeparator == '\u0009') {options.add("-tbls:\\t");}
else if(pd.tblFieldSeparator == ' ') {options.add("-tbls:\" \"");}
else {options.add("-tbls:"+pd.tblFieldSeparator);}
if(pd.tblCommentLineStart != null) {
if(pd.tblCommentLineStart.length() >0) {options.add("-tblcs:"+pd.tblCommentLineStart);}
else {options.add("-tblcs: ");} //if not given quotes (") are used as default
}
if(pd.tblCommentLineEnd != null) {
if(pd.tblCommentLineEnd.length() >0) {options.add("-tblce:"+pd.tblCommentLineEnd);}
else {options.add("-tblce: ");} //if not given quotes (") are used as default
}
}
}
if(runPredomSED ==2) { // SED diagram
runNbrStepsSED = (int)((float)jScrollBarSEDNbrP.getValue()/1f);
if(runNbrStepsSED != MainFrame.NSTEPS_DEF) {options.add("-n="+(runNbrStepsSED));}
if(diag.plotType == 1 && !oldProg) { // "fraction"
options.add("-thr="+(pd.fractionThreshold));
}
} else if(runPredomSED ==1) { // Predom diagram
if(runAqu) {options.add("-aqu");}
runNbrStepsPred = (int)((float)jScrollBarPredNbrP.getValue()/1f);
if(runNbrStepsPred != MainFrame.NSTEPS_DEF) {options.add("-n="+(runNbrStepsPred));}
if(runPHline) {options.add("-pH");}
}
if(runConcUnits != 0 && !oldProg) {options.add("-units="+(runConcUnits));}
if(runConcNottn != 0 && !oldProg) {
if(runConcNottn == 1) {options.add("-sci");}
else if(runConcNottn == 2) {options.add("-eng");}
}
if(runRevs) {options.add("-rev");}
if(pd.keepFrame) {
options.add("-keep");
if(!oldProg) {
if(pd.calcDbg) {options.add("-dbg");}
if(pd.calcDbgHalta != Chem.DBGHALTA_DEF) {options.add("-dbgH="+String.valueOf(pd.calcDbgHalta));}
}
} //if "keep"
args = new String[options.size()];
args = options.toArray(args);
final long pltFileDate0 = pltFile.lastModified();
MainFrame.getInstance().setCursorWait();
new javax.swing.SwingWorker<Void,Void>() {
@Override
protected Void doInBackground() throws Exception {
if(oldProg) {
String pSP = MainFrame.pathSedPredom;
if(pSP != null && pSP.endsWith(SLASH)) {pSP = pSP.substring(0,pSP.length()-1);}
final String prg;
if(pSP != null) {prg = pSP + SLASH + prog_name+".exe";} else {prg = prog_name+".exe";}
boolean waitForCompletion = true;
lib.huvud.RunProgr.runProgramInProcess(null,prg,args,waitForCompletion,
(pc.dbg || pd.calcDbg),pc.pathAPP);
return null;
}
if(!pd.jarClassLd) { // run calculations in a separate system process
boolean waitForCompletion = true;
lib.huvud.RunProgr.runProgramInProcess(MainFrame.getInstance(), prog_name+".jar", args,
waitForCompletion, (pc.dbg || pd.calcDbg), pc.pathAPP);
return null;
}
// ----- neither "old" programs, or ProgramData.jarClassLd:
// invoke the main class of the jar-file
// save the look-and-feel
javax.swing.LookAndFeel oldLaF = javax.swing.UIManager.getLookAndFeel();
if(pc.dbg) {System.out.println("--- oldLookAndFeel("+oldLaF.getName()+");");}
rj = new lib.huvud.RunJar();
// The "main" method of SED and Predom waits for the calculations to be finished..
// RunJar uses a separate thread (SwingWorker) to run the programs.
// Next statement will return when the jar-program ends
rj.runJarLoadingFile(MainFrame.getInstance(), prog_name+".jar", args, (pc.dbg || pd.calcDbg),
pc.pathAPP);
// reset the look-and-feel if needed
if(!oldLaF.getName().equals(javax.swing.UIManager.getLookAndFeel().getName())) {
try {
if(pc.dbg) {System.out.println("--- setLookAndFeel("+oldLaF.getName()+");");}
javax.swing.UIManager.setLookAndFeel(oldLaF);
}
catch (javax.swing.UnsupportedLookAndFeelException ex) {
System.out.println("--- setLookAndFeel: "+ex.getMessage());
}
}
// --- restore the Mac OS Dock icon
if(System.getProperty("os.name").startsWith("Mac OS")) {
String iconName = "images/Spana_icon_48x48.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
if (imgURL != null) {
java.awt.Image icon = new javax.swing.ImageIcon(imgURL).getImage();
try {
Class<?> c = Class.forName("com.apple.eawt.Application");
java.lang.reflect.Method m =
c.getDeclaredMethod("setDockIconImage",new Class[] { java.awt.Image.class });
Object i = c.newInstance();
Object paramsObj[] = new Object[]{icon};
m.invoke(i, paramsObj);
} catch (Exception e) {System.out.println("Error: "+e.getMessage());}
} else {
System.out.println("Error: Could not load image = \""+iconName+"\"");
}
} //---- Mac OS Dock Icon
return null;
} // doInBackground()
@Override protected void done(){
long pltFileDate = pltFile.lastModified();
if(pltFileDate <= pltFileDate0) {
String msg = "Apparently the program \""+prog_name+"\" has"+nl+
"failed the calculations, and the plot-file:"+nl+
" \""+pltFile.getName()+"\""+nl+
"has NOT been generated.";
if(pc.dbg || pd.calcDbg) {System.out.println(msg);}
javax.swing.JOptionPane.showMessageDialog(MainFrame.getInstance(), msg,
pc.progName, javax.swing.JOptionPane.INFORMATION_MESSAGE);
} else {
MainFrame.getInstance().displayPlotFile(pltFile.getPath(), null);
}
MainFrame.getInstance().setCursorDef();
} // done()
}.execute(); // SwingWorker returns inmediately, but it continues running...
return true;
} // runSedPredom()
/** returns true if the "old" Fortran program SED.exe exists
* in the executable-path, <u>and</u> if "SED.jar" is not found. False otherwise */
private static boolean isOldSED() {
if(MainFrame.pathSedPredom == null) {return false;}
java.io.File exePath = new java.io.File(MainFrame.pathSedPredom);
if(!exePath.exists()) {return false;}
if(Div.progExists(exePath, "SED","jar")) {return false;}
if(!System.getProperty("os.name").toLowerCase().startsWith("windows")) {
if(!Div.progExists(exePath, "SED","exe")) {return false;}
java.io.File f = new java.io.File(exePath.getPath() + java.io.File.separator + "SED.exe");
return f.length() >= 100000;
}
return false;
}
/** returns true if the "old" Fortran program Predom.exe (or Predom2.exe) exists
* in the executable-path, <u>and</u> if "Predom.jar" is not found. False otherwise */
private static boolean isOldPredom() {
if(MainFrame.pathSedPredom == null) {return false;}
java.io.File exePath = new java.io.File(MainFrame.pathSedPredom);
if(!exePath.exists()) {return false;}
if(Div.progExists(exePath, "Predom","jar")) {return false;}
if(!System.getProperty("os.name").toLowerCase().startsWith("windows")) {
if(!Div.progExists(exePath, "Predom","exe")) {
return Div.progExists(exePath, "Predom2","exe");
}
java.io.File f = new java.io.File(exePath.getPath() + java.io.File.separator + "Predom.exe");
return f.length() >= 100000;
}
return false;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="setConcText(component)">
/** Creates a text String describing the concentration
* (or range of concentration values) used in the diagram
* for chemical component "ic"
* @param ic the chemical component
* @return a descriptive text String */
private String setConcText(int ic) {
if(ic < 0 || ic >= cs.Na) {
return "? program error in \"setConcText\"; ic = "+String.valueOf(ic);}
String compConcText = "? unknown conc. type (" + namn.identC[ic] + ")";
int use_pHpe = 0;
if(dgrC.hur[ic] >= 4) { // "LA" or "LAV"
if(ic == hPresent) {use_pHpe =1;}
else if(ic == ePresent) {use_pHpe =2; if(runUseEh) {use_pHpe =3;}}
}
double x1, x2;
x1 = dgrC.cLow[ic]; x2 = dgrC.cHigh[ic];
if(use_pHpe == 1 || use_pHpe == 2) {x1 = -x1; x2 = -x2;}
else if(use_pHpe == 3) {
double fEh = (MainFrame.Rgas * ln10 * (diag.temperature +273.15)) / MainFrame.Faraday;
x1 = -x1 * fEh;
x2 = -x2 * fEh;
}
if(!runRevs && // Varied: concentration range?
(dgrC.hur[ic] == 2 || dgrC.hur[ic] == 3 || dgrC.hur[ic] == 5)) { // "TV", "LTV" or "LAV"
if(x2 < x1) {double w = x1; x1 = x2; x2 = w;}
}
String cLowText, cHighText;
cLowText = Util.formatDbl6(x1);
if(dgrC.hur[ic] == 2 || dgrC.hur[ic] == 3 || dgrC.hur[ic] == 5) { // varied
cHighText = Util.formatDbl6(x2);
} else {cHighText = " ";}
if(use_pHpe == 1) {compConcText = "pH ";}
else if(use_pHpe == 2) {compConcText = "pe ";}
else if(use_pHpe == 3) {compConcText = "Eh ";}
else if(dgrC.hur[ic] == 4 || dgrC.hur[ic] == 5) {// LA or LAV
if(Util.isGas(namn.identC[ic])) {
compConcText = "log P("+namn.identC[ic]+") ";
} else {
compConcText = "log activity ("+namn.identC[ic]+") ";
}
}
else if(dgrC.hur[ic] == 1 || dgrC.hur[ic] == 2) {// T or TV
compConcText = "Total conc. ("+namn.identC[ic]+") ";
}
else if(dgrC.hur[ic] == 3) {// LTV
compConcText = "log Total conc. ("+namn.identC[ic]+") ";
}
if(dgrC.hur[ic] == 2 || dgrC.hur[ic] == 3 || dgrC.hur[ic] == 5) {
// Varied: concentration range?
compConcText = compConcText + "varied from "+ cLowText +" to "+ cHighText;
} else {
compConcText = compConcText + "= "+ cLowText;
}
return compConcText;
} // setConcText(i)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="setUpFrame()">
private void setUpFrame() {
if(pc.dbg) {System.out.println("setUpFrame()");}
String datFileN = dataFile.getPath();
jTextFieldDataFile.setText(datFileN);
jTextFieldDataFile.setCaretPosition(datFileN.length());
String plotFileN;
if(lastDataFileName != null && lastDataFileName.equalsIgnoreCase(datFileN)
&& (lastPlotFileName != null && lastPlotFileName.length() >0)) {
plotFileN = lastPlotFileName;
} else {
String txt = dataFile.getName();
plotFileN = txt.substring(0,txt.length()-4);
}
jTextFieldDiagName.setText(plotFileN);
if(diag.title != null && diag.title.length() >0) {
jTextFieldTitle.setText(diag.title);
} else {jTextFieldTitle.setText("");}
Ycalc = -1;
// are "H+" or "e-" a complex?
// (need to know to fill-in diagram-types in combo box)
boolean e_Complex = false;
boolean h_Complex = false;
for(int i = cs.Na; i < cs.Ms; i++) {
if(Util.isProton(namn.ident[i])) {
h_Complex = true;
if(e_Complex) {break;}
}
if(Util.isElectron(namn.ident[i])) {
e_Complex = true;
if(h_Complex) {break;}
}
} // for i
// --- ionic strength
if(cs.nx <=0) { //for non-aqueous systems
jRadioButtonFixed.doClick();
diag.ionicStrength = 0;
jTextFieldIonicStr.setText("0");
}
loading = true;
// --- temperature
jTextFieldT.setText(Util.formatNum(diag.temperature));
if(Double.isNaN(diag.temperature)) {
jCheckBoxUseEh.setSelected(false);
jCheckBoxUseEh.setEnabled(jTextFieldT.isEnabled());
}
// --- set up lists: Main-comp, X-comp and Y-comp
jComboBoxMainComp.removeAllItems();
jComboBoxXaxComp.removeAllItems();
jComboBoxYaxComp.removeAllItems();
for(int i=0; i < cs.Na; i++) {
if(!Util.isWater(namn.identC[i])) {
if(!Util.isElectron(namn.identC[i]) && !Util.isProton(namn.identC[i])) {
jComboBoxMainComp.addItem(namn.identC[i]);
}
if(i < (cs.Na - cs.solidC) || cs.nx > 0) {
jComboBoxXaxComp.addItem(namn.identC[i]);
jComboBoxYaxComp.addItem(namn.identC[i]);
}
}
} // for i
// --- set available diagram types
jComboBoxDiagType.removeAllItems();
diagramType_doNothing = true;
if(jComboBoxMainComp.getItemCount()>0) {
jComboBoxDiagType.addItem("Predominance Area");
}
jComboBoxDiagType.addItem("Logarithmic");
if(pd.advancedVersion || diag.plotType == 7) {jComboBoxDiagType.addItem("log Activities");}
jComboBoxDiagType.addItem("Fraction");
if(cs.mSol > 0 || nbrGases > 0) {jComboBoxDiagType.addItem("log Solubilities");}
jComboBoxDiagType.addItem("Relative activities");
if(ePresent >=0 || e_Complex) {
if(runUseEh) {jComboBoxDiagType.addItem("Calculated Eh");}
else {jComboBoxDiagType.addItem("Calculated pe");}
}
if(hPresent >=0 || h_Complex) {jComboBoxDiagType.addItem("Calculated pH");}
if((pd.advancedVersion && hPresent >= 0 && hPresent < cs.Na)
|| diag.plotType == 8) {jComboBoxDiagType.addItem("H+ affinity spectrum");}
diagramType_doNothing = false;
// is a Predom diagram impossible? (e.g. in a system with only H+ and e-)
if(jComboBoxMainComp.getItemCount()<=0) {
if(diag.compMain >= 0 || diag.plotType == 0) {
diag.compMain = -1;
diag.plotType = 3; // log Concs.
diag.yLow = -9; diag.yHigh = 1;
}
}
// --- Y-axis
// --- set Ymin and Ymax
if(diag.plotType == 3) { // if "log conc."
if(!diag.inputYMinMax) {diag.yLow = -9; diag.yHigh = 1;}
} else if(diag.plotType == 2) { // if "log solubility"
if(cs.mSol < 1) { // no solids?
diag.plotType = 3; diag.yLow = -9; diag.yHigh = 1;
} else {
if(!diag.inputYMinMax) {diag.yLow = -16; diag.yHigh = 0;}
}
}
if((ePresent < 0 && !e_Complex && diag.plotType == 5) || //calc. pe
(hPresent < 0 && !h_Complex && diag.plotType == 6)) { //calc. pH
diag.plotType = 3;
diag.yLow = -9; diag.yHigh = 1;
}
jTextFieldYmin.setText(String.valueOf(diag.yLow));
jTextFieldYmax.setText(String.valueOf(diag.yHigh));
//--- make sure that diag.compX (and diag.compY) are >=0
if(diag.compX >= 0) {
int ic = diag.compX;
diag.compX = -1;
for(int j =0; j < jComboBoxXaxComp.getItemCount(); j++) {
if(namn.identC[ic].equalsIgnoreCase(jComboBoxXaxComp.getItemAt(j).toString())) {
diag.compX = ic; break;
}
} // for j
} // if compX >= 0
if(diag.compX < 0) { // nothing fits, get the 1st one in the list
for(int ic =0; ic < cs.Na; ic++) {
if(namn.identC[ic].equalsIgnoreCase(jComboBoxXaxComp.getItemAt(0).toString())) {
diag.compX = ic;
dgrC.cLow[ic] = -6;
dgrC.cHigh[ic] = 0.5;
if(dgrC.hur[ic] == 1 || dgrC.hur[ic] == 2 || dgrC.hur[ic] == 3) { // "T"
dgrC.hur[ic] = 3; // "LTV" = "log (Total conc.) varied"
} else { //not "T"
dgrC.hur[ic] = 5; // "LAV" = "log (activity) varied"
}
break;
}
} // for ic
} // if compX < 0
if(diag.compY >= 0) {
int ic = diag.compY;
diag.compY = -1;
for(int j =0; j < jComboBoxXaxComp.getItemCount(); j++) {
if(namn.identC[ic].equalsIgnoreCase(jComboBoxXaxComp.getItemAt(j).toString())) {
diag.compY = ic; break;
}
} // for j
if(diag.compY < 0) { // nothing fits, get the 1st one in the list
for(ic =0; ic < cs.Na; ic++) {
if(namn.identC[ic].equalsIgnoreCase(jComboBoxXaxComp.getItemAt(0).toString())) {
diag.compY = ic;
dgrC.cLow[ic] = -6;
dgrC.cHigh[ic] = 0.5;
if(dgrC.hur[ic] == 1 || dgrC.hur[ic] == 2 ||
dgrC.hur[ic] == 3) { // "T"
dgrC.hur[ic] = 3; // "LTV" = "log (Total conc.) varied"
} else { //not "T"
dgrC.hur[ic] = 5; // "LAV" = "log (activity) varied"
}
break;
}
} // for ic
} // if compY < 0
} // if compY >= 0
if(diag.compMain >= 0) {
int ic = diag.compMain;
diag.compMain = -1;
for(int j =0; j < jComboBoxMainComp.getItemCount(); j++) {
if(namn.identC[ic].equalsIgnoreCase(jComboBoxMainComp.getItemAt(j).toString())) {
diag.compMain = ic; break;
}
} // for j
if(diag.compMain < 0) { // something failed, get the 1st one in the list
for(ic =0; ic < cs.Na; ic++) {
if(namn.identC[ic].equalsIgnoreCase(jComboBoxMainComp.getItemAt(0).toString())) {
diag.compMain = ic; break;
}
} // for ic
} //if compMain <0
} // if compMain >= 0
//--- Set the X-axis component in the frame
for(int j = 0; j < jComboBoxXaxComp.getItemCount(); j++) {
if(namn.identC[diag.compX].equalsIgnoreCase(jComboBoxXaxComp.getItemAt(j).toString())) {
jComboBoxXaxComp.setSelectedIndex(j);
break;
}
} // for j
if((diag.plotType == 0 || diag.plotType == 1 || diag.plotType == 4) && diag.compY >=0) {
// Set the Y-axis component in the frame
for(int j = 0; j < jComboBoxYaxComp.getItemCount(); j++) {
if(namn.identC[diag.compY].equalsIgnoreCase(jComboBoxYaxComp.getItemAt(j).toString())) {
jComboBoxYaxComp.setSelectedIndex(j);
break;
}
} // for j
} //PREDOM
// set diagram type in the frame
String[] diagramType = {"Predominance Area","Fraction","log Solubilities","Logarithmic","Relative activities","Calculated pe","Calculated pH","log Activities","H+ affinity spectrum"};
for(int i = 0; i < jComboBoxDiagType.getItemCount(); i++) {
if(diagramType[diag.plotType].equalsIgnoreCase(jComboBoxDiagType.getItemAt(i).toString()) ||
(diagramType[diag.plotType].equalsIgnoreCase("Calculated pe") &&
jComboBoxDiagType.getItemAt(i).toString().equalsIgnoreCase("Calculated Eh"))) {
jComboBoxDiagType.setSelectedIndex(i); // = diagramType_Click();
break;
}
} // for i
// set the "main" component for PREDOM
if(diag.compMain >= 0) {
for(int i =0; i < jComboBoxMainComp.getItemCount(); i++) {
if(namn.identC[diag.compMain].equals(jComboBoxMainComp.getItemAt(i))) {
jComboBoxMainComp.setSelectedIndex(i);
break;
}
} // for i
}
if(pc.dbg) {System.out.println("setUpFrame() -- ends");}
} // setUpFrame()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="temperature & ionic strength">
/** Reads the ionic strength, writes the value (to make sure) in the text
* field, and enables/disables the activity coefficient and temperature fields */
private void validateIonicStrength() {
diag.ionicStrength = readTextField(jTextFieldIonicStr);
diag.ionicStrength = Math.min(1000,Math.max(diag.ionicStrength, -1));
ionicStrOld = diag.ionicStrength;
jTextFieldIonicStr.setText(Util.formatNum(diag.ionicStrength));
if(diag.ionicStrength == 0) {
jComboBoxActCoeff.setVisible(false);
jLabelModel.setVisible(false);
} else {
if(pd.advancedVersion) {
jLabelModel.setVisible(true);
jComboBoxActCoeff.setVisible(true);
}
}
enableTemperature();
} // validateIonicStrength()
/** Reads the temperature and stores it in <code>diag.temperature</code>.
* The temperature is written (to make sure) in the text field.
* @see lib.kemi.chem.Chem.Diagr#temperature diag.temperature */
private void validateTemperature() {
if(jTextFieldT.getText().length() <=0) {return;}
diag.temperature = readTextField(jTextFieldT);
diag.temperature = Math.min(1000,Math.max(diag.temperature, -50));
jTextFieldT.setText(Util.formatNum(diag.temperature));
} // validateTemperature()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="updateAxes()">
/** Sets the Axes: Xmin/max, Ymin/max and conc-types, from
* the values given in the "Concentration List Box" */
private void updateAxes() {
if(loading) {return;}
if(pc.dbg) {System.out.println("updateAxes()");}
double fEh;
// -----------------------------------
// 1st set permissible conc-types for X/Y axes
int x0 = jComboBoxXaxType.getSelectedIndex();
int ix4 = 4;
if(diag.compX == hPresent) {ix4 = 6;}
else if(diag.compX == ePresent) {
ix4 = 8;
if(runUseEh) {ix4 = 10;}
} else if(Util.isGas(namn.identC[diag.compX])) {ix4 = 12;} // "log P varied"
int iy4 = 4;
if(diag.compY >= 0) {
if(diag.compY == hPresent) {iy4 = 6;} else
if(diag.compY == ePresent) {
iy4 = 8;
if(runUseEh) {iy4 = 10;}
} else
if(Util.isGas(namn.identC[diag.compY])) {iy4 = 12;} // "log P varied"
} // if compY >=0
updatingAxes = true;
jComboBoxXaxType.removeAllItems();
if(runPredomSED == 1) { // Predom
int y0 = jComboBoxYaxType.getSelectedIndex();
jComboBoxXaxType.addItem(concTypes[ix4]); //log (activity) varied (or pH,pe,Eh)
jComboBoxXaxType.addItem(concTypes[2]); //log (Total conc.) varied
jComboBoxYaxType.removeAllItems();
jComboBoxYaxType.addItem(concTypes[iy4]); //log (activity) varied (or pH,pe,Eh)
jComboBoxYaxType.addItem(concTypes[2]); //log (Total conc.) varied
if(y0 >= 0 && y0 < jComboBoxYaxType.getItemCount()) {
jComboBoxYaxType.setSelectedIndex(y0);
} else {
jComboBoxYaxType.setSelectedIndex(-1);
}
} else { // SED
jComboBoxXaxType.addItem(concTypes[ix4]); //log (activity) varied (or pH,pe,Eh)
jComboBoxXaxType.addItem(concTypes[2]); //log (Total conc.) varied
jComboBoxXaxType.addItem(concTypes[1]); //Total conc. varied
} // if run Predom
if(x0 >= 0 && x0 < jComboBoxXaxType.getItemCount()) {
jComboBoxXaxType.setSelectedIndex(x0);
} else {
jComboBoxXaxType.setSelectedIndex(-1);
}
// -----------------------------------
// check the conc-type
// if the user changes a component in an axis,
// the conc-type might be wrong (not varied)
// or Eh should be used instead of pe
// ---------
// X-axis:
// ---------
// set the concentration to "varied"
int use_pHpe = 0; int jc;
if(dgrC.hur[diag.compX] == 4 || dgrC.hur[diag.compX] == 5) { //"LA" or "LAV"
// set right type (pH/pe/Eh/P)
if(diag.compX == hPresent) {use_pHpe = 1;}
else if(diag.compX == ePresent) {use_pHpe = 2; if(runUseEh) {use_pHpe = 3;}}
else if(Util.isGas(namn.identC[diag.compX])) {use_pHpe = 4;}
jc = 4 + use_pHpe*2;
componentConcType[diag.compX] = jc;
} else if(dgrC.hur[diag.compX] == 1
|| dgrC.hur[diag.compX] == 2 || dgrC.hur[diag.compX] == 3) { //"T", "TV" or "LTV"
if(runPredomSED != 1 && // not Predom and
(dgrC.hur[diag.compX] != 3 && dgrC.hur[diag.compX] != 4 &&
dgrC.hur[diag.compX] != 5)) { // no "L"
componentConcType[diag.compX] = 1; // Total conc. varied
} else {
componentConcType[diag.compX] = 2; // log Total conc. varied
if(dgrC.hur[diag.compX] != 3) { // not "LTV"
dgrC.cLow[diag.compX] = Math.max(-50, Math.log10(Math.max(1e-51, Math.abs(dgrC.cLow[diag.compX]))));
dgrC.cHigh[diag.compX] = Math.max(-45, Math.log10(Math.max(1e-46, Math.abs(dgrC.cHigh[diag.compX]))));
}
}
} // if "LA" or "T.."
boolean mustChange = true;
for(int j = 0; j < jComboBoxXaxType.getItemCount(); j++) {
if(concTypes[componentConcType[diag.compX]].equals(jComboBoxXaxType.getItemAt(j))) {
jComboBoxXaxType.setSelectedIndex(j);
mustChange = false;
break;
}
} // for j
if(pc.dbg) {System.out.println(" X-mustChange="+mustChange);}
if(mustChange) {
// set default values
jComboBoxXaxType.setSelectedIndex(1); // default is: log Tot-conc varied
if(diag.compX == ePresent) {
if(dgrC.hur[diag.compX] != 4 && dgrC.hur[diag.compX] != 5) { // not "A"
dgrC.cLow[diag.compX] = -17;
dgrC.cHigh[diag.compX] = 17;
jComboBoxXaxType.setSelectedIndex(0);
}
}
else
if(diag.compX == hPresent) {
if(dgrC.hur[diag.compX] != 4 && dgrC.hur[diag.compX] != 5) { // not "A"
dgrC.cLow[diag.compX] = -12;
dgrC.cHigh[diag.compX] = -1;
jComboBoxXaxType.setSelectedIndex(0);
}
}
} // if mustChange
for(int j=0; j < concTypes.length; j++) {
if(concTypes[j].equalsIgnoreCase(jComboBoxXaxType.getSelectedItem().toString())) {
int j2 = j;
if(j2 > 4) {j2 = 4;}
dgrC.hur[diag.compX] = j2+1;
componentConcType[diag.compX] = j;
break;
} // if equal
} // for j
if(Double.isNaN(dgrC.cHigh[diag.compX])) {
if(dgrC.hur[diag.compX] == 3 || dgrC.hur[diag.compX] == 5) { // log scale
if(dgrC.cLow[diag.compX] <-1) {
dgrC.cHigh[diag.compX] = dgrC.cLow[diag.compX]+1;
} else {
dgrC.cHigh[diag.compX] = dgrC.cLow[diag.compX]-1;
}
} else { // tot-conc.
if(dgrC.cLow[diag.compX] ==0) {
dgrC.cHigh[diag.compX] = 0.1;
} else {
dgrC.cHigh[diag.compX] = dgrC.cLow[diag.compX];
dgrC.cLow[diag.compX] = 0;
}
}
}
TwoDoubles td = new TwoDoubles(dgrC.cLow[diag.compX], dgrC.cHigh[diag.compX]);
checkForEqual(td);
dgrC.cLow[diag.compX] = td.x1; dgrC.cHigh[diag.compX] = td.x2;
double w, w1, w2;
fEh = (MainFrame.Rgas * ln10 * (diag.temperature +273.15)) / MainFrame.Faraday;
w1 = dgrC.cLow[diag.compX]; w2 = dgrC.cHigh[diag.compX];
if(use_pHpe == 1 || use_pHpe == 2) {w1 = -w1; w2 = -w2;}
else if(use_pHpe == 3) {
w1 = -w1 * fEh;
w2 = -w2 * fEh;
}
if(!runRevs) {if(w2 < w1) {w = w1; w1 = w2; w2 = w;}}
jTextFieldXmin.setText(Util.formatNum(w1));
jTextFieldXmax.setText(Util.formatNum(w2));
if(runPredomSED != 1) {// not Predom
if(jComboBoxXaxType.getSelectedIndex() > -1) {
xAxisType0 = jComboBoxXaxType.getSelectedItem().toString();
}
if(jComboBoxYaxType.getSelectedIndex() > -1) {
yAxisType0 = jComboBoxYaxType.getSelectedItem().toString();
}
updatingAxes = false;
if(pc.dbg) {System.out.println("updateAxes() - ends");}
return;
}
//---- for Predom diagrams:
// ---------
// Y-axis:
// ---------
// set the concentration to "varied"
use_pHpe = 0;
if(dgrC.hur[diag.compY] == 4 || dgrC.hur[diag.compY] == 5) { //"LA" or "LAV"
// set right type (pH/pe/Eh/P)
if(diag.compY == hPresent) {use_pHpe = 1;}
else if(diag.compY == ePresent) {use_pHpe = 2; if(runUseEh) {use_pHpe = 3;}}
else if(Util.isGas(namn.identC[diag.compY])) {use_pHpe = 4;}
jc = 4 + use_pHpe*2;
componentConcType[diag.compY] = jc;
} // "LA."
else if(dgrC.hur[diag.compY] == 1 || dgrC.hur[diag.compY] == 2
|| dgrC.hur[diag.compY] == 3) { //"T", "TV" or "LTV"
componentConcType[diag.compY] = 2; // log Total conc. varied
if(dgrC.hur[diag.compY] != 3) { // not "LTV"
dgrC.cLow[diag.compY] = Math.max(-50, Math.log10(Math.max(1e-51, Math.abs(dgrC.cLow[diag.compY]))));
dgrC.cHigh[diag.compY] = Math.max(-45, Math.log10(Math.max(1e-46, Math.abs(dgrC.cHigh[diag.compY]))));
}
}
mustChange = true;
for(int j = 0; j < jComboBoxYaxType.getItemCount(); j++) {
if(concTypes[componentConcType[diag.compY]].equals(jComboBoxYaxType.getItemAt(j))) {
jComboBoxYaxType.setSelectedIndex(j);
mustChange = false;
break;
}
} // for j
if(pc.dbg) {System.out.println(" Y-mustChange="+mustChange);}
if(mustChange) { // set default values
jComboBoxYaxType.setSelectedIndex(1); // default is: log Tot-conc varied
if(diag.compY == ePresent) {
if(dgrC.hur[diag.compY] != 4 && dgrC.hur[diag.compY] != 5) { // not "A"
dgrC.cLow[diag.compY] = -17;
dgrC.cHigh[diag.compY] = 17;
jComboBoxYaxType.setSelectedIndex(0);
}
}
else if(diag.compY == hPresent) {
if(dgrC.hur[diag.compY] != 4 && dgrC.hur[diag.compY] != 5) { // not "A"
dgrC.cLow[diag.compY] = -12;
dgrC.cHigh[diag.compY] = -1;
jComboBoxYaxType.setSelectedIndex(0);
}
}
} // if mustChange
for(int j=0; j < concTypes.length; j++) {
if(concTypes[j].equalsIgnoreCase(jComboBoxYaxType.getSelectedItem().toString())) {
int j2 = j;
if(j2 > 4) {j2 = 4;}
dgrC.hur[diag.compY] = j2+1;
componentConcType[diag.compY] = j;
break;
} // if equal
} // for j
if(Double.isNaN(dgrC.cHigh[diag.compY])) {
if(dgrC.cLow[diag.compY] <-1) {
dgrC.cHigh[diag.compY] = dgrC.cLow[diag.compY]+1;
} else {
dgrC.cHigh[diag.compY] = dgrC.cLow[diag.compY]-1;
}
}
td = new TwoDoubles(dgrC.cLow[diag.compY], dgrC.cHigh[diag.compY]);
checkForEqual(td);
dgrC.cLow[diag.compY] = td.x1;
dgrC.cHigh[diag.compY] = td.x2;
w1 = dgrC.cLow[diag.compY]; w2 = dgrC.cHigh[diag.compY];
if(use_pHpe == 1 || use_pHpe == 2) {w1 = -w1; w2 = -w2;}
else if(use_pHpe == 3) {
fEh = (MainFrame.Rgas * ln10 * (diag.temperature +273.15)) / MainFrame.Faraday;
w1 = -w1 * fEh;
w2 = -w2 * fEh;
}
if(!runRevs) {if(w2 < w1) {w = w1; w1 = w2; w2 = w;}}
jTextFieldYmin.setText(Util.formatDbl6(w1));
jTextFieldYmax.setText(Util.formatDbl6(w2));
// -----------------------------------
updateConcList();
if(jComboBoxXaxType.getSelectedIndex() > -1) {
xAxisType0 = jComboBoxXaxType.getSelectedItem().toString();
}
if(jComboBoxYaxType.getSelectedIndex() > -1) {
yAxisType0 = jComboBoxYaxType.getSelectedItem().toString();
}
updatingAxes = false;
if(pc.dbg) {System.out.println("updateAxes() - ends");}
} // updateAxes()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="updateConcList()">
/** Displays the concentration for each component in the list:
* jScrollPaneCompConcList / jListCompConc */
private void updateConcList() {
if(pc.dbg) {System.out.println("updateConcList()");}
listCompConcModel.clear();
String compConcText;
for(int i = 0; i < cs.Na; i++) {
//if(Util.isWater(namn.identC[i])) {continue;}
compConcText = setConcText(i);
listCompConcModel.addElement(compConcText);
} // for i = 0 to ca.Na-1
jListCompConc.clearSelection();
} // updateConcList()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="updateConcs()">
/** For the components in the axes: change the conc-type (<code>dgrC.hur<code>) and Min/Max values
* (<code>dgrC.cLow</code> and <code>dgrC.cHigh</code>) to those seen in the form.
* If PREDOM diagram: check that only components in the axes have concentrations varied. */
private void updateConcs(){
if(loading) {return;}
if(pc.dbg) {System.out.println("updateConcs()");}
int j2;
// --------
// X-axis
// --------
if(jComboBoxXaxType.getSelectedIndex() >= 0 &&
jComboBoxXaxType.getSelectedItem() != null) {
String t = jComboBoxXaxType.getSelectedItem().toString();
for(int j = 0; j < concTypes.length; j++) {
if(t.equals(concTypes[j])) {
j2=j+1;
if(j2>5) {j2=5;}
dgrC.hur[diag.compX] = j2;
break;
}
} // for j
}
// make sure we got something useful
int use_pHpe = 0;
if(dgrC.hur[diag.compX] ==4 || dgrC.hur[diag.compX] ==5) { // LA or LAV
if(!Util.isGas(namn.identC[diag.compX])) {
if(diag.compX == hPresent) {use_pHpe =1;}
else if(diag.compX == ePresent) {use_pHpe =2; if(runUseEh) {use_pHpe =3;}}
}
} // if LA or LAV
double fEh, x1, x2;
fEh = (MainFrame.Rgas * ln10 * (diag.temperature +273.15))/MainFrame.Faraday;
x1 = readTextField(jTextFieldXmin);
if(use_pHpe ==1 || use_pHpe == 2) {x1 = -x1;}
else if(use_pHpe == 3) {
x1 = -x1 / fEh;
}
x2 = readTextField(jTextFieldXmax);
if(use_pHpe ==1 || use_pHpe == 2) {x2 = -x2;}
else if(use_pHpe == 3) {
x2 = -x2 / fEh;
}
dgrC.cLow[diag.compX] = x1 + Math.signum(x1) * Math.abs(x1) * 1e-14;
dgrC.cHigh[diag.compX] = x2 + Math.signum(x2) * Math.abs(x2) * 1e-14;
// --------
// Y-axis
// --------
if(runPredomSED != 1) { //not Predom (i.e., for SED)
updateConcList();
diag.yHigh = readTextField(jTextFieldYmax);
diag.yLow = readTextField(jTextFieldYmin);
if(pc.dbg) {System.out.println("updateConcs() -- end");}
return;
} // for SED
else {
if(jComboBoxYaxType.getSelectedIndex() >= 0
&& jComboBoxYaxType.getSelectedItem() != null) {
String t = jComboBoxYaxType.getSelectedItem().toString();
for(int j = 0; j < concTypes.length; j++) {
if(t.equals(concTypes[j])) {
j2=j+1; if(j2>5) {j2=5;}
dgrC.hur[diag.compY] = j2;
break;
}
} // for j
}
// make sure we got something useful
use_pHpe = 0;
if(dgrC.hur[diag.compY] == 4 || dgrC.hur[diag.compY] == 5) { // LA or LAV
if(!Util.isGas(namn.identC[diag.compY])) {
if(diag.compY == hPresent) {use_pHpe =1;}
else if(diag.compY == ePresent) {use_pHpe =2; if(runUseEh) {use_pHpe =3;}}
}
} // if LA or LAV
fEh = (MainFrame.Rgas * ln10 * (diag.temperature +273.15))/MainFrame.Faraday;
x1 = readTextField(jTextFieldYmin);
if(use_pHpe ==1 || use_pHpe == 2) {x1 = -x1;}
else if(use_pHpe == 3) {x1 = -x1 / fEh;}
x2 = readTextField(jTextFieldYmax);
if(use_pHpe ==1 || use_pHpe == 2) {x2 = -x2;}
else if(use_pHpe == 3) {x2 = -x2 / fEh;}
dgrC.cLow[diag.compY] = x1 + Math.signum(x1) * Math.abs(x1) * 1e-14;
dgrC.cHigh[diag.compY] = x2 + Math.signum(x2) * Math.abs(x2) * 1e-14;
checkInputConcs();
updateConcList();
} // for Predom
if(pc.dbg) {System.out.println("updateConcs() -- end");}
} // updateConcs()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="updateDrawPHlineBox()">
/** sets Eh check box visible and enabled/disabled */
private void updateDrawPHlineBox() {
if(loading) {return;}
if(pc.dbg) {System.out.println("updateDrawPHlineBox()");}
jCheckBoxDrawPHline.setVisible(false);
if(ePresent < 0 || ePresent >= cs.Na || hPresent < 0 || hPresent >= cs.Na) {return;}
if(ePresent < cs.Na && dgrC.hur[ePresent] == 5
&& hPresent < cs.Na && dgrC.hur[hPresent] == 5
&& (jComboBoxDiagType.getSelectedIndex() >=0 &&
(jComboBoxDiagType.getSelectedItem().toString().equals("Predominance Area"))))
{
jCheckBoxDrawPHline.setVisible(true);
jCheckBoxDrawPHline.setSelected(runPHline);
}
} // updateDrawPHlineBox()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="updateUseEhCheckBox()">
/** sets Eh check box visible and enabled/disabled */
private void updateUseEhCheckBox() {
if(loading) {return;}
if(pc.dbg) {System.out.println("updateUseEhCheckBox()");}
if(ePresent < 0) {
jCheckBoxUseEh.setVisible(false);
return;
} else {
jCheckBoxUseEh.setVisible(true);
}
boolean enableEhCheckBox = false;
if(!Double.isNaN(diag.temperature) &&
((jComboBoxDiagType.getSelectedIndex() >=0 &&
(jComboBoxDiagType.getSelectedItem().toString().equalsIgnoreCase("calculated pe")
|| jComboBoxDiagType.getSelectedItem().toString().equalsIgnoreCase("calculated Eh")))
|| (ePresent < cs.Na && dgrC.hur[ePresent] == 4)
|| (ePresent < cs.Na && dgrC.hur[ePresent] == 5)))
{
enableEhCheckBox = true;
}
jCheckBoxUseEh.setEnabled(enableEhCheckBox);
if(enableEhCheckBox) {
jCheckBoxUseEh.setText("<html>use <u>E</u>h for e-</html>");
} else {
jCheckBoxUseEh.setText("use Eh for e-");
}
if(Double.isNaN(diag.temperature)) {
jCheckBoxUseEh.setSelected(false);
jCheckBoxUseEh.setEnabled(jTextFieldT.isEnabled());
} else {
jCheckBoxUseEh.setSelected(runUseEh);
}
} // updateUseEhCheckBox()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="enableTemperature()">
/** enable temperature?
* If the temperature is given in the input file, then it is not enabled.
* If the normal/advanced preference is "normal", then it is not enabled.
*/
private void enableTemperature() {
if(pc.dbg) {System.out.println("enableTemperature()");}
boolean enableTemp = true;
if(temperatureGivenInInputFile || !pd.advancedVersion) {
enableTemp = false;
} else {
if(diag.ionicStrength == 0) {enableTemp = false;}
if(runUseEh && ePresent >= 0
&& ((jComboBoxDiagType.getSelectedIndex() >=0
&& (jComboBoxDiagType.getSelectedItem().toString().equalsIgnoreCase("calculated pe")
|| jComboBoxDiagType.getSelectedItem().toString().equalsIgnoreCase("calculated Eh")))
|| (ePresent < cs.Na && dgrC.hur[ePresent] ==4)
|| (ePresent < cs.Na && dgrC.hur[ePresent] ==5))) {
enableTemp = true;
if(pc.dbg) {System.out.println(" use Eh = true, enableTemp = true.");}
}
if(ePresent >= 0 && ePresent < cs.Na) { // is it an pe/pH (Pourbaix) diagram?
if(runPredomSED == 1) {
if((dgrC.hur[ePresent] == 4 || dgrC.hur[ePresent] == 5)
&& (hPresent >= 0 && hPresent < cs.Na)) { // pe varied and hPresent
if(dgrC.hur[hPresent] == 4 || dgrC.hur[hPresent] == 5) { // pH varied
boolean pHinAxis = false;
boolean EhInAxis = false;
if(jComboBoxXaxComp.getSelectedIndex() >=0 &&
jComboBoxXaxComp.getSelectedItem().toString().equalsIgnoreCase(namn.identC[hPresent])) {pHinAxis = true;}
if(jComboBoxYaxComp.getSelectedIndex() >=0 &&
jComboBoxYaxComp.getSelectedItem().toString().equalsIgnoreCase(namn.identC[hPresent])) {pHinAxis = true;}
if(jComboBoxXaxComp.getSelectedIndex() >=0 &&
jComboBoxXaxComp.getSelectedItem().toString().equalsIgnoreCase(namn.identC[ePresent])) {EhInAxis = true;}
if(jComboBoxYaxComp.getSelectedIndex() >=0 &&
jComboBoxYaxComp.getSelectedItem().toString().equalsIgnoreCase(namn.identC[ePresent])) {EhInAxis = true;}
if(pHinAxis && EhInAxis) { // pe/pH diagram
enableTemp = true;
if(pc.dbg) {System.out.println(" Pourbaix diagr., enableTemp = true.");}
}
} // pH varied
} // pe varied and hPresent
} // if Predom
} // if ePresent
} // if pd.advancedVersion
jTextFieldT.setText(Util.formatNum(diag.temperature));
jLabelT.setEnabled(enableTemp);
jTextFieldT.setEnabled(enableTemp);
jLabelTC.setEnabled(enableTemp);
} // enableTemperature()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="updateYcomp(species)">
/** Set a list of Component/Species names on Y-axis combo box.
* For relative activity diagrams: both components and reaction products must be
* in the list, which is accomplished by setting species = true.
* @param includeAllSpecies set to true if the combo box must list both component
* names and all species */
private void updateYcomp(boolean includeAllSpecies) {
if(pc.dbg) {System.out.println("updateYcomp("+includeAllSpecies+")");}
int jOld = jComboBoxYaxComp.getSelectedIndex();
updatingAxes = true;
jComboBoxYaxComp.removeAllItems();
boolean axisCompAdd;
for(int i = 0; i < cs.Na; i++) {
axisCompAdd = true;
if(Util.isWater(namn.identC[i])) {axisCompAdd = false;}
// is this component solid or soluble ?
if(i > (cs.Na - cs.solidC -1)) { // solid component
// Solid component and no soluble complexes?
// then do not add to Y-axis-list
if(cs.nx <= 0) {axisCompAdd = false;}
}
if(axisCompAdd) {jComboBoxYaxComp.addItem(namn.identC[i]);}
} // for i
if(includeAllSpecies) {
for(int i = 0; i < (cs.nx + cs.mSol); i++ ) {
axisCompAdd = true;
if(Util.isWater(namn.ident[i+cs.Na])) {axisCompAdd = false;}
if(axisCompAdd) {jComboBoxYaxComp.addItem(namn.ident[i+cs.Na]);}
} // for i
} // if species
if(jOld >= jComboBoxYaxComp.getItemCount()) {jOld = 0;}
jComboBoxYaxComp.setSelectedIndex(jOld);
updatingAxes = false;
} // updateYcomp
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="comboBoxAxisType">
/** Sets new values in the "textFieldMin" and "textFieldMax" of an axis,
* from the type of concentration in the axis in the combo box.
* The type is either "pH varied" or "log (Tot.conc.) varied" or something like that.
*
* @param axisTypeNow
* @param axisTypeBefore
* @param textFieldMin a text field whose value will be changed
* @param textFieldMax a text field whose value will be changed
*/
private void comboBoxAxisType(String axisTypeNow, String axisTypeBefore,
javax.swing.JTextField textFieldMin, javax.swing.JTextField textFieldMax) {
if(axisTypeNow.equalsIgnoreCase(axisTypeBefore)) {return;}
double valueMin = readTextField(textFieldMin);
if(Double.isNaN(valueMin)) {valueMin = 0;}
double valueMax = readTextField(textFieldMax);
if(Double.isNaN(valueMax)) {valueMax = 0;}
double valueMinNew, valueMaxNew;
// --- set default values
if(axisTypeNow.startsWith("Tot")) {valueMinNew = 1e-6; valueMaxNew = 1;}
else if(axisTypeNow.startsWith("pH")) {valueMinNew = 1; valueMaxNew = 12;}
else if(axisTypeNow.startsWith("pe")) {valueMinNew = -17; valueMaxNew = 17;}
else if(axisTypeNow.startsWith("Eh")) {valueMinNew = -1; valueMaxNew = 1;}
else {valueMinNew = -6; valueMaxNew = 0;} // should start with "log"
// ---
if(axisTypeNow.startsWith("log")) {
if(axisTypeBefore.startsWith("log")) {
if(valueMin >= -10 && valueMin <=2) {valueMinNew = valueMin;}
if(valueMax >= -10 && valueMax <=2) {valueMaxNew = valueMax;}
} else if(axisTypeBefore.startsWith("Tot")) {
if(valueMin >0) {valueMinNew = Math.log10(valueMin);}
if(valueMax >0) {valueMaxNew = Math.log10(valueMax);}
} else if(axisTypeNow.startsWith("log (Tot") && axisTypeBefore.startsWith("pH")) {
if(valueMax <= 14) {valueMinNew = -valueMax;}
if(valueMin >= 0) {valueMaxNew = -valueMin;}
}
} else if(axisTypeNow.startsWith("Tot")) {
if(axisTypeBefore.startsWith("log")) {
if(valueMin <= 1) {valueMinNew = logToNoLog(valueMin);}
if(valueMax <= 2) {valueMaxNew = logToNoLog(valueMax);}
} else if(axisTypeBefore.startsWith("pH")) {
if(valueMax >= 0 && valueMax <= 14) {valueMinNew = logToNoLog(-valueMax);}
if(valueMin >= 0 && valueMin <= 14) {valueMaxNew = logToNoLog(-valueMin);}
}
} else if(axisTypeNow.startsWith("pH")) {
if(axisTypeBefore.startsWith("Tot")) {
if(valueMax >0) {valueMinNew = -Math.log10(valueMax);}
if(valueMin >0) {valueMaxNew = -Math.log10(valueMin);}
} else
if(axisTypeBefore.startsWith("log (Tot")) {
if(valueMax <0) {valueMinNew = -valueMax;}
if(valueMin <0) {valueMaxNew = -valueMin;}
}
}
if(valueMaxNew < valueMinNew) {valueMin = valueMinNew; valueMinNew = valueMaxNew; valueMaxNew = valueMin;}
// --- we got new values: change the text fields.
textFieldMin.setText(Util.formatNum(valueMinNew));
textFieldMax.setText(Util.formatNum(valueMaxNew));
//return
} // comboBoxAxisType(axisTypeNow, axisTypeBefore, valueMin, valueMax, textFieldMax, textFieldMin)
//</editor-fold>
//</editor-fold>
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroupActCoef;
private javax.swing.JButton jButtonGetConcCancel;
private javax.swing.JButton jButtonGetConcOK;
private javax.swing.JButton jButtonSaveDef;
private javax.swing.JButton jButton_Cancel;
private javax.swing.JButton jButton_Help;
private javax.swing.JButton jButton_OK;
private javax.swing.JCheckBox jCheckBoxAqu;
private javax.swing.JCheckBox jCheckBoxDrawPHline;
private javax.swing.JCheckBox jCheckBoxRev;
private javax.swing.JCheckBox jCheckBoxTableOut;
private javax.swing.JCheckBox jCheckBoxUseEh;
private javax.swing.JComboBox<String> jComboBoxActCoeff;
private javax.swing.JComboBox<String> jComboBoxConcType;
private javax.swing.JComboBox<String> jComboBoxDiagType;
private javax.swing.JComboBox<String> jComboBoxMainComp;
private javax.swing.JComboBox<String> jComboBoxXaxComp;
private javax.swing.JComboBox<String> jComboBoxXaxType;
private javax.swing.JComboBox<String> jComboBoxYaxComp;
private javax.swing.JComboBox<String> jComboBoxYaxType;
private javax.swing.JLabel jLabelDFileName;
private javax.swing.JLabel jLabelDataFile;
private javax.swing.JLabel jLabelDiagrType;
private javax.swing.JLabel jLabelEnterConc;
private javax.swing.JLabel jLabelEqual;
private javax.swing.JLabel jLabelFrom;
private javax.swing.JLabel jLabelHaff;
private javax.swing.JLabel jLabelIS;
private javax.swing.JLabel jLabelIonicS;
private javax.swing.JLabel jLabelM;
private javax.swing.JLabel jLabelModel;
private javax.swing.JLabel jLabelNbrCalcs;
private javax.swing.JLabel jLabelOFile;
private javax.swing.JLabel jLabelPredNbr;
private javax.swing.JLabel jLabelPredNbrP;
private javax.swing.JLabel jLabelSEDNbr;
private javax.swing.JLabel jLabelSEDNbrP;
private javax.swing.JLabel jLabelSpace;
private javax.swing.JLabel jLabelSpaceP;
private javax.swing.JLabel jLabelT;
private javax.swing.JLabel jLabelTC;
private javax.swing.JLabel jLabelTitle;
private javax.swing.JLabel jLabelTo;
private javax.swing.JLabel jLabelTotNbr;
private javax.swing.JLabel jLabelXaxis;
private javax.swing.JLabel jLabelYFract;
private javax.swing.JLabel jLabelYRef;
private javax.swing.JLabel jLabelYaxis;
private javax.swing.JLabel jLabelYcalc;
private javax.swing.JLabel jLabelYlogA;
private javax.swing.JLabel jLabelYlogC;
private javax.swing.JLabel jLabelYlogS;
private javax.swing.JLabel jLabel_GetConcCompName;
private javax.swing.JLabel jLabl1;
private javax.swing.JLabel jLabl2;
private javax.swing.JLabel jLabl3;
private javax.swing.JLabel jLabl4;
private javax.swing.JList jListCompConc;
private javax.swing.JPanel jPanelActCoef;
private javax.swing.JPanel jPanelAxes;
private javax.swing.JPanel jPanelButtons;
private javax.swing.JPanel jPanelConcInner;
private javax.swing.JPanel jPanelConcs;
private javax.swing.JPanel jPanelDiagrType;
private javax.swing.JPanel jPanelDiagram;
private javax.swing.JPanel jPanelEmptyDiagram;
private javax.swing.JPanel jPanelEmptyParameters;
private javax.swing.JPanel jPanelEmptyYax;
private javax.swing.JPanel jPanelFileNames;
private javax.swing.JPanel jPanelGetConc;
private javax.swing.JPanel jPanelLabl;
private javax.swing.JPanel jPanelLow;
private javax.swing.JPanel jPanelMainComp;
private javax.swing.JPanel jPanelModel;
private javax.swing.JPanel jPanelParams;
private javax.swing.JPanel jPanelPredom;
private javax.swing.JPanel jPanelSED;
private javax.swing.JPanel jPanelSedPredom;
private javax.swing.JPanel jPanelTitle;
private javax.swing.JPanel jPanelTotCalcs;
private javax.swing.JPanel jPanelXComponent;
private javax.swing.JPanel jPanelXaxis;
private javax.swing.JPanel jPanelYHaff;
private javax.swing.JPanel jPanelYRef;
private javax.swing.JPanel jPanelYaxComp;
private javax.swing.JPanel jPanelYaxInner;
private javax.swing.JPanel jPanelYaxis;
private javax.swing.JPanel jPanelYcalc;
private javax.swing.JPanel jPanelYcombo;
private javax.swing.JPanel jPanelYfraction;
private javax.swing.JPanel jPanelYlogA;
private javax.swing.JPanel jPanelYlogC;
private javax.swing.JPanel jPanelYlogS;
private javax.swing.JPanel jPanelYmax;
private javax.swing.JPanel jPanelYmin;
private javax.swing.JRadioButton jRadioButtonCalc;
private javax.swing.JRadioButton jRadioButtonFixed;
private javax.swing.JScrollBar jScrollBarPredNbrP;
private javax.swing.JScrollBar jScrollBarSEDNbrP;
private javax.swing.JScrollPane jScrollPaneCompConcList;
private javax.swing.JTextField jTextFieldCHigh;
private javax.swing.JTextField jTextFieldCLow;
private javax.swing.JTextField jTextFieldDataFile;
private javax.swing.JTextField jTextFieldDiagName;
private javax.swing.JTextField jTextFieldIonicStr;
private javax.swing.JTextField jTextFieldT;
private javax.swing.JTextField jTextFieldTitle;
private javax.swing.JTextField jTextFieldXmax;
private javax.swing.JTextField jTextFieldXmin;
private javax.swing.JTextField jTextFieldYmax;
private javax.swing.JTextField jTextFieldYmin;
// End of variables declaration//GEN-END:variables
}
| 272,469 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
OptionsCalcs.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Spana/src/spana/OptionsCalcs.java | package spana;
import lib.huvud.ProgramConf;
import lib.kemi.chem.Chem;
/** Options dialog for chemical equilibrium calculations with Haltafall.
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class OptionsCalcs extends javax.swing.JFrame {
// Note: for java 1.6 jComboBox must not have type,
// for java 1.7 jComboBox must be <String>
private boolean finished = false;
private java.awt.Dimension windowSize;
private double tolHalta = Chem.TOL_HALTA_DEF;
private ProgramDataSpana pd;
private ProgramConf pc;
private javax.swing.border.Border scrollBorder;
/** level of debug output in HaltaFall:<br>
* 0 - none<br>
* 1 - errors only<br>
* 2 - errors + results<br>
* 3 - errors + results + input<br>
* 4 = 3 + output from Fasta<br>
* 5 = 4 + output from activity coeffs<br>
* 6 = 5 + lots of output.<br>
* Default = Chem.DBGHALTA_DEF =1 (output errors only)
* @see Chem#DBGHALTA_DEF Chem.DBGHALTA_DEF
* @see Chem.ChemSystem.ChemConcs#dbg Chem.ChemSystem.ChemConcs.dbg */
private int calcDbgHalta = Chem.DBGHALTA_DEF;
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
//<editor-fold defaultstate="collapsed" desc="Constructor">
/** Creates new form OptionsCalcs
* @param pc0
* @param pd0 */
public OptionsCalcs(ProgramConf pc0, ProgramDataSpana pd0) {
initComponents();
this.pc = pc0;
this.pd = pd0;
finished = false;
//center Window on Screen
windowSize = this.getSize();
int left; int top;
left = Math.max(55, (MainFrame.screenSize.width - windowSize.width ) / 2);
top = Math.max(10, (MainFrame.screenSize.height - windowSize.height) / 2);
this.setLocation(Math.min(MainFrame.screenSize.width-100, left),
Math.min(MainFrame.screenSize.height-100, top));
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
//--- close window on ESC key
javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE");
javax.swing.Action escAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
closeWindow();
}};
getRootPane().getActionMap().put("ESCAPE", escAction);
//--- F1 for help
javax.swing.KeyStroke f1KeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(f1KeyStroke,"F1");
javax.swing.Action f1Action = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
OptionsCalcs.this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
Thread hlp = new Thread() {@Override public void run(){
String[] a = {"S_Menu_Prefs_htm_Calcs"};
lib.huvud.RunProgr.runProgramInProcess(OptionsCalcs.this,ProgramConf.HELP_JAR,a,false,pc.dbg,pc.pathAPP);
try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec
catch (InterruptedException e) {}
OptionsCalcs.this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
}};//new Thread
hlp.start();
}};
getRootPane().getActionMap().put("F1", f1Action);
//--- Alt-H help
javax.swing.KeyStroke altHKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_H, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altHKeyStroke,"ALT_H");
getRootPane().getActionMap().put("ALT_H", f1Action);
//--- alt-X
javax.swing.KeyStroke altXKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altXKeyStroke,"ALT_X");
javax.swing.Action altXAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jButton_OK.doClick();
}};
getRootPane().getActionMap().put("ALT_X", altXAction);
//--- alt-D
javax.swing.KeyStroke altDKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_D, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altDKeyStroke,"ALT_D");
javax.swing.Action altDAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jComboBoxDbgH.requestFocusInWindow();
}};
getRootPane().getActionMap().put("ALT_D", altDAction);
//--- alt-T
javax.swing.KeyStroke altTKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altTKeyStroke,"ALT_T");
javax.swing.Action altTAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jComboBoxTol.requestFocusInWindow();
}};
getRootPane().getActionMap().put("ALT_T", altTAction);
//--- alt-E
javax.swing.KeyStroke altEKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altEKeyStroke,"ALT_E");
javax.swing.Action altEAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jComboBoxExt.requestFocusInWindow();
}};
getRootPane().getActionMap().put("ALT_E", altEAction);
//--- alt-C
javax.swing.KeyStroke altCKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altCKeyStroke,"ALT_C");
javax.swing.Action altCAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jComboBoxChar.requestFocusInWindow();
}};
getRootPane().getActionMap().put("ALT_C", altCAction);
//
scrollBorder = jScrollBarMin.getBorder();
//--- Title
this.setTitle("Calculation Options:");
//---- Icon
String iconName = "images/Wrench_32x32.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
if (imgURL != null) {this.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());}
else {System.out.println("Error: Could not load image = \""+iconName+"\"");}
// --- set up the frame
if(pd.jarClassLd) {jRadioButtonLoadJars.setSelected(true);} else {jRadioButtonSeparate.setSelected(true);}
jCheckBoxCalcsDbg.setSelected(pd.calcDbg);
// store variables locally so the user can quit without saving
// debugging in HaltaFall
calcDbgHalta = Math.max(0, Math.min(jComboBoxDbgH.getItemCount()-1,pd.calcDbgHalta));
jComboBoxDbgH.setSelectedIndex(calcDbgHalta);
// tolerance in HaltaFall
tolHalta = pd.tolHalta;
set_tol_inComboBox();
for(String tblExtension_type : pd.tblExtension_types) {
jComboBoxExt.addItem(tblExtension_type);
}
boolean found = false;
for(int i=0; i < jComboBoxExt.getItemCount(); i++) {
if(jComboBoxExt.getItemAt(i).toString().equalsIgnoreCase(pd.tblExtension)) {
jComboBoxExt.setSelectedIndex(i);
found = true;
break;
}
}
if(!found) {jComboBoxExt.setSelectedIndex(0);}
// character separating column output
for(int i=0; i< pd.tblFieldSeparator_types.length; i++) {
String t;
if(pd.tblFieldSeparator_types[i] == ';') {t = "; (semicolon)";}
else if(pd.tblFieldSeparator_types[i] == ',') {t = ", (comma)";}
else if(pd.tblFieldSeparator_types[i] == ' ') {t = " (space)";}
else if(pd.tblFieldSeparator_types[i] == '\u0009') {t = "\\t (tab)";}
else {t = "(error)";}
jComboBoxChar.addItem(t);
}
found = false;
String c;
if(pd.tblFieldSeparator == '\u0009') {c = "\\t";}
else {c = Character.toString(pd.tblFieldSeparator)+" ";}
for(int i=0; i < jComboBoxChar.getItemCount(); i++) {
if(jComboBoxChar.getItemAt(i).toString().substring(0,2).equalsIgnoreCase(c)) {
jComboBoxChar.setSelectedIndex(i);
found = true;
break;
}
}
if(!found) {jComboBoxChar.setSelectedIndex(0);}
jComboBoxTol.setToolTipText("default: "+Chem.TOL_HALTA_DEF);
jLabelTol.setToolTipText("default: "+Chem.TOL_HALTA_DEF);
jLabel4.setToolTipText("default: 3%");
jScrollBarMin.setToolTipText("default: 3%");
jScrollBarMin.setValue(Math.round(pd.fractionThreshold*1000f));
jScrollBarMinAdjustmentValueChanged(null);
jScrollBarMin.setFocusable(true);
jCheckBoxKeep.setSelected(pd.keepFrame);
if(pd.tblCommentLineStart !=null && pd.tblCommentLineStart.length() >0) {
jTextF_Start.setText(pd.tblCommentLineStart);
} else {jTextF_Start.setText("");}
if(pd.tblCommentLineEnd !=null && pd.tblCommentLineEnd.length() >0) {
jTextF_End.setText(pd.tblCommentLineEnd);
} else {jTextF_End.setText("");}
checkBoxKeep();
} //constructor
//</editor-fold>
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
jButton_OK = new javax.swing.JButton();
jButton_Cancel = new javax.swing.JButton();
jPanel10 = new javax.swing.JPanel();
jLabelTol = new javax.swing.JLabel();
jComboBoxTol = new javax.swing.JComboBox<>();
jLabel4 = new javax.swing.JLabel();
jScrollBarMin = new javax.swing.JScrollBar();
jLabelMinVal = new javax.swing.JLabel();
jPanelTable = new javax.swing.JPanel();
jLabelExt = new javax.swing.JLabel();
jComboBoxExt = new javax.swing.JComboBox<>();
jLabelChar = new javax.swing.JLabel();
jComboBoxChar = new javax.swing.JComboBox<>();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jTextF_End = new javax.swing.JTextField();
jTextF_Start = new javax.swing.JTextField();
jPanel3 = new javax.swing.JPanel();
jRadioButtonLoadJars = new javax.swing.JRadioButton();
jRadioButtonSeparate = new javax.swing.JRadioButton();
jPanel1 = new javax.swing.JPanel();
jCheckBoxKeep = new javax.swing.JCheckBox();
jCheckBoxCalcsDbg = new javax.swing.JCheckBox();
jLabelDbgH = new javax.swing.JLabel();
jComboBoxDbgH = new javax.swing.JComboBox<>();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jButton_OK.setIcon(new javax.swing.ImageIcon(getClass().getResource("/spana/images/OK_32x32.gif"))); // NOI18N
jButton_OK.setMnemonic('O');
jButton_OK.setText("OK");
jButton_OK.setToolTipText("OK (Alt-O orAlt-X)"); // NOI18N
jButton_OK.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButton_OK.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jButton_OK.setMargin(new java.awt.Insets(2, 2, 2, 2));
jButton_OK.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_OKActionPerformed(evt);
}
});
jButton_Cancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/spana/images/Trash.gif"))); // NOI18N
jButton_Cancel.setMnemonic('Q');
jButton_Cancel.setText("Quit");
jButton_Cancel.setToolTipText("Cancel (Esc or Alt-Q)"); // NOI18N
jButton_Cancel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButton_Cancel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jButton_Cancel.setMargin(new java.awt.Insets(2, 2, 2, 2));
jButton_Cancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_CancelActionPerformed(evt);
}
});
jLabelTol.setLabelFor(jComboBoxTol);
jLabelTol.setText("<html>Max. <u>t</u>olerance for mass-balance eqns. in HaltaFall:</html>"); // NOI18N
jLabelTol.setToolTipText("default: 1E-5");
jComboBoxTol.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "1E-2", "1E-3", "1E-4", "1E-5", "1E-6", "1E-7", "1E-8", "1E-9" }));
jComboBoxTol.setToolTipText("default: 1E-4");
jLabel4.setText("Fraction diagrams: threshold for curves:");
jLabel4.setToolTipText("default: 3%");
jScrollBarMin.setMinimum(1);
jScrollBarMin.setOrientation(javax.swing.JScrollBar.HORIZONTAL);
jScrollBarMin.setToolTipText("default: 3%");
jScrollBarMin.setValue(0);
jScrollBarMin.setVisibleAmount(0);
jScrollBarMin.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jScrollBarMin.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jScrollBarMinFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jScrollBarMinFocusLost(evt);
}
});
jScrollBarMin.addAdjustmentListener(new java.awt.event.AdjustmentListener() {
public void adjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {
jScrollBarMinAdjustmentValueChanged(evt);
}
});
jLabelMinVal.setText("3 %");
jLabelMinVal.setToolTipText("double-click to set default value");
jLabelMinVal.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabelMinValMouseClicked(evt);
}
});
jPanelTable.setBorder(javax.swing.BorderFactory.createTitledBorder(null, " Table output in SED: ", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11), new java.awt.Color(51, 0, 255))); // NOI18N
jLabelExt.setLabelFor(jComboBoxExt);
jLabelExt.setText("<html>Name <u>e</u>xtension for output file:</html>"); // NOI18N
jLabelChar.setLabelFor(jComboBoxChar);
jLabelChar.setText("<html><u>C</u>olumn-separation character:</html>"); // NOI18N
jLabel1.setText("Comment-lines:"); // NOI18N
jLabel3.setLabelFor(jTextF_Start);
jLabel3.setText("start characters:"); // NOI18N
jLabel2.setLabelFor(jTextF_End);
jLabel2.setText("end characters:"); // NOI18N
jTextF_End.setText("\""); // NOI18N
jTextF_End.setToolTipText("Text that will be appended at the end of any comment line. Default is double quote (\")"); // NOI18N
jTextF_End.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextF_EndFocusGained(evt);
}
});
jTextF_Start.setText("\""); // NOI18N
jTextF_Start.setToolTipText("Text that will be inserted before any comment line. Default is double quote (\")"); // NOI18N
jTextF_Start.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextF_StartFocusGained(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jLabel3)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextF_End)
.addComponent(jTextF_Start))
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextF_Start, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)
.addComponent(jLabel1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jTextF_End, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanelTableLayout = new javax.swing.GroupLayout(jPanelTable);
jPanelTable.setLayout(jPanelTableLayout);
jPanelTableLayout.setHorizontalGroup(
jPanelTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelTableLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabelExt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelChar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jComboBoxChar, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBoxExt, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanelTableLayout.setVerticalGroup(
jPanelTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelTableLayout.createSequentialGroup()
.addGroup(jPanelTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelExt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBoxExt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jComboBoxChar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelChar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10);
jPanel10.setLayout(jPanel10Layout);
jPanel10Layout.setHorizontalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollBarMin, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelMinVal, javax.swing.GroupLayout.DEFAULT_SIZE, 53, Short.MAX_VALUE))
.addGroup(jPanel10Layout.createSequentialGroup()
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addComponent(jLabelTol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBoxTol, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanelTable, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel10Layout.setVerticalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelTol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBoxTol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(jScrollBarMin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelMinVal))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanelTable, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(null, " Calculations: ", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11), new java.awt.Color(51, 0, 255))); // NOI18N
buttonGroup1.add(jRadioButtonLoadJars);
jRadioButtonLoadJars.setMnemonic('L');
jRadioButtonLoadJars.setText("Load jar-files in Java Virtual machine");
buttonGroup1.add(jRadioButtonSeparate);
jRadioButtonSeparate.setMnemonic('R');
jRadioButtonSeparate.setText("Run jar-files in separate system process");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jRadioButtonLoadJars)
.addComponent(jRadioButtonSeparate))
.addContainerGap(23, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jRadioButtonLoadJars)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jRadioButtonSeparate))
);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, " Debugging: ", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11), new java.awt.Color(51, 0, 255))); // NOI18N
jCheckBoxKeep.setMnemonic('K');
jCheckBoxKeep.setText("Keep windows open after calculations"); // NOI18N
jCheckBoxKeep.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxKeepActionPerformed(evt);
}
});
jCheckBoxCalcsDbg.setMnemonic('W');
jCheckBoxCalcsDbg.setText("Write messages in SED & Predom"); // NOI18N
jLabelDbgH.setLabelFor(jComboBoxDbgH);
jLabelDbgH.setText("<html><u>D</u>ebugging in HaltaFall:</html>"); // NOI18N
jLabelDbgH.setToolTipText("Default is 1 (show errors)");
jComboBoxDbgH.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "0 - none", "1 - errors only", "2 - errors + results", "3 - errors + results + input", "4 = 3 + output from Fasta", "5 = 4 + output from activity coeffs.", "6 = 5 + lots of output" }));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jCheckBoxKeep)
.addComponent(jCheckBoxCalcsDbg)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jComboBoxDbgH, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelDbgH, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jCheckBoxKeep)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jCheckBoxCalcsDbg)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabelDbgH, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBoxDbgH, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton_OK, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton_Cancel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jButton_OK)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton_Cancel))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
//<editor-fold defaultstate="collapsed" desc="Events">
private void jButton_OKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_OKActionPerformed
pd.jarClassLd = jRadioButtonLoadJars.isSelected();
pd.keepFrame = jCheckBoxKeep.isSelected();
pd.calcDbg = jCheckBoxCalcsDbg.isSelected();
pd.calcDbgHalta = Integer.parseInt(jComboBoxDbgH.getSelectedItem().toString().substring(0,2).trim());
String t = jComboBoxTol.getSelectedItem().toString();
try{pd.tolHalta = Double.parseDouble(t);}
catch (NumberFormatException ex) {
System.err.println("Error: trying to read a number in \""+t+"\""+nl+"Setting max tolerance to "+(float)Chem.TOL_HALTA_DEF+" ...");
pd.tolHalta = Chem.TOL_HALTA_DEF;
}
//file name extention for table output
pd.tblExtension = jComboBoxExt.getSelectedItem().toString();
//character separating column output
t = jComboBoxChar.getSelectedItem().toString().substring(0,2);
if(t.equalsIgnoreCase("\\t")) {pd.tblFieldSeparator = '\u0009';}
else {pd.tblFieldSeparator = t.charAt(0);}
t = jTextF_Start.getText();
if(t !=null && t.length() >0) {pd.tblCommentLineStart = t;} else {pd.tblCommentLineStart = "";}
t = jTextF_End.getText();
if(t !=null && t.length() >0) {pd.tblCommentLineEnd = t;} else {pd.tblCommentLineEnd = "";}
pd.fractionThreshold = (float)jScrollBarMin.getValue()/1000f;
closeWindow();
}//GEN-LAST:event_jButton_OKActionPerformed
private void jButton_CancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_CancelActionPerformed
closeWindow();
}//GEN-LAST:event_jButton_CancelActionPerformed
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
closeWindow();
}//GEN-LAST:event_formWindowClosing
private void jCheckBoxKeepActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxKeepActionPerformed
checkBoxKeep();
}//GEN-LAST:event_jCheckBoxKeepActionPerformed
private void jTextF_StartFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextF_StartFocusGained
jTextF_Start.selectAll();
}//GEN-LAST:event_jTextF_StartFocusGained
private void jTextF_EndFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextF_EndFocusGained
jTextF_End.selectAll();
}//GEN-LAST:event_jTextF_EndFocusGained
private void jScrollBarMinAdjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {//GEN-FIRST:event_jScrollBarMinAdjustmentValueChanged
jLabelMinVal.setText(String.valueOf((float) jScrollBarMin.getValue() / 10f) + "%");
}//GEN-LAST:event_jScrollBarMinAdjustmentValueChanged
private void jScrollBarMinFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jScrollBarMinFocusGained
jScrollBarMin.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
}//GEN-LAST:event_jScrollBarMinFocusGained
private void jScrollBarMinFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jScrollBarMinFocusLost
jScrollBarMin.setBorder(scrollBorder);
}//GEN-LAST:event_jScrollBarMinFocusLost
private void jLabelMinValMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelMinValMouseClicked
if(evt.getClickCount() >1) { // double-click
jScrollBarMin.setValue(Math.round(0.03f*1000f));
}
}//GEN-LAST:event_jLabelMinValMouseClicked
private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
if(windowSize != null) {
int w = windowSize.width;
int h = windowSize.height;
if(this.getHeight()<h){this.setSize(this.getWidth(), h);}
if(this.getWidth()<w){this.setSize(w,this.getHeight());}
}
}//GEN-LAST:event_formComponentResized
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Methods">
private void closeWindow() {
finished = true;
this.notify_All();
this.dispose();
} // closeWindow()
private synchronized void notify_All() {notifyAll();}
/** this method will wait for this dialog frame to be closed */
public synchronized void waitFor() {
while(!finished) {
try {wait();} catch (InterruptedException ex) {}
} // while
} // waitFor()
private void checkBoxKeep() {
if(jCheckBoxKeep.isSelected()) {
jCheckBoxCalcsDbg.setEnabled(true);
jLabelDbgH.setEnabled(true);
jLabelDbgH.setText("<html><u>D</u>ebugging in HaltaFall:</html>");
jComboBoxDbgH.setEnabled(true);
} else {
jCheckBoxCalcsDbg.setEnabled(false);
jLabelDbgH.setText("Debugging in HaltaFall:");
jLabelDbgH.setEnabled(false);
jComboBoxDbgH.setEnabled(false);
}
} //checkBoxKeep()
//<editor-fold defaultstate="collapsed" desc="set_tol_inComboBox">
/** find the closest item in the tolerances combo box and select it */
private void set_tol_inComboBox() {
double w0;
double w1;
int listItem =0;
int listCount = jComboBoxTol.getItemCount();
for(int i =1; i < listCount; i++) {
w0 = Double.parseDouble(jComboBoxTol.getItemAt(i-1).toString());
w1 = Double.parseDouble(jComboBoxTol.getItemAt(i).toString());
if(tolHalta >= w0 && i==1) {listItem = 0; break;}
if(tolHalta <= w1 && i==(listCount-1)) {listItem = (listCount-1); break;}
if(tolHalta < w0 && tolHalta >=w1) {
if(Math.abs(tolHalta-w0) < Math.abs(tolHalta-w1)) {
listItem = i-1;
} else {
listItem = i;
}
break;
}
} //for i
jComboBoxTol.setSelectedIndex(listItem);
} //set_tol_inComboBox()
//</editor-fold>
//</editor-fold>
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JButton jButton_Cancel;
private javax.swing.JButton jButton_OK;
private javax.swing.JCheckBox jCheckBoxCalcsDbg;
private javax.swing.JCheckBox jCheckBoxKeep;
private javax.swing.JComboBox<String> jComboBoxChar;
private javax.swing.JComboBox<String> jComboBoxDbgH;
private javax.swing.JComboBox<String> jComboBoxExt;
private javax.swing.JComboBox<String> jComboBoxTol;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabelChar;
private javax.swing.JLabel jLabelDbgH;
private javax.swing.JLabel jLabelExt;
private javax.swing.JLabel jLabelMinVal;
private javax.swing.JLabel jLabelTol;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel10;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanelTable;
private javax.swing.JRadioButton jRadioButtonLoadJars;
private javax.swing.JRadioButton jRadioButtonSeparate;
private javax.swing.JScrollBar jScrollBarMin;
private javax.swing.JTextField jTextF_End;
private javax.swing.JTextField jTextF_Start;
// End of variables declaration//GEN-END:variables
}
| 41,529 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
ModifyChemSyst.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Spana/src/spana/ModifyChemSyst.java | package spana;
import lib.common.MsgExceptn;
import lib.common.Util;
import lib.huvud.ProgramConf;
import lib.kemi.chem.Chem;
import lib.kemi.readDataLib.ReadDataLib;
import lib.kemi.readWriteDataFiles.DefaultPlotAndConcs;
import lib.kemi.readWriteDataFiles.ReadChemSyst;
import lib.kemi.readWriteDataFiles.WriteChemSyst;
/** This "frame" is used to allow the user to modyfy a chemical system: delete
* components or reactions, excahnge a component for a reaction product, etc.
* The data file is read and only the definition of the chemical system is changed:
* the plot information and concentrations for each component are not changed,
* but when finishing, if the user decides to save the new chemical system, the
* plot information and concentrations for each component are adjusted depending
* on the new components.
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class ModifyChemSyst extends javax.swing.JFrame {
private final ProgramDataSpana pd;
private ProgramConf pc;
private boolean dbg = true;
private spana.ModifyChemSyst thisFrame = null;
private final java.awt.Dimension windowSize;
private boolean finished = false;
private java.io.File dataFile;
/** the main Chem instance */
private Chem ch = null;
/** a Chem instance used to read a chemical systems from a data file */
private Chem chRead = null;
/** a Chem instance used when merging two chemical systems */
private Chem ch2 = null;
/** the main ChemSystem instance */
private Chem.ChemSystem cs = null;
/** the main ChemSystem.NamesEtc instance */
private Chem.ChemSystem.NamesEtc namn = null;
/** the main Diagr instance */
private Chem.Diagr diagr = null;
/** the main DiagrConcs instance */
private Chem.DiagrConcs dgrC = null;
private final java.util.ArrayList<String> identC0 = new java.util.ArrayList<String>();
private String compXname0 = null;
private String compYname0 = null;
private String compMainName0 = null;
private int Na0;
/** java 1.6
private final javax.swing.DefaultListModel listSolubleCompModel = new javax.swing.DefaultListModel();
private final javax.swing.DefaultListModel listSolidCompModel = new javax.swing.DefaultListModel();
private final javax.swing.DefaultListModel listSolubleCmplxModel = new javax.swing.DefaultListModel();
private final javax.swing.DefaultListModel listSolidCmplxModel = new javax.swing.DefaultListModel();
*/
private final javax.swing.DefaultListModel<String> listSolubleCompModel = new javax.swing.DefaultListModel<>();
private final javax.swing.DefaultListModel<String> listSolidCompModel = new javax.swing.DefaultListModel<>();
private final javax.swing.DefaultListModel<String> listSolubleCmplxModel = new javax.swing.DefaultListModel<>();
private final javax.swing.DefaultListModel<String> listSolidCmplxModel = new javax.swing.DefaultListModel<>();
private final javax.swing.border.Border defBorder;
private final javax.swing.border.Border highlightedBorder = javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED, java.awt.Color.gray, java.awt.Color.black);
/** has the initial chemical system been modified? */
private boolean modified = false;
/** has the initial chemical system been merged with another one? */
private boolean merged = false;
private int compToDelete;
private int complxToExchange;
private static final String noReactionMessage = "(double-click or type space on a name to change its logK)";
private final static String nl = System.getProperty("line.separator");
//<editor-fold defaultstate="collapsed" desc="Constructor">
/** Creates new form ModifyChemSyst
* @param pc0
* @param pd0 */
public ModifyChemSyst(
ProgramConf pc0,
spana.ProgramDataSpana pd0
) {
initComponents();
this.pd = pd0;
this.pc = pc0;
dbg = pc.dbg;
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
//--- close window on ESC key
javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE");
javax.swing.Action escAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jButton_Quit.doClick();
}};
getRootPane().getActionMap().put("ESCAPE", escAction);
//--- F1 for help
javax.swing.KeyStroke f1KeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(f1KeyStroke,"F1");
javax.swing.Action f1Action = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
ModifyChemSyst.this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
Thread hlp = new Thread() {@Override public void run(){
String[] a = {"S_Modify_Chem_System_htm"};
lib.huvud.RunProgr.runProgramInProcess(ModifyChemSyst.this,ProgramConf.HELP_JAR,a,false,pc.dbg,pc.pathAPP);
try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec
catch (InterruptedException e) {}
ModifyChemSyst.this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
}};//new Thread
hlp.start();
}};
getRootPane().getActionMap().put("F1", f1Action);
// ---- Define Alt-keys
// Alt-Q is a button mnemonics
//--- Alt-H help
javax.swing.KeyStroke altHKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_H, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altHKeyStroke,"ALT_H");
getRootPane().getActionMap().put("ALT_H", f1Action);
//--- Alt-X quit
javax.swing.KeyStroke altXKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altXKeyStroke,"ALT_X");
javax.swing.Action altXAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jButton_Save.doClick();
}};
getRootPane().getActionMap().put("ALT_X", altXAction);
//---- Icon
String iconName = "images/Modify_32x32.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
if (imgURL != null) {this.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());}
else {System.out.println("Error: Could not load image = \""+iconName+"\"");}
defBorder = jScrollPane1.getBorder();
java.awt.CardLayout cl =(java.awt.CardLayout)jPanel1Top.getLayout();
cl.show(jPanel1Top, "cardDataFile");
jButton_Merge.setEnabled(pd.advancedVersion);
jButton_Merge.setVisible(pd.advancedVersion);
java.awt.Dimension d = jPanelUpDown.getPreferredSize();
if(!pd.advancedVersion) {
jButtonUp.setVisible(false);
jButtonDn.setVisible(false);
} else {
jButtonUp.setEnabled(false);
jButtonDn.setEnabled(false);
}
jLabelReaction.setText(" ");
jLabelReactionSetSize();
this.pack();
//center Window on Screen
windowSize = this.getSize();
int left; int top;
left = Math.max(0, (MainFrame.screenSize.width - windowSize.width ) / 2);
top = Math.max(0, (MainFrame.screenSize.height - windowSize.height) / 2);
this.setLocation(Math.min(MainFrame.screenSize.width-100, left),
Math.min(MainFrame.screenSize.height-100, top));
MainFrame.getInstance().setCursorDef();
this.setVisible(true);
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
thisFrame = ModifyChemSyst.this;
}}); //invokeLater(Runnable)
} // constructor
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="startDataFile(dataFile)">
/** Reads a data file and arranges the window frame.
* @param datFile */
public void startDataFile(java.io.File datFile) {
dataFile = datFile;
if(dbg) {System.out.println(" ---- Modify Chemical System: "+datFile.getName());}
if(!readDataFile(dataFile, pc.dbg)) {
System.err.println(" ---- Error reading file \""+dataFile.getName()+"\"");
MainFrame.getInstance().setCursorDef();
quitFrame();
return;}
ch = chRead;
chRead = null;
cs = ch.chemSystem;
namn = cs.namn;
diagr = ch.diag;
dgrC = ch.diagrConcs;
if(cs.Na <=0) {return;} //this should not happen
//--- store component names in axes, concs., etc, needed by checkPlotInfo()
storeInitialSystem(ch);
setupFrame();
pack();
} // startDataFile(dataFile)
//</editor-fold>
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jPanel1Top = new javax.swing.JPanel();
jPanelDataFile = new javax.swing.JPanel();
jLabel0 = new javax.swing.JLabel();
jTextFieldDataFile = new javax.swing.JTextField();
jPanelNew = new javax.swing.JPanel();
jLabel5 = new javax.swing.JLabel();
jPanelUpDown = new javax.swing.JPanel();
jButtonUp = new javax.swing.JButton();
jButtonDn = new javax.swing.JButton();
jPanel2up = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jListSolubComps = new javax.swing.JList();
jPanel6 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jScrollPane2 = new javax.swing.JScrollPane();
jListSolubCmplx = new javax.swing.JList();
jPanel2down = new javax.swing.JPanel();
jPanel7 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jScrollPane3 = new javax.swing.JScrollPane();
jListSolidComps = new javax.swing.JList();
jPanel8 = new javax.swing.JPanel();
jLabel4 = new javax.swing.JLabel();
jScrollPane4 = new javax.swing.JScrollPane();
jListSolidCmplx = new javax.swing.JList();
jPanel2 = new javax.swing.JPanel();
jLabelReaction = new javax.swing.JLabel();
jPanel10 = new javax.swing.JPanel();
jButton_Delete = new javax.swing.JButton();
jButton_Exchange = new javax.swing.JButton();
jButton_Merge = new javax.swing.JButton();
jPanel11 = new javax.swing.JPanel();
jButton_Quit = new javax.swing.JButton();
jButton_Save = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
setTitle("Modify Data File"); // NOI18N
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
jPanel1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
jPanel1MouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
jPanel1MouseExited(evt);
}
});
jPanel1Top.setLayout(new java.awt.CardLayout());
jLabel0.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel0.setForeground(new java.awt.Color(0, 0, 153));
jLabel0.setLabelFor(jTextFieldDataFile);
jLabel0.setText("Original Data File:"); // NOI18N
jLabel0.setToolTipText("Click to change Data File"); // NOI18N
jTextFieldDataFile.setText("jTextField1"); // NOI18N
jTextFieldDataFile.setToolTipText("Click to change Data File"); // NOI18N
jTextFieldDataFile.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextFieldDataFileActionPerformed(evt);
}
});
jTextFieldDataFile.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextFieldDataFileFocusGained(evt);
}
});
jTextFieldDataFile.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTextFieldDataFileKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextFieldDataFileKeyTyped(evt);
}
});
jTextFieldDataFile.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTextFieldDataFileMouseClicked(evt);
}
});
javax.swing.GroupLayout jPanelDataFileLayout = new javax.swing.GroupLayout(jPanelDataFile);
jPanelDataFile.setLayout(jPanelDataFileLayout);
jPanelDataFileLayout.setHorizontalGroup(
jPanelDataFileLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelDataFileLayout.createSequentialGroup()
.addComponent(jLabel0)
.addContainerGap(287, Short.MAX_VALUE))
.addComponent(jTextFieldDataFile, javax.swing.GroupLayout.DEFAULT_SIZE, 385, Short.MAX_VALUE)
);
jPanelDataFileLayout.setVerticalGroup(
jPanelDataFileLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelDataFileLayout.createSequentialGroup()
.addComponent(jLabel0)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextFieldDataFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Top.add(jPanelDataFile, "cardDataFile");
jLabel5.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel5.setForeground(new java.awt.Color(0, 0, 153));
jLabel5.setText("New Chemical System:"); // NOI18N
javax.swing.GroupLayout jPanelNewLayout = new javax.swing.GroupLayout(jPanelNew);
jPanelNew.setLayout(jPanelNewLayout);
jPanelNewLayout.setHorizontalGroup(
jPanelNewLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelNewLayout.createSequentialGroup()
.addGap(105, 105, 105)
.addComponent(jLabel5)
.addContainerGap(124, Short.MAX_VALUE))
);
jPanelNewLayout.setVerticalGroup(
jPanelNewLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelNewLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel5)
.addContainerGap(20, Short.MAX_VALUE))
);
jPanel1Top.add(jPanelNew, "cardNewSystem");
jButtonUp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/spana/images/Arrow_up.gif"))); // NOI18N
jButtonUp.setToolTipText("move component up"); // NOI18N
jButtonUp.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonUp.setMargin(new java.awt.Insets(1, 0, 1, 0));
jButtonUp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonUpActionPerformed(evt);
}
});
jButtonDn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/spana/images/Arrow_down.gif"))); // NOI18N
jButtonDn.setToolTipText("move component down"); // NOI18N
jButtonDn.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonDn.setMargin(new java.awt.Insets(1, 0, 1, 0));
jButtonDn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonDnActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanelUpDownLayout = new javax.swing.GroupLayout(jPanelUpDown);
jPanelUpDown.setLayout(jPanelUpDownLayout);
jPanelUpDownLayout.setHorizontalGroup(
jPanelUpDownLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelUpDownLayout.createSequentialGroup()
.addGap(4, 4, 4)
.addGroup(jPanelUpDownLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButtonDn)
.addComponent(jButtonUp))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelUpDownLayout.setVerticalGroup(
jPanelUpDownLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelUpDownLayout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(jButtonUp)
.addGap(18, 18, 18)
.addComponent(jButtonDn)
.addContainerGap(179, Short.MAX_VALUE))
);
jPanel2up.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
jPanel2upMouseEntered(evt);
}
});
jPanel2up.setLayout(new javax.swing.BoxLayout(jPanel2up, javax.swing.BoxLayout.LINE_AXIS));
jPanel5.setPreferredSize(new java.awt.Dimension(190, 141));
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel1.setForeground(new java.awt.Color(0, 0, 153));
jLabel1.setLabelFor(jScrollPane1);
jLabel1.setText("Soluble Components:"); // NOI18N
jListSolubComps.setModel(listSolubleCompModel);
jListSolubComps.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jListSolubComps.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
jListSolubCompsMouseReleased(evt);
}
});
jListSolubComps.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
jListSolubCompsMouseMoved(evt);
}
});
jListSolubComps.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jListSolubCompsFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jListSolubCompsFocusLost(evt);
}
});
jListSolubComps.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jListSolubCompsKeyReleased(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jListSolubCompsKeyTyped(evt);
}
});
jScrollPane1.setViewportView(jListSolubComps);
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE))
.addContainerGap())
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 150, Short.MAX_VALUE)
.addContainerGap())
);
jPanel2up.add(jPanel5);
jPanel6.setPreferredSize(new java.awt.Dimension(190, 141));
jPanel6.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
jPanel6MouseEntered(evt);
}
});
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel2.setForeground(new java.awt.Color(0, 0, 153));
jLabel2.setLabelFor(jScrollPane2);
jLabel2.setText("Soluble Complexes:"); // NOI18N
jScrollPane2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
jScrollPane2MouseEntered(evt);
}
});
jListSolubCmplx.setModel(listSolubleCmplxModel);
jListSolubCmplx.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jListSolubCmplxMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
jListSolubCmplxMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
jListSolubCmplxMouseExited(evt);
}
});
jListSolubCmplx.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
jListSolubCmplxMouseMoved(evt);
}
});
jListSolubCmplx.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jListSolubCmplxFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jListSolubCmplxFocusLost(evt);
}
});
jListSolubCmplx.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
jListSolubCmplxKeyTyped(evt);
}
});
jScrollPane2.setViewportView(jListSolubCmplx);
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addGroup(jPanel6Layout.createSequentialGroup()
.addComponent(jLabel2)
.addContainerGap(65, Short.MAX_VALUE))))
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 150, Short.MAX_VALUE)
.addContainerGap())
);
jPanel2up.add(jPanel6);
jPanel2down.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
jPanel2downMouseEntered(evt);
}
});
jPanel2down.setLayout(new javax.swing.BoxLayout(jPanel2down, javax.swing.BoxLayout.LINE_AXIS));
jPanel7.setPreferredSize(new java.awt.Dimension(190, 123));
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel3.setForeground(new java.awt.Color(0, 0, 153));
jLabel3.setLabelFor(jScrollPane3);
jLabel3.setText("Solid Components"); // NOI18N
jListSolidComps.setModel(listSolidCompModel);
jListSolidComps.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jListSolidComps.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
jListSolidCompsMouseReleased(evt);
}
});
jListSolidComps.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
jListSolidCompsMouseMoved(evt);
}
});
jListSolidComps.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jListSolidCompsFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jListSolidCompsFocusLost(evt);
}
});
jListSolidComps.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jListSolidCompsKeyReleased(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jListSolidCompsKeyTyped(evt);
}
});
jScrollPane3.setViewportView(jListSolidComps);
javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
jPanel7.setLayout(jPanel7Layout);
jPanel7Layout.setHorizontalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(0, 83, Short.MAX_VALUE))
.addGroup(jPanel7Layout.createSequentialGroup()
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addContainerGap())
);
jPanel7Layout.setVerticalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 144, Short.MAX_VALUE))
);
jPanel2down.add(jPanel7);
jPanel8.setPreferredSize(new java.awt.Dimension(190, 123));
jPanel8.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
jPanel8MouseEntered(evt);
}
});
jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel4.setForeground(new java.awt.Color(0, 0, 153));
jLabel4.setLabelFor(jScrollPane4);
jLabel4.setText("Solid Products"); // NOI18N
jScrollPane4.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
jScrollPane4MouseEntered(evt);
}
});
jListSolidCmplx.setModel(listSolidCmplxModel);
jListSolidCmplx.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jListSolidCmplxMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
jListSolidCmplxMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
jListSolidCmplxMouseExited(evt);
}
});
jListSolidCmplx.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
jListSolidCmplxMouseMoved(evt);
}
});
jListSolidCmplx.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jListSolidCmplxFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jListSolidCmplxFocusLost(evt);
}
});
jListSolidCmplx.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
jListSolidCmplxKeyTyped(evt);
}
});
jScrollPane4.setViewportView(jListSolidCmplx);
javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
jPanel8.setLayout(jPanel8Layout);
jPanel8Layout.setHorizontalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addGroup(jPanel8Layout.createSequentialGroup()
.addComponent(jLabel4)
.addGap(0, 93, Short.MAX_VALUE))))
);
jPanel8Layout.setVerticalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 144, Short.MAX_VALUE))
);
jPanel2down.add(jPanel8);
jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabelReaction.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabelReaction.setText("jLabelReaction");
jPanel2.add(jLabelReaction, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 360, -1));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(jPanel1Top, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanelUpDown, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2up, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addComponent(jPanel2down, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))))
.addGap(10, 10, 10))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(27, 27, 27)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(11, 11, 11)
.addComponent(jPanel1Top, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(2, 2, 2)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanelUpDown, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(91, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel2up, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(0, 0, 0)
.addComponent(jPanel2down, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(0, 0, 0)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(5, 5, 5))))
);
jButton_Delete.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButton_Delete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/spana/images/Delete_32x32.gif"))); // NOI18N
jButton_Delete.setMnemonic('D');
jButton_Delete.setText("<html><u>D</u>elete</html>"); // NOI18N
jButton_Delete.setToolTipText("Alt-D"); // NOI18N
jButton_Delete.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButton_Delete.setHorizontalAlignment(javax.swing.SwingConstants.LEADING);
jButton_Delete.setIconTextGap(8);
jButton_Delete.setMargin(new java.awt.Insets(2, 2, 2, 2));
jButton_Delete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_DeleteActionPerformed(evt);
}
});
jButton_Exchange.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButton_Exchange.setIcon(new javax.swing.ImageIcon(getClass().getResource("/spana/images/Exchange_32x32.gif"))); // NOI18N
jButton_Exchange.setMnemonic('E');
jButton_Exchange.setText("<html><u>E</u>xchange a component<br>with a reaction</html>"); // NOI18N
jButton_Exchange.setToolTipText("Alt-E"); // NOI18N
jButton_Exchange.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButton_Exchange.setHorizontalAlignment(javax.swing.SwingConstants.LEADING);
jButton_Exchange.setIconTextGap(8);
jButton_Exchange.setMargin(new java.awt.Insets(2, 2, 2, 2));
jButton_Exchange.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_ExchangeActionPerformed(evt);
}
});
jButton_Merge.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButton_Merge.setIcon(new javax.swing.ImageIcon(getClass().getResource("/spana/images/Merge_32x32.gif"))); // NOI18N
jButton_Merge.setMnemonic('M');
jButton_Merge.setText("<html><u>M</u>erge with another<br> data file</html>"); // NOI18N
jButton_Merge.setToolTipText("Alt-M"); // NOI18N
jButton_Merge.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButton_Merge.setHorizontalAlignment(javax.swing.SwingConstants.LEADING);
jButton_Merge.setIconTextGap(8);
jButton_Merge.setMargin(new java.awt.Insets(2, 2, 2, 2));
jButton_Merge.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_MergeActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10);
jPanel10.setLayout(jPanel10Layout);
jPanel10Layout.setHorizontalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton_Exchange, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton_Delete, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton_Merge, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE)
);
jPanel10Layout.setVerticalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addComponent(jButton_Delete, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton_Exchange, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(11, 11, 11)
.addComponent(jButton_Merge, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jButton_Quit.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButton_Quit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/spana/images/Quit_32x32.gif"))); // NOI18N
jButton_Quit.setMnemonic('Q');
jButton_Quit.setText("<html><u>Q</u>uit</html>"); // NOI18N
jButton_Quit.setToolTipText("Esc or Alt-Q"); // NOI18N
jButton_Quit.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButton_Quit.setHorizontalAlignment(javax.swing.SwingConstants.LEADING);
jButton_Quit.setIconTextGap(8);
jButton_Quit.setMargin(new java.awt.Insets(2, 2, 2, 2));
jButton_Quit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_QuitActionPerformed(evt);
}
});
jButton_Save.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButton_Save.setIcon(new javax.swing.ImageIcon(getClass().getResource("/spana/images/Save_32x32.gif"))); // NOI18N
jButton_Save.setMnemonic('S');
jButton_Save.setText("Save & exit"); // NOI18N
jButton_Save.setToolTipText("Alt-S or Alt-X"); // NOI18N
jButton_Save.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButton_Save.setHorizontalAlignment(javax.swing.SwingConstants.LEADING);
jButton_Save.setIconTextGap(8);
jButton_Save.setMargin(new java.awt.Insets(2, 2, 2, 2));
jButton_Save.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_SaveActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel11Layout = new javax.swing.GroupLayout(jPanel11);
jPanel11.setLayout(jPanel11Layout);
jPanel11Layout.setHorizontalGroup(
jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel11Layout.createSequentialGroup()
.addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton_Save, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton_Quit, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel11Layout.setVerticalGroup(
jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel11Layout.createSequentialGroup()
.addComponent(jButton_Quit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton_Save))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(jPanel10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jPanel11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jPanel11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
quitFrame();
}//GEN-LAST:event_formWindowClosing
private void jTextFieldDataFileKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldDataFileKeyTyped
char c = Character.toUpperCase(evt.getKeyChar());
if(evt.getKeyChar() != java.awt.event.KeyEvent.VK_ESCAPE &&
!(evt.isAltDown() && ((c == 'X') ||
(c == 'D') || (c == 'E') ||
(c == 'M') || (c == 'Q') ||
(evt.getKeyChar() == java.awt.event.KeyEvent.VK_ENTER))
) //isAltDown
) { // if not ESC or Alt-something
evt.consume(); // remove the typed key
dataFile_Click();
} // if char ok
}//GEN-LAST:event_jTextFieldDataFileKeyTyped
private void jTextFieldDataFileKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldDataFileKeyPressed
if(!Util.isKeyPressedOK(evt)) {evt.consume();}
}//GEN-LAST:event_jTextFieldDataFileKeyPressed
private void jTextFieldDataFileMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFieldDataFileMouseClicked
dataFile_Click();
}//GEN-LAST:event_jTextFieldDataFileMouseClicked
private void jTextFieldDataFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldDataFileActionPerformed
dataFile_Click();
}//GEN-LAST:event_jTextFieldDataFileActionPerformed
private void jTextFieldDataFileFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldDataFileFocusGained
jTextFieldDataFile.selectAll();
}//GEN-LAST:event_jTextFieldDataFileFocusGained
private void jButton_DeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_DeleteActionPerformed
delete_Click();
}//GEN-LAST:event_jButton_DeleteActionPerformed
private void jButton_ExchangeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_ExchangeActionPerformed
exchangeComponentWithComplex();
}//GEN-LAST:event_jButton_ExchangeActionPerformed
private void jButton_QuitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_QuitActionPerformed
quitFrame();
}//GEN-LAST:event_jButton_QuitActionPerformed
private void jButton_SaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_SaveActionPerformed
if(!modified) {
javax.swing.JOptionPane.showMessageDialog(this,
"No changes made,\ndata-file does not need to be saved.",
"Modify Chemical System", javax.swing.JOptionPane.INFORMATION_MESSAGE);
quitFrame();
return;
} //if not modified
// get a file name
String defName = null;
if(!merged) {defName = dataFile.getPath();}
String fileNameToSave = Util.getSaveFileName(this, pc.progName,
"Enter a file name or select a file:", 5, defName, pc.pathDef.toString());
if(fileNameToSave == null) {return;}
// save the file
setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
java.io.File dataFileToSave = new java.io.File(fileNameToSave);
//--- ready to write the new data file: check if the plot information
// needs to be changed
if(dbg) {System.out.println(" ---- Saving modified system in data file: "+dataFileToSave.getName());}
checkPlotInfo();
try{WriteChemSyst.writeChemSyst(ch, dataFileToSave);}
catch (Exception ex) {
MsgExceptn.showErrMsg(this,ex.getMessage(),1);
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
return;
}
if(dbg) {System.out.println(" ---- data file written: \""+dataFileToSave.getName()+"\"");}
// add file to list in main frame; do not mind about errors
MainFrame.getInstance().addDatFile(fileNameToSave);
modified = false;
merged = false;
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
quitFrame();
}//GEN-LAST:event_jButton_SaveActionPerformed
private void jListSolubCompsKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jListSolubCompsKeyTyped
jListSolidComps.clearSelection();
component_Click();
}//GEN-LAST:event_jListSolubCompsKeyTyped
private void jListSolubCompsFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListSolubCompsFocusGained
jScrollPane1.setBorder(highlightedBorder);
}//GEN-LAST:event_jListSolubCompsFocusGained
private void jListSolubCompsFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListSolubCompsFocusLost
jScrollPane1.setBorder(defBorder);
}//GEN-LAST:event_jListSolubCompsFocusLost
private void jListSolubCmplxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListSolubCmplxMouseClicked
complex_Click();
if(evt.getClickCount() >1) { // double-click
checkLogKchange(jListSolubCmplx, jListSolubCmplx.getSelectedIndex());
}
}//GEN-LAST:event_jListSolubCmplxMouseClicked
private void jListSolubCmplxKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jListSolubCmplxKeyTyped
complex_Click();
if(!(evt.isControlDown() || evt.isAltGraphDown() || evt.isAltDown() || evt.isMetaDown())
&& evt.getKeyChar() == ' ') {
checkLogKchange(jListSolubCmplx, jListSolubCmplx.getSelectedIndex());
}
evt.consume(); // remove the typed key
}//GEN-LAST:event_jListSolubCmplxKeyTyped
private void jListSolubCmplxMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListSolubCmplxMouseMoved
float cellBounds;
try{cellBounds = (float)jListSolubCmplx.getCellBounds(0, 0).getHeight();}
catch (Exception ex) {cellBounds =
(float)jListSolubCmplx.getHeight() /
(float)listSolubleCmplxModel.getSize();}
if(listSolubleCmplxModel.getSize()>0) {
int ix = (int)( (float)evt.getY()/ cellBounds );
if(ix >= listSolubleCmplxModel.getSize()) {ix = -1;}
jLabelReaction.setText(reactionText(cs, ix, true));
jLabelReactionSetSize();
}
}//GEN-LAST:event_jListSolubCmplxMouseMoved
private void jListSolubCmplxMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListSolubCmplxMouseExited
jLabelReaction.setText(noReactionMessage);
jLabelReactionSetSize();
}//GEN-LAST:event_jListSolubCmplxMouseExited
private void jListSolubCmplxFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListSolubCmplxFocusGained
jScrollPane2.setBorder(highlightedBorder);
}//GEN-LAST:event_jListSolubCmplxFocusGained
private void jListSolubCmplxFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListSolubCmplxFocusLost
jScrollPane2.setBorder(defBorder);
if(jListSolubCmplx.getSelectedIndex() <0 &&
jListSolidCmplx.getSelectedIndex() <0 &&
cs.Na <=1) {
jButton_Delete.setEnabled(false); //can not delete the last component
}
}//GEN-LAST:event_jListSolubCmplxFocusLost
private void jListSolidCmplxKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jListSolidCmplxKeyTyped
complex_Click();
if(!(evt.isControlDown() || evt.isAltGraphDown() || evt.isAltDown() || evt.isMetaDown())
&& evt.getKeyChar() == ' ') {
checkLogKchange(jListSolidCmplx,
jListSolidCmplx.getSelectedIndex() + listSolubleCmplxModel.getSize());
}
evt.consume(); // remove the typed key
}//GEN-LAST:event_jListSolidCmplxKeyTyped
private void jListSolidCmplxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListSolidCmplxMouseClicked
complex_Click();
if(evt.getClickCount() >1) { // double-click
checkLogKchange(jListSolidCmplx,
jListSolidCmplx.getSelectedIndex() + listSolubleCmplxModel.getSize());
}
}//GEN-LAST:event_jListSolidCmplxMouseClicked
private void jListSolidCmplxMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListSolidCmplxMouseMoved
float cellBounds;
try{cellBounds = (float)jListSolidCmplx.getCellBounds(0, 0).getHeight();}
catch (Exception ex) {cellBounds =
(float)jListSolidCmplx.getHeight() /
(float)listSolidCmplxModel.getSize();}
if(listSolidCmplxModel.getSize()>0) {
int ix = (int)( (float)evt.getY()/ cellBounds );
if(ix >= listSolidCmplxModel.getSize()) {ix = -1;}
else {ix = (cs.nx+ix);}
jLabelReaction.setText(reactionText(cs, ix, true));
jLabelReactionSetSize();
}
}//GEN-LAST:event_jListSolidCmplxMouseMoved
private void jListSolidCmplxMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListSolidCmplxMouseExited
jLabelReaction.setText(noReactionMessage);
jLabelReactionSetSize();
}//GEN-LAST:event_jListSolidCmplxMouseExited
private void jListSolidCmplxFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListSolidCmplxFocusGained
jScrollPane4.setBorder(highlightedBorder);
}//GEN-LAST:event_jListSolidCmplxFocusGained
private void jListSolidCmplxFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListSolidCmplxFocusLost
jScrollPane4.setBorder(defBorder);
if(jListSolubCmplx.getSelectedIndex() <0 &&
jListSolidCmplx.getSelectedIndex() <0 &&
cs.Na <=1) {
jButton_Delete.setEnabled(false); //can not delete the last component
}
}//GEN-LAST:event_jListSolidCmplxFocusLost
private void jListSolidCompsKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jListSolidCompsKeyTyped
jListSolubComps.clearSelection();
component_Click();
}//GEN-LAST:event_jListSolidCompsKeyTyped
private void jListSolidCompsFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListSolidCompsFocusLost
jScrollPane3.setBorder(defBorder);
}//GEN-LAST:event_jListSolidCompsFocusLost
private void jListSolidCompsFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListSolidCompsFocusGained
jScrollPane3.setBorder(highlightedBorder);
}//GEN-LAST:event_jListSolidCompsFocusGained
private void jButton_MergeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_MergeActionPerformed
mergeTwoSystems();
}//GEN-LAST:event_jButton_MergeActionPerformed
private void jListSolubCompsKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jListSolubCompsKeyReleased
jListSolidComps.clearSelection();
component_Click();
}//GEN-LAST:event_jListSolubCompsKeyReleased
private void jListSolidCompsKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jListSolidCompsKeyReleased
jListSolubComps.clearSelection();
component_Click();
}//GEN-LAST:event_jListSolidCompsKeyReleased
private void jButtonUpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonUpActionPerformed
upDownComponent(true);
}//GEN-LAST:event_jButtonUpActionPerformed
private void jButtonDnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDnActionPerformed
upDownComponent(false);
}//GEN-LAST:event_jButtonDnActionPerformed
private void jListSolubCompsMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListSolubCompsMouseReleased
jListSolidComps.clearSelection();
component_Click();
}//GEN-LAST:event_jListSolubCompsMouseReleased
private void jListSolidCompsMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListSolidCompsMouseReleased
jListSolubComps.clearSelection();
component_Click();
}//GEN-LAST:event_jListSolidCompsMouseReleased
private void jPanel1MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel1MouseEntered
jLabelReactionSetSize();
}//GEN-LAST:event_jPanel1MouseEntered
private void jPanel2upMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel2upMouseEntered
jLabelReactionSetSize();
}//GEN-LAST:event_jPanel2upMouseEntered
private void jPanel2downMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel2downMouseEntered
jLabelReactionSetSize();
}//GEN-LAST:event_jPanel2downMouseEntered
private void jScrollPane4MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jScrollPane4MouseEntered
jLabelReactionSetSize();
}//GEN-LAST:event_jScrollPane4MouseEntered
private void jScrollPane2MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jScrollPane2MouseEntered
jLabelReactionSetSize();
}//GEN-LAST:event_jScrollPane2MouseEntered
private void jPanel8MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel8MouseEntered
jLabelReactionSetSize();
}//GEN-LAST:event_jPanel8MouseEntered
private void jPanel6MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel6MouseEntered
jLabelReactionSetSize();
}//GEN-LAST:event_jPanel6MouseEntered
private void jListSolubCmplxMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListSolubCmplxMouseEntered
jLabelReactionSetSize();
}//GEN-LAST:event_jListSolubCmplxMouseEntered
private void jListSolidCmplxMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListSolidCmplxMouseEntered
jLabelReactionSetSize();
}//GEN-LAST:event_jListSolidCmplxMouseEntered
private void jListSolubCompsMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListSolubCompsMouseMoved
jLabelReaction.setText(" ");
jLabelReactionSetSize();
}//GEN-LAST:event_jListSolubCompsMouseMoved
private void jListSolidCompsMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListSolidCompsMouseMoved
jLabelReaction.setText(" ");
jLabelReactionSetSize();
}//GEN-LAST:event_jListSolidCompsMouseMoved
private void jPanel1MouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel1MouseExited
jLabelReaction.setText(" ");
jLabelReactionSetSize();
}//GEN-LAST:event_jPanel1MouseExited
private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
if(windowSize != null) {
int w = windowSize.width;
int h = windowSize.height;
if(this.getHeight()<h){this.setSize(this.getWidth(), h);}
if(this.getWidth()<w){this.setSize(w,this.getHeight());}
}
}//GEN-LAST:event_formComponentResized
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Methods">
public final void quitFrame() {
if(thisFrame != null && modified) {
this.bringToFront();
int n;
//note that the first button is "cancel"
Object[] options = {"Cancel", "Yes"};
n = javax.swing.JOptionPane.showOptionDialog(this,"Discard your changes?",
"Modify Chemical System", javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE, null, options, null);
if(n != javax.swing.JOptionPane.NO_OPTION) {return;} //the second button is "yes"
}
modified = false;
merged = false;
finished = true;
this.notify_All();
this.setVisible(false);
thisFrame = null;
this.dispose();
} // quitForm_Gen_Options
private synchronized void notify_All() {notifyAll();}
/** this method will wait for this dialog frame to be closed */
public synchronized void waitForModifyChemSyst() {
while(!finished) {
try {wait();} catch (InterruptedException ex) {}
} // while
} // waitForModifyChemSyst()
/** Are there changes that should be saved?
* @return true if changes in the Chemical System have been made (and the
* file is not yet saved); false if no changes to the Chemical System have
* been made */
public boolean isModified() {return modified;}
public void bringToFront() {
if(thisFrame != null) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override public void run() {
thisFrame.setVisible(true);
if((thisFrame.getExtendedState() & javax.swing.JFrame.ICONIFIED) // minimised?
== javax.swing.JFrame.ICONIFIED) {
thisFrame.setExtendedState(javax.swing.JFrame.NORMAL);
} // if minimized
thisFrame.setAlwaysOnTop(true);
thisFrame.toFront();
thisFrame.requestFocus();
thisFrame.setAlwaysOnTop(false);
}
});
}
} // bringToFront()
private void jLabelReactionSetSize() {
jLabelReaction.setSize(jPanel2.getWidth(), jPanel2.getHeight());
int i = Math.max(0,(jPanel2.getWidth()-jLabelReaction.getWidth()));
jLabelReaction.setLocation(i,0);
}
//<editor-fold defaultstate="collapsed" desc="checkPlotInfo()">
/** If some components have been deleted: Find out if the plot definition can
* be the same, if not, fix it. Also remove concentration
* information for deleted components */
private void checkPlotInfo() {
boolean plotMustBeChanged = false;
boolean found;
int compXnew = -1; int compYnew = -1; int compMainNew = -1;
if(dbg) {
System.out.println(" ---- Checking if plot information is still valid");
diagr.printPlotType(null);
if(dgrC != null) {System.out.println(dgrC.toString());}
else {System.out.println(" undefined diagram concentrations: \"null\" pointer for dgrC (DiagrConcs).");}
}
//--- Is there any plot information?
if(diagr.plotType <0 || diagr.compX <0 ||
(diagr.plotType ==0 && (diagr.compY <0 || diagr.compMain <0)) ||
((diagr.plotType ==1 || diagr.plotType ==4) && diagr.compY <0)) {
plotMustBeChanged = true;
if(dbg) {System.out.println("Plot Must Be Changed: plotType="+diagr.plotType+" compX="+diagr.compX+" compY="+diagr.compY+" compMain="+diagr.compMain);}
}
//--- check if a component is given in an axis,
// but it is not found among the new components.
//
// In case the components have been rearranged:
// find out the new component numbers is the axes.
if(compXname0 != null && !plotMustBeChanged) {
found = false;
for(int inew =0; inew < cs.Na; inew++) {
if(namn.identC[inew].equals(compXname0)) {
compXnew = inew;
found = true; break;
}
} //for inew
if(!found) {
plotMustBeChanged = true;
if(dbg) {System.out.println("Plot Must Be Changed: component \""+compXname0+"\" in X-axis has been removed");}
}
} //if compXname0 != null
if((diagr.plotType ==0 || diagr.plotType ==1 || diagr.plotType ==4) &&
compYname0 != null && !plotMustBeChanged) {
found = false;
for(int inew =0; inew < cs.Na; inew++) {
if(namn.identC[inew].equals(compYname0)) {
compYnew = inew;
found = true; break;
}
} //for inew
if(!found) {
plotMustBeChanged = true;
if(dbg) {System.out.println("Plot Must Be Changed: component \""+compYname0+"\" in Y-axis has been removed");}
}
} //if compYname0 != null
if(diagr.plotType ==0 && compMainName0 != null && !plotMustBeChanged) {
found = false;
for(int inew =0; inew < cs.Na; inew++) {
if(namn.identC[inew].equals(compMainName0)) {
compMainNew = inew;
found = true; break;
}
} //for inew
if(!found) {
plotMustBeChanged = true;
if(dbg) {System.out.println("Plot Must Be Changed: main-component \""+compMainName0+"\" has been removed");}
}
} //if compYname0 != null
//--- if an old-component with concentration varied is not found in
// the new component-list: the plot definition must change.
if(!plotMustBeChanged) {
if(dgrC == null) {plotMustBeChanged = true;}
else {
for(int iold = 0; iold < Na0; iold++) {
// is the concentration varied?
if(dgrC.hur[iold] ==2 || dgrC.hur[iold] ==3 || dgrC.hur[iold] ==5) {
found = false;
for(int inew =0; inew < cs.Na; inew++) {
if(namn.identC[inew].equals(identC0.get(iold))) {found = true; break;}
} //for inew
if(!found) {
plotMustBeChanged = true;
if(dbg) {System.out.println("Plot Must Be Changed: component \""+identC0.get(iold)+"\" (with varied concentration) has been removed");}
break;
}
} //concentration varied?
} //for iold
} // if dgrC != null
} //if !plotMustBeChanged
//--- are there H+ and e- in the new chemical system?
int H_present = -1; int e_present = -1; int e_cmplx = -1;
for(int inew =0; inew < cs.Na; inew++) {
if(Util.isProton(namn.identC[inew])) {H_present = inew;}
if(Util.isElectron(namn.identC[inew])) {e_present = inew;}
} //for inew
if(e_present < 0) {
for(int ix =0; ix < cs.nx; ix++) {
if(Util.isElectron(namn.ident[ix+cs.Na])) {e_cmplx = ix; break;}
} //for ix
} //if !e_present
//--- check if pH is given for the Y-axis or it is an H-affinity diagram
// and there is no H+
if((diagr.plotType == 6 || diagr.plotType == 8) && !plotMustBeChanged) {
if(H_present < 0) {
plotMustBeChanged = true;
if(dbg) {System.out.println("Plot Must Be Changed: calculated pH or H-affinity requested but \"H+\" has been removed");}
}
} //calculated "pH" in y-axis or H-affinity
//--- check if pe or Eh is given for the Y-axis and there are no electrons
if(diagr.plotType == 5 && !plotMustBeChanged) {
if(e_present < 0 && e_cmplx < 0) {
plotMustBeChanged = true;
if(dbg) {System.out.println("Plot Must Be Changed: calculated pe/Eh requested but \"e-\" has been removed");}
}
} //calculated "pe" in y-axis
//--- get a new plot type if needed
if(plotMustBeChanged) {
diagr.Eh = pd.useEh;
//set a default plot
if(dbg) {System.out.println("Setting New Plot Type");}
DefaultPlotAndConcs.setDefaultPlot(cs, diagr, dgrC);
} //if plotMustBeChanged
else {
//In case the components have been rearranged:
// put in the new component numbers is the axes.
diagr.compX = compXnew;
diagr.compY = compYnew;
diagr.compMain = compMainNew;
}
if(dbg) {diagr.printPlotType(null);}
//--- create a new instance of DiagrConcs
Chem.DiagrConcs dgrCnew;
try{dgrCnew = ch.new DiagrConcs(cs.Na);}
catch (Chem.ChemicalParameterException ex) {
MsgExceptn.showErrMsg(this, ex.getMessage(), 1);
System.err.println(Util.stack2string(ex));
storeInitialSystem(ch);
return;
}
//--- Get concentrations (default if needed) for all new components
if(dbg) {System.out.println("Checking concentrations:");}
for(int inew =0; inew < cs.Na; inew++) {
found = false;
if(dgrC != null) {
for(int iold = 0; iold < Na0; iold++) {
if(namn.identC[inew].equals(identC0.get(iold)) && dgrC.hur[iold] >0) {
dgrCnew.hur[inew] = dgrC.hur[iold];
dgrCnew.cLow[inew] = dgrC.cLow[iold];
dgrCnew.cHigh[inew] = dgrC.cHigh[iold];
found = true;
break;
}
} //for iold
}
if(!found) { //a component is new (due to an exchange)
if(dbg) {
System.out.println("concentration for component \""+namn.identC[inew]+"\" not found; setting default conc.");
}
DefaultPlotAndConcs.setDefaultConc(inew, namn.identC[inew], dgrCnew, pd.kth);
} //if !found
} //for inew
//--- change the pointer to the new instance (the old instance becomes garbage)
ch.diagrConcs = dgrCnew;
dgrC = ch.diagrConcs;
//--- check that concentrations in axes (and "main") are varied (or fixed)
if(dbg) {System.out.println("Checking concentrations for components in axes...");}
DefaultPlotAndConcs.checkConcsInAxesAndMain(namn, diagr, dgrC, dbg, pd.kth);
if(dbg) {
System.out.println("Component's concentrations:");
for(int ic =0; ic < cs.Na; ic++) {
System.out.println(" \""+namn.identC[ic]+"\" hur="+dgrC.hur[ic]+" cLow="+dgrC.cLow[ic]+" cHigh="+dgrC.cHigh[ic]);
} //for ic
System.out.println(" ---- Finished checking concentrations and plot-information.");
}
storeInitialSystem(ch);
} //checkPlotInfo()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="complex_Click()">
private void complex_Click() {
int nbr = 0;
if(listSolubleCmplxModel.getSize()>0) {
if(jListSolubCmplx.getSelectedIndex() >=0) {
if(!jButton_Delete.isEnabled()) {jButton_Delete.setEnabled(true);}
int[] indx = jListSolubCmplx.getSelectedIndices();
if(indx.length == 1) {nbr = 1;}
else if(indx.length > 1) {nbr = 2;}
}
}
if(listSolidCmplxModel.getSize()>0) {
if(jListSolidCmplx.getSelectedIndex() >=0) {
if(!jButton_Delete.isEnabled()) {jButton_Delete.setEnabled(true);}
int[] indx = jListSolidCmplx.getSelectedIndices();
if(indx.length == 1) {nbr++;}
else if(indx.length > 1) {nbr = nbr + 2;}
}
}
if(nbr <= 1) {
jButton_Delete.setText("<html><u>D</u>elete a reaction</html>");
} else {
jButton_Delete.setText("<html><u>D</u>elete reactions</html>");
}
} //complex_Click()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="component_Click()">
private void component_Click() {
int nbr = 0;
jButtonUp.setEnabled(false);
jButtonDn.setEnabled(false);
if(listSolubleCompModel.getSize()>0 &&
jListSolubComps.getSelectedIndex()>=0) {
nbr++;
if(listSolubleCompModel.getSize() >=2) {
if(jListSolubComps.getSelectedIndex()>=1) {jButtonUp.setEnabled(true);}
if(jListSolubComps.getSelectedIndex()< listSolubleCompModel.getSize()-1) {
jButtonDn.setEnabled(true);
}
}
}
if(listSolidCompModel.getSize()>0 &&
jListSolidComps.getSelectedIndex()>=0) {
nbr++;
if(listSolidCompModel.getSize() >=2) {
if(jListSolidComps.getSelectedIndex()>=1) {jButtonUp.setEnabled(true);}
if(jListSolidComps.getSelectedIndex()< listSolidCompModel.getSize()-1) {
jButtonDn.setEnabled(true);
}
}
}
if(nbr < 1) {
jButton_Delete.setText("Delete");
} else {
jButton_Delete.setText("Delete a component");
}
} //component_Click()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="dataFile_Click()">
private void dataFile_Click() {
// get a file name
String fileName = Util.getOpenFileName(this, pc.progName, true,
"Enter a Data file name:", 5, dataFile.getPath(), pc.pathDef.toString());
if(fileName == null) {jTextFieldDataFile.requestFocusInWindow(); return;}
if(MainFrame.getInstance().addDatFile(fileName)) {
setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
dataFile = new java.io.File(fileName);
if(!readDataFile(dataFile, pc.dbg)) {
System.err.println(" ---- Error reading file \""+dataFile.getName()+"\"");
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
return;}
if(dbg) {System.out.println(" ---- new data file = \""+dataFile.getName()+"\"");}
ch = chRead;
chRead = null;
cs = ch.chemSystem;
namn = cs.namn;
diagr = ch.diag;
dgrC = ch.diagrConcs;
}
storeInitialSystem(ch);
setupFrame();
this.toFront();
this.requestFocus();
jTextFieldDataFile.requestFocusInWindow();
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
} // dataFile_Click()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="disableButtons()">
private void disableButtons() {
jTextFieldDataFile.setEnabled(false);
jButton_Delete.setEnabled(false);
jButton_Delete.setForeground(java.awt.Color.gray);
jButton_Exchange.setEnabled(false);
jButton_Exchange.setForeground(java.awt.Color.gray);
jButton_Merge.setEnabled(false);
jButton_Merge.setForeground(java.awt.Color.gray);
jButton_Save.setText("Save & exit");
jButton_Save.setEnabled(false);
jButton_Save.setForeground(java.awt.Color.gray);
jButtonUp.setEnabled(false);
jButtonDn.setEnabled(false);
} //disableButtons()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="delete_Click()">
private void delete_Click() {
disableButtons();
// ---- component or complex?
int del_Comp_or_Cmplx = -1;
if(jButton_Delete.getText().contains("component")) {
if(listSolubleCompModel.getSize()>0 &&
jListSolubComps.getSelectedIndex()>=0) {
del_Comp_or_Cmplx = 1;
}
if(listSolidCompModel.getSize()>0 &&
jListSolidComps.getSelectedIndex()>=0) {
del_Comp_or_Cmplx = 1;
}
}
else if(jButton_Delete.getText().contains("reaction")){
if(listSolubleCmplxModel.getSize()>0) {
if(jListSolubCmplx.getSelectedIndex() >=0) {
del_Comp_or_Cmplx = 2;
}
}
if(listSolidCmplxModel.getSize()>0) {
if(jListSolidCmplx.getSelectedIndex() >=0) {
del_Comp_or_Cmplx = 2;
}
}
}
// ----
switch (del_Comp_or_Cmplx) {
case 1:
// ---- delete a component
// ---- is it water (H2O)?
if(listSolubleCompModel.getSize()>0 &&
jListSolubComps.getSelectedIndex()>=0 &&
Util.isWater(jListSolubComps.getSelectedValue().toString())) {
compToDelete = jListSolubComps.getSelectedIndex();
final String water = jListSolubComps.getSelectedValue().toString();
int n;
// note that the buttons are [Cancel] [Yes] [No]
final int YES_OPTION = javax.swing.JOptionPane.NO_OPTION; //second button
final int NO_OPTION = javax.swing.JOptionPane.CANCEL_OPTION; //third button
// are there any complexes?
if(listSolubleCmplxModel.getSize() > 0 ||
listSolidCmplxModel.getSize() > 0) {
// is there OH- among the complexes?
String oh = "";
for(int i=0; i < cs.Ms-cs.mSol; i++) {
if(namn.ident[i].equals("OH-") || namn.ident[i].equals("OH -")) {
oh = "\"OH-\" and ";
}
} //for i
// note that the buttons are [Cancel] [Yes] [No]
Object[] options = {"Cancel", "Yes", "No"};
n = javax.swing.JOptionPane.showOptionDialog(this,
"Remove water without removing its reactions?\n\n"+
"Press \"YES\" to remove "+water+" but keep its reactions\n"+
"(for example to keep "+oh+"any hydrolysis species).\n\n"+
"Press \"NO\" to delete "+water+" and all its reactions.\n\n",
"Modify Chemical System", javax.swing.JOptionPane.YES_NO_CANCEL_OPTION,
javax.swing.JOptionPane.QUESTION_MESSAGE, null, options, null);
} else {n = NO_OPTION;}
if(n == YES_OPTION) {
//do not remove reactions of H2O
if(dbg) {System.out.println(" ---- Remove water but leave its reactions");}
for(int ic = compToDelete; ic < cs.Na-1; ic++) {
namn.identC[ic] = namn.identC[ic+1];
namn.ident[ic] = namn.ident[ic+1];
}//for ic
for(int i=cs.Na-1; i < cs.Ms-1; i++) {
namn.ident[i] = namn.ident[i+1];
} //for i
for(int ix =0; ix < cs.Ms-cs.Na; ix++) {
for(int ic = compToDelete; ic < cs.Na-1; ic++) {
cs.a[ix][ic] = cs.a[ix][ic+1];
}//for ic
}//for ix
cs.Na = cs.Na -1;
cs.Ms = cs.Ms -1;
cs.jWater = -1;
//--- fix plot information data (if posssible)
checkPlotInfo();
modified = true;
setupFrame();
} else if(n == NO_OPTION) {
//remove also all reactions with H2O
if(dbg) {System.out.println(" ---- Remove water and all its reactions");}
this.setVisible(false);
final ModifyChemSyst thisModify = this;
Thread mod = new Thread() {@Override public void run(){
spana.ModifyConfirm modifyC =
new spana.ModifyConfirm(thisModify.getLocation(),
ch, compToDelete, -99, pc);
boolean cancel = modifyC.waitForModifyConfirm();
thisModify.cs = ch.chemSystem;
thisModify.namn = cs.namn;
if(!cancel) {
//--- fix plot information data (if posssible)
checkPlotInfo();
modified = true;
cs.jWater = -1;
}
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
setupFrame();
thisModify.setVisible(true);
}}); //invokeLater(Runnable)
}};//new Thread
mod.start();
} else {setupFrame(); break;} //if cancel_option
} else {
// ---- not water (H2O):
if(jListSolubComps.getSelectedIndex()>=0) {
compToDelete = jListSolubComps.getSelectedIndex();
} else {
compToDelete = jListSolidComps.getSelectedIndex() + (cs.Na - cs.solidC);
}
if(dbg) {System.out.println(" ---- Remove component \""+namn.identC[compToDelete]+"\"");}
this.setVisible(false);
final ModifyChemSyst thisModify = this;
Thread mod = new Thread() {@Override public void run(){
spana.ModifyConfirm modifyC =
new spana.ModifyConfirm(thisModify.getLocation(),
ch, compToDelete, -99, pc);
boolean cancel = modifyC.waitForModifyConfirm();
thisModify.cs = ch.chemSystem;
thisModify.namn = cs.namn;
if(!cancel) {
//--- fix plot information data (if posssible)
checkPlotInfo();
modified = true;
}
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
setupFrame();
thisModify.setVisible(true);
}}); //invokeLater(Runnable)
}};//new Thread
mod.start();
} //water?
break;
case 2:
// ---- delete one or more reactions:
//show a warning:
String onlyOne = "";
if(jListSolubCmplx.getSelectedIndex() >=0 &&
jListSolubCmplx.getMaxSelectionIndex() == jListSolubCmplx.getMinSelectionIndex()) {
onlyOne = jListSolubCmplx.getSelectedValue().toString();
}
if(jListSolidCmplx.getSelectedIndex() >=0) {
if(jListSolidCmplx.getMaxSelectionIndex() == jListSolidCmplx.getMinSelectionIndex()) {
if(onlyOne.length() ==0) {onlyOne = jListSolidCmplx.getSelectedValue().toString();}
else {onlyOne = "";}
} else {onlyOne = "";}
}
if(onlyOne.length() ==0) {onlyOne = "selected reactions";}
else {onlyOne = "\""+onlyOne+"\"";}
//note that the first button is "cancel"
Object[] options = {"Cancel", "Yes"};
int n = javax.swing.JOptionPane.showOptionDialog(this,
"Remove "+onlyOne+" ?",
"Modify Chemical System", javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE, null, options, null);
if (n != javax.swing.JOptionPane.NO_OPTION) {setupFrame(); break;} //second button is "yes"
n = javax.swing.JOptionPane.showOptionDialog(this,
"Warning!\nRemoving reactions will probably result in wrong diagrams !\n\n"+
"Remove "+onlyOne+" anyway?",
"Modify Chemical System", javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE, null, options, null);
if (n != javax.swing.JOptionPane.NO_OPTION) {setupFrame(); break;} //second button is "yes"
// ---- go ahead and do it!
int i1; int ix;
int ixCount = 0;
for(int i=0; i < listSolubleCmplxModel.getSize(); i++) {
ix = i;
if(jListSolubCmplx.isSelectedIndex(i)) {ixCount++;}
else{ //not selected: keep
if(ixCount >0) {
i1 = ix -ixCount;
namn.ident[cs.Na+i1] = namn.ident[cs.Na+ix];
cs.lBeta[i1] = cs.lBeta[ix];
//for(int ic=0; ic<cs.Na; ic++) {cs.a[i1][ic] = cs.a[ix][ic];}
System.arraycopy(cs.a[ix], 0, cs.a[i1], 0, cs.Na);
}//if ixCount >0
}//if not isSelectedIndex(i)
}//for i
cs.Ms = cs.Ms - ixCount;
cs.nx = cs.nx - ixCount;
int ifCount = 0;
int iCount;
for(int i=0; i < listSolidCmplxModel.getSize(); i++) {
ix = cs.nx + ixCount + i;
if(jListSolidCmplx.isSelectedIndex(i)) {ifCount++;}
else{ //not selected: keep
iCount = ixCount + ifCount;
if(iCount >0) {
i1 = ix -iCount;
namn.ident[cs.Na+i1] = namn.ident[cs.Na+ix];
cs.lBeta[i1] = cs.lBeta[ix];
//for(int ic=0; ic<cs.Na; ic++) {cs.a[i1][ic] = cs.a[ix][ic];}
System.arraycopy(cs.a[ix], 0, cs.a[i1], 0, cs.Na);
}//if iCount >0
}//if not isSelectedIndex(i)
}//for i
cs.Ms = cs.Ms - ifCount;
cs.mSol = cs.mSol - ifCount;
modified = true;
setupFrame();
break;
default:
javax.swing.JOptionPane.showMessageDialog(this,
"Please, select either:\n - a component, or\n - one or more reaction products\nfrom the lists.",
"Modify Chemical System",javax.swing.JOptionPane.WARNING_MESSAGE);
setupFrame();
break;
} //switch
} //delete_Click()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="exchangeComponentWithComplex()">
private void exchangeComponentWithComplex() {
if(listSolubleCmplxModel.getSize() <=0 && listSolidCmplxModel.getSize() <=0) {return;}
disableButtons();
// which component is selected?
compToDelete = -1;
compToDelete = jListSolubComps.getSelectedIndex();
if(compToDelete < 0) {
compToDelete = jListSolidComps.getSelectedIndex();
if(compToDelete>=0) {compToDelete = compToDelete +(cs.Na - cs.solidC);}
}
// check that a component is indeed selected
if(compToDelete < 0) {
String msg = "list";
if(listSolubleCompModel.getSize() > 0 && listSolidCompModel.getSize() > 0) {msg = "lists";}
javax.swing.JOptionPane.showMessageDialog(this, "Please, select one component from the "+msg+".", "Modify Chemical System", javax.swing.JOptionPane.WARNING_MESSAGE);
setupFrame();
return;
}
// does this component have any soluble complex?
int complxs = 0 ;
for(int i=0; i < cs.nx; i++) {
if(Math.abs(cs.a[i][compToDelete])>1e-7) {complxs++; break;}
} //for i
if(complxs <= 0) {
int i;
for(int is=0; is < cs.mSol-cs.solidC; is++) {
i = is +cs.nx;
if(Math.abs(cs.a[i][compToDelete])>1e-7) {complxs++; break;}
} //for i
}
if(complxs <=0) {
String comp = namn.identC[compToDelete];
javax.swing.JOptionPane.showMessageDialog(this,
"\""+comp+"\" does not form any reaction products.\n\n"+
"Can not exchange this component.",
"Modify Chemical System", javax.swing.JOptionPane.WARNING_MESSAGE);
setupFrame();
return;
}
// check if only one reaction is selected:
complxToExchange = -1;
int[] cmplxSel = jListSolubCmplx.getSelectedIndices();
if(cmplxSel.length == 1) {complxToExchange = jListSolubCmplx.getSelectedIndex();}
if(complxToExchange < 0) {
int[] solidSel = jListSolidCmplx.getSelectedIndices();
if(solidSel.length == 1) {
complxToExchange = jListSolidCmplx.getSelectedIndex()
+ listSolubleCmplxModel.getSize();
}
}
if(complxToExchange < 0) {complxToExchange = -1;} //this should not be needed
if(dbg) {System.out.println(" ---- Exchange \""+namn.identC[compToDelete]+"\" with reaction="+complxToExchange);}
this.setVisible(false);
final ModifyChemSyst thisModify = this;
Thread exch = new Thread() {@Override public void run(){
spana.ModifyConfirm modifyC =
new spana.ModifyConfirm(thisModify.getLocation(),
ch, compToDelete, complxToExchange, pc);
boolean cancel = modifyC.waitForModifyConfirm();
thisModify.cs = ch.chemSystem;
thisModify.namn = cs.namn;
if(!cancel) {
//--- fix plot information data (if posssible)
checkPlotInfo();
modified = true;
}
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
setupFrame();
thisModify.setVisible(true);
}}); //invokeLater(Runnable)
}};//new Thread
exch.start();
} //exchangeComponentWithComplex()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="checkLogKchange()">
private void checkLogKchange(final javax.swing.JList list, final int cmplx) {
if(cmplx<0) {return;}
disableButtons();
this.setVisible(false);
final ModifyChemSyst thisModify = this;
final int i = list.getSelectedIndex();
Thread lgK = new Thread() {@Override public void run(){
spana.LogKchange logKc = new spana.LogKchange(cs, cmplx, pc);
boolean cancel = logKc.waitForLogKchange();
if(!cancel) {modified = true;}
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
if(modified) {
java.awt.CardLayout cl =
(java.awt.CardLayout)jPanel1Top.getLayout();
cl.show(jPanel1Top, "cardNewSystem");
jTextFieldDataFile.setEnabled(false);
}
setupFrame();
thisModify.setVisible(true);
list.setSelectedIndex(i);
list.requestFocusInWindow();
}}); //invokeLater(Runnable)
}};//new Thread
lgK.start();
} //checkLogKchange()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="mergeTwoSystems()">
private void mergeTwoSystems() {
if(modified) {
javax.swing.JOptionPane.showMessageDialog(this,
"Please save first this modified chemical system.\n"+
"Only existing (un-modified) data files can be merged.",
"Modify Chemical System", javax.swing.JOptionPane.WARNING_MESSAGE);
return;}
//--- warning (note that the first button is "cancel")
Object[] options = {"Cancel", "Yes"};
int answ = javax.swing.JOptionPane.showOptionDialog(this,
"<html><b>Note: a merged chemical system<br>"+
"is probably incomplete.</b><br>"+
"For example, after merging the two systems:<br>"+
" H+, Ca+2, Cl−,<br>"+
" H+, Fe+3, CO3−2,<br>"+ //− unicode minus
"you will <b>NOT</b> have chloride complexes of Fe(III)<br>"+
"and you will <b>NOT</b> have calcium carbonate!<br><br>"+
"Are you <b>sure</b> that you still want to do this?</html>",
"Modify Chemical System",javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE, null, options, null);
if(answ != javax.swing.JOptionPane.NO_OPTION) {return;} // second button is "yes"
//go ahead and do it
disableButtons();
//--- get the second file name
String fileName2 = Util.getOpenFileName(this, pc.progName, true,
"Select data file to merge with this chemical system:", 5, null, pc.pathDef.toString());
if(fileName2 == null) {setupFrame(); return;}
java.io.File dataFile2 = new java.io.File(fileName2);
if(dataFile2.getPath().equalsIgnoreCase(dataFile.getPath())) {
javax.swing.JOptionPane.showMessageDialog(this,
"File \""+dataFile2.getPath()+"\"\n"+
"is already open!",
"Modify Chemical System", javax.swing.JOptionPane.ERROR_MESSAGE);
setupFrame();
return;}
//--- read the second data file
setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
if(dbg) {
System.out.println(
" ---- Merging data file \""+dataFile.getName()+"\" with \""+dataFile2.getName()+"\"");
}
boolean ok = readDataFile(dataFile2, pc.dbg); //read the file
if(!ok) {
System.err.println(" ---- Error reading file \""+dataFile2.getName()+"\"");
setupFrame();
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
this.bringToFront();
return;
}
if(dbg) {System.out.println("---- data file read: \""+dataFile2.getName()+"\"");}
ch2 = chRead;
chRead = null;
Chem.ChemSystem cs2 = ch2.chemSystem;
Chem.ChemSystem.NamesEtc namn2 = cs2.namn;
Chem.Diagr diag2 = ch2.diag;
Chem.DiagrConcs dgrC2 = ch2.diagrConcs;
if(dbg) {
System.out.print("---- First file has "+cs.Na+" components");
if(cs.solidC >0) {String t; if(cs.solidC ==1) {t=" is";} else {t=" are";}
System.out.print(" (the last "+cs.solidC+t+" solid)");
}
System.out.print(":"+nl+" ");
System.out.print(namn.identC[0]);
if(cs.Na >1) {for(int i=1;i<cs.Na;i++) {System.out.print(", "+namn.identC[i]);}}
System.out.println();
System.out.print("---- Second file has "+cs2.Na+" components");
if(cs2.solidC >0) {String t; if(cs2.solidC ==1) {t=" is";} else {t=" are";}
System.out.print(" (the last "+cs2.solidC+t+" solid)");
}
System.out.print(":"+nl+" ");
System.out.print(namn2.identC[0]);
if(cs2.Na >1) {for(int i=1;i<cs2.Na;i++) {System.out.print(", "+namn2.identC[i]);}}
System.out.println(nl+"----");
}
int mSol = cs.mSol;
int mSol2 = cs2.mSol;
int solidC_Out = cs.solidC;
//--- what components are new? ---
int naOut = cs.Na;
// iel[] will contain what components will be in the merged system
// and in what order
int found;
for(int ic2 = 0; ic2 < cs2.Na; ic2++) {
found = -1;
for(int ic1 = 0; ic1 < cs.Na; ic1++) {
if(Util.nameCompare(namn.identC[ic1], namn2.identC[ic2])) {
found = ic1; break;
}
} //for ic1
namn2.iel[ic2] = found; //it will be -1 if not found
if(found < 0) { //not found: a new component
naOut++;
if(dbg) {System.out.print("Component to add: \""+namn2.identC[ic2]+"\"");}
if(ic2 > (cs2.Na - cs2.solidC -1)) {
solidC_Out++;
if(dbg) {System.out.print(" (this is a solid component)");}
}
if(dbg) {System.out.println();}
//no complex in File1 may have the same name as this component in File2
for(int ix1=cs.Na; ix1 < (cs.Ms-cs.solidC); ix1++) {
if(Util.nameCompare(namn.ident[ix1],namn2.identC[ic2])) {
javax.swing.JOptionPane.showMessageDialog(this,
"Big trouble!\n\n"+
"component: \""+namn2.identC[ic2]+"\"\n"+
"in file \""+dataFile2.getName()+"\"\n"+
"has the same name as reaction product: \""+namn.ident[ix1]+"\"\n"+
"in file \""+dataFile.getName()+"\"\n\n"+
"Please switch a component/reaction.\n"+
"Terminating . . .",
"Modify Chemical System", javax.swing.JOptionPane.ERROR_MESSAGE);
if(dbg) {System.out.println("Component in file \""+dataFile2.getName()+"\""+nl+
" has the same name as reaction in file \""+dataFile.getName()+"\"."+nl+
" Can not continue merge.");}
setupFrame();
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
return;
}
} //for ix1
} //if found <0
} //for ic2
//--- number of new components: soluble (solblCompsNew) and new solid (solidCompsNew)
int solidCompsNew = solidC_Out - cs.solidC;
int solblCompsNew = (naOut - cs.Na) - solidCompsNew;
if(dbg) {
System.out.println("New components= "+(naOut-cs.Na)+", total in the merged system= "+naOut+nl+
" new components: soluble= "+solblCompsNew+" solid= "+solidCompsNew);
}
//--- The merged system will be larger than any of the two individual files,
// so the storage capacity of the arrays in the chem.Chem classes
// is not enough. The new species are first saved in ArrayLists and
// when the size of the merged system is known in detail at the end,
// then a new chem.Chem instance is created
java.util.ArrayList<String> identCM = new java.util.ArrayList<String>();
for(int i=0; i < naOut; i++) {identCM.add(i, null);}
java.util.ArrayList<String> identM = new java.util.ArrayList<String>();
java.util.ArrayList<Double> lBetaM = new java.util.ArrayList<Double>();
java.util.ArrayList<Double[]> aM = new java.util.ArrayList<Double[]>();
double[] a1 = new double[naOut];
double[] a2 = new double[naOut];
//--- Copy/move names of solid components in File1:
// Note that solid componensts must be the last in the list
for(int ic1=0; ic1 < cs.Na; ic1++) {
if(ic1 > (cs.Na - cs.solidC - 1)) { //solid component
namn.iel[ic1] = ic1 + solblCompsNew;
identCM.set(ic1+solblCompsNew, namn.identC[ic1]);
} else {
namn.iel[ic1] = ic1;
identCM.set(ic1, namn.identC[ic1]);
}
}
//--- Insert new component names
// Note that solid componensts must be the last in the list
int iaCount=0; int iaNew;
for(int ic2=0; ic2 < cs2.Na; ic2++) {
if(namn2.iel[ic2] < 0) {//component to add (not found among the existing)
iaCount++;
if(iaCount <= solblCompsNew) {
iaNew = iaCount + (cs.Na - cs.solidC - 1);
} else {
iaNew = iaCount + cs.Na -1;
}
identCM.set(iaNew, namn2.identC[ic2]);
namn2.iel[ic2] = iaNew;
}
}
if(dbg) { // list the names of all components in the merged system
int n0, nM, iPl, nP;
System.out.println("---- Components in the merged system: "+naOut); System.out.print(" ");
n0 = 0; //start index to print
nM = naOut-1; //end index to print
iPl = 5; nP= nM-n0; if(nP >=0) { //items_Per_Line and items to print
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
System.out.format(" %15s",identCM.get(kjj));
if(kjj >(nM-1)) {System.out.println(); break print_1;}} //for j
System.out.println(); System.out.print(" ");} //for ijj
}
} //if dbg
//--- find new Soluble complexes in 2nd file ---
int nxOut = cs.nx;
for(int ix2=0; ix2 < cs2.nx; ix2++) {
found = -1;
for(int ix1=0; ix1 < cs.nx; ix1++) {
if(Util.nameCompare(namn.ident[ix1+cs.Na],namn2.ident[ix2+cs2.Na])) {
found = ix1; break;
}
} //for ix1
if(found < 0) { //new complex
if(dbg) {System.out.println("New soluble complex: "+namn2.ident[ix2+cs2.Na]);}
//check that no component in File1 has the same name as this complex
for(int ic1=0; ic1 < cs.Na; ic1++) {
if(Util.nameCompare(namn.identC[ic1],namn2.ident[ix2+cs2.Na])) {
javax.swing.JOptionPane.showMessageDialog(this,
"Big trouble!\n\n"+
"complex: \""+namn2.ident[ix2+cs2.Na]+"\"\n"+
"in file \""+dataFile2.getName()+"\"\n"+
"has the same name as component: \""+namn.identC[ic1]+"\"\n"+
"in file \""+dataFile.getName()+"\"\n\n"+
"Please switch a component/complex.\n"+
"Terminating . . .",
"Modify Chemical System", javax.swing.JOptionPane.ERROR_MESSAGE);
if(dbg) {System.out.println("Complex in file \""+dataFile2.getName()+"\""+nl+
" has the same name as component in file \""+dataFile.getName()+"\"."+nl+
" Can not continue merging.");}
setupFrame();
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
return;
}
} //for ic1
nxOut++;
identM.add(namn2.ident[ix2+cs2.Na]);
lBetaM.add(cs2.lBeta[ix2]);
aM.add(new Double[cs2.Na]);
for(int i=0; i < cs2.Na; i++) {aM.get(aM.size()-1)[i] = cs2.a[ix2][i];}
} //if found <0
else { //found >=0: there are two complexes with the same name
//check that not only the names match, but also the stoichiometries match
for(int ic=0; ic < naOut; ic++) {a1[ic] = 0; a2[ic] = 0;}
for(int ic=0; ic < cs.Na; ic++) {a1[namn.iel[ic]] = cs.a[found][ic];}
for(int ic=0; ic < cs2.Na; ic++) {a2[namn2.iel[ic]]= cs2.a[ix2][ic];}
for(int ic=0; ic < naOut; ic++) {
if(Math.abs(a1[ic]-a2[ic]) > 0.0001) {
javax.swing.JOptionPane.showMessageDialog(this,
"Big trouble!\n\n"+
"the complex \""+namn.ident[found+cs.Na]+"\" exists both\n"+
"in file \""+dataFile2.getName()+"\" and\n"+
"in file \""+dataFile.getName()+"\",\n"+
"but the stoichiometries are different!\n\n"+
"Please correct the input files.\nTerminating . . .",
"Modify Chemical System", javax.swing.JOptionPane.ERROR_MESSAGE);
if(dbg) {System.out.println("Complex has the same name in both files but different stoichiometries."+nl+
" Can not continue merge.");}
setupFrame();
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
return;
}
} //for ic
//check also for equal equilibrium constants
if(Math.abs(cs.lBeta[found]-cs2.lBeta[ix2]) > 0.02) {
javax.swing.JOptionPane.showMessageDialog(this,
"Warning:\n\n"+
"logK = "+cs.lBeta[found]+
"for complex \""+namn.ident[found+cs.Na]+"\"\n"+
"in file \""+dataFile.getName()+"\"\n"+
"but logK = "+cs2.lBeta[ix2]+
"in file \""+dataFile2.getName()+"\",\n\n"+
"The first value will be used.",
"Modify Chemical System", javax.swing.JOptionPane.INFORMATION_MESSAGE);
}
} //if found >=0
} //for ix2
int solblComplxsNew = nxOut - cs.nx;
if(dbg) {System.out.println("New soluble complexes= "+solblComplxsNew+" total="+nxOut);}
//--- find new Solid reactions in 2nd file ---
// total number of solids (components + reactions) so far
// "mSol" is the total number of solids (reaction products + solid components)
int mSolOut = (mSol-cs.solidC) + solidC_Out;
for(int ix2=cs2.nx; ix2 < (cs2.nx + (mSol2-cs2.solidC)); ix2++) {
found = -1;
for(int ix1=cs.nx; ix1 < (cs.nx + (mSol-cs.solidC)); ix1++) {
if(Util.nameCompare(namn.ident[ix1+cs.Na],namn2.ident[ix2+cs2.Na])) {
found = ix1; break;
}
} //for ix1
if(found < 0) { //new solid reaction product
if(dbg) {System.out.println("New solid reaction product: "+namn2.ident[ix2+cs2.Na]);}
//check that no component in File1 has the same name as this solid product
for(int ic1=0; ic1 < cs.Na; ic1++) {
if(Util.nameCompare(namn.identC[ic1],namn2.ident[ix2+cs2.Na])) {
javax.swing.JOptionPane.showMessageDialog(this,
"Big trouble!\n\n"+
"solid product: \""+namn2.ident[ix2+cs2.Na]+"\"\n"+
"in file \""+dataFile2.getName()+"\"\n"+
"has the same name as component: \""+namn.identC[ic1]+"\"\n"+
"in file \""+dataFile.getName()+"\"\n\n"+
"Please switch a component/reaction.\n"+
"Terminating . . .",
"Modify Chemical System", javax.swing.JOptionPane.ERROR_MESSAGE);
if(dbg) {System.out.println("Solid product in file \""+dataFile2.getName()+"\""+nl+
" has the same name as component in file \""+dataFile.getName()+"\"."+nl+
" Can not continue merge.");}
setupFrame();
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
return;
}
} //for ic1
mSolOut++;
identM.add(namn2.ident[ix2+cs2.Na]);
lBetaM.add(cs2.lBeta[ix2]);
aM.add(new Double[cs2.Na]);
for(int i=0; i < cs2.Na; i++) {aM.get(aM.size()-1)[i] = cs2.a[ix2][i];}
} //if found <0
else { //found >=0: there are two solid products with the same name
//check that not only the names match, but also the stoichiometries match
for(int ic=0; ic < naOut; ic++) {a1[ic] = 0; a2[ic] = 0;}
for(int ic=0; ic < cs.Na; ic++) {a1[namn.iel[ic]] = cs.a[found][ic];}
for(int ic=0; ic < cs2.Na; ic++) {a2[namn2.iel[ic]]= cs2.a[ix2][ic];}
for(int ic=0; ic < naOut; ic++) {
if(Math.abs(a1[ic]-a2[ic]) > 0.0001) {
javax.swing.JOptionPane.showMessageDialog(this,
"Big trouble!\n\n"+
"the solid product \""+namn.ident[found+cs.Na]+"\" exists both\n"+
"in file \""+dataFile2.getName()+"\" and\n"+
"in file \""+dataFile.getName()+"\",\n"+
"but the stoichiometries are different!\n\n"+
"Please correct the input files.\nTerminating . . .",
"Modify Chemical System", javax.swing.JOptionPane.ERROR_MESSAGE);
if(dbg) {System.out.println("Solid product has the same name in both files but different stoichiometries."+nl+
" Can not continue merge.");}
setupFrame();
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
return;
}
} //for ic
//check also for equal equilibrium constants
if(Math.abs(cs.lBeta[found]-cs2.lBeta[ix2]) > 0.02) {
javax.swing.JOptionPane.showMessageDialog(this,
"Warning:\n\n"+
"logK = "+cs.lBeta[found]+
"for reaction \""+namn.ident[found+cs.Na]+"\"\n"+
"in file \""+dataFile.getName()+"\"\n"+
"but logK = "+cs2.lBeta[ix2]+
"in file \""+dataFile2.getName()+"\",\n\n"+
"The first value will be used.",
"Modify Chemical System", javax.swing.JOptionPane.INFORMATION_MESSAGE);
}
} //if found >=0
} //for ix2
int solidComplxsNew = (mSolOut-solidC_Out) - (mSol-cs.solidC);
if(dbg) {System.out.println("New solid products= "+solidComplxsNew+" total= "+(mSolOut-solidC_Out));}
//--- check temperature/pressure and title
if(Double.isNaN(diagr.temperature) && !Double.isNaN(diag2.temperature)) {
if(dbg) {System.out.println("Setting temperature to: "+diag2.temperature);}
diagr.temperature = diag2.temperature;
}
if(!Double.isNaN(diagr.temperature) && !Double.isNaN(diag2.temperature) &&
Math.abs(diagr.temperature-diag2.temperature)>0.0001) {
if(dbg) {System.out.println("Warning: different temperatures."+nl+
" in file \""+dataFile.getName()+"\" t="+diagr.temperature+nl+
" but in file \""+dataFile2.getName()+"\" t="+diag2.temperature+","+nl+
" keeping t = "+diagr.temperature);}
}
if(Double.isNaN(diagr.pressure) && !Double.isNaN(diag2.pressure)) {
if(dbg) {System.out.println("Setting pressure to: "+diag2.pressure);}
diagr.pressure = diag2.pressure;
}
if(!Double.isNaN(diagr.pressure) && !Double.isNaN(diag2.pressure) &&
Math.abs(diagr.pressure-diag2.pressure)>0.0001) {
if(dbg) {System.out.println("Warning: different pressures."+nl+
" in file \""+dataFile.getName()+"\" P="+diagr.pressure+nl+
" but in file \""+dataFile2.getName()+"\" P="+diag2.pressure+","+nl+
" keeping P = "+diagr.pressure);}
}
if(diag2.title != null && diagr.title == null) {
if(dbg) {System.out.println("Setting title to: \""+diag2.title+"\"");}
diagr.title = diag2.title;
}
if(diagr.title != null && diag2.title != null) {
if(dbg) {System.out.println("Warning: title in merge file discarded.");}
}
//--- create new instances of ChemSystem and other Chem-classes
// and store the merged chemical system into it
Chem.ChemSystem csNew;
try{csNew = ch.new ChemSystem(naOut, (naOut+nxOut+mSolOut), mSolOut, solidC_Out);}
catch (Chem.ChemicalParameterException ex) {
MsgExceptn.showErrMsg(this, ex.getMessage(), 1);
System.err.println(Util.stack2string(ex));
csNew = null;
}
if(csNew == null) {
storeInitialSystem(ch);
setupFrame();
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
return;
}
Chem.ChemSystem.NamesEtc namnNew = csNew.namn;
if(dbg) {System.out.print("---- New chemical system: components total= "+naOut+" of which solid= "+solidC_Out+nl+
" reactions: soluble= "+nxOut+" solid= "+(mSolOut-solidC_Out)+nl+
" total number of species = "+(naOut+nxOut+mSolOut));
System.out.print(" (including components");
if(solidC_Out >0) {System.out.print(" and solids corresponding to any solid components");}
System.out.println(")");
}
boolean plotInfoGiven = (diagr.plotType >=0 && diagr.compX >=0 && dgrC.hur[0] >0);
Chem.DiagrConcs dgrCNew = null;
if(plotInfoGiven) {
try{dgrCNew = ch.new DiagrConcs(naOut);}
catch (Chem.ChemicalParameterException ex) {
plotInfoGiven = false;
dgrCNew = null;
MsgExceptn.showErrMsg(this, ex.getMessage(), 1);
System.err.println(Util.stack2string(ex));
}
} //if plotInfoGiven
csNew.chemConcs = cs.chemConcs;
csNew.solidC = solidC_Out;
csNew.nx = nxOut;
//copy component names
for(int ic1=0; ic1 < cs.Na; ic1++) {
namnNew.identC[namn.iel[ic1]] = namn.identC[ic1];
namnNew.ident[namn.iel[ic1]] = namn.identC[ic1];
}
for(int ic2=0; ic2 < cs2.Na; ic2++) {
namnNew.identC[namn2.iel[ic2]] = namn2.identC[ic2];
namnNew.ident[namn2.iel[ic2]] = namn2.identC[ic2];
}
//copy soluble complexes
for(int ix1=0; ix1 < cs.nx; ix1++) {
namnNew.ident[naOut+ix1] = namn.ident[cs.Na+ix1];
csNew.lBeta[ix1] = cs.lBeta[ix1];
for(int ic=0; ic < naOut; ic++) {csNew.a[ix1][ic] = 0;}
for(int ic1=0; ic1 < cs.Na; ic1++) {csNew.a[ix1][namn.iel[ic1]] = cs.a[ix1][ic1];}
}
for(int ixM = 0; ixM < solblComplxsNew; ixM++) {
namnNew.ident[naOut+cs.nx + ixM] = identM.get(ixM);
csNew.lBeta[cs.nx + ixM] = lBetaM.get(ixM);
for(int ic=0; ic < naOut; ic++) {csNew.a[cs.nx + ixM][ic] = 0;}
for(int ic2=0; ic2 < cs2.Na; ic2++) {
csNew.a[cs.nx + ixM][namn2.iel[ic2]] = aM.get(ixM)[ic2];
}
}
//copy solid products
for(int if1=0; if1 < (mSol-cs.solidC); if1++) {
namnNew.ident[naOut+nxOut + if1] = namn.ident[cs.Na+cs.nx + if1];
csNew.lBeta[nxOut + if1] = cs.lBeta[cs.nx + if1];
for(int ic=0; ic < naOut; ic++) {csNew.a[nxOut + if1][ic] = 0;}
for(int ic1=0; ic1 < cs.Na; ic1++) {
csNew.a[nxOut + if1][namn.iel[ic1]] = cs.a[cs.nx + if1][ic1];
}
}
int soFar = nxOut + (mSol-cs.solidC);
for(int ifM = solblComplxsNew; ifM < solblComplxsNew+solidComplxsNew; ifM++) {
int ifS = ifM - solblComplxsNew;
namnNew.ident[naOut+soFar + ifS] = identM.get(ifM);
csNew.lBeta[soFar + ifS] = lBetaM.get(ifM);
for(int ic=0; ic < naOut; ic++) {csNew.a[soFar + ifS][ic] = 0;}
for(int ic2=0; ic2 < cs2.Na; ic2++) {
csNew.a[soFar + ifS][namn2.iel[ic2]] = aM.get(ifM)[ic2];
}
}
//--- add the "fictive" solids corresponding to any solid components
if(solidC_Out >0) {
int j,k;
for(int ic=0; ic < solidC_Out; ic++) {
j = (csNew.Ms-csNew.Na-solidC_Out) + ic;
k = (csNew.Na-solidC_Out)+ic;
csNew.lBeta[j] = 0;
for(int ic2=0; ic2 < csNew.Na; ic2++) {
if(ic2 == k) {csNew.a[j][ic2] = 1;} else {csNew.a[j][ic2] = 0;}
}
namnNew.ident[j+csNew.Na] = namnNew.identC[k];
csNew.noll[k] = true;
}
}
if(dbg) {
System.out.print("---- The merged ");
csNew.printChemSystem(System.out);
}
//--- if there is a plot deffinition and concentration(s) for File1,
// then the information is kept.
if(diagr.compMain >=0) {diagr.compMain = namn.iel[diagr.compMain];}
if(diagr.compX >=0) {diagr.compX = namn.iel[diagr.compX];}
if(diagr.compY >=0) {diagr.compY = namn.iel[diagr.compY];}
if(plotInfoGiven && dgrCNew != null) {
for(int ic1=0; ic1 < cs.Na; ic1++) {
if(dgrC.hur[ic1] >0) {
dgrCNew.hur[namn.iel[ic1]] = dgrC.hur[ic1];
dgrCNew.cLow[namn.iel[ic1]] = dgrC.cLow[ic1];
dgrCNew.cHigh[namn.iel[ic1]] = dgrC.cHigh[ic1];
}
}//for ic1
for(int ic2=0; ic2 < cs2.Na; ic2++) {
if(dgrC2.hur[ic2] >0) {
dgrCNew.hur[namn2.iel[ic2]] = dgrC2.hur[ic2];
dgrCNew.cLow[namn2.iel[ic2]] = dgrC2.cLow[ic2];
dgrCNew.cHigh[namn2.iel[ic2]] = dgrC2.cHigh[ic2];
}
}//for ic2
}//if there is plot info
//--- change the pointers from the old to the new instances
ch.chemSystem = csNew;
ch.chemSystem.namn = namnNew;
try{ch.diagrConcs = ch.new DiagrConcs(naOut);}
catch (Chem.ChemicalParameterException ex) {
MsgExceptn.showErrMsg(this, ex.getMessage(), 1);
System.err.println(Util.stack2string(ex));
return;}
this.cs = csNew;
this.namn = namnNew;
this.diagr = ch.diag;
this.dgrC = dgrCNew;
//--- is there a plot deffinition? check concentrations
if(plotInfoGiven && dgrC != null) {
for(int ic=0; ic < cs.Na; ic++) {
if(dgrC.hur[ic] <=0) {
DefaultPlotAndConcs.setDefaultConc(ic, namn.identC[ic], dgrC, pd.kth);
}//if no concentration range
}//for ic
}//if there is plot info
// --- if there are any solid components, add corresponding
// fictive solid products corresponding to the components
ReadChemSyst.addFictiveSolids(cs);
storeInitialSystem(ch);
modified = true;
merged = true;
if(dbg) {System.out.println(" ---- Merge successful.");}
setupFrame();
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
} //mergeTwoSystems()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="reactionText">
public static String reactionText(Chem.ChemSystem cs,
int complex, boolean logK) {
if(cs == null || cs.namn == null) {
return "** Error **";
}
if(complex < 0 || complex >= (cs.Ms-cs.Na)) {
return noReactionMessage;
}
boolean first = true;
String text = "";
String stoich;
double w;
for(int ic = 0; ic < cs.Na; ic++) {
w = cs.a[complex][ic];
if(w > 0) {
if(first) {stoich = ""; first = false;} else {stoich = " +";}
if (Math.abs(w-1)>1e-6) {stoich = stoich + Util.formatNumAsInt(w);}
text = text + stoich + " " + cs.namn.identC[ic];
}
} //for ic
text = text + " = "; first = true;
for(int ic = 0; ic < cs.Na; ic++) {
w = -cs.a[complex][ic];
if(w > 0) {
if(first) {stoich = ""; first = false;} else {stoich = " +";}
if (Math.abs(w-1)>1e-6) {stoich = stoich + Util.formatNumAsInt(w);}
text = text + stoich + " " + cs.namn.identC[ic];
}
} //for ic
if(first) {stoich = " ";} else {stoich = " + ";}
text = Util.rTrim(text) + stoich + cs.namn.ident[complex+cs.Na];
if(logK) {text = text + "; logK="+Util.formatNum(cs.lBeta[complex]);}
return text;
} //reactionText
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="readDataFile()">
/** Read a data file
* @param dtaFile the data file to read.
* @param dbg true if debug information is to be printed
* @return true if there is no error, false otherwise.
*/
private boolean readDataFile(java.io.File dtaFile, boolean dbg){
//--- create a ReadData instance
ReadDataLib rd;
try {rd = new ReadDataLib(dtaFile);}
catch (ReadDataLib.DataFileException ex) {
MsgExceptn.showErrMsg(this,ex.getMessage(),1);
return false;
}
if(dbg) {
System.out.println("- - - - - - - - - - - - - - - - - - - - - - - - - - -");
System.out.println("Reading input data file \""+dtaFile+"\"");
}
//--- read the chemical system (names, equilibrium constants, stoichiometry)
boolean warn = true; // report missing plot data as a warning
try {
chRead = ReadChemSyst.readChemSystAndPlotInfo(rd, dbg, warn, System.out);
}
catch (ReadChemSyst.DataLimitsException ex) {
System.err.println(ex.getMessage());
}
catch (ReadChemSyst.ReadDataFileException ex) {
System.err.println(ex.getMessage());
}
catch (ReadChemSyst.PlotDataException ex) {}
catch (ReadChemSyst.ConcDataException ex) {}
if(chRead == null) {
try {rd.close();}
catch (ReadDataLib.ReadDataLibException ex) {MsgExceptn.exception(ex.getMessage());}
MsgExceptn.showErrMsg(spana.MainFrame.getInstance(),
"Error while reading file"+nl+"\""+dtaFile+"\"", 1);
return false;
}
//--- get other information to be saved in the modified data file
//temperature written as a comment in the data file?
double w;
try{w = rd.getTemperature();}
catch(ReadDataLib.DataReadException ex) {System.err.println(nl+ex.getMessage()); w = 25;}
chRead.diag.temperature = w;
try{w = rd.getPressure();}
catch(ReadDataLib.DataReadException ex) {System.err.println(nl+ex.getMessage()); w = 1;}
chRead.diag.pressure = w;
// is there a title?
if(chRead.diag.plotType >= 0 && chRead.diagrConcs.hur[0] >= 1) {
try {chRead.diag.title = rd.readLine();}
catch (ReadDataLib.DataEofException ex) {chRead.diag.title = null;}
catch (ReadDataLib.DataReadException ex) {chRead.diag.title = null;}
}
//--- finished
try {rd.close();}
catch (ReadDataLib.ReadDataLibException ex) {
System.err.println(ex.getMessage());
return false;
}
if(dbg) {System.out.println("Finished reading the input data file");
System.out.println("- - - - - - - - - - - - - - - - - - - - - - - - - - -");
}
return true;
} // readDataFile()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="setupFrame()">
private void setupFrame() {
jTextFieldDataFile.setText(dataFile.getPath());
//--- Components
int solubleComps = cs.Na - cs.solidC;
if(solubleComps <=0) {jLabel1.setText("No Soluble Components");}
else if(solubleComps ==1) {jLabel1.setText("1 Soluble Component:");}
else if(solubleComps >1) {jLabel1.setText(solubleComps+" Soluble Components:");}
listSolubleCompModel.clear();
if(solubleComps>=1) {
for(int i=0; i < solubleComps; i++) {
listSolubleCompModel.addElement(namn.identC[i]);
}
}
if(cs.solidC <=0) {jLabel3.setText("No Solid Components");}
else if(cs.solidC ==1) {jLabel3.setText("1 Solid Component:");}
else if(cs.solidC >1) {jLabel3.setText(cs.solidC+" Solid Components:");}
listSolidCompModel.clear();
if(cs.solidC >=1) {
for(int i=solubleComps; i < cs.Na; i++) {
listSolidCompModel.addElement(namn.identC[i]);
}
}
//--- Complexes
if(cs.nx <=0) {jLabel2.setText("No Soluble Complexes");}
else if(cs.nx ==1) {jLabel2.setText("1 Soluble Complex:");}
else if(cs.nx >1) {jLabel2.setText(cs.nx+" Soluble Complexes:");}
listSolubleCmplxModel.clear();
if(cs.nx >=1) {
for(int i=cs.Na; i < cs.Na+cs.nx; i++) {
listSolubleCmplxModel.addElement(namn.ident[i]);
}
}
int solidComplexes = cs.mSol-cs.solidC;
if(solidComplexes <=0) {jLabel4.setText("No Solid Products");}
else if(solidComplexes ==1) {jLabel4.setText("1 Solid Product:");}
else if(solidComplexes >1) {jLabel4.setText(solidComplexes+" Solid Products:");}
listSolidCmplxModel.clear();
if(solidComplexes >=1) {
for(int i=(cs.Na+cs.nx); i < cs.Ms-cs.solidC; i++) {
listSolidCmplxModel.addElement(namn.ident[i]);
}
}
//---
if(!modified) {
jTextFieldDataFile.setEnabled(true);
} else {
java.awt.CardLayout cl = (java.awt.CardLayout)jPanel1Top.getLayout();
cl.show(jPanel1Top, "cardNewSystem");
jTextFieldDataFile.setEnabled(false);
}
jButton_Delete.setEnabled(true);
jButton_Delete.setText("<html><u>D</u>elete</html>");
jButton_Delete.setForeground(java.awt.Color.black);
jButton_Exchange.setEnabled(true);
jButton_Exchange.setForeground(java.awt.Color.black);
jButton_Merge.setEnabled(true);
jButton_Merge.setForeground(java.awt.Color.black);
jButton_Save.setEnabled(true);
jButton_Save.setForeground(java.awt.Color.black);
jButton_Save.setText("<html><u>S</u>ave & exit</html>");
jButtonUp.setEnabled(false);
jButtonDn.setEnabled(false);
//---
if(listSolubleCmplxModel.getSize() <=0 &&
listSolidCmplxModel.getSize() <=0) {
jButton_Exchange.setEnabled(false);
jButton_Exchange.setForeground(java.awt.Color.gray);
}
//---
} //setupFrame()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="storeInitialSystem(chem)">
/** Store the names of the components in the axes, etc,
* needed by checkPlotInfo() */
private void storeInitialSystem(Chem chem) {
Na0 = chem.chemSystem.Na;
if(chem.diag.compX >= 0) {compXname0= chem.chemSystem.namn.identC[chem.diag.compX];}
if(chem.diag.compY >= 0) {compYname0= chem.chemSystem.namn.identC[chem.diag.compY];}
if(chem.diag.compMain >= 0) {compMainName0= chem.chemSystem.namn.identC[chem.diag.compMain];}
if(identC0.size()>0) { //empty the ArrayList
for(int i = identC0.size()-1; i>=0 ; i--) {identC0.remove(i);}
}
for(int i=0; i < chem.chemSystem.Na; i++) {identC0.add(i, chem.chemSystem.namn.identC[i]);}
}//storeInitialSystem
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="upDownComponent()">
/** Move the selected component "up" or "down" one position in the
* component list.
* @param up if true the component is moved one step closser to zero (move up),
* if false the orther of component is increased by one (moved down).*/
private void upDownComponent(boolean up) {
// which component is selected?
// is the move possible?
boolean impossibleMove = false;
int compToMove;
String compToMoveName;
compToMove = jListSolubComps.getSelectedIndex();
if(compToMove >= 0) {
if(compToMove == 0 && up) {impossibleMove = true;}
if(compToMove >= (listSolubleCompModel.getSize()-1) && !up) {impossibleMove = true;}
compToMoveName = jListSolubComps.getSelectedValue().toString();
} else {
compToMove = jListSolidComps.getSelectedIndex();
if(compToMove == 0 && up) {impossibleMove = true;}
if(compToMove >= (listSolidCompModel.getSize()-1) && !up) {impossibleMove = true;}
compToMoveName = jListSolidComps.getSelectedValue().toString();
if(compToMove>=0) {compToMove = compToMove +(cs.Na - cs.solidC);}
}
if(impossibleMove) {
String move = "up"; if(!up) {move = "down";}
System.err.println("Programming error: impossible move \""+move+"\""+
" of component "+compToMove+" \""+compToMoveName+"\"");
setupFrame();
return;
}
// check that a component is indeed selected
if(compToMove < 0) {
String msg = "list";
if(listSolubleCompModel.getSize() > 0 && listSolidCompModel.getSize() > 0) {msg = "lists";}
javax.swing.JOptionPane.showMessageDialog(this, "Please, select one component from the "+msg+".", "Modify Chemical System", javax.swing.JOptionPane.WARNING_MESSAGE);
setupFrame();
return;
}
disableButtons();
double w;
int otherCompMoved;
if(up) {otherCompMoved = compToMove -1;}
else {otherCompMoved = compToMove +1;}
setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
for(int ic=0; ic < cs.Na; ic++) {namn.iel[ic] = ic;}
namn.iel[otherCompMoved] = compToMove;
namn.iel[compToMove] = otherCompMoved;
//move info on components
String other = namn.identC[otherCompMoved];
namn.identC[otherCompMoved] = compToMoveName;
namn.identC[compToMove] = other;
namn.ident[otherCompMoved] = namn.identC[otherCompMoved];
namn.ident[compToMove] = namn.identC[compToMove];
boolean plotInfoGiven = false;
if(diagr.plotType >=0 && diagr.compX >=0 && dgrC.hur[0] >=1) {plotInfoGiven = true;}
if(plotInfoGiven) {
diagr.compX = namn.iel[diagr.compX];
if(diagr.compY >=0) {diagr.compY = namn.iel[diagr.compY];}
if(diagr.compMain >=0) {diagr.compMain = namn.iel[diagr.compMain];}
int otherHur = dgrC.hur[otherCompMoved];
dgrC.hur[otherCompMoved] = dgrC.hur[compToMove];
dgrC.hur[compToMove] = otherHur;
w = dgrC.cLow[otherCompMoved];
dgrC.cLow[otherCompMoved] = dgrC.cLow[compToMove];
dgrC.cLow[compToMove] = w;
w = dgrC.cHigh[otherCompMoved];
dgrC.cHigh[otherCompMoved] = dgrC.cHigh[compToMove];
dgrC.cHigh[compToMove] = w;
}
//move stoichiometric coefficients
for(int ix=0; ix < cs.Ms-cs.Na; ix++) {
w = cs.a[ix][otherCompMoved];
cs.a[ix][otherCompMoved] = cs.a[ix][compToMove];
cs.a[ix][compToMove] = w;
}//for ix
modified = true;
storeInitialSystem(ch);
setupFrame();
//select (highlight) the component that has been moved
if(compToMove < cs.Na-cs.solidC) {
jListSolubComps.setSelectedIndex(otherCompMoved);
} else {
jListSolidComps.setSelectedIndex(otherCompMoved - (cs.Na-cs.solidC));
}
component_Click();
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
} //upDownComponent()
//</editor-fold>
//</editor-fold>
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButtonDn;
private javax.swing.JButton jButtonUp;
private javax.swing.JButton jButton_Delete;
private javax.swing.JButton jButton_Exchange;
private javax.swing.JButton jButton_Merge;
private javax.swing.JButton jButton_Quit;
private javax.swing.JButton jButton_Save;
private javax.swing.JLabel jLabel0;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabelReaction;
private javax.swing.JList jListSolidCmplx;
private javax.swing.JList jListSolidComps;
private javax.swing.JList jListSolubCmplx;
private javax.swing.JList jListSolubComps;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel10;
private javax.swing.JPanel jPanel11;
private javax.swing.JPanel jPanel1Top;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel2down;
private javax.swing.JPanel jPanel2up;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel8;
private javax.swing.JPanel jPanelDataFile;
private javax.swing.JPanel jPanelNew;
private javax.swing.JPanel jPanelUpDown;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JTextField jTextFieldDataFile;
// End of variables declaration//GEN-END:variables
}
| 125,747 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
OptionsGeneral.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Spana/src/spana/OptionsGeneral.java | package spana;
import lib.common.Util;
import lib.huvud.Div;
import lib.huvud.ProgramConf;
/** Options dialog for general program behaviour.
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class OptionsGeneral extends javax.swing.JFrame {
private boolean finished = false;
private java.awt.Dimension windowSize;
private ProgramConf pc;
private final ProgramDataSpana pd;
private static lib.huvud.RedirectedFrame msgFrame = null;
private boolean associateDAT0, associatePLT0;
/** Windows only: the full path of the application exe-file,
* used when associating file types. Null if the user can not make file
* associations (e.g if not admin rights) */
private final String pathToExecute;
/** New-line character(s) to substitute "\n". */
private static final String nl = System.getProperty("line.separator");
private static final String SLASH = java.io.File.separator;
//<editor-fold defaultstate="collapsed" desc="Constructor">
/** Creates new form OptionsGeneral
* @param pc0
* @param pd0
* @param msgF */
public OptionsGeneral(ProgramConf pc0, ProgramDataSpana pd0, lib.huvud.RedirectedFrame msgF) {
initComponents();
this.pc = pc0;
this.pd = pd0;
msgFrame = msgF;
finished = false;
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
//--- close window on ESC key
javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE");
javax.swing.Action escAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
closeWindow();
}};
getRootPane().getActionMap().put("ESCAPE", escAction);
//--- F1 for help
javax.swing.KeyStroke f1KeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(f1KeyStroke,"F1");
javax.swing.Action f1Action = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
OptionsGeneral.this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
Thread hlp = new Thread() {@Override public void run(){
String[] a = {"S_Menu_Prefs_htm"};
lib.huvud.RunProgr.runProgramInProcess(OptionsGeneral.this,ProgramConf.HELP_JAR,a,false,pc.dbg,pc.pathAPP);
try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec
catch (InterruptedException e) {}
OptionsGeneral.this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
}};//new Thread
hlp.start();
}};
getRootPane().getActionMap().put("F1", f1Action);
//--- Alt-H help
javax.swing.KeyStroke altHKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_H, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altHKeyStroke,"ALT_H");
getRootPane().getActionMap().put("ALT_H", f1Action);
//--- alt-X
javax.swing.KeyStroke altXKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altXKeyStroke,"ALT_X");
javax.swing.Action altXAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jButton_OK.doClick();
}};
getRootPane().getActionMap().put("ALT_X", altXAction);
//--- alt-P
javax.swing.KeyStroke altPKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altPKeyStroke,"ALT_P");
javax.swing.Action altPAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jTextF_ISP.requestFocus(); jTextF_ISPMouseClicked(null);
}};
getRootPane().getActionMap().put("ALT_P", altPAction);
//--- alt-C
javax.swing.KeyStroke altCKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altCKeyStroke,"ALT_C");
javax.swing.Action altCAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jTextFnewData.requestFocus();
jTextFnewDataMouseClicked(null);
}};
getRootPane().getActionMap().put("ALT_C", altCAction);
//--- alt-T
javax.swing.KeyStroke altTKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altTKeyStroke,"ALT_T");
javax.swing.Action altTAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jTextFedit.requestFocus();
jTextFeditMouseClicked(null);
}};
getRootPane().getActionMap().put("ALT_T", altTAction);
//
//--- Title
this.setTitle("Preferences:");
//--- Icon
String iconName = "images/Wrench_32x32.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
if (imgURL != null) {this.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());}
else {System.out.println("Error: Could not load image = \""+iconName+"\"");}
//if(MainFrame.windows && (!isAdmin() || !canWriteToProgramFiles())) {
// jLabelNote.setText("You have no \"admin\" rights...");
//}
if(MainFrame.windows //&& isAdmin() && canWriteToProgramFiles()
&& pc.pathAPP != null && pc.pathAPP.trim().length()>0) {
String dir = pc.pathAPP;
if(dir.endsWith(SLASH)) {dir = dir.substring(0,dir.length()-1);}
pathToExecute = dir +SLASH+ pc.progName+".exe";
} else {pathToExecute = null;}
setupFrame();
frameResize();
//center Window on Screen
int left; int top;
left = Math.max(55, (MainFrame.screenSize.width - windowSize.width ) / 2);
top = Math.max(10, (MainFrame.screenSize.height - windowSize.height) / 2);
this.setLocation(Math.min(MainFrame.screenSize.width-100, left),
Math.min(MainFrame.screenSize.height-100, top));
setVisible(true);
} // constructor
public static boolean isAdmin() {
String groups[];
try {
groups = (new com.sun.security.auth.module.NTSystem()).getGroupIDs();
} catch (Exception e) {return false;}
if(groups == null || groups.length <= 0) {return false;}
for (String group : groups) {
if (group.equals("S-1-5-32-544"))
return true;
}
return false;
}
public static boolean isAdmin2(){
java.util.prefs.Preferences prefs = java.util.prefs.Preferences.systemRoot();
try{
prefs.put("foo", "bar"); // SecurityException on Windows
prefs.remove("foo");
prefs.flush(); // BackingStoreException on Linux
return true;
}catch(java.util.prefs.BackingStoreException e){return false;}
}
/**
private boolean canWriteToProgramFiles() {
try {
String programFiles = System.getenv("ProgramFiles");
if(programFiles == null) {programFiles = "C:\\Program Files";}
java.io.File temp = new java.io.File(programFiles, "deleteMe.txt");
if(temp.createNewFile()) {
temp.delete();
return true;
} else {return false;}
} catch (java.io.IOException e) {return false;}
}
*/
//</editor-fold>
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
jPanelLevel = new javax.swing.JPanel();
jRadioB_LevelNorm = new javax.swing.JRadioButton();
jRadioB_LevelAdv = new javax.swing.JRadioButton();
jPanelButtons = new javax.swing.JPanel();
jButton_OK = new javax.swing.JButton();
jButton_Cancel = new javax.swing.JButton();
jButton_Reset = new javax.swing.JButton();
jPanelAdv = new javax.swing.JPanel();
jLabel_ISP = new javax.swing.JLabel();
jTextF_ISP = new javax.swing.JTextField();
jLabelFnewData = new javax.swing.JLabel();
jTextFnewData = new javax.swing.JTextField();
jLabelFedit = new javax.swing.JLabel();
jTextFedit = new javax.swing.JTextField();
jLabelDebug = new javax.swing.JLabel();
jCheckBoxOutput = new javax.swing.JCheckBox();
jLabelOutput = new javax.swing.JLabel();
jPanelAssoc = new javax.swing.JPanel();
jCheckBoxDat = new javax.swing.JCheckBox();
jCheckBoxPlt = new javax.swing.JCheckBox();
jLabelNote = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jPanelLevel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, " Program Level: ", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11), new java.awt.Color(51, 51, 255))); // NOI18N
buttonGroup1.add(jRadioB_LevelNorm);
jRadioB_LevelNorm.setMnemonic('n');
jRadioB_LevelNorm.setSelected(true);
jRadioB_LevelNorm.setText("<html><u>n</u>ormal</html>"); // NOI18N
jRadioB_LevelNorm.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioB_LevelNormActionPerformed(evt);
}
});
buttonGroup1.add(jRadioB_LevelAdv);
jRadioB_LevelAdv.setMnemonic('a');
jRadioB_LevelAdv.setText("<html><u>a</u>dvanced</html>"); // NOI18N
jRadioB_LevelAdv.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioB_LevelAdvActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanelLevelLayout = new javax.swing.GroupLayout(jPanelLevel);
jPanelLevel.setLayout(jPanelLevelLayout);
jPanelLevelLayout.setHorizontalGroup(
jPanelLevelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelLevelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelLevelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jRadioB_LevelNorm, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jRadioB_LevelAdv, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(28, Short.MAX_VALUE))
);
jPanelLevelLayout.setVerticalGroup(
jPanelLevelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelLevelLayout.createSequentialGroup()
.addComponent(jRadioB_LevelNorm, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jRadioB_LevelAdv, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jButton_OK.setIcon(new javax.swing.ImageIcon(getClass().getResource("/spana/images/OK_32x32.gif"))); // NOI18N
jButton_OK.setMnemonic('O');
jButton_OK.setText("OK");
jButton_OK.setToolTipText("OK (Alt-O orAlt-X)"); // NOI18N
jButton_OK.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButton_OK.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButton_OK.setMargin(new java.awt.Insets(2, 2, 2, 2));
jButton_OK.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jButton_OK.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_OKActionPerformed(evt);
}
});
jButton_Cancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/spana/images/Trash.gif"))); // NOI18N
jButton_Cancel.setMnemonic('Q');
jButton_Cancel.setText("Quit");
jButton_Cancel.setToolTipText("Cancel (Esc or Alt-Q)"); // NOI18N
jButton_Cancel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButton_Cancel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButton_Cancel.setMargin(new java.awt.Insets(2, 2, 2, 2));
jButton_Cancel.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jButton_Cancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_CancelActionPerformed(evt);
}
});
jButton_Reset.setIcon(new javax.swing.ImageIcon(getClass().getResource("/spana/images/Setup.gif"))); // NOI18N
jButton_Reset.setMnemonic('R');
jButton_Reset.setText("Reset");
jButton_Reset.setToolTipText("Reset to default values (Alt-R)"); // NOI18N
jButton_Reset.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButton_Reset.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButton_Reset.setMargin(new java.awt.Insets(2, 2, 2, 2));
jButton_Reset.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jButton_Reset.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_ResetActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanelButtonsLayout = new javax.swing.GroupLayout(jPanelButtons);
jPanelButtons.setLayout(jPanelButtonsLayout);
jPanelButtonsLayout.setHorizontalGroup(
jPanelButtonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelButtonsLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton_OK)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton_Cancel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton_Reset)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelButtonsLayout.setVerticalGroup(
jPanelButtonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelButtonsLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanelButtonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton_OK)
.addComponent(jButton_Cancel)
.addComponent(jButton_Reset)))
);
jLabel_ISP.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel_ISP.setForeground(new java.awt.Color(51, 51, 255));
jLabel_ISP.setText("<html><u>P</u>ath to SED and PREDOM:</html>"); // NOI18N
jTextF_ISP.setText("jTextField1"); // NOI18N
jTextF_ISP.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextF_ISPFocusGained(evt);
}
});
jTextF_ISP.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTextF_ISPKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextF_ISPKeyTyped(evt);
}
});
jTextF_ISP.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTextF_ISPMouseClicked(evt);
}
});
jLabelFnewData.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabelFnewData.setForeground(new java.awt.Color(51, 51, 255));
jLabelFnewData.setText("<html>Program used to <u>c</u>reate new data files:</html>"); // NOI18N
jTextFnewData.setText("jTextField2"); // NOI18N
jTextFnewData.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTextFnewDataMouseClicked(evt);
}
});
jTextFnewData.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextFnewDataFocusGained(evt);
}
});
jTextFnewData.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTextFnewDataKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextFnewDataKeyTyped(evt);
}
});
jLabelFedit.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabelFedit.setForeground(new java.awt.Color(102, 102, 102));
jLabelFedit.setText("<html><u>T</u>ext editor:</html>"); // NOI18N
jTextFedit.setText("jTextField3"); // NOI18N
jTextFedit.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextFeditFocusGained(evt);
}
});
jTextFedit.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTextFeditKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextFeditKeyTyped(evt);
}
});
jTextFedit.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTextFeditMouseClicked(evt);
}
});
jLabelDebug.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabelDebug.setForeground(new java.awt.Color(51, 51, 255));
jLabelDebug.setLabelFor(jCheckBoxOutput);
jLabelDebug.setText("Debugging:"); // NOI18N
jCheckBoxOutput.setMnemonic('v');
jCheckBoxOutput.setText("<html><u>V</u>erbose output of program messages</html>"); // NOI18N
jLabelOutput.setLabelFor(jCheckBoxOutput);
jLabelOutput.setText("<html>Note: messages and errors are written to a separate frame<br>which is shown / hidden from menu "Preferences"</html>"); // NOI18N
jLabelOutput.setVerticalAlignment(javax.swing.SwingConstants.TOP);
jPanelAssoc.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Associate file extensions with this program: ", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11), new java.awt.Color(51, 51, 255))); // NOI18N
jCheckBoxDat.setText("<html><b>.</b><u>D</u>AT</html>"); // NOI18N
jCheckBoxDat.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxDatActionPerformed(evt);
}
});
jCheckBoxPlt.setText("<html><b>.</b>P<u>L</u>T</html>"); // NOI18N
jCheckBoxPlt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxPltActionPerformed(evt);
}
});
jLabelNote.setText("<html>Note: this might conflict with other<br>programs installed on your computer</html>"); // NOI18N
javax.swing.GroupLayout jPanelAssocLayout = new javax.swing.GroupLayout(jPanelAssoc);
jPanelAssoc.setLayout(jPanelAssocLayout);
jPanelAssocLayout.setHorizontalGroup(
jPanelAssocLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelAssocLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelAssocLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jCheckBoxDat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jCheckBoxPlt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jLabelNote, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelAssocLayout.setVerticalGroup(
jPanelAssocLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelAssocLayout.createSequentialGroup()
.addComponent(jCheckBoxDat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(1, 1, 1)
.addComponent(jCheckBoxPlt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabelNote, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
);
javax.swing.GroupLayout jPanelAdvLayout = new javax.swing.GroupLayout(jPanelAdv);
jPanelAdv.setLayout(jPanelAdvLayout);
jPanelAdvLayout.setHorizontalGroup(
jPanelAdvLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelAdvLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelAdvLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextFnewData)
.addComponent(jTextF_ISP)
.addComponent(jTextFedit)
.addComponent(jLabelOutput, javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanelAdvLayout.createSequentialGroup()
.addGroup(jPanelAdvLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel_ISP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelFnewData, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelFedit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanelAdvLayout.createSequentialGroup()
.addComponent(jLabelDebug)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jCheckBoxOutput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
.addComponent(jPanelAssoc, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanelAdvLayout.setVerticalGroup(
jPanelAdvLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelAdvLayout.createSequentialGroup()
.addComponent(jLabel_ISP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextF_ISP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabelFnewData, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextFnewData, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabelFedit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextFedit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanelAdvLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelDebug)
.addComponent(jCheckBoxOutput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelOutput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE)
.addComponent(jPanelAssoc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanelLevel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(50, 50, 50)
.addComponent(jPanelButtons, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 56, Short.MAX_VALUE))
.addComponent(jPanelAdv, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanelButtons, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanelLevel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(10, 10, 10)
.addComponent(jPanelAdv, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
//<editor-fold defaultstate="collapsed" desc="Events">
private void jRadioB_LevelNormActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioB_LevelNormActionPerformed
frameResize();
}//GEN-LAST:event_jRadioB_LevelNormActionPerformed
private void jRadioB_LevelAdvActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioB_LevelAdvActionPerformed
frameResize();
}//GEN-LAST:event_jRadioB_LevelAdvActionPerformed
private void jButton_OKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_OKActionPerformed
pd.advancedVersion = jRadioB_LevelAdv.isSelected();
if(jTextF_ISP.getText() != null) {MainFrame.pathSedPredom = jTextF_ISP.getText();}
if(jTextFnewData.getText() != null) {MainFrame.createDataFileProg = jTextFnewData.getText();}
if(jTextFedit.getText() != null) {MainFrame.txtEditor = jTextFedit.getText();}
pc.dbg = jCheckBoxOutput.isSelected();
if(MainFrame.windows && pathToExecute != null) { // Windows registry
boolean changed = false;
try{
if(!associateDAT0 && jCheckBoxDat.isSelected()) {
System.out.println("Associating \"dat\" files.");
FileAssociation.associateFileExtension("dat", pathToExecute);
changed = true;
} else if(associateDAT0 && !jCheckBoxDat.isSelected()) {
System.out.println("Un-associating \"dat\" files.");
FileAssociation.unAssociateFileExtension("dat");
changed = true;
}
} catch (java.io.IOException ex) {System.out.println(ex.getMessage());}
catch (IllegalAccessException ex) {System.out.println(ex.getMessage());}
catch (IllegalArgumentException ex) {System.out.println(ex.getMessage());}
catch (java.lang.reflect.InvocationTargetException ex) {System.out.println(ex.getMessage());}
catch (java.net.URISyntaxException ex) {System.out.println(ex.getMessage());}
try{
if(!associatePLT0 && jCheckBoxPlt.isSelected()) {
System.out.println("Associating \"plt\" files.");
FileAssociation.associateFileExtension("plt", pathToExecute);
changed = true;
} else if(associatePLT0 && !jCheckBoxPlt.isSelected()) {
System.out.println("Un-associating \"plt\" files.");
FileAssociation.unAssociateFileExtension("plt");
changed = true;
}
} catch (java.io.IOException ex) {System.out.println(ex.getMessage());}
catch (IllegalAccessException ex) {System.out.println(ex.getMessage());}
catch (IllegalArgumentException ex) {System.out.println(ex.getMessage());}
catch (java.lang.reflect.InvocationTargetException ex) {System.out.println(ex.getMessage());}
catch (java.net.URISyntaxException ex) {System.out.println(ex.getMessage());}
if(changed) {
//--- Call "shell32.dll", SHChangeNotify to update icons in folders
// -- alternative: call a NSIS script:
lib.huvud.RunProgr.runProgramInProcess(OptionsGeneral.this,
"ShellChangeNotify.exe",null,false,
pc.dbg,pc.pathAPP);
// -- alternative using NativeCall
//try{
// NativeCall.init();
// VoidCall ic = new VoidCall("shell32.dll","SHChangeNotify");
// int SHCNE_ASSOCCHANGED = 0x8000000; int SHCNF_IDLIST = 0x0000000;
// ic.executeCall(new Object[] { SHCNE_ASSOCCHANGED, SHCNF_IDLIST, 0, 0 });
// ic.destroy();
//} catch (Exception ex) {
// //notify the user?
//}
}
} // if Windows
closeWindow();
}//GEN-LAST:event_jButton_OKActionPerformed
private void jButton_CancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_CancelActionPerformed
closeWindow();
}//GEN-LAST:event_jButton_CancelActionPerformed
private void jButton_ResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_ResetActionPerformed
Object[] options = {"OK", "Cancel"};
int n = javax.swing.JOptionPane.showOptionDialog(this,
"Do you wish to set ALL program settings"+nl+
"(general options, graphic window preferences, etc)"+nl+
"to default values?",
pc.progName, javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE, null, options, null);
if (n == javax.swing.JOptionPane.YES_OPTION) { //the first button is "ok"
options[0] = "Yes";
n = javax.swing.JOptionPane.showOptionDialog(this,
"Are you sure?",
pc.progName, javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE, null, options, null);
if(n == javax.swing.JOptionPane.YES_OPTION) { //the first button is "yes"
MainFrame.getInstance().iniDefaults();
setupFrame();
frameResize();
}
}
}//GEN-LAST:event_jButton_ResetActionPerformed
private void jTextF_ISPFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextF_ISPFocusGained
jTextF_ISP.selectAll();
}//GEN-LAST:event_jTextF_ISPFocusGained
private void jTextF_ISPKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextF_ISPKeyPressed
if(!Util.isKeyPressedOK(evt)) {evt.consume();}
}//GEN-LAST:event_jTextF_ISPKeyPressed
private void jTextF_ISPKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextF_ISPKeyTyped
if(consumeKeyTyped(evt)) {
evt.consume();
jTextF_ISPMouseClicked(null);
}
}//GEN-LAST:event_jTextF_ISPKeyTyped
private void jTextF_ISPMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextF_ISPMouseClicked
// Ask the user for a file name using a Open File dialog
java.io.File currDir;
if(MainFrame.pathSedPredom != null) {currDir = new java.io.File(MainFrame.pathSedPredom);}
else if(pc.pathAPP != null) {currDir = new java.io.File(pc.pathAPP);}
else {currDir = new java.io.File(System.getProperty("user.dir"));}
boolean mustExist = true;
boolean openF = true;
boolean filesOnly = false;
String dir = Util.getFileName(this, pc.progName, openF, mustExist, filesOnly,
"Select either a program or a directory:", 1, "SED.jar", currDir.getPath());
if(dir == null || dir.length() <=0) {return;}
java.io.File f = new java.io.File(dir);
//if(!f.isDirectory()) {f = MainFrame.fc.getCurrentDirectory();}
if(!f.isDirectory()) {
f = f.getParentFile();
}
dir = null;
try {dir = f.getCanonicalPath();} catch (java.io.IOException ex) {}
if (dir == null) {
try {dir = f.getAbsolutePath();} catch (Exception ex) {dir = f.getPath();}
}
String msg = null;
if(!Div.progSEDexists(f)) {msg = " SED";}
if(!Div.progPredomExists(f)) {
if(msg == null) {msg = " Predom";} else {msg = "s SED and Predom";}
}
if(msg != null) {
javax.swing.JOptionPane.showMessageDialog(this,
"Program"+msg+" not found in the slected directory:" +nl+
"\""+dir+"\""+nl+nl+
"Selection discarded.",
pc.progName+" Preferences", javax.swing.JOptionPane.ERROR_MESSAGE);
return;
}
jTextF_ISP.setText(dir);
}//GEN-LAST:event_jTextF_ISPMouseClicked
private void jTextFnewDataFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFnewDataFocusGained
jTextFnewData.selectAll();
}//GEN-LAST:event_jTextFnewDataFocusGained
private void jTextFnewDataKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFnewDataKeyPressed
if(!Util.isKeyPressedOK(evt)) {evt.consume();}
}//GEN-LAST:event_jTextFnewDataKeyPressed
private void jTextFnewDataKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFnewDataKeyTyped
if(consumeKeyTyped(evt)) {
evt.consume();
jTextFnewDataMouseClicked(null);
}
}//GEN-LAST:event_jTextFnewDataKeyTyped
private void jTextFnewDataMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFnewDataMouseClicked
boolean mustExist = true;
String prgr = Util.getOpenFileName(this, pc.progName, mustExist,
"Select a program:", 1, "DataBase.jar", pc.pathAPP);
if(prgr == null || prgr.length() <=0) {return;}
java.io.File f = new java.io.File(prgr);
String fName = null;
try {fName = f.getCanonicalPath();} catch (java.io.IOException ex) {}
if(fName == null) {
try {fName = f.getAbsolutePath();} catch (Exception ex) {fName = f.getPath();}
}
jTextFnewData.setText(fName);
}//GEN-LAST:event_jTextFnewDataMouseClicked
private void jTextFeditFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFeditFocusGained
jTextFedit.selectAll();
}//GEN-LAST:event_jTextFeditFocusGained
private void jTextFeditKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFeditKeyPressed
if(!Util.isKeyPressedOK(evt)) {evt.consume();}
}//GEN-LAST:event_jTextFeditKeyPressed
private void jTextFeditKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFeditKeyTyped
if(consumeKeyTyped(evt)) {
evt.consume();
jTextFeditMouseClicked(null);
}
}//GEN-LAST:event_jTextFeditKeyTyped
private void jTextFeditMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFeditMouseClicked
// Ask the user for a file name using a Open File dialog
String edt = Util.getOpenFileName(this, pc.progName, true,
"Select an editor:", 1, null, pc.pathAPP);
if(edt == null || edt.length() <=0) {return;}
java.io.File f = new java.io.File(edt);
String fName = null;
try {fName = f.getCanonicalPath();} catch (java.io.IOException ex) {}
if (fName == null) {
try {fName = f.getAbsolutePath();} catch (Exception ex) {fName = f.getPath();}
}
jTextFedit.setText(fName);
}//GEN-LAST:event_jTextFeditMouseClicked
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
closeWindow();
}//GEN-LAST:event_formWindowClosing
private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
if(windowSize != null) {
int w = windowSize.width;
int h = windowSize.height;
if(this.getHeight()<h){this.setSize(this.getWidth(), h);}
if(this.getWidth()<w){this.setSize(w,this.getHeight());}
}
}//GEN-LAST:event_formComponentResized
private void jCheckBoxDatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxDatActionPerformed
if((jCheckBoxDat.isSelected())
|| (jCheckBoxPlt.isSelected())) {
jLabelNote.setVisible(true);
} else {
jLabelNote.setVisible(false);
}
}//GEN-LAST:event_jCheckBoxDatActionPerformed
private void jCheckBoxPltActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxPltActionPerformed
if((jCheckBoxDat.isSelected()) || (jCheckBoxPlt.isSelected())) {
jLabelNote.setVisible(true);
} else {
jLabelNote.setVisible(false);
}
}//GEN-LAST:event_jCheckBoxPltActionPerformed
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Methods">
private void closeWindow() {
finished = true;
this.notify_All();
this.dispose();
} // closeWindow()
private synchronized void notify_All() {notifyAll();}
/** this method will wait for this dialog frame to be closed */
public synchronized void waitFor() {
while(!finished) {
try {wait();} catch (InterruptedException ex) {}
} // while
} // waitFor()
private void frameResize() {
if(jRadioB_LevelNorm.isSelected()) {
jPanelAdv.setVisible(false);
jPanelAssoc.setVisible(false);
pack();
windowSize = this.getSize();
} else {
jPanelAdv.setVisible(true);
if(MainFrame.windows) {jPanelAssoc.setVisible(true);}
pack();
windowSize = this.getSize();
}
}
private boolean consumeKeyTyped(java.awt.event.KeyEvent evt) {
char c = Character.toUpperCase(evt.getKeyChar());
if(!Character.isISOControl(evt.getKeyChar()) &&
evt.getKeyChar() != java.awt.event.KeyEvent.VK_ESCAPE ) {
if (!( evt.isAltDown() &&
(evt.getKeyChar() != java.awt.event.KeyEvent.VK_ENTER ||
(c == 'N') || (c == 'A') || (c == 'P') || (c == 'C') ||
(c == 'T') || (c == 'K') || (c == 'D') || (c == 'L') ||
(c == 'O') || (c == 'X') || (c == 'Q')) )) {
return true;
}
}
return false;
}
private void setupFrame() {
if(pd.advancedVersion) {jRadioB_LevelAdv.setSelected(true);}
else {jRadioB_LevelNorm.setSelected(true);}
if(MainFrame.pathSedPredom != null) {
jTextF_ISP.setText(MainFrame.pathSedPredom);
} else {jTextF_ISP.setText("");}
if(MainFrame.createDataFileProg != null) {
jTextFnewData.setText(MainFrame.createDataFileProg);
} else {jTextFnewData.setText("");}
if(MainFrame.txtEditor != null) {
jTextFedit.setText(MainFrame.txtEditor);
} else {jTextFedit.setText("");}
if(System.getProperty("os.name").startsWith("Mac OS")) {
jLabelFedit.setForeground(new java.awt.Color(102, 102, 102));
jTextFedit.setEnabled(false);
} else { // not MacOS
jLabelFedit.setForeground(new java.awt.Color(51, 51, 255));
jTextFedit.setEnabled(true);
}
jCheckBoxOutput.setSelected(pc.dbg);
if(!MainFrame.windows) {
jPanelAssoc.setVisible(false);
} else { // Windows
jPanelAssoc.setVisible(true);
associateDAT0 = false;
associatePLT0 = false;
if(pathToExecute != null) { // look at Windows registry
boolean msgFramePopUp = msgFrame.isPopupOnErr();
msgFrame.setPopupOnErr(false);
try {
associateDAT0 = FileAssociation.isAssociated("dat", pathToExecute);
associatePLT0 = FileAssociation.isAssociated("plt", pathToExecute);
}
catch (IllegalAccessException ex) {System.out.println(ex.getMessage());}
catch (IllegalArgumentException ex) {System.out.println(ex.getMessage());}
catch (java.lang.reflect.InvocationTargetException ex) {System.out.println(ex.getMessage());}
msgFrame.setPopupOnErr(msgFramePopUp);
jCheckBoxDat.setSelected(associateDAT0);
jCheckBoxPlt.setSelected(associatePLT0);
if(associateDAT0 || associatePLT0) {
jLabelNote.setVisible(true);
} else {jLabelNote.setVisible(false);}
} else {
jCheckBoxDat.setText(".DAT");
jCheckBoxDat.setEnabled(false);
jCheckBoxPlt.setText(".PLT");
jCheckBoxPlt.setEnabled(false);
}
} // windows
} //setupFrame
//</editor-fold>
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JButton jButton_Cancel;
private javax.swing.JButton jButton_OK;
private javax.swing.JButton jButton_Reset;
private javax.swing.JCheckBox jCheckBoxDat;
private javax.swing.JCheckBox jCheckBoxOutput;
private javax.swing.JCheckBox jCheckBoxPlt;
private javax.swing.JLabel jLabelDebug;
private javax.swing.JLabel jLabelFedit;
private javax.swing.JLabel jLabelFnewData;
private javax.swing.JLabel jLabelNote;
private javax.swing.JLabel jLabelOutput;
private javax.swing.JLabel jLabel_ISP;
private javax.swing.JPanel jPanelAdv;
private javax.swing.JPanel jPanelAssoc;
private javax.swing.JPanel jPanelButtons;
private javax.swing.JPanel jPanelLevel;
private javax.swing.JRadioButton jRadioB_LevelAdv;
private javax.swing.JRadioButton jRadioB_LevelNorm;
private javax.swing.JTextField jTextF_ISP;
private javax.swing.JTextField jTextFedit;
private javax.swing.JTextField jTextFnewData;
// End of variables declaration//GEN-END:variables
}
| 47,181 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
WinRegistry.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Spana/src/spana/WinRegistry.java | package spana;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/** Adapted from http://www.rgagnon.com/javadetails/java-0630.html<br>
* <br>
* The JDK contains the required code (java.util.prefs.WindowsPreferences) to access
* the Windows registry. The trick is to use reflection to access private
* methods defined in the WindowsPreference class.
* Changes by Ignasi Puigdomenech: added error messages to exceptions thrown;
* and removed access to HKEY_LOCAL_MACHINE and to HKEY_CLASSES_ROOT.
* @author Real Gagnon
*/
public class WinRegistry {
public static final int HKEY_CURRENT_USER = 0x80000001;
public static final int REG_SUCCESS = 0;
//public static final int REG_NOTFOUND = 2;
//public static final int REG_ACCESSDENIED = 5;
private static final int KEY_ALL_ACCESS = 0xf003f;
private static final int KEY_READ = 0x20019;
private static final java.util.prefs.Preferences userRoot = java.util.prefs.Preferences.userRoot();
private static final Class<? extends java.util.prefs.Preferences> userClass = userRoot.getClass();
private static Method regOpenKey = null;
private static Method regCloseKey = null;
private static Method regQueryValueEx = null;
private static Method regEnumValue = null;
private static Method regQueryInfoKey = null;
private static Method regEnumKeyEx = null;
private static Method regCreateKeyEx = null;
private static Method regSetValueEx = null;
private static Method regDeleteKey = null;
private static Method regDeleteValue = null;
static {
try {
regOpenKey = userClass.getDeclaredMethod("WindowsRegOpenKey",
new Class[] { int.class, byte[].class, int.class });
regOpenKey.setAccessible(true);
regCloseKey = userClass.getDeclaredMethod("WindowsRegCloseKey",
new Class[] { int.class });
regCloseKey.setAccessible(true);
regQueryValueEx = userClass.getDeclaredMethod("WindowsRegQueryValueEx",
new Class[] { int.class, byte[].class });
regQueryValueEx.setAccessible(true);
regEnumValue = userClass.getDeclaredMethod("WindowsRegEnumValue",
new Class[] { int.class, int.class, int.class });
regEnumValue.setAccessible(true);
regQueryInfoKey = userClass.getDeclaredMethod("WindowsRegQueryInfoKey1",
new Class[] { int.class });
regQueryInfoKey.setAccessible(true);
regEnumKeyEx = userClass.getDeclaredMethod(
"WindowsRegEnumKeyEx", new Class[] { int.class, int.class, int.class });
regEnumKeyEx.setAccessible(true);
regCreateKeyEx = userClass.getDeclaredMethod(
"WindowsRegCreateKeyEx", new Class[] { int.class, byte[].class });
regCreateKeyEx.setAccessible(true);
regSetValueEx = userClass.getDeclaredMethod(
"WindowsRegSetValueEx", new Class[] { int.class, byte[].class, byte[].class });
regSetValueEx.setAccessible(true);
regDeleteValue = userClass.getDeclaredMethod(
"WindowsRegDeleteValue", new Class[] { int.class, byte[].class });
regDeleteValue.setAccessible(true);
regDeleteKey = userClass.getDeclaredMethod(
"WindowsRegDeleteKey", new Class[] { int.class, byte[].class });
regDeleteKey.setAccessible(true);
} catch (NoSuchMethodException e) {
System.out.println(e.getMessage()+" in class WinRegistry");
} catch (SecurityException e) {
System.out.println(e.getMessage()+" in class WinRegistry");
}
}
private WinRegistry() {}
/*
/** Create a key. Nothing happens if the key already exists.
* @param key
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException */
public static void createKey(String key)
throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
int [] ret;
ret = createKeyPrivate(key);
regCloseKey.invoke(userRoot, new Object[] { new Integer(ret[0]) });
if (ret[1] != REG_SUCCESS) {
throw new IllegalArgumentException("Error in \"createKey\", rc=" + ret[1] + ", hkey=HKCU, key=" + key );
}
}
/** Delete a given key, even if it has values.
* Throws an IllegalArgumentException if either the key has subkeys,
* or if the key does not exist.
* @param key
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException */
public static void deleteKey(String key)
throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
int rc = deleteKeyPrivate(key);
if (rc != REG_SUCCESS) {
throw new IllegalArgumentException("Error in \"deleteKey\", rc=" + rc + ", hkey=HKCU, key=" + key );
}
}
/** Delete a value from a given key/value name.
* Throws an IllegalArgumentException if the key/value does not exist.
* @param key
* @param value
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException */
public static void deleteValue(String key, String value)
throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
int rc = deleteValuePrivate(key, value);
if (rc != REG_SUCCESS) {
throw new IllegalArgumentException("Error in \"deleteValue\", rc=" + rc + ", hkey=HKCU, key=" + key + ", value=" + value);
}
}
/** Read a value from a key and value name.
* Returns "null" if there is no such key/valueName
* @param key
* @param value
* @return the value
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException */
public static String readString(String key, String value)
throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
int[] handles = (int[]) regOpenKey.invoke(userRoot, new Object[] {
new Integer(HKEY_CURRENT_USER), toCstr(key), new Integer(KEY_READ) });
if (handles[1] != REG_SUCCESS) {
return null;
}
byte[] valb = (byte[]) regQueryValueEx.invoke(userRoot, new Object[] {
new Integer(handles[0]), toCstr(value) });
regCloseKey.invoke(userRoot, new Object[] { new Integer(handles[0]) });
return (valb != null ? new String(valb).trim() : null);
}
/** Read the subkey name(s) from a given key.
* It returns an empty List if there are no subkeys.
* @param key
* @return the value name(s)
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException */
public static List<String> readStringSubKeys(String key)
throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
List<String> results = new ArrayList<String>();
int[] handles = (int[]) regOpenKey.invoke(userRoot, new Object[] {
new Integer(HKEY_CURRENT_USER), toCstr(key), new Integer(KEY_READ)
});
if (handles[1] != REG_SUCCESS) {
return null;
}
int[] info = (int[]) regQueryInfoKey.invoke(userRoot,
new Object[] { new Integer(handles[0]) });
// int count = info[2]; // count
int count = info[0]; // bug fix 20130112
int maxlen = info[3]; // value length max
for(int index=0; index<count; index++) {
byte[] name = (byte[]) regEnumKeyEx.invoke(userRoot, new Object[] {
new Integer
(handles[0]), new Integer(index), new Integer(maxlen + 1)
});
if(name != null) { // Ignasi
results.add(new String(name).trim());
}
}
regCloseKey.invoke(userRoot, new Object[] { new Integer(handles[0]) });
return results;
}
/** Write a value in a given key/value name.
* If the valueName does not exist, it is created.
* Otherwise its contents is replaced with the new value.
* @param key
* @param valueName
* @param value
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException */
public static void writeStringValue(String key, String valueName, String value)
throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
int[] handles = (int[]) regOpenKey.invoke(userRoot, new Object[] {
new Integer(HKEY_CURRENT_USER), toCstr(key), new Integer(KEY_ALL_ACCESS) });
regSetValueEx.invoke(userRoot,
new Object[] {
new Integer(handles[0]), toCstr(valueName), toCstr(value)
});
regCloseKey.invoke(userRoot, new Object[] { new Integer(handles[0]) });
}
/** Read value(s) and value name(s) from given key.
* It returns an empty Map if there are no values.
* Note by Ignasi: it seems not to work properly if the key has no subKeys.
* @param key
* @return the value name(s) plus the value(s)
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException */
public static java.util.Map<String,String> readStringValues(String key)
throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
java.util.HashMap<String, String> results = new java.util.HashMap<String,String>();
int[] handles = (int[]) regOpenKey.invoke(userRoot, new Object[] {
new Integer(HKEY_CURRENT_USER), toCstr(key), new Integer(KEY_READ) });
if (handles[1] != REG_SUCCESS) {
return null;
}
int[] info = (int[]) regQueryInfoKey.invoke(userRoot,
new Object[] { new Integer(handles[0]) });
// int count = info[2]; // count
int count = info[0]; // bug fix 20130112
int maxlen = info[3]; // value length max
for(int index=0; index<count; index++) {
byte[] name = (byte[]) regEnumValue.invoke(userRoot, new Object[] {
new Integer
(handles[0]), new Integer(index), new Integer(maxlen + 1)});
if(name != null) { // Ignasi
String value = readString(key, new String(name));
results.put(new String(name).trim(), value);
}
}
regCloseKey.invoke(userRoot, new Object[] { new Integer(handles[0]) });
return results;
}
// =====================
//<editor-fold defaultstate="collapsed" desc="private methods">
private static int deleteValuePrivate(String key, String value)
throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
int[] handles = (int[]) regOpenKey.invoke(userRoot, new Object[] {
new Integer(HKEY_CURRENT_USER), toCstr(key), new Integer(KEY_ALL_ACCESS) });
if (handles[1] != REG_SUCCESS) {
return handles[1]; // can be REG_NOTFOUND, REG_ACCESSDENIED
}
int rc =((Integer) regDeleteValue.invoke(userRoot,
new Object[] {
new Integer(handles[0]), toCstr(value)
})).intValue();
regCloseKey.invoke(userRoot, new Object[] { new Integer(handles[0]) });
return rc;
}
private static int deleteKeyPrivate(String key)
throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
int rc =((Integer) regDeleteKey.invoke(userRoot,
new Object[] { new Integer(HKEY_CURRENT_USER), toCstr(key) })).intValue();
return rc; // can be REG_NOTFOUND, REG_ACCESSDENIED, REG_SUCCESS
}
private static int [] createKeyPrivate(String key)
throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
return (int[]) regCreateKeyEx.invoke(userRoot,
new Object[] { new Integer(HKEY_CURRENT_USER), toCstr(key) });
}
// utility
private static byte[] toCstr(String str) {
byte[] result = new byte[str.length() + 1];
for (int i = 0; i < str.length(); i++) {
result[i] = (byte) str.charAt(i);
}
result[str.length()] = 0;
return result;
}
//</editor-fold>
}
| 12,021 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
DiagrConvert.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Spana/src/spana/DiagrConvert.java | package spana;
import lib.common.MsgExceptn;
import lib.huvud.Div;
import lib.huvud.ProgramConf;
import lib.kemi.graph_lib.GraphLib;
/** Asks the user for parameters to convert a "plt"-file to either pdf or PostScript.
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class DiagrConvert extends javax.swing.JFrame {
private ProgramConf pc;
private final ProgramDataSpana pd;
private final GraphLib.PltData dd;
private boolean finished = false;
private final java.awt.Dimension windowSize;
/** conversion: 1 = to "pdf"; 2 = to "ps" (PostScript); 3 = to "eps" (encapsulated PostScript) */
private int type = -1;
private String pltFileFullName;
private String convertedFileFullN;
private java.io.File convertedFile;
private boolean cancel = true;
private boolean convertHeader = true;
private boolean convertColours = true;
/** Font type: 0=draw; 1=Times; 2=Helvetica; 3=Courier. */
private int convertFont = 2;
private boolean convertPortrait = true;
private boolean convertEPS = false;
private int convertSizeX = 100;
private int convertSizeY = 100;
/** margin in cm */
private float convertMarginB = 1;
/** margin in cm */
private float convertMarginL = 1;
/** the "bounds" for jPanelPaper */
private java.awt.Rectangle paper = new java.awt.Rectangle(0, 0, 100, 100);
/** the "bounds" for jScrollBarMarginB */
private java.awt.Rectangle marginB = new java.awt.Rectangle(0, 0, 16, 100);
/** the "bounds" for jScrollBarMarginL */
private java.awt.Rectangle marginL = new java.awt.Rectangle(0, 0, 100, 16);
/** the diagram box shown inside the jPanelPaper */
private final java.awt.Rectangle diagram = new java.awt.Rectangle(0, 0, 100, 100);
private final java.awt.Dimension A4 = new java.awt.Dimension(21*4, 29*4);
private final double D_FACTOR = 1.00*4;
/** {"pdf", "ps", "eps"} */
private static final String[] EXTS = {"pdf", "ps", "eps"};
private javax.swing.border.Border scrollBorder;
private static final String nl = System.getProperty("line.separator");
private javax.swing.ImageIcon icon = null;
//<editor-fold defaultstate="collapsed" desc="Constructor">
/** Displays a frame to allow the user to change the settings and perform the
* conversion of a "plt" file into "pdf", "ps" or "eps".
* @param pc0 program configuration parameters
* @param pd0 program data
* @param dd0 data from the "plt" file and other information needed to paint the diagram
*/
public DiagrConvert(
ProgramConf pc0,
ProgramDataSpana pd0,
GraphLib.PltData dd0) {
initComponents();
pc = pc0; pd = pd0; dd = dd0;
finished = false;
cancel = true;
//--- close window on ESC key
javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_ESCAPE,0, false);
javax.swing.Action escAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
closeWindow();
}};
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE");
getRootPane().getActionMap().put("ESCAPE", escAction);
//--- alt-Q quit
javax.swing.KeyStroke altQKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altQKeyStroke,"ALT_Q");
getRootPane().getActionMap().put("ALT_Q", escAction);
//--- Alt-X eXit
javax.swing.KeyStroke altXKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altXKeyStroke,"ALT_X");
javax.swing.Action altXAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jButtonDoIt.doClick();
}};
getRootPane().getActionMap().put("ALT_X", altXAction);
//--- F1 for help
javax.swing.KeyStroke f1KeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(f1KeyStroke,"F1");
javax.swing.Action f1Action = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
DiagrConvert.this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
Thread hlp = new Thread() {@Override public void run(){
String[] a = {"S_Printing_htm_Convert"};
lib.huvud.RunProgr.runProgramInProcess(DiagrConvert.this,ProgramConf.HELP_JAR,a,false,pc.dbg,pc.pathAPP);
try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec
catch (InterruptedException e) {}
DiagrConvert.this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
}};//new Thread
hlp.start();
}};
getRootPane().getActionMap().put("F1", f1Action);
//--- Alt-H help
javax.swing.KeyStroke altHKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_H, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altHKeyStroke,"ALT_H");
getRootPane().getActionMap().put("ALT_H", f1Action);
//--- center Window on Screen
windowSize = this.getSize();
int left; int top;
left = Math.max(55, (MainFrame.screenSize.width - windowSize.width ) / 2);
top = Math.max(10, (MainFrame.screenSize.height - windowSize.height) / 2);
this.setLocation(Math.min(MainFrame.screenSize.width-100, left),
Math.min(MainFrame.screenSize.height-100, top));
scrollBorder = jScrollBarX.getBorder(); // get the default scroll bar border
this.setTitle("Convert a diagram:");
//--- Icon
String iconName;
if(type == 1) {iconName = "images/Icon-PDF.gif";} else {iconName = "images/Icon-PS.gif";}
java.net.URL imgURL = this.getClass().getResource(iconName);
if(imgURL != null) {
icon = new javax.swing.ImageIcon(imgURL);
this.setIconImage(icon.getImage());
}
else {System.out.println("--- Error in DiagrConvert constructor: Could not load image = \""+iconName+"\""); icon =null;}
convertHeader = pd.diagrConvertHeader;
convertColours = pd.diagrConvertColors;
convertFont = pd.diagrConvertFont;
convertPortrait = pd.diagrConvertPortrait;
convertSizeX = pd.diagrConvertSizeX;
convertSizeY = pd.diagrConvertSizeY;
convertMarginB = pd.diagrConvertMarginB;
convertMarginL = pd.diagrConvertMarginL;
convertEPS = pd.diagrConvertEPS;
jCheckHeader.setSelected(convertHeader);
jCheckColours.setSelected(convertColours);
jComboBoxFonts.setSelectedIndex(Math.max(0, Math.min(jComboBoxFonts.getItemCount()-1,convertFont)));
jRadioButtonP.setSelected(convertPortrait);
jRadioButtonL.setSelected(!convertPortrait);
jScrollBarX.setValue(Math.max(20,Math.min(300,convertSizeX)));
jScrollBarY.setValue(Math.max(20,Math.min(300,convertSizeY)));
jScrollBarMarginB.setValue(-Math.max(-50,Math.min(200,(int)(10f*convertMarginB))));
jScrollBarMarginL.setValue(Math.max(-50,Math.min(210,(int)(10f*convertMarginL))));
jLabelMarginBcm.setText(String.valueOf(convertMarginB));
jLabelMarginLcm.setText(String.valueOf(convertMarginL));
jButtonDoIt.setIcon(icon);
jLabelPltFileName.setText(" ");
jLabelDirName.setText(pc.pathDef.toString());
jLabelOutputName.setText(" ");
jScrollBarX.setFocusable(true);
jScrollBarY.setFocusable(true);
jScrollBarMarginL.setFocusable(true);
jScrollBarMarginB.setFocusable(true);
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="start(type, plotFile)">
/** Displays this window frame (after making some checks)
* to allow the user to change the settings and perform the
* conversion of a "plt" file into "pdf", "ps" or "eps".
* @param typ conversion: 1 = to "pdf"; 2 = to "ps" (PostScript);
* 3 = to "eps" (encapsulated PostScript)
* @param pltFileN name (with full path) of the plt file to be converted
*/
public void start(
int typ,
String pltFileN
) {
type = typ;
if(type < 1 || type > 3) {
String msg = "Programming Error: type = "+type+" in DiagrConvert. Should be 1, 2 or 3.";
MsgExceptn.exception(msg);
closeWindow();
return;
}
jButtonDoIt.setText("convert to "+EXTS[type-1].toUpperCase());
if(type == 1) {jCheckBoxEPS.setVisible(false);}
else {
jCheckBoxEPS.setVisible(true);
jCheckBoxEPS.setSelected(convertEPS);
}
if(type ==2 || type ==3) {setEPS(convertEPS);}
redrawDisposition();
if(pc.dbg) {System.out.println(" - - - - - - DiagrConvert, typ="+typ);}
this.setVisible(true);
if(pltFileN == null || pltFileN.trim().length() <=0) {
String msg = "Programming Error: empty or null file name in DiagrConvert.";
MsgExceptn.exception(msg);
javax.swing.JOptionPane.showMessageDialog(this, msg, "Programming error",
javax.swing.JOptionPane.ERROR_MESSAGE);
closeWindow();
return;
}
//---- get the full name, with path
java.io.File pltFile = new java.io.File(pltFileN);
String msg = null;
if(!pltFile.exists()) {msg = "the file does not exist.";}
if(!pltFile.canRead()) {msg = "can not open file for reading.";}
if(msg != null) {
String t = "Error: \""+pltFileN+"\""+nl+msg;
MsgExceptn.exception(t);
javax.swing.JOptionPane.showMessageDialog(this, t, pc.progName,
javax.swing.JOptionPane.ERROR_MESSAGE);
closeWindow();
return;
}
try{pltFileFullName = pltFile.getCanonicalPath();}
catch (java.io.IOException ex) {
try{pltFileFullName = pltFile.getAbsolutePath();}
catch (Exception e) {pltFileFullName = pltFile.getPath();}
}
this.setTitle(pltFile.getName());
jLabelPltFileName.setText(pltFile.getName());
jLabelDirName.setText(pltFile.getParent());
//---- get the file name after conversion
convertedFileFullN = Div.getFileNameWithoutExtension(pltFileFullName)+"."+EXTS[type-1];
convertedFile = new java.io.File(convertedFileFullN);
jLabelOutputName.setText(convertedFile.getName());
int k = this.getWidth() - jPanelBottom.getWidth();
DiagrConvert.this.validate();
int j = Math.max(jPanelBottom.getWidth(), jPanelTop.getWidth());
java.awt.Dimension d = new java.awt.Dimension(k+j, DiagrConvert.this.getHeight());
DiagrConvert.this.setSize(d);
} // start
//</editor-fold>
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroupO = new javax.swing.ButtonGroup();
jPanelTop = new javax.swing.JPanel();
jLabelPltFile = new javax.swing.JLabel();
jLabelPltFileName = new javax.swing.JLabel();
jLabelDir = new javax.swing.JLabel();
jLabelDirName = new javax.swing.JLabel();
jPanelMain = new javax.swing.JPanel();
jPanelSize = new javax.swing.JPanel();
jScrollBarY = new javax.swing.JScrollBar();
jScrollBarX = new javax.swing.JScrollBar();
jLabelSize = new javax.swing.JLabel();
jPanel7 = new javax.swing.JPanel();
jLabelY = new javax.swing.JLabel();
jLabelX = new javax.swing.JLabel();
jLabelX100 = new javax.swing.JLabel();
jLabelY100 = new javax.swing.JLabel();
jPanelDisposition = new javax.swing.JPanel();
jPanelMarginB = new javax.swing.JPanel();
jPanelBmargin = new javax.swing.JPanel();
jLabelMarginB = new javax.swing.JLabel();
jLabelMarginBcm = new javax.swing.JLabel();
jPanelEmpty = new javax.swing.JPanel();
jPanelPaperMargins = new javax.swing.JPanel();
jPanelPaper = new javax.swing.JPanel();
jPanelDiagram = new javax.swing.JPanel();
jLabelDiagram = new javax.swing.JLabel();
jScrollBarMarginL = new javax.swing.JScrollBar();
jScrollBarMarginB = new javax.swing.JScrollBar();
jPanelLmargin = new javax.swing.JPanel();
jLabelMarginL = new javax.swing.JLabel();
jLabelMarginLcm = new javax.swing.JLabel();
jPanelBottom = new javax.swing.JPanel();
jLabelOut = new javax.swing.JLabel();
jLabelOutputName = new javax.swing.JLabel();
jPanelRight = new javax.swing.JPanel();
jLabelFont = new javax.swing.JLabel();
jComboBoxFonts = new javax.swing.JComboBox();
jCheckColours = new javax.swing.JCheckBox();
jCheckHeader = new javax.swing.JCheckBox();
jPanelOrientation = new javax.swing.JPanel();
jRadioButtonP = new javax.swing.JRadioButton();
jRadioButtonL = new javax.swing.JRadioButton();
jCheckBoxEPS = new javax.swing.JCheckBox();
jButtonDoIt = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jLabelPltFile.setText("Plot file:");
jLabelPltFileName.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabelPltFileName.setText("Hello.plt");
jLabelDir.setText("Directory: ");
jLabelDirName.setText("\"D:\\myfiles\\subdir");
javax.swing.GroupLayout jPanelTopLayout = new javax.swing.GroupLayout(jPanelTop);
jPanelTop.setLayout(jPanelTopLayout);
jPanelTopLayout.setHorizontalGroup(
jPanelTopLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelTopLayout.createSequentialGroup()
.addGroup(jPanelTopLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelTopLayout.createSequentialGroup()
.addComponent(jLabelPltFile)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelPltFileName))
.addGroup(jPanelTopLayout.createSequentialGroup()
.addComponent(jLabelDir)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelDirName)))
.addGap(0, 0, Short.MAX_VALUE))
);
jPanelTopLayout.setVerticalGroup(
jPanelTopLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelTopLayout.createSequentialGroup()
.addGroup(jPanelTopLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelPltFile)
.addComponent(jLabelPltFileName))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelTopLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelDir)
.addComponent(jLabelDirName)))
);
jScrollBarY.setBlockIncrement(5);
jScrollBarY.setMaximum(210);
jScrollBarY.setMinimum(20);
jScrollBarY.setOrientation(javax.swing.JScrollBar.HORIZONTAL);
jScrollBarY.setValue(100);
jScrollBarY.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jScrollBarY.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jScrollBarYFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jScrollBarYFocusLost(evt);
}
});
jScrollBarY.addAdjustmentListener(new java.awt.event.AdjustmentListener() {
public void adjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {
jScrollBarYAdjustmentValueChanged(evt);
}
});
jScrollBarX.setBlockIncrement(5);
jScrollBarX.setMaximum(210);
jScrollBarX.setMinimum(20);
jScrollBarX.setOrientation(javax.swing.JScrollBar.HORIZONTAL);
jScrollBarX.setValue(100);
jScrollBarX.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jScrollBarX.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jScrollBarXFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jScrollBarXFocusLost(evt);
}
});
jScrollBarX.addAdjustmentListener(new java.awt.event.AdjustmentListener() {
public void adjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {
jScrollBarXAdjustmentValueChanged(evt);
}
});
jLabelSize.setText("Size");
jLabelY.setText("Y");
jLabelY.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabelYMouseClicked(evt);
}
});
jLabelX.setText("X");
jLabelX.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabelXMouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
jPanel7.setLayout(jPanel7Layout);
jPanel7Layout.setHorizontalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelY, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabelX, javax.swing.GroupLayout.Alignment.TRAILING))
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel7Layout.setVerticalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addComponent(jLabelX)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelY)
.addGap(0, 0, Short.MAX_VALUE))
);
jLabelX100.setText("100 %");
jLabelX100.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabelX100MouseClicked(evt);
}
});
jLabelY100.setText("100 %");
jLabelY100.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabelY100MouseClicked(evt);
}
});
javax.swing.GroupLayout jPanelSizeLayout = new javax.swing.GroupLayout(jPanelSize);
jPanelSize.setLayout(jPanelSizeLayout);
jPanelSizeLayout.setHorizontalGroup(
jPanelSizeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelSizeLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabelSize)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelSizeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelSizeLayout.createSequentialGroup()
.addComponent(jScrollBarX, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelX100, javax.swing.GroupLayout.DEFAULT_SIZE, 58, Short.MAX_VALUE))
.addGroup(jPanelSizeLayout.createSequentialGroup()
.addComponent(jScrollBarY, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelY100, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGap(0, 10, 10))
);
jPanelSizeLayout.setVerticalGroup(
jPanelSizeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelSizeLayout.createSequentialGroup()
.addComponent(jLabelSize)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanelSizeLayout.createSequentialGroup()
.addGroup(jPanelSizeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabelX100)
.addComponent(jScrollBarX, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanelSizeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollBarY, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelY100)))
);
jPanelMarginB.setLayout(new java.awt.CardLayout());
jLabelMarginB.setText("<html>Bottom<br>margin:</html>");
jLabelMarginB.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabelMarginBMouseClicked(evt);
}
});
jLabelMarginBcm.setText("1.0");
jLabelMarginBcm.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabelMarginBcmMouseClicked(evt);
}
});
javax.swing.GroupLayout jPanelBmarginLayout = new javax.swing.GroupLayout(jPanelBmargin);
jPanelBmargin.setLayout(jPanelBmarginLayout);
jPanelBmarginLayout.setHorizontalGroup(
jPanelBmarginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelBmarginLayout.createSequentialGroup()
.addGroup(jPanelBmarginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelBmarginLayout.createSequentialGroup()
.addComponent(jLabelMarginB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanelBmarginLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabelMarginBcm)))
.addContainerGap())
);
jPanelBmarginLayout.setVerticalGroup(
jPanelBmarginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelBmarginLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabelMarginB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelMarginBcm)
.addGap(0, 14, Short.MAX_VALUE))
);
jPanelMarginB.add(jPanelBmargin, "labels");
javax.swing.GroupLayout jPanelEmptyLayout = new javax.swing.GroupLayout(jPanelEmpty);
jPanelEmpty.setLayout(jPanelEmptyLayout);
jPanelEmptyLayout.setHorizontalGroup(
jPanelEmptyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 46, Short.MAX_VALUE)
);
jPanelEmptyLayout.setVerticalGroup(
jPanelEmptyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 73, Short.MAX_VALUE)
);
jPanelMarginB.add(jPanelEmpty, "empty");
jPanelPaperMargins.setLayout(null);
jPanelPaper.setBackground(new java.awt.Color(255, 255, 255));
jPanelPaper.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jPanelPaper.setPreferredSize(new java.awt.Dimension(42, 60));
jPanelPaper.setLayout(null);
jPanelDiagram.setBackground(new java.awt.Color(153, 153, 153));
jPanelDiagram.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jPanelDiagram.setLayout(null);
jLabelDiagram.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabelDiagram.setText("Diagram");
jPanelDiagram.add(jLabelDiagram);
jLabelDiagram.setBounds(11, 12, 48, 14);
jPanelPaper.add(jPanelDiagram);
jPanelDiagram.setBounds(6, 60, 0, 0);
jPanelPaperMargins.add(jPanelPaper);
jPanelPaper.setBounds(17, 0, 84, 116);
jScrollBarMarginL.setMaximum(210);
jScrollBarMarginL.setMinimum(-50);
jScrollBarMarginL.setOrientation(javax.swing.JScrollBar.HORIZONTAL);
jScrollBarMarginL.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jScrollBarMarginL.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jScrollBarMarginLFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jScrollBarMarginLFocusLost(evt);
}
});
jScrollBarMarginL.addAdjustmentListener(new java.awt.event.AdjustmentListener() {
public void adjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {
jScrollBarMarginLAdjustmentValueChanged(evt);
}
});
jPanelPaperMargins.add(jScrollBarMarginL);
jScrollBarMarginL.setBounds(17, 117, 84, 16);
jScrollBarMarginB.setMaximum(60);
jScrollBarMarginB.setMinimum(-200);
jScrollBarMarginB.setValue(-10);
jScrollBarMarginB.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jScrollBarMarginB.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jScrollBarMarginBFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jScrollBarMarginBFocusLost(evt);
}
});
jScrollBarMarginB.addAdjustmentListener(new java.awt.event.AdjustmentListener() {
public void adjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {
jScrollBarMarginBAdjustmentValueChanged(evt);
}
});
jPanelPaperMargins.add(jScrollBarMarginB);
jScrollBarMarginB.setBounds(0, 0, 16, 116);
jLabelMarginL.setText("Left margin:");
jLabelMarginL.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabelMarginLMouseClicked(evt);
}
});
jLabelMarginLcm.setText("1.0");
jLabelMarginLcm.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabelMarginLcmMouseClicked(evt);
}
});
javax.swing.GroupLayout jPanelLmarginLayout = new javax.swing.GroupLayout(jPanelLmargin);
jPanelLmargin.setLayout(jPanelLmarginLayout);
jPanelLmarginLayout.setHorizontalGroup(
jPanelLmarginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelLmarginLayout.createSequentialGroup()
.addComponent(jLabelMarginL)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelMarginLcm)
.addGap(0, 55, Short.MAX_VALUE))
);
jPanelLmarginLayout.setVerticalGroup(
jPanelLmarginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelLmarginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelMarginL)
.addComponent(jLabelMarginLcm))
);
javax.swing.GroupLayout jPanelDispositionLayout = new javax.swing.GroupLayout(jPanelDisposition);
jPanelDisposition.setLayout(jPanelDispositionLayout);
jPanelDispositionLayout.setHorizontalGroup(
jPanelDispositionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelDispositionLayout.createSequentialGroup()
.addComponent(jPanelMarginB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanelPaperMargins, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelDispositionLayout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(jPanelLmargin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelDispositionLayout.setVerticalGroup(
jPanelDispositionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelDispositionLayout.createSequentialGroup()
.addGroup(jPanelDispositionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanelPaperMargins, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanelDispositionLayout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(jPanelMarginB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanelLmargin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanelMainLayout = new javax.swing.GroupLayout(jPanelMain);
jPanelMain.setLayout(jPanelMainLayout);
jPanelMainLayout.setHorizontalGroup(
jPanelMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanelSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanelDisposition, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
jPanelMainLayout.setVerticalGroup(
jPanelMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelMainLayout.createSequentialGroup()
.addComponent(jPanelSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanelDisposition, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jLabelOut.setText("Output file:");
jLabelOutputName.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabelOutputName.setText("Hello.pdf");
javax.swing.GroupLayout jPanelBottomLayout = new javax.swing.GroupLayout(jPanelBottom);
jPanelBottom.setLayout(jPanelBottomLayout);
jPanelBottomLayout.setHorizontalGroup(
jPanelBottomLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelBottomLayout.createSequentialGroup()
.addComponent(jLabelOut)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelOutputName)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelBottomLayout.setVerticalGroup(
jPanelBottomLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelBottomLayout.createSequentialGroup()
.addGroup(jPanelBottomLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelOutputName)
.addComponent(jLabelOut))
.addGap(8, 8, 8))
);
jLabelFont.setText("Font");
jComboBoxFonts.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Vector graphics", "Times-Roman", "Helvetica", "Courier" }));
jComboBoxFonts.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBoxFontsActionPerformed(evt);
}
});
jCheckColours.setMnemonic('c');
jCheckColours.setText("Colours");
jCheckColours.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckColoursActionPerformed(evt);
}
});
jCheckHeader.setMnemonic('b');
jCheckHeader.setText("Banner");
jCheckHeader.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckHeaderActionPerformed(evt);
}
});
jPanelOrientation.setBorder(javax.swing.BorderFactory.createTitledBorder("Orientation"));
buttonGroupO.add(jRadioButtonP);
jRadioButtonP.setMnemonic('p');
jRadioButtonP.setSelected(true);
jRadioButtonP.setText("Portrait");
jRadioButtonP.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonPActionPerformed(evt);
}
});
buttonGroupO.add(jRadioButtonL);
jRadioButtonL.setMnemonic('l');
jRadioButtonL.setText("Landscape");
jRadioButtonL.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonLActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanelOrientationLayout = new javax.swing.GroupLayout(jPanelOrientation);
jPanelOrientation.setLayout(jPanelOrientationLayout);
jPanelOrientationLayout.setHorizontalGroup(
jPanelOrientationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelOrientationLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelOrientationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jRadioButtonP)
.addComponent(jRadioButtonL)))
);
jPanelOrientationLayout.setVerticalGroup(
jPanelOrientationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelOrientationLayout.createSequentialGroup()
.addComponent(jRadioButtonP)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jRadioButtonL)
.addContainerGap())
);
jCheckBoxEPS.setMnemonic('e');
jCheckBoxEPS.setText("encapsulated PS");
jCheckBoxEPS.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxEPSActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanelRightLayout = new javax.swing.GroupLayout(jPanelRight);
jPanelRight.setLayout(jPanelRightLayout);
jPanelRightLayout.setHorizontalGroup(
jPanelRightLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelRightLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelRightLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jComboBoxFonts, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanelRightLayout.createSequentialGroup()
.addGroup(jPanelRightLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelFont)
.addComponent(jPanelOrientation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jCheckColours)
.addComponent(jCheckBoxEPS)
.addComponent(jCheckHeader))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jPanelRightLayout.setVerticalGroup(
jPanelRightLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelRightLayout.createSequentialGroup()
.addComponent(jLabelFont)
.addGap(3, 3, 3)
.addComponent(jComboBoxFonts, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jCheckColours)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jCheckHeader)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanelOrientation, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jCheckBoxEPS)
.addContainerGap())
);
jButtonDoIt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/spana/images/Icon-PDF.gif"))); // NOI18N
jButtonDoIt.setMnemonic('c');
jButtonDoIt.setText("convert to ...");
jButtonDoIt.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonDoIt.setIconTextGap(8);
jButtonDoIt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonDoItActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanelBottom, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanelTop, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addComponent(jButtonDoIt)
.addGap(0, 264, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(jPanelMain, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanelRight, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanelTop, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanelMain, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanelRight, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanelBottom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButtonDoIt)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
//<editor-fold defaultstate="collapsed" desc="Events">
private void jRadioButtonPActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonPActionPerformed
convertPortrait = jRadioButtonP.isSelected();
redrawDisposition();
}//GEN-LAST:event_jRadioButtonPActionPerformed
private void jRadioButtonLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonLActionPerformed
convertPortrait = jRadioButtonP.isSelected();
redrawDisposition();
}//GEN-LAST:event_jRadioButtonLActionPerformed
private void jCheckHeaderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckHeaderActionPerformed
convertHeader = jCheckHeader.isSelected();
}//GEN-LAST:event_jCheckHeaderActionPerformed
private void jCheckColoursActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckColoursActionPerformed
convertColours = jCheckColours.isSelected();
}//GEN-LAST:event_jCheckColoursActionPerformed
private void jButtonDoItActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDoItActionPerformed
saveSettings();
cancel = false;
DiagrConvert.this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
//---- do the conversion
doIt(DiagrConvert.this, type, pltFileFullName, pd, pc);
closeWindow();
}//GEN-LAST:event_jButtonDoItActionPerformed
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
closeWindow();
}//GEN-LAST:event_formWindowClosing
private void jScrollBarXAdjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {//GEN-FIRST:event_jScrollBarXAdjustmentValueChanged
convertSizeX = jScrollBarX.getValue();
jLabelX100.setText(String.valueOf(jScrollBarX.getValue())+" %");
redrawDisposition();
}//GEN-LAST:event_jScrollBarXAdjustmentValueChanged
private void jScrollBarYAdjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {//GEN-FIRST:event_jScrollBarYAdjustmentValueChanged
convertSizeY = jScrollBarY.getValue();
jLabelY100.setText(String.valueOf(jScrollBarY.getValue())+" %");
redrawDisposition();
}//GEN-LAST:event_jScrollBarYAdjustmentValueChanged
private void jLabelXMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelXMouseClicked
jScrollBarX.setValue(100);
}//GEN-LAST:event_jLabelXMouseClicked
private void jLabelX100MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelX100MouseClicked
jScrollBarX.setValue(100);
}//GEN-LAST:event_jLabelX100MouseClicked
private void jLabelYMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelYMouseClicked
jScrollBarY.setValue(100);
}//GEN-LAST:event_jLabelYMouseClicked
private void jLabelY100MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelY100MouseClicked
jScrollBarY.setValue(100);
}//GEN-LAST:event_jLabelY100MouseClicked
private void jScrollBarMarginBAdjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {//GEN-FIRST:event_jScrollBarMarginBAdjustmentValueChanged
convertMarginB = -(float)jScrollBarMarginB.getValue()/10f;
if(Math.abs(convertMarginB) < 0.001) {convertMarginB = 0f;}
jLabelMarginBcm.setText(String.valueOf(convertMarginB));
redrawDisposition();
}//GEN-LAST:event_jScrollBarMarginBAdjustmentValueChanged
private void jScrollBarMarginLAdjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {//GEN-FIRST:event_jScrollBarMarginLAdjustmentValueChanged
convertMarginL = (float)jScrollBarMarginL.getValue()/10f;
if(Math.abs(convertMarginL) < 0.001) {convertMarginL = 0f;}
jLabelMarginLcm.setText(String.valueOf(convertMarginL));
redrawDisposition();
}//GEN-LAST:event_jScrollBarMarginLAdjustmentValueChanged
private void jLabelMarginBMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelMarginBMouseClicked
jScrollBarMarginB.setValue(-10);
}//GEN-LAST:event_jLabelMarginBMouseClicked
private void jLabelMarginBcmMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelMarginBcmMouseClicked
jScrollBarMarginB.setValue(-10);
}//GEN-LAST:event_jLabelMarginBcmMouseClicked
private void jLabelMarginLMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelMarginLMouseClicked
jScrollBarMarginL.setValue(10);
}//GEN-LAST:event_jLabelMarginLMouseClicked
private void jLabelMarginLcmMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelMarginLcmMouseClicked
jScrollBarMarginL.setValue(10);
}//GEN-LAST:event_jLabelMarginLcmMouseClicked
private void jComboBoxFontsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxFontsActionPerformed
convertFont = jComboBoxFonts.getSelectedIndex();
}//GEN-LAST:event_jComboBoxFontsActionPerformed
private void jCheckBoxEPSActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxEPSActionPerformed
setEPS(jCheckBoxEPS.isSelected());
redrawDisposition();
}//GEN-LAST:event_jCheckBoxEPSActionPerformed
private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
if(windowSize != null) {
int w = windowSize.width;
int h = windowSize.height;
if(this.getHeight()<h){this.setSize(this.getWidth(), h);}
if(this.getWidth()<w){this.setSize(w,this.getHeight());}
}
}//GEN-LAST:event_formComponentResized
private void jScrollBarXFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jScrollBarXFocusGained
jScrollBarX.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0,0,0)));
}//GEN-LAST:event_jScrollBarXFocusGained
private void jScrollBarXFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jScrollBarXFocusLost
jScrollBarX.setBorder(scrollBorder);
}//GEN-LAST:event_jScrollBarXFocusLost
private void jScrollBarYFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jScrollBarYFocusGained
jScrollBarY.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0,0,0)));
}//GEN-LAST:event_jScrollBarYFocusGained
private void jScrollBarYFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jScrollBarYFocusLost
jScrollBarY.setBorder(scrollBorder);
}//GEN-LAST:event_jScrollBarYFocusLost
private void jScrollBarMarginBFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jScrollBarMarginBFocusGained
jScrollBarMarginB.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0,0,0)));
}//GEN-LAST:event_jScrollBarMarginBFocusGained
private void jScrollBarMarginBFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jScrollBarMarginBFocusLost
jScrollBarMarginB.setBorder(scrollBorder);
}//GEN-LAST:event_jScrollBarMarginBFocusLost
private void jScrollBarMarginLFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jScrollBarMarginLFocusGained
jScrollBarMarginL.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0,0,0)));
}//GEN-LAST:event_jScrollBarMarginLFocusGained
private void jScrollBarMarginLFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jScrollBarMarginLFocusLost
jScrollBarMarginL.setBorder(scrollBorder);
}//GEN-LAST:event_jScrollBarMarginLFocusLost
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Methods">
public final void closeWindow() {
if(cancel && changes()) {
Object[] opt = {"Yes","NO","Cancel"};
int answer = javax.swing.JOptionPane.showOptionDialog(this,
"Save options?", pc.progName,
javax.swing.JOptionPane.YES_NO_CANCEL_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[1]);
if(answer == javax.swing.JOptionPane.YES_OPTION) {saveSettings();}
else if(answer == javax.swing.JOptionPane.CANCEL_OPTION) {return;}
}
finished = true;
this.setVisible(false);
this.dispose();
this.notify_All();
} // closeWindow()
private synchronized void notify_All() {notifyAll();}
/** this method will wait for this dialog frame to be closed
* @return "cancel" */
public synchronized boolean waitFor() {
while(!finished) {try {wait();} catch (InterruptedException ex) {}}
return cancel;
} // waitFor()
//<editor-fold defaultstate="collapsed" desc="changes">
private boolean changes() {
boolean changed = false;
if(pd.diagrConvertHeader != convertHeader) {changed = true;}
else if(pd.diagrConvertColors != convertColours) {changed = true;}
else if(pd.diagrConvertFont != convertFont) {changed = true;}
else if(pd.diagrConvertPortrait != convertPortrait) {changed = true;}
else if(pd.diagrConvertSizeX != convertSizeX) {changed = true;}
else if(pd.diagrConvertSizeY != convertSizeY) {changed = true;}
else if(pd.diagrConvertMarginB != convertMarginB) {changed = true;}
else if(pd.diagrConvertMarginL != convertMarginL) {changed = true;}
else if(pd.diagrConvertEPS != convertEPS) {changed = true;}
return changed;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="saveSettings">
private void saveSettings() {
pd.diagrConvertHeader = convertHeader;
pd.diagrConvertColors = convertColours;
pd.diagrConvertFont = convertFont;
pd.diagrConvertPortrait = convertPortrait;
pd.diagrConvertSizeX = convertSizeX;
pd.diagrConvertSizeY = convertSizeY;
pd.diagrConvertMarginB = convertMarginB;
pd.diagrConvertMarginL = convertMarginL;
pd.diagrConvertEPS = convertEPS;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="setEPS">
private void setEPS(boolean eps) {
convertEPS = eps;
java.awt.CardLayout cl = (java.awt.CardLayout)jPanelMarginB.getLayout();
if(eps) {
type = 3;
cl.show(jPanelMarginB, "empty");
jLabelMarginL.setText(" ");
jLabelMarginLcm.setText(" ");
} else {
type = 2;
cl.show(jPanelMarginB, "labels");
jLabelMarginL.setText("Left margin:");
jLabelMarginLcm.setText(String.valueOf(convertMarginL));
}
jScrollBarMarginB.setEnabled(!eps);
jScrollBarMarginL.setEnabled(!eps);
jPanelOrientation.setVisible(!eps);
jCheckHeader.setVisible(!eps);
jButtonDoIt.setText("convert to "+EXTS[type-1].toUpperCase());
//---- get the file name after conversion
convertedFileFullN = Div.getFileNameWithoutExtension(pltFileFullName)+"."+EXTS[type-1];
convertedFile = new java.io.File(convertedFileFullN);
jLabelOutputName.setText(convertedFile.getName());
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="redrawDisposition">
private void redrawDisposition() {
// these are Rectangles:
paper = jPanelPaper.getBounds();
marginB = jScrollBarMarginB.getBounds();
marginL = jScrollBarMarginL.getBounds();
boolean portrait;
if(type !=1 && convertEPS) {portrait = true;} else {portrait = convertPortrait;}
if(portrait) {
paper.height = A4.height;
paper.width = A4.width;
paper.y = 0;
} else { //landscape
paper.width = A4.height;
paper.height = A4.width;
paper.y = A4.height - paper.height;
}
paper.x = marginB.width + 1;
marginB.height = paper.height;
marginB.y = paper.y;
marginL.width = paper.width;
jPanelPaper.setBounds(paper);
jScrollBarMarginB.setBounds(marginB);
jScrollBarMarginL.setBounds(marginL);
diagram.height = (int)( ((double)Math.abs(dd.userSpaceMax.y - dd.userSpaceMin.y)/100d)
* ((double)convertSizeY/100d) * D_FACTOR );
diagram.width = (int)( ((double)Math.abs(dd.userSpaceMax.x - dd.userSpaceMin.x)/100d)
* ((double)convertSizeX/100d) * D_FACTOR);
if(type !=1 && convertEPS) {
diagram.x = (paper.width - diagram.width)/2;
diagram.y = (paper.height - diagram.height)/2;
} else {
diagram.x = (int)(convertMarginL * 4f);
diagram.y = (int)((float)(paper.height - diagram.height) - (convertMarginB * 4f));
}
int x,y;
x = (diagram.width - jLabelDiagram.getWidth())/2;
y = (diagram.height - jLabelDiagram.getHeight())/2;
jLabelDiagram.setLocation(x, y);
jPanelDiagram.setBounds(diagram);
jPanelDisposition.validate();
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="doIt">
/** Convert a plot file to either pdf, PostScript (PS) or encapsulated PS.
* @param parent the parent window used for message boxes.
* If null, no messages are displayed
* @param typ 1 = pdf conversion; 2 = PS; 3 = EPS
* @param fileName full path plot file name
* @param pd0
* @param pc0 */
public static void doIt(
final java.awt.Frame parent,
int typ,
String fileName,
ProgramDataSpana pd0,
ProgramConf pc0) {
if(typ <1 || typ >3) {MsgExceptn.exception("Error: typ = "+typ+" (must be 1,2 or 3)"); return;}
if(fileName == null || fileName.trim().length() <=0) {MsgExceptn.exception("Error: empty file name"); return;}
if(pd0 == null) {MsgExceptn.exception("Error: prgram data = null"); return;}
if(pc0 == null) {MsgExceptn.exception("Error: program configuration = null"); return;}
final ProgramDataSpana pd = pd0;
final ProgramConf pc = pc0;
final int type = typ;
final String pltFileFullName = fileName;
final String program;
if(type <= 2) {program = "Plot"+EXTS[type-1].toUpperCase()+".jar";}
else {program = "Plot"+EXTS[type-1].substring(1).toUpperCase() +".jar";}
//---- do the conversion
java.util.ArrayList<String> options = new java.util.ArrayList<String>();
options.add(pltFileFullName);
//---- get the file name after conversion
String convertedFileFullN = Div.getFileNameWithoutExtension(pltFileFullName)+"."+EXTS[type-1];
if(type == 1) {options.add("-pdf="+convertedFileFullN);}
else if(type == 2 || type == 3) {options.add("-ps="+convertedFileFullN);}
synchronized (pd) {
options.add("-b="+pd.diagrConvertMarginB);
options.add("-l="+pd.diagrConvertMarginL);
options.add("-sX="+(int)(pd.diagrConvertSizeX));
options.add("-sY="+(int)(pd.diagrConvertSizeY));
if(!pd.diagrConvertHeader) {options.add("-noH");}
if(pd.diagrConvertColors) {options.add("-clr");} else {options.add("-bw");}
if(pd.diagrConvertPortrait) {options.add("-o=P");} else {options.add("-o=L");}
options.add("-f="+(1+Math.max(0,Math.min(3,pd.diagrConvertFont))));
} //synchronized
String[] args = new String[options.size()];
args = options.toArray(args);
if(pd.keepFrame || pc.dbg) {
System.out.println("Running:");
System.out.print(program+" ");
for(String t : args) {System.out.print(" "+t);}
System.out.println();
}
final java.io.File convertedFile = new java.io.File(convertedFileFullN);
final long fileDate0 = convertedFile.lastModified();
boolean waitForCompletion = true;
lib.huvud.RunProgr.runProgramInProcess(parent,program,args,waitForCompletion,pc.dbg,pc.pathAPP);
if(parent != null) {parent.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));}
long fileDate = convertedFile.lastModified();
if(fileDate > fileDate0) {
if(pc.dbg) {System.out.println("--- Created file \""+convertedFile.getName()+"\"");}
if(parent != null) {
String msg = "<html>Created ";
if(type == 1) {msg = msg + "pdf-";}
else if(type == 3) {msg = msg + "encapsulated ";}
if(type == 2 || type == 3) {msg = msg + "PostScript-";}
msg = msg + "file:<br>"+
"<b>\""+convertedFile.getName()+"\"</b></html>";
//--- Icon
//String iconName = "images/Icon-"+EXTS[type-1]+".gif";
String iconName = "images/Successful.gif";
java.net.URL imgURL = DiagrConvert.class.getResource(iconName);
javax.swing.ImageIcon icon;
if(imgURL != null) {icon = new javax.swing.ImageIcon(imgURL);}
else {System.out.println("--- Error in DiagrConvert constructor: Could not load image = \""+iconName+"\""); icon =null;}
if(icon != null) {
javax.swing.JOptionPane.showMessageDialog(parent,
msg, pc.progName,javax.swing.JOptionPane.INFORMATION_MESSAGE, icon);
} else {
javax.swing.JOptionPane.showMessageDialog(parent,
msg, pc.progName,javax.swing.JOptionPane.INFORMATION_MESSAGE);
}
}
} else {
if(pc.dbg) {System.out.println("--- Failed to create file \""+convertedFile.getName()+"\"");}
if(parent != null) {
javax.swing.JOptionPane.showMessageDialog(parent,
"<html>Failed to create file:<br>"+
"<b>\""+convertedFile.getName()+"\"</b></html>",
pc.progName,javax.swing.JOptionPane.ERROR_MESSAGE);
}
}
}
//</editor-fold>
//</editor-fold>
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroupO;
private javax.swing.JButton jButtonDoIt;
private javax.swing.JCheckBox jCheckBoxEPS;
private javax.swing.JCheckBox jCheckColours;
private javax.swing.JCheckBox jCheckHeader;
private javax.swing.JComboBox jComboBoxFonts;
private javax.swing.JLabel jLabelDiagram;
private javax.swing.JLabel jLabelDir;
private javax.swing.JLabel jLabelDirName;
private javax.swing.JLabel jLabelFont;
private javax.swing.JLabel jLabelMarginB;
private javax.swing.JLabel jLabelMarginBcm;
private javax.swing.JLabel jLabelMarginL;
private javax.swing.JLabel jLabelMarginLcm;
private javax.swing.JLabel jLabelOut;
private javax.swing.JLabel jLabelOutputName;
private javax.swing.JLabel jLabelPltFile;
private javax.swing.JLabel jLabelPltFileName;
private javax.swing.JLabel jLabelSize;
private javax.swing.JLabel jLabelX;
private javax.swing.JLabel jLabelX100;
private javax.swing.JLabel jLabelY;
private javax.swing.JLabel jLabelY100;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanelBmargin;
private javax.swing.JPanel jPanelBottom;
private javax.swing.JPanel jPanelDiagram;
private javax.swing.JPanel jPanelDisposition;
private javax.swing.JPanel jPanelEmpty;
private javax.swing.JPanel jPanelLmargin;
private javax.swing.JPanel jPanelMain;
private javax.swing.JPanel jPanelMarginB;
private javax.swing.JPanel jPanelOrientation;
private javax.swing.JPanel jPanelPaper;
private javax.swing.JPanel jPanelPaperMargins;
private javax.swing.JPanel jPanelRight;
private javax.swing.JPanel jPanelSize;
private javax.swing.JPanel jPanelTop;
private javax.swing.JRadioButton jRadioButtonL;
private javax.swing.JRadioButton jRadioButtonP;
private javax.swing.JScrollBar jScrollBarMarginB;
private javax.swing.JScrollBar jScrollBarMarginL;
private javax.swing.JScrollBar jScrollBarX;
private javax.swing.JScrollBar jScrollBarY;
// End of variables declaration//GEN-END:variables
}
| 64,751 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
ModifyConfirm.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Spana/src/spana/ModifyConfirm.java | package spana;
import lib.huvud.ProgramConf;
import lib.kemi.chem.Chem;
import lib.kemi.readWriteDataFiles.ReadChemSyst;
/** Confirm dialog.
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class ModifyConfirm extends javax.swing.JFrame {
private java.awt.Dimension windowSize;
private boolean finished = false;
private boolean cancel = true;
private boolean dbg = true;
private Chem ch = null;
private Chem.ChemSystem cs = null;
private Chem.ChemSystem.NamesEtc namn = null;
private javax.swing.DefaultListModel<String> listSolubleCmplxModel = new javax.swing.DefaultListModel<>();
// private javax.swing.DefaultListModel listSolubleCmplxModel = new javax.swing.DefaultListModel(); // java 1.6
private javax.swing.DefaultListModel<String> listSolidCmplxModel = new javax.swing.DefaultListModel<>();
// private javax.swing.DefaultListModel listSolidCmplxModel = new javax.swing.DefaultListModel(); // java 1.6
private int compToDelOrExch;
private boolean delete;
private final static String nl = System.getProperty("line.separator");
//<editor-fold defaultstate="collapsed" desc="Constructor">
/** Creates new form ModifyConfirm, used when a component is to be either deleted
* or exchanged with a reaction product
* @param parentPosition
* @param chem an instance of a Chem storage class
* @param compToDelOrExch the component to delete or to exchange
* @param complxToExchange if the user wishes to exchange the component:
* the reaction product initially selected by the user; if there is not initial
* selection then complxToExchange = -1. If the user wishes to delete the
* reaction then complxToExchange < -1.
* @param pc program configuration data */
public ModifyConfirm(java.awt.Point parentPosition,
Chem chem, int compToDelOrExch, int complxToExchange,
final ProgramConf pc) {
//--- set the reference pointing to instance of storage class
if(chem == null) {
System.err.println("Programming error in ModifyConfirm: \"ch\" is null.");
return;}
ch = chem;
cs = ch.chemSystem;
namn = cs.namn;
if(cs == null || namn == null) {
System.err.println("Programming error in ModifyConfirm: either \"cs\" or \"namn\" are null.");
return;}
if(compToDelOrExch < 0 || compToDelOrExch >= cs.Na) {
System.err.println("Programming error in ModifyConfirm: \"compToDelOrExch\" = "+compToDelOrExch);
return;}
this.compToDelOrExch = compToDelOrExch;
initComponents();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
//set Window on Screen
this.setLocation(parentPosition);
//--- close window on ESC key
javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE");
javax.swing.Action escAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
quitFrame();
}};
getRootPane().getActionMap().put("ESCAPE", escAction);
//--- F1 for help
javax.swing.KeyStroke f1KeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(f1KeyStroke,"F1");
javax.swing.Action f1Action = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
ModifyConfirm.this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
Thread hlp = new Thread() {@Override public void run(){
String[] a = {"S_Modify_Chem_System_htm"};
lib.huvud.RunProgr.runProgramInProcess(ModifyConfirm.this,ProgramConf.HELP_JAR,a,false,pc.dbg,pc.pathAPP);
try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec
catch (InterruptedException e) {}
ModifyConfirm.this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
}};//new Thread
hlp.start();
}};
getRootPane().getActionMap().put("F1", f1Action);
//--- Define Alt-keys
// Alt-O and Alt-Q are button mnemonics
// Define Alt-X
//--- Alt-X quit
javax.swing.KeyStroke altXKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altXKeyStroke,"ALT_X");
javax.swing.Action altXAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jButtonOK.doClick();
}};
getRootPane().getActionMap().put("ALT_X", altXAction);
//--- Alt-H help
javax.swing.KeyStroke altHKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_H, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altHKeyStroke,"ALT_H");
getRootPane().getActionMap().put("ALT_H", f1Action);
//--- Icon
String iconName = "images/Modify_32x32.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
if (imgURL != null) {this.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());}
else {System.out.println("Error: Could not load image = \""+iconName+"\"");}
//---
if(complxToExchange >= -1) { // Exchange a component for a reaction
jLabelSolubleCmplx.setText("Soluble complexes:");
jLabelSolidCmplx.setText("Solid products:");
}
//--- add complexes to the list
int complxs = 0 ;
for(int i=0; i < cs.nx; i++) {
if(Math.abs(cs.a[i][compToDelOrExch])>1e-7) {
listSolubleCmplxModel.addElement(namn.ident[i+cs.Na]);
complxs++;
}
} //for i
if(complxs <= 0) {
jLabelSolubleCmplx.setText("No soluble complexes");
jListSolubCmplx.setBackground(java.awt.Color.lightGray);
}
//--- add solids to the list
int complexesS = 0;
int i;
for(int is=0; is < cs.mSol-cs.solidC; is++) {
i = is +cs.nx;
if(Math.abs(cs.a[i][compToDelOrExch])>1e-7) {
listSolidCmplxModel.addElement(namn.ident[i+cs.Na]);
complexesS++;
}
} //for i
if(complexesS <= 0) {
jLabelSolidCmplx.setText("No solid products");
jListSolidCmplx.setBackground(java.awt.Color.lightGray);
}
//delete a component or exchange with a reaction?
String comp;
comp = namn.identC[compToDelOrExch];
jLabelName.setText(comp);
if(complxToExchange < -1) { // delete a component
delete = true;
//Title
this.setTitle("Delete \""+comp+"\"");
if(dbg) {System.out.println(" ---- Confirm delete component: \""+comp+"\"");}
if(complxs <= 0) {
jLabelSolubleCmplx.setText("No soluble complexes removed");
}
if(complexesS <= 0) {
jLabelSolidCmplx.setText("No solid products removed");
}
if(complxs <=0 && complexesS <=0) {
jLabelWarning.setText(" ");
jButtonOK.setText("OK");
}
jListSolubCmplx.setFocusable(false);
jListSolidCmplx.setFocusable(false);
} else { //exchange the component with a complex
delete = false;
//Title
this.setTitle("Exchange \""+comp+"\" with a reaction");
if(dbg) {System.out.println(" ---- Confirm exchange component \""+comp+"\" with a reaction");}
jLabel0.setText("Exchange chemical component");
jLabelWarning.setText("<html>Select the reaction product to become the<br>component:</html>");
// select the complex in the list if user has already selected it
if(complxToExchange >=0) {
String cmplx = namn.ident[complxToExchange + cs.Na];
boolean found = false;
for(int ix=0; ix < listSolubleCmplxModel.getSize(); ix++) {
if(cmplx.equals(listSolubleCmplxModel.elementAt(ix).toString())) {
found = true;
jListSolubCmplx.setSelectedIndex(ix);
jListSolubCmplx.ensureIndexIsVisible(ix);
break;
}
} //for ix
if(!found) {
for(int ix=0; ix < listSolidCmplxModel.getSize(); ix++) {
if(cmplx.equals(listSolidCmplxModel.elementAt(ix).toString())) {
jListSolidCmplx.setSelectedIndex(ix);
jListSolidCmplx.ensureIndexIsVisible(ix);
break;
}
} //for ix
} //if !found
} //if complxToExchange >=0
// select the complex in the list if there is only one
if((listSolubleCmplxModel.getSize()+listSolidCmplxModel.getSize())==1) {
if(listSolubleCmplxModel.getSize()==1) {
jListSolubCmplx.setSelectedIndex(0);
jListSolubCmplx.ensureIndexIsVisible(0);
}
else {
jListSolidCmplx.setSelectedIndex(0);
jListSolidCmplx.ensureIndexIsVisible(0);
}
}
jButtonOK.setText("OK do it!");
iconName = "images/Exchange_32x32.gif";
imgURL = this.getClass().getResource(iconName);
if(imgURL != null) {jButtonOK.setIcon(new javax.swing.ImageIcon(imgURL));}
else {System.out.println("Error: Could not load image = \""+iconName+"\"");}
} // complxToExchange < -1?
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
this.setVisible(true);
} // constructor
//</editor-fold>
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel0 = new javax.swing.JLabel();
jLabelName = new javax.swing.JLabel();
jLabelWarning = new javax.swing.JLabel();
jPanelLists = new javax.swing.JPanel();
jLabelSolubleCmplx = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jListSolubCmplx = new javax.swing.JList();
jLabelSolidCmplx = new javax.swing.JLabel();
jScrollPane2 = new javax.swing.JScrollPane();
jListSolidCmplx = new javax.swing.JList();
jPanel2 = new javax.swing.JPanel();
jPanelButtons = new javax.swing.JPanel();
jButtonQuit = new javax.swing.JButton();
jButtonOK = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jLabel0.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel0.setForeground(new java.awt.Color(0, 0, 204));
jLabel0.setText("Delete chemical component:"); // NOI18N
jLabelName.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabelName.setText("SO4-2"); // NOI18N
jLabelWarning.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabelWarning.setForeground(new java.awt.Color(0, 0, 204));
jLabelWarning.setText("<html>Will delete the following species<br>as well!</html>"); // NOI18N
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel0)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabelName)))
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jLabelWarning))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel0)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelName)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelWarning, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jLabelSolubleCmplx.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabelSolubleCmplx.setForeground(new java.awt.Color(0, 0, 204));
jLabelSolubleCmplx.setText("Soluble complexes removed:"); // NOI18N
jListSolubCmplx.setModel(listSolubleCmplxModel);
jListSolubCmplx.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jListSolubCmplx.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
jListSolubCmplxValueChanged(evt);
}
});
jScrollPane1.setViewportView(jListSolubCmplx);
jLabelSolidCmplx.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabelSolidCmplx.setForeground(new java.awt.Color(0, 0, 204));
jLabelSolidCmplx.setText("Solid products removed:"); // NOI18N
jListSolidCmplx.setModel(listSolidCmplxModel);
jListSolidCmplx.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
jListSolidCmplxValueChanged(evt);
}
});
jScrollPane2.setViewportView(jListSolidCmplx);
javax.swing.GroupLayout jPanelListsLayout = new javax.swing.GroupLayout(jPanelLists);
jPanelLists.setLayout(jPanelListsLayout);
jPanelListsLayout.setHorizontalGroup(
jPanelListsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelListsLayout.createSequentialGroup()
.addGroup(jPanelListsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelSolubleCmplx)
.addComponent(jLabelSolidCmplx, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanelListsLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelListsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))))
.addContainerGap())
);
jPanelListsLayout.setVerticalGroup(
jPanelListsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelListsLayout.createSequentialGroup()
.addComponent(jLabelSolubleCmplx)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabelSolidCmplx)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 137, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 82, Short.MAX_VALUE)
);
jButtonQuit.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButtonQuit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/spana/images/Quit_32x32.gif"))); // NOI18N
jButtonQuit.setMnemonic('Q');
jButtonQuit.setText("<html><u>Q</u>uit</html>"); // NOI18N
jButtonQuit.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonQuit.setHorizontalAlignment(javax.swing.SwingConstants.LEADING);
jButtonQuit.setIconTextGap(8);
jButtonQuit.setMargin(new java.awt.Insets(2, 2, 2, 2));
jButtonQuit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonQuitActionPerformed(evt);
}
});
jButtonOK.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButtonOK.setIcon(new javax.swing.ImageIcon(getClass().getResource("/spana/images/Delete_32x32.gif"))); // NOI18N
jButtonOK.setMnemonic('O');
jButtonOK.setText("<html><u>O</u>K <br>get rid of them!</html>"); // NOI18N
jButtonOK.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonOK.setHorizontalAlignment(javax.swing.SwingConstants.LEADING);
jButtonOK.setIconTextGap(8);
jButtonOK.setMargin(new java.awt.Insets(2, 2, 2, 2));
jButtonOK.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonOKActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanelButtonsLayout = new javax.swing.GroupLayout(jPanelButtons);
jPanelButtons.setLayout(jPanelButtonsLayout);
jPanelButtonsLayout.setHorizontalGroup(
jPanelButtonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelButtonsLayout.createSequentialGroup()
.addComponent(jButtonQuit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(114, Short.MAX_VALUE))
.addComponent(jButtonOK, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE)
);
jPanelButtonsLayout.setVerticalGroup(
jPanelButtonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelButtonsLayout.createSequentialGroup()
.addComponent(jButtonQuit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButtonOK, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addComponent(jPanelLists, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanelButtons, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(10, 10, Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(11, 11, 11)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanelLists, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanelButtons, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
//<editor-fold defaultstate="collapsed" desc="Events">
private void jListSolubCmplxValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jListSolubCmplxValueChanged
jListSolidCmplx.clearSelection();
if(delete) {jListSolubCmplx.clearSelection();}
}//GEN-LAST:event_jListSolubCmplxValueChanged
private void jListSolidCmplxValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jListSolidCmplxValueChanged
jListSolubCmplx.clearSelection();
if(delete) {jListSolidCmplx.clearSelection();}
}//GEN-LAST:event_jListSolidCmplxValueChanged
private void jButtonQuitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonQuitActionPerformed
quitFrame();
}//GEN-LAST:event_jButtonQuitActionPerformed
private void jButtonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOKActionPerformed
cancel = false;
if(delete) {deleteComponent(cs, compToDelOrExch);}
else {exchangeComponent(cs, compToDelOrExch);}
if(!cancel) {quitFrame();}
}//GEN-LAST:event_jButtonOKActionPerformed
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
cancel = true;
quitFrame();
}//GEN-LAST:event_formWindowClosing
private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
if(windowSize != null) {
int w = windowSize.width;
int h = windowSize.height;
if(this.getHeight()<h){this.setSize(this.getWidth(), h);}
if(this.getWidth()<w){this.setSize(w,this.getHeight());}
}
}//GEN-LAST:event_formComponentResized
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Methods">
private void quitFrame() {
finished = true;
this.notify_All();
this.dispose();
} // quitForm_Gen_Options
private synchronized void notify_All() {notifyAll();}
/** this method will wait for this dialog frame to be closed
*
* @return "cancel" = true if no modification is made */
public synchronized boolean waitForModifyConfirm() {
while(!finished) {
try {wait();} catch (InterruptedException ex) {}
} // while
return cancel;
} // waitForModifyConfirm()
//<editor-fold defaultstate="collapsed" desc="deleteComponent">
private void deleteComponent(Chem.ChemSystem cs, int compToDel) {
cs.printChemSystem(null);
// --- count first the number of species remaining
// count soluble complexes formed by this component
int nxOut = cs.nx;
for(int i=0; i<cs.nx; i++) {
if(Math.abs(cs.a[i][compToDel]) > 1e-7) {nxOut--;}
} //for i
// count solid products formed by this component
int mSolOut = cs.mSol;
for(int i=cs.nx; i<(cs.Ms-cs.Na-cs.solidC); i++) {
if(Math.abs(cs.a[i][compToDel]) > 1e-7) {mSolOut--;}
} //for i
// components
int naOut = cs.Na - 1;
// solid components
int solidCout = cs.solidC;
if(compToDel >= (cs.Na-cs.solidC)) {solidCout--; mSolOut--;}
// --- remove the species: move other species in arrays
// remove the name of the component
for(int i=compToDel; i<naOut; i++) {
cs.namn.identC[i] = cs.namn.identC[i+1];
cs.namn.ident[i] = cs.namn.ident[i+1];
} //for i
for(int i=naOut; i < cs.Ms-1; i++) {
cs.namn.ident[i] = cs.namn.ident[i+1];
} //for i
// remove the species
int ix1;
int count =0;
for(int ix =0; ix < (cs.Ms-cs.Na-cs.solidC); ix++) {
if(Math.abs(cs.a[ix][compToDel]) > 1e-7) {
count++;
} else {
ix1 = ix - count;
cs.namn.ident[ix1+naOut] = cs.namn.ident[ix+naOut];
cs.lBeta[ix1] = cs.lBeta[ix];
for(int ic =0; ic < naOut; ic++) {
cs.a[ix1][ic] = cs.a[ix][ic];
if(ic >= compToDel) {cs.a[ix1][ic] = cs.a[ix][ic+1];}
} //for ic
}
} //for ix
// --- change the numbers of species
cs.Ms = cs.Ms -(count + (cs.solidC - solidCout)) -1;
cs.mSol = mSolOut;
cs.Na = naOut;
cs.nx = nxOut;
cs.solidC = solidCout;
if(dbg) {System.out.println(" ---- Component deleted.");}
} //deleteComponent
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="exchangeComponent">
private void exchangeComponent(Chem.ChemSystem cs, int compToExch) {
if(dbg) {System.out.println("---- exchangeComponent(cs,"+compToExch+")");}
int solidC0 = cs.solidC;
// --- check
if(jListSolubCmplx.getSelectedIndex() < 0 &&
jListSolidCmplx.getSelectedIndex() < 0) {
javax.swing.JOptionPane.showMessageDialog(this,
"Please, select a species"+nl+"from the list of reaction products",
this.getTitle(), javax.swing.JOptionPane.WARNING_MESSAGE);
cancel = true;
if(dbg) {System.out.println("---- exchangeComponent: cancelled");}
return;
}
// --- the "fictive" solids corresponding to any solid components
// are removed here. If at the end there are any solid components,
// the corresponding solids are added.
//done here on local variables: the instance of ChemSystem is not changed
int Ms = cs.Ms;
int mSol = cs.mSol;
if(cs.solidC > 0) {
Ms = cs.Ms - cs.solidC;
mSol = cs.mSol - cs.solidC;
}
// --- make the exchange
int ix;
int nxOut = cs.nx;
int mSol_Out = mSol;
int solidC_out = cs.solidC;
// is it a solid component?
if(compToExch >= (cs.Na - cs.solidC)) {
solidC_out--;
mSol_Out++;
} else {
nxOut++;
}
String complexExchName;
if(jListSolubCmplx.getSelectedIndex() > -1) {
complexExchName = jListSolubCmplx.getSelectedValue().toString();
} else {
complexExchName = jListSolidCmplx.getSelectedValue().toString();
}
int complexToExch = -1;
for(ix = 0; ix < (Ms - cs.Na); ix++) {
if(complexExchName.equals(cs.namn.ident[ix + cs.Na])) {
complexToExch = ix; break;
}
} //for ix
if(complexToExch < 0) { //this should not occur
System.err.println("Error exchanging \""+complexExchName+"\"; complexToExch = "+complexToExch);
if(dbg) {System.out.println("---- exchangeComponent: error exit");}
cancel = false; // something is really wrong: quit the frame
return;
}
if(dbg) {System.out.println(" exchanging component with reaction: \""+complexExchName+"\"");}
// exchange with a solid complex?
if(complexToExch >= cs.nx) {
solidC_out++;
mSol_Out--;
} else {
nxOut--;
}
String newCompName = complexExchName;
String newCmplxName = cs.namn.identC[compToExch];
double oldLogK = cs.lBeta[complexToExch];
double a1 = cs.a[complexToExch][compToExch];
double[] old_a = new double[cs.Na];
//for(int ic=0; ic < cs.Na; ic++) {old_a[ic] = cs.a[complexToExch][ic];}
System.arraycopy(cs.a[complexToExch], 0, old_a, 0, cs.Na);
for(int ic=compToExch; ic < cs.Na-1; ic++) {
cs.namn.identC[ic] = cs.namn.identC[ic+1];
cs.namn.ident[ic] = cs.namn.ident[ic+1];
}
cs.namn.identC[cs.Na-1] = "** no name **";
cs.namn.ident[cs.Na-1] = "** no name **";
for(ix = complexToExch; ix < (cs.nx + mSol -1); ix++) {
cs.namn.ident[ix + cs.Na] = cs.namn.ident[ix+1 + cs.Na];
cs.lBeta[ix] = cs.lBeta[ix+1];
//for(int ic=0; ic < cs.Na; ic++){cs.a[ix][ic] = cs.a[ix+1][ic];}
System.arraycopy(cs.a[ix+1], 0, cs.a[ix], 0, cs.Na);
} //for ix
ix = cs.nx + mSol -1;
cs.namn.ident[ix + cs.Na] = "** no name **";
cs.lBeta[ix] = 9999999;
for(int ic=0; ic < cs.Na; ic++) {cs.a[ix][ic] = 0;}
// a soluble complex to become a soluble component?
int i; int i_cplx_new; int i_comp_new;
if(complexToExch < cs.nx) {
for(int ic=0; ic < cs.Na; ic++) {
i = cs.Na -1 -ic;
if(i > (cs.Na - solidC_out -1)) {
cs.namn.identC[i] = cs.namn.identC[i-1];
cs.namn.ident[i] = cs.namn.ident[i-1];
}
} //for ic
i_comp_new = cs.Na - solidC_out -1;
cs.namn.identC[i_comp_new] = newCompName;
cs.namn.ident[i_comp_new] = newCompName;
} else { //a solid complex to become a solid component:
i_comp_new = cs.Na -1;
cs.namn.identC[i_comp_new] = newCompName;
cs.namn.ident[i_comp_new] = newCompName;
} //soluble/solid complex
// soluble component to become a soluble complex?
if(compToExch < (cs.Na - cs.solidC)) {
for(ix =0; ix < (cs.nx + mSol); ix++) {
i = (cs.nx + mSol) -1 - ix;
if(i > (nxOut-1)) {
cs.namn.ident[i+cs.Na] = cs.namn.ident[i+cs.Na-1];
cs.lBeta[i] = cs.lBeta[i-1];
//for(int ic=0; ic < cs.Na; ic++) {cs.a[i][ic] = cs.a[i-1][ic];}
System.arraycopy(cs.a[i-1], 0, cs.a[i], 0, cs.Na);
}
} //for ix
i_cplx_new = nxOut -1;
} else { //solid component to become a solid complex:
i_cplx_new = nxOut + mSol_Out -1;
} //solid/soluble component
cs.namn.ident[i_cplx_new + cs.Na] = newCmplxName;
cs.lBeta[i_cplx_new] = -oldLogK / a1;
//for(int ic=0; ic < cs.Na; ic++) {cs.a[i_cplx_new][ic] = old_a[ic];}
System.arraycopy(old_a, 0, cs.a[i_cplx_new], 0, cs.Na);
double old_a_x;
for(ix = 0; ix < (cs.nx + mSol); ix++) {
old_a_x = cs.a[ix][compToExch];
for(int ic=0; ic < cs.Na-1; ic++) {
if(ic >= compToExch) {cs.a[ix][ic] = cs.a[ix][ic+1];}
} //for ic
if(complexToExch < cs.nx) {
for(int ic=0; ic < cs.Na-1; ic++) {
i = cs.Na -1 -ic;
if(i > (cs.Na - solidC_out -1)) {cs.a[ix][i] = cs.a[ix][i-1];}
} //for ic
cs.a[ix][cs.Na - solidC_out -1] = old_a_x;
} else {
cs.a[ix][cs.Na -1] = old_a_x;
}
}
for(int ic=0; ic < cs.Na; ic++) {
old_a[ic] = cs.a[i_cplx_new][ic];
cs.a[i_cplx_new][ic] = round4(-old_a[ic] /a1);
}
cs.a[i_cplx_new][i_comp_new] = round4(1/a1);
double a1p;
for(ix=0; ix < (cs.nx + mSol); ix++) {
if(ix != i_cplx_new) {
a1p = round4(-cs.a[ix][i_comp_new]/a1);
cs.lBeta[ix] = cs.lBeta[ix] + a1p * oldLogK;
for(int ic=0; ic < cs.Na; ic++) {
if(ic != i_comp_new) {
cs.a[ix][ic] = round4(cs.a[ix][ic] + a1p * old_a[ic]);
} else {
cs.a[ix][i_comp_new] = round4(-a1p);
} //if ic != i_cplx_new
} //for ic
} // if ix != i_cplx_new
} //for ix
cs.nx = nxOut;
mSol = mSol_Out;
cs.solidC = solidC_out;
//--- If a new solid component has been introduced, then one must create new
// instances of "ChemSystem" and "NamesEtc" large enough to accomodate
// the new arrays (because one must add a fictive solid reaction product for
// each solid component)
if(solidC0 < cs.solidC) {
if(dbg) {System.out.println(" A new solid component has been introduced.");}
Chem.ChemSystem csNew;
try{csNew = ch.new ChemSystem(cs.Na, (Ms + cs.solidC), (mSol + cs.solidC), cs.solidC);}
catch (Chem.ChemicalParameterException ex) {System.err.println(ex.getMessage()); return;}
Chem.ChemSystem.NamesEtc namnNew;
try{namnNew = csNew.new NamesEtc(cs.Na, (Ms + cs.solidC), (mSol + cs.solidC));}
catch (Chem.ChemicalParameterException ex) {System.err.println(ex.getMessage()); return;}
csNew.jWater = cs.jWater; //not really needed
csNew.chemConcs = cs.chemConcs;
for(ix=0; ix < cs.Ms-cs.Na; ix++) {
csNew.noll[ix] = cs.noll[ix];
csNew.lBeta[ix] = cs.lBeta[ix];
//for(int ic=0; ic < cs.Na; ic++) {csNew.a[ix][ic] = cs.a[ix][ic];}
System.arraycopy(cs.a[ix], 0, csNew.a[ix], 0, cs.Na);
} //for ix
csNew.nx = cs.nx;
csNew.solidC = cs.solidC;
//for(int ia=0; ia < cs.Na; ia++) {namnNew.identC[ia] = cs.namn.identC[ia];}
System.arraycopy(cs.namn.identC, 0, namnNew.identC, 0, cs.Na);
for(ix=0; ix < cs.Ms; ix++) {
namnNew.ident[ix] = cs.namn.ident[ix];
namnNew.nameLength[ix] = cs.namn.nameLength[ix]; //not really needed
} //for ix
// these two arrays are not really needed in this context
//for(ix=0; ix < cs.namn.iel.length; ix++) {namnNew.iel[ix] = cs.namn.iel[ix];}
//for(ix=0; ix < Math.min(cs.namn.z.length,namnNew.z.length); ix++) {namnNew.z[ix] = cs.namn.z[ix];}
//-- change the pointers from the old to the new instances
ch.chemSystem = csNew;
cs.namn = namnNew;
this.cs = csNew;
this.namn = namnNew;
cs = csNew;
cs.namn = namnNew;
} //if solidC0 < cs.namn.solidC
else { // solidC0 >= cs.namn.solidC
//--- No new solid components have appeared.
// Existing instances of "ChemSystem" and "NamesEtc" are large enough
cs.mSol = mSol + cs.solidC;
cs.Ms = Ms + cs.solidC;
}
// --- if there are any solid components, add corresponding
// fictive solid reaction products corresponding to the components
ReadChemSyst.addFictiveSolids(cs);
if(dbg) {System.out.println("---- exchangeComponent: Exchange successful.");}
} //exchangeComponent
/** Rounds to the 4th decimal place, but only if after the 4th decimal place
* the "value" is less than ±0.0002. For example:<br>
* if x<±0.00019 it returns x=+0 (negative zero is avoided)<br>
* if x=±3.000199 it returns x=±3<br>
* if x=±0.2502 no change.<br>
* if x=±9.999801 it returns x=±10<br>
* if x=±0.9998 no change.<br>
* if x=±0.199999 it returns x=±0.2<br>
* Values larger (or smaller) than ±327.6 are <b>NOT</b> rounded.
* @param x a double
* @return rounded value of x */
private double round4(double x) {
if(Double.isNaN(x) || Math.abs(x) > 327.6) {return x;}
if(Math.abs(x)<0.00019999999) {return +0;}
double x100 = x * 100; //if x=0.123456, x100=12.3456
double diff = Math.abs(x100 - Math.rint(x100));
double result = x;
if(diff < 0.0199999999) {result = Math.rint(x100) / 100;}
if(Math.abs(x100 / 100 - result) > 0.00021) {
System.err.println("Error in \"round4(x)\": x="+x+" x100="+x100+" diff="+diff+", result="+result+"(!?)");
}
return result;
} //round4(x)
//</editor-fold>
//</editor-fold>
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButtonOK;
private javax.swing.JButton jButtonQuit;
private javax.swing.JLabel jLabel0;
private javax.swing.JLabel jLabelName;
private javax.swing.JLabel jLabelSolidCmplx;
private javax.swing.JLabel jLabelSolubleCmplx;
private javax.swing.JLabel jLabelWarning;
private javax.swing.JList jListSolidCmplx;
private javax.swing.JList jListSolubCmplx;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanelButtons;
private javax.swing.JPanel jPanelLists;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
// End of variables declaration//GEN-END:variables
}
| 38,946 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
HelpAbout.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Spana/src/spana/HelpAbout.java | package spana;
import lib.Version;
import lib.common.MsgExceptn;
import lib.huvud.LicenseFrame;
/** Shows a window frame with "help-about" information, versions, etc.
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class HelpAbout extends javax.swing.JFrame {
private boolean finished = false;
private HelpAbout frame = null;
private LicenseFrame lf = null;
private java.awt.Dimension windowSize = new java.awt.Dimension(300,200);
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
/** Creates new form HelpAboutF
* @param pathAPP */
public HelpAbout(final String pathAPP) {
initComponents();
finished = false;
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
//--- Close window on ESC key
javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_ESCAPE,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE");
javax.swing.Action escAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
closeWindow();
}};
getRootPane().getActionMap().put("ESCAPE", escAction);
//--- Alt-X eXit
javax.swing.KeyStroke altXKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altXKeyStroke,"ALT_X");
getRootPane().getActionMap().put("ALT_X", escAction);
//--- alt-Q exit
javax.swing.KeyStroke altQKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altQKeyStroke,"ALT_Q");
getRootPane().getActionMap().put("ALT_Q", escAction);
//--- Enter exit
javax.swing.KeyStroke enterKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_ENTER, 0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(enterKeyStroke,"_Enter");
getRootPane().getActionMap().put("_Enter", escAction);
//--- Title, etc
//getContentPane().setBackground(new java.awt.Color(255, 255, 153));
getContentPane().setBackground(java.awt.Color.white);
this.setTitle("Spana: About");
//---- Icon
String iconName = "images/Question_16x16.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
if(imgURL != null) {this.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());}
else {System.out.println("Error: Could not load image = \""+iconName+"\"");}
//
jLabelVers.setText("Program version: "+MainFrame.VERS);
//
jLabelLib.setText("LibChemDiagr: "+Version.version());
//
if(pathAPP != null) {
if(pathAPP.trim().length()>0) {jLabelPathApp.setText(pathAPP);}
else {jLabelPathApp.setText(" \"\"");}
}
jLabelPathUser.setText(System.getProperty("user.home"));
this.validate();
int w = jLabelPathApp.getWidth()+40;
if(w > this.getWidth()) {this.setSize(w, this.getHeight());}
//
if(MainFrame.fileIni != null) {jLabelIniFile.setText(MainFrame.fileIni.getPath());}
jLabelJavaVers.setText("Java Runtime Environment "+System.getProperty("java.version"));
jLabelOS.setText("<html>Operating system: \""+
System.getProperty("os.name")+" "+System.getProperty("os.version")+"\"<br>"+
"architecture: \""+System.getProperty("os.arch")+"\"</html>");
this.validate();
w = jLabelIniFile.getWidth()+40;
if(w > this.getWidth()) {this.setSize(w, this.getHeight());}
// Center the window on the screen
int left = Math.max(0,(MainFrame.screenSize.width-this.getWidth())/2);
int top = Math.max(0,(MainFrame.screenSize.height-this.getHeight())/2);
this.setLocation(Math.min(MainFrame.screenSize.width-100, left),
Math.min(MainFrame.screenSize.height-100, top));
} //constructor
public void start() {
this.setVisible(true);
windowSize = this.getSize();
frame = this;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabelName = new javax.swing.JLabel();
jLabelVers = new javax.swing.JLabel();
jLabelLibs = new javax.swing.JLabel();
jLabelLib = new javax.swing.JLabel();
jLabelJVectClipb = new javax.swing.JLabel();
jLabelJVectClipb_www = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jButtonLicense = new javax.swing.JButton();
jLabel_wwwKTH = new javax.swing.JLabel();
jLabel_www = new javax.swing.JLabel();
jSeparator2 = new javax.swing.JSeparator();
jLabelJava = new javax.swing.JLabel();
jLabelJavaIcon = new javax.swing.JLabel();
jPanelNetBeans = new javax.swing.JPanel();
jLabelNetbeansIcon = new javax.swing.JLabel();
jLabelNetBeans = new javax.swing.JLabel();
jLabelNetBeans_www = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jLabelJavaVers = new javax.swing.JLabel();
jLabelOS = new javax.swing.JLabel();
jSeparator3 = new javax.swing.JSeparator();
jLabelPathA = new javax.swing.JLabel();
jLabelPathApp = new javax.swing.JLabel();
jLabelPathU = new javax.swing.JLabel();
jLabelPathUser = new javax.swing.JLabel();
jLabelIniF = new javax.swing.JLabel();
jLabelIniFile = new javax.swing.JLabel();
jLabelUnicode = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jLabelName.setText("<html><font size=+1><b>Spana</b></font> © 2012-2020 I.Puigdomenech<br>\nThis program comes with<br>\nABSOLUTELY NO WARRANTY.<br>\nThis is free software, and you may<br>\nredistribute it under the GNU GPL license.</html>"); // NOI18N
jLabelName.setVerticalAlignment(javax.swing.SwingConstants.TOP);
jLabelVers.setText(" Program version: 2010-September-30");
jLabelLibs.setFont(new java.awt.Font("Tahoma", 2, 11)); // NOI18N
jLabelLibs.setText("Libraries:");
jLabelLib.setText("LibChemDiagr: 2011-March-30");
jLabelJVectClipb.setText("jvect-clipboard 1.3 "); // NOI18N
jLabelJVectClipb_www.setForeground(new java.awt.Color(0, 0, 221));
jLabelJVectClipb_www.setText("<html><u>sourceforge.net/projects/jvect-clipboard/</u></html>"); // NOI18N
jLabelJVectClipb_www.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jLabelJVectClipb_www.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabelJVectClipb_wwwMouseClicked(evt);
}
});
jPanel2.setOpaque(false);
jButtonLicense.setMnemonic('l');
jButtonLicense.setText(" License Details ");
jButtonLicense.setAlignmentX(0.5F);
jButtonLicense.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonLicense.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonLicenseActionPerformed(evt);
}
});
jLabel_wwwKTH.setForeground(new java.awt.Color(0, 0, 221));
jLabel_wwwKTH.setText("<html><u>www.kth.se/che/medusa</u></html>"); // NOI18N
jLabel_wwwKTH.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jLabel_wwwKTH.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel_wwwKTHMouseClicked(evt);
}
});
jLabel_www.setForeground(new java.awt.Color(0, 0, 221));
jLabel_www.setText("<html><u>sites.google.com/site/chemdiagr/</u></html>"); // NOI18N
jLabel_www.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jLabel_www.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel_wwwMouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel_www, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel_wwwKTH, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButtonLicense))
.addContainerGap(32, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addGap(25, 25, 25)
.addComponent(jButtonLicense)
.addGap(18, 18, 18)
.addComponent(jLabel_wwwKTH, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(3, 3, 3)
.addComponent(jLabel_www, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(42, Short.MAX_VALUE))
);
jLabelJava.setText("<html>Java Standard Edition<br> Development Kit 7 (JDK 1.7)</html>"); // NOI18N
jLabelJavaIcon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/spana/images/Java_24x24.gif"))); // NOI18N
jLabelJavaIcon.setIconTextGap(0);
jPanelNetBeans.setOpaque(false);
jLabelNetbeansIcon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/spana/images/Netbeans11_24x24.gif"))); // NOI18N
jLabelNetBeans.setText("NetBeans IDE 11"); // NOI18N
jLabelNetBeans_www.setForeground(new java.awt.Color(0, 0, 221));
jLabelNetBeans_www.setText("<html><u>netbeans.org</u></html>"); // NOI18N
jLabelNetBeans_www.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jLabelNetBeans_www.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabelNetBeans_wwwMouseClicked(evt);
}
});
javax.swing.GroupLayout jPanelNetBeansLayout = new javax.swing.GroupLayout(jPanelNetBeans);
jPanelNetBeans.setLayout(jPanelNetBeansLayout);
jPanelNetBeansLayout.setHorizontalGroup(
jPanelNetBeansLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelNetBeansLayout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jLabelNetbeansIcon)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabelNetBeans)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelNetBeans_www, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelNetBeansLayout.setVerticalGroup(
jPanelNetBeansLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelNetBeansLayout.createSequentialGroup()
.addGap(0, 0, 0)
.addGroup(jPanelNetBeansLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelNetbeansIcon)
.addGroup(jPanelNetBeansLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelNetBeans_www, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelNetBeans, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))))
);
jPanel1.setOpaque(false);
jLabelJavaVers.setText("jLabelJavaVers");
jLabelOS.setText("<html>Operating system:<br>\"os.name os.version\" \narchitecture: \"os.arch\"</html>");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelOS)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabelJavaVers)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(2, 2, 2)
.addComponent(jLabelJavaVers)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelOS, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jLabelPathA.setLabelFor(jLabelPathA);
jLabelPathA.setText("Application path:"); // NOI18N
jLabelPathApp.setText("\"null\""); // NOI18N
jLabelPathU.setText("User \"home\" directory:");
jLabelPathUser.setText("\"null\"");
jLabelIniF.setLabelFor(jLabelIniFile);
jLabelIniF.setText("Ini-file:"); // NOI18N
jLabelIniFile.setText("\"null\""); // NOI18N
jLabelUnicode.setText("(Unicode UTF-8)");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelJavaIcon)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelJava, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanelNetBeans, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jSeparator3)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelPathA)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelPathApp))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelPathU)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelPathUser))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelIniF)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelIniFile)))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelLib)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelJVectClipb)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabelJVectClipb_www, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addComponent(jLabelLibs)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelVers)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelUnicode))
.addComponent(jLabelName, javax.swing.GroupLayout.PREFERRED_SIZE, 331, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(jLabelName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelVers)
.addComponent(jLabelUnicode))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabelLibs)
.addGap(2, 2, 2)
.addComponent(jLabelLib)
.addGap(2, 2, 2)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelJVectClipb)
.addComponent(jLabelJVectClipb_www, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelJavaIcon, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelJava, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanelNetBeans, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelPathA)
.addComponent(jLabelPathApp))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelPathU)
.addComponent(jLabelPathUser))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelIniF)
.addComponent(jLabelIniFile))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jLabel_wwwKTHMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel_wwwKTHMouseClicked
this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
jLabel_wwwKTH.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
BareBonesBrowserLaunch.openURL("https://www.kth.se/che/medusa/",this);
this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jLabel_wwwKTH.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
}//GEN-LAST:event_jLabel_wwwKTHMouseClicked
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
closeWindow();
}//GEN-LAST:event_formWindowClosing
private void jLabelJVectClipb_wwwMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelJVectClipb_wwwMouseClicked
this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
jLabelJVectClipb_www.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
BareBonesBrowserLaunch.openURL("https://sourceforge.net/projects/jvect-clipboard/",this);
this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jLabelJVectClipb_www.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
}//GEN-LAST:event_jLabelJVectClipb_wwwMouseClicked
private void jLabelNetBeans_wwwMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelNetBeans_wwwMouseClicked
this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
jLabelNetBeans_www.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
BareBonesBrowserLaunch.openURL("https://netbeans.org/",this);
this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jLabelNetBeans_www.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
}//GEN-LAST:event_jLabelNetBeans_wwwMouseClicked
private void jLabel_wwwMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel_wwwMouseClicked
this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
jLabel_www.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
BareBonesBrowserLaunch.openURL("https://sites.google.com/site/chemdiagr/",this);
this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jLabel_www.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
}//GEN-LAST:event_jLabel_wwwMouseClicked
private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
if(windowSize != null) {
int w = windowSize.width;
int h = windowSize.height;
if(this.getHeight()<h){this.setSize(this.getWidth(), h);}
if(this.getWidth()<w){this.setSize(w,this.getHeight());}
}
}//GEN-LAST:event_formComponentResized
private void jButtonLicenseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLicenseActionPerformed
if(lf != null) {return;} //this should not happen
this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
Thread licShow = new Thread() {@Override public void run(){
jButtonLicense.setEnabled(false);
lf = new LicenseFrame(HelpAbout.this);
lf.setVisible(true);
HelpAbout.this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
lf.waitFor();
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
lf = null;
jButtonLicense.setEnabled(true);
}}); //invokeLater(Runnable)
}};//new Thread
licShow.start();
}//GEN-LAST:event_jButtonLicenseActionPerformed
public void closeWindow() {
if(lf != null) {lf.closeWindow(); lf = null;}
finished = true;
this.notify_All();
this.setVisible(false);
frame = null;
this.dispose();
} // closeWindow()
private synchronized void notify_All() {notifyAll();}
/** this method will wait for this dialog frame to be closed */
public synchronized void waitFor() {
while(!finished) {
try {wait();} catch (InterruptedException ex) {}
} // while
} // waitFor()
public void bringToFront() {
if(frame != null) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override public void run() {
frame.setVisible(true);
if((frame.getExtendedState() & javax.swing.JFrame.ICONIFIED) // minimised?
== javax.swing.JFrame.ICONIFIED) {
frame.setExtendedState(javax.swing.JFrame.NORMAL);
} // if minimized
frame.setAlwaysOnTop(true);
frame.toFront();
frame.requestFocus();
frame.setAlwaysOnTop(false);
}
});
}
} // bringToFront()
//<editor-fold defaultstate="collapsed" desc="class BareBonesBrowserLaunch">
/**
* <b>Bare Bones Browser Launch for Java</b><br>
* Utility class to open a web page from a Swing application
* in the user's default browser.<br>
* Supports: Mac OS X, GNU/Linux, Unix, Windows XP/Vista/7<br>
* Example Usage:<code><br>
* String url = "http://www.google.com/";<br>
* BareBonesBrowserLaunch.openURL(url);<br></code>
* Latest Version: <a href=http://centerkey.com/java/browser>centerkey.com/java/browser</a><br>
* Author: Dem Pilafian<br>
* WTFPL -- Free to use as you like
* @version 3.2, October 24, 2010
*/
private static class BareBonesBrowserLaunch {
static final String[] browsers = { "x-www-browser", "google-chrome",
"firefox", "opera", "epiphany", "konqueror", "conkeror", "midori",
"kazehakase", "mozilla", "chromium" }; // modified by Ignasi (added "chromium")
static final String errMsg = "Error attempting to launch web browser";
/**
* Opens the specified web page in the user's default browser
* @param url A web address (URL) of a web page (ex: "http://www.google.com/")
*/
public static void openURL(String url, javax.swing.JFrame parent) { // modified by Ignasi (added "parent")
try { //attempt to use Desktop library from JDK 1.6+
Class<?> d = Class.forName("java.awt.Desktop");
d.getDeclaredMethod("browse", new Class[] {java.net.URI.class}).invoke(
d.getDeclaredMethod("getDesktop").invoke(null),
new Object[] {java.net.URI.create(url)});
//above code mimicks: java.awt.Desktop.getDesktop().browse()
}
catch (Exception ignore) { //library not available or failed
String osName = System.getProperty("os.name");
try {
if (osName.startsWith("Mac OS")) {
Class.forName("com.apple.eio.FileManager").getDeclaredMethod(
"openURL", new Class[] {String.class}).invoke(null,new Object[] {url});
}
else if (osName.startsWith("Windows"))
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
else { //assume Unix or Linux
String browser = null;
for (String b : browsers)
if (browser == null && Runtime.getRuntime().exec(new String[]
{"which", b}).getInputStream().read() != -1)
Runtime.getRuntime().exec(new String[] {browser = b, url});
if (browser == null)
throw new Exception(java.util.Arrays.toString(browsers));
}
}
catch (Exception e) {
MsgExceptn.exception(errMsg + "\n" + e.getMessage()); // added by Ignasi
javax.swing.JOptionPane.showMessageDialog(parent, errMsg + "\n" + e.getMessage(), // modified by Ignasi (added "parent")
"Chemical Equilibrium Diagrams", javax.swing.JOptionPane.ERROR_MESSAGE); // added by Ignasi
}
}
}
}
//</editor-fold>
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButtonLicense;
private javax.swing.JLabel jLabelIniF;
private javax.swing.JLabel jLabelIniFile;
private javax.swing.JLabel jLabelJVectClipb;
private javax.swing.JLabel jLabelJVectClipb_www;
private javax.swing.JLabel jLabelJava;
private javax.swing.JLabel jLabelJavaIcon;
private javax.swing.JLabel jLabelJavaVers;
private javax.swing.JLabel jLabelLib;
private javax.swing.JLabel jLabelLibs;
private javax.swing.JLabel jLabelName;
private javax.swing.JLabel jLabelNetBeans;
private javax.swing.JLabel jLabelNetBeans_www;
private javax.swing.JLabel jLabelNetbeansIcon;
private javax.swing.JLabel jLabelOS;
private javax.swing.JLabel jLabelPathA;
private javax.swing.JLabel jLabelPathApp;
private javax.swing.JLabel jLabelPathU;
private javax.swing.JLabel jLabelPathUser;
private javax.swing.JLabel jLabelUnicode;
private javax.swing.JLabel jLabelVers;
private javax.swing.JLabel jLabel_www;
private javax.swing.JLabel jLabel_wwwKTH;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanelNetBeans;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JSeparator jSeparator3;
// End of variables declaration//GEN-END:variables
}
| 33,871 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
OptionsDiagram.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Spana/src/spana/OptionsDiagram.java | package spana;
import lib.huvud.ProgramConf;
import lib.kemi.graph_lib.DiagrPaintUtility;
/** Options dialog for diagram windows.
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class OptionsDiagram extends javax.swing.JFrame {
private DiagrPaintUtility diagrPaintUtil;
private ProgramConf pc;
private boolean finished = false;
private java.awt.Dimension windowSize;
// set values in the local variables, which will be discarded
// if the user presses "Cancel"
private java.awt.Color[] L_colours =
new java.awt.Color[DiagrPaintUtility.MAX_COLOURS];
private javax.swing.border.Border scrollBorder;
private javax.swing.border.Border buttonBorder;
private final javax.swing.border.Border buttonBorderSelected =
javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED,
new java.awt.Color(102,102,102),
new java.awt.Color(255,255,255),
new java.awt.Color(102,102,102),
new java.awt.Color(0,0,0));
private java.awt.Color L_backgrnd;
/** New-line character(s) to substitute "\n". */
private static final String nl = System.getProperty("line.separator");
private final static java.text.NumberFormat nf =
java.text.NumberFormat.getNumberInstance(java.util.Locale.ENGLISH);
private static final java.text.DecimalFormat myFormatter = (java.text.DecimalFormat)nf;
/** use "df" to write numbers using decimal point and without thousand separators:
* df.setGroupingUsed(false); // no commas to separate thousands
* outputFile.write(df.format(X)); */
// static java.text.DecimalFormat df = (java.text.DecimalFormat)nf;
// alternatively use the "dfp" method
// outputFile.write(dfp("##0.0##",X));
// outputFile.write(dfp("##0.0##E#00",X));
//<editor-fold defaultstate="collapsed" desc="Constructor">
/** Creates new form OptionsDiagram
* @param diagPU
* @param pc0 */
public OptionsDiagram(DiagrPaintUtility diagPU,
ProgramConf pc0) {
initComponents();
this.pc = pc0;
this.diagrPaintUtil = diagPU;
finished = false;
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
//--- close window on ESC key
javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE");
javax.swing.Action escAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jButton_Cancel.requestFocus();
closeWindow();
}};
getRootPane().getActionMap().put("ESCAPE", escAction);
//--- F1 for help
javax.swing.KeyStroke f1KeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(f1KeyStroke,"F1");
javax.swing.Action f1Action = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
OptionsDiagram.this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
Thread hlp = new Thread() {@Override public void run(){
String[] a = {"S_Menu_Prefs_htm_Diagr"};
lib.huvud.RunProgr.runProgramInProcess(OptionsDiagram.this,ProgramConf.HELP_JAR,a,false,pc.dbg,pc.pathAPP);
try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec
catch (InterruptedException e) {}
OptionsDiagram.this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
}};//new Thread
hlp.start();
}};
getRootPane().getActionMap().put("F1", f1Action);
//--- Alt-H help
javax.swing.KeyStroke altHKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_H, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altHKeyStroke,"ALT_H");
getRootPane().getActionMap().put("ALT_H", f1Action);
//--- alt-X
javax.swing.KeyStroke altXKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altXKeyStroke,"ALT_X");
javax.swing.Action altXAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jButton_OK.doClick();
}};
getRootPane().getActionMap().put("ALT_X", altXAction);
//--- Alt-B - set Background colour
javax.swing.KeyStroke altBKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_B, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altBKeyStroke,"ALT_B");
javax.swing.Action altBAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(!jCheckBackgr.isSelected()) {return;}
jPanelBackGrnd.requestFocus();
changeBackgroundColour();
}};
getRootPane().getActionMap().put("ALT_B", altBAction);
//
getRootPane().setDefaultButton(jButton_OK);
buttonBorder = jButton1.getBorder(); // get the default button border
scrollBorder = jScrollBar_Pen.getBorder(); // get the default scroll bar border
//--- Title
this.setTitle("Graphic Options:");
//--- Icon
String iconName = "images/Wrench_32x32.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
if (imgURL != null) {this.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());}
else {System.out.println("Error: Could not load image = \""+iconName+"\"");}
//
jPanel_Fonts.setPreferredSize(new java.awt.Dimension(jPanel_Fonts.getSize()));
// center Window on Screen
windowSize = this.getSize();
int left; int top;
left = Math.max(0, (MainFrame.screenSize.width - windowSize.width ) / 2);
top = Math.max(0, (MainFrame.screenSize.height - windowSize.height) / 2);
this.setLocation(Math.min(MainFrame.screenSize.width-100, left),
Math.min(MainFrame.screenSize.height-100, top));
//
System.arraycopy(diagrPaintUtil.colours, 0, L_colours, 0, DiagrPaintUtility.MAX_COLOURS);
L_backgrnd = diagrPaintUtil.backgrnd;
if(diagrPaintUtil.textWithFonts) {
jRadioButton_FontPrinter.setSelected(true);
jCombo_FontFamily.setVisible(true);
jCombo_FontStyle.setVisible(true);
jText_FontSize.setVisible(true);
jLabelAntiAT.setVisible(true);
jComboAntiAliasT.setVisible(true);
} else {
jRadioButton_FontNone.setSelected(true);
jCombo_FontFamily.setVisible(false);
jCombo_FontStyle.setVisible(false);
jText_FontSize.setVisible(false);
jLabelAntiAT.setVisible(false);
jComboAntiAliasT.setVisible(false);
}
jCombo_FontFamily.setSelectedIndex(diagrPaintUtil.fontFamily);
jCombo_FontStyle.setSelectedIndex(diagrPaintUtil.fontStyle);
jText_FontSize.setText(String.valueOf(diagrPaintUtil.fontSize));
jScrollBar_Pen.setValue(Math.round(diagrPaintUtil.penThickness*10f));
jScrollBar_PenAdjustmentValueChanged(null);
myFormatter.applyPattern("##0.#");
jCheckBox_FixedSize.setText("Constant Size ("+
myFormatter.format(diagrPaintUtil.fixedSizeWidth)+"x"+
myFormatter.format(diagrPaintUtil.fixedSizeHeight)+")");
jCheckBox_FixedSize.setSelected(diagrPaintUtil.fixedSize);
jCheckBox_AspectRatio.setSelected(diagrPaintUtil.keepAspectRatio);
jCheckBox_FixedSize.setVisible(!jCheckBox_AspectRatio.isSelected());
jComboAntiAlias.setSelectedIndex(diagrPaintUtil.antiAliasing);
jComboAntiAliasT.setSelectedIndex(diagrPaintUtil.antiAliasingText);
jButton1.setBackground(diagrPaintUtil.colours[0]);
jButton2.setBackground(diagrPaintUtil.colours[1]);
jButton3.setBackground(diagrPaintUtil.colours[2]);
jButton4.setBackground(diagrPaintUtil.colours[3]);
jButton5.setBackground(diagrPaintUtil.colours[4]);
jButton6.setBackground(diagrPaintUtil.colours[5]);
jButton7.setBackground(diagrPaintUtil.colours[6]);
jButton8.setBackground(diagrPaintUtil.colours[7]);
jButton9.setBackground(diagrPaintUtil.colours[8]);
jButton10.setBackground(diagrPaintUtil.colours[9]);
jButton11.setBackground(diagrPaintUtil.colours[10]);
jCheckBackgr.setSelected(diagrPaintUtil.useBackgrndColour);
jCheckBoxPrintColour.setSelected(diagrPaintUtil.printColour);
jCheckPrintHeader.setSelected(diagrPaintUtil.printHeader);
jScrollBar_PenPrint.setValue(Math.round(diagrPaintUtil.printPenThickness*10f));
java.awt.Dimension d = jPanelColours.getSize();
jPanelColours.setPreferredSize(d);
if (jCheckBackgr.isSelected()) {
jPanelBackGrnd.setFocusable(true);
jPanelBackGrnd.setBorder(
javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
jPanelBackGrnd.setBackground(L_backgrnd);
jPanelBackGrnd.setToolTipText("Alt-B");
} else {
jPanelBackGrnd.setBorder(null);
jPanelBackGrnd.setBackground(java.awt.Color.white);
jPanelBackGrnd.setToolTipText(null);
jPanelBackGrnd.setFocusable(false);
}
switch (diagrPaintUtil.colourType) {
case 1: // BW
jRadioButtonBW.setSelected(true);
jCheckBackgr.setVisible(false);
jButton_ResetColours.setVisible(false);
jPanelBackGrnd.setVisible(false);
break;
case 2: // WB
jRadioButtonWB.setSelected(true);
jCheckBackgr.setVisible(false);
jButton_ResetColours.setVisible(false);
jPanelBackGrnd.setVisible(false);
break;
default:
jRadioButtonColour.setSelected(true);
jCheckBackgr.setVisible(true);
jButton_ResetColours.setVisible(true);
jPanelBackGrnd.setVisible(true);
} //switch
jPanelScreenDisp.setPreferredSize(jPanelScreenDisp.getSize());
jScrollBar_Pen.setFocusable(true);
jScrollBar_PenPrint.setFocusable(true);
} //constructor
//</editor-fold>
/* public static String dfp (String pattern, double value) {
//java.text.NumberFormat nf = java.text.NumberFormat.getNumberInstance(Locale.ENGLISH);
java.text.DecimalFormat myFormatter = (java.text.DecimalFormat)nf;
myFormatter.setGroupingUsed(false);
try {myFormatter.applyPattern(pattern);}
catch (Exception ex) {System.err.println("Error: "+ex.getMessage()+nl+
" value="+value+" pattern = \""+pattern+"\"");}
return myFormatter.format(value);
}
*/
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup_FontPrinter = new javax.swing.ButtonGroup();
buttonGroup_Colr = new javax.swing.ButtonGroup();
jPanel4 = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
jButton_OK = new javax.swing.JButton();
jButton_Cancel = new javax.swing.JButton();
jPanelScreenDisp = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jCheckBox_AspectRatio = new javax.swing.JCheckBox();
jCheckBox_FixedSize = new javax.swing.JCheckBox();
jPanel3 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jLabel_PenThickness = new javax.swing.JLabel();
jScrollBar_Pen = new javax.swing.JScrollBar();
jLabelAntiA1 = new javax.swing.JLabel();
jComboAntiAlias = new javax.swing.JComboBox();
jPanel_Fonts = new javax.swing.JPanel();
jPanel6 = new javax.swing.JPanel();
jRadioButton_FontNone = new javax.swing.JRadioButton();
jRadioButton_FontPrinter = new javax.swing.JRadioButton();
jCombo_FontFamily = new javax.swing.JComboBox();
jCombo_FontStyle = new javax.swing.JComboBox();
jText_FontSize = new javax.swing.JTextField();
jLabelAntiAT = new javax.swing.JLabel();
jComboAntiAliasT = new javax.swing.JComboBox();
jPanelColours = new javax.swing.JPanel();
jPanel7 = new javax.swing.JPanel();
jRadioButtonColour = new javax.swing.JRadioButton();
jRadioButtonBW = new javax.swing.JRadioButton();
jRadioButtonWB = new javax.swing.JRadioButton();
jPanel2 = new javax.swing.JPanel();
jCheckBackgr = new javax.swing.JCheckBox();
jButton_ResetColours = new javax.swing.JButton();
jPanelBackGrnd = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton();
jButton7 = new javax.swing.JButton();
jButton8 = new javax.swing.JButton();
jButton9 = new javax.swing.JButton();
jButton10 = new javax.swing.JButton();
jButton11 = new javax.swing.JButton();
jPanelPrint = new javax.swing.JPanel();
jPanel9 = new javax.swing.JPanel();
jCheckBoxPrintColour = new javax.swing.JCheckBox();
jCheckPrintHeader = new javax.swing.JCheckBox();
jPanel8 = new javax.swing.JPanel();
jLabel4 = new javax.swing.JLabel();
jLabel_PenPrint = new javax.swing.JLabel();
jScrollBar_PenPrint = new javax.swing.JScrollBar();
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jButton_OK.setIcon(new javax.swing.ImageIcon(getClass().getResource("/spana/images/OK_32x32.gif"))); // NOI18N
jButton_OK.setMnemonic('O');
jButton_OK.setText("OK");
jButton_OK.setToolTipText("OK (Alt-O orAlt-X)"); // NOI18N
jButton_OK.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButton_OK.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jButton_OK.setMargin(new java.awt.Insets(2, 2, 2, 2));
jButton_OK.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_OKActionPerformed(evt);
}
});
jButton_Cancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/spana/images/Trash.gif"))); // NOI18N
jButton_Cancel.setMnemonic('Q');
jButton_Cancel.setText("Quit");
jButton_Cancel.setToolTipText("Cancel (Esc or Alt-Q)"); // NOI18N
jButton_Cancel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButton_Cancel.setDefaultCapable(false);
jButton_Cancel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jButton_Cancel.setMargin(new java.awt.Insets(2, 2, 2, 2));
jButton_Cancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_CancelActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton_Cancel, javax.swing.GroupLayout.DEFAULT_SIZE, 67, Short.MAX_VALUE)
.addComponent(jButton_OK, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
.addComponent(jButton_OK)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton_Cancel)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel1.setForeground(new java.awt.Color(0, 0, 255));
jLabel1.setText("Screen display:"); // NOI18N
jCheckBox_AspectRatio.setMnemonic(java.awt.event.KeyEvent.VK_K);
jCheckBox_AspectRatio.setText("Keep Diagram's Aspect Ratio"); // NOI18N
jCheckBox_AspectRatio.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBox_AspectRatioActionPerformed(evt);
}
});
jCheckBox_FixedSize.setMnemonic(java.awt.event.KeyEvent.VK_S);
jCheckBox_FixedSize.setText("Constant Size (21x15)"); // NOI18N
javax.swing.GroupLayout jPanelScreenDispLayout = new javax.swing.GroupLayout(jPanelScreenDisp);
jPanelScreenDisp.setLayout(jPanelScreenDispLayout);
jPanelScreenDispLayout.setHorizontalGroup(
jPanelScreenDispLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelScreenDispLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelScreenDispLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jCheckBox_FixedSize)
.addComponent(jCheckBox_AspectRatio)
.addComponent(jLabel1))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelScreenDispLayout.setVerticalGroup(
jPanelScreenDispLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelScreenDispLayout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jCheckBox_AspectRatio)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jCheckBox_FixedSize))
);
jLabel2.setText("Line Thickness"); // NOI18N
jLabel_PenThickness.setText("1"); // NOI18N
jScrollBar_Pen.setMinimum(2);
jScrollBar_Pen.setOrientation(javax.swing.JScrollBar.HORIZONTAL);
jScrollBar_Pen.setUnitIncrement(2);
jScrollBar_Pen.setValue(10);
jScrollBar_Pen.setVisibleAmount(0);
jScrollBar_Pen.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jScrollBar_Pen.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jScrollBar_PenFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jScrollBar_PenFocusLost(evt);
}
});
jScrollBar_Pen.addAdjustmentListener(new java.awt.event.AdjustmentListener() {
public void adjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {
jScrollBar_PenAdjustmentValueChanged(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2))
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollBar_Pen, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(40, 40, 40)
.addComponent(jLabel_PenThickness)))
.addContainerGap())
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(11, 11, 11)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel_PenThickness)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollBar_Pen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jLabelAntiA1.setText("Antialiasing:"); // NOI18N
jComboAntiAlias.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Off", "On", "Default" }));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabelAntiA1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboAntiAlias, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanelScreenDisp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanelScreenDisp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jComboAntiAlias, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelAntiA1))))
.addContainerGap())
);
jPanel_Fonts.setBorder(javax.swing.BorderFactory.createTitledBorder(null, " Fonts: ", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11), new java.awt.Color(0, 0, 255))); // NOI18N
buttonGroup_FontPrinter.add(jRadioButton_FontNone);
jRadioButton_FontNone.setMnemonic(java.awt.event.KeyEvent.VK_N);
jRadioButton_FontNone.setSelected(true);
jRadioButton_FontNone.setText("None"); // NOI18N
jRadioButton_FontNone.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton_FontNoneActionPerformed(evt);
}
});
buttonGroup_FontPrinter.add(jRadioButton_FontPrinter);
jRadioButton_FontPrinter.setMnemonic(java.awt.event.KeyEvent.VK_P);
jRadioButton_FontPrinter.setText("Printer Font"); // NOI18N
jRadioButton_FontPrinter.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton_FontPrinterActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jRadioButton_FontPrinter)
.addComponent(jRadioButton_FontNone))
.addContainerGap(11, Short.MAX_VALUE))
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
.addComponent(jRadioButton_FontNone)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jRadioButton_FontPrinter)
.addContainerGap())
);
jCombo_FontFamily.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Serif", "SansSerif", "Monospaced", "Dialog", "DialogInput" }));
jCombo_FontStyle.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Plain", "Bold", "Italic" }));
jText_FontSize.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
jText_FontSize.setText("12"); // NOI18N
jText_FontSize.setMinimumSize(new java.awt.Dimension(60, 20));
jText_FontSize.setPreferredSize(new java.awt.Dimension(30, 20));
jText_FontSize.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jText_FontSizeKeyReleased(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jText_FontSizeKeyTyped(evt);
}
});
jLabelAntiAT.setLabelFor(jComboAntiAliasT);
jLabelAntiAT.setText("Antialiasing (text):"); // NOI18N
jComboAntiAliasT.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Off", "On", "Default" }));
javax.swing.GroupLayout jPanel_FontsLayout = new javax.swing.GroupLayout(jPanel_Fonts);
jPanel_Fonts.setLayout(jPanel_FontsLayout);
jPanel_FontsLayout.setHorizontalGroup(
jPanel_FontsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel_FontsLayout.createSequentialGroup()
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel_FontsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel_FontsLayout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jCombo_FontFamily, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jCombo_FontStyle, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jText_FontSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel_FontsLayout.createSequentialGroup()
.addGap(85, 85, 85)
.addComponent(jLabelAntiAT)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboAntiAliasT, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
jPanel_FontsLayout.setVerticalGroup(
jPanel_FontsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel_FontsLayout.createSequentialGroup()
.addGroup(jPanel_FontsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel_FontsLayout.createSequentialGroup()
.addGroup(jPanel_FontsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jCombo_FontFamily, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jCombo_FontStyle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jText_FontSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(7, 7, 7)
.addGroup(jPanel_FontsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jComboAntiAliasT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelAntiAT)))
.addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
jPanelColours.setBorder(javax.swing.BorderFactory.createTitledBorder(null, " Colours: ", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11), new java.awt.Color(0, 0, 255))); // NOI18N
buttonGroup_Colr.add(jRadioButtonColour);
jRadioButtonColour.setMnemonic(java.awt.event.KeyEvent.VK_C);
jRadioButtonColour.setText("Colour"); // NOI18N
jRadioButtonColour.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonColourActionPerformed(evt);
}
});
buttonGroup_Colr.add(jRadioButtonBW);
jRadioButtonBW.setMnemonic(java.awt.event.KeyEvent.VK_L);
jRadioButtonBW.setText("bLack on white"); // NOI18N
jRadioButtonBW.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonBWActionPerformed(evt);
}
});
buttonGroup_Colr.add(jRadioButtonWB);
jRadioButtonWB.setMnemonic(java.awt.event.KeyEvent.VK_W);
jRadioButtonWB.setText("White on black"); // NOI18N
jRadioButtonWB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonWBActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
jPanel7.setLayout(jPanel7Layout);
jPanel7Layout.setHorizontalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jRadioButtonColour)
.addComponent(jRadioButtonBW)
.addComponent(jRadioButtonWB))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel7Layout.setVerticalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addComponent(jRadioButtonColour)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jRadioButtonBW)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jRadioButtonWB)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jCheckBackgr.setMnemonic(java.awt.event.KeyEvent.VK_G);
jCheckBackgr.setText("Background"); // NOI18N
jCheckBackgr.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBackgrActionPerformed(evt);
}
});
jButton_ResetColours.setMnemonic(java.awt.event.KeyEvent.VK_R);
jButton_ResetColours.setText("Reset"); // NOI18N
jButton_ResetColours.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButton_ResetColours.setDefaultCapable(false);
jButton_ResetColours.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_ResetColoursActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jCheckBackgr))
.addComponent(jButton_ResetColours, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jCheckBackgr)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton_ResetColours)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelBackGrnd.setBackground(new java.awt.Color(255, 255, 255));
jPanelBackGrnd.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
jPanelBackGrnd.setToolTipText("Alt-B"); // NOI18N
jPanelBackGrnd.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jPanelBackGrndFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jPanelBackGrndFocusLost(evt);
}
});
jPanelBackGrnd.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
jPanelBackGrndMouseReleased(evt);
}
});
jPanelBackGrnd.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jPanelBackGrndKeyReleased(evt);
}
});
jButton1.setBackground(new java.awt.Color(102, 102, 255));
jButton1.setMnemonic(java.awt.event.KeyEvent.VK_1);
jButton1.setToolTipText("Alt-1"); // NOI18N
jButton1.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jButton1.setContentAreaFilled(false);
jButton1.setDefaultCapable(false);
jButton1.setMargin(new java.awt.Insets(0, 0, 0, 0));
jButton1.setOpaque(true);
jButton1.setPreferredSize(new java.awt.Dimension(14, 14));
jButton1.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jButton1FocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jButton1FocusLost(evt);
}
});
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setBackground(new java.awt.Color(255, 153, 153));
jButton2.setMnemonic(java.awt.event.KeyEvent.VK_2);
jButton2.setToolTipText("Alt-2"); // NOI18N
jButton2.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jButton2.setContentAreaFilled(false);
jButton2.setDefaultCapable(false);
jButton2.setMargin(new java.awt.Insets(0, 0, 0, 0));
jButton2.setOpaque(true);
jButton2.setPreferredSize(new java.awt.Dimension(14, 14));
jButton2.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jButton2FocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jButton2FocusLost(evt);
}
});
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setBackground(new java.awt.Color(51, 255, 51));
jButton3.setMnemonic(java.awt.event.KeyEvent.VK_3);
jButton3.setToolTipText("Alt-3"); // NOI18N
jButton3.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jButton3.setContentAreaFilled(false);
jButton3.setDefaultCapable(false);
jButton3.setMargin(new java.awt.Insets(0, 0, 0, 0));
jButton3.setOpaque(true);
jButton3.setPreferredSize(new java.awt.Dimension(14, 14));
jButton3.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jButton3FocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jButton3FocusLost(evt);
}
});
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton4.setMnemonic(java.awt.event.KeyEvent.VK_4);
jButton4.setToolTipText("Alt-4"); // NOI18N
jButton4.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jButton4.setContentAreaFilled(false);
jButton4.setDefaultCapable(false);
jButton4.setMargin(new java.awt.Insets(0, 0, 0, 0));
jButton4.setOpaque(true);
jButton4.setPreferredSize(new java.awt.Dimension(14, 14));
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jButton4.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jButton4FocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jButton4FocusLost(evt);
}
});
jButton5.setMnemonic(java.awt.event.KeyEvent.VK_5);
jButton5.setToolTipText("Alt-5"); // NOI18N
jButton5.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jButton5.setContentAreaFilled(false);
jButton5.setDefaultCapable(false);
jButton5.setMargin(new java.awt.Insets(0, 0, 0, 0));
jButton5.setOpaque(true);
jButton5.setPreferredSize(new java.awt.Dimension(14, 14));
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
jButton5.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jButton5FocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jButton5FocusLost(evt);
}
});
jButton6.setMnemonic(java.awt.event.KeyEvent.VK_6);
jButton6.setToolTipText("Alt-6"); // NOI18N
jButton6.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jButton6.setContentAreaFilled(false);
jButton6.setDefaultCapable(false);
jButton6.setMargin(new java.awt.Insets(0, 0, 0, 0));
jButton6.setOpaque(true);
jButton6.setPreferredSize(new java.awt.Dimension(14, 14));
jButton6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton6ActionPerformed(evt);
}
});
jButton6.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jButton6FocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jButton6FocusLost(evt);
}
});
jButton7.setMnemonic(java.awt.event.KeyEvent.VK_7);
jButton7.setToolTipText("Alt-7"); // NOI18N
jButton7.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jButton7.setContentAreaFilled(false);
jButton7.setDefaultCapable(false);
jButton7.setMargin(new java.awt.Insets(0, 0, 0, 0));
jButton7.setOpaque(true);
jButton7.setPreferredSize(new java.awt.Dimension(14, 14));
jButton7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton7ActionPerformed(evt);
}
});
jButton7.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jButton7FocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jButton7FocusLost(evt);
}
});
jButton8.setMnemonic(java.awt.event.KeyEvent.VK_8);
jButton8.setToolTipText("Alt-8"); // NOI18N
jButton8.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jButton8.setContentAreaFilled(false);
jButton8.setDefaultCapable(false);
jButton8.setMargin(new java.awt.Insets(0, 0, 0, 0));
jButton8.setOpaque(true);
jButton8.setPreferredSize(new java.awt.Dimension(14, 14));
jButton8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton8ActionPerformed(evt);
}
});
jButton8.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jButton8FocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jButton8FocusLost(evt);
}
});
jButton9.setMnemonic(java.awt.event.KeyEvent.VK_9);
jButton9.setToolTipText("Alt-9"); // NOI18N
jButton9.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jButton9.setContentAreaFilled(false);
jButton9.setDefaultCapable(false);
jButton9.setMargin(new java.awt.Insets(0, 0, 0, 0));
jButton9.setOpaque(true);
jButton9.setPreferredSize(new java.awt.Dimension(14, 14));
jButton9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton9ActionPerformed(evt);
}
});
jButton9.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jButton9FocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jButton9FocusLost(evt);
}
});
jButton10.setMnemonic(java.awt.event.KeyEvent.VK_0);
jButton10.setToolTipText("Alt-0"); // NOI18N
jButton10.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jButton10.setContentAreaFilled(false);
jButton10.setDefaultCapable(false);
jButton10.setMargin(new java.awt.Insets(0, 0, 0, 0));
jButton10.setOpaque(true);
jButton10.setPreferredSize(new java.awt.Dimension(14, 14));
jButton10.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton10ActionPerformed(evt);
}
});
jButton10.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jButton10FocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jButton10FocusLost(evt);
}
});
jButton11.setMnemonic(java.awt.event.KeyEvent.VK_Z);
jButton11.setToolTipText("Alt-Z"); // NOI18N
jButton11.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jButton11.setContentAreaFilled(false);
jButton11.setDefaultCapable(false);
jButton11.setMargin(new java.awt.Insets(0, 0, 0, 0));
jButton11.setOpaque(true);
jButton11.setPreferredSize(new java.awt.Dimension(14, 14));
jButton11.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton11ActionPerformed(evt);
}
});
jButton11.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jButton11FocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jButton11FocusLost(evt);
}
});
javax.swing.GroupLayout jPanelBackGrndLayout = new javax.swing.GroupLayout(jPanelBackGrnd);
jPanelBackGrnd.setLayout(jPanelBackGrndLayout);
jPanelBackGrndLayout.setHorizontalGroup(
jPanelBackGrndLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelBackGrndLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelBackGrndLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelBackGrndLayout.createSequentialGroup()
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelBackGrndLayout.createSequentialGroup()
.addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelBackGrndLayout.setVerticalGroup(
jPanelBackGrndLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelBackGrndLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelBackGrndLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(11, 11, 11)
.addGroup(jPanelBackGrndLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanelColoursLayout = new javax.swing.GroupLayout(jPanelColours);
jPanelColours.setLayout(jPanelColoursLayout);
jPanelColoursLayout.setHorizontalGroup(
jPanelColoursLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelColoursLayout.createSequentialGroup()
.addGap(2, 2, 2)
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanelBackGrnd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelColoursLayout.setVerticalGroup(
jPanelColoursLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanelBackGrnd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
jPanelPrint.setBorder(javax.swing.BorderFactory.createTitledBorder(null, " Diagram printing: ", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11), new java.awt.Color(0, 0, 255))); // NOI18N
jCheckBoxPrintColour.setMnemonic(java.awt.event.KeyEvent.VK_T);
jCheckBoxPrintColour.setText("Print colours"); // NOI18N
jCheckPrintHeader.setMnemonic(java.awt.event.KeyEvent.VK_D);
jCheckPrintHeader.setText("header with file name & date"); // NOI18N
javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9);
jPanel9.setLayout(jPanel9Layout);
jPanel9Layout.setHorizontalGroup(
jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel9Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jCheckBoxPrintColour)
.addComponent(jCheckPrintHeader))
.addContainerGap(48, Short.MAX_VALUE))
);
jPanel9Layout.setVerticalGroup(
jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel9Layout.createSequentialGroup()
.addComponent(jCheckBoxPrintColour)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jCheckPrintHeader)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jLabel4.setText("Line Thickness"); // NOI18N
jLabel_PenPrint.setText("1"); // NOI18N
jScrollBar_PenPrint.setMaximum(50);
jScrollBar_PenPrint.setMinimum(10);
jScrollBar_PenPrint.setOrientation(javax.swing.JScrollBar.HORIZONTAL);
jScrollBar_PenPrint.setUnitIncrement(5);
jScrollBar_PenPrint.setVisibleAmount(0);
jScrollBar_PenPrint.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jScrollBar_PenPrint.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jScrollBar_PenPrintFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jScrollBar_PenPrintFocusLost(evt);
}
});
jScrollBar_PenPrint.addAdjustmentListener(new java.awt.event.AdjustmentListener() {
public void adjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {
jScrollBar_PenPrintAdjustmentValueChanged(evt);
}
});
javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
jPanel8.setLayout(jPanel8Layout);
jPanel8Layout.setHorizontalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(jScrollBar_PenPrint, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel8Layout.createSequentialGroup()
.addComponent(jLabel4)
.addGap(6, 6, 6)
.addComponent(jLabel_PenPrint, javax.swing.GroupLayout.DEFAULT_SIZE, 45, Short.MAX_VALUE)))
.addGap(31, 31, 31))
);
jPanel8Layout.setVerticalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(jLabel_PenPrint))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollBar_PenPrint, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(22, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanelPrintLayout = new javax.swing.GroupLayout(jPanelPrint);
jPanelPrint.setLayout(jPanelPrintLayout);
jPanelPrintLayout.setHorizontalGroup(
jPanelPrintLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelPrintLayout.createSequentialGroup()
.addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelPrintLayout.setVerticalGroup(
jPanelPrintLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel_Fonts, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanelColours, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanelPrint, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel_Fonts, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanelColours, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanelPrint, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
//<editor-fold defaultstate="collapsed" desc="Events">
private void jButton_OKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_OKActionPerformed
diagrPaintUtil.textWithFonts = jRadioButton_FontPrinter.isSelected();
diagrPaintUtil.fontFamily = jCombo_FontFamily.getSelectedIndex();
diagrPaintUtil.fontStyle = jCombo_FontStyle.getSelectedIndex();
int i;
try{i = Integer.parseInt(jText_FontSize.getText());} catch (NumberFormatException ex) {System.err.println("Error reading integer from text \""+jText_FontSize.getText()+"\""); i=10;}
diagrPaintUtil.fontSize = Math.max(1, Math.min(i,72));
diagrPaintUtil.penThickness = (float)jScrollBar_Pen.getValue()/10f;
diagrPaintUtil.antiAliasing = jComboAntiAlias.getSelectedIndex();
diagrPaintUtil.antiAliasingText = jComboAntiAliasT.getSelectedIndex();
diagrPaintUtil.fixedSize = jCheckBox_FixedSize.isSelected();
diagrPaintUtil.keepAspectRatio = jCheckBox_AspectRatio.isSelected();
diagrPaintUtil.useBackgrndColour = jCheckBackgr.isSelected();
diagrPaintUtil.backgrnd = L_backgrnd;
diagrPaintUtil.colours[0]=jButton1.getBackground();
diagrPaintUtil.colours[1]=jButton2.getBackground();
diagrPaintUtil.colours[2]=jButton3.getBackground();
diagrPaintUtil.colours[3]=jButton4.getBackground();
diagrPaintUtil.colours[4]=jButton5.getBackground();
diagrPaintUtil.colours[5]=jButton6.getBackground();
diagrPaintUtil.colours[6]=jButton7.getBackground();
diagrPaintUtil.colours[7]=jButton8.getBackground();
diagrPaintUtil.colours[8]=jButton9.getBackground();
diagrPaintUtil.colours[9]=jButton10.getBackground();
diagrPaintUtil.colours[10]=jButton11.getBackground();
diagrPaintUtil.colourType = 0;
if (jRadioButtonBW.isSelected()) {
diagrPaintUtil.colourType = 1;} else if (jRadioButtonWB.isSelected()) {
diagrPaintUtil.colourType = 2;}
diagrPaintUtil.printColour = jCheckBoxPrintColour.isSelected();
diagrPaintUtil.printHeader = jCheckPrintHeader.isSelected();
diagrPaintUtil.printPenThickness = (float)jScrollBar_PenPrint.getValue()/10f;
closeWindow();
}//GEN-LAST:event_jButton_OKActionPerformed
private void jButton_CancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_CancelActionPerformed
closeWindow();
}//GEN-LAST:event_jButton_CancelActionPerformed
private void jCheckBox_AspectRatioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox_AspectRatioActionPerformed
if (jCheckBox_AspectRatio.isSelected()) {
jCheckBox_FixedSize.setVisible(false);} else {jCheckBox_FixedSize.setVisible(true);}
}//GEN-LAST:event_jCheckBox_AspectRatioActionPerformed
private void jScrollBar_PenFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jScrollBar_PenFocusGained
jScrollBar_Pen.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0,0,0)));
}//GEN-LAST:event_jScrollBar_PenFocusGained
private void jScrollBar_PenFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jScrollBar_PenFocusLost
jScrollBar_Pen.setBorder(scrollBorder);
}//GEN-LAST:event_jScrollBar_PenFocusLost
private void jScrollBar_PenAdjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {//GEN-FIRST:event_jScrollBar_PenAdjustmentValueChanged
jLabel_PenThickness.setText(String.valueOf((float)jScrollBar_Pen.getValue()/10f));
}//GEN-LAST:event_jScrollBar_PenAdjustmentValueChanged
private void jRadioButton_FontNoneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton_FontNoneActionPerformed
if (jRadioButton_FontNone.isSelected()) {
jCombo_FontFamily.setVisible(false);
jCombo_FontStyle.setVisible(false);
jText_FontSize.setVisible(false);
jLabelAntiAT.setVisible(false);
jComboAntiAliasT.setVisible(false);} else {
jCombo_FontFamily.setVisible(true);
jCombo_FontStyle.setVisible(true);
jText_FontSize.setVisible(true);
jLabelAntiAT.setVisible(true);
jComboAntiAliasT.setVisible(true);}
}//GEN-LAST:event_jRadioButton_FontNoneActionPerformed
private void jRadioButton_FontPrinterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton_FontPrinterActionPerformed
if (jRadioButton_FontPrinter.isSelected()) {
jCombo_FontFamily.setVisible(true);
jCombo_FontStyle.setVisible(true);
jText_FontSize.setVisible(true);
jLabelAntiAT.setVisible(true);
jComboAntiAliasT.setVisible(true);} else {
jCombo_FontFamily.setVisible(false);
jCombo_FontStyle.setVisible(false);
jText_FontSize.setVisible(false);
jLabelAntiAT.setVisible(false);
jComboAntiAliasT.setVisible(false);}
}//GEN-LAST:event_jRadioButton_FontPrinterActionPerformed
private void jText_FontSizeKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jText_FontSizeKeyReleased
int i;
try{i = Integer.parseInt(jText_FontSize.getText());} catch (NumberFormatException ex) {i=0;}
i = Math.max(0, Math.min(i,72));
jText_FontSize.setText(String.valueOf(i));
}//GEN-LAST:event_jText_FontSizeKeyReleased
private void jText_FontSizeKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jText_FontSizeKeyTyped
if (!Character.isDigit(evt.getKeyChar())) {evt.consume();}
}//GEN-LAST:event_jText_FontSizeKeyTyped
private void jRadioButtonColourActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonColourActionPerformed
jCheckBackgr.setVisible(true);
jButton_ResetColours.setVisible(true);
jPanelBackGrnd.setVisible(true);
}//GEN-LAST:event_jRadioButtonColourActionPerformed
private void jRadioButtonBWActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonBWActionPerformed
jCheckBackgr.setVisible(false);
jButton_ResetColours.setVisible(false);
jPanelBackGrnd.setVisible(false);
}//GEN-LAST:event_jRadioButtonBWActionPerformed
private void jRadioButtonWBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonWBActionPerformed
jCheckBackgr.setVisible(false);
jButton_ResetColours.setVisible(false);
jPanelBackGrnd.setVisible(false);
}//GEN-LAST:event_jRadioButtonWBActionPerformed
private void jButton_ResetColoursActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_ResetColoursActionPerformed
L_backgrnd = new java.awt.Color(255,255,255);
jPanelBackGrnd.setBackground(L_backgrnd);
if (jCheckBackgr.isSelected()) {
jPanelBackGrnd.setFocusable(true);
} else {jPanelBackGrnd.setFocusable(false);}
L_colours = resetColours(L_colours);
jButton1.setBackground(L_colours[0]);
jButton2.setBackground(L_colours[1]);
jButton3.setBackground(L_colours[2]);
jButton4.setBackground(L_colours[3]);
jButton5.setBackground(L_colours[4]);
jButton6.setBackground(L_colours[5]);
jButton7.setBackground(L_colours[6]);
jButton8.setBackground(L_colours[7]);
jButton9.setBackground(L_colours[8]);
jButton10.setBackground(L_colours[9]);
jButton11.setBackground(L_colours[10]);
}//GEN-LAST:event_jButton_ResetColoursActionPerformed
private void jCheckBackgrActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBackgrActionPerformed
if (jCheckBackgr.isSelected()) {
jPanelBackGrnd.setFocusable(true);
jPanelBackGrnd.setBorder(
javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
jPanelBackGrnd.setBackground(L_backgrnd);
jPanelBackGrnd.setToolTipText("Alt-B");
} else {
jPanelBackGrnd.setBorder(null);
jPanelBackGrnd.setBackground(java.awt.Color.white);
jPanelBackGrnd.setToolTipText(null);
jPanelBackGrnd.setFocusable(false);
}
}//GEN-LAST:event_jCheckBackgrActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
changeColour(jButton1);
L_colours[0] = jButton1.getBackground();
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton1FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jButton1FocusGained
jButton1.setBorder(buttonBorderSelected);
}//GEN-LAST:event_jButton1FocusGained
private void jButton1FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jButton1FocusLost
jButton1.setBorder(buttonBorder);
}//GEN-LAST:event_jButton1FocusLost
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
changeColour(jButton2);
L_colours[1] = jButton2.getBackground();
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton2FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jButton2FocusGained
jButton2.setBorder(buttonBorderSelected);
}//GEN-LAST:event_jButton2FocusGained
private void jButton2FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jButton2FocusLost
jButton2.setBorder(buttonBorder);
}//GEN-LAST:event_jButton2FocusLost
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
changeColour(jButton3);
L_colours[2] = jButton3.getBackground();
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton3FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jButton3FocusGained
jButton3.setBorder(buttonBorderSelected);
}//GEN-LAST:event_jButton3FocusGained
private void jButton3FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jButton3FocusLost
jButton3.setBorder(buttonBorder);
}//GEN-LAST:event_jButton3FocusLost
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
changeColour(jButton4);
L_colours[3] = jButton4.getBackground();
}//GEN-LAST:event_jButton4ActionPerformed
private void jButton4FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jButton4FocusGained
jButton4.setBorder(buttonBorderSelected);
}//GEN-LAST:event_jButton4FocusGained
private void jButton4FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jButton4FocusLost
jButton4.setBorder(buttonBorder);
}//GEN-LAST:event_jButton4FocusLost
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
changeColour(jButton5);
L_colours[4] = jButton5.getBackground();
}//GEN-LAST:event_jButton5ActionPerformed
private void jButton5FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jButton5FocusGained
jButton5.setBorder(buttonBorderSelected);
}//GEN-LAST:event_jButton5FocusGained
private void jButton5FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jButton5FocusLost
jButton5.setBorder(buttonBorder);
}//GEN-LAST:event_jButton5FocusLost
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
changeColour(jButton6);
L_colours[5] = jButton6.getBackground();
}//GEN-LAST:event_jButton6ActionPerformed
private void jButton6FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jButton6FocusGained
jButton6.setBorder(buttonBorderSelected);
}//GEN-LAST:event_jButton6FocusGained
private void jButton6FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jButton6FocusLost
jButton6.setBorder(buttonBorder);
}//GEN-LAST:event_jButton6FocusLost
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
changeColour(jButton7);
L_colours[6] = jButton7.getBackground();
}//GEN-LAST:event_jButton7ActionPerformed
private void jButton7FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jButton7FocusGained
jButton7.setBorder(buttonBorderSelected);
}//GEN-LAST:event_jButton7FocusGained
private void jButton7FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jButton7FocusLost
jButton7.setBorder(buttonBorder);
}//GEN-LAST:event_jButton7FocusLost
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
changeColour(jButton8);
L_colours[7] = jButton8.getBackground();
}//GEN-LAST:event_jButton8ActionPerformed
private void jButton8FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jButton8FocusGained
jButton8.setBorder(buttonBorderSelected);
}//GEN-LAST:event_jButton8FocusGained
private void jButton8FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jButton8FocusLost
jButton8.setBorder(buttonBorder);
}//GEN-LAST:event_jButton8FocusLost
private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed
changeColour(jButton9);
L_colours[8] = jButton9.getBackground();
}//GEN-LAST:event_jButton9ActionPerformed
private void jButton9FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jButton9FocusGained
jButton9.setBorder(buttonBorderSelected);
}//GEN-LAST:event_jButton9FocusGained
private void jButton9FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jButton9FocusLost
jButton9.setBorder(buttonBorder);
}//GEN-LAST:event_jButton9FocusLost
private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed
changeColour(jButton10);
L_colours[9] = jButton10.getBackground();
}//GEN-LAST:event_jButton10ActionPerformed
private void jButton10FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jButton10FocusGained
jButton10.setBorder(buttonBorderSelected);
}//GEN-LAST:event_jButton10FocusGained
private void jButton10FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jButton10FocusLost
jButton10.setBorder(buttonBorder);
}//GEN-LAST:event_jButton10FocusLost
private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton11ActionPerformed
changeColour(jButton11);
L_colours[10] = jButton11.getBackground();
}//GEN-LAST:event_jButton11ActionPerformed
private void jButton11FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jButton11FocusGained
jButton11.setBorder(buttonBorderSelected);
}//GEN-LAST:event_jButton11FocusGained
private void jButton11FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jButton11FocusLost
jButton11.setBorder(buttonBorder);
}//GEN-LAST:event_jButton11FocusLost
private void jPanelBackGrndFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jPanelBackGrndFocusGained
if (!jCheckBackgr.isSelected()) {return;}
jPanelBackGrnd.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED,
new java.awt.Color(102,102,102),
new java.awt.Color(255,255,255),
new java.awt.Color(102,102,102),
new java.awt.Color(0,0,0)));
}//GEN-LAST:event_jPanelBackGrndFocusGained
private void jPanelBackGrndFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jPanelBackGrndFocusLost
if (!jCheckBackgr.isSelected()) {return;}
jPanelBackGrnd.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
}//GEN-LAST:event_jPanelBackGrndFocusLost
private void jPanelBackGrndKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPanelBackGrndKeyReleased
if (!jCheckBackgr.isSelected() ||
evt.getKeyCode() == java.awt.event.KeyEvent.VK_ESCAPE ||
evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER ||
evt.isActionKey()) {
evt.consume(); return;}
changeBackgroundColour();
}//GEN-LAST:event_jPanelBackGrndKeyReleased
private void jPanelBackGrndMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanelBackGrndMouseReleased
if (jCheckBackgr.isSelected()) {
changeBackgroundColour();
}
evt.consume();
}//GEN-LAST:event_jPanelBackGrndMouseReleased
private void jScrollBar_PenPrintFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jScrollBar_PenPrintFocusGained
jScrollBar_PenPrint.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0,0,0)));
}//GEN-LAST:event_jScrollBar_PenPrintFocusGained
private void jScrollBar_PenPrintFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jScrollBar_PenPrintFocusLost
jScrollBar_PenPrint.setBorder(scrollBorder);
}//GEN-LAST:event_jScrollBar_PenPrintFocusLost
private void jScrollBar_PenPrintAdjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {//GEN-FIRST:event_jScrollBar_PenPrintAdjustmentValueChanged
jLabel_PenPrint.setText(String.valueOf((float)jScrollBar_PenPrint.getValue()/10f));
}//GEN-LAST:event_jScrollBar_PenPrintAdjustmentValueChanged
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
closeWindow();
}//GEN-LAST:event_formWindowClosing
private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
if(windowSize != null) {
int w = windowSize.width;
int h = windowSize.height;
if(this.getHeight()<h){this.setSize(this.getWidth(), h);}
if(this.getWidth()<w){this.setSize(w,this.getHeight());}
}
}//GEN-LAST:event_formComponentResized
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Methods">
private void closeWindow() {
finished = true;
this.notify_All();
this.dispose();
} // closeWindow
private synchronized void notify_All() {notifyAll();}
/** this method will wait for this dialog frame to be closed */
public synchronized void waitFor() {
while(!finished) {
try {wait();} catch (InterruptedException ex) {}
} // while
} // waitFor()
public java.awt.Color[] resetColours (java.awt.Color c[])
{c[0] = new java.awt.Color(0,0,0); //black
c[1] = new java.awt.Color(255,35,35); //red
c[2] = new java.awt.Color(149,67,0); //vermilion
c[3] = new java.awt.Color(47,47,255); //light blue
c[4] = new java.awt.Color(0,151,0); //green
c[5] = new java.awt.Color(200,140,0); //orange
c[6] = new java.awt.Color(255,0,255); //magenta
c[7] = new java.awt.Color(0,0,128); //blue
c[8] = new java.awt.Color(128,128,128);//gray
c[9] = new java.awt.Color(0,166,255); //sky blue
c[10] = new java.awt.Color(128,0,255); //violet
return c;}
private void changeColour(javax.swing.JButton jB) {
setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
Thread w = new Thread() {@Override public void run(){
try{Thread.sleep(10000);} //show the "wait" cursor for 10 sec
catch (InterruptedException e) {}
OptionsDiagram.this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
}};//new Thread
w.start();
java.awt.Color newColour = javax.swing.JColorChooser.showDialog(
jB.getRootPane(),
"Select a colour",
jB.getBackground());
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
if(newColour != null) {
if(pc.dbg) {System.out.println(
"new color = "+newColour.getRed()+"-"+newColour.getGreen()+"-"+newColour.getBlue()+
", background = "+L_backgrnd.getRed()+"-"+L_backgrnd.getGreen()+"-"+L_backgrnd.getBlue());}
if(jCheckBackgr.isSelected()) {
if(MainFrame.twoColoursEqual(newColour, L_backgrnd)) {
javax.swing.JOptionPane.showMessageDialog(this,
"The selected colour is too close"+nl+
"to the background colour."+nl+nl+
"Your colour selection is discarded.",
pc.progName, javax.swing.JOptionPane.WARNING_MESSAGE);
return;
} // different from background?
} // if jCheckBackgr.isSelected()
jB.setBackground(newColour);
} // if newColour != null
} // changeColour
private void changeBackgroundColour() {
java.awt.Color newColour = javax.swing.JColorChooser.showDialog(
jPanelBackGrnd.getRootPane(),
"Select the background colour",
jPanelBackGrnd.getBackground());
if(newColour != null) {
for(int i=0; i < DiagrPaintUtility.MAX_COLOURS; i++) {
if(MainFrame.twoColoursEqual(L_colours[i], newColour)) {
javax.swing.JOptionPane.showMessageDialog(this,
"The selected background colour is too close"+nl+
"to one of the other colours."+nl+nl+
"Your background colour selection is discarded.",
pc.progName, javax.swing.JOptionPane.WARNING_MESSAGE);
return;
}
} // for i
L_backgrnd = newColour;
jPanelBackGrnd.setBackground(L_backgrnd);
} // if newColour !=null
} // changeBackgroundColour
//</editor-fold>
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup_Colr;
private javax.swing.ButtonGroup buttonGroup_FontPrinter;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton10;
private javax.swing.JButton jButton11;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JButton jButton7;
private javax.swing.JButton jButton8;
private javax.swing.JButton jButton9;
private javax.swing.JButton jButton_Cancel;
private javax.swing.JButton jButton_OK;
private javax.swing.JButton jButton_ResetColours;
private javax.swing.JCheckBox jCheckBackgr;
private javax.swing.JCheckBox jCheckBoxPrintColour;
private javax.swing.JCheckBox jCheckBox_AspectRatio;
private javax.swing.JCheckBox jCheckBox_FixedSize;
private javax.swing.JCheckBox jCheckPrintHeader;
private javax.swing.JComboBox jComboAntiAlias;
private javax.swing.JComboBox jComboAntiAliasT;
private javax.swing.JComboBox jCombo_FontFamily;
private javax.swing.JComboBox jCombo_FontStyle;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabelAntiA1;
private javax.swing.JLabel jLabelAntiAT;
private javax.swing.JLabel jLabel_PenPrint;
private javax.swing.JLabel jLabel_PenThickness;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel8;
private javax.swing.JPanel jPanel9;
private javax.swing.JPanel jPanelBackGrnd;
private javax.swing.JPanel jPanelColours;
private javax.swing.JPanel jPanelPrint;
private javax.swing.JPanel jPanelScreenDisp;
private javax.swing.JPanel jPanel_Fonts;
private javax.swing.JRadioButton jRadioButtonBW;
private javax.swing.JRadioButton jRadioButtonColour;
private javax.swing.JRadioButton jRadioButtonWB;
private javax.swing.JRadioButton jRadioButton_FontNone;
private javax.swing.JRadioButton jRadioButton_FontPrinter;
private javax.swing.JScrollBar jScrollBar_Pen;
private javax.swing.JScrollBar jScrollBar_PenPrint;
private javax.swing.JTextField jText_FontSize;
// End of variables declaration//GEN-END:variables
}
| 91,232 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
DiagrWSize.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Spana/src/spana/DiagrWSize.java | package spana;
/** A dialog to change the size of the parent "Disp" window.
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class DiagrWSize extends javax.swing.JDialog {
private boolean finished = false;
private DiagrWSize frame = null;
private spana.Disp d = null;
private java.awt.Dimension windowSize;
private final int h0; //original height
private final int w0; //original width
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
//<editor-fold defaultstate="collapsed" desc="Constructor">
public DiagrWSize(java.awt.Frame parent, boolean modal, spana.Disp diagr0) {
super(parent, modal);
initComponents();
d = diagr0;
finished = false;
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
//--- Close window on ESC key
javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE");
javax.swing.Action escAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
closeWindow();
}};
getRootPane().getActionMap().put("ESCAPE", escAction);
//--- Alt-Q quit
javax.swing.KeyStroke altQKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altQKeyStroke,"ALT_Q");
getRootPane().getActionMap().put("ALT_Q", escAction);
//--- Alt-X eXit
javax.swing.KeyStroke altXKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altXKeyStroke,"ALT_X");
javax.swing.Action altXAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jButtonOK.doClick();
}};
getRootPane().getActionMap().put("ALT_X", altXAction);
//--- Title, etc
//getContentPane().setBackground(new java.awt.Color(255, 255, 153));
this.setTitle(" Diagram size");
//---- data
jLabelName.setText("Diagram: \""+d.diagrName+"\"");
h0 = Math.round((float)d.diagrSize.getHeight());
jTextFieldH.setText(String.valueOf(h0).trim());
w0 = Math.round((float)d.diagrSize.getWidth());
jTextFieldW.setText(String.valueOf(w0).trim());
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
frame = DiagrWSize.this;
windowSize = frame.getSize();
// Center window on the parent
int left = Math.max(0,(d.getX() + (d.getWidth()/2) - frame.getWidth()/2));
int top = Math.max(0,(d.getY()+(d.getHeight()/2)-frame.getHeight()/2));
frame.setLocation(left, top);
} }); //invokeLater(Runnable)
} //constructor
//</editor-fold>
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jButtonOK = new javax.swing.JButton();
jLabelName = new javax.swing.JLabel();
jLabelW = new javax.swing.JLabel();
jTextFieldW = new javax.swing.JTextField();
jLabelH = new javax.swing.JLabel();
jTextFieldH = new javax.swing.JTextField();
jButtonCancel = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jButtonOK.setMnemonic('O');
jButtonOK.setText("<html><u>O</u>K</html>");
jButtonOK.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonOK.setMargin(new java.awt.Insets(2, 4, 2, 4));
jButtonOK.setMinimumSize(new java.awt.Dimension(47, 23));
jButtonOK.setPreferredSize(new java.awt.Dimension(47, 23));
jButtonOK.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonOKActionPerformed(evt);
}
});
jLabelName.setText("Diagram: \"hello\"");
jLabelW.setLabelFor(jTextFieldW);
jLabelW.setText("width:");
jTextFieldW.setText("1000");
jTextFieldW.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextFieldWFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jTextFieldWFocusLost(evt);
}
});
jTextFieldW.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextFieldWKeyTyped(evt);
}
});
jLabelH.setLabelFor(jTextFieldH);
jLabelH.setText("height:");
jTextFieldH.setText("1000");
jTextFieldH.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextFieldHFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jTextFieldHFocusLost(evt);
}
});
jTextFieldH.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextFieldHKeyTyped(evt);
}
});
jButtonCancel.setMnemonic('C');
jButtonCancel.setText("<html><u>C</u>ancel</html>");
jButtonCancel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonCancel.setMargin(new java.awt.Insets(2, 4, 2, 4));
jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonCancelActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelName)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabelH)
.addComponent(jLabelW))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextFieldH, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextFieldW, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addComponent(jButtonOK, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButtonCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(48, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jLabelName)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextFieldW, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelW))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextFieldH, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelH))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonOK, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButtonCancel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(18, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
//<editor-fold defaultstate="collapsed" desc="Events">
private void jButtonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOKActionPerformed
int h;
try {h = Integer.parseInt(jTextFieldH.getText());}
catch (NumberFormatException ex) {
javax.swing.JOptionPane.showMessageDialog(this, "Error: "+ex.toString(),
"Diagram Size - Error", javax.swing.JOptionPane.ERROR_MESSAGE);
h = h0;}
int w;
try {w = Integer.parseInt(jTextFieldW.getText());}
catch (NumberFormatException ex) {
javax.swing.JOptionPane.showMessageDialog(this, "Error: "+ex.toString(),
"Diagram Size - Error", javax.swing.JOptionPane.ERROR_MESSAGE);
w = w0;}
d.diagrSize.setSize(w, h);
closeWindow();
}//GEN-LAST:event_jButtonOKActionPerformed
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
closeWindow();
}//GEN-LAST:event_formWindowClosing
private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
if(windowSize != null) {
int w = windowSize.width;
int h = windowSize.height;
if(this.getHeight()<h){this.setSize(this.getWidth(), h);}
if(this.getWidth()<w){this.setSize(w,this.getHeight());}
}
}//GEN-LAST:event_formComponentResized
private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelActionPerformed
closeWindow();
}//GEN-LAST:event_jButtonCancelActionPerformed
private void jTextFieldWKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldWKeyTyped
if(!Character.isDigit(evt.getKeyChar())) {evt.consume();}
}//GEN-LAST:event_jTextFieldWKeyTyped
private void jTextFieldHKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldHKeyTyped
if(!Character.isDigit(evt.getKeyChar())) {evt.consume();}
}//GEN-LAST:event_jTextFieldHKeyTyped
private void jTextFieldWFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldWFocusLost
int w;
try {
w = Integer.parseInt(jTextFieldW.getText());
jTextFieldW.setText(String.valueOf(w).trim());
} //try
catch (NumberFormatException nfe) {
javax.swing.JOptionPane.showMessageDialog
(this,"Wrong numeric format"+nl+nl+
"Please enter an integer.",
"Numeric Format Error", javax.swing.JOptionPane.WARNING_MESSAGE);
w = w0;
jTextFieldW.setText(String.valueOf(w));
jTextFieldW.requestFocus();
} //catch
}//GEN-LAST:event_jTextFieldWFocusLost
private void jTextFieldHFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldHFocusLost
int h;
try {
h = Integer.parseInt(jTextFieldH.getText());
jTextFieldH.setText(String.valueOf(h).trim());
} //try
catch (NumberFormatException nfe) {
javax.swing.JOptionPane.showMessageDialog
(this,"Wrong numeric format"+nl+nl+
"Please enter an integer.",
"Numeric Format Error", javax.swing.JOptionPane.WARNING_MESSAGE);
h = h0;
jTextFieldH.setText(String.valueOf(h));
jTextFieldH.requestFocus();
} //catch
}//GEN-LAST:event_jTextFieldHFocusLost
private void jTextFieldWFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldWFocusGained
jTextFieldW.selectAll();
}//GEN-LAST:event_jTextFieldWFocusGained
private void jTextFieldHFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldHFocusGained
jTextFieldH.selectAll();
}//GEN-LAST:event_jTextFieldHFocusGained
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Methods">
private void closeWindow() {
finished = true;
this.notify_All();
this.dispose();
} // closeWindow()
private synchronized void notify_All() {notifyAll();}
/** this method will wait for this dialog frame to be closed */
public synchronized void waitFor() {
while(!finished) {
try {wait();} catch (InterruptedException ex) {}
} // while
} // waitFor()
//</editor-fold>
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButtonCancel;
private javax.swing.JButton jButtonOK;
private javax.swing.JLabel jLabelH;
private javax.swing.JLabel jLabelName;
private javax.swing.JLabel jLabelW;
private javax.swing.JTextField jTextFieldH;
private javax.swing.JTextField jTextFieldW;
// End of variables declaration//GEN-END:variables
}
| 15,686 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
MainFrame.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Spana/src/spana/MainFrame.java | package spana;
import java.util.Arrays;
import lib.common.MsgExceptn;
import lib.common.Util;
import lib.huvud.Div;
import lib.huvud.ProgramConf;
import lib.huvud.RedirectedFrame;
import lib.huvud.SortedProperties;
import lib.kemi.chem.Chem;
import lib.kemi.graph_lib.DiagrPaintUtility;
/** The main frame.
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class MainFrame extends javax.swing.JFrame {
// Note: for java 1.6 jComboBox must not have type,
// for java 1.7 jComboBox must be <String>
static final String VERS = "2020-June-08";
/** all program instances will use the same redirected frame */
private static RedirectedFrame msgFrame = null;
/** Because the program checks for other instances and exits if there is
* another instance, "spf" is a reference to the only instance of
* this class */
private static MainFrame spf = null;
//<editor-fold defaultstate="collapsed" desc="Fields">
private final ProgramDataSpana pd = new ProgramDataSpana();
private final ProgramConf pc;
private DiagrPaintUtility diagrPaintUtil = null;
private HelpAbout helpAboutFrame = null;
static boolean windows = false;
private static String windir = null;
private static java.awt.Dimension msgFrameSize = new java.awt.Dimension(500,400);
private static java.awt.Point locationMsgFrame = new java.awt.Point(80,30);
private static java.awt.Point locationFrame = new java.awt.Point(-1000,-1000);
protected static java.awt.Point locationSDFrame = new java.awt.Point(-1000,-1000);
static final java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();;
private java.awt.Dimension windowSize;
private final java.awt.Dimension ZERO = new java.awt.Dimension(0,0);
private final java.awt.Dimension PANELsize = new java.awt.Dimension(345,170);
static java.awt.Dimension dispSize = new java.awt.Dimension(400,350);
static java.awt.Point dispLocation = new java.awt.Point(60,30);
static String txtEditor;
static String pathSedPredom;
static String createDataFileProg;
/** used to avoid duplicate entries in the list of data files */
private final java.util.ArrayList<String> dataFileArrList =
new java.util.ArrayList<String>();
/** used to show instances of Disp corresponding to the
* entries in the list of plot files */
private final java.util.ArrayList<spana.Disp> diagrArrList =
new java.util.ArrayList<spana.Disp>();
/** do not fire an event when adding an item to the combo box
* or when setting the selected item within the program */
private boolean jComboBox_Plt_doNothing = false;
static java.io.File fileIni;
private static final String FileINI_NAME = ".Spana.ini";
/** <tt>laf</tt> = LookAndFeel: the look-and-feel to be used (read from the ini-file).
* If <tt>laf</tt> = 2 then the <i>C<rossPlatform</i> look-and-feel will be used;
* else if <tt>laf</tt> = 1 the <i>System</i> look-and-feel will be used.
* Else (<tt>laf</tt> = 0, default) then the look-and-feel will be <i>System</i>
* for Windows and <i>CrossPlatform</i> on Linux and Mac OS.
* Default at program start = 0 **/
private int laf = 0;
private ModifyChemSyst modifyDiagramWindow = null;
// variables used when dealing with command-line args.
private boolean doNotExit = false;
private boolean waitingForPrinter = false;
public static final double Faraday = 96485.309;
public static final double Rgas = 8.31451;
/** The maximum number of calculation steps along an axis */
final static int MXSTP = 1000;
/** The minimum number of calculation steps along the X-axis */
final static int MNSTP = 4;
/** The default number of calculation steps along an axis */
final static int NSTEPS_DEF = 50;
/** New-line character(s) to substitute "\n".<br>
* It is needed when a String is created first, including new-lines,
* and the String is then printed. For example
* <pre>String t = "1st line\n2nd line";
*System.out.println(t);</pre>will add a carriage return character
* between the two lines, which on Windows system might be
* unsatisfactory. Use instead:
* <pre>String t = "1st line" + nl + "2nd line";
*System.out.println(t);</pre> */
private static final String nl = System.getProperty("line.separator");
private static final String SLASH = java.io.File.separator;
public static final String[] FORMAT_NAMES;
public static final String LINE = "- - - - - - - - - - - - - - - - - - - - - - - - - - -";
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="static initializer">
static { // static initializer
// Get list of unique supported write formats, e.g. png jpeg jpg
String[] names = javax.imageio.ImageIO.getWriterFormatNames();
if(names.length >0) {
java.util.Set<String> set = new java.util.TreeSet<String>();
for (String name : names) {set.add(name.toLowerCase());}
FORMAT_NAMES = (String[])set.toArray(new String[0]);
} else {FORMAT_NAMES = new String[]{"error"};}
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="Constructor">
/**
* Creates new form MainFrame
* @param pc0
* @param msgFrame0 */
public MainFrame(ProgramConf pc0, RedirectedFrame msgFrame0) {
initComponents();
pc = pc0;
msgFrame = msgFrame0;
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
//--- ESC key: with a menu bar, the behaviour of ESC is too complex
//--- Alt-Q quit
javax.swing.KeyStroke altQKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altQKeyStroke,"ALT_Q");
javax.swing.Action altQAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
end_program();
}};
getRootPane().getActionMap().put("ALT_Q", altQAction);
//--- F1 for help
javax.swing.KeyStroke f1KeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_F1,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(f1KeyStroke,"F1");
javax.swing.Action f1Action = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jMenu_Help_Contents.doClick();
}};
getRootPane().getActionMap().put("F1", f1Action);
//---- Icon
String iconName = "images/Spana_icon_32x32.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
java.awt.Image icon;
if (imgURL != null) {
icon = new javax.swing.ImageIcon(imgURL).getImage();
this.setIconImage(icon);
//com.apple.eawt.Application.getApplication().setDockIconImage(new javax.swing.ImageIcon("Football.png").getImage());
if(System.getProperty("os.name").startsWith("Mac OS")) {
try {
Class<?> c = Class.forName("com.apple.eawt.Application");
//Class params[] = new Class[] {java.awt.Image.class};
java.lang.reflect.Method m =
c.getDeclaredMethod("setDockIconImage",new Class[] { java.awt.Image.class });
Object i = c.newInstance();
java.net.URL iconURL = this.getClass().getResource("images/Spana_icon_48x48.gif");
if (iconURL != null) {icon = new javax.swing.ImageIcon(iconURL).getImage();}
Object paramsObj[] = new Object[]{icon};
m.invoke(i, paramsObj);
} catch (Exception e) {System.out.println("Error: "+e.getMessage());}
}
} else {
System.out.println("Error: Could not load image = \""+iconName+"\"");
}
//---- Set up Drag-and-Drop
jPanel1.setTransferHandler(tHandler);
jMenuBar.setTransferHandler(tHandler);
jLabelBackgrd.setTransferHandler(tHandler);
//---- Title, menus, etc
this.setTitle(pc.progName+" diagram");
getContentPane().setBackground(java.awt.Color.white);
jPanel1.setBackground(java.awt.Color.white);
jMenuBar.add(javax.swing.Box.createHorizontalGlue(),3); //move "Help" menu to the right
jMenu_Data_SaveAs.setEnabled(false);
jMenu_Plot_SaveAs.setEnabled(false);
//---- Fix the panel and combo boxes
jLabel_Dat.setVisible(false);
jComboBox_Dat.setVisible(false);
jLabel_Plt.setVisible(false);
jComboBox_Plt.setVisible(false);
jLabelBackgrd.setVisible(true);
//---- initial size
jLabelBackgrd.setSize(PANELsize);
jLabelBackgrd.setVisible(true);
jPanel1.setSize(ZERO);
jPanel1.setVisible(false);
pack();
//---- initial location
locationFrame.x = Math.max(0, (screenSize.width - this.getWidth() ) / 2);
locationFrame.y = Math.max(0, (screenSize.height - this.getHeight() ) / 2);
setLocation(locationFrame);
} //MainFrame constructor
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="start(args)">
/** Performs start-up actions that require an "object" of this class to be
* present, for example actions that may display a message dialog box
* (because a dialog requires a parent frame).
* @param args the command-line arguments
*/
private void start(final String[] args) {
// the methods and variables in DiagrPaintUtility are used to paint the diagrams
diagrPaintUtil = new DiagrPaintUtility();
//---- read the INI-file
// (this may display message dialogs)
readIni();
//---- Position the window on the screen
locationFrame.x = Math.min( screenSize.width-this.getWidth()-5,
Math.max(5, locationFrame.x));
locationFrame.y = Math.min( screenSize.height-this.getHeight()-35,
Math.max(5, locationFrame.y));
setLocation(locationFrame);
spf = this;
if(pc.dbg) {
System.out.flush();
StringBuffer msg = new StringBuffer();
msg.append(LINE); msg.append(nl);
msg.append("After reading cfg- and INI-files");msg.append(nl);
msg.append(" and after checking for another instance:");msg.append(nl);
msg.append("App_Path = ");
if(pc.pathAPP == null) {
msg.append("\"null\"");
} else {
if(pc.pathAPP.trim().length()<=0) {msg.append("\"\"");}
else {msg.append(pc.pathAPP);}
}
msg.append(nl);
msg.append("Def_path = ");msg.append(pc.pathDef.toString());msg.append(nl);
try {
msg.append("User.dir = ");msg.append(System.getProperty("user.dir"));msg.append(nl);
msg.append("User.home = ");msg.append(System.getProperty("user.home"));msg.append(nl);
}
catch (Exception e) {}
msg.append("CLASSPATH = ");msg.append(System.getProperty("java.class.path"));msg.append(nl);
msg.append(LINE);
System.out.println(msg);
System.out.flush();
} // if(pd.dbg)
//---- set Look-And-Feel
boolean changeLookAndFeel = ((laf == 2 && windows) || (laf == 1 && !windows));
if(pc.dbg) {System.out.println("--- Change look-and-feel: windows = "+windows+", look-and-feel in ini-file = "+laf);}
if (changeLookAndFeel) {
try{
if(laf == 2) {
javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getCrossPlatformLookAndFeelClassName());
System.out.println("--- setLookAndFeel(CrossPlatform);");
} else if(laf == 1) {
javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
System.out.println("--- setLookAndFeel(System);");
}
}
catch (Exception ex) {System.out.println("Error: "+ex.getMessage());}
javax.swing.SwingUtilities.updateComponentTreeUI(spf);
spf.invalidate(); spf.validate(); spf.repaint();
javax.swing.SwingUtilities.updateComponentTreeUI(msgFrame);
msgFrame.invalidate(); msgFrame.validate(); msgFrame.repaint();
if(pc.dbg) {System.out.println("--- configureOptionPane();");}
Util.configureOptionPane();
} // changeLookAndFeel
setVisible(true);
windowSize = MainFrame.this.getSize();
//---- at this point the INI-file (if it exists) has been read.
if(txtEditor == null || txtEditor.trim().length() <=0) {jMenu_Data_Edit.setVisible(false);}
//
if(msgFrame != null) {
msgFrame.setLocation(locationMsgFrame);
msgFrame.setSize(msgFrameSize);
msgFrame.setParentFrame(spf);
jCheckBoxMenuDebug.setSelected(msgFrame.isVisible());
} else {jCheckBoxMenuDebug.setVisible(false);}
dispLocation.x = dispLocation.x - 20;
dispLocation.y = dispLocation.y - 20;
//
if(!pd.advancedVersion) {
jMenu_Run_FileExpl.setVisible(false);
jMenu_Run_Cmd.setVisible(false);
jSeparatorCmd.setVisible(false);
} else {
jMenu_Run_FileExpl.setVisible(windows);
}
if(!pd.advancedVersion) {jMenu_Prefs_Calcs.setVisible(false);}
else {jMenu_Prefs_Calcs.setVisible(true);}
java.io.File f;
if(createDataFileProg != null && createDataFileProg.trim().length()>0) {
f = new java.io.File(createDataFileProg);
if(!f.exists()) {jMenu_Run_Database.setEnabled(false);}
} else {jMenu_Run_Database.setEnabled(false);}
if(pathSedPredom != null) {
f = new java.io.File(pathSedPredom);
if(!Div.progSEDexists(f) && !Div.progPredomExists(f)) {
jMenu_Run_MakeDiagr.setEnabled(false);
jMenu_Data_Open.setEnabled(false);
}
} else {
jMenu_Run_MakeDiagr.setEnabled(false);
jMenu_Data_Open.setEnabled(false);
}
f = new java.io.File(pc.pathAPP+SLASH+ProgramConf.HELP_JAR);
if(!f.exists()) {jMenu_Help_Contents.setEnabled(false);}
//---- deal with command-line arguments
if(args != null && args.length >0){
Thread dArg = new Thread() {@Override public void run(){
for(String arg : args) {
dispatchArg(arg);
}
// do not end the program if an error occurred
if(msgFrame == null || !msgFrame.isVisible()) {
if(!doNotExit) {end_program();}
}
}}; //new Thread
dArg.start();
} // args != null
} // start(args)
// </editor-fold>
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabelBackgrd = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jLabel_Dat = new javax.swing.JLabel();
jComboBox_Dat = new javax.swing.JComboBox<String>();
jPanel3 = new javax.swing.JPanel();
jLabel_Plt = new javax.swing.JLabel();
jComboBox_Plt = new javax.swing.JComboBox<String>();
jMenuBar = new javax.swing.JMenuBar();
jMenu_File = new javax.swing.JMenu();
jMenu_File_Data = new javax.swing.JMenu();
jMenu_Data_Open = new javax.swing.JMenuItem();
jMenu_Data_New = new javax.swing.JMenuItem();
jMenu_Data_Modif = new javax.swing.JMenuItem();
jMenu_Data_Edit = new javax.swing.JMenuItem();
jMenu_Data_AddToList = new javax.swing.JMenuItem();
jMenu_Data_SaveAs = new javax.swing.JMenuItem();
jMenu_File_Plot = new javax.swing.JMenu();
jMenu_Plot_Open = new javax.swing.JMenuItem();
jMenu_Plot_SaveAs = new javax.swing.JMenuItem();
jSeparator1 = new javax.swing.JPopupMenu.Separator();
jMenu_File_Exit = new javax.swing.JMenuItem();
jMenu_Run = new javax.swing.JMenu();
jMenu_Run_FileExpl = new javax.swing.JMenuItem();
jMenu_Run_Cmd = new javax.swing.JMenuItem();
jSeparatorCmd = new javax.swing.JPopupMenu.Separator();
jMenu_Run_Modif = new javax.swing.JMenuItem();
jMenu_Run_MakeDiagr = new javax.swing.JMenuItem();
jSeparatorMake = new javax.swing.JPopupMenu.Separator();
jMenu_Run_Database = new javax.swing.JMenuItem();
jMenu_Prefs = new javax.swing.JMenu();
jMenu_Prefs_General = new javax.swing.JMenuItem();
jMenu_Prefs_Diagr = new javax.swing.JMenuItem();
jMenu_Prefs_Calcs = new javax.swing.JMenuItem();
jCheckBoxMenuDebug = new javax.swing.JCheckBoxMenuItem();
jMenu_Help = new javax.swing.JMenu();
jMenu_Help_Contents = new javax.swing.JMenuItem();
jMenu_Help_About = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(255, 255, 255));
setMinimumSize(new java.awt.Dimension(345, 170));
addWindowFocusListener(new java.awt.event.WindowFocusListener() {
public void windowGainedFocus(java.awt.event.WindowEvent evt) {
formWindowGainedFocus(evt);
}
public void windowLostFocus(java.awt.event.WindowEvent evt) {
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowActivated(java.awt.event.WindowEvent evt) {
formWindowActivated(evt);
}
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
jLabelBackgrd.setBackground(new java.awt.Color(255, 255, 255));
jLabelBackgrd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/spana/images/Spana_diagram.gif"))); // NOI18N
jLabelBackgrd.setVerticalAlignment(javax.swing.SwingConstants.TOP);
jLabelBackgrd.setAlignmentY(0.0F);
jLabelBackgrd.setMinimumSize(new java.awt.Dimension(345, 160));
jLabelBackgrd.setOpaque(true);
jLabelBackgrd.setPreferredSize(new java.awt.Dimension(345, 160));
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jPanel1.setMinimumSize(new java.awt.Dimension(345, 160));
jPanel1.setPreferredSize(new java.awt.Dimension(345, 160));
jPanel2.setBackground(new java.awt.Color(255, 255, 255));
jPanel2.setPreferredSize(new java.awt.Dimension(0, 66));
jLabel_Dat.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel_Dat.setText("Data files:");
jComboBox_Dat.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox_DatActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel_Dat)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jComboBox_Dat, javax.swing.GroupLayout.Alignment.TRAILING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel_Dat)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBox_Dat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(12, Short.MAX_VALUE))
);
jPanel3.setBackground(new java.awt.Color(255, 255, 255));
jPanel3.setPreferredSize(new java.awt.Dimension(0, 66));
jLabel_Plt.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel_Plt.setText("Plot files:");
jComboBox_Plt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox_PltActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel_Plt)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jComboBox_Plt, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel_Plt)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 7, Short.MAX_VALUE)
.addComponent(jComboBox_Plt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 325, Short.MAX_VALUE)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 325, Short.MAX_VALUE))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(28, Short.MAX_VALUE))
);
jMenu_File.setMnemonic('F');
jMenu_File.setText("File");
jMenu_File_Data.setMnemonic('D');
jMenu_File_Data.setText("Data file");
jMenu_Data_Open.setMnemonic('O');
jMenu_Data_Open.setText("Open (make a diagram)");
jMenu_Data_Open.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu_Data_OpenActionPerformed(evt);
}
});
jMenu_File_Data.add(jMenu_Data_Open);
jMenu_Data_New.setMnemonic('N');
jMenu_Data_New.setText("New (create)");
jMenu_Data_New.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu_Data_NewActionPerformed(evt);
}
});
jMenu_File_Data.add(jMenu_Data_New);
jMenu_Data_Modif.setMnemonic('M');
jMenu_Data_Modif.setText("Modify");
jMenu_Data_Modif.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu_Data_ModifActionPerformed(evt);
}
});
jMenu_File_Data.add(jMenu_Data_Modif);
jMenu_Data_Edit.setMnemonic('E');
jMenu_Data_Edit.setText("Edit");
jMenu_Data_Edit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu_Data_EditActionPerformed(evt);
}
});
jMenu_File_Data.add(jMenu_Data_Edit);
jMenu_Data_AddToList.setMnemonic('A');
jMenu_Data_AddToList.setText("Add name to list");
jMenu_Data_AddToList.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu_Data_AddToListActionPerformed(evt);
}
});
jMenu_File_Data.add(jMenu_Data_AddToList);
jMenu_Data_SaveAs.setMnemonic('S');
jMenu_Data_SaveAs.setText("Save as");
jMenu_Data_SaveAs.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu_Data_SaveAsActionPerformed(evt);
}
});
jMenu_File_Data.add(jMenu_Data_SaveAs);
jMenu_File.add(jMenu_File_Data);
jMenu_File_Plot.setMnemonic('P');
jMenu_File_Plot.setText("Plot file");
jMenu_Plot_Open.setMnemonic('O');
jMenu_Plot_Open.setText("Open (display)");
jMenu_Plot_Open.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu_Plot_OpenActionPerformed(evt);
}
});
jMenu_File_Plot.add(jMenu_Plot_Open);
jMenu_Plot_SaveAs.setMnemonic('S');
jMenu_Plot_SaveAs.setText("Save as");
jMenu_Plot_SaveAs.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu_Plot_SaveAsActionPerformed(evt);
}
});
jMenu_File_Plot.add(jMenu_Plot_SaveAs);
jMenu_File.add(jMenu_File_Plot);
jMenu_File.add(jSeparator1);
jMenu_File_Exit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK));
jMenu_File_Exit.setMnemonic('X');
jMenu_File_Exit.setText("Exit");
jMenu_File_Exit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu_File_ExitActionPerformed(evt);
}
});
jMenu_File.add(jMenu_File_Exit);
jMenuBar.add(jMenu_File);
jMenu_Run.setMnemonic('R');
jMenu_Run.setText("Run");
jMenu_Run_FileExpl.setMnemonic('E');
jMenu_Run_FileExpl.setText("file Explorer");
jMenu_Run_FileExpl.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu_Run_FileExplActionPerformed(evt);
}
});
jMenu_Run.add(jMenu_Run_FileExpl);
jMenu_Run_Cmd.setMnemonic('P');
jMenu_Run_Cmd.setText("command Prompt");
jMenu_Run_Cmd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu_Run_CmdActionPerformed(evt);
}
});
jMenu_Run.add(jMenu_Run_Cmd);
jMenu_Run.add(jSeparatorCmd);
jMenu_Run_Modif.setMnemonic('M');
jMenu_Run_Modif.setText("Modify chemical system");
jMenu_Run_Modif.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu_Run_ModifActionPerformed(evt);
}
});
jMenu_Run.add(jMenu_Run_Modif);
jMenu_Run_MakeDiagr.setMnemonic('D');
jMenu_Run_MakeDiagr.setText("make a Diagram");
jMenu_Run_MakeDiagr.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu_Run_MakeDiagrActionPerformed(evt);
}
});
jMenu_Run.add(jMenu_Run_MakeDiagr);
jMenu_Run.add(jSeparatorMake);
jMenu_Run_Database.setMnemonic('L');
jMenu_Run_Database.setText("LogK Database");
jMenu_Run_Database.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu_Run_DatabaseActionPerformed(evt);
}
});
jMenu_Run.add(jMenu_Run_Database);
jMenuBar.add(jMenu_Run);
jMenu_Prefs.setMnemonic('P');
jMenu_Prefs.setText("Preferences");
jMenu_Prefs_General.setMnemonic('G');
jMenu_Prefs_General.setText("General options");
jMenu_Prefs_General.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu_Prefs_GeneralActionPerformed(evt);
}
});
jMenu_Prefs.add(jMenu_Prefs_General);
jMenu_Prefs_Diagr.setMnemonic('D');
jMenu_Prefs_Diagr.setText("Diagram windows");
jMenu_Prefs_Diagr.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu_Prefs_DiagrActionPerformed(evt);
}
});
jMenu_Prefs.add(jMenu_Prefs_Diagr);
jMenu_Prefs_Calcs.setMnemonic('C');
jMenu_Prefs_Calcs.setText("Calculation options");
jMenu_Prefs_Calcs.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu_Prefs_CalcsActionPerformed(evt);
}
});
jMenu_Prefs.add(jMenu_Prefs_Calcs);
jCheckBoxMenuDebug.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.ALT_MASK));
jCheckBoxMenuDebug.setMnemonic('S');
jCheckBoxMenuDebug.setText("Show messages and errors");
jCheckBoxMenuDebug.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxMenuDebugActionPerformed(evt);
}
});
jMenu_Prefs.add(jCheckBoxMenuDebug);
jMenuBar.add(jMenu_Prefs);
jMenu_Help.setMnemonic('H');
jMenu_Help.setText("Help");
jMenu_Help_Contents.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0));
jMenu_Help_Contents.setMnemonic('C');
jMenu_Help_Contents.setText("help Contents");
jMenu_Help_Contents.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu_Help_ContentsActionPerformed(evt);
}
});
jMenu_Help.add(jMenu_Help_Contents);
jMenu_Help_About.setMnemonic('A');
jMenu_Help_About.setText("About");
jMenu_Help_About.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu_Help_AboutActionPerformed(evt);
}
});
jMenu_Help.add(jMenu_Help_About);
jMenuBar.add(jMenu_Help);
setJMenuBar(jMenuBar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelBackgrd, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(0, 0, 0))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelBackgrd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
//<editor-fold defaultstate="collapsed" desc="Events">
private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
if(windowSize != null) {
int w = windowSize.width;
int h = windowSize.height;
if(this.getHeight()<h){this.setSize(this.getWidth(), h);}
if(this.getWidth()<w){this.setSize(w,this.getHeight());}
}
}//GEN-LAST:event_formComponentResized
private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
if(msgFrame != null && msgFrame.isVisible()) {
jCheckBoxMenuDebug.setSelected(true);
}
}//GEN-LAST:event_formWindowActivated
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
end_program();
}//GEN-LAST:event_formWindowClosing
private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus
if(helpAboutFrame != null) {helpAboutFrame.bringToFront();}
if(msgFrame != null) {jCheckBoxMenuDebug.setSelected(msgFrame.isVisible());}
else {jCheckBoxMenuDebug.setVisible(false);}
}//GEN-LAST:event_formWindowGainedFocus
private void jComboBox_DatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox_DatActionPerformed
if(jComboBox_Dat.getSelectedIndex() < 0) {return;}
String name = jComboBox_Dat.getSelectedItem().toString();
java.io.File datF = new java.io.File(name);
if(!datF.exists()) {removeDatFile(name);} else {pc.setPathDef(datF);}
}//GEN-LAST:event_jComboBox_DatActionPerformed
private void jComboBox_PltActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox_PltActionPerformed
if(jComboBox_Plt_doNothing) {return;}
int k = jComboBox_Plt.getSelectedIndex();
if(k < 0) {return;}
String name = jComboBox_Plt.getItemAt(k).toString();
java.io.File pltF = new java.io.File(name);
if(!pltF.exists()) {removePltFile(name); return;}
displayPlotFile(name, null);
}//GEN-LAST:event_jComboBox_PltActionPerformed
private void jMenu_Data_OpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu_Data_OpenActionPerformed
setCursorWait();
String fileName = Util.getOpenFileName(this, pc.progName, true,
"Enter Data file name", 5, null, pc.pathDef.toString());
if(fileName != null) {
setCursorWait();
java.io.File dataFile = new java.io.File(fileName);
if(dataFile.exists() && (!dataFile.canWrite() || !dataFile.setWritable(true))) {
String msg = "Warning - the file:"+nl+
" \""+dataFile.getPath()+"\""+nl+
"is write-protected!"+nl+nl+
"It might be best to copy the file"+nl+
"to a writable location"+nl+
"before going ahead...";
System.out.println(LINE+nl+msg+nl+LINE);
Object[] opt = {"Go ahead anyway", "Cancel"};
int m = javax.swing.JOptionPane.showOptionDialog(this, msg,
pc.progName, javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[1]);
if(m != javax.swing.JOptionPane.YES_OPTION) {setCursorDef(); return;}
}
addDatFile(fileName);
if(jMenu_Run_MakeDiagr.isEnabled()) {jMenu_Run_MakeDiagr.doClick();}
}
}//GEN-LAST:event_jMenu_Data_OpenActionPerformed
private void jMenu_Data_NewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu_Data_NewActionPerformed
setCursorWait();
run_Database();
}//GEN-LAST:event_jMenu_Data_NewActionPerformed
private void jMenu_Data_ModifActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu_Data_ModifActionPerformed
setCursorWait();
modifyDataFile();
}//GEN-LAST:event_jMenu_Data_ModifActionPerformed
private void jMenu_Data_EditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu_Data_EditActionPerformed
if(txtEditor == null) {return;}
setCursorWait();
String fileName;
//---- is the data-files combo box empty? if so, get a file name
if(dataFileArrList.size() <=0) {
// -- get a file name through an Open File Dialog
fileName = Util.getOpenFileName(this, pc.progName, true,
"Enter Data file name", 5, null, pc.pathDef.toString());
if(fileName == null) {setCursorDef(); return;}
} // if dataFileArrList.size() <=0
else {
// -- get the file name selected in the combo box
String defFile = jComboBox_Dat.getSelectedItem().toString();
// -- confirm the file name through an Open File Dialog
fileName = Util.getOpenFileName(this, pc.progName, true,
"Enter Data file name", 5, defFile, pc.pathDef.toString());
if(fileName == null) {setCursorDef(); return;}
}
setCursorWait();
//---- get the full name, with path
java.io.File datFile = new java.io.File(fileName);
try{fileName = datFile.getCanonicalPath();}
catch (java.io.IOException ex) {
try{fileName = datFile.getAbsolutePath();}
catch (Exception e) {fileName = datFile.getPath();}
}
//---- add the file name to the combo-box
addDatFile(fileName);
//---- start the editor on a separate process
final String editor;
final String[] args;
if(System.getProperty("os.name").startsWith("Mac OS")
&& txtEditor.equalsIgnoreCase("/usr/bin/open -t")) {
editor = "/usr/bin/open";
args = new String[]{"-t",fileName};
} else { // not MacOS
editor = txtEditor;
args = new String[]{fileName};
}
setCursorWait();
Thread edt = new Thread() {@Override public void run(){
boolean waitForCompletion = false;
lib.huvud.RunProgr.runProgramInProcess(null, editor, args,
waitForCompletion, pc.dbg, pc.pathDef.toString());
try{Thread.sleep(1000);} //show the "wait" cursor for 1 sec
catch (InterruptedException e) {}
setCursorDef();
}};//new Thread
edt.start();
}//GEN-LAST:event_jMenu_Data_EditActionPerformed
private void jMenu_Data_AddToListActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu_Data_AddToListActionPerformed
setCursorWait();
String fileName = Util.getOpenFileName(this, pc.progName, true,
"Enter Data file name", 5, null, pc.pathDef.toString());
if(fileName != null && fileName.trim().length() >0) {
setCursorWait();
java.io.File dataFile = new java.io.File(fileName);
if(dataFile.exists() && (!dataFile.canWrite() || !dataFile.setWritable(true))) {
String msg = "Warning - the file:"+nl+
" \""+dataFile.getPath()+"\""+nl+
"is write-protected!"+nl+nl+
"It might be best to copy the file"+nl+
"to a writable location"+nl+
"before going ahead...";
System.out.println(LINE+nl+msg+nl+LINE);
Object[] opt = {"Go ahead anyway", "Cancel"};
int m = javax.swing.JOptionPane.showOptionDialog(this, msg,
pc.progName, javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[1]);
if(m != javax.swing.JOptionPane.YES_OPTION) {setCursorDef(); return;}
}
addDatFile(fileName);
}
setCursorDef();
}//GEN-LAST:event_jMenu_Data_AddToListActionPerformed
private void jMenu_File_ExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu_File_ExitActionPerformed
end_program();
}//GEN-LAST:event_jMenu_File_ExitActionPerformed
private void jMenu_Run_FileExplActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu_Run_FileExplActionPerformed
if(!windows) {return;}
setCursorWait();
Runtime r = Runtime.getRuntime();
try{ //%windir%\explorer.exe /n, /e, m:\
String t = windir;
if(t != null && t.endsWith(SLASH)) {t = t.substring(0, t.length()-1);}
if(t != null) {t = t + SLASH + "explorer.exe";} else {t = "explorer.exe";}
String[] a = {t,"/n,","/e,",pc.pathDef.toString()};
java.io.File d = new java.io.File(pc.pathDef.toString());
if(pc.dbg) {System.out.println("---- Exec "+Arrays.toString(a)+nl+
" working dir: "+d);}
r.exec( a, null, d);
} catch (java.io.IOException ex) {
MsgExceptn.exception("Error: "+ex.toString());
} //catch
setCursorDef();
}//GEN-LAST:event_jMenu_Run_FileExplActionPerformed
private void jMenu_Run_CmdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu_Run_CmdActionPerformed
setCursorWait();
String OS = System.getProperty("os.name").toLowerCase();
// System.out.println(OS);
Runtime r = Runtime.getRuntime();
try{
if(OS.indexOf("windows 9") > -1) {
if(pc.dbg) {System.out.println("---- Exec \"command.com /e:1024\"");}
r.exec( "command.com /e:1024" );
} //Windows 9x
else if (OS.startsWith("windows")) {
String[] a = {"cmd.exe", "/k start cmd.exe"};
java.io.File d = new java.io.File(pc.pathDef.toString());
if(pc.dbg) {System.out.println("---- Exec "+Arrays.toString(a)+nl+
" working dir: "+d);}
r.exec( a, null, d);
} //Windows
else if(OS.startsWith("mac os")) {
final String [] args;
java.io.File term = new java.io.File("/Applications/Utilities/Terminal.app");
if(!term.exists()) {
MsgExceptn.exception("---- Error - file:"+term.getAbsolutePath()+nl+
" does NOT exist");
} else {
if(pc.dbg) {System.out.println(
"---- Exec \"/usr/bin/open -n "+term.getAbsolutePath()+"\"");}
args = new String[]{"-n",term.getAbsolutePath()};
setCursorWait();
Thread cmd = new Thread() {@Override public void run(){
boolean waitForCompletion = false;
lib.huvud.RunProgr.runProgramInProcess(null, "/usr/bin/open", args,
waitForCompletion, pc.dbg, pc.pathDef.toString());
try{Thread.sleep(1000);} //show the "wait" cursor for 1 sec
catch (InterruptedException e) {}
setCursorDef();
}};//new Thread
cmd.start();
}
} else {
// our last hope, we assume Unix
if(pc.dbg) {System.out.println("---- Exec \"/usr/bin/xterm\"");}
r.exec( "/usr/bin/xterm" );
} //unix
} catch (java.io.IOException ex) {
MsgExceptn.exception("Error: "+ex.toString());
} //catch
setCursorDef();
}//GEN-LAST:event_jMenu_Run_CmdActionPerformed
private void jMenu_Run_ModifActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu_Run_ModifActionPerformed
setCursorWait();
modifyDataFile();
}//GEN-LAST:event_jMenu_Run_ModifActionPerformed
private void jMenu_Run_MakeDiagrActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu_Run_MakeDiagrActionPerformed
setCursorWait();
//---- is the data-files combo box empty? if so, get a file name
if(dataFileArrList.size() <=0) {
String fileName = Util.getOpenFileName(this, pc.progName, true,
"Enter data file name", 5, null, pc.pathDef.toString());
if(fileName == null) {setCursorDef(); return;}
java.io.File dataFile = new java.io.File(fileName);
if(dataFile.exists() && (!dataFile.canWrite() || !dataFile.setWritable(true))) {
String msg = "Warning - the file:"+nl+
" \""+dataFile.getPath()+"\""+nl+
"is write-protected!"+nl+nl+
"It might be best to copy the file"+nl+
"to a writable location"+nl+
"before going ahead...";
System.out.println(LINE+nl+msg+nl+LINE);
Object[] opt = {"Go ahead anyway", "Cancel"};
int m = javax.swing.JOptionPane.showOptionDialog(this, msg,
pc.progName, javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[1]);
if(m != javax.swing.JOptionPane.YES_OPTION) {setCursorDef(); return;}
}
if(!addDatFile(fileName)) {setCursorDef(); return;}
} // if dataFileArrList.size() <=0
else {
String name = jComboBox_Dat.getSelectedItem().toString();
java.io.File datF = new java.io.File(name);
if(!datF.exists()) {
removeDatFile(name);
String fileName = Util.getOpenFileName(this, pc.progName, true,
"Enter data file name", 5, null, pc.pathDef.toString());
if(fileName == null) {setCursorDef(); return;}
if(!addDatFile(fileName)) {setCursorDef(); return;}
}
}
setCursorWait();
// ---- get the file name selected in the combo box
final java.io.File datFile = new java.io.File(jComboBox_Dat.getSelectedItem().toString());
jMenu_Run_MakeDiagr.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
final boolean jMenu_Prefs_General_setEnabled = jMenu_Prefs_General.isEnabled();
final boolean jMenu_Run_MakeDiagr_setEnabled = jMenu_Run_MakeDiagr.isEnabled();
final boolean jMenu_Data_Open_setEnabled = jMenu_Data_Open.isEnabled();
final boolean jMenu_Run_Modif_setEnabled = jMenu_Run_Modif.isEnabled();
final boolean jMenu_Data_Modif_setEnabled = jMenu_Data_Modif.isEnabled();
final boolean jMenu_Data_Edit_setEnabled = jMenu_Data_Edit.isEnabled();
jMenu_Prefs_General.setEnabled(false);
jMenu_Run_MakeDiagr.setEnabled(false);
jMenu_Data_Open.setEnabled(false);
jMenu_Run_Modif.setEnabled(false);
jMenu_Data_Modif.setEnabled(false);
jMenu_Data_Edit.setEnabled(false);
// ---- Going to wait for another frame (Select_Diagram): Start a thread
new javax.swing.SwingWorker<Void,Void>() {
@Override protected Void doInBackground() throws Exception {
Select_Diagram selectDiagramWindow = new Select_Diagram(datFile, pc, pd);
selectDiagramWindow.start();
spf.setCursorDef();
jMenu_Run_MakeDiagr.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
selectDiagramWindow.waitForSelectDiagram();
return null;
}
@Override protected void done(){
jMenu_Prefs_General.setEnabled(jMenu_Prefs_General_setEnabled);
jMenu_Run_MakeDiagr.setEnabled(jMenu_Run_MakeDiagr_setEnabled);
jMenu_Data_Open.setEnabled(jMenu_Data_Open_setEnabled);
jMenu_Run_Modif.setEnabled(jMenu_Run_Modif_setEnabled);
jMenu_Data_Modif.setEnabled(jMenu_Data_Modif_setEnabled);
jMenu_Data_Edit.setEnabled(jMenu_Data_Edit_setEnabled);
}
}.execute();
}//GEN-LAST:event_jMenu_Run_MakeDiagrActionPerformed
private void jMenu_Run_DatabaseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu_Run_DatabaseActionPerformed
setCursorWait();
run_Database();
}//GEN-LAST:event_jMenu_Run_DatabaseActionPerformed
private void jMenu_Prefs_GeneralActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu_Prefs_GeneralActionPerformed
setCursorWait();
final boolean jMenu_Prefs_General_setEnabled = jMenu_Prefs_General.isEnabled();
final boolean jMenu_Prefs_Calcs_setEnabled = jMenu_Prefs_Calcs.isEnabled();
final boolean jMenu_Run_MakeDiagr_setEnabled = jMenu_Run_MakeDiagr.isEnabled();
final boolean jMenu_Run_Modif_setEnabled = jMenu_Run_Modif.isEnabled();
final boolean jMenu_Data_Modif_setEnabled = jMenu_Data_Modif.isEnabled();
final boolean jMenu_Data_Open_setEnabled = jMenu_Data_Open.isEnabled();
final boolean jMenu_Run_Database_setEnabled = jMenu_Run_Database.isEnabled();
jMenu_Prefs_General.setEnabled(false);
jMenu_Prefs_Calcs.setEnabled(false);
jMenu_Run_MakeDiagr.setEnabled(false);
jMenu_Run_Modif.setEnabled(false);
jMenu_Data_Modif.setEnabled(false);
jMenu_Data_Open.setEnabled(false);
Thread genO = new Thread() {@Override public void run(){
OptionsGeneral genOptionsFrame = new OptionsGeneral(pc,pd,msgFrame);
spf.setCursorDef();
genOptionsFrame.waitFor();
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
jMenu_Prefs_General.setEnabled(jMenu_Prefs_General_setEnabled);
jMenu_Prefs_Calcs.setEnabled(jMenu_Prefs_Calcs_setEnabled);
jMenu_Run_MakeDiagr.setEnabled(jMenu_Run_MakeDiagr_setEnabled);
jMenu_Run_Modif.setEnabled(jMenu_Run_Modif_setEnabled);
jMenu_Data_Modif.setEnabled(jMenu_Data_Modif_setEnabled);
jMenu_Data_Open.setEnabled(jMenu_Data_Open_setEnabled);
if(!pd.advancedVersion) {
jMenu_Run_Cmd.setVisible(false);
jMenu_Run_FileExpl.setVisible(false);
jSeparatorCmd.setVisible(false);
jMenu_Prefs_Calcs.setVisible(false);
} else {
jMenu_Run_Cmd.setVisible(true);
jMenu_Run_FileExpl.setVisible(windows);
jSeparatorCmd.setVisible(true);
jMenu_Prefs_Calcs.setVisible(true);
}
java.io.File file;
if(createDataFileProg != null && createDataFileProg.trim().length() >0) {
file = new java.io.File(createDataFileProg);
if(!file.exists()) {
System.out.println("Note: file does NOT exist: "+createDataFileProg);
jMenu_Run_Database.setEnabled(false);
} else {jMenu_Run_Database.setEnabled(jMenu_Run_Database_setEnabled);}
} else {jMenu_Run_Database.setEnabled(false);}
if(pathSedPredom != null) {
file = new java.io.File(pathSedPredom);
if(!Div.progSEDexists(file) && !Div.progPredomExists(file)) {
jMenu_Run_MakeDiagr.setEnabled(false);
jMenu_Data_Open.setEnabled(false);
}
} else {
jMenu_Run_MakeDiagr.setEnabled(false);
jMenu_Data_Open.setEnabled(false);
}
java.awt.Frame[] f = Disp.getFrames();
if(diagrArrList.size() >0 && f.length >0) {
for(int k=0; k<diagrArrList.size(); k++) {
Disp gotDisp = diagrArrList.get(k);
for(java.awt.Frame f1 : f) {
if (f1.equals(gotDisp)) {
if(gotDisp.getExtendedState()!=javax.swing.JFrame.ICONIFIED) { // minimised?
gotDisp.setAdvancedFeatures(pd.advancedVersion);
gotDisp.repaint();
} }
} // for f1 : f
} // for k
} //if diagrArrList.size() >0 & f.length >0
}}); //invokeLater(Runnable)
}};//new Thread
genO.start();
}//GEN-LAST:event_jMenu_Prefs_GeneralActionPerformed
private void jMenu_Prefs_DiagrActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu_Prefs_DiagrActionPerformed
setCursorWait();
jMenu_Prefs_Diagr.setEnabled(false);
final boolean oldTextWithFonts = diagrPaintUtil.textWithFonts;
Thread diagPrefs = new Thread() {@Override public void run(){
OptionsDiagram optionsWindow = new OptionsDiagram(diagrPaintUtil, pc);
optionsWindow.setVisible(true);
spf.setCursorDef();
optionsWindow.waitFor();
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
//take these actions on the Event Dispatch Thread
jMenu_Prefs_Diagr.setEnabled(true);
java.awt.Frame[] f = Disp.getFrames();
if(diagrArrList.size() >0 && f.length >0) {
for(int k=0; k<diagrArrList.size(); k++) {
Disp gotDisp = diagrArrList.get(k);
for(java.awt.Frame f1 : f) {
if (f1.equals(gotDisp)) {
if(oldTextWithFonts != diagrPaintUtil.textWithFonts)
{gotDisp.reloadPlotFile();}
if(gotDisp.getExtendedState()!=javax.swing.JFrame.ICONIFIED) // minimised?
{gotDisp.repaint();}
}
} // for f1 : f
} // for k
} //if diagrArrList.size() >0 & f.length >0
}}); //invokeLater(Runnable)
}};//new Thread
diagPrefs.start();
}//GEN-LAST:event_jMenu_Prefs_DiagrActionPerformed
private void jMenu_Prefs_CalcsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu_Prefs_CalcsActionPerformed
setCursorWait();
jMenu_Prefs_Calcs.setEnabled(false);
final boolean jMenu_Prefs_General_setEnabled = jMenu_Prefs_General.isEnabled();
final boolean jMenu_Run_MakeDiagr_setEnabled = jMenu_Run_MakeDiagr.isEnabled();
final boolean jMenu_Data_Open_setEnabled = jMenu_Data_Open.isEnabled();
jMenu_Prefs_General.setEnabled(false);
jMenu_Run_MakeDiagr.setEnabled(false);
jMenu_Data_Open.setEnabled(false);
Thread calcO = new Thread() {@Override public void run(){
OptionsCalcs calcsOptionsFrame = new OptionsCalcs(pc,pd);
calcsOptionsFrame.setVisible(true);
spf.setCursorDef();
calcsOptionsFrame.waitFor();
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
jMenu_Prefs_Calcs.setEnabled(true);
jMenu_Prefs_General.setEnabled(jMenu_Prefs_General_setEnabled);
jMenu_Run_MakeDiagr.setEnabled(jMenu_Run_MakeDiagr_setEnabled);
jMenu_Data_Open.setEnabled(jMenu_Data_Open_setEnabled);
}}); //invokeLater(Runnable)
}};//new Thread
calcO.start();
}//GEN-LAST:event_jMenu_Prefs_CalcsActionPerformed
private void jCheckBoxMenuDebugActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxMenuDebugActionPerformed
if(msgFrame != null) {msgFrame.setVisible(jCheckBoxMenuDebug.isSelected());}
}//GEN-LAST:event_jCheckBoxMenuDebugActionPerformed
private void jMenu_Help_ContentsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu_Help_ContentsActionPerformed
setCursorWait();
Thread hlp = new Thread() {@Override public void run(){
String[] a = {"S_0_Main_htm"};
lib.huvud.RunProgr.runProgramInProcess(null,ProgramConf.HELP_JAR,a,false,pc.dbg,pc.pathAPP);
try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec
catch (InterruptedException e) {}
setCursorDef();
}};//new Thread
hlp.start();
}//GEN-LAST:event_jMenu_Help_ContentsActionPerformed
private void jMenu_Help_AboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu_Help_AboutActionPerformed
setCursorWait();
jMenu_Help_About.setEnabled(false);
// -- although HelpAbout is a frame, it behaves almost as a modal dialog
// because it is brought to focus when "this" gains focus
Thread hlp = new Thread() {@Override public void run(){
spf.helpAboutFrame = new HelpAbout(pc.pathAPP);
spf.helpAboutFrame.start();
spf.setCursorDef();
spf.helpAboutFrame.waitFor();
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
spf.helpAboutFrame = null;
jMenu_Help_About.setEnabled(true);
bringToFront();
}}); //invokeLater(Runnable)
}};//new Thread
hlp.start();
}//GEN-LAST:event_jMenu_Help_AboutActionPerformed
private void jMenu_Plot_OpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu_Plot_OpenActionPerformed
setCursorWait();
String pltFileName = Util.getOpenFileName(this, pc.progName, true,
"Enter Plot file name", 6, null, pc.pathDef.toString());
if(pltFileName == null) {setCursorDef(); return;}
setCursorWait();
java.io.File pltFile = new java.io.File(pltFileName);
try{pltFileName = pltFile.getCanonicalPath();}
catch (java.io.IOException ex) {
try{pltFileName = pltFile.getAbsolutePath();}
catch (Exception e) {pltFileName = pltFile.getPath();}
}
displayPlotFile(pltFileName, null);
setCursorDef();
}//GEN-LAST:event_jMenu_Plot_OpenActionPerformed
private void jMenu_Plot_SaveAsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu_Plot_SaveAsActionPerformed
if(pc.dbg) {System.out.println("--- Plot file \"save as\"");}
String fileName;
java.io.File f, newF;
if(jComboBox_Plt.getSelectedIndex() < 0) {
if(pc.dbg) {System.out.println(" jComboBox_Plt.getSelectedIndex() < 0"+nl+
" canceling \"save as\".");}
return;
} else {
fileName = jComboBox_Plt.getSelectedItem().toString();
if(pc.dbg) {System.out.println(" jComboBox_Plt.getSelectedItem() = "+fileName);}
f = new java.io.File(fileName);
if(!f.exists()) {
if(pc.dbg) {System.out.println(" file does not exist. Canceling \"save as\".");}
removePltFile(fileName);
return;
}
}
if(fileName == null || fileName.trim().length() <=0) {
if(pc.dbg) {System.out.println(" Empty source file name; canceling \"save as\".");}
return;
}
setCursorWait();
f = new java.io.File(fileName);
String source = f.getName();
String newFileName = source;
if(source.length()>4) {newFileName = source.substring(0, source.length()-4)+"(2).plt";}
newFileName = Util.getSaveFileName(this, pc.progName,
"Save file as ...", 6, newFileName, pc.pathDef.toString());
setCursorDef();
if(newFileName == null || newFileName.trim().length() <=0) {
if(pc.dbg) {System.out.println(" Empty target file name; canceling \"save as\".");}
return;
}
if(newFileName.equalsIgnoreCase(fileName)) {
if(pc.dbg) {System.out.println(" Target file name = source file name; canceling \"save as\".");}
return;
}
setCursorWait();
newF = new java.io.File(newFileName);
boolean ok = copyTextFile(f, newF, pc.dbg);
if (ok) {
String msg = "File \""+newF.getName()+"\" has been created.";
System.out.println(" "+msg);
javax.swing.JOptionPane.showMessageDialog(this,msg,
pc.progName,javax.swing.JOptionPane.INFORMATION_MESSAGE);
}
setCursorDef();
}//GEN-LAST:event_jMenu_Plot_SaveAsActionPerformed
private void jMenu_Data_SaveAsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu_Data_SaveAsActionPerformed
if(pc.dbg) {System.out.println("--- Data file \"save as\"");}
String fileName;
java.io.File f, newF;
if(jComboBox_Dat.getSelectedIndex() < 0) {
if(pc.dbg) {System.out.println(" jComboBox_Dat.getSelectedIndex() < 0"+nl+
" canceling \"save as\".");}
return;
} else {
fileName = jComboBox_Dat.getSelectedItem().toString();
if(pc.dbg) {System.out.println(" jComboBox_Dat.getSelectedItem() = "+fileName);}
f = new java.io.File(fileName);
if(!f.exists()) {
if(pc.dbg) {System.out.println(" file does not exist. Canceling \"save as\".");}
removeDatFile(fileName);
return;
}
}
if(fileName == null || fileName.trim().length() <=0) {
if(pc.dbg) {System.out.println(" Empty source file name; canceling \"save as\".");}
return;
}
setCursorWait();
f = new java.io.File(fileName);
String source = f.getName();
String newFileName = source;
if(source.length()>4) {newFileName = source.substring(0, source.length()-4)+"(2).dat";}
newFileName = Util.getSaveFileName(this, pc.progName,
"Save file as ...", 5, newFileName, pc.pathDef.toString());
setCursorDef();
if(newFileName == null || newFileName.trim().length() <=0) {
if(pc.dbg) {System.out.println(" Empty target file name; canceling \"save as\".");}
return;
}
if(newFileName.equalsIgnoreCase(fileName)) {
if(pc.dbg) {System.out.println(" Target file name = source file name; canceling \"save as\".");}
return;
}
setCursorWait();
newF = new java.io.File(newFileName);
boolean ok = copyTextFile(f, newF, pc.dbg);
if (ok) {
String msg = "File \""+newF.getName()+"\" has been created.";
System.out.println(" "+msg);
javax.swing.JOptionPane.showMessageDialog(this,msg,
pc.progName,javax.swing.JOptionPane.INFORMATION_MESSAGE);
}
setCursorDef();
}//GEN-LAST:event_jMenu_Data_SaveAsActionPerformed
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="Methods">
/** wake up any thread waiting: "this.wait()" */
private synchronized void notify_All() {notifyAll();}
private synchronized void synchWaitPrinted() {
if(pc.dbg) {System.out.println("---- synchWaitPrinted()");}
while(!waitingForPrinter) {
try {this.wait();} catch(InterruptedException ex) {}
}
} // synchWaitPrinted()
private void end_program() {
if(pc.dbg){System.out.println(pc.progName+"---- end_program()");}
if(modifyDiagramWindow != null) {
if(modifyDiagramWindow.isModified()) {
modifyDiagramWindow.quitFrame();
if(modifyDiagramWindow != null && modifyDiagramWindow.isModified()) {return;}
}
}
if(helpAboutFrame != null) {helpAboutFrame.closeWindow();}
if(fileIni != null) {saveIni(fileIni);}
this.dispose();
spf = null;
OneInstance.endCheckOtherInstances();
if(pc.dbg) {System.out.println("System.exit(0);");}
System.exit(0);
} // end_program()
public void bringToFront() {
if(pc.dbg) {System.out.println("---- bringToFront()");}
if(spf == null) {return;}
java.awt.EventQueue.invokeLater(new Runnable() {@Override public void run() {
if(!spf.isVisible()) {spf.setVisible(true);}
if(spf.getExtendedState()==javax.swing.JFrame.ICONIFIED // minimised?
|| spf.getExtendedState()==javax.swing.JFrame.MAXIMIZED_BOTH)
{spf.setExtendedState(javax.swing.JFrame.NORMAL);}
spf.setEnabled(true);
spf.setAlwaysOnTop(true);
spf.toFront();
spf.requestFocus();
spf.setAlwaysOnTop(false);
}});
} // bringToFront()
private void minimize() {
if(pc.dbg) {System.out.println("---- minimize()");}
if(spf != null && spf.isVisible()) {this.setExtendedState(javax.swing.JFrame.ICONIFIED);}
} // minimize()
void setCursorWait() {
if(spf != null) {spf.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));}
if(msgFrame != null && msgFrame.isShowing()) {
msgFrame.setCursorWait();
}
if(modifyDiagramWindow != null && modifyDiagramWindow.isShowing()) {
modifyDiagramWindow.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
}
}
void setCursorDef() {
if(spf != null) {spf.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));}
if(msgFrame != null && msgFrame.isShowing()) {
msgFrame.setCursorDef();
}
if(modifyDiagramWindow != null && modifyDiagramWindow.isShowing()) {
modifyDiagramWindow.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
}
}
//<editor-fold defaultstate="collapsed" desc="addDatFile(String)">
/** Add a data file as an item in the combo box if the file is not
* already there; bring the main window to front.
* @param datFileN String containing the name of the data file
* @return true if ok, false otherwise. */
protected boolean addDatFile(String datFileN) {
if(datFileN == null) {return false;}
if(pc.dbg) {System.out.println("---- addDatFile("+datFileN+")");}
//--- check the name
if(!datFileN.toLowerCase().endsWith(".dat")) {
MsgExceptn.exception("Data file name = \""+datFileN.toLowerCase()+"\""+nl+
"Error: data file name must end with \".dat\"");
return false;}
java.io.File datFile = new java.io.File(datFileN);
if(datFile.getName().length() <= 4) {
MsgExceptn.exception("Error: file name must have at least one character");
return false;}
if(!datFile.exists()) {
String msg;
if(datFileN.startsWith("-") || datFileN.startsWith("/")) {
msg = "Error: \""+datFileN+"\""+nl+
" is neither a data file"+nl+
" nor a command-line switch."+nl+nl+
"Enter: \"java -jar Spana.jar -?\""+nl+"for a list of command-line options.";
} else {msg = "Error: \""+datFileN+"\""+nl+
" is not an existing data file.";
}
MsgExceptn.showErrMsg(this, msg, 1);
return false;
}
if(!datFile.canRead()) {
String msg = "Error - can not read from file:"+nl+" \""+datFileN+"\"";
System.out.println(msg);
javax.swing.JOptionPane.showMessageDialog(this,msg,
pc.progName,javax.swing.JOptionPane.ERROR_MESSAGE);
return false;
}
this.bringToFront();
String datFileNameFull;
try {datFileNameFull = datFile.getCanonicalPath();}
catch (java.io.IOException ex) {
try{datFileNameFull = datFile.getAbsolutePath();}
catch (Exception e) {datFileNameFull = datFile.getPath();}
}
datFile = new java.io.File(datFileNameFull);
pc.setPathDef(datFile);
// make sure the extension is lower case
datFileNameFull = datFileNameFull.substring(0, datFileNameFull.length()-3)+"dat";
// allow "save as" menu item
jMenu_Data_SaveAs.setEnabled(true);
// if we already have this file name in the list, just highlight it
if(dataFileArrList.size() >0) {
int datFile_found = -1;
for (int i = 0; i < dataFileArrList.size(); i++) {
if (dataFileArrList.get(i).equalsIgnoreCase(datFileNameFull)) {datFile_found = i; break;}
} // for i
if(datFile_found >-1) {
final int i = datFile_found;
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
jComboBox_Dat.setSelectedIndex(i);
}}); //invokeLater(Runnable)
return true;
}
} // if dataFileArrList.size() >0
// the file name was not in the list: add it
final String fileName = datFileNameFull;
dataFileArrList.add(fileName);
jComboBox_Dat.addItem(fileName);
jLabelBackgrd.setIcon(null);
jLabelBackgrd.setSize(ZERO);
jLabelBackgrd.setVisible(false);
jPanel1.setSize(PANELsize);
jPanel1.setVisible(true);
//jLabelBackgrd.setVisible(false);
//jPanel1.setVisible(true);
jLabel_Dat.setVisible(true);
jComboBox_Dat.setVisible(true);
jComboBox_Dat.setSelectedIndex(jComboBox_Dat.getItemCount()-1);
return true;
} // addDatFile(String)
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="removeDatFile(String)">
/** Removes a data file as an item in the combo box if the file is there.
* @param datFileN String containing the name of the data file
* @return true if ok (file name removed from the combo box), false otherwise. */
protected boolean removeDatFile(String datFileN) {
if(datFileN == null || datFileN.trim().length() <=0) {return false;}
if(pc.dbg) {System.out.println("---- removeDatFile("+datFileN+")");}
// if we already have this file name in the list, remove it
int datFile_found;
if(dataFileArrList.size() >0) {
synchronized (this) {
datFile_found = -1;
for (int i = 0; i < dataFileArrList.size(); i++) {
if (dataFileArrList.get(i).equalsIgnoreCase(datFileN)) {datFile_found = i; break;}
} // for i
if(datFile_found == -1) {return false;}
else {
dataFileArrList.remove(datFile_found);
jComboBox_Dat.removeItemAt(datFile_found);
if(jComboBox_Dat.getItemCount()<=0) {
jComboBox_Dat.setVisible(false);
jLabel_Dat.setVisible(false);
}
System.out.println("Warning: file \""+datFileN+"\""+nl+
" does not exist any more. Name removed from list.");
}
} // synchronized
} // if dataFileArrList.size() >0
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
int i = jComboBox_Dat.getItemCount();
if(i >0) {jComboBox_Dat.setSelectedIndex(i-1);}
else {jComboBox_Dat.setSelectedIndex(-1); jMenu_Data_SaveAs.setEnabled(false);}
}}); //invokeLater(Runnable)
return true;
} // removeDatFile(String)
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="dispatchArg(String)">
/** Execute the command-line arguments (one by one)
* @param arg String containing a command-line argument */
public void dispatchArg(String arg) {
if(arg == null) {return;}
if(arg.length() <=0) {doNotExit = true; return;}
System.out.println("Command-line argument = "+arg);
//these are handled in "main"
if(arg.equals("-dbg") || arg.equals("/dbg")) {doNotExit = true; return;}
if(arg.equals("-?") || arg.equals("/?") || arg.equals("?")
|| arg.equals("-help") || arg.equals("--help")) {
printInstructions();
doNotExit = true;
return;}
String pltFileName;
if(arg.length() >3) {
String arg0 = arg.substring(0, 2).toLowerCase();
// ---- starts with "-p"
if(arg0.startsWith("-p") || arg0.startsWith("/p")) {
if(arg.charAt(2) == '=' || arg.charAt(2) == ':') {
pltFileName = arg.substring(3);
if(pltFileName.length() > 2 && pltFileName.startsWith("\"") && pltFileName.endsWith("\"")) {
pltFileName = pltFileName.substring(1, arg.length()-1);
}
if(pltFileName.length()>4 && pltFileName.toLowerCase().endsWith(".plt")) {
if(pc.dbg){System.out.println("Print: "+pltFileName);}
displayPlotFile(pltFileName, "print");
return;
}
}
} // if starts with "-p"
} // if length >3
// ---- starts with "-ps"
if(arg.length() >4) {
String arg0 = arg.substring(0, 3).toLowerCase();
if(arg0.startsWith("-ps") || arg0.startsWith("/ps")) {
if(arg.charAt(3) == '=' || arg.charAt(3) == ':') {
pltFileName = arg.substring(4);
if(pltFileName.length() > 2 && pltFileName.startsWith("\"") && pltFileName.endsWith("\"")) {
pltFileName = pltFileName.substring(1, arg.length()-1);
}
if(pltFileName.length()>4 && pltFileName.toLowerCase().endsWith(".plt")) {
if(pc.dbg){System.out.println("Convert to PS: "+pltFileName);}
DiagrConvert.doIt(null, 2, pltFileName, pd, pc);
return;
}
}
} // if starts with "-ps"
} // if length > 4
// ---- starts with "-eps", "-pdf", etc
if(arg.length() >5) {
String arg0 = arg.substring(0, 4).toLowerCase();
pltFileName = arg.substring(5);
if(arg.charAt(0) == '-' || arg.charAt(0) == '/') {
String argType = arg0.substring(1,4);
boolean ok = false;
for(String ext : FORMAT_NAMES) {if(argType.equalsIgnoreCase(ext)) {ok = true; break;}}
if(argType.equals("eps") || argType.equals("pdf") || ok ) {
if(arg.charAt(4) == '=' || arg.charAt(4) == ':') {
if(pltFileName.length() > 2 && pltFileName.startsWith("\"") && pltFileName.endsWith("\"")) {
pltFileName = pltFileName.substring(1, arg.length()-1);
}
if(pltFileName.length()>4 && pltFileName.toLowerCase().endsWith(".plt")) {
if(pc.dbg){System.out.println("Convert to "
+arg0.substring(1,4).toUpperCase()+": "+pltFileName);}
if(argType.equals("pdf") || argType.equals("eps")) {
int typ = -1;
if(argType.equals("pdf")) {typ = 1;} else if(argType.equals("eps")) {typ = 3;}
DiagrConvert.doIt(null, typ, pltFileName, pd, pc);
} else {
displayPlotFile(pltFileName, argType);
}
return;
}
}
} // if eps/pdf/jpg/gif/png/emf
} // if it starts with "-" or "/"
} // if length > 5
if(arg.length() > 2 && arg.startsWith("\"") && arg.endsWith("\"")) {
arg = arg.substring(1, arg.length()-1);
}
if(arg.toLowerCase().endsWith(".plt")) {
this.minimize();
if(!displayPlotFile(arg, null)) {bringToFront();}
doNotExit = true;
return;
} else if(arg.toLowerCase().endsWith(".dat")) {
addDatFile(arg);
doNotExit = true;
return;
}
String msg = "Error: bad format for"+nl+
" command-line argument: \""+arg+"\"";
System.out.println(msg);
printInstructions();
javax.swing.JOptionPane.showMessageDialog(this,msg,
pc.progName,javax.swing.JOptionPane.ERROR_MESSAGE);
setCursorWait();
Thread hlp = new Thread() {@Override public void run(){
String[] a = {"SP_Batch_Mode_htm"};
lib.huvud.RunProgr.runProgramInProcess(null,ProgramConf.HELP_JAR,a,false,pc.dbg,pc.pathAPP);
try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec
catch (InterruptedException e) {}
setCursorDef();
}};//new Thread
hlp.start();
doNotExit = true;
} // dispatchArg(arg)
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="displayPlotFile(pltFileN, action)">
/** Displays a plot file either by<ul>
* <li>finding out if there is already an instance
* of <code>Disp</code> for this plot file,
* and if so, bringing the corresponding frame to front;</li>
* <li>if no previous instance of <code>Disp</code> corresponds
* to this file name: create a new instance of <code>Disp</code></li>
* @param pltFileN name of the plot file to display.
* @param action <ul>
* <li>"null" the file is only displayed.
* <li>"print" then the plot file is printed on the <u>default</u> printer.
* <li>"ps", "eps", "pdf", "gif", "jpg", "png", or "bmp",<br>
* then the plot file is exported to a file with the
* corresponding graphic format.</ul> */
boolean displayPlotFile(final String pltFileN, final String action) {
if(pltFileN == null || pltFileN.trim().length() <=0) {
this.setExtendedState(javax.swing.JFrame.NORMAL);
MsgExceptn.exception("Error: pltFileN empty in method \"displayPlotFile\"");
return false;}
if(!pltFileN.toLowerCase().endsWith(".plt")) {
this.setExtendedState(javax.swing.JFrame.NORMAL);
MsgExceptn.exception("Error: plot file name \""+pltFileN+"\""+nl+
" does not end with \".plt\"!");
return false;
}
if(pc.dbg) {System.out.println("diaplayPlotFile("+pltFileN+", "+action+")");}
java.io.File pltFile = new java.io.File(pltFileN);
if(!pltFile.exists()) {
this.bringToFront();
String msg;
if(pltFileN.startsWith("-") || pltFileN.startsWith("/")) {
msg = "Error: \""+pltFileN+"\""+nl+
" is neither a plot file"+nl+
" nor a command-line switch."+nl+nl+
"Enter: \"java -jar Spana.jar -?\""+nl+"for a list of command-line options.";
} else {msg = "Error: \""+pltFileN+"\""+nl+
" is not an existing plot file.";}
MsgExceptn.showErrMsg(this, msg, 1);
return false;}
if(!pltFile.canRead()) {
this.setExtendedState(javax.swing.JFrame.NORMAL);
String msg = "Error - can not read file:"+nl+
" \""+pltFile.getPath()+"\"";
MsgExceptn.showErrMsg(this, msg, 1);
return false;}
// is there an action?
boolean printFile = false;
boolean export = false;
final String actionLC;
if(action != null && action.trim().length() >0) {actionLC = action.toLowerCase();}
else {actionLC = null;}
if(actionLC != null) {
if(actionLC.equals("print")) {printFile = true;}
else {export = true;}
} // if actionLC !=null
setCursorWait();
// get file name
String pltFileNameFull;
try {pltFileNameFull = pltFile.getCanonicalPath();}
catch (java.io.IOException ex) {
try{pltFileNameFull = pltFile.getAbsolutePath();}
catch (Exception e) {pltFileNameFull = pltFile.getPath();}
}
// make sure the extension is lower case
pltFileNameFull = pltFileNameFull.substring(0, pltFileNameFull.length()-3)+"plt";
pltFile = new java.io.File(pltFileNameFull);
pc.setPathDef(pltFile);
// allow "save as" menu item
jMenu_Plot_SaveAs.setEnabled(true);
// if we already have this file name in the list,
// just show the diagram and highlight it in the list
Disp disp = null;
if(diagrArrList.size() > 0) {
if(pc.dbg) {System.out.println(" diagrArrList not empty.");}
int plt_found = -1;
for (int i = 0; i < diagrArrList.size(); i++) {
if(diagrArrList.get(i).diagrFullName.equalsIgnoreCase(pltFileNameFull)) {plt_found = i; break;}
} // for i
if(plt_found >-1) {
if(pc.dbg) {System.out.println(" plot file found in the list.");}
disp = showDiagr(plt_found, printFile);
if(disp != null) {
final int i = plt_found;
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
jComboBox_Plt_doNothing = true;
jComboBox_Plt.setSelectedIndex(i);
jComboBox_Plt_doNothing = false;
}}); //invokeLater(Runnable)
} // if disp != null
} // if plt_found >-1
} // if diagrArrList.size() >0
// else:
if(disp == null) {
if(pc.dbg) {System.out.println(" plot file not found in the list. Adding.");}
// The file name was not in the list: add it
// Create a new Diagram frame (window)
dispLocation.x = dispLocation.x + 20;
dispLocation.y = dispLocation.y + 20;
if(dispLocation.x > (screenSize.width-dispSize.width)) {dispLocation.x = 60;}
if(dispLocation.y > (screenSize.height-dispSize.height-20)) {dispLocation.y = 10;}
disp = new Disp(diagrPaintUtil, pc, pd);
disp.startPlotFile(pltFile);
if(disp.diagrName == null || disp.diagrName.trim().length() <=0) {setCursorDef(); return false;}
jComboBox_Plt_doNothing = true;
jComboBox_Plt.addItem(pltFileNameFull);
jComboBox_Plt_doNothing = false;
diagrArrList.add(disp);
// execute changes to frames in Swing's "Event Dispatching Thread"
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
jLabelBackgrd.setIcon(null);
jLabelBackgrd.setSize(ZERO);
jLabelBackgrd.setVisible(false);
jPanel1.setSize(PANELsize);
jPanel1.setVisible(true);
jLabel_Plt.setVisible(true);
jComboBox_Plt.setVisible(true);
int i = jComboBox_Plt.getItemCount()-1;
jComboBox_Plt_doNothing = true;
jComboBox_Plt.setSelectedIndex(i);
jComboBox_Plt_doNothing = false;
}}); //invokeLater(Runnable)
} // if disp = null
if(printFile) {
final Disp fDisp = disp;
setCursorWait();
disp.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
Thread printF = new Thread() {@Override public void run(){
if(pc.dbg){System.out.println("Printing file: "+pltFileN);}
fDisp.printDiagram(true);
waitingForPrinter = true;
// wake up any thread waiting for the printing to finish
notify_All();
}}; //new Thread
printF.start();
// make sure the file has been printed before going ahead
this.synchWaitPrinted();
waitingForPrinter = false;
} // íf printFile
else if(export) {
setCursorWait();
disp.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
disp.export(actionLC, false);
} // íf export
setCursorDef();
disp.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
return true;
} // displayPlotFile(String, String)
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="removePlotFile(String)">
/** Removes a plot file as an item in the combo box if the file is there.
* @param pltFileN String containing the name of the plot file
* @return true if ok (file name removed from the combo box), false otherwise. */
protected boolean removePltFile(String pltFileN) {
if(pltFileN == null || pltFileN.trim().length() <=0) {return false;}
if(pc.dbg) {System.out.println("---- removePltFile("+pltFileN+")");}
// if we already have this file name in the list, remove it
int plt_found;
if(diagrArrList.size() >0) {
plt_found = -1;
for (int i = 0; i < diagrArrList.size(); i++) {
if(diagrArrList.get(i).diagrFullName.equalsIgnoreCase(pltFileN)) {plt_found = i; break;}
}
if(plt_found == -1) {return false;}
else {
// close the diagram window if visible
Disp gotDisp = diagrArrList.get(plt_found);
java.awt.Frame[] f = Disp.getFrames();
int foundFrame=-1;
for(int i = 0; i<f.length ;i++){if(f[i].equals(gotDisp)) {foundFrame=i; break;}}
if(foundFrame>0) {
spf.bringToFront();
jPanel1.requestFocusInWindow();
if(gotDisp.isVisible()) {
int n= javax.swing.JOptionPane.showConfirmDialog(spf,
"Plot file \""+gotDisp.diagrFullName+"\""+nl+
"does NOT EXIST anymore!"+nl+nl+
"The diagram window will be closed"+nl+
"and the name removed from the list.",
pc.progName, javax.swing.JOptionPane.OK_CANCEL_OPTION, javax.swing.JOptionPane.ERROR_MESSAGE);
if(n != javax.swing.JOptionPane.OK_OPTION) {return false;}
if((gotDisp.getExtendedState() & javax.swing.JFrame.ICONIFIED)
== javax.swing.JFrame.ICONIFIED) // minimised?
{gotDisp.setExtendedState(javax.swing.JFrame.NORMAL);}
gotDisp.setVisible(false);
}
gotDisp.dispose();
} // if foundFrame
synchronized (this) {
diagrArrList.remove(plt_found);
jComboBox_Plt_doNothing = true;
jComboBox_Plt.removeItemAt(plt_found);
if(jComboBox_Plt.getItemCount()<=0) {
jComboBox_Plt.setVisible(false);
jLabel_Plt.setVisible(false);
}
jComboBox_Plt_doNothing = false;
} //synchronized
/* final int i = plt_found;
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
jComboBox_Plt_doNothing = true;
jComboBox_Plt.removeItemAt(i);
jComboBox_Plt_doNothing = false;
}}); //invokeLater(Runnable) */
System.out.println("Warning: file \""+pltFileN+"\""+nl+
" does not exist any more. Name removed from list.");
}
} // if dataFileArrList.size() >0
plt_found = jComboBox_Plt.getItemCount();
if(plt_found >0) {jComboBox_Plt.setSelectedIndex(plt_found-1);}
else {jComboBox_Plt.setSelectedIndex(-1); jMenu_Plot_SaveAs.setEnabled(false);}
return true;
} // removeDatFile(String)
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="modifyDataFile">
private void modifyDataFile() {
setCursorWait();
if(pc.dbg) {System.out.println("---- modifyDataFile()");}
//---- is the data-files combo box empty? if so, get a file name
if(dataFileArrList.size() <=0) {
String fileName = Util.getOpenFileName(this, pc.progName, true,
"Open data file", 5, null, pc.pathDef.toString());
if(fileName == null) {setCursorDef(); return;}
java.io.File f = new java.io.File(fileName);
if(f.exists() && (!f.canWrite() || !f.setWritable(true))) {
String msg = "Warning - the file:"+nl+
" \""+f.getPath()+"\""+nl+
"is write-protected!"+nl+nl+
"You will be able to save changes to another file,"+nl+
"but it might be best to make a non read-only copy"+nl+
"of this file before continuing...";
System.out.println(LINE+nl+msg+nl+LINE);
Object[] opt = {"Continue anyway", "Cancel"};
int m = javax.swing.JOptionPane.showOptionDialog(this, msg,
pc.progName, javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[1]);
if(m != javax.swing.JOptionPane.YES_OPTION) {setCursorDef(); return;}
}
if(!addDatFile(fileName)) {setCursorDef(); return;}
} // if dataFileArrList.size() <=0
setCursorWait();
// ---- get the file name selected in the combo box
final java.io.File datFile = new java.io.File(jComboBox_Dat.getSelectedItem().toString());
final boolean jMenu_Prefs_General_setEnabled = jMenu_Prefs_General.isEnabled();
final boolean jMenu_Run_Modif_setEnabled = jMenu_Run_Modif.isEnabled();
jMenu_Prefs_General.setEnabled(false);
jMenu_Run_Modif.setEnabled(false);
// ---- Start a thread
new javax.swing.SwingWorker<Void,Void>() {
@Override protected Void doInBackground() throws Exception {
modifyDiagramWindow = new ModifyChemSyst(pc, pd);
modifyDiagramWindow.startDataFile(datFile);
setCursorDef();
modifyDiagramWindow.waitForModifyChemSyst();
return null;
}
@Override protected void done(){
jMenu_Run_Modif.setEnabled(jMenu_Run_Modif_setEnabled);
jMenu_Prefs_General.setEnabled(jMenu_Prefs_General_setEnabled);
modifyDiagramWindow = null;
} // done()
}.execute(); // this returns inmediately,
// but the SwingWorker continues running...
} //modifyDataFile
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="run_Database">
private void run_Database() {
if(pc.dbg) {System.out.println("---- run_Database()");}
java.io.File f;
String msg = null;
if(createDataFileProg != null && createDataFileProg.trim().length()>0) {
f = new java.io.File(createDataFileProg);
if(!f.exists()) {
msg = "Error: the program to create input data files:"+nl+
" \""+createDataFileProg+"\""+nl+
" does not exist.";
}
} else {
msg = "Error:"+nl+
"no name given for the program"+nl+
"to create input data files.";
}
if(msg != null) {
MsgExceptn.exception(msg);
javax.swing.JOptionPane.showMessageDialog(this, msg, pc.progName,
javax.swing.JOptionPane.ERROR_MESSAGE);
setCursorDef();
return;
}
final boolean jMenu_Run_Database_setEnabled = jMenu_Run_Database.isEnabled();
final boolean jMenu_Data_New_setEnabled = jMenu_Data_New.isEnabled();
jMenu_Run_Database.setEnabled(false);
jMenu_Data_New.setEnabled(false);
setCursorWait();
Thread runDatabase = new Thread() {@Override public void run(){
// for some reason, at least in Windows XP,
// a command argument such as "a\" is transfored into: a"
String d = pc.pathDef.toString();
if(d.endsWith("\\")) {d = d + " ";} // avoid the combination: \"
String[] argsDatabase = new String[]{d};
boolean waitForCompletion = false;
if(pc.dbg) {System.out.println("---- runProgramInProcess:"+nl+
" "+createDataFileProg+nl+
" "+java.util.Arrays.toString(argsDatabase)+nl+
" wait = "+waitForCompletion+", dbg = "+pc.dbg+nl+
" path = "+pc.pathAPP);}
lib.huvud.RunProgr.runProgramInProcess(MainFrame.this, createDataFileProg, argsDatabase,
waitForCompletion, pc.dbg, pc.pathAPP);
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
jMenu_Run_Database.setEnabled(jMenu_Run_Database_setEnabled);
jMenu_Data_New.setEnabled(jMenu_Data_New_setEnabled);
}}); //invokeLater(Runnable)
try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec
catch (InterruptedException e) {}
setCursorDef();
}};
runDatabase.start();
} //run_Database()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="showDiagr">
/** Shows an instance of <code>Disp</code> that may have been hidden by the user.
* @param k int: the Disp instance in the array list <code>diagrArrList</code>
* @param printFile = true if the plot file is to be printed on the
* default printer.
* @return <code>true</code> if successful. */
private Disp showDiagr(int k, boolean printFile) {
// check for erroneous situations
if (k <0 || diagrArrList.size() <=0 || jComboBox_Plt.getItemCount()<=0) {return null;}
if(pc.dbg) {System.out.println("---- showDiagr("+k+")");}
Disp gotDisp = diagrArrList.get(k);
java.awt.Frame[] f = Disp.getFrames();
int foundFrame=-1;
for(int i = 0; i<f.length ;i++){
if(f[i].equals(gotDisp)) {foundFrame=i; break;}
} // for i
if(foundFrame>0) {
if((gotDisp.getExtendedState() & javax.swing.JFrame.ICONIFIED)
== javax.swing.JFrame.ICONIFIED) // minimised?
{gotDisp.setExtendedState(javax.swing.JFrame.NORMAL);}
gotDisp.setVisible(true);
gotDisp.toFront();
gotDisp.requestFocus();
gotDisp.reloadPlotFile();
gotDisp.repaint();
if(printFile) {gotDisp.printDiagram(true);}
return gotDisp;
} // if foundFrame
// if foundFrame <=0
synchronized (this) {
diagrArrList.remove(k);
jComboBox_Plt_doNothing = true;
jComboBox_Plt.removeItemAt(k);
if(jComboBox_Plt.getItemCount()<=0) {
jComboBox_Plt.setVisible(false);
jLabel_Plt.setVisible(false);
}
jComboBox_Plt_doNothing = false;
} //synchronized
return null;
} // showDiagr(k)
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="read-write INI file">
/** Reads program settings saved when the program was previously closed.
* Exceptions are reported both to the console (if there is one) and to a dialog.<br>
* Reads the ini-file in:<ul>
* <li> the Application Path if found there.</ul>
* If not found in the application path, or if the file is write-protected:<ul>
* <li> in %HomeDrive%%HomePath% if found there; if write-protected also
* <li> in %Home% if found there; if write-protected also
* <li> in the user's home directory (system dependent) if it is found there
* otherwise: give a warning and create a new file. Note: except for the
* installation directory, the ini-file will be writen in a sub-folder
* named "<code>.config\eq-diag</code>".
* <p>
* This method also saves the ini-file after reading it and after
* checking its contents. The file is written in the application path if
* "saveIniFileToApplicationPathOnly" is <code>true</code>. Otherwise,
* if an ini-file was read and if it was not write-protected, then program
* options are saved in that file on exit. If no ini-file was found,
* an ini file is created on the first non-write protected directory of
* those listed above. */
private void readIni() {
// start by getting the defaults (this is needed because the arrays must be initialised)
iniDefaults(); // needed to initialise arrays etc.
if(pc.dbg) {System.out.println("--- readIni() --- reading ini-file(s)");}
fileIni = null;
java.io.File p = null, fileRead = null, fileINInotRO = null;
boolean ok, readOk = false;
//--- check the application path ---//
if(pc.pathAPP == null || pc.pathAPP.trim().length() <=0) {
if(pc.saveIniFileToApplicationPathOnly) {
String name = "\"null\"" + SLASH + FileINI_NAME;
MsgExceptn.exception("Error: can not read ini file"+nl+
" "+name+nl+
" (application path is \"null\")");
return;
}
} else { //pathApp is defined
String dir = pc.pathAPP;
if(dir.endsWith(SLASH)) {dir = dir.substring(0, dir.length()-1);}
fileIni = new java.io.File(dir + SLASH + FileINI_NAME);
p = new java.io.File(dir);
if(!p.exists()) {
p = null; fileIni = null;
if(pc.saveIniFileToApplicationPathOnly) {
MsgExceptn.exception("Error: can not read ini file:"+nl+
" "+fileIni.getPath()+nl+
" (application path does not exist)");
return;
}
}
}
success: {
// --- first read the ini-file from the application path, if possible
if(pc.saveIniFileToApplicationPathOnly && fileIni != null) {
// If the ini-file must be written to the application path,
// then try to read this file, even if the file is write-protected
fileINInotRO = fileIni;
if(fileIni.exists()) {
readOk = readIni2(fileIni);
if(readOk) {fileRead = fileIni;}
}
break success;
} else { // not saveIniFileToApplicationPathOnly or fileINI does not exist
if(fileIni != null && fileIni.exists()) {
readOk = readIni2(fileIni);
if(readOk) {fileRead = fileIni;}
if(fileIni.canWrite() && fileIni.setWritable(true)) {
fileINInotRO = fileIni;
if(readOk) {break success;}
}
} else { //ini-file null or does not exist
if(fileIni != null && p != null) {
try{ // can we can write to this directory?
java.io.File tmp = java.io.File.createTempFile("spana",".tmp", p);
ok = tmp.exists();
if(ok) {tmp.delete();}
} catch (java.io.IOException ex) {ok = false;}
if(pc.dbg) {
String s; if(ok) {s="";} else {s="NOT ";}
System.out.println(" can "+s+"write files to path: "+p.getAbsolutePath());
}
// file does not exist, but the path is not write-protected
if(ok && fileINInotRO == null) {fileINInotRO = fileIni;}
}
}
}
// --- an ini-file has not been read in the application path
// and saveIniFileToApplicationPathOnly = false. Read the ini-file from
// the user's path, if possible
java.util.ArrayList<String> dirs = new java.util.ArrayList<String>(5);
String homeDrv = System.getenv("HOMEDRIVE");
String homePath = System.getenv("HOMEPATH");
if(homePath != null && homePath.trim().length() >0 && !homePath.startsWith(SLASH)) {
homePath = SLASH + homePath;
}
if(homeDrv != null && homeDrv.trim().length() >0 && homeDrv.endsWith(SLASH)) {
homeDrv = homeDrv.substring(0, homeDrv.length()-1);
}
if((homeDrv != null && homeDrv.trim().length() >0)
&& (homePath != null && homePath.trim().length() >0)) {
p = new java.io.File(homeDrv+homePath);
if(p.exists()) {dirs.add(p.getAbsolutePath());}
}
String home = System.getenv("HOME");
if(home != null && home.trim().length() >0) {
p = new java.io.File(home);
if(p.exists()) {dirs.add(p.getAbsolutePath());}
}
home = System.getProperty("user.home");
if(home != null && home.trim().length() >0) {
p = new java.io.File(home);
if(p.exists()) {dirs.add(p.getAbsolutePath());}
}
for(String t : dirs) {
if(t.endsWith(SLASH)) {t = t.substring(0, t.length()-1);}
fileIni = new java.io.File(t+SLASH+".config"+SLASH+"eq-diagr"+SLASH+FileINI_NAME);
if(fileIni.exists()) {
readOk = readIni2(fileIni);
if(readOk) {fileRead = fileIni;}
if(fileIni.canWrite() && fileIni.setWritable(true)) {
if(fileINInotRO == null) {fileINInotRO = fileIni;}
if(readOk) {break success;}
}
} else { //ini-file does not exist
try{ // can we can write to this directory?
p = new java.io.File(t);
java.io.File tmp = java.io.File.createTempFile("spana",".tmp", p);
ok = tmp.exists();
if(ok) {tmp.delete();}
} catch (java.io.IOException ex) {ok = false;}
if(pc.dbg) {
String s; if(ok) {s="";} else {s="NOT ";}
System.out.println(" can "+s+"write files to path: "+t);
}
// file does not exist, but the path is not write-protected
if(ok && fileINInotRO == null) {fileINInotRO = fileIni;}
}
} // for(dirs)
} //--- success?
if(pc.dbg) {
String s;
if(fileINInotRO != null) {s=fileINInotRO.getAbsolutePath();} else {s="\"null\"";}
System.out.println(" ini-file not read-only = "+s);
if(fileRead != null) {s=fileRead.getAbsolutePath();} else {s="\"null\"";}
System.out.println(" ini-file read = "+s);
}
if(!readOk) {
String msg = "Failed to read any INI-file."+nl+
"Default program settings will be used.";
MsgExceptn.showErrMsg(spf, msg, 1);
}
if(fileINInotRO != null && fileINInotRO != fileRead) {
ok = saveIni(fileINInotRO);
if(ok) {fileIni = fileINInotRO;} else {fileIni = null;}
}
} // readIni()
private boolean readIni2(java.io.File f) {
String msg;
System.out.flush();
System.out.println("Reading ini-file: \""+f.getPath()+"\"");
java.util.Properties propertiesIni= new java.util.Properties();
java.io.FileInputStream fis = null;
java.io.BufferedReader r = null;
boolean ok = true;
try {
fis = new java.io.FileInputStream(f);
r = new java.io.BufferedReader(new java.io.InputStreamReader(fis,"UTF8"));
propertiesIni.load(r);
} catch (java.io.FileNotFoundException e) {
String t = "Warning: file Not found: \""+f.getPath()+"\""+nl+
"using default parameter values.";
System.out.println(t);
if(!this.isVisible()) {this.setVisible(true);}
javax.swing.JOptionPane.showMessageDialog(spf, t, pc.progName, javax.swing.JOptionPane.INFORMATION_MESSAGE);
ok = false;
}
catch (java.io.IOException e) {
msg = "Error: \""+e.toString()+"\""+nl+
" while loading INI-file:"+nl+
" \""+f.getPath()+"\"";
System.out.println(msg);
if(!this.isVisible()) {this.setVisible(true);}
javax.swing.JOptionPane.showMessageDialog(spf, msg, pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE);
ok = false;
} // catch loading-exception
try {if(r != null) {r.close();} if(fis != null) {fis.close();}}
catch (java.io.IOException e) {
msg ="Error: \""+e.toString()+"\""+nl+
" while closing INI-file:"+nl+
" \""+f.getPath()+"\"";
System.out.println(msg);
if(!this.isVisible()) {this.setVisible(true);}
javax.swing.JOptionPane.showMessageDialog(spf, msg, pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE);
ok = false;
}
finally {
try {if(r != null) {r.close();} if(fis != null) {fis.close();}}
catch (java.io.IOException e) {
msg = "Error: \""+e.toString()+"\""+nl+
" while closing INI-file:"+nl+
" \""+f.getPath()+"\"";
System.out.println(msg);
if(!this.isVisible()) {this.setVisible(true);}
javax.swing.JOptionPane.showMessageDialog(spf, msg, pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE);
}
}
if(!ok) {return ok;}
try {
locationFrame.x = Integer.parseInt(propertiesIni.getProperty("Location_left"));
locationFrame.y = Integer.parseInt(propertiesIni.getProperty("Location_top"));
msgFrameSize.width = Integer.parseInt(propertiesIni.getProperty("LogFrame_Width"));
msgFrameSize.height = Integer.parseInt(propertiesIni.getProperty("LogFrame_Height"));
locationMsgFrame.x = Integer.parseInt(propertiesIni.getProperty("LogFrame_left"));
locationMsgFrame.y = Integer.parseInt(propertiesIni.getProperty("LogFrame_top"));
dispSize.width = Integer.parseInt(propertiesIni.getProperty("Disp_Width"));
dispSize.height = Integer.parseInt(propertiesIni.getProperty("Disp_Height"));
dispLocation.x = Integer.parseInt(propertiesIni.getProperty("Disp_left"));
dispLocation.y = Integer.parseInt(propertiesIni.getProperty("Disp_top"));
diagrPaintUtil.keepAspectRatio = Boolean.parseBoolean(propertiesIni.getProperty("Disp_KeepAspectRatio","false"));
diagrPaintUtil.fixedSize = Boolean.parseBoolean(propertiesIni.getProperty("Disp_FixedSize","false"));
diagrPaintUtil.fixedSizeWidth = Float.parseFloat(propertiesIni.getProperty("Disp_FixedSizeWidth"));
diagrPaintUtil.fixedSizeHeight = Float.parseFloat(propertiesIni.getProperty("Disp_FixedSizeHeight"));
diagrPaintUtil.fontFamily = Integer.parseInt(propertiesIni.getProperty("Disp_FontFamily"));
diagrPaintUtil.fontStyle = Integer.parseInt(propertiesIni.getProperty("Disp_FontStyle"));
diagrPaintUtil.fontSize = Integer.parseInt(propertiesIni.getProperty("Disp_FontSize"));
String anti = propertiesIni.getProperty("Disp_AntialiasingText");
if (anti.toLowerCase().equals("on")) {diagrPaintUtil.antiAliasingText = 1;}
else if (anti.toLowerCase().equals("default")) {diagrPaintUtil.antiAliasingText = 2;}
else {diagrPaintUtil.antiAliasingText = 0;}
anti = propertiesIni.getProperty("Disp_Antialiasing");
if (anti.toLowerCase().equals("on")) {diagrPaintUtil.antiAliasing = 1;}
else if (anti.toLowerCase().equals("default")) {diagrPaintUtil.antiAliasing = 2;}
else {diagrPaintUtil.antiAliasing = 0;}
diagrPaintUtil.penThickness = Float.parseFloat(propertiesIni.getProperty("Disp_PenThickness"));
if(pc.pathDef.length() >0) {pc.pathDef.delete(0, pc.pathDef.length());}
pc.pathDef.append(propertiesIni.getProperty("defaultPath"));
txtEditor = propertiesIni.getProperty("txtEditor");
pathSedPredom = propertiesIni.getProperty("pathSedPredom");
createDataFileProg = propertiesIni.getProperty("createDataFileProg");
pd.advancedVersion = Boolean.parseBoolean(propertiesIni.getProperty("advancedVersion","false"));
int red, green, blue;
for(int ii=0; ii < DiagrPaintUtility.MAX_COLOURS; ii++) {
String[] colrs = propertiesIni.getProperty("Disp_Colour["+ii+"]").split(",");
if (colrs.length > 0) {red =Integer.parseInt(colrs[0]);} else {red=0;}
if (colrs.length > 1) {green =Integer.parseInt(colrs[1]);} else {green=0;}
if (colrs.length > 2) {blue =Integer.parseInt(colrs[2]);} else {blue=0;}
red=Math.max(0, Math.min(255, red));
green=Math.max(0, Math.min(255, green));
blue=Math.max(0, Math.min(255, blue));
diagrPaintUtil.colours[ii] = new java.awt.Color(red,green,blue);
} // for ii
diagrPaintUtil.colourType = Integer.parseInt(propertiesIni.getProperty("Disp_ColourType"));
diagrPaintUtil.printColour = Boolean.parseBoolean(propertiesIni.getProperty("Disp_PrintColour","true"));
diagrPaintUtil.printHeader = Boolean.parseBoolean(propertiesIni.getProperty("Disp_PrintHeader","true"));
diagrPaintUtil.textWithFonts = Boolean.parseBoolean(propertiesIni.getProperty("Disp_TextWithFonts","true"));
diagrPaintUtil.printPenThickness = Float.parseFloat(propertiesIni.getProperty("Disp_PrintPenThickness"));
diagrPaintUtil.useBackgrndColour = Boolean.parseBoolean(propertiesIni.getProperty("Disp_UseBackgrndColour","false"));
String[] colrs = propertiesIni.getProperty("Disp_BackgroundColour").split(",");
if (colrs.length > 0) {red =Integer.parseInt(colrs[0]);} else {red=0;}
if (colrs.length > 1) {green =Integer.parseInt(colrs[1]);} else {green=0;}
if (colrs.length > 2) {blue =Integer.parseInt(colrs[2]);} else {blue=0;}
red=Math.max(0, Math.min(255, red));
green=Math.max(0, Math.min(255, green));
blue=Math.max(0, Math.min(255, blue));
diagrPaintUtil.backgrnd = new java.awt.Color(red,green,blue);
pd.fractionThreshold = Float.parseFloat(propertiesIni.getProperty("Disp_FractionThreshold"));
pd.keepFrame = Boolean.parseBoolean(propertiesIni.getProperty("Calc_keepFrame","false"));
pd.SED_nbrSteps = Integer.parseInt(propertiesIni.getProperty("Calc_SED_nbrSteps"));
pd.SED_tableOutput = Boolean.parseBoolean(propertiesIni.getProperty("Calc_SED_tableOutput","false"));
pd.Predom_nbrSteps = Integer.parseInt(propertiesIni.getProperty("Calc_Predom_nbrSteps"));
pd.ionicStrength = Double.parseDouble(propertiesIni.getProperty("Calc_ionicStrength"));
pd.actCoeffsMethod = Integer.parseInt(propertiesIni.getProperty("Calc_activityCoefficientsMethod"));
pd.pathSIT = propertiesIni.getProperty("Calc_pathSIT");
pd.aquSpeciesOnly = Boolean.parseBoolean(propertiesIni.getProperty("Calc_Predom_aquSpeciesOnly","false"));
pd.reversedConcs = Boolean.parseBoolean(propertiesIni.getProperty("Calc_allowReversedConcRanges","false"));
pd.useEh = Boolean.parseBoolean(propertiesIni.getProperty("Calc_useEh","true"));
pd.calcDbg = Boolean.parseBoolean(propertiesIni.getProperty("Calc_dbg","false"));
pd.calcDbgHalta = Integer.parseInt(propertiesIni.getProperty("Calc_dbgHalta"));
pd.tolHalta = Double.parseDouble(propertiesIni.getProperty("Calc_tolerance"));
pd.tblExtension = propertiesIni.getProperty("Calc_tableFileExt");
String t = propertiesIni.getProperty("Calc_tableFieldSeparatorChar");
if(t !=null && t.length()>=2 && t.substring(0,1).equalsIgnoreCase("\\t")) {
pd.tblFieldSeparator = '\u0009';
} else {
if(t != null) {pd.tblFieldSeparator = t.charAt(0);} else {pd.tblFieldSeparator = ';';}
}
t = propertiesIni.getProperty("Calc_tableCommentLineStart");
if(t !=null) {pd.tblCommentLineStart = t;}
else {pd.tblCommentLineStart = "\"";}
t = propertiesIni.getProperty("Calc_tableCommentLineEnd");
if(t !=null) {pd.tblCommentLineEnd = t;}
else {pd.tblCommentLineEnd = "\"";}
pd.diagrConvertSizeX = Integer.parseInt(propertiesIni.getProperty("Convert_SizeX"));
pd.diagrConvertSizeY = Integer.parseInt(propertiesIni.getProperty("Convert_SizeY"));
pd.diagrConvertMarginB = Float.parseFloat(propertiesIni.getProperty("Convert_MarginBottom"));
pd.diagrConvertMarginL = Float.parseFloat(propertiesIni.getProperty("Convert_MarginLeft"));
pd.diagrConvertFont = Integer.parseInt(propertiesIni.getProperty("Convert_Font"));
pd.diagrConvertEPS = Boolean.parseBoolean(propertiesIni.getProperty("Convert_EPS","false"));
pd.diagrExportType = propertiesIni.getProperty("Export_To");
pd.diagrExportSize = Integer.parseInt(propertiesIni.getProperty("Export_Size"));
pd.temperature = Double.parseDouble(propertiesIni.getProperty("Calc_temperature","25"));
pd.pressure = Double.parseDouble(propertiesIni.getProperty("Calc_pressure","1"));
String units = propertiesIni.getProperty("Calc_concentration_units","0");
if(units.length() <2) {units = units+" ";}
pd.concentrationUnits = Integer.parseInt(units.substring(0,2).trim());
pd.concentrationNotation = Integer.parseInt(propertiesIni.getProperty("Calc_concentration_notation","0").substring(0,1));
pd.drawNeutralPHinPourbaix = Boolean.parseBoolean(propertiesIni.getProperty("Calc_draw_pH_line","false"));
pd.kth = Boolean.parseBoolean(propertiesIni.getProperty("KTH_settings","false"));
pd.jarClassLd = Boolean.parseBoolean(propertiesIni.getProperty("Calc_load_jar-files","true"));
} catch (Exception e) {
msg = "Error: \""+e.toString()+"\""+nl+
" while reading INI-file:"+nl+
" \""+f.getPath()+"\""+nl+nl+
"Setting default program parameters.";
System.out.println(msg);
if(!this.isVisible()) {this.setVisible(true);}
javax.swing.JOptionPane.showMessageDialog(spf, msg, pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE);
ok = false;
}
try{
String s = propertiesIni.getProperty("lookAndFeel").trim().toLowerCase();
if(s.startsWith("system")) {laf = 1;}
else if(s.startsWith("cross")) {laf = 2;}
else {laf = 0;}
} catch (Exception e) {laf = 0;}
if(pc.dbg) {System.out.println("Finished reading ini-file");}
System.out.flush();
checkIniValues();
return ok;
} // readIni2()
private void checkIniValues() {
System.out.flush();
System.out.println(LINE+nl+"Checking ini-values.");
if(locationFrame.x < -1 || locationFrame.y < -1) {
locationFrame.x = Math.max(0, (screenSize.width - this.getWidth() ) / 2);
locationFrame.y = Math.max(0, (screenSize.height - this.getHeight() ) / 2);
}
// check Default Path
java.io.File currentDir = new java.io.File(pc.pathDef.toString());
if(!currentDir.exists()) {
pc.setPathDef(); // set Default Path = Start Directory
} // if !currentDir.exists()
java.io.File f;
// check the editor
if(txtEditor == null || txtEditor.trim().length() <=0) {
String t;
if(windows) {
t = windir;
if(t != null && t.endsWith(SLASH)) {t = t.substring(0, t.length()-1);}
if(t != null) {t = t + SLASH + "Notepad.exe";} else {t = "Notepad.exe";}
txtEditor = t;
} else if(System.getProperty("os.name").startsWith("Mac OS")) {
//txtEditor = "/Applications/TextEdit.app/Contents/MacOS/TextEdit";
txtEditor = "/usr/bin/open -t";
} else { //assume Unix or Linux
txtEditor = "/usr/bin/gedit";
}
System.out.println("Note: setting editor = \""+txtEditor+"\"");
}
f = new java.io.File(txtEditor);
if(!System.getProperty("os.name").startsWith("Mac OS") && !f.exists()) {
System.out.println("Warning: the text editor \""+txtEditor+"\""+nl+
" in the INI-file does not exist.");
}
// check path to SED/PREDOM
java.io.File d = null;
String dir = pc.pathAPP;
if(dir != null && dir.endsWith(SLASH)) {dir = dir.substring(0, dir.length()-1);}
if(pathSedPredom != null && pathSedPredom.trim().length() >0) {
d = new java.io.File(pathSedPredom);
if(!d.exists() || !d.isDirectory()) {
System.out.println("Warning: path \""+pathSedPredom+"\""+nl+
" in the INI-file does not exist (or is not a directory).");
d = null;
}
}
if(d == null || !d.exists() || !d.isDirectory()) {
if(dir != null && dir.trim().length()>0) {
pathSedPredom = dir;
} else {
pathSedPredom = System.getProperty("user.dir");
}
d = new java.io.File(pathSedPredom);
}
String msg = null;
if(!Div.progSEDexists(d)) {msg = " SED";}
if(!Div.progPredomExists(d)) {if(msg == null) {msg = " Predom";} else {msg = "s SED and Predom";}}
if(msg != null) {
if(pathSedPredom != null) {
System.out.println("Warning: directory \""+pathSedPredom+"\""+nl+
" in the INI-file does not contain program"+msg);
if(pc.pathAPP != null && pc.pathAPP.trim().length()>0) {
pathSedPredom = pc.pathAPP;
} else {
pathSedPredom = System.getProperty("user.dir");
}
}
}
if(createDataFileProg != null && createDataFileProg.trim().length() >0) {
f = new java.io.File(createDataFileProg);
} else {f = null;}
if(f==null || !f.exists()) {
String s = createDataFileProg;
if(s==null) {s="null";}
System.out.println("Warning: file \""+s+"\""+nl+
" (the program to create input data files)"+nl+
" given in the INI-file does not exist.");
getDatabaseProgr(true);
}
d = null;
if(pd.pathSIT != null && pd.pathSIT.trim().length() >0) {
d = new java.io.File(pd.pathSIT);
if(!d.exists() || !d.isDirectory()) {
System.out.println("Warning: path \""+pd.pathSIT+"\""+nl+
" where file \"SIT-coefficients.dta\" should be found"+nl+
" in the INI-file does not exist (or is not a directory).");
d = null;
}
}
if(d == null || !d.exists() || !d.isDirectory()) {
if(pc.pathAPP != null && pc.pathAPP.trim().length()>0) {
pd.pathSIT = pc.pathAPP;
} else {
pd.pathSIT = System.getProperty("user.dir");
}
}
String sit = pd.pathSIT;
if(sit != null && sit.trim().length()>0) {
if(sit.endsWith(SLASH)) {sit = sit.substring(0, sit.length()-1);}
sit = sit +SLASH+ "SIT-coefficients.dta";
f = new java.io.File(sit);
if(!f.exists()) {
System.out.println("Warning: directory \""+pd.pathSIT+"\""+nl+
" in the INI-file does not contain file: \"SIT-coefficients.dta\".");
}
}
// progLocation, dispLocation and dispSize are checked
// each time these windows are loaded
diagrPaintUtil.fixedSizeHeight = Math.max(1f,Math.min(99f,diagrPaintUtil.fixedSizeHeight));
diagrPaintUtil.fixedSizeWidth = Math.max(1f,Math.min(99f,diagrPaintUtil.fixedSizeWidth));
diagrPaintUtil.colourType = Math.max(0,Math.min(2,diagrPaintUtil.colourType));
diagrPaintUtil.antiAliasing = Math.max(0,Math.min(2,diagrPaintUtil.antiAliasing));
diagrPaintUtil.antiAliasingText = Math.max(0,Math.min(2,diagrPaintUtil.antiAliasingText));
diagrPaintUtil.penThickness = Math.max(0.2f, Math.min(diagrPaintUtil.penThickness,10f));
diagrPaintUtil.printPenThickness = Math.max(1f, Math.min(diagrPaintUtil.printPenThickness,5f));
diagrPaintUtil.fontFamily = Math.max(0,Math.min(diagrPaintUtil.fontFamily,4));
diagrPaintUtil.fontStyle = Math.max(0,Math.min(diagrPaintUtil.fontStyle,2));
diagrPaintUtil.fontSize = Math.max(1,Math.min(diagrPaintUtil.fontSize,72));
pd.fractionThreshold = Math.max(0.001f, Math.min(pd.fractionThreshold,0.1f));
boolean backgrndDark = false;
if (Math.sqrt(Math.pow(diagrPaintUtil.backgrnd.getRed(),2) +
Math.pow(diagrPaintUtil.backgrnd.getGreen(),2) +
Math.pow(diagrPaintUtil.backgrnd.getBlue(),2)) < 221)
{backgrndDark = true;}
for(int i=0; i < DiagrPaintUtility.MAX_COLOURS; i++) {
if(twoColoursEqual(diagrPaintUtil.backgrnd,diagrPaintUtil.colours[i])) {
if(pc.dbg) {System.out.print("checkIniValues(): color["+i+"] is \"equal\" to background color. Dark background = "+backgrndDark+nl+
" setting color["+i+"] to ");}
if(backgrndDark) {
diagrPaintUtil.colours[i] = new java.awt.Color(200,200,200);
if(pc.dbg) {System.out.println("(200,200,200)");}
} else {
diagrPaintUtil.colours[i] = new java.awt.Color(100,100,100);}
if(pc.dbg) {System.out.println("(100,100,100)");}
} // if twoColoursEqual
} // for i
pd.SED_nbrSteps = Math.max(MNSTP, Math.min(MXSTP,pd.SED_nbrSteps));
pd.Predom_nbrSteps = Math.max(MNSTP, Math.min(MXSTP,pd.Predom_nbrSteps));
pd.ionicStrength = Math.max(-100, Math.min(1000,pd.ionicStrength));
if(!Double.isNaN(pd.temperature)) {pd.temperature = Math.max(-50, Math.min(400,pd.temperature));} else {pd.temperature = 25;}
if(!Double.isNaN(pd.pressure)) {pd.pressure = Math.max(1., Math.min(10000,pd.pressure));} else {pd.pressure = 1.;}
pd.actCoeffsMethod = Math.max(0, Math.min(2,pd.actCoeffsMethod));
pd.concentrationUnits = Math.max(-1, Math.min(2,pd.concentrationUnits));
pd.concentrationNotation = Math.max(0, Math.min(2,pd.concentrationNotation));
pd.calcDbgHalta = Math.max(0, Math.min(6,pd.calcDbgHalta));
pd.tolHalta = Math.max(1e-9, Math.min(0.01, pd.tolHalta));
boolean found = false;
if(pd.tblExtension != null && pd.tblExtension.length() == 3) {
for(String tblExtension_type : pd.tblExtension_types) {
if(pd.tblExtension.equalsIgnoreCase(tblExtension_type)) {found = true; break;}
}
}
if(!found) {pd.tblExtension = pd.tblExtension_types[0];}
for(int i=0; i < pd.tblFieldSeparator_types.length; i++) {
if(pd.tblFieldSeparator ==
pd.tblFieldSeparator_types[i]) {found = true; break;}
}
if(!found) {pd.tblFieldSeparator = pd.tblFieldSeparator_types[0];}
pd.diagrConvertSizeX = Math.max(20,Math.min(300,pd.diagrConvertSizeX));
pd.diagrConvertSizeY = Math.max(20,Math.min(300,pd.diagrConvertSizeY));
pd.diagrConvertMarginB = Math.max(-5,Math.min(21,pd.diagrConvertMarginB));
pd.diagrConvertMarginL = Math.max(-5,Math.min(21,pd.diagrConvertMarginL));
pd.diagrConvertFont = Math.max(0, Math.min(3,pd.diagrConvertFont));
boolean fnd = false;
for(String t : FORMAT_NAMES) {if(t.equalsIgnoreCase(pd.diagrExportType)) {fnd = true; break;}}
if(!fnd) {pd.diagrExportType = FORMAT_NAMES[0];}
pd.diagrExportSize = Math.max(2, Math.min(5000,pd.diagrExportSize));
laf = Math.min(2,Math.max(0,laf));
System.out.println(LINE);
System.out.flush();
} // checkIniValues()
public static boolean twoColoursEqual (java.awt.Color A, java.awt.Color B) {
int diff = Math.abs(A.getRed()-B.getRed()) +
Math.abs(A.getGreen()-B.getGreen()) +
Math.abs(A.getBlue()-B.getBlue());
return diff <= 120;
} // twoColoursEqual
public void iniDefaults() {
// Set default values for program variables
if (pc.dbg) {
System.out.flush();
System.out.println("Setting default parameter values (\"ini\"-values).");
}
locationFrame.x = Math.max(0, (screenSize.width - this.getWidth() ) / 2);
locationFrame.y = Math.max(0, (screenSize.height - this.getHeight() ) / 2);
msgFrameSize.width = 500; msgFrameSize.height = 400;
locationMsgFrame.x = 80; locationMsgFrame.y = 30;
dispSize.width = 400; dispSize.height = 350;
dispLocation.x = 60; dispLocation.y = 30;
// set the default path to the "current directory" (from where the program is started)
pc.setPathDef(); // set Default Path = Start Directory
pd.advancedVersion = false;
txtEditor = null;
java.io.File f;
if(windows) {
String dir = windir;
if(dir != null) {
if(dir.endsWith(SLASH)) {dir = dir.substring(0, dir.length()-1);}
txtEditor = dir + SLASH + "Notepad.exe";
f = new java.io.File(txtEditor);
if(!f.exists()) {txtEditor = "Notepad.exe";}
} else {txtEditor = "Notepad.exe";}
} else if(System.getProperty("os.name").startsWith("Mac OS")) {
//txtEditor = "/Applications/TextEdit.app";
txtEditor = "/usr/bin/open -t";
} else { //assume Unix or Linux
txtEditor = "/usr/bin/gedit";
f = new java.io.File(txtEditor);
if(!f.exists()) {txtEditor = null;}
}
String dir = pc.pathAPP;
if(dir != null && dir.trim().length()>0) {
pathSedPredom = dir;
} else {
pathSedPredom = System.getProperty("user.dir");
}
getDatabaseProgr(false);
pd.actCoeffsMethod = 2;
pd.advancedVersion = false;
pd.aquSpeciesOnly = false;
pd.calcDbg = false;
pd.calcDbgHalta = Chem.DBGHALTA_DEF;
pd.tolHalta = Chem.TOL_HALTA_DEF;
pd.ionicStrength = 0;
pd.keepFrame = false;
if(pc.pathAPP != null && pc.pathAPP.trim().length()>0) {pd.pathSIT = pc.pathAPP;} else {pd.pathSIT = ".";}
pd.reversedConcs = false;
pd.drawNeutralPHinPourbaix = false;
pd.concentrationUnits = 0;
pd.concentrationNotation = 0;
pd.temperature = 25;
pd.pressure = 1.;
pd.useEh = true;
pd.SED_nbrSteps = NSTEPS_DEF;
pd.SED_tableOutput = false;
pd.Predom_nbrSteps = NSTEPS_DEF*2;
pd.tblExtension = "csv";
pd.tblFieldSeparator = ';';
pd.tblCommentLineStart = "\"";
pd.tblCommentLineEnd = "\"";
diagrPaintUtil.keepAspectRatio = false;
diagrPaintUtil.fixedSize = false;
diagrPaintUtil.fixedSizeHeight = 15f;
diagrPaintUtil.fixedSizeWidth = 21f;
diagrPaintUtil.antiAliasing = 1; diagrPaintUtil.antiAliasingText = 1;
diagrPaintUtil.colourType = 0;
diagrPaintUtil.printColour = true;
diagrPaintUtil.penThickness = 1f;
diagrPaintUtil.printHeader = true;
diagrPaintUtil.printPenThickness = 1f;
diagrPaintUtil.fontFamily = 1; // 0 = SansSerif
diagrPaintUtil.fontStyle = 0; // 0 = plain
diagrPaintUtil.fontSize = 9;
diagrPaintUtil.useBackgrndColour = false;
diagrPaintUtil.backgrnd = java.awt.Color.white;
diagrPaintUtil.textWithFonts = true;
pd.fractionThreshold = 0.03f;
pd.diagrConvertSizeX = 90;
pd.diagrConvertSizeY = 90;
pd.diagrConvertMarginB = 1f;
pd.diagrConvertMarginL = 1f;
pd.diagrConvertPortrait = true;
pd.diagrConvertHeader = true;
pd.diagrConvertColors = true;
pd.diagrConvertFont = 2;
pd.diagrConvertEPS = false;
pd.diagrExportType = FORMAT_NAMES[0];
pd.diagrExportSize = 1000;
pd.kth = false;
pd.jarClassLd = true;
} // iniDefaults()
private void getDatabaseProgr(final boolean print) {
String dir = pc.pathAPP;
if(dir != null && dir.endsWith(SLASH)) {dir = dir.substring(0, dir.length()-1);}
java.io.File f;
if(dir == null || dir.trim().length()<=0) {
createDataFileProg = "DataBase.jar";
} else {
createDataFileProg = dir + SLASH + "DataBase.jar";
f = new java.io.File(createDataFileProg);
if(!f.exists() && System.getProperty("os.name").startsWith("Mac OS")) {
createDataFileProg = dir +SLASH+".."+SLASH+".."+SLASH+".."+SLASH+".."+SLASH+"DataBase.app"
+SLASH+"Contents"+SLASH+"Resources"+SLASH+"Java"+SLASH+"DataBase.jar";
f = new java.io.File(createDataFileProg);
try{createDataFileProg = f.getCanonicalPath();}
catch (java.io.IOException ex) {createDataFileProg = f.getAbsolutePath();}
}
}
f = new java.io.File(createDataFileProg);
if(!f.exists()) {
if(print) {System.out.println("Warning: could NOT find the database program: "+nl+" "+createDataFileProg);}
createDataFileProg = null;
} else if(print) {System.out.println("Setting database program = "+nl+" "+createDataFileProg);}
}
/** Save program settings.
* Exceptions are reported both to the console (if there is one) and to a dialog */
private boolean saveIni(java.io.File f) {
if(f == null) {return false;}
if(pc.dbg) {System.out.println("--- saveIni("+f.getAbsolutePath()+")");}
boolean ok = true;
String msg = null;
if(f.exists() && (!f.canWrite() || !f.setWritable(true))) {
msg = "Error - can not write ini-file:"+nl+
" \""+f.getAbsolutePath()+"\""+nl+
"The file is read-only.";
}
if(!f.exists() && !f.getParentFile().exists()) {
ok = f.getParentFile().mkdirs();
if(!ok) {
msg = "Error - can not create directory:"+nl+
" \""+f.getParent()+"\""+nl+
"Can not write ini-file.";
}
}
if(msg != null) {
MsgExceptn.showErrMsg(spf, msg, 2);
return false;
}
java.util.Properties propertiesIni = new SortedProperties();
if (this != null && this.isVisible()
&& locationFrame.x > -1 && locationFrame.y > -1) {
if(this.getExtendedState()==javax.swing.JFrame.ICONIFIED // minimised?
|| this.getExtendedState()==javax.swing.JFrame.MAXIMIZED_BOTH)
{this.setExtendedState(javax.swing.JFrame.NORMAL);}
locationFrame.x = this.getLocation().x;
locationFrame.y = this.getLocation().y;
}
propertiesIni.setProperty("<program_version>", VERS);
propertiesIni.setProperty("defaultPath", pc.pathDef.toString());
if(txtEditor != null) {
propertiesIni.setProperty("txtEditor",txtEditor);
} else {propertiesIni.setProperty("txtEditor","");}
if(pathSedPredom != null) {
propertiesIni.setProperty("pathSedPredom",pathSedPredom);
} else {propertiesIni.setProperty("pathSedPredom","");}
if(createDataFileProg != null) {
propertiesIni.setProperty("createDataFileProg",createDataFileProg);
} else {propertiesIni.setProperty("createDataFileProg","");}
if(laf==2) {propertiesIni.setProperty("lookAndFeel", "CrossPlatform (may be 'CrossPlatform', 'System' or 'Default')");}
else if(laf==1) {propertiesIni.setProperty("lookAndFeel", "System (may be 'CrossPlatform', 'System' or 'Default')");}
else {propertiesIni.setProperty("lookAndFeel", "Default (may be 'CrossPlatform', 'System' or 'Default')");}
propertiesIni.setProperty("advancedVersion",String.valueOf(pd.advancedVersion));
propertiesIni.setProperty("Calc_keepFrame",String.valueOf(pd.keepFrame));
propertiesIni.setProperty("Calc_SED_nbrSteps",String.valueOf(pd.SED_nbrSteps));
propertiesIni.setProperty("Calc_SED_tableOutput",String.valueOf(pd.SED_tableOutput));
propertiesIni.setProperty("Calc_Predom_nbrSteps",String.valueOf(pd.Predom_nbrSteps));
propertiesIni.setProperty("Calc_Predom_aquSpeciesOnly",String.valueOf(pd.aquSpeciesOnly));
propertiesIni.setProperty("Calc_allowReversedConcRanges",String.valueOf(pd.reversedConcs));
propertiesIni.setProperty("Calc_ionicStrength",String.valueOf(pd.ionicStrength));
propertiesIni.setProperty("Calc_temperature",String.valueOf(pd.temperature));
propertiesIni.setProperty("Calc_pressure",String.valueOf(pd.pressure));
propertiesIni.setProperty("Calc_activityCoefficientsMethod", String.valueOf(pd.actCoeffsMethod));
propertiesIni.setProperty("Calc_useEh",String.valueOf(pd.useEh));
propertiesIni.setProperty("Calc_draw_pH_line",String.valueOf(pd.drawNeutralPHinPourbaix));
propertiesIni.setProperty("Calc_concentration_units", String.valueOf(pd.concentrationUnits)+" (may be 0 (\"molal\"), 1 (\"mol/kg_w\"), 2 (\"M\") or -1 (\"\"))");
propertiesIni.setProperty("Calc_concentration_notation", String.valueOf(pd.concentrationNotation)+" (may be 0 (\"no choice\"), 1 (\"scientific\") or 2 (\"engineering\"))");
propertiesIni.setProperty("Calc_dbg",String.valueOf(pd.calcDbg));
propertiesIni.setProperty("Calc_dbgHalta",String.valueOf(pd.calcDbgHalta));
propertiesIni.setProperty("Calc_tolerance",String.valueOf(pd.tolHalta));
propertiesIni.setProperty("Calc_pathSIT",pd.pathSIT);
propertiesIni.setProperty("Calc_tableFileExt",pd.tblExtension);
propertiesIni.setProperty("Calc_tableFieldSeparatorChar",Character.toString(pd.tblFieldSeparator));
if(pd.tblCommentLineStart != null && pd.tblCommentLineStart.length() >0) {
propertiesIni.setProperty("Calc_tableCommentLineStart",pd.tblCommentLineStart);
} else {propertiesIni.setProperty("Calc_tableCommentLineStart","");}
if(pd.tblCommentLineEnd != null && pd.tblCommentLineEnd.length() >0) {
propertiesIni.setProperty("Calc_tableCommentLineEnd",pd.tblCommentLineEnd);
} else {propertiesIni.setProperty("Calc_tableCommentLineEnd","");}
propertiesIni.setProperty("Disp_Width", String.valueOf(dispSize.width));
propertiesIni.setProperty("Disp_Height", String.valueOf(dispSize.height));
propertiesIni.setProperty("Disp_left", String.valueOf(dispLocation.x));
propertiesIni.setProperty("Disp_top", String.valueOf(dispLocation.y));
if(msgFrame != null) {msgFrameSize = msgFrame.getSize(); locationMsgFrame = msgFrame.getLocation();}
propertiesIni.setProperty("LogFrame_Width", String.valueOf(msgFrameSize.width));
propertiesIni.setProperty("LogFrame_Height", String.valueOf(msgFrameSize.height));
propertiesIni.setProperty("LogFrame_left", String.valueOf(locationMsgFrame.x));
propertiesIni.setProperty("LogFrame_top", String.valueOf(locationMsgFrame.y));
propertiesIni.setProperty("Location_left", String.valueOf(locationFrame.x));
propertiesIni.setProperty("Location_top", String.valueOf(locationFrame.y));
propertiesIni.setProperty("Disp_KeepAspectRatio", String.valueOf(diagrPaintUtil.keepAspectRatio));
propertiesIni.setProperty("Disp_FixedSize", String.valueOf(diagrPaintUtil.fixedSize));
propertiesIni.setProperty("Disp_FixedSizeWidth", String.valueOf(diagrPaintUtil.fixedSizeWidth));
propertiesIni.setProperty("Disp_FixedSizeHeight", String.valueOf(diagrPaintUtil.fixedSizeHeight));
propertiesIni.setProperty("Disp_FontFamily", String.valueOf(diagrPaintUtil.fontFamily));
propertiesIni.setProperty("Disp_FontStyle", String.valueOf(diagrPaintUtil.fontStyle));
propertiesIni.setProperty("Disp_FontSize", String.valueOf(diagrPaintUtil.fontSize));
propertiesIni.setProperty("Disp_TextWithFonts", String.valueOf(diagrPaintUtil.textWithFonts));
propertiesIni.setProperty("Disp_FractionThreshold", String.valueOf(pd.fractionThreshold));
String anti;
if (diagrPaintUtil.antiAliasingText == 1) {anti="on";}
else if (diagrPaintUtil.antiAliasingText == 2) {anti="default";}
else {anti="off";}
propertiesIni.setProperty("Disp_AntialiasingText", anti);
if (diagrPaintUtil.antiAliasing == 1) {anti="on";}
else if (diagrPaintUtil.antiAliasing == 2) {anti="default";}
else {anti="off";}
propertiesIni.setProperty("Disp_Antialiasing", anti);
propertiesIni.setProperty("Disp_ColourType", String.valueOf(diagrPaintUtil.colourType));
propertiesIni.setProperty("Disp_PrintColour", String.valueOf(diagrPaintUtil.printColour));
propertiesIni.setProperty("Disp_PrintHeader", String.valueOf(diagrPaintUtil.printHeader));
propertiesIni.setProperty("Disp_PrintPenThickness", String.valueOf(diagrPaintUtil.printPenThickness));
propertiesIni.setProperty("Disp_PenThickness", String.valueOf(diagrPaintUtil.penThickness));
propertiesIni.setProperty("Disp_UseBackgrndColour",String.valueOf(diagrPaintUtil.useBackgrndColour));
propertiesIni.setProperty("Disp_BackgroundColour",diagrPaintUtil.backgrnd.getRed()+","+
diagrPaintUtil.backgrnd.getGreen()+","+
diagrPaintUtil.backgrnd.getBlue());
for(int ii=0; ii < DiagrPaintUtility.MAX_COLOURS; ii++) {
propertiesIni.setProperty("Disp_Colour["+ii+"]",diagrPaintUtil.colours[ii].getRed()+","+
diagrPaintUtil.colours[ii].getGreen()+","+
diagrPaintUtil.colours[ii].getBlue());
}
propertiesIni.setProperty("Convert_SizeX", String.valueOf(pd.diagrConvertSizeX));
propertiesIni.setProperty("Convert_SizeY", String.valueOf(pd.diagrConvertSizeY));
propertiesIni.setProperty("Convert_MarginBottom", String.valueOf(pd.diagrConvertMarginB));
propertiesIni.setProperty("Convert_MarginLeft", String.valueOf(pd.diagrConvertMarginL));
propertiesIni.setProperty("Convert_Portrait", String.valueOf(pd.diagrConvertPortrait));
propertiesIni.setProperty("Convert_Font", String.valueOf(pd.diagrConvertFont));
propertiesIni.setProperty("Convert_Colour", String.valueOf(pd.diagrConvertColors));
propertiesIni.setProperty("Convert_Header", String.valueOf(pd.diagrConvertHeader));
propertiesIni.setProperty("Convert_EPS", String.valueOf(pd.diagrConvertEPS));
propertiesIni.setProperty("Export_To", pd.diagrExportType);
propertiesIni.setProperty("Export_Size", String.valueOf(pd.diagrExportSize));
propertiesIni.setProperty("KTH_settings", String.valueOf(pd.kth));
propertiesIni.setProperty("Calc_load_jar-files", String.valueOf(pd.jarClassLd));
System.out.println("Saving ini-file: \""+f.getPath()+"\"");
java.io.FileOutputStream fos = null;
java.io.Writer w = null;
try{
fos = new java.io.FileOutputStream(f);
w = new java.io.BufferedWriter(new java.io.OutputStreamWriter(fos,"UTF8"));
// INI-section needed by PortableApps java launcher
char[] b = new char[7 + nl.length()];
b[0]='['; b[1]='S'; b[2]='p'; b[3]='a'; b[4]='n'; b[5]='a'; b[6]=']';
for(int j =0; j < nl.length(); j++) {b[7+j] = nl.charAt(j);}
w.write(b);
//
propertiesIni.store(w,null);
if (pc.dbg) {System.out.println("Written: \""+f.getPath()+"\"");}
} catch (java.io.IOException e) {
msg = "Error: \""+e.toString()+"\""+nl+
" while writing INI-file:"+nl+
" \""+f.getPath()+"\"";
if(!this.isVisible()) {this.setVisible(true);}
MsgExceptn.showErrMsg(spf,msg,1);
ok = false;
}
finally {
try {if(w != null) {w.close();} if(fos != null) {fos.close();}}
catch (java.io.IOException e) {
msg = e.getMessage()+nl+
" trying to write ini-file: \""+f.getPath()+"\"";
if(!this.isVisible()) {this.setVisible(true);}
MsgExceptn.showErrMsg(spf, msg, 1);
ok = false;
}
} //finally
return ok;
} // saveIni()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="printInstructions">
public static void printInstructions() {
System.out.flush();
String msg = "Possible commands are:"+nl+
" -dbg (output debugging information to the messages window)"+nl+
" data-file-name (add data file to list, name must end with \".dat\")"+nl+
" plot-file-name (display plot file, name must end with \".plt\")"+nl+
" -p=plot-file-name (print plot file)"+nl+
" -pdf=plot-file-name (convert plot file to \"pdf\" format)"+nl+
" -ps=plot-file-name (convert plot file to \"PostScript\")"+nl+
" -eps=plot-file-name (convert plot file to encapsulated \"PostScript\")"+nl+
" -ext=plot-file-name (export plot file to \"ext\" format"+nl+
" where \"ext\" is one of: bmp, jpg or png, and perhaps gif."+nl+
" Plot-file-name must end with \".plt\")."+nl+
"Enclose file names with double quotes (\"\") it they contain blank space."+nl+
"Example: java -jar Spana.jar \"plt\\Fe 25.plt\" -p:\"plt\\Fe I=3M\"";
System.out.println(msg);
System.out.flush();
System.err.println(LINE); // show the message window
System.err.flush();
} //printInstructions()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="copyTextFile">
static boolean copyTextFile(java.io.File source, java.io.File target, boolean dbg){
if (dbg) {System.out.println("--- copyTextFile ---");}
if(source == null) {
MsgExceptn.exception("\"source\" file is \"null\"");
return false;
}
if(target == null) {
MsgExceptn.exception("\"target\" file is \"null\"");
return false;
}
if (dbg) {System.out.println(" source: \""+source.getAbsolutePath()+"\""+nl+
" target: \""+target.getAbsolutePath()+"\"");}
java.io.BufferedReader in;
try{
in = new java.io.BufferedReader(
new java.io.InputStreamReader(new java.io.FileInputStream(source),"UTF8"));
}
catch (Exception ex) {
MsgExceptn.exception("Error: "+ex.getMessage()+nl+
"with \"source\" file: \""+source.getAbsolutePath()+"\"");
return false;
}
java.io.BufferedWriter out;
try {
out = new java.io.BufferedWriter(
new java.io.OutputStreamWriter(
new java.io.FileOutputStream(target),"UTF8"));
}
catch (Exception ex) {
MsgExceptn.exception("Error: "+ex.toString()+nl+
"with \"target\" file: \""+target.getAbsolutePath()+"\"");
return false;
}
try {
String aLine;
while ((aLine = in.readLine()) != null) {
//Process each line and add output to destination file
out.write(aLine);
out.newLine();
out.flush();
}
} catch (Exception ex) {
MsgExceptn.exception("Error: "+ex.toString()+nl+
"while reading \"source\" file: \""+source.getAbsolutePath()+"\","+nl+
"and writing \"target\" file: \""+target.getAbsolutePath()+"\".");
return false;
}
finally {
// do not forget to close the buffer reader
try{in.close();} catch (java.io.IOException ex) {}
// close buffer writer
try{out.flush(); out.close();} catch (java.io.IOException ex) {}
}
if (dbg) {System.out.println("--- copyTextFile: OK");}
return true;
}
//</editor-fold>
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="TransferHandler for Drag-and-Drop">
//==========================================================================
// Drag and Drop:
/** Use <code>tHandler</code> to allow Drag-and-Drop of files;
* for example:
* <pre> jPanel.setTransferHandler(tHandler);</pre>
* Where <code>jPanel</code> is a component.
* Then change in method <code>importData</code> the code using the
* list of file names obtained through the Drop action.
*/
public static javax.swing.TransferHandler tHandler =
new javax.swing.TransferHandler(null) {@Override
public boolean importData(javax.swing.JComponent component,
java.awt.datatransfer.Transferable t) {
// Import file names from the Drop action
// First check for "javaFileListFlavor"
if (!canImport(component, t.getTransferDataFlavors()))
{return false;}
// Get the list of file names
try {
@SuppressWarnings("unchecked")
java.util.List<java.io.File> list =
(java.util.List<java.io.File>)t.
getTransferData(java.awt.datatransfer.DataFlavor.javaFileListFlavor);
for(java.io.File f : list) {
String fileName;
try {fileName = f.getCanonicalPath();}
catch (java.io.IOException ex) {
try {fileName = f.getAbsolutePath();}
catch (Exception e) {fileName = f.getPath();}
}
final String fileN = fileName;
if(fileName.toLowerCase().endsWith(".plt")) {
spf.displayPlotFile(fileN, null);
} // if ".plt"
if(fileName.toLowerCase().endsWith(".dat")) {
spf.addDatFile(fileN);
} // if ".dat"
} //for f : lists
} //try
catch (java.awt.datatransfer.UnsupportedFlavorException e) {return false;}
catch (java.io.IOException ex) {return false;}
return true;
} // importData(JComponent, Transferable)
@Override
public boolean canImport(javax.swing.JComponent component,
java.awt.datatransfer.DataFlavor[] flavors) {
// check for "javaFileListFlavor"
boolean hasFileFlavor = false;
for(java.awt.datatransfer.DataFlavor flavor : flavors) {
if(java.awt.datatransfer.DataFlavor.javaFileListFlavor.equals(flavor)) {
hasFileFlavor = true;
return true;
}
}
return false;
} // canImport(JComponent, DataFlavor[])
}; // TransferHandler tHandler
//==========================================================================
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="main">
/** Starts "Spana". If another instance is running, send the command
* arguments to the other instance and quit, otherwise, start a MainFrame.
* @param args the command line arguments
*/
public static void main(final String[] args) {
System.out.println("Starting Spana - version "+VERS);
//---- deal with some command-line arguments
boolean dbg = false;
if(args.length > 0) {
for(String arg : args) {
if (arg.equalsIgnoreCase("-dbg") || arg.equalsIgnoreCase("/dbg")) {
System.out.println("Command-line argument = \"" + arg + "\"");
dbg = true;
}
if (arg.equals("-?") || arg.equals("/?") || arg.equals("?")
|| arg.equals("-help") || arg.equals("--help")) {
System.out.println("Command-line argument = \"" + arg + "\"");
printInstructions();
} //if args[] = "?"
}
}
//---- is there another instance already running?
if((new OneInstance()).findOtherInstance(args, 56055, "Spana", dbg)) {
System.out.println("---- Already running.");
return;
}
//---- create a local instance of ProgramConf.
// Contains information read from the configuration file.
final ProgramConf pc = new ProgramConf("Spana");
pc.dbg = dbg;
//---- all output to System.err will show the error in a frame.
if(msgFrame == null) {
msgFrame = new RedirectedFrame(500, 400, pc);
msgFrame.setVisible(dbg);
System.out.println("Spana diagram - version "+VERS);
}
//---- is it Windows?
if(System.getProperty("os.name").toLowerCase().startsWith("windows")) {
windows = true;
// get windows directory
try{windir = System.getenv("windir");}
catch (Exception ex) {
System.out.println("Warning: could not get environment variable \"windir\"");
windir = null;
}
if(windir != null && windir.trim().length() <= 0) {windir = null;}
if(windir != null) {
java.io.File f = new java.io.File(windir);
if(!f.exists() || !f.isDirectory()) {windir = null;}
}
}
//---- set Look-And-Feel
// laf = 0
try{
if(windows) {
javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
System.out.println("--- setLookAndFeel(System);");
} else {
javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getCrossPlatformLookAndFeelClassName());
System.out.println("--- setLookAndFeel(CrossPlatform);");
}
}
catch (Exception ex) {System.out.println("Error: "+ex.getMessage());}
//---- for JOptionPanes set the default button to the one with the focus
// so that pressing "enter" behaves as expected:
javax.swing.UIManager.put("Button.defaultButtonFollowsFocus", Boolean.TRUE);
// and make the arrow keys work:
Util.configureOptionPane();
//---- get the Application Path
pc.pathAPP = Main.getPathApp();
//---- read the CFG-file
java.io.File fileNameCfg;
String dir = pc.pathAPP;
if(dir != null && dir.trim().length()>0) {
if(dir.endsWith(SLASH)) {dir = dir.substring(0, dir.length()-1);}
fileNameCfg = new java.io.File(dir + SLASH + pc.progName+".cfg");
} else {fileNameCfg = new java.io.File(pc.progName+".cfg");}
ProgramConf.read_cfgFile(fileNameCfg, pc);
if(!pc.dbg) {pc.dbg=dbg;}
msgFrame.setVisible(pc.dbg);
java.text.DateFormat dateFormatter =
java.text.DateFormat.getDateTimeInstance
(java.text.DateFormat.DEFAULT, java.text.DateFormat.DEFAULT, java.util.Locale.getDefault());
java.util.Date today = new java.util.Date();
String dateOut = dateFormatter.format(today);
System.out.println("\"Spana\" started: "+dateOut);
System.out.println(LINE);
//---- set Default Path = Start Directory
pc.setPathDef();
//---- show the main window
java.awt.EventQueue.invokeLater(new Runnable() {@Override public void run() {
// create the frame object
spf = new MainFrame(pc, msgFrame); //send configuration data
// process command-line arguments etc
spf.start(args);
} // run
}); // invokeLater
} //main(args)
// </editor-fold>
public static MainFrame getInstance() {return spf;}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JCheckBoxMenuItem jCheckBoxMenuDebug;
private javax.swing.JComboBox<String> jComboBox_Dat;
private javax.swing.JComboBox<String> jComboBox_Plt;
private javax.swing.JLabel jLabelBackgrd;
private javax.swing.JLabel jLabel_Dat;
private javax.swing.JLabel jLabel_Plt;
private javax.swing.JMenuBar jMenuBar;
private javax.swing.JMenuItem jMenu_Data_AddToList;
private javax.swing.JMenuItem jMenu_Data_Edit;
private javax.swing.JMenuItem jMenu_Data_Modif;
private javax.swing.JMenuItem jMenu_Data_New;
private javax.swing.JMenuItem jMenu_Data_Open;
private javax.swing.JMenuItem jMenu_Data_SaveAs;
private javax.swing.JMenu jMenu_File;
private javax.swing.JMenu jMenu_File_Data;
private javax.swing.JMenuItem jMenu_File_Exit;
private javax.swing.JMenu jMenu_File_Plot;
private javax.swing.JMenu jMenu_Help;
private javax.swing.JMenuItem jMenu_Help_About;
private javax.swing.JMenuItem jMenu_Help_Contents;
private javax.swing.JMenuItem jMenu_Plot_Open;
private javax.swing.JMenuItem jMenu_Plot_SaveAs;
private javax.swing.JMenu jMenu_Prefs;
private javax.swing.JMenuItem jMenu_Prefs_Calcs;
private javax.swing.JMenuItem jMenu_Prefs_Diagr;
private javax.swing.JMenuItem jMenu_Prefs_General;
private javax.swing.JMenu jMenu_Run;
private javax.swing.JMenuItem jMenu_Run_Cmd;
private javax.swing.JMenuItem jMenu_Run_Database;
private javax.swing.JMenuItem jMenu_Run_FileExpl;
private javax.swing.JMenuItem jMenu_Run_MakeDiagr;
private javax.swing.JMenuItem jMenu_Run_Modif;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPopupMenu.Separator jSeparator1;
private javax.swing.JPopupMenu.Separator jSeparatorCmd;
private javax.swing.JPopupMenu.Separator jSeparatorMake;
// End of variables declaration//GEN-END:variables
}
| 152,963 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
ErrMsgBox.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Predom/src/predominanceAreaDiagrams/ErrMsgBox.java | package predominanceAreaDiagrams;
/** Displays a "message box" modal dialog with an "OK" button and a title.
* The message is displayed in a text area (non-editable),
* which can be copied and pasted elsewhere.
*
* Copyright (C) 2014-2016 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class ErrMsgBox {
private static final String nl = System.getProperty("line.separator");
//<editor-fold defaultstate="collapsed" desc="ErrMsgBox(msg, title)">
/** Displays a "message box" modal dialog with an "OK" button and a title.
* The message is displayed in a text area (non-editable),
* which can be copied and pasted elsewhere.
* @param msg will be displayed in a text area, and line breaks may be
* included, for example: <code>new MsgBox("Very\nbad!",""); </code>
* If null or empty nothing is done.
* @param title for the dialog. If null or empty, "Error:" is used
* @see #showErrMsg(java.awt.Component, java.lang.String, int) showErrMsg
* @version 2015-July-14 */
public ErrMsgBox(String msg, String title) {
if(msg == null || msg.trim().length() <=0) {
System.out.println("--- MsgBox: null or empty \"message\".");
return;
}
//--- Title
if(title == null || title.length() <=0) {title = " Error:";}
java.awt.Frame frame = new java.awt.Frame(title);
//--- Icon
String iconName = "images/ErrMsgBx.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
if(imgURL != null) {frame.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());}
else {System.out.println("--- Error in MsgBox constructor: Could not load image = \""+iconName+"\"");}
frame.pack();
//--- centre Window frame on Screen
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int left; int top;
left = Math.max(55, (screenSize.width - frame.getWidth() ) / 2);
top = Math.max(10, (screenSize.height - frame.getHeight()) / 2);
frame.setLocation(Math.min(screenSize.width-100, left), Math.min(screenSize.height-100, top));
//---
final String msgText = wrapString(msg.trim(),80);
//System.out.println("--- MsgBox:"+nl+msgText+nl+"---");
frame.setVisible(true);
//javax.swing.JOptionPane.showMessageDialog(frame, msg, title, javax.swing.JOptionPane.ERROR_MESSAGE);
MsgBoxDialog msgBox = new MsgBoxDialog(frame, msgText, title, true);
msgBox.setVisible(true); // becase the dialog is modal, statements below will wait
msgBox.dispose();
frame.setVisible(false);
frame.dispose();
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="private class MsgBoxDialog">
private static class MsgBoxDialog extends java.awt.Dialog {
private java.awt.Button ok;
private java.awt.Panel p;
private final java.awt.TextArea text;
/** Creates new form NewDialog */
public MsgBoxDialog(java.awt.Frame parent, String msg, String title, boolean modal) {
super(parent, (" "+title), modal);
addWindowListener(new java.awt.event.WindowAdapter() {
@Override public void windowClosing(java.awt.event.WindowEvent evt) {
MsgBoxDialog.this.setVisible(false);
}
});
setLayout(new java.awt.BorderLayout());
p = new java.awt.Panel();
p.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER));
ok = new java.awt.Button();
// find out the size of the message (width and height)
final int wMax = 85; final int hMax=20;
final int wMin = 5; final int hMin = 1;
int w = wMin;
int h=hMin; int i=0; int j=wMin;
final String eol = "\n"; char c;
final String nl = System.getProperty("line.separator");
while (true) {
c = msg.charAt(i);
String s = String.valueOf(c);
if(s.equals(eol) || s.equals(nl)) {
h++; j=wMin;
} else {
j++; w = Math.max(j,w);
}
i++;
if(i >= msg.length()-1) {break;}
}
// create a text area
int scroll = java.awt.TextArea.SCROLLBARS_NONE;
if(w > wMax && h <= hMax) {scroll = scroll & java.awt.TextArea.SCROLLBARS_HORIZONTAL_ONLY;}
if(h > hMax && w <= wMax) {scroll = scroll & java.awt.TextArea.SCROLLBARS_VERTICAL_ONLY;}
if(w > wMax && h > hMax) {scroll = java.awt.TextArea.SCROLLBARS_BOTH;}
w = Math.min(Math.max(w,10),wMax);
h = Math.min(h,hMax);
text = new java.awt.TextArea(msg, h, w, scroll);
text.setEditable(false);
//text.setBackground(java.awt.Color.white);
text.addKeyListener(new java.awt.event.KeyAdapter() {
@Override public void keyPressed(java.awt.event.KeyEvent evt) {
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER
|| evt.getKeyCode() == java.awt.event.KeyEvent.VK_ESCAPE) {closeDialog();}
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_TAB) {ok.requestFocusInWindow();}
}
});
text.setBackground(java.awt.Color.WHITE);
text.setFont(new java.awt.Font("monospaced", java.awt.Font.PLAIN, 12));
add(text, java.awt.BorderLayout.CENTER);
ok.setLabel("OK");
ok.addActionListener(new java.awt.event.ActionListener() {
@Override public void actionPerformed(java.awt.event.ActionEvent evt) {
closeDialog();
}
});
ok.addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER
|| evt.getKeyCode() == java.awt.event.KeyEvent.VK_ESCAPE) {closeDialog();}
}
});
p.add(ok);
add(p, java.awt.BorderLayout.SOUTH);
pack();
ok.requestFocusInWindow();
//--- centre Window frame on Screen
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int left; int top;
left = Math.max(55, (screenSize.width - getWidth() ) / 2);
top = Math.max(10, (screenSize.height - getHeight()) / 2);
setLocation(Math.min(screenSize.width-100, left), Math.min(screenSize.height-100, top));
}
private void closeDialog() {this.setVisible(false);}
} // private static class MsgBoxDialog
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="private wrapString">
/** Returns an input string, with lines that are longer than <code>maxLength</code>
* word-wrapped and indented. *
* @param s input string
* @param maxLength if an input line is longer than this length,
* the line will be word-wrapped at the first white space after <code>maxLength</code>
* and indented with 4 spaces
* @return string with long-lines word-wrapped
*/
private static String wrapString(String s, int maxLength) {
String deliminator = "\n";
StringBuilder result = new StringBuilder();
StringBuffer wrapLine;
int lastdelimPos;
for (String line : s.split(deliminator, -1)) {
if(line.length()/(maxLength+1) < 1) {
result.append(line).append(deliminator);
}
else { //line too long, try to split it
wrapLine = new StringBuffer();
lastdelimPos = 0;
for (String token : line.trim().split("\\s+", -1)) {
if (wrapLine.length() - lastdelimPos + token.length() > maxLength) {
if(wrapLine.length()>0) {wrapLine.append(deliminator);}
wrapLine.append(" ").append(token);
lastdelimPos = wrapLine.length() + 1;
} else {
if(wrapLine.length() <=0) {wrapLine.append(token);}
else {wrapLine.append(" ").append(token);}
}
}
result.append(wrapLine).append(deliminator);
}
}
return result.toString();
}
// </editor-fold>
}
| 8,992 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
Main.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Predom/src/predominanceAreaDiagrams/Main.java | package predominanceAreaDiagrams;
/** Checks for all the jar-libraries needed.
* <br>
* Copyright (C) 2014-2016 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class Main {
private static final String progName = "Program PREDOM";
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
private static boolean started = false;
private static final String SLASH = java.io.File.separator;
/** Check that all the jar-libraries needed do exist.
* @param args the command line arguments */
public static void main(String[] args) {
// ---- are all jar files needed there?
if(!doJarFilesExist()) {return;}
// ---- ok!
Predom.main(args);
} //main
//<editor-fold defaultstate="collapsed" desc="doJarFilesExist">
/** Look in the running jar file's classPath Manifest for any other "library"
* jar-files listed under "Class-path".
* If any of these jar files does not exist display an error message
* (and an error Frame) and continue.
* @return true if all needed jar files exist; false otherwise.
* @version 2016-Aug-03 */
private static boolean doJarFilesExist() {
java.io.File libJarFile, libPathJarFile;
java.util.jar.JarFile runningJar = getRunningJarFile();
// runningJar.getName() = C:\Eq-Calc_Java\dist\Prog.jar
if(runningJar != null) { // if running within Netbeans there will be no jar-file
java.util.jar.Manifest manifest;
try {manifest = runningJar.getManifest();}
catch (java.io.IOException ex) {
manifest = null;
String msg = "Warning: no manifest found in the application's jar file:"+nl+
"\""+runningJar.getName()+"\"";
ErrMsgBox emb = new ErrMsgBox(msg, progName);
//this will return true;
}
if(manifest != null) {
String classPath = manifest.getMainAttributes().getValue("Class-Path");
if(classPath != null && classPath.length() > 0) {
// this will be a list of space-separated names
String[] jars = classPath.split("\\s+"); //regular expression to match one or more spaces
if(jars.length >0) {
java.io.File[] rootNames = java.io.File.listRoots();
boolean isPathAbsolute;
String pathJar;
String p = getPathApp(); // get the application's path
for(String jar : jars) { // loop through all jars needed
libJarFile = new java.io.File(jar);
if(libJarFile.exists()) {continue;}
isPathAbsolute = false;
for(java.io.File f : rootNames) {
if(jar.toLowerCase().startsWith(f.getAbsolutePath().toLowerCase())) {
isPathAbsolute = true;
break;}
}
if(!isPathAbsolute) { // add the application's path
if(!p.endsWith(SLASH) && !jar.startsWith(SLASH)) {p = p+SLASH;}
pathJar = p + jar;
} else {pathJar = jar;}
libPathJarFile = new java.io.File(pathJar);
if(libPathJarFile.exists()) {continue;}
libPathJarFile = new java.io.File(libPathJarFile.getAbsolutePath());
ErrMsgBox emb = new ErrMsgBox(progName+" - Error:"+nl+
" File: \""+jar+"\" NOT found."+nl+
" And file: \""+libPathJarFile.getName()+"\" is NOT in folder:"+nl+
" \""+libPathJarFile.getParent()+"\""+nl+
" either!"+nl+nl+
" This file is needed by the program."+nl, progName);
return false;
}
}
}//if classPath != null
} //if Manifest != null
} //if runningJar != null
return true;
} //doJarFilesExist()
//<editor-fold defaultstate="collapsed" desc="getRunningJarFile()">
/** Find out the jar file that contains this class
* @return a File object of the jar file containing the enclosing class "Main",
* or null if the main class is not inside a jar file.
* @version 2014-Jan-17 */
public static java.util.jar.JarFile getRunningJarFile() {
//from http://www.rgagnon.com/javadetails/
//and the JarClassLoader class
C c = new C();
String className = c.getClass().getName().replace('.', '/');
// class = "progPackage.Main"; className = "progPackage/Main"
java.net.URL url = c.getClass().getResource("/" + className + ".class");
// url = "jar:file:/C:/Eq-Calc_Java/dist/Prog.jar!/progPackage/Main.class"
if(url.toString().startsWith("jar:")) {
java.net.JarURLConnection jUrlC;
try{
jUrlC = (java.net.JarURLConnection)url.openConnection();
return jUrlC.getJarFile();
} catch(java.io.IOException ex) {
ErrMsgBox emb = new ErrMsgBox("Error "+ex.toString(), progName);
return null;
}
} else {
// it might not be a jar file if running within NetBeans
return null;
}
} //getRunningJarFile()
//</editor-fold>
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="getPathApp">
/** Get the path where an application is located.
* @return the directory where the application is located,
* or "user.dir" if an error occurs
* @version 2014-Jan-17 */
private static class C {private static void C(){}}
public static String getPathApp() {
C c = new C();
String path;
java.net.URI dir;
try{
dir = c.getClass().
getProtectionDomain().
getCodeSource().
getLocation().
toURI();
if(dir != null) {
String d = dir.toString();
if(d.startsWith("jar:") && d.endsWith("!/")) {
d = d.substring(4, d.length()-2);
dir = new java.net.URI(d);
}
path = (new java.io.File(dir.getPath())).getParent();
} else {path = System.getProperty("user.dir");}
}
catch (java.net.URISyntaxException e) {
if(!started) {
ErrMsgBox emb = new ErrMsgBox("Error: "+e.toString()+nl+
" trying to get the application's directory.", progName);
}
path = System.getProperty("user.dir");
} // catch
started = true;
return path;
} //getPathApp()
//</editor-fold>
}
| 7,275 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
HelpAboutF.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Predom/src/predominanceAreaDiagrams/HelpAboutF.java | package predominanceAreaDiagrams;
import lib.common.MsgExceptn;
/** Show a frame with the program version, acknowledgements, etc.
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class HelpAboutF extends javax.swing.JFrame {
private boolean finished = false;
private HelpAboutF frame = null;
/** Where errors will be printed. It may be <code>System.err</code>.
* If null, <code>System.err</code> is used. */
private final java.io.PrintStream out;
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
/** Creates new form HelpAboutF
* @param vers A text providing the program version
* @param pathApp path where the application is located
* @param out0 Where errors will be printed. For example <code>System.err</code>.
* If null, <code>System.err</code> is used */
public HelpAboutF(final String vers, final String pathApp, java.io.PrintStream out0) {
if(out0 != null) {this.out = out0;} else {this.out = System.out;}
finished = false;
initComponents();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
//--- Close window on ESC key
javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE");
javax.swing.Action escAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
closeWindow();
}};
getRootPane().getActionMap().put("ESCAPE", escAction);
//--- Alt-X eXit
javax.swing.KeyStroke altXKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altXKeyStroke,"ALT_X");
getRootPane().getActionMap().put("ALT_X", escAction);
//--- alt-Q exit
javax.swing.KeyStroke altQKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altQKeyStroke,"ALT_Q");
getRootPane().getActionMap().put("ALT_Q", escAction);
//--- Title, etc
//getContentPane().setBackground(java.awt.Color.white);
this.setTitle(Predom.progName+": About");
//---- Icon
String iconName = "images/Question_16x16.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
if (imgURL != null) {this.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());}
else {out.println("Error: Could not load image = \""+iconName+"\"");}
jLabelVers.setText("Program version: "+vers);
jLabelPathApp.setText(pathApp);
jLabelPathUser.setText(System.getProperty("user.home"));
this.validate();
int w = jLabelPathApp.getWidth()+40;
if(w > this.getWidth()) {this.setSize(w, this.getHeight());}
// Centre the window on the screen
int left = Math.max(0,(Predom.screenSize.width-this.getWidth())/2);
int top = Math.max(0,(Predom.screenSize.height-this.getHeight())/2);
this.setLocation(Math.min(Predom.screenSize.width-100, left),
Math.min(Predom.screenSize.height-100, top));
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
frame = HelpAboutF.this;
} }); //invokeLater(Runnable)
//return;
} //constructor
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel_Name = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jLabel_wwwKTH = new javax.swing.JLabel();
jLabel_www = new javax.swing.JLabel();
jLabelVers = new javax.swing.JLabel();
jLabelLicense = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jLabelJava = new javax.swing.JLabel();
jLabelPathA = new javax.swing.JLabel();
jLabelPathApp = new javax.swing.JLabel();
jLabelPathU = new javax.swing.JLabel();
jLabelPathUser = new javax.swing.JLabel();
jLabelUnicode = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jLabel_Name.setText("<html><b><font size=+1>Predom:</font></b> Predominance Area Diagrams<br>\n© 2020 I.Puigdomenech,<br>\nHaltafall algorithm by Ingri <i>et al</i> (1967).</html>");
jLabel_wwwKTH.setForeground(new java.awt.Color(0, 0, 221));
jLabel_wwwKTH.setText("<html><u>www.kth.se/che/medusa</u></html>");
jLabel_wwwKTH.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jLabel_wwwKTH.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel_wwwKTHMouseClicked(evt);
}
});
jLabel_www.setForeground(new java.awt.Color(0, 0, 221));
jLabel_www.setText("<html><u>sites.google.com/site/chemdiagr/</u></html>");
jLabel_www.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jLabel_www.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel_wwwMouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel_wwwKTH, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel_www, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(21, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel_wwwKTH, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel_www, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jLabelVers.setText("jLabelVers");
jLabelLicense.setText("<html>This program comes with ABSOLUTELY NO WARRANTY.<br>This is free software, and you are welcome to redistribute it<br>under the GNU GPL license. See file \"GPL.txt\".</html>");
jLabelJava.setText("<html>Java Standard Edition<br>Development Kit 7 (JDK 1.7)<br>NetBeans IDE</html>");
jLabelPathA.setLabelFor(jLabelPathApp);
jLabelPathA.setText("Application path:");
jLabelPathApp.setText("\"null\"");
jLabelPathU.setText("User \"home\" directory:");
jLabelPathUser.setText("\"null\"");
jLabelUnicode.setText("(Unicode UTF-8)");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator1)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelJava, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelPathA)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelPathApp))
.addComponent(jLabelLicense, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelPathU)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelPathUser))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelVers)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelUnicode)))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel_Name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(5, 5, 5)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel_Name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelVers)
.addComponent(jLabelUnicode))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelLicense, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 4, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelJava, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelPathA)
.addComponent(jLabelPathApp))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelPathU)
.addComponent(jLabelPathUser))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jLabel_wwwMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel_wwwMouseClicked
BareBonesBrowserLaunch.openURL("https://sites.google.com/site/chemdiagr/", this);
}//GEN-LAST:event_jLabel_wwwMouseClicked
private void jLabel_wwwKTHMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel_wwwKTHMouseClicked
BareBonesBrowserLaunch.openURL("https://www.kth.se/che/medusa/", this);
}//GEN-LAST:event_jLabel_wwwKTHMouseClicked
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
closeWindow();
}//GEN-LAST:event_formWindowClosing
public void closeWindow() {
finished = true;
this.notify_All();
this.dispose();
} // closeWindow()
private synchronized void notify_All() {notifyAll();}
/** this method will wait for this dialog frame to be closed */
public synchronized void waitFor() {
while(!finished) {
try {wait();} catch (InterruptedException ex) {}
} // while
} // waitFor()
public void bringToFront() {
if(frame != null) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override public void run() {
frame.setVisible(true);
if((frame.getExtendedState() & javax.swing.JFrame.ICONIFIED) // minimised?
== javax.swing.JFrame.ICONIFIED) {
frame.setExtendedState(javax.swing.JFrame.NORMAL);
} // if minimized
frame.setAlwaysOnTop(true);
frame.toFront();
frame.requestFocus();
frame.setAlwaysOnTop(false);
}
});
}
} // bringToFront()
//<editor-fold defaultstate="collapsed" desc="class BareBonesBrowserLaunch">
/**
* <b>Bare Bones Browser Launch for Java</b><br>
* Utility class to open a web page from a Swing application
* in the user's default browser.<br>
* Supports: Mac OS X, GNU/Linux, Unix, Windows XP/Vista/7<br>
* Example Usage:<code><br>
* String url = "http://www.google.com/";<br>
* BareBonesBrowserLaunch.openURL(url);<br></code>
* Latest Version: <a href=http://centerkey.com/java/browser>centerkey.com/java/browser</a><br>
* Author: Dem Pilafian<br>
* WTFPL -- Free to use as you like
* @version 3.2, October 24, 2010
*/
private static class BareBonesBrowserLaunch {
static final String[] browsers = { "x-www-browser", "google-chrome",
"firefox", "opera", "epiphany", "konqueror", "conkeror", "midori",
"kazehakase", "mozilla", "chromium" }; // modified by Ignasi (added "chromium")
static final String errMsg = "Error attempting to launch web browser";
/**
* Opens the specified web page in the user's default browser
* @param url A web address (URL) of a web page (ex: "http://www.google.com/")
*/
public static void openURL(String url, javax.swing.JFrame parent) { // modified by Ignasi (added "parent")
try { //attempt to use Desktop library from JDK 1.6+
Class<?> d = Class.forName("java.awt.Desktop");
d.getDeclaredMethod("browse", new Class[] {java.net.URI.class}).invoke(
d.getDeclaredMethod("getDesktop").invoke(null),
new Object[] {java.net.URI.create(url)});
//above code mimicks: java.awt.Desktop.getDesktop().browse()
}
catch (Exception ignore) { //library not available or failed
String osName = System.getProperty("os.name");
try {
if (osName.startsWith("Mac OS")) {
Class.forName("com.apple.eio.FileManager").getDeclaredMethod(
"openURL", new Class[] {String.class}).invoke(null,new Object[] {url});
}
else if (osName.startsWith("Windows"))
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
else { //assume Unix or Linux
String browser = null;
for (String b : browsers)
if (browser == null && Runtime.getRuntime().exec(new String[]
{"which", b}).getInputStream().read() != -1)
Runtime.getRuntime().exec(new String[] {browser = b, url});
if (browser == null)
throw new Exception(java.util.Arrays.toString(browsers));
}
}
catch (Exception e) {
MsgExceptn.exception(errMsg + "\n" + e.getMessage()); // added by Ignasi
javax.swing.JOptionPane.showMessageDialog(parent, errMsg + "\n" + e.getMessage(), // modified by Ignasi (added "parent")
"Chemical Equilibrium Diagrams", javax.swing.JOptionPane.ERROR_MESSAGE); // added by Ignasi
}
}
}
}
//</editor-fold>
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabelJava;
private javax.swing.JLabel jLabelLicense;
private javax.swing.JLabel jLabelPathA;
private javax.swing.JLabel jLabelPathApp;
private javax.swing.JLabel jLabelPathU;
private javax.swing.JLabel jLabelPathUser;
private javax.swing.JLabel jLabelUnicode;
private javax.swing.JLabel jLabelVers;
private javax.swing.JLabel jLabel_Name;
private javax.swing.JLabel jLabel_www;
private javax.swing.JLabel jLabel_wwwKTH;
private javax.swing.JPanel jPanel1;
private javax.swing.JSeparator jSeparator1;
// End of variables declaration//GEN-END:variables
}
| 19,077 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
PredomData.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Predom/src/predominanceAreaDiagrams/PredomData.java | package predominanceAreaDiagrams;
/** A class that contains diverse information associated with a Predom diagram.
* <br>
* Copyright (C) 2014 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class PredomData {
/** <code>pair[i][0]</code> and <code>pair[i][1]</code> = number of the
* two chemical species that in the predominance area diagram are separated
* by the line going through the point "i". <code>pair[i][2]</code> = number
* of a third species involved in the point "i". */
public int[][] pair;
/** X-coordinate of a point to plot; a point that is a frontier between
* two predominating species */
public double[] xPl;
/** Y-coordinate of a point to plot; a point that is a frontier between
* two predominating species */
public double[] yPl;
/** number of points to plot, that is, the number of points that are
* the borderlines between predominance areas */
public int nPoint;
/** The size of the step in the X-axis */
public double stepX;
/** The size of the step in the Y-axis */
public double stepY;
/** The leftmost value in the x-axis */
public double xLeft;
/** The rightmost value in the x-axis */
public double xRight;
/** The bottom value in the y-axis */
public double yBottom;
/** The top value in the y-axis */
public double yTop;
/** X-value for the center of the predominance area for each species */
public double[] xCentre;
/** Y-value for the center of the predominance area for each species */
public double[] yCentre;
/** Max number of points to be plotted. In a predominance area diagram
* these are the points delimiting the areas. */
public final int mxPNT;
/** Constructs an instance
* @param ms number of species
* @param maxPNT Max. number of points to be plotted. In a predominance area diagram
* these are the points delimiting the areas. */
public PredomData(int ms, int maxPNT){
mxPNT = maxPNT;
nPoint = 0;
pair = new int[mxPNT][3];
for(int[] pair1 : pair) {pair1[0] = -1; pair1[1] = -1; pair1[2] = -1;}
xPl = new double[mxPNT];
yPl = new double[mxPNT];
xCentre = new double[2*ms];
yCentre = new double[2*ms];
for(int i=0; i < xCentre.length; i++) {xCentre[i]=-100000; yCentre[i]=-100000;}
} // constructor
} // class PredomData
| 2,849 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
Predom.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Predom/src/predominanceAreaDiagrams/Predom.java | package predominanceAreaDiagrams;
import lib.common.Util;
import lib.kemi.chem.Chem;
import lib.kemi.graph_lib.DiagrPaintUtility;
import lib.kemi.graph_lib.GraphLib;
import lib.kemi.haltaFall.Factor;
import lib.kemi.haltaFall.HaltaFall;
import lib.kemi.readDataLib.ReadDataLib;
import lib.kemi.readWriteDataFiles.ReadChemSyst;
/** Creates a Predominance Area diagram. <br>
* This program will read a data file, make some calculations, and
* create a diagram. The diagram is displayed and stored in a plot file. <br>
* The data file contains the description of a chemical system (usually
* an aqueous system) and a description on how the diagram should be drawn:
* what should be in the axes, concentrations for each chemical
* component, etc. <br>
* If the command-line option "-nostop" is given, then no option dialogs will
* be shown. <br>
* Output messages and errors are written to <code>System.out</code> and
* <code>.err</code> (the console) and output is directed to a JTextArea as well.
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech
*
* 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 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/
*
* @author Ignasi Puigdomenech */
public class Predom extends javax.swing.JFrame {
static final String VERS = "2020-June-18";
static final String progName = "PREDOM";
/** variable needed in "main" method */
private static Predom predomFrame;
/** print debug information? */
private static final boolean DBG_DEFAULT = false;
/** print debug information? */
boolean dbg = false;
/** if true the program does not exit after the diagram is drawn (and saved
* as a plot file), that is, the diagram remains visible for the user.
* If false, and if the data file is given as a command-line argument,
* then the program saves the diagram and exits without displaying it */
private boolean doNotExit = false;
/** if true the program does display dialogs with warnings or errors */
private boolean doNotStop = false;
/** if true the concentration range in the x-axis may have a reversed "order",
* that is, minimum value to the right and maximum value to the left, if so
* it is given in the input data file. */
private boolean reversedConcs = false;
/** the directory where the program files are located */
private static String pathApp;
/** the directory where the last input data file is located */
StringBuffer pathDef = new StringBuffer();
private java.io.File inputDataFile = null;
private java.io.File outputPltFile = null;
/** true if an input data file is given in the command line.
* If so, then the calculations are performed without waiting for user actions,
* a diagram is generated and saved, and the program exits unless doNotExit is true. */
private boolean inputDataFileInCommandLine;
/** true if the calculations have finished, or if the user wishes to finish
* them (and to end the program) */
private boolean finishedCalculations = true;
/** true if the graphic user interface (GUI) has been displayed and then closed by the user */
private boolean programEnded = true;
/** An instance of SwingWorker to perform the HaltaFall calculations */
private HaltaTask tsk = null;
/** used to calculate execution time */
private long calculationStart = 0;
/** the execution time */
private long calculationTime = 0;
/** size of the user's computer screen */
static java.awt.Dimension screenSize;
/** original size of the program window */
private final java.awt.Dimension originalSize;
/** a class used to store and retrieve data, used by HaltaFall */
private Chem ch = null;
/** a class to store data about a chemical system */
private Chem.ChemSystem cs = null;
/** a class to store data about a the concentrations to calculate an
* equilibrium composition, used by HaltaFall */
private Chem.ChemSystem.ChemConcs csC = null;
/** a class to store diverse information on a chemical system: names of species, etc */
private Chem.ChemSystem.NamesEtc namn = null;
/** a class to store array data about a diagram */
private Chem.DiagrConcs dgrC = null;
/** a class to store non-array data about a diagram */
private Chem.Diagr diag = null;
/** a class to calculate activity coefficients */
private Factor factor;
/** the calculations class */
private HaltaFall h;
/** if true only aqueous species will be shown in the diagram, that is,
* predominance areas for solids will not appear. */
boolean aqu = false;
/** if true a dashed line will be plotted in the diagram showing the pH of
* neutral water, which is temperature dependent. At 25 C the neutral pH is 7. */
boolean neutral_pH = false;
/** This value is set in findTopSpecies() to the species predominating in the
* diagram at the point being calculated. It is set to -2 if two solid species
* have practically the same amount of "main component" */
private int topSpecies = -1;
/** used to direct SED and Predom to draw concentration units
* as either:<ul><li>0="molal"</li><li>1="mol/kg_w"</li><li>2="M"</li><li>-1=""</li></ul> */
int conc_units = 0;
String[] cUnits = new String[]{"","molal","mol/kg`w'","M"};
/** used to direct SED and Predom to draw concentrations
* as either scientific notation or engineering notation:<ul><li>0 = no choice
* (default, means scientific for "molal" and engineering for "M")</li>
* <li>1 = scientific notation</li><li>2 = engineering notation</li></ul> */
int conc_nottn = 0;
/** a class to read text files where data is separated by commas */
private ReadDataLib rd;
private Plot_Predom plot = null;
/** data from a plot-file needed by the paint methods */
GraphLib.PltData dd; // instantiated in "Plot_Predom.drawPlot"
// it containts the info in the plot file
private HelpAboutF helpAboutFrame = null;
private final javax.swing.JFileChooser fc;
private final javax.swing.filechooser.FileNameExtensionFilter filterDat;
/** true if the message text area should be erased before a new datafile is
* read (after the user has selected a new data file) */
private boolean eraseTextArea = false;
/** Where errors will be printed. It may be <code>System.err</code>.
* If null, <code>System.err</code> is used. */
private java.io.PrintStream err;
/** Where messages will be printed. It may be <code>System.out</code>.
* If null, <code>System.out</code> is used. */
private java.io.PrintStream out;
/** The maximum number of calculation steps along an axis */
private final static int NSTP_MAX = 1000;
/** The minimum number of calculation steps along the X-axis */
private final static int NSTP_MIN = 4;
private final static int NSTP_DEF = 50;
/** The number of calculation steps along an axis.
* The number of calculated points in the plot is <code>nSteps+1</code>
* along each axis. Note that to the outside world, the number of
* calculation points are reported. */
int nSteps = NSTP_DEF;
/** The calculation step being performed along the outer loop (out of nSteps).
* The first point corresponds to no step, <code>nStepOuter = 0</code> */
private int nStepOuter;
/** The calculation step being performed along the inner loop (out of nSteps)
* The first point corresponds to no step, <code>nStepInner = 0</code> */
private int nStepInner;
private final double ln10 = Math.log(10d);
/** true if activity coeeficients have to be calculated */
boolean calcActCoeffs = false;
private final int actCoeffsModelDefault =2;
/** the ionic strength, or -1 if it has to be calculated at each calculation step */
private double ionicStrength = Double.NaN;
/** the temperature value given given in the command line */
double temperature_InCommandLine = Double.NaN;
/** the pressure value given given in the command line */
double pressure_InCommandLine = Double.NaN;
private int actCoeffsModel_InCommandLine = -1;
private double tolHalta = Chem.TOL_HALTA_DEF;
double peEh = Double.NaN;
double tHeight;
/** output debug reporting in HaltaFall. Default = Chem.DBGHALTA_DEF = 1 (report errors only)
* @see Chem.ChemSystem.ChemConcs#dbg Chem.ChemSystem.ChemConcs.dbg */
private int dbgHalta = Chem.DBGHALTA_DEF;
/** true if the component has either <code>noll</code> = false or it has positive
* values for the stoichiometric coefficients (a[ix][ia]-values)
* @see chem.Chem.ChemSystem#a a
* @see chem.Chem.ChemSystem#noll noll */
private boolean[] pos;
/** true if the component has some negative
* values for the stoichiometric coefficients (a[ix][ia]-values)
* @see chem.Chem.ChemSystem#a a */
private boolean[] neg;
//
private final DiagrPaintUtility diagrPaintUtil;
//
private final java.io.PrintStream errPrintStream =
new java.io.PrintStream(
new errFilteredStreamPredom(
new java.io.ByteArrayOutputStream()),true);
private final java.io.PrintStream outPrintStream =
new java.io.PrintStream(
new outFilteredStreamPredom(
new java.io.ByteArrayOutputStream()),true);
/** true if a minimum of information is sent to the console (System.out)
* when inputDataFileInCommandLine and not doNotExit.
* False if all output is sent only to the JTextArea panel. */
boolean consoleOutput = true;
/** New-line character(s) to substitute "\n".<br>
* It is needed when a String is created first, including new-lines,
* and the String is then printed. For example
* <pre>String t = "1st line\n2nd line";
*System.out.println(t);</pre>will add a carriage return character
* between the two lines, which on Windows system might be
* unsatisfactory. Use instead:
* <pre>String t = "1st line" + nl + "2nd line";
*System.out.println(t);</pre> */
private static final String nl = System.getProperty("line.separator");
private static final java.util.Locale engl = java.util.Locale.ENGLISH;
static final String LINE = "-------------------------------------";
private static final String SLASH = java.io.File.separator;
//
//todo: no names can start with "*" after reading the chemical system
//<editor-fold defaultstate="collapsed" desc="Constructor">
/** Creates new form Predom
* @param doNotExit0
* @param doNotStop0
* @param dbg0 */
public Predom(
final boolean doNotExit0,
final boolean doNotStop0,
final boolean dbg0) {
initComponents();
dbg = dbg0;
doNotStop = doNotStop0;
doNotExit = doNotExit0;
// ---- redirect all output to the tabbed pane
out = outPrintStream;
err = errPrintStream;
// ---- get the current working directory
setPathDef();
if(DBG_DEFAULT) {System.out.println("default path: \""+pathDef.toString()+"\"");}
// ---- Define open/save file filters
fc = new javax.swing.JFileChooser("."); //the "user" path
filterDat =new javax.swing.filechooser.FileNameExtensionFilter("*.dat", new String[] { "DAT"});
// ----
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
//--- F1 for help
javax.swing.KeyStroke f1KeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(f1KeyStroke,"F1");
javax.swing.Action f1Action = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jMenuHelpAbout.isEnabled()) {jMenuHelpAbout.doClick();}
}};
getRootPane().getActionMap().put("F1", f1Action);
//--- ctrl-C: stop calculations
javax.swing.KeyStroke ctrlCKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_DOWN_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(ctrlCKeyStroke,"CTRL_C");
javax.swing.Action ctrlCAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jTabbedPane.getSelectedIndex() == 1) {
if(h != null) {h.haltaCancel();}
if(tsk != null) {tsk.cancel(true);}
finishedCalculations = true;
Predom.this.notify_All();
}
}};
getRootPane().getActionMap().put("CTRL_C", ctrlCAction);
//--- define Alt-key actions
//--- alt-X: eXit
javax.swing.KeyStroke altXKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altXKeyStroke,"ALT_X");
javax.swing.Action altXAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jMenuFileXit.isEnabled()) {jMenuFileXit.doClick();}
}};
getRootPane().getActionMap().put("ALT_X", altXAction);
//--- alt-Q: quit
javax.swing.KeyStroke altQKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altQKeyStroke,"ALT_Q");
getRootPane().getActionMap().put("ALT_Q", altXAction);
//--- alt-Enter: make diagram
javax.swing.KeyStroke altEnterKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_ENTER, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altEnterKeyStroke,"ALT_Enter");
javax.swing.Action altEnterAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jMenuFileMakeD.isEnabled()) {jMenuFileMakeD.doClick();}
}};
getRootPane().getActionMap().put("ALT_Enter", altEnterAction);
//--- alt-C: method for activity coefficients
javax.swing.KeyStroke altCKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altCKeyStroke,"ALT_C");
javax.swing.Action altCAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jTabbedPane.getSelectedIndex() == 0 &&
jComboBoxModel.isEnabled()) {jComboBoxModel.requestFocusInWindow();}
}};
getRootPane().getActionMap().put("ALT_C", altCAction);
//--- alt-D: diagram
javax.swing.KeyStroke altDKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_D, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altDKeyStroke,"ALT_D");
javax.swing.Action altDAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jTabbedPane.getSelectedIndex() == 0 &&
jMenuFileMakeD.isEnabled() &&
jButtonDoIt.isEnabled()) {jButtonDoIt.doClick();
} else if(jTabbedPane.getSelectedIndex() != 2 &&
jTabbedPane.isEnabledAt(2)) {jTabbedPane.setSelectedIndex(2);
}
}};
getRootPane().getActionMap().put("ALT_D", altDAction);
//--- alt-E: hEight
javax.swing.KeyStroke altEKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.ALT_MASK, false);
javax.swing.Action altEAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jTabbedPane.getSelectedIndex() == 0){jScrollBarHeight.requestFocusInWindow();}
}};
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altEKeyStroke,"ALT_E");
getRootPane().getActionMap().put("ALT_E", altEAction);
//--- alt-L: pLot file name
javax.swing.KeyStroke altLKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_L, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altLKeyStroke,"ALT_L");
javax.swing.Action altLAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jTabbedPane.getSelectedIndex() == 0){jTextFieldPltFile.requestFocusInWindow();}
}};
getRootPane().getActionMap().put("ALT_L", altLAction);
//--- alt-M: messages pane
javax.swing.KeyStroke altMKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_M, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altMKeyStroke,"ALT_M");
javax.swing.Action altMAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jTabbedPane.getSelectedIndex() != 1 &&
jTabbedPane.isEnabledAt(1)) {jTabbedPane.setSelectedComponent(jScrollPaneMessg);}
}};
getRootPane().getActionMap().put("ALT_M", altMAction);
//--- alt-N: nbr of points
javax.swing.KeyStroke altNKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altNKeyStroke,"ALT_N");
javax.swing.Action altNAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jTabbedPane.getSelectedIndex() == 0){jScrollBarNbrPoints.requestFocusInWindow();}
}};
getRootPane().getActionMap().put("ALT_N", altNAction);
//--- alt-P: parameters
javax.swing.KeyStroke altPKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altPKeyStroke,"ALT_P");
javax.swing.Action altPAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jTabbedPane.getSelectedIndex() != 0) {jTabbedPane.setSelectedIndex(0);}
}};
getRootPane().getActionMap().put("ALT_P", altPAction);
//--- alt-S: ionic strength / stop calcúlations
javax.swing.KeyStroke altSKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altSKeyStroke,"ALT_S");
javax.swing.Action altSAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jTabbedPane.getSelectedIndex() == 0 &&
jTextFieldIonicStgr.isEnabled()) {
jTextFieldIonicStgr.requestFocusInWindow();
} else if(jTabbedPane.getSelectedIndex() == 1) {
if(h != null) {h.haltaCancel();}
if(tsk != null) {tsk.cancel(true);}
finishedCalculations = true;
Predom.this.notify_All();
}
}};
getRootPane().getActionMap().put("ALT_S", altSAction);
//--- alt-T: tolerance in Haltafall
javax.swing.KeyStroke altTKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altTKeyStroke,"ALT_T");
javax.swing.Action altTAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jTabbedPane.getSelectedIndex() == 0 &&
jComboBoxTol.isEnabled()) {jComboBoxTol.requestFocusInWindow();}
}};
getRootPane().getActionMap().put("ALT_T", altTAction);
// -------
//--- Title
this.setTitle("Predom: Predominance Area Diagrams");
jMenuBar.add(javax.swing.Box.createHorizontalGlue(),2); //move "Help" menu to the right
//--- center Window on Screen
originalSize = this.getSize();
screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int left; int top;
left = Math.max(55, (screenSize.width - originalSize.width ) / 2);
top = Math.max(10, (screenSize.height - originalSize.height) / 2);
this.setLocation(Math.min(screenSize.width-100, left),
Math.min(screenSize.height-100, top));
//---- Icon
String iconName = "images/Predom256_32x32_blackBckgr.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
java.awt.Image icon;
if (imgURL != null) {
icon = new javax.swing.ImageIcon(imgURL).getImage();
this.setIconImage(icon);
//com.apple.eawt.Application.getApplication().setDockIconImage(new javax.swing.ImageIcon("Football.png").getImage());
if(System.getProperty("os.name").startsWith("Mac OS")) {
try {
Class<?> c = Class.forName("com.apple.eawt.Application");
//Class params[] = new Class[] {java.awt.Image.class};
java.lang.reflect.Method m =
c.getDeclaredMethod("setDockIconImage",new Class[] { java.awt.Image.class });
Object i = c.newInstance();
Object paramsObj[] = new Object[]{icon};
m.invoke(i, paramsObj);
} catch (Exception e) {System.out.println("Error: "+e.getMessage());}
}
} else {
System.out.println("Error: Could not load image = \""+iconName+"\"");
}
//--- set up the Form
jMenuFileMakeD.setEnabled(false);
jButtonDoIt.setText("make the Diagram");
jButtonDoIt.setEnabled(false);
java.awt.Font f = new java.awt.Font("Monospaced", java.awt.Font.PLAIN, 12);
jTextAreaA.setFont(f);
jTextAreaA.setText(null);
jTabbedPane.setEnabledAt(1, false);
jTabbedPane.setEnabledAt(2, false);
jScrollBarNbrPoints.setFocusable(true);
jScrollBarNbrPoints.setValue(nSteps);
jScrollBarHeight.setFocusable(true);
tHeight = 1;
jScrollBarHeight.setValue(Math.round((float)(10*tHeight)));
jLabelPltFile.setText("plot file name");
jLabelPltFile.setEnabled(false);
jTextFieldPltFile.setText(null);
jTextFieldPltFile.setEnabled(false);
jLabelStatus.setText("waiting...");
jLabelProgress.setText(" ");
jLabelTemperature.setText("NaN"); // no temperature given
jLabelPressure.setText("NaN"); // no pressure given
jComboBoxModel.setSelectedIndex(actCoeffsModelDefault);
//--- the methods in DiagrPaintUtility are used to paint the diagram
diagrPaintUtil = new DiagrPaintUtility();
} // Predom constructor
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="start">
/** Sets this window frame visible, and deals with the command-line arguments
* @param reversedConcs0 needed when reading the input data file.
* The command-line argument may be given <i>after</i> the data file name...
* @param help0 if help is displayed, request focus for the text pane,
* where the help is shown
* @param args the command-line arguments */
private void start(
final boolean reversedConcs0,
final boolean help0,
final String[] args) {
this.setVisible(true);
//----
out.println(LINE+nl+progName+" (Predominance Area Diagrams), version: "+VERS);
java.util.Date today = new java.util.Date();
java.text.DateFormat dateFormatter =
java.text.DateFormat.getDateTimeInstance(java.text.DateFormat.DEFAULT,
java.text.DateFormat.DEFAULT, java.util.Locale.getDefault());
out.println("PREDOM started: "+dateFormatter.format(today));
//--- deal with any command line arguments
inputDataFileInCommandLine = false;
reversedConcs = reversedConcs0; //this is needed when reading the data file
boolean argErr = false;
if(args != null && args.length >0){
for (String arg : args) {
if (!dispatchArg(arg)) {argErr = true;}
} // for arg
} // if argsList != null
if(argErr && !doNotExit) {end_program(); return;}
out.println("Finished reading command-line arguments.");
if(dbg) {
out.println("--------"+nl+
"Application path: \""+pathApp+"\""+nl+
"Default path: \""+pathDef.toString()+"\""+nl+
"--------");
}
consoleOutput = inputDataFileInCommandLine & !doNotExit;
// is the temperture missing even if a ionic strength is given?
if((!Double.isNaN(ionicStrength) && Math.abs(ionicStrength) >1e-10)
&& Double.isNaN(temperature_InCommandLine)) {
showMsg("Warning: ionic strength given as command line argument, I="
+(float)ionicStrength+nl+
" but no temperature is given on the command line.",2);
}
// if the command-line "-i" is not given, set the ionic strength to zero
if(!calcActCoeffs) {ionicStrength = 0;}
jCheckReverse.setSelected(reversedConcs);
jCheckActCoeff.setSelected(calcActCoeffs);
jTextFieldIonicStgr.setText(String.valueOf(ionicStrength));
showActivityCoefficientControls(calcActCoeffs);
set_tol_inComboBox();
//--- if help is requested on the command line and the
// program's window stays on screen: show the message pane
if(help0) {
jTextAreaA.setCaretPosition(0);
jTabbedPane.setSelectedComponent(jScrollPaneMessg);
}
// Make a diagram if an input file is given in the command-line
if(inputDataFileInCommandLine == true) {
if(outputPltFile == null) {
String txt = inputDataFile.getAbsolutePath();
String plotFileN = txt.substring(0,txt.length()-3).concat("plt");
outputPltFile = new java.io.File(plotFileN);
}
// note: as the calculations are done on a worker thread, this returns pretty quickly
try {doCalculations();}
catch (Exception ex) {showErrMsgBx(ex);}
}
programEnded = false;
} //start
//</editor-fold>
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroupDebug = new javax.swing.ButtonGroup();
jLabel2 = new javax.swing.JLabel();
jTabbedPane = new javax.swing.JTabbedPane();
jPanelParameters = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanelFiles = new javax.swing.JPanel();
jLabelData = new javax.swing.JLabel();
jTextFieldDataFile = new javax.swing.JTextField();
jLabelPltFile = new javax.swing.JLabel();
jTextFieldPltFile = new javax.swing.JTextField();
jPanel6 = new javax.swing.JPanel();
jButtonDoIt = new javax.swing.JButton();
jPanel2 = new javax.swing.JPanel();
jLabelNbrPText = new javax.swing.JLabel();
jLabelPointsNbr = new javax.swing.JLabel();
jScrollBarNbrPoints = new javax.swing.JScrollBar();
jLabelHeight = new javax.swing.JLabel();
jLabelHD = new javax.swing.JLabel();
jScrollBarHeight = new javax.swing.JScrollBar();
jPanel3 = new javax.swing.JPanel();
jCheckReverse = new javax.swing.JCheckBox();
jPanelActC = new javax.swing.JPanel();
jCheckActCoeff = new javax.swing.JCheckBox();
jPanel1 = new javax.swing.JPanel();
jLabelIonicStr = new javax.swing.JLabel();
jTextFieldIonicStgr = new javax.swing.JTextField();
jLabelIonicStrM = new javax.swing.JLabel();
jPanelT = new javax.swing.JPanel();
jLabelT = new javax.swing.JLabel();
jLabelTC = new javax.swing.JLabel();
jLabelP = new javax.swing.JLabel();
jLabelPressure = new javax.swing.JLabel();
jLabelBar = new javax.swing.JLabel();
jLabelTemperature = new javax.swing.JLabel();
jPanel5 = new javax.swing.JPanel();
jLabelModel = new javax.swing.JLabel();
jComboBoxModel = new javax.swing.JComboBox();
jPanel4 = new javax.swing.JPanel();
jLabelTol = new javax.swing.JLabel();
jComboBoxTol = new javax.swing.JComboBox();
jScrollPaneMessg = new javax.swing.JScrollPane();
jTextAreaA = new javax.swing.JTextArea();
jPanelDiagram = new javax.swing.JPanel()
{
@Override
public void paint(java.awt.Graphics g)
{
super.paint(g);
paintDiagrPanel(g);
}
};
jPanelStatusBar = new javax.swing.JPanel();
jLabelStatus = new javax.swing.JLabel();
jLabelProgress = new javax.swing.JLabel();
jMenuBar = new javax.swing.JMenuBar();
jMenuFile = new javax.swing.JMenu();
jMenuFileOpen = new javax.swing.JMenuItem();
jMenuFileMakeD = new javax.swing.JMenuItem();
jMenuFileXit = new javax.swing.JMenuItem();
jMenuDebug = new javax.swing.JMenu();
jCheckBoxMenuPredomDebug = new javax.swing.JCheckBoxMenuItem();
jMenuSave = new javax.swing.JMenuItem();
jMenuCancel = new javax.swing.JMenuItem();
jMenuHelp = new javax.swing.JMenu();
jMenuHelpAbout = new javax.swing.JMenuItem();
jLabel2.setText("jLabel2");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
addWindowFocusListener(new java.awt.event.WindowFocusListener() {
public void windowGainedFocus(java.awt.event.WindowEvent evt) {
formWindowGainedFocus(evt);
}
public void windowLostFocus(java.awt.event.WindowEvent evt) {
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jTabbedPane.setTabLayoutPolicy(javax.swing.JTabbedPane.SCROLL_TAB_LAYOUT);
jTabbedPane.setAlignmentX(0.0F);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/predominanceAreaDiagrams/images/Predom256_32x32_whiteBckgr.gif"))); // NOI18N
jLabelData.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabelData.setLabelFor(jTextFieldDataFile);
jLabelData.setText("input data file:");
jTextFieldDataFile.setBackground(new java.awt.Color(204, 204, 204));
jTextFieldDataFile.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTextFieldDataFileMouseClicked(evt);
}
});
jTextFieldDataFile.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTextFieldDataFileKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextFieldDataFileKeyTyped(evt);
}
});
jLabelPltFile.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabelPltFile.setLabelFor(jTextFieldPltFile);
jLabelPltFile.setText("<html>p<u>l</u>ot file name:</html>");
jTextFieldPltFile.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextFieldPltFileFocusGained(evt);
}
});
javax.swing.GroupLayout jPanelFilesLayout = new javax.swing.GroupLayout(jPanelFiles);
jPanelFiles.setLayout(jPanelFilesLayout);
jPanelFilesLayout.setHorizontalGroup(
jPanelFilesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelFilesLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelFilesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabelData, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabelPltFile))
.addGap(5, 5, 5)
.addGroup(jPanelFilesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jTextFieldDataFile, javax.swing.GroupLayout.DEFAULT_SIZE, 460, Short.MAX_VALUE)
.addComponent(jTextFieldPltFile, javax.swing.GroupLayout.DEFAULT_SIZE, 460, Short.MAX_VALUE))
.addContainerGap())
);
jPanelFilesLayout.setVerticalGroup(
jPanelFilesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelFilesLayout.createSequentialGroup()
.addGap(0, 0, 0)
.addGroup(jPanelFilesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabelData)
.addComponent(jTextFieldDataFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelFilesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelPltFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextFieldPltFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jButtonDoIt.setText("make the Diagram");
jButtonDoIt.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonDoIt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonDoItActionPerformed(evt);
}
});
jLabelNbrPText.setLabelFor(jLabelPointsNbr);
jLabelNbrPText.setText("<html><u>N</u>br of calc. steps:</html>");
jLabelPointsNbr.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabelPointsNbr.setText(" 50");
jLabelPointsNbr.setToolTipText("double-click to reset to default");
jLabelPointsNbr.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabelPointsNbrMouseClicked(evt);
}
});
jScrollBarNbrPoints.setMaximum(NSTP_MAX+1);
jScrollBarNbrPoints.setMinimum(NSTP_MIN);
jScrollBarNbrPoints.setOrientation(javax.swing.JScrollBar.HORIZONTAL);
jScrollBarNbrPoints.setVisibleAmount(1);
jScrollBarNbrPoints.addAdjustmentListener(new java.awt.event.AdjustmentListener() {
public void adjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {
jScrollBarNbrPointsAdjustmentValueChanged(evt);
}
});
jScrollBarNbrPoints.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jScrollBarNbrPointsFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jScrollBarNbrPointsFocusLost(evt);
}
});
jLabelHeight.setText("<html>h<u>e</u>ight of text in diagram:</html>");
jLabelHD.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabelHD.setText("1.0");
jLabelHD.setToolTipText("double-click to reset to default");
jLabelHD.setMaximumSize(new java.awt.Dimension(15, 14));
jLabelHD.setMinimumSize(new java.awt.Dimension(15, 14));
jLabelHD.setPreferredSize(new java.awt.Dimension(15, 14));
jLabelHD.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabelHDMouseClicked(evt);
}
});
jScrollBarHeight.setMaximum(101);
jScrollBarHeight.setMinimum(3);
jScrollBarHeight.setOrientation(javax.swing.JScrollBar.HORIZONTAL);
jScrollBarHeight.setValue(10);
jScrollBarHeight.setVisibleAmount(1);
jScrollBarHeight.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jScrollBarHeightFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jScrollBarHeightFocusLost(evt);
}
});
jScrollBarHeight.addAdjustmentListener(new java.awt.event.AdjustmentListener() {
public void adjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {
jScrollBarHeightAdjustmentValueChanged(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabelNbrPText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelHeight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelPointsNbr, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelHD, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollBarHeight, javax.swing.GroupLayout.DEFAULT_SIZE, 75, Short.MAX_VALUE)
.addComponent(jScrollBarNbrPoints, javax.swing.GroupLayout.DEFAULT_SIZE, 75, Short.MAX_VALUE))
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelNbrPText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelPointsNbr))
.addComponent(jScrollBarNbrPoints, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelHeight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelHD, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollBarHeight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(17, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButtonDoIt, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel6Layout.createSequentialGroup()
.addGap(11, 11, 11)
.addComponent(jButtonDoIt)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jCheckReverse.setMnemonic(java.awt.event.KeyEvent.VK_R);
jCheckReverse.setText("<html>allow <u>R</u>eversed min. and max. axes limits</html>");
jCheckReverse.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckReverseActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jCheckReverse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jCheckReverse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jCheckActCoeff.setMnemonic(java.awt.event.KeyEvent.VK_A);
jCheckActCoeff.setText("<html><u>A</u>ctivity coefficient calculations</html>");
jCheckActCoeff.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckActCoeffActionPerformed(evt);
}
});
jLabelIonicStr.setLabelFor(jTextFieldIonicStgr);
jLabelIonicStr.setText("<html>ionic <u>S</u>trength</html>");
jLabelIonicStr.setEnabled(false);
jTextFieldIonicStgr.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
jTextFieldIonicStgr.setEnabled(false);
jTextFieldIonicStgr.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextFieldIonicStgrActionPerformed(evt);
}
});
jTextFieldIonicStgr.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextFieldIonicStgrFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jTextFieldIonicStgrFocusLost(evt);
}
});
jTextFieldIonicStgr.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTextFieldIonicStgrKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextFieldIonicStgrKeyTyped(evt);
}
});
jLabelIonicStrM.setText("<html>mol/(kg H<sub>2</sub>O)</html>");
jLabelIonicStrM.setEnabled(false);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabelIonicStr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextFieldIonicStgr, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelIonicStrM, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(7, 7, 7))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelIonicStr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextFieldIonicStgr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelIonicStrM, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jLabelT.setText("<html>temperature =</html>");
jLabelT.setEnabled(false);
jLabelTC.setText("<html>°C</html>");
jLabelTC.setEnabled(false);
jLabelP.setText("<html>pressure =</html>");
jLabelP.setEnabled(false);
jLabelPressure.setText("88.36");
jLabelPressure.setEnabled(false);
jLabelBar.setText("<html> bar</html>");
jLabelBar.setEnabled(false);
jLabelTemperature.setText("25");
jLabelTemperature.setEnabled(false);
javax.swing.GroupLayout jPanelTLayout = new javax.swing.GroupLayout(jPanelT);
jPanelT.setLayout(jPanelTLayout);
jPanelTLayout.setHorizontalGroup(
jPanelTLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelTLayout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jLabelT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelTemperature)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelTC, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(88, 88, 88)
.addComponent(jLabelP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelPressure)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(85, Short.MAX_VALUE))
);
jPanelTLayout.setVerticalGroup(
jPanelTLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelTLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelTC, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelPressure)
.addComponent(jLabelBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelTemperature))
);
jLabelModel.setLabelFor(jComboBoxModel);
jLabelModel.setText("<html>activity <u>C</u>officient model:<html>");
jComboBoxModel.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Davies eqn.", "SIT (Specific Ion interaction 'Theory')", "simplified HKF (Helgeson, Kirkham & Flowers)" }));
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jComboBoxModel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelModel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(28, Short.MAX_VALUE))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addComponent(jLabelModel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBoxModel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanelActCLayout = new javax.swing.GroupLayout(jPanelActC);
jPanelActC.setLayout(jPanelActCLayout);
jPanelActCLayout.setHorizontalGroup(
jPanelActCLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelActCLayout.createSequentialGroup()
.addGroup(jPanelActCLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelActCLayout.createSequentialGroup()
.addGroup(jPanelActCLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelActCLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jCheckActCoeff, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanelT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(18, Short.MAX_VALUE))
);
jPanelActCLayout.setVerticalGroup(
jPanelActCLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelActCLayout.createSequentialGroup()
.addGroup(jPanelActCLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelActCLayout.createSequentialGroup()
.addComponent(jCheckActCoeff, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanelT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(33, Short.MAX_VALUE))
);
jLabelTol.setLabelFor(jComboBoxTol);
jLabelTol.setText("tolerance (for calculations in HaltaFall):");
jComboBoxTol.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1E-2", "1E-3", "1E-4", "1E-5", "1E-6", "1E-7", "1E-8", "1E-9", " " }));
jComboBoxTol.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBoxTolActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jLabelTol)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBoxTol, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelTol)
.addComponent(jComboBoxTol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
javax.swing.GroupLayout jPanelParametersLayout = new javax.swing.GroupLayout(jPanelParameters);
jPanelParameters.setLayout(jPanelParametersLayout);
jPanelParametersLayout.setHorizontalGroup(
jPanelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelParametersLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelParametersLayout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanelFiles, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jPanel4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanelActC, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel6, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelParametersLayout.setVerticalGroup(
jPanelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelParametersLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jPanelFiles, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanelActC, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(80, Short.MAX_VALUE))
);
jTabbedPane.addTab("<html><u>P</u>arameters</html>", jPanelParameters);
jScrollPaneMessg.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
jScrollPaneMessg.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
jScrollPaneMessg.setFont(new java.awt.Font("Monospaced", 0, 13)); // NOI18N
jTextAreaA.setBackground(new java.awt.Color(255, 255, 204));
jTextAreaA.setText("Use the PrintStreams \"err\" and \"out\" to\nsend messages to this pane, for example;\n out.println(\"message\");\n err.println(\"Error\");\netc.\nSystem.out and System.err will send\noutput to the console, which might\nnot be available to the user.");
jTextAreaA.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTextAreaAKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextAreaAKeyTyped(evt);
}
});
jScrollPaneMessg.setViewportView(jTextAreaA);
jTabbedPane.addTab("Messages", jScrollPaneMessg);
jPanelDiagram.setBackground(new java.awt.Color(255, 255, 255));
javax.swing.GroupLayout jPanelDiagramLayout = new javax.swing.GroupLayout(jPanelDiagram);
jPanelDiagram.setLayout(jPanelDiagramLayout);
jPanelDiagramLayout.setHorizontalGroup(
jPanelDiagramLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 611, Short.MAX_VALUE)
);
jPanelDiagramLayout.setVerticalGroup(
jPanelDiagramLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jTabbedPane.addTab("Diagram", jPanelDiagram);
jPanelStatusBar.setBackground(new java.awt.Color(204, 255, 255));
jPanelStatusBar.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jLabelStatus.setText("# # # #");
jLabelProgress.setText("text");
javax.swing.GroupLayout jPanelStatusBarLayout = new javax.swing.GroupLayout(jPanelStatusBar);
jPanelStatusBar.setLayout(jPanelStatusBarLayout);
jPanelStatusBarLayout.setHorizontalGroup(
jPanelStatusBarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelStatusBarLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabelStatus)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabelProgress, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jPanelStatusBarLayout.setVerticalGroup(
jPanelStatusBarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelStatusBarLayout.createSequentialGroup()
.addGroup(jPanelStatusBarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelProgress)
.addComponent(jLabelStatus))
.addContainerGap())
);
jMenuFile.setMnemonic('F');
jMenuFile.setText("File");
jMenuFileOpen.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.ALT_MASK));
jMenuFileOpen.setMnemonic('o');
jMenuFileOpen.setText("Open input file");
jMenuFileOpen.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuFileOpenActionPerformed(evt);
}
});
jMenuFile.add(jMenuFileOpen);
jMenuFileMakeD.setMnemonic('D');
jMenuFileMakeD.setText("make the Diagram");
jMenuFileMakeD.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuFileMakeDActionPerformed(evt);
}
});
jMenuFile.add(jMenuFileMakeD);
jMenuFileXit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK));
jMenuFileXit.setMnemonic('x');
jMenuFileXit.setText("Exit");
jMenuFileXit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuFileXitActionPerformed(evt);
}
});
jMenuFile.add(jMenuFileXit);
jMenuBar.add(jMenuFile);
jMenuDebug.setMnemonic('b');
jMenuDebug.setText("debug");
jCheckBoxMenuPredomDebug.setMnemonic('V');
jCheckBoxMenuPredomDebug.setText("Verbose");
jCheckBoxMenuPredomDebug.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxMenuPredomDebugActionPerformed(evt);
}
});
jMenuDebug.add(jCheckBoxMenuPredomDebug);
jMenuSave.setMnemonic('v');
jMenuSave.setText("save messages to file");
jMenuSave.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuSaveActionPerformed(evt);
}
});
jMenuDebug.add(jMenuSave);
jMenuCancel.setMnemonic('S');
jMenuCancel.setText("STOP the Calculations (Alt-S)");
jMenuCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuCancelActionPerformed(evt);
}
});
jMenuDebug.add(jMenuCancel);
jMenuBar.add(jMenuDebug);
jMenuHelp.setText("Help");
jMenuHelpAbout.setMnemonic('a');
jMenuHelpAbout.setText("About");
jMenuHelpAbout.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuHelpAboutActionPerformed(evt);
}
});
jMenuHelp.add(jMenuHelpAbout);
jMenuBar.add(jMenuHelp);
setJMenuBar(jMenuBar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTabbedPane)
.addComponent(jPanelStatusBar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jTabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 426, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanelStatusBar, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
//<editor-fold defaultstate="collapsed" desc="Events">
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
end_program();
}//GEN-LAST:event_formWindowClosing
private void jMenuHelpAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuHelpAboutActionPerformed
jMenuHelpAbout.setEnabled(false);
Thread hlp = new Thread() {@Override public void run(){
helpAboutFrame = new HelpAboutF(VERS, pathApp, out);
helpAboutFrame.setVisible(true);
helpAboutFrame.waitFor();
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
helpAboutFrame = null;
jMenuHelpAbout.setEnabled(true);
}}); //invokeLater(Runnable)
}};//new Thread
hlp.start();
}//GEN-LAST:event_jMenuHelpAboutActionPerformed
private void jMenuFileXitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuFileXitActionPerformed
end_program();
}//GEN-LAST:event_jMenuFileXitActionPerformed
private void jMenuFileOpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuFileOpenActionPerformed
eraseTextArea = true;
getTheInputFileName();
jTabbedPane.requestFocusInWindow();
}//GEN-LAST:event_jMenuFileOpenActionPerformed
private void jMenuFileMakeDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuFileMakeDActionPerformed
jButtonDoIt.doClick();
}//GEN-LAST:event_jMenuFileMakeDActionPerformed
private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
int width = originalSize.width;
int height = originalSize.height;
if(this.getHeight()<height){this.setSize(this.getWidth(), height);}
if(this.getWidth()<width){this.setSize(width,this.getHeight());}
if(jTabbedPane.getWidth()>this.getWidth()) {
jTabbedPane.setSize(this.getWidth(), jTabbedPane.getWidth());
}
}//GEN-LAST:event_formComponentResized
private void jTextAreaAKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextAreaAKeyTyped
evt.consume();
}//GEN-LAST:event_jTextAreaAKeyTyped
private void jTextAreaAKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextAreaAKeyPressed
if(!Util.isKeyPressedOK(evt)) {evt.consume();}
}//GEN-LAST:event_jTextAreaAKeyPressed
private void jCheckBoxMenuPredomDebugActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxMenuPredomDebugActionPerformed
dbg = jCheckBoxMenuPredomDebug.isSelected();
}//GEN-LAST:event_jCheckBoxMenuPredomDebugActionPerformed
private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus
if(helpAboutFrame != null) {helpAboutFrame.bringToFront();}
}//GEN-LAST:event_formWindowGainedFocus
private void jComboBoxTolActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxTolActionPerformed
int i = jComboBoxTol.getSelectedIndex();
tolHalta = 0.01/Math.pow(10,i);
}//GEN-LAST:event_jComboBoxTolActionPerformed
private void jButtonDoItActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDoItActionPerformed
// If no plot-file name is given in the command line but
// a data-file name is given: set a default plot-file name
if(outputPltFile == null) {
String dir = pathDef.toString();
if(dir.endsWith(SLASH)) {dir = dir.substring(0,dir.length()-1);}
outputPltFile = new java.io.File(dir + SLASH + jTextFieldPltFile.getText());
}
// note: as the calculations are done on a worker thread, this returns pretty quickly
doCalculations();
// statements here are performed almost inmediately
}//GEN-LAST:event_jButtonDoItActionPerformed
private void jTextFieldIonicStgrKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldIonicStgrKeyTyped
char key = evt.getKeyChar();
if(!isCharOKforNumberInput(key)) {evt.consume();}
}//GEN-LAST:event_jTextFieldIonicStgrKeyTyped
private void jTextFieldIonicStgrKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldIonicStgrKeyPressed
if(evt.getKeyChar() == java.awt.event.KeyEvent.VK_ENTER) {
validateIonicStrength();
}
}//GEN-LAST:event_jTextFieldIonicStgrKeyPressed
private void jTextFieldIonicStgrFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldIonicStgrFocusLost
validateIonicStrength();
}//GEN-LAST:event_jTextFieldIonicStgrFocusLost
private void jTextFieldIonicStgrFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldIonicStgrFocusGained
jTextFieldIonicStgr.selectAll();
}//GEN-LAST:event_jTextFieldIonicStgrFocusGained
private void jTextFieldIonicStgrActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldIonicStgrActionPerformed
validateIonicStrength();
}//GEN-LAST:event_jTextFieldIonicStgrActionPerformed
private void jCheckActCoeffActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckActCoeffActionPerformed
if(jCheckActCoeff.isSelected()) {
calcActCoeffs = true;
showActivityCoefficientControls(true);
ionicStrength = readIonStrength();
}
else {
calcActCoeffs = false;
showActivityCoefficientControls(false);
}
}//GEN-LAST:event_jCheckActCoeffActionPerformed
private void jCheckReverseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckReverseActionPerformed
reversedConcs = jCheckReverse.isSelected();
}//GEN-LAST:event_jCheckReverseActionPerformed
private void jScrollBarHeightAdjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {//GEN-FIRST:event_jScrollBarHeightAdjustmentValueChanged
jLabelHD.setText(String.valueOf((float)jScrollBarHeight.getValue()/10f).trim());
}//GEN-LAST:event_jScrollBarHeightAdjustmentValueChanged
private void jScrollBarHeightFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jScrollBarHeightFocusLost
jScrollBarHeight.setBorder(null);
}//GEN-LAST:event_jScrollBarHeightFocusLost
private void jScrollBarHeightFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jScrollBarHeightFocusGained
jScrollBarHeight.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0,0,0)));
}//GEN-LAST:event_jScrollBarHeightFocusGained
private void jScrollBarNbrPointsAdjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {//GEN-FIRST:event_jScrollBarNbrPointsAdjustmentValueChanged
jLabelPointsNbr.setText(String.valueOf(jScrollBarNbrPoints.getValue()).trim());
}//GEN-LAST:event_jScrollBarNbrPointsAdjustmentValueChanged
private void jScrollBarNbrPointsFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jScrollBarNbrPointsFocusLost
jScrollBarNbrPoints.setBorder(null);
}//GEN-LAST:event_jScrollBarNbrPointsFocusLost
private void jScrollBarNbrPointsFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jScrollBarNbrPointsFocusGained
jScrollBarNbrPoints.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0,0,0)));
}//GEN-LAST:event_jScrollBarNbrPointsFocusGained
private void jLabelPointsNbrMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelPointsNbrMouseClicked
if(evt.getClickCount() >1) { // double-click
jScrollBarNbrPoints.setValue(NSTP_DEF);
}
}//GEN-LAST:event_jLabelPointsNbrMouseClicked
private void jTextFieldPltFileFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldPltFileFocusGained
jTextFieldPltFile.selectAll();
}//GEN-LAST:event_jTextFieldPltFileFocusGained
private void jTextFieldDataFileKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldDataFileKeyTyped
char c = Character.toUpperCase(evt.getKeyChar());
if(evt.getKeyChar() != java.awt.event.KeyEvent.VK_ESCAPE &&
!(evt.isAltDown() &&
((c == 'A') ||
(c == 'B') || (c == 'C') ||
(c == 'D') || (c == 'E') ||
(c == 'F') || (c == 'H') ||
(c == 'L') || (c == 'M') ||
(c == 'N') ||
(c == 'P') || (c == 'R') ||
(c == 'S') || (c == 'T') ||
(c == 'X') )
) //isAltDown
)
{
evt.consume(); // remove the typed key
getTheInputFileName();
}
}//GEN-LAST:event_jTextFieldDataFileKeyTyped
private void jTextFieldDataFileKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldDataFileKeyPressed
if(!Util.isKeyPressedOK(evt)) {evt.consume();}
}//GEN-LAST:event_jTextFieldDataFileKeyPressed
private void jTextFieldDataFileMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFieldDataFileMouseClicked
eraseTextArea = true;
getTheInputFileName();
}//GEN-LAST:event_jTextFieldDataFileMouseClicked
private void jLabelHDMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelHDMouseClicked
if(evt.getClickCount() >1) { // double-click
jScrollBarHeight.setValue(10);
}
}//GEN-LAST:event_jLabelHDMouseClicked
private void jMenuSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuSaveActionPerformed
jTextFieldDataFile.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
setCursorWait();
if(pathDef == null) {setPathDef();}
String txtfn = Util.getSaveFileName(this, progName, "Choose an output file name:", 7, "messages.txt", pathDef.toString());
jTextFieldDataFile.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
setCursorDef();
if(txtfn == null || txtfn.trim().equals("")) {return;}
java.io.File outputTxtFile = new java.io.File(txtfn);
java.io.Writer w = null;
try {
w = new java.io.BufferedWriter(
new java.io.OutputStreamWriter(
new java.io.FileOutputStream(outputTxtFile),"UTF8"));
w.write(jTextAreaA.getText());
w.flush();
w.close();
javax.swing.JOptionPane.showMessageDialog(this, "File:"+nl+" "+outputTxtFile.toString()+nl+"has been written.",
progName,javax.swing.JOptionPane.INFORMATION_MESSAGE);
}
catch (Exception ex) {showErrMsgBx(ex.toString(),1);}
finally {
try{if(w != null) {w.flush(); w.close();}}
catch (Exception ex) {showErrMsgBx(ex.toString(),1);}
}
jTabbedPane.setSelectedComponent(jScrollPaneMessg);
jTabbedPane.requestFocusInWindow();
}//GEN-LAST:event_jMenuSaveActionPerformed
private void jMenuCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuCancelActionPerformed
quitConfirm(this);
}//GEN-LAST:event_jMenuCancelActionPerformed
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="checkInput">
/** Make checks and make changes to the data stored in the Chem classes.
* @return true if checks are OK */
private boolean checkInput() {
if(cs == null) {err.println("? Programming error in \"PREDOM.checkInput\": cs=null."); return false;}
if(dbg) {out.println("--- checkInput()");}
// -------------------
// CHEMICAL SYSTEM
// -------------------
// mg = total number of soluble species in the aqueous solution:
// all components + soluble complexes
// Note that in HaltaFall the solid components are fictitious soluble
// components with "zero" concentration (with noll = true)
int mg = cs.Ms - cs.mSol; // = na + nx;
int i;
// ---- Remove asterisk "*" from the name of components
for(i=0; i<cs.Na; i++) {
if(namn.identC[i].startsWith("*")) {
namn.identC[i] = namn.identC[i].substring(1);
namn.ident[i] = namn.identC[i];
cs.noll[i] = true;
}
//if(chem_syst.Chem.isWater(csNamn.identC[i]))
// {water = i;}
} // for i=0...Na-1
// ---- Remove reaction products (soluble or solid) with
// name starting with "*".
// Note that the solids corresponding to the components will
// not have a name starting with "*". This is already removed when
// reading the input file.
double w; int j; int js;
i = cs.Na;
while (i < cs.Ms) {
if(namn.ident[i].startsWith("*")) {
if(i < mg) {mg--; cs.nx = cs.nx-1;} else {cs.mSol = cs.mSol -1;}
cs.Ms = cs.Ms -1;
if(i >= cs.Ms) {break;}
for(j=i; j<cs.Ms; j++) {
js = j - cs.Na;
cs.lBeta[js] = cs.lBeta[js+1];
// for(int ia=0; ia<cs.Na; ia++) {cs.a[js][ia] = cs.a[js+1][ia];}
System.arraycopy(cs.a[js+1], 0, cs.a[js], 0, cs.Na);
namn.ident[j] = namn.ident[j+1];
cs.noll[j] = cs.noll[j+1];
}
}
else {i++;}
} //while (true)
// ---- get electric charge, length of name, etc
diag.aquSystem = false;
for(i=0; i<cs.Ms; i++) {
namn.nameLength[i] = getNameLength(namn.ident[i]);
// Species for which the concentration is not to be
// included in the Mass-Balance (for ex. the concentration
// of "free" electrons is excluded)
if(Util.isElectron(namn.ident[i]) ||
Util.isWater(namn.ident[i])) {
cs.noll[i] = true;
diag.aquSystem = true;} // e- or H2O
if(i < mg) { //aqueous species
namn.z[i]=0;
csC.logf[i] = 0;
if(namn.ident[i].length() >4 &&
namn.ident[i].toUpperCase().endsWith("(AQ)")) {
diag.aquSystem = true;}
else { //does not end with "(aq)"
namn.z[i] = Util.chargeOf(namn.ident[i]);
if(namn.z[i] != 0) {diag.aquSystem = true;}
} // ends with "(aq)"?
}// if i < mg
} // for i=0...Ms-1
// The electric charge of two fictive species (Na+ and Cl-)
// that are used to ensure electrically neutral aqueous solutions
// when calculating the ionic strength and activity coefficients
namn.z[mg] = 1; //electroneutrality "Na+"
namn.z[mg+1] =-1; //electroneutrality "Na+"
// ---- set Gaseous species to have zero conc
// if it is an aqueous system
if(diag.aquSystem) {
for(i =0; i < mg; i++) {
if(Util.isGas(namn.ident[i]) ||
Util.isLiquid(namn.ident[i]) ||
Util.isWater(namn.ident[i])) {
cs.noll[i] = true;}
} //for i
} //if aquSystem
// ---- Remove H2O among the complexes, if found
if(diag.aquSystem) {
for(i=cs.Na; i<cs.Ms; i++) {
if(Util.isWater(namn.ident[i])) {
if(i < mg) {mg--; cs.nx = cs.nx-1;} else {cs.mSol = cs.mSol -1;}
cs.Ms = cs.Ms -1;
if(i >= cs.Ms) {break;}
for(j=i; j<cs.Ms; j++) {
js = j - cs.Na;
cs.lBeta[js] = cs.lBeta[js+1];
//for(int ia=0; ia<cs.Na; ia++) {cs.a[js][ia] = cs.a[js+1][ia];}
System.arraycopy(cs.a[js+1], 0, cs.a[js], 0, cs.Na);
namn.ident[j] = namn.ident[j+1];
cs.noll[j] = cs.noll[j+1];
}
} //ident[i]="H2O"
} //for i
} //if aquSystem
if(dbg) {cs.printChemSystem(out);}
// ---- Check that all reactions are charge balanced
if(calcActCoeffs) {
double zSum;
boolean ok = true;
for(i=cs.Na; i < mg; i++) {
int ix = i - cs.Na;
zSum = (double)(-namn.z[i]);
for(j=0; j < cs.Na; j++) {
zSum = zSum + cs.a[ix][j]*(double)namn.z[j];
} //for j
if(Math.abs(zSum) > 0.0005) {
ok = false;
err.format(engl,"--- Warning: %s, z=%3d, charge imbalance:%9.4f",
namn.ident[i],namn.z[i],zSum);
}
} //for i
if(!ok) {
if(!showErrMsgBxCancel("There are charge imbalanced reactions in the input file.",1)) {
return false;
}
}
} // if calcActCoeffs
// ---- Check that at least there is one fuid species active
boolean foundOne = false;
for(i =0; i < mg; i++) {
if(!cs.noll[i]) {foundOne = true; break;}
} //for i
if(!foundOne) {
String t = "Error: There are no fluid species active ";
if(cs.mSol > 0) {t = t.concat("(Only solids)");}
t = t+nl+"This program can not handle such chemical systems.";
showErrMsgBx(t,1);
return false;
}
// --------------------
// PLOT INFORMATION
// --------------------
diag.pInX =0; diag.pInY = 0;
// pInX=0 "normal" X-axis
// pInX=1 pH in X-axis
// pInX=2 pe in X-axis
// pInX=3 Eh in X-axis
if(Util.isElectron(namn.identC[diag.compX])) {
if(diag.Eh) {diag.pInX = 3;} else {diag.pInX = 2;}
} else if(Util.isProton(namn.identC[diag.compX])) {diag.pInX = 1;}
if(Util.isElectron(namn.identC[diag.compY])) {
if(diag.Eh) {diag.pInY = 3;} else {diag.pInY = 2;}
} else if(Util.isProton(namn.identC[diag.compY])) {diag.pInY = 1;}
// ----------------------------------------------
// CHECK THE CONCENTRATION FOR EACH COMPONENT
// ----------------------------------------------
for(int ia =0; ia < cs.Na; ia++) {
if(dgrC.hur[ia]==1 && // T
ia==diag.compX) {
showErrMsgBx("Error: the concentration for component \""+namn.identC[ia]+"\" "+
"must vary, as it belongs to the X-axis!",1);
return false;
}
if(ia==diag.compMain && dgrC.hur[ia]==1 && // T
Math.abs(dgrC.cLow[ia]) <= 0) {
if(!showErrMsgBxCancel("The concentration for "+nl
+"the main component \""+namn.identC[ia]+"\" is zero!",1)) {return false;}
}
if(dgrC.hur[ia] >0 && dgrC.hur[ia]<=3) { //T, TV or LTV
if(Util.isWater(namn.identC[ia])) {
showErrMsgBx("Error: The calculations are made for 1kg H2O"+nl+
"Give log(H2O-activity) instead of a total conc. for water.",1);
return false;
} // if water
} //if T, TV or LTV
if(dgrC.hur[ia] ==2 || dgrC.hur[ia] ==3 || dgrC.hur[ia] ==5) { //TV, LTV or LAV
if(ia != diag.compX && ia != diag.compY) {
String t;
if(dgrC.hur[ia] ==5) {t="log(activity)";} else {t="total conc.";}
String msg = "Error: The "+t+" is varied for \""+namn.identC[ia]+"\""+nl+
" but this component is neither the component in the Y-axis ("+namn.identC[diag.compY]+"),"+nl+
" nor the component in the X-axis ("+namn.identC[diag.compX]+")!";
showErrMsgBx(msg,2);
return false;
}
} //if TV, LTV or LAV
if((dgrC.hur[ia] ==1 || dgrC.hur[ia] ==4) && //T or LA
(ia == diag.compX || ia == diag.compY)) {
String t, ax;
if(dgrC.hur[ia] ==4) {t="log(activity)";} else {t="total conc.";}
if(ia == diag.compX) {ax="X";} else {ax="Y";}
showErrMsgBx("Error: The "+t+" of \""+namn.identC[ia]+"\""+nl+
"can NOT be a fixed value because this component belongs to the "+ax+"-axis !",1);
return false;
}
if(dgrC.hur[ia] ==1 && // T
Math.abs(dgrC.cLow[ia]) >100) {
String t = String.format(engl,"Error: For component: "+namn.identC[ia]+nl+
" Tot.Conc.=%12.4g mol/kg. This is not a reasonable value!",dgrC.cLow[ia]);
showErrMsgBx(t,1);
return false;
}
if(dgrC.hur[ia] ==4 && // LA
Util.isProton(namn.identC[ia]) &&
(dgrC.cLow[ia] <-14 || dgrC.cLow[ia] >2)) {
String msg = String.format(engl,"Warning: In the input, you give pH =%8.2f%n"+
"This value could be due to an input error.",(-dgrC.cLow[ia]));
if(!showErrMsgBxCancel(msg,2)) {return false;}
}
if(dgrC.hur[ia] !=1 && dgrC.hur[ia] !=4) {//if TV, LTV or LAV
if(dgrC.cLow[ia] == dgrC.cHigh[ia] ||
Math.max(Math.abs(dgrC.cLow[ia]), Math.abs(dgrC.cHigh[ia])) < 1e-15) {
showErrMsgBx("Error: Min-value = Max-value for component \""+namn.identC[ia]+"\"",1);
return false;
}
if(dgrC.cLow[ia] > dgrC.cHigh[ia] && !reversedConcs) {
w = dgrC.cLow[ia];
dgrC.cLow[ia] = dgrC.cHigh[ia];
dgrC.cHigh[ia] = w;
}
if(!reversedConcs && dgrC.hur[ia] ==5 && // pH/pe/EH varied - LAV
(Util.isProton(namn.identC[ia]) ||
Util.isElectron(namn.identC[ia]))) {
w = dgrC.cLow[ia];
dgrC.cLow[ia] = dgrC.cHigh[ia];
dgrC.cHigh[ia] = w;
}
if(dgrC.hur[ia] ==5 && // LAV
(Util.isProton(namn.identC[ia])) &&
(dgrC.cLow[ia] <-14.00001 || dgrC.cLow[ia] >2.00001 ||
dgrC.cHigh[ia] <-14.00001 || dgrC.cHigh[ia] >2.00001)) {
String msg = String.format(engl,"Warning: In the input, you give pH =%8.2f to %7.2f%n"+
"These values could be due to an input error.",(-dgrC.cLow[ia]),(-dgrC.cHigh[ia]));
if(!showErrMsgBxCancel(msg,2)) {return false;}
}
if(dgrC.hur[ia] ==2 && // TV
(Math.max(Math.abs(dgrC.cHigh[ia]),Math.abs(dgrC.cLow[ia]))>100)) {
showErrMsgBx("Error: You give ABS(TOT.CONC.) > 100 for component: "+namn.identC[ia]+nl+
"This value is too high and perhaps an input error."+nl+
"Set the maximum ABS(TOT.CONC.) value to 100.",1);
return false;
}
if(dgrC.hur[ia] ==3) { // LTV
if((Math.min(dgrC.cLow[ia], dgrC.cHigh[ia]) < -7.0001) &&
(Util.isProton(namn.identC[ia]))) {
String msg = "Warning: You give a LOG (TOT.CONC.) < -7 for component: "+namn.identC[ia]+nl+
"This value is rather low and could be due to an input error."+nl+
"Maybe you meant to set LOG (ACTIVITY) < -7 ??";
if(!showErrMsgBxCancel(msg,2)) {return false;}
}
if(Math.max(dgrC.cLow[ia], dgrC.cHigh[ia]) > 2.0001) {
showErrMsgBx("Error: You give a LOG (TOT.CONC.) > 2 for component: "+namn.identC[ia]+nl+
"This value is too high and it could be due to an input error."+nl+
"Please set the LOG (TOT.CONC.) value to <=2.",1);
return false;
}
} //if LTV
} //if TV, LTV or LAV
} // for ia = 0... Na-1
// ----------------
// OTHER CHECKS
// ----------------
if(cs.nx == 0) {
for(i =0; i < cs.Na; i++) {
if(csC.kh[i] == 2) {continue;} //only it Tot.conc. is given
if(i == diag.compX || i == diag.compY) { //component in an axis:
if(i >= (cs.Na-cs.solidC)) { //is it a solid?
if(!showErrMsgBxCancel("Warning: with no complexes in the fluid phase you should not have"+nl+
"a solid component ("+namn.identC[i]+") in an axis.",2)) {return false;}
}
}
} //for i
} //if nx=0
// ---- Check that a total concentration is given for the main component
// is it a solid? and log(activity) given?
if(diag.compMain >= (cs.Na - cs.solidC) && csC.kh[diag.compMain] == 2) {
String v;
if(dgrC.hur[diag.compMain] == 5) {v = " varied";} else {v = "";}
String t = "Error: For the main component \""+namn.identC[diag.compMain]+"\""+nl+
" please give its total concentration"+v+nl+
" instead of its log(activity)"+v;
showErrMsgBx(t+".",1);
return false;
}
// ---- See which components have positive or negative (or both)
// values for the stoichiometric coefficients (a[ix][ia]-values)
pos = new boolean[cs.Na];
neg = new boolean[cs.Na];
for(i =0; i < cs.Na; i++) {
pos[i] = false; neg[i] = false;
if(csC.kh[i] == 2) {continue;} //only it Tot.conc. is given
if(!cs.noll[i]) { // if not "e-" and not solid component
pos[i] = true;}
for(j = cs.Na; j < cs.Ms; j++) {
if(!cs.noll[j]) {
if(cs.a[j-cs.Na][i] >0) {pos[i] = true;}
if(cs.a[j-cs.Na][i] <0) {neg[i] = true;}
} // !noll
} //for j
} //for i
// check POS and NEG with the Tot.Conc. given in the input
for(i =0; i < cs.Na; i++) {
if(csC.kh[i] == 2) {continue;} //only it Tot.conc. is given
if((!pos[i] && !neg[i]) ) { // || cs.nx ==0
String msg = "Error: for component \""+namn.identC[i]+"\" give Log(Activity)";
if(dgrC.hur[i] !=1) { // not "T", that is: "TV" or "LTV"
msg = msg+" to vary";}
showErrMsgBx(msg,1);
return false;
} //if Nx =0 or (!pos[] & !neg[])
if((pos[i] && neg[i]) ||
(pos[i] && (dgrC.hur[i] ==3 || //LTV
(dgrC.cLow[i]>0 && (Double.isNaN(dgrC.cHigh[i]) || dgrC.cHigh[i]>0)))) ||
(neg[i] && (
dgrC.hur[i] !=3 && //LTV
(dgrC.cLow[i]<0 && (Double.isNaN(dgrC.cHigh[i]) || dgrC.cHigh[i]<0))))) {
continue;
}
if(pos[i] || neg[i]) {
String msg = "Error: Component \"%s\" may not have %s Tot.Conc. values.%s"+
"Give either Tot.Conc. %s=0.0 or Log(Activity)%s";
if(!pos[i] && (dgrC.cLow[i]>0 || (!Double.isNaN(dgrC.cHigh[i]) && dgrC.cHigh[i]>0))) {
showErrMsgBx(String.format(msg, namn.identC[i], "positive", nl,"<",nl),1);
return false;}
if(!neg[i] && (dgrC.cLow[i]<0 || (!Double.isNaN(dgrC.cHigh[i]) && dgrC.cHigh[i]<0))) {
showErrMsgBx(String.format(msg, namn.identC[i], "negative", nl,">",nl),1);
return false;}
} //if pos or neg
} //for i
// OK so far. Update "nx" (=nbr of soluble complexes)
cs.nx = mg - cs.Na;
return true;
} // checkInput()
//<editor-fold defaultstate="collapsed" desc="getNameLength(species)">
private static int getNameLength(String species) {
int nameL = Math.max(1, Util.rTrim(species).length());
if(nameL < 3) {return nameL;}
// Correct name length if there is a space between name and charge
// "H +", "S 2-", "Q 23+"
int sign; int ik;
sign =-1;
for(ik =nameL-1; ik >= 2; ik--) {
char c = species.charAt(ik);
if(c == '+' || c == '-' ||
// unicode en dash or unicode minus
c =='\u2013' || c =='\u2212') {sign = ik; break;}
} //for ik
if(sign <2) {return nameL;}
if(sign < nameL-1 &&
(Character.isLetterOrDigit(species.charAt(sign+1)))) {return nameL;}
if(species.charAt(sign-1) == ' ')
{nameL = nameL-1; return nameL;}
if(nameL >=4) {
if(species.charAt(sign-1) >= '2' && species.charAt(sign-1) <= '9' &&
species.charAt(sign-2) == ' ')
{nameL = nameL-1; return nameL;}
} //if nameL >=4
if(nameL >=5) {
if((species.charAt(sign-1) >= '0' && species.charAt(sign-1) <= '9') &&
(species.charAt(sign-2) >= '1' && species.charAt(sign-2) <= '9') &&
species.charAt(sign-3) == ' ')
{nameL = nameL-1;}
} //if nameL >=5
return nameL;
} // getNameLength(species)
//</editor-fold>
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="dispatchArg">
/**
* @param arg String containing a command-line argument
* @return false if there was an error associated with the command argument
*/
private boolean dispatchArg(String arg) {
if(arg == null) {return true;}
out.println("Command-line argument = \""+arg+"\"");
if(arg.equals("-?") || arg.equals("/?") || arg.equals("?")) {
out.println("Usage: PREDOM [-command=value]");
printInstructions(out);
if(this.isVisible()) {jTabbedPane.setSelectedComponent(jScrollPaneMessg);}
return true;} //if args[] = "?"
String msg = null;
while(true) {
if(arg.length() >3) {
String arg0 = arg.substring(0, 2).toLowerCase();
if(arg0.startsWith("-d") || arg0.startsWith("/d")) {
if(arg.charAt(2) == '=' || arg.charAt(2) == ':') {
String f = arg.substring(3);
if(f.startsWith("\"") && f.endsWith("\"")) { //remove enclosing quotes
f = f.substring(1, f.length()-1);
}
if(!f.toLowerCase().endsWith(".dat")) {f = f.concat(".dat");}
inputDataFile = new java.io.File(f);
setPathDef(inputDataFile);
//get the complete file name
String fil;
try {fil = inputDataFile.getCanonicalPath();}
catch (java.io.IOException e) {
try{fil = inputDataFile.getAbsolutePath();}
catch (Exception e1) {fil = inputDataFile.getPath();}
}
inputDataFile = new java.io.File(fil);
if(dbg){out.println("Data file: "+inputDataFile.getAbsolutePath());}
if(!doNotExit) {consoleOutput = true;}
if(!readDataFile(inputDataFile)) {
//-- error reading data file
if(this.isVisible()) {jTabbedPane.setSelectedComponent(jScrollPaneMessg);}
inputDataFileInCommandLine = false;
return false;
}
else {showTheInputFileName(inputDataFile);}
inputDataFileInCommandLine = true;
return true; // no error
}// = or :
} else if(arg0.startsWith("-p") || arg0.startsWith("/p")) {
if(arg.charAt(2) == '=' || arg.charAt(2) == ':') {
String f = arg.substring(3);
if(f.startsWith("\"") && f.endsWith("\"")) { //remove enclosing quotes
f = f.substring(1, f.length()-1);
}
if(!f.toLowerCase().endsWith(".plt")) {f = f.concat(".plt");}
outputPltFile = new java.io.File(f);
if(dbg){out.println("Plot file: "+outputPltFile.getAbsolutePath());}
jTextFieldPltFile.setText(outputPltFile.getName());
return true;
}// = or :
} else if(arg0.startsWith("-i") || arg0.startsWith("/i")) {
if(arg.charAt(2) == '=' || arg.charAt(2) == ':') {
String t = arg.substring(3);
try {ionicStrength = Double.parseDouble(t);
ionicStrength = Math.max(-1,Math.min(1000,ionicStrength));
if(ionicStrength < 0) {ionicStrength = -1;}
jTextFieldIonicStgr.setText(String.valueOf(ionicStrength));
if(Math.abs(ionicStrength) > 1e-10) {calcActCoeffs = true;}
if(dbg) {out.println("Ionic strength = "+ionicStrength);}
return true;
} //try
catch (NumberFormatException nfe) {
msg = "Wrong numeric format for ionic strength in text \""+t+"\"";
ionicStrength = 0;
jTextFieldIonicStgr.setText(String.valueOf(ionicStrength));
break;
} //catch
}// = or :
} else if(arg0.startsWith("-t") || arg0.startsWith("/t")) {
if(arg.charAt(2) == '=' || arg.charAt(2) == ':') {
String t = arg.substring(3);
try {temperature_InCommandLine = Double.parseDouble(t);
temperature_InCommandLine = Math.min(1000,Math.max(temperature_InCommandLine,-10));
jLabelTemperature.setText(String.valueOf(temperature_InCommandLine));
if(dbg) {out.println("Temperature = "+temperature_InCommandLine);}
return true;
} //try
catch (NumberFormatException nfe) {
msg = "Error: Wrong numeric format for temperature in text \""+t+"\"";
temperature_InCommandLine = Double.NaN;
break;
} //catch
}// = or :
} else if(arg0.startsWith("-h") || arg0.startsWith("/h")) {
if(arg.charAt(2) == '=' || arg.charAt(2) == ':') {
String t = arg.substring(3);
try {tHeight = Double.parseDouble(t);
tHeight = Math.min(10,Math.max(tHeight, 0.3));
jScrollBarHeight.setValue(Math.round((float)(10*tHeight)));
if(dbg) {out.println("Height factor for texts in diagrams = "+tHeight);}
return true;
} //try
catch (NumberFormatException nfe) {
msg = "Wrong numeric format for text height in \""+t+"\"";
tHeight =1;
jScrollBarHeight.setValue(Math.round((float)(10*tHeight)));
break;
} //catch
}// = or :
} // if starts with "-h"
if(arg0.startsWith("-m") || arg0.startsWith("/m")) {
if(arg.charAt(2) == '=' || arg.charAt(2) == ':') {
String t = arg.substring(3);
try {actCoeffsModel_InCommandLine = Integer.parseInt(t);
actCoeffsModel_InCommandLine = Math.min(jComboBoxModel.getItemCount()-1,
Math.max(0,actCoeffsModel_InCommandLine));
jComboBoxModel.setSelectedIndex(actCoeffsModel_InCommandLine);
if(dbg) {out.println("Activity coeffs. method = "+actCoeffsModel_InCommandLine);}
return true;
} //try
catch (NumberFormatException nfe) {
msg = "Wrong numeric format for activity coeff. model in \""+t+"\"";
actCoeffsModel_InCommandLine = actCoeffsModelDefault;
jComboBoxModel.setSelectedIndex(actCoeffsModelDefault);
break;
} //catch
}// = or :
} else if(arg0.startsWith("-n") || arg0.startsWith("/n")) {
if(arg.charAt(2) == '=' || arg.charAt(2) == ':') {
String t = arg.substring(3);
try {nSteps = Integer.parseInt(t);
nSteps = Math.min(NSTP_MAX, Math.max(nSteps, NSTP_MIN));
jScrollBarNbrPoints.setValue(nSteps);
if(dbg) {out.println("Nbr calc. steps in diagram = "+(nSteps)+" (nbr. points = "+(nSteps+1)+")");}
return true;
} //try
catch (NumberFormatException nfe) {
msg = "Wrong numeric format for number of calculation steps in \""+t+"\"";
nSteps =NSTP_DEF;
jScrollBarNbrPoints.setValue(nSteps);
break;
} //catch
}// = or :
} // if starts with "-n"
} // if length >3
if(arg.length() >4) {
String arg0 = arg.substring(0, 4).toLowerCase();
if(arg0.startsWith("-pr") || arg0.startsWith("/pr")) {
if(arg.charAt(4) == '=' || arg.charAt(4) == ':') {
String t = arg.substring(4);
try {pressure_InCommandLine = Double.parseDouble(t);
pressure_InCommandLine = Math.min(10000,Math.max(pressure_InCommandLine,1));
jLabelPressure.setText(String.valueOf(pressure_InCommandLine));
if(dbg) {out.println("Pressure = "+pressure_InCommandLine);}
return true;
} //try
catch (NumberFormatException nfe) {
msg = "Error: Wrong numeric format for pressure in text \""+t+"\"";
pressure_InCommandLine = Double.NaN;
break;
} //catch
}// = or :
} // if starts with "-tol"
} // if length >4
if(arg.length() >5) {
String arg0 = arg.substring(0, 5).toLowerCase();
if(arg0.startsWith("-tol") || arg0.startsWith("/tol")) {
if(arg.charAt(4) == '=' || arg.charAt(4) == ':') {
String t = arg.substring(5);
double w;
try {w = Double.parseDouble(t);
tolHalta = Math.min(1e-2,Math.max(w, 1e-9));
set_tol_inComboBox();
if(dbg) {out.println("Max tolerance in HaltaFall = "+tolHalta);}
return true;
} //try
catch (NumberFormatException nfe) {
msg = "Wrong numeric format for tolerance in \""+t+"\"";
tolHalta = Chem.TOL_HALTA_DEF;
set_tol_inComboBox();
break;
} //catch
}// = or :
} // if starts with "-tol"
}
if(arg.length() >6) {
String arg0 = arg.substring(0, 5).toLowerCase();
if(arg0.startsWith("-dbgh") || arg0.startsWith("/dbgh")) {
if(arg.charAt(5) == '=' || arg.charAt(5) == ':') {
String t = arg.substring(6);
try {dbgHalta = Integer.parseInt(t);
dbgHalta = Math.min(6, Math.max(dbgHalta, 0));
if(dbg) {out.println("Debug printout level in HaltaFall = "+dbgHalta);}
return true;
} //try
catch (NumberFormatException nfe) {
msg = "Wrong numeric format for HaltaFall debug level \""+t+"\" (setting default:"+Chem.DBGHALTA_DEF+")";
dbgHalta = Chem.DBGHALTA_DEF;
break;
} //catch
}// = or :
} // if starts with "-dbgh"
} //if length >6
if(arg.length() >7) {
String arg0 = arg.substring(0, 6).toLowerCase();
if(arg0.startsWith("-units") || arg0.startsWith("/units")) {
if(arg.charAt(6) == '=' || arg.charAt(6) == ':') {
String t = arg.substring(7);
try {conc_units = Integer.parseInt(t);
conc_units = Math.min(2, Math.max(conc_units, -1));
if(dbg) {out.println("Concentration units = "+conc_units+"(\""+cUnits[(conc_units+1)]+"\")");}
return true;
} //try
catch (NumberFormatException nfe) {
msg = "Wrong numeric format for concentration units \""+t+"\" (setting default: 0=\"molal\")";
conc_units = 0;
break;
} //catch
}// = or :
} // if starts with "-dbgh"
} //if length >7
if(arg.equalsIgnoreCase("-ph") || arg.equalsIgnoreCase("/ph")) {
neutral_pH = true;
jCheckBoxMenuPredomDebug.setSelected(dbg);
out.println("Add neutral pH dash-line to plot.");
return true;
} else if(arg.equalsIgnoreCase("-aqu") || arg.equalsIgnoreCase("/aqu")) {
aqu = true;
jCheckBoxMenuPredomDebug.setSelected(dbg);
out.println("Plot only aqueous species; areas for solids not shown.");
return true;
} else if(arg.equalsIgnoreCase("-dbg") || arg.equalsIgnoreCase("/dbg")) {
dbg = true;
jCheckBoxMenuPredomDebug.setSelected(dbg);
out.println("Debug printout = true");
return true;
} else if(arg.equalsIgnoreCase("-rev") || arg.equalsIgnoreCase("/rev")) {
reversedConcs = true;
if(dbg) {out.println("Allow reversed ranges in axes");}
return true;
} else if(arg.equalsIgnoreCase("-keep") || arg.equalsIgnoreCase("/keep")) {
out = outPrintStream; // direct messages to tabbed pane
err = errPrintStream; // direct error messages to tabbed pane
doNotExit = true;
if(dbg) {out.println("Do not close window after calculations");}
return true;
} else if(arg.equalsIgnoreCase("-nostop") || arg.equalsIgnoreCase("/nostop")) {
doNotStop = true;
if(dbg) {out.println("Do not show message boxes");}
return true;
} else if(arg.equalsIgnoreCase("-sci") || arg.equalsIgnoreCase("/sci")) {
conc_nottn = 1;
if(dbg) {out.println("Display concentrations in scientific notation.");}
return true;
} else if(arg.equalsIgnoreCase("-eng") || arg.equalsIgnoreCase("/eng")) {
conc_nottn = 2;
if(dbg) {out.println("Display concentrations in engineerng notation.");}
return true;
}
break;
} //while
if(msg == null) {msg = "Error: can not understand command-line argument:"+nl+
" \""+arg+"\""+nl+"For a list of possible commands type: PREDOM -?";}
else {msg = "Command-line argument \""+arg+"\":"+nl+msg;}
out.flush();
err.println(msg);
err.flush();
printInstructions(out);
if(!doNotStop) {
if(!this.isVisible()) {this.setVisible(true);}
javax.swing.JOptionPane.showMessageDialog(this,msg,progName,
javax.swing.JOptionPane.ERROR_MESSAGE);
}
if(this.isVisible()) {jTabbedPane.setSelectedComponent(jScrollPaneMessg);}
return false;
} // dispatchArg(arg)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="diverse Methods">
//<editor-fold defaultstate="collapsed" desc="showActivityCoefficientControls">
/** show/hide the activity coefficient controls in the window */
private void showActivityCoefficientControls(boolean show) {
if(show) {
jTextFieldIonicStgr.setEnabled(true);
jLabelIonicStr.setEnabled(true);
jLabelIonicStr.setText("<html>ionic <u>S</u>trength</html>");
jLabelIonicStrM.setEnabled(true);
jLabelModel.setEnabled(true);
jLabelModel.setText("<html>activity <u>C</u>officient model:<html>");
jComboBoxModel.setEnabled(true);
} else {
jLabelIonicStr.setEnabled(false);
jLabelIonicStr.setText("ionic Strength");
jLabelIonicStrM.setEnabled(false);
jTextFieldIonicStgr.setEnabled(false);
jLabelModel.setText("activity cofficient model:");
jLabelModel.setEnabled(false);
jComboBoxModel.setEnabled(false);
}
} //showActivityCoefficientControls(show)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="disable/restore Menus">
/** disable menus and buttons during calculations */
private void disableMenus() {
//if(this.isVisible()) {
jMenuFileOpen.setEnabled(false);
jMenuFileMakeD.setEnabled(false);
jMenuDebug.setEnabled(true);
jCheckBoxMenuPredomDebug.setEnabled(false);
jMenuSave.setEnabled(false);
jMenuCancel.setEnabled(true);
jTabbedPane.setSelectedComponent(jScrollPaneMessg);
jLabelData.setText("input data file:");
jLabelData.setEnabled(false);
jTextFieldDataFile.setEnabled(false);
jLabelPltFile.setText("plot file name:");
jLabelPltFile.setEnabled(false);
jTextFieldPltFile.setEnabled(false);
jLabelNbrPText.setText("Nbr of calcs. steps:");
jLabelNbrPText.setEnabled(false);
jLabelPointsNbr.setEnabled(false);
jScrollBarNbrPoints.setEnabled(false);
jLabelHeight.setText("height of text in diagram:");
jLabelHeight.setEnabled(false);
jLabelHD.setEnabled(false);
jScrollBarHeight.setEnabled(false);
jCheckActCoeff.setText("Activity coefficient calculations");
jCheckActCoeff.setEnabled(false);
showActivityCoefficientControls(false);
jLabelTol.setEnabled(false);
jComboBoxTol.setEnabled(false);
jCheckReverse.setText("allow Reversed min. and max. axes limits");
jCheckReverse.setEnabled(false);
jButtonDoIt.setText("make the Diagram");
jButtonDoIt.setEnabled(false);
//} //if visible
} //disableMenus()
/** enable menus and buttons after the calculations are finished
* and the diagram is displayed
* @param allowMakeDiagram if true then the button and menu to make diagrams are enabled,
* they are disabled otherwise */
private void restoreMenus(boolean allowMakeDiagram) {
//if(this.isVisible()) {
jMenuFileOpen.setEnabled(true);
if(allowMakeDiagram) {
jButtonDoIt.setText("<html>make the <u>D</u>iagram</html>");
} else {
jButtonDoIt.setText("make the Diagram");
}
jButtonDoIt.setEnabled(allowMakeDiagram);
jMenuFileMakeD.setEnabled(allowMakeDiagram);
jMenuDebug.setEnabled(true);
jCheckBoxMenuPredomDebug.setEnabled(true);
jMenuSave.setEnabled(true);
jMenuCancel.setEnabled(false);
jLabelData.setEnabled(true);
jTextFieldDataFile.setEnabled(true);
jLabelPltFile.setText("<html>p<u>l</u>ot file name:</html>");
jLabelPltFile.setEnabled(true);
jTextFieldPltFile.setEnabled(true);
jLabelNbrPText.setText("<html><u>N</u>br of calc. steps:</html>");
jLabelNbrPText.setEnabled(true);
jLabelPointsNbr.setEnabled(true);
jScrollBarNbrPoints.setEnabled(true);
jLabelHeight.setText("<html>h<u>e</u>ight of text in diagram:</html>");
jLabelHeight.setEnabled(true);
jLabelHD.setEnabled(true);
jScrollBarHeight.setEnabled(true);
jCheckActCoeff.setText("<html><u>A</u>ctivity coefficient calculations</html>");
jCheckActCoeff.setEnabled(true);
showActivityCoefficientControls(jCheckActCoeff.isSelected());
jLabelPltFile.setText("plot file name");
jLabelPltFile.setEnabled(false);
jTextFieldPltFile.setText(null);
jTextFieldPltFile.setEnabled(false);
//jTextFieldDataFile.setText("");
jLabelTol.setEnabled(true);
jComboBoxTol.setEnabled(true);
jCheckReverse.setText("<html>allow <u>R</u>eversed min. and max. axes limits</html>");
jCheckReverse.setEnabled(true);
jLabelStatus.setText("waiting...");
jLabelProgress.setText(" ");
//} //if visible
} //restoreMenus()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="readDataFile_hadError">
/** enable controls and disable diagram if an error is found when
* reading the input file */
private void readDataFile_hadError() {
out.println("--- Error(s) reading the input file ---");
if(this.isVisible()) {
jTabbedPane.setTitleAt(2, "Diagram");
jTabbedPane.setEnabledAt(2, false); //disable the diagram
restoreMenus(false);
jTabbedPane.setSelectedComponent(jScrollPaneMessg);
}
} // readDataFile_hadError()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="set_tol_inComboBox">
/** find the closest item in the tolerances combo box and select it */
private void set_tol_inComboBox() {
double w0, w1;
int listItem =0;
int listCount = jComboBoxTol.getItemCount();
for(int i =1; i < listCount; i++) {
w0 = Double.parseDouble(jComboBoxTol.getItemAt(i-1).toString());
w1 = Double.parseDouble(jComboBoxTol.getItemAt(i).toString());
if(tolHalta >= w0 && i==1) {listItem = 0; break;}
if(tolHalta <= w1 && i==(listCount-1)) {listItem = (listCount-1); break;}
if(tolHalta < w0 && tolHalta >=w1) {
if(Math.abs(tolHalta-w0) < Math.abs(tolHalta-w1)) {
listItem = i-1;
} else {
listItem = i;
}
break;
}
} //for i
jComboBoxTol.setSelectedIndex(listItem);
} //set_tol_inComboBox()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="end_program">
private void end_program() {
if(dbg) {out.println("--- end_program()");}
if(!finishedCalculations && !quitConfirm(this)) {return;}
programEnded = true;
this.notify_All();
this.dispose();
if(helpAboutFrame != null) {
helpAboutFrame.closeWindow();
helpAboutFrame = null;
}
} // end_program()
//</editor-fold>
private synchronized void notify_All() {this.notifyAll();}
private synchronized void synchWaitCalcs() {
while(!finishedCalculations) {
try {wait();} catch(InterruptedException ex) {}
}
}
private synchronized void synchWaitProgramEnded() {
while(!programEnded) {
try {wait();} catch(InterruptedException ex) {}
}
}
//<editor-fold defaultstate="collapsed" desc="isCharOKforNumberInput">
/** @param key a character
* @return true if the character is ok, that is, it is either a number,
* or a dot, or a minus sign, or an "E" (such as in "2.5e-6") */
private boolean isCharOKforNumberInput(char key) {
return Character.isDigit(key)
|| key == '-' || key == '+' || key == '.' || key == 'E' || key == 'e';
} // isCharOKforNumberInput(char)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="quitConfirm">
private boolean quitConfirm(javax.swing.JFrame c) {
boolean q = true;
if(!doNotStop) {
Object[] options = {"Cancel", "STOP"};
int n = javax.swing.JOptionPane.showOptionDialog (c,
"Do you really want to stop the calculations?",
progName, javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.ERROR_MESSAGE, null, options, null);
q = n == javax.swing.JOptionPane.NO_OPTION;
} //not "do not stop":
if(q) {
if(h != null) {h.haltaCancel();}
finishedCalculations = true;
this.notify_All();
}
return q;
} // quitConfirm(JFrame)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="showTheInputFileName">
/** Show the input data file name in the JFrame (window) */
private void showTheInputFileName(java.io.File dataFile) {
jTextFieldDataFile.setText(dataFile.getAbsolutePath());
jLabelPltFile.setEnabled(true);
jLabelPltFile.setText("<html>p<u>l</u>ot file name:</html>");
jTextFieldPltFile.setEnabled(true);
jMenuFileMakeD.setEnabled(true);
jButtonDoIt.setEnabled(true);
jButtonDoIt.setText("<html>make the <u>D</u>iagram</html>");
jButtonDoIt.requestFocusInWindow();
} // showTheInputFileName()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="setPathDef">
/** Sets the variable "pathDef" to the path of a file.
* Note that "pathDef" may end with the file separator character, e.g. "D:\"
* @param f File */
private void setPathDef(java.io.File f) {
if(pathDef == null) {pathDef = new StringBuffer();}
java.net.URI uri;
if(f != null) {
if(!f.getAbsolutePath().contains(SLASH)) {
// it is a bare file name, without a path
if(pathDef.length()>0) {return;}
}
try{uri = f.toURI();}
catch (Exception ex) {uri = null;}
} else {uri = null;}
if(pathDef.length()>0) {pathDef.delete(0, pathDef.length());}
if(uri != null) {
if(f != null && f.isDirectory()) {
pathDef.append((new java.io.File(uri.getPath())).toString());
} else {
pathDef.append((new java.io.File(uri.getPath())).getParent().toString());
} //directory?
} else { //uri = null: set Default Path = Start Directory
java.io.File currDir = new java.io.File("");
try {pathDef.append(currDir.getCanonicalPath());}
catch (java.io.IOException e) {
try{pathDef.append(System.getProperty("user.dir"));}
catch (Exception e1) {pathDef.append(".");}
}
} //uri = null
} // setPathDef(File)
/** Set the variable "pathDef" to the path of a file name.
* Note that "pathDef" may end with the file separator character, e.g. "D:\"
* @param fName String with the file name */
private void setPathDef(String fName) {
java.io.File f = new java.io.File(fName);
setPathDef(f);
}
/** Set the variable "pathDef" to the user directory ("user.home", system dependent) */
private void setPathDef() {
String t = System.getProperty("user.home");
setPathDef(t);
}
// </editor-fold>
/*
static void pause() {
// Defines the standard input stream
java.io.BufferedReader stdin =
new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
System.out.print ("Press Enter");
System.out.flush();
try{String txt = stdin.readLine();}
catch (java.io.IOException ex) {System.err.println(ex.toString());}
}
*/
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="millisToShortDHMS">
/** converts time (in milliseconds) to human-readable format "<dd>hh:mm:ss"
* @param duration (in milliseconds)
* @return */
public static String millisToShortDHMS(long duration) {
//adapted from http://www.rgagnon.com
String res;
int millis = (int)(duration % 1000);
duration /= 1000;
int seconds = (int) (duration % 60);
duration /= 60;
int minutes = (int) (duration % 60);
duration /= 60;
int hours = (int) (duration % 24);
int days = (int) (duration / 24);
if (days == 0) {
res = String.format("%02d:%02d:%02d.%03d", hours, minutes, seconds,millis);
} else {
res = String.format("%dd%02d:%02d:%02d", days, hours, minutes, seconds);
}
return res;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="setCursor">
private void setCursorWait() {
this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
jTextAreaA.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
}
private void setCursorDef() {
this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jTextAreaA.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="FilteredStreams">
private class errFilteredStreamPredom extends java.io.FilterOutputStream {
private int n=0;
public errFilteredStreamPredom(java.io.OutputStream aStream) {
super(aStream);
} // constructor
@Override
public void write(byte b[]) throws java.io.IOException {
String aString = new String(b);
jTabbedPane.setTitleAt(1, "<html><u>M</u>essages</html>");
jTabbedPane.setEnabledAt(1, true);
jTabbedPane.setSelectedComponent(jScrollPaneMessg);
jTextAreaA.append(aString);
jTextAreaA.setSelectionStart(Integer.MAX_VALUE);
if(n%1000 == 0) {
try{Thread.sleep(1);} catch (InterruptedException ex) {}
n=0;
} else {n++;}
}
@Override
public void write(byte b[], int off, int len) throws java.io.IOException {
String aString = new String(b , off , len);
jTabbedPane.setTitleAt(1, "<html><u>M</u>essages</html>");
jTabbedPane.setEnabledAt(1, true);
jTabbedPane.setSelectedComponent(jScrollPaneMessg);
jTextAreaA.append(aString);
jTextAreaA.setSelectionStart(Integer.MAX_VALUE);
if(n%1000 == 0) {
try{Thread.sleep(1);} catch (InterruptedException ex) {}
n=0;
} else {n++;}
} // write
} // class errFilteredStreamPredom
private class outFilteredStreamPredom extends java.io.FilterOutputStream {
public outFilteredStreamPredom(java.io.OutputStream aStream) {
super(aStream);
} // constructor
@Override
public void write(byte b[]) throws java.io.IOException {
String aString = new String(b);
jTabbedPane.setTitleAt(1, "<html><u>M</u>essages</html>");
jTabbedPane.setEnabledAt(1, true);
jTextAreaA.append(aString);
jTextAreaA.setSelectionStart(Integer.MAX_VALUE);
}
@Override
public void write(byte b[], int off, int len) throws java.io.IOException {
String aString = new String(b , off , len);
jTabbedPane.setTitleAt(1, "<html><u>M</u>essages</html>");
jTabbedPane.setEnabledAt(1, true);
jTextAreaA.append(aString);
jTextAreaA.setSelectionStart(Integer.MAX_VALUE);
} // write
} // class outFilteredStreamPredom
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="findTopSpecies()">
/** get the value of <code>topSpecies</code> */
private void findTopSpecies() {
//if(dbg) {out.println("--- findTopSpecies()");}
double topConc;
double topConcSolid;
if(diag.compMain < (cs.Na - cs.solidC) && !cs.noll[diag.compMain]) {
topConc = csC.C[diag.compMain];
topSpecies = diag.compMain;
} else {topConc = 0; topSpecies = -1;}
double w;
int nIons = cs.Na + cs.nx;
for (int i = cs.Na; i < nIons; i++) {
w = cs.a[i-cs.Na][diag.compMain];
if(Math.abs(w) < 0.00001) {continue;}
w = w * csC.C[i];
if(w <= topConc) {continue;}
topConc = w;
topSpecies = i;
} //for i
if(aqu) {return;}
//plot also predominance areas for solids
topConcSolid = Double.MIN_VALUE;
if(diag.oneArea >= (cs.Na+cs.nx)) { //if only one area is plotted
w = cs.a[diag.oneArea][diag.compMain]*csC.C[diag.oneArea];
if(w > topConcSolid) {topSpecies = diag.oneArea;}
return;
} //if only one area
for (int i = nIons; i < cs.Ms; i++) {
w = cs.a[i-cs.Na][diag.compMain]*csC.C[i];
if(w < topConcSolid) {continue;}
topSpecies = i;
//che if the amount of "compMain" is almost the same for two solids (<0.001% diff)
if(Math.abs(w/topConcSolid)-1 <= 0.00001) {topSpecies = -2;}
topConcSolid = w;
} //for i
} //findTopSpecies()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="getTheInputFileName">
/** Get an input data file name from the user
* using an Open File dialog */
private void getTheInputFileName() {
jTextFieldDataFile.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
setCursorWait();
if(pathDef == null) {setPathDef();}
fc.setMultiSelectionEnabled(false);
fc.setCurrentDirectory(new java.io.File(pathDef.toString()));
fc.setDialogTitle("Select a data file:");
fc.setFileSelectionMode(javax.swing.JFileChooser.FILES_ONLY);
fc.setAcceptAllFileFilterUsed(true);
javax.swing.LookAndFeel defLaF = javax.swing.UIManager.getLookAndFeel();
try {javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());}
catch (Exception ex) {}
fc.updateUI();
jTextFieldDataFile.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
setCursorDef();
fc.setFileFilter(filterDat);
int returnVal = fc.showOpenDialog(this);
// reset the look and feel
try {javax.swing.UIManager.setLookAndFeel(defLaF);}
catch (javax.swing.UnsupportedLookAndFeelException ex) {}
if(returnVal == javax.swing.JFileChooser.APPROVE_OPTION) {
if(eraseTextArea) {
jTextAreaA.selectAll();
jTextAreaA.replaceRange("", 0, jTextAreaA.getSelectionEnd());
}
inputDataFile = fc.getSelectedFile();
setPathDef(fc.getCurrentDirectory());
if(readDataFile(inputDataFile)) {
showTheInputFileName(inputDataFile);
outputPltFile = null;
String txt = inputDataFile.getName();
String plotFileN = txt.substring(0,txt.length()-3).concat("plt");
jTextFieldPltFile.setText(plotFileN);
jTabbedPane.setSelectedComponent(jPanelParameters);
jTabbedPane.setTitleAt(2, "Diagram");
jTabbedPane.setEnabledAt(2, false);
jMenuFileOpen.setEnabled(true);
jMenuFileMakeD.setEnabled(true);
jButtonDoIt.setEnabled(true);
jButtonDoIt.setText("<html>make the <u>D</u>iagram</html>");
jButtonDoIt.requestFocusInWindow();
} // if readDataFile
else {return;}
} // if returnVal = JFileChooser.APPROVE_OPTION
jTabbedPane.setSelectedComponent(jPanelParameters);
jTabbedPane.requestFocusInWindow();
jButtonDoIt.requestFocusInWindow();
jCheckReverse.setText("allow Reversed min. and max. axes limits");
jCheckReverse.setEnabled(false);
} // getTheInputFileName()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="paintDiagrPanel">
/** used when constructing the jPanelDiagram:
* <pre>jPanelDiagram = new javax.swing.JPanel() {
* public void paint(java.awt.Graphics g)
* {
* super.paint(g);
* paintDiagrPanel(g);
* }
* };</pre>
*/
private void paintDiagrPanel(java.awt.Graphics g) {
java.awt.Graphics2D g2D = (java.awt.Graphics2D)g;
if(dd != null) {
diagrPaintUtil.paintDiagram(g2D, jPanelDiagram.getSize(), dd, false);
}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="printInstructions(out)">
private static void printInstructions(java.io.PrintStream out) {
if(out == null) {out = System.out;}
out.flush();
out.println("Possible commands are:"+nl+
" -aqu (plot only aqueous species; areas for solids not shown)"+nl+
" -d=data-file-name (input file name)"+nl+
" -dbg (output debug information)"+nl+
" -dbgH=n (level for debug output from HaltaFall"+nl+
" in the first calculation point; default ="+Chem.DBGHALTA_DEF+")"+nl+
" -d=data-file-name (input file name)"+nl+
" -eng (display concentrations in engineering notation)"+nl+
" -h=nbr (height factor for labels in the plot)"+nl+
" -i=nbr (ionic strength (the equil. constants are"+nl+
" assumed for I=0). Requires a temperature."+nl+
" Enter \"-i=-1\" to calculate I at each point)"+nl+
" -keep (window open at the end)"+nl+
" -m=nbr (model to calculate activity coefficients:"+nl+
" 0 = Davies eqn; 1 = SIT; 2 = simplified HKF; default =2)"+nl+
" -n=nbr (calculation steps along"+nl+ //nStep
" each axes; "+(NSTP_MIN)+" to "+(NSTP_MAX)+")"+nl+
" -nostop (do not stop for warnings)"+nl+
" -p=output-plot-file-name"+nl+
" (note: diagram not displayed after the calculation)"+nl+
" -pH (show neutral pH as a dash line)"+nl+
" -pr=nbr (pressure in bar; displayed in the diagram)"+nl+
" -rev (do not reverse the input"+nl+
" min. and max. limits in x-axis)"+nl+
" -sci (display concentrations in scientific notation)"+nl+
" -t=nbr (temperature in °C, ignored if not needed)"+nl+
" -tol=nbr (tolerance when solving mass-balance equations in Haltafall,"+nl+
" 0.01 >= nbr >= 1e-9; default ="+Chem.TOL_HALTA_DEF+")"+nl+
" -units=nbr (concentration units displayed in the diagram: 0=\"molal\","+nl+
" 1=\"mol/kg_w\", 2=\"M\", -1=\"\")"+nl+
"Enclose file names with double quotes (\"\") it they contain blank space."+nl+
"Example: PREDOM \"/d=Fe 25\" -t:25 -i=-1 \"-p:plt\\Fe 25\" -n=200");
} //printInstructions(out)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="readDataFile">
private boolean readDataFile(java.io.File dataFile) {
if(dbg) {out.println("--- readDataFile("+dataFile.getAbsolutePath()+")");}
String msg;
//--- check the name
if(!dataFile.getName().toLowerCase().endsWith(".dat")) {
msg = "File: \""+dataFile.getName()+"\""+nl+
"Error: data file name must end with \".dat\"";
showErrMsgBx(msg,1);
return false;
}
if(dataFile.getName().length() <= 4) {
msg = "File: \""+dataFile.getName()+"\""+nl+
"Error: file name must have at least one character";
showErrMsgBx(msg,1);
return false;
}
String dataFileN = null;
try {dataFileN = dataFile.getCanonicalPath();} catch (java.io.IOException ex) {}
if(dataFileN == null) {
try {dataFileN = dataFile.getAbsolutePath();}
catch (Exception ex) {dataFileN = dataFile.getPath();}
}
dataFile = new java.io.File(dataFileN);
//
//--- create a ReadDataLib instance
try {rd = new ReadDataLib(dataFile);}
catch (ReadDataLib.DataFileException ex) {
showErrMsgBx(ex.getMessage(),1);
if(rd != null) {
try {rd.close();}
catch (ReadDataLib.ReadDataLibException ex2) {showErrMsgBx(ex2);}
}
return false;
}
msg = "Reading input data file \""+dataFile+"\"";
out.println(msg);
if(consoleOutput) {System.out.println(msg);}
//--- read the chemical system (names, equilibrium constants, stoichiometry)
boolean warn = false; // throw an exception for missing plot data
try {ch = null;
ch = ReadChemSyst.readChemSystAndPlotInfo(rd, dbg, warn, out);
}
catch (ReadChemSyst.ConcDataException ex) {
ch = null; showMsg(ex);
}
catch (ReadChemSyst.DataLimitsException ex) {
ch = null; showMsg(ex);
}
catch (ReadChemSyst.PlotDataException ex) {
ch = null; showMsg(ex);
}
catch (ReadChemSyst.ReadDataFileException ex) {
ch = null; showMsg(ex);
}
if(ch == null) {
msg = "Error while reading data file \""+dataFile.getName()+"\"";
showErrMsgBx(msg,1);
try {rd.close();}
catch (ReadDataLib.ReadDataLibException ex) {showMsg(ex);}
readDataFile_hadError();
return false;
}
if(ch.diag.plotType != 0) {
msg = "Error: data file \""+dataFile.getName()+"\""+nl;
if(ch.diag.plotType >= 1 && ch.diag.plotType <=8) {msg = msg +
"does NOT contain information for a Predominance Area Diagram."+nl+
"Run program SED instead.";}
else {msg = msg + "contains erroneous plot information.";}
showErrMsgBx(msg,1);
try {rd.close();}
catch (ReadDataLib.ReadDataLibException ex) {showMsg(ex);}
readDataFile_hadError();
return false;
}
//
//--- get a temperature:
double t_d, w;
try {w = rd.getTemperature();} // temperature written as a comment in the data file?
catch (ReadDataLib.DataReadException ex) {showErrMsgBx(ex); w = Double.NaN;}
if(!Double.isNaN(w)) {
t_d = w;
if(!Double.isNaN(temperature_InCommandLine)) {
// temperature also given in command line
if(Math.abs(t_d - temperature_InCommandLine)>0.001) { // difference?
msg = String.format(engl,"Warning: temperature in data file =%6.2f,%s",t_d,nl);
msg = msg + String.format(engl,
" but in the command line t=%6.2f!%s",
temperature_InCommandLine,nl);
msg = msg + String.format(engl,"t=%6.2f will be used.",temperature_InCommandLine);
showErrMsgBx(msg,2);
t_d = temperature_InCommandLine;
} // temperatures differ
} // temperature also given
} // temperature written in data file
else {t_d = 25.;}
jLabelTemperature.setText(String.valueOf(t_d));
//--- get a pressure:
double p_d;
try {w = rd.getPressure();} // pressure written as a comment in the data file?
catch (ReadDataLib.DataReadException ex) {showErrMsgBx(ex); w = Double.NaN;}
if(!Double.isNaN(w)) {
p_d = w;
if(!Double.isNaN(pressure_InCommandLine)) {
// pressure also given in command line
if(Math.abs(p_d - pressure_InCommandLine)>0.001) { // difference?
msg = String.format(engl,"Warning: pressure in data file =%.3f bar,%s",p_d,nl);
msg = msg + String.format(engl,
" but in the command line p=%.3f bar!%s",
pressure_InCommandLine,nl);
msg = msg + String.format(engl,"p=%.3f will be used.",pressure_InCommandLine);
showErrMsgBx(msg,2);
p_d = pressure_InCommandLine;
} // pressures differ
} // pressure also given in command line
} // pressure written in data file
else {p_d = 1.;}
jLabelPressure.setText(String.valueOf(p_d));
try {rd.close();}
catch (ReadDataLib.ReadDataLibException ex) {showMsg(ex);}
msg = "Finished reading the input data file.";
out.println(msg);
if(consoleOutput) {System.out.println(msg);}
//--- set the references pointing to the instances of the storage classes
cs = ch.chemSystem;
csC = cs.chemConcs;
namn = cs.namn;
dgrC = ch.diagrConcs;
diag = ch.diag;
//---- Set the calculation instructions for HaltaFall
// Concentration types for each component:
// hur =1 for "T" (fixed Total conc.)
// hur =2 for "TV" (Tot. conc. Varied)
// hur =3 for "LTV" (Log(Tot.conc.) Varied)
// hur =4 for "LA" (fixed Log(Activity) value)
// hur =5 for "LAV" (Log(Activity) Varied)</pre>
for(int j =0; j < cs.Na; j++) {
if(dgrC.hur[j] >3)
{csC.kh[j]=2;} //kh=2 log(activity) is given
//The Mass Balance eqn. has to be solved
else {csC.kh[j]=1;} //kh=1 Tot.Conc. is given
//The Tot.Conc. will be calculated
}
// --------------------------
// --- Check concs. etc ---
// --------------------------
if(!checkInput()) {
ch = null; cs = null; csC = null; namn = null; dgrC = null; diag = null;
readDataFile_hadError();
return false;}
if(cs.jWater >=0 && dbg) {
out.println("Water (H2O) is included. All concentrations are in \"mol/(kg H2O)\".");
}
return true;
} //readDataFile()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Temperature & Ionic Strength">
private void validateIonicStrength() {
if(jTextFieldIonicStgr.getText().length() <=0) {return;}
try{
ionicStrength = readIonStrength();
ionicStrength = Math.min(1000,Math.max(ionicStrength, -1000));
if(ionicStrength < 0) {ionicStrength = -1;}
jTextFieldIonicStgr.setText(String.valueOf(ionicStrength));
} //try
catch (NumberFormatException nfe) {
String msg = "Wrong numeric format"+nl+nl+"Please enter a floating point number.";
showErrMsgBx(msg,1);
jTextFieldIonicStgr.setText(String.valueOf(ionicStrength));
jTextFieldIonicStgr.requestFocusInWindow();
} //catch
} // validateIonicStrength()
/** Reads the value in <code>jTextFieldIonicStgr</code>.
* Check that it is within -1 to 1000
* @return the ionic strength */
private double readIonStrength() {
if(jTextFieldIonicStgr.getText().length() <=0) {return 0;}
double w;
try{w = Double.parseDouble(jTextFieldIonicStgr.getText());
w = Math.min(1000,Math.max(w, -1));
if(w < 0) {w = -1;}
} //try
catch (NumberFormatException nfe) {
out.println("Error reading Ionic Strength:"+nl+" "+nfe.toString());
w = 0;
} //catch
return w;
} //readIonStrength()
/** Reads the value in <code>jLabelTemperature</code>.
* Checks that it is within -50 to 1000 Celsius. It returns 25
* if there is no temperature to read.
* @return the temperature in Celsius */
private double readTemperature() {
if(jLabelTemperature.getText().length() <=0) {return 25.;}
double w;
try{w = Double.parseDouble(jLabelTemperature.getText());
w = Math.min(1000,Math.max(w, -50));
} //try
catch (NumberFormatException nfe) {
if(!jLabelTemperature.getText().equals("NaN")) {
out.println("Error reading Temperature:"+nl+" "+nfe.toString());
}
w = 25.;
} //catch
return w;
} //readTemperature()
/** Reads the value in <code>jLabelPressure</code>.
* Checks that it is within 1 to 10000 bar. It returns 1 (one bar)
* if there is no pressure to read.
* @return the pressure in bar */
private double readPressure() {
if(jLabelPressure.getText().length() <=0) {return 1.;}
double w;
try{w = Double.parseDouble(jLabelPressure.getText());
w = Math.min(10000.,Math.max(w, 1.));
} //try
catch (NumberFormatException nfe) {
if(!jLabelPressure.getText().equals("NaN")) {
out.println("Error reading Pressure:"+nl+" "+nfe.toString());
}
w = 1.;
} //catch
return w;
} //readPressure()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="showErrMsgBx">
/** Outputs a message (through a call to <code>showMsg(msg,type)</code>
* and shows it in a [OK, Cancel] message box (if doNotStop = false)
* @param msg the message
* @param type =1 exception error; =2 warning; =3 information
* @return it return <code>true</code> if the user chooses "OK", returns <code>false</code> otherwise
* @see #showMsg(java.lang.String, int) showMsg */
boolean showErrMsgBxCancel(String msg, int type) {
if(msg == null || msg.trim().length() <=0) {return true;}
//if(type == 1) {type = 0;}
showMsg(msg,type);
if(!doNotStop && predomFrame != null) {
int j;
if(type<=1) {j=javax.swing.JOptionPane.ERROR_MESSAGE;}
else if(type==2) {j=javax.swing.JOptionPane.INFORMATION_MESSAGE;}
else {j=javax.swing.JOptionPane.WARNING_MESSAGE;}
if(!predomFrame.isVisible()) {predomFrame.setVisible(true);}
Object[] opt = {"OK", "Cancel"};
int n= javax.swing.JOptionPane.showOptionDialog(predomFrame,msg,
progName,javax.swing.JOptionPane.OK_CANCEL_OPTION,j, null, opt, opt[0]);
if(n != javax.swing.JOptionPane.OK_OPTION) {return false;}
}
return true;
}
/** Outputs a message (through a call to <code>showMsg(msg,0)</code> if type=1,
* or to <code>showMsg(msg,type)</code> if type is =2 or 3),
* and shows it in a message box (if doNotStop = false)
* @param msg the message
* @param type =1 exception error; =2 warning; =3 information
* @see #showMsg(java.lang.String, int) showMsg
*/
void showErrMsgBx(String msg, int type) {
if(msg == null || msg.trim().length() <=0) {return;}
//if(type == 1) {type = 0;}
showMsg(msg,type);
if(!doNotStop) {
if(predomFrame == null) {
ErrMsgBox mb = new ErrMsgBox(msg, progName);
} else {
int j;
if(type<=1) {j=javax.swing.JOptionPane.ERROR_MESSAGE;}
else if(type==2) {j=javax.swing.JOptionPane.INFORMATION_MESSAGE;}
else {j=javax.swing.JOptionPane.WARNING_MESSAGE;}
if(!this.isVisible()) {this.setVisible(true);}
javax.swing.JOptionPane.showMessageDialog(this, msg, progName,j);
}
}
}
/** Outputs the exception message and the stack trace,
* through a call to <code>showMsg(ex)</code>,
* and shows a message box (if doNotStop = false)
* @param ex the exception
* @see #showMsg(java.lang.Exception) showMsg */
void showErrMsgBx(Exception ex) {
if(ex == null) {return;}
showMsg(ex);
String msg = ex.toString();
if(!doNotStop) {
if(predomFrame == null) {
ErrMsgBox mb = new ErrMsgBox(msg, progName);
} else {
int j = javax.swing.JOptionPane.ERROR_MESSAGE;
if(!this.isVisible()) {this.setVisible(true);}
javax.swing.JOptionPane.showMessageDialog(this, msg, progName,j);
}
}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="showMsg">
/** Outputs a message either to System.out (if type is 1, 2 or 3) or
* to System.err otherwise (type=0).
* @param msg the message
* @param type =0 error (outputs message to System.err); =1 error; =2 warning; =3 information
* @see #showErrMsgBx(java.lang.String, int) showErrMsgBx */
void showMsg(String msg, int type) {
if(msg == null || msg.trim().length() <=0) {return;}
final String flag;
if(type == 2) {flag = "Warning";} else if(type == 3) {flag = "Message";} else {flag = "Error";}
if(type == 1 || type == 2 || type == 3) {
out.println("- - - - "+flag+":"+nl+msg+nl+"- - - -");
System.out.println("- - - - "+flag+":"+nl+msg+nl+"- - - -");
out.flush(); System.out.flush();
} else {
err.println("- - - - "+flag+":"+nl+msg+nl+"- - - -");
System.err.println("- - - - "+flag+":"+nl+msg+nl+"- - - -");
err.flush(); System.err.flush();
}
}
/** Outputs the exception message and the stack trace to System.err and to err
* @param ex the exception
* @see #showErrMsgBx(java.lang.Exception) showErrMsgBx */
void showMsg(Exception ex) {
if(ex == null) {return;}
String msg = "- - - - Error:"+nl+ex.toString()+nl+nl+Util.stack2string(ex)+nl+"- - - -";
err.println(msg);
System.err.println(msg);
err.flush();
System.err.flush();
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="doCalculations">
private void doCalculations() {
setCursorWait();
if(dbg) {out.println("--- doCalculations()");}
jLabelStatus.setText("Starting the calculations");
jLabelProgress.setText(" ");
disableMenus();
//---- Check if "EH" is needed -----------
if(diag.Eh && diag.pInX != 3 && diag.pInY != 3) {
boolean peGiven = false;
for(int i =0; i < cs.Na; i++) {
if(Util.isElectron(namn.identC[i]) &&
csC.kh[i] ==2) { // kh=2 logA given
peGiven = true; break;}
} //for i
if(!peGiven) {diag.Eh = false;}
}
//--- temperature & pressure ------------------------
diag.temperature = readTemperature();
diag.pressure = readPressure();
if(Double.isNaN(diag.temperature)){
String msg = "";
if(diag.Eh) {msg = "\"Error: Need to plot Eh values but no temperature is given.";}
else if(calcActCoeffs) {msg = "\"Error: activity coefficient calculations required but no temperature is given.";}
if(!msg.isEmpty()) {
showErrMsgBx(msg,1);
setCursorDef();
restoreMenus(true);
return;
}
}
// decide if the temperature should be displayed in the diagram
if(!diag.Eh && !calcActCoeffs
&& !(neutral_pH && (diag.pInX ==1 || diag.pInY ==1))) {
if(dbg) {out.println(" (Note: temperature not needed in the diagram)");}
} else {
double pSat;
try {pSat= lib.kemi.H2O.IAPWSF95.pSat(diag.temperature);}
catch (Exception ex) {
out.println("\"IAPWSF95.pSat\": "+ex.getMessage());
out.println("Calculations cancelled.");
restoreMenus(false);
setCursorDef();
return;
}
if(Double.isNaN(diag.pressure)){diag.pressure = 1.;}
if(diag.temperature <= 99.61) {
if(diag.pressure < 1.) {
out.println("tC = "+diag.temperature+", pBar = "+diag.pressure+", setting pBar = 1.");
}
diag.pressure = Math.max(1.,diag.pressure);
}
// if pressure = 1 bar and temperature = 0, set temperature to 0.01 C (tripple point of water)
if(diag.pressure >0.99999 && diag.pressure < 1.00001 && Math.abs(diag.temperature) < 0.001) {diag.temperature = 0.01;}
if(diag.temperature <= 373.95) { // below critical point
if(diag.pressure < (pSat*0.999)) {
out.println("tC = "+diag.temperature+", pBar = "+diag.pressure+", setting pBar = "+(float)pSat);
diag.pressure = pSat;
}
}
}
if(diag.Eh) {peEh = (ln10*8.3144126d*(diag.temperature+273.15d)/96484.56d);} else {peEh = Double.NaN;}
// nbr of calculation steps
nSteps = jScrollBarNbrPoints.getValue();
nSteps = Math.max(NSTP_MIN,nSteps);
/** Max. number of points to be plotted. In a predominance area diagram
* these are the points delimiting the areas. Should be at least = 15 * nSteps. */
final int mxPNT = nSteps * 17;
/** a class to store data about a Predom diagram */
final PredomData predData = new PredomData(cs.Ms, mxPNT); // create a new instance
jLabelNbrPText.setText("Nbr of calc. steps:");
jScrollBarNbrPoints.setEnabled(false);
jLabelNbrPText.setEnabled(false);
if(dbg) {out.println(" "+(nSteps+1)+" caculation points"+nl+
"ionic strength = "+ionicStrength+nl+
"temperature = "+(float)diag.temperature+", pressure = "+(float)diag.pressure+nl+
"max relative mass-balance tolerance = "+(float)tolHalta);}
// ---------------------------------------
// get an instance of Plot
plot = new Plot_Predom(this, err, out);
// ---------------------------------------
String msg;
// ionic strength
diag.ionicStrength = ionicStrength;
if(!diag.aquSystem && diag.ionicStrength != 0) {
msg = "File: "+inputDataFile.getName()+nl+
"Warning: This does not appear to be an aqueous system,"+nl+
"and yet you give a value for the ionic strength?";
if(!showErrMsgBxCancel(msg, 1)) {
out.println("--- Cancelled by the user ---");
setCursorDef();
restoreMenus(true);
return;
}
}
// model to calculate ion activity coefficients
if(calcActCoeffs) {
diag.activityCoeffsModel = jComboBoxModel.getSelectedIndex();
diag.activityCoeffsModel = Math.min(jComboBoxModel.getItemCount()-1,
Math.max(0,diag.activityCoeffsModel));
csC.actCoefCalc = true;
} else {
diag.activityCoeffsModel = -1;
csC.actCoefCalc = false;
}
// height scale for texts in the diagram
tHeight = jScrollBarHeight.getValue()/10;
tHeight = Math.min(10.d,Math.max(tHeight, 0.3));
// keep track of elapsed time
calculationStart = System.nanoTime();
//-- a simple check...
if(dgrC.hur[diag.compX] <=1 || dgrC.hur[diag.compX] ==4 || dgrC.hur[diag.compX] >=6) { //error?
err.println("Programming error found at \"doCalculations()\":"+nl+
" diag.compX = "+diag.compX+" hur = "+dgrC.hur[diag.compX]+" (should be 2,3 or 5)");
}
if(dgrC.hur[diag.compY] <=1 || dgrC.hur[diag.compY] ==4 || dgrC.hur[diag.compY] >=6) { //error?
err.println("Programming error found at \"doCalculations()\":"+nl+
" diag.compY = "+diag.compY+" hur = "+dgrC.hur[diag.compY]+" (should be 2,3 or 5)");
}
// check POS and NEG with the Tot.Conc. given in the input
int j;
for(j =0; j < cs.Na; j++) {
if(csC.kh[j] == 2) {continue;} //only it Tot.conc. is given
if(!(pos[j] && neg[j]) && (pos[j] || neg[j])) {
if(dgrC.hur[j] !=3 && //not LTV
dgrC.cLow[j]==0 && (Double.isNaN(dgrC.cHigh[j]) || dgrC.cHigh[j]==0)) {
//it is only POS or NEG and Tot.Conc =0
csC.logA[j] = -9999.;
dgrC.cLow[j] = csC.logA[j];
if(j == diag.compX || j == diag.compY) {dgrC.cHigh[j] = dgrC.cLow[j]+10;}
csC.kh[j] =2; //kh=2 means logA given
if(dbg) {out.println("Can not calculate mass-balance for for component \""+namn.identC[j]+"\""+nl+
" its log(activity) is now set to -9999.");}
}
}
} //for j
// ---- Make an instance of Factor
String userHome = System.getProperty("user.home");
try{factor = new Factor(ch, pathApp, userHome, pathDef.toString(), out);}
catch (Exception ex) {showErrMsgBx(ex.getMessage(),1); calcActCoeffs = false; diag.ionicStrength = Double.NaN;}
out.flush();
// ---- print information on the model used for activity coefficients
if(factor != null) {
try {factor.factorPrint(dbg);}
catch (Exception ex) {showErrMsgBx(ex.getMessage(),1); calcActCoeffs = false; diag.ionicStrength = Double.NaN;}
}
if(factor == null) {
out.println("Calculations cancelled.");
restoreMenus(false);
setCursorDef();
return;
}
// ---- Initialize variables
csC.dbg = dbgHalta;
csC.cont = false;
csC.tol = tolHalta;
for(j =0; j < cs.Na; j++) {
if(csC.kh[j] == 1) {
csC.tot[j]=dgrC.cLow[j];
csC.logA[j]=-10;
if(csC.tot[j]>0) {csC.logA[j] = Math.log10(csC.tot[j]) -3;}
}
else {csC.logA[j]=dgrC.cLow[j];}
} // for j
predData.xLeft = dgrC.cLow[diag.compX];
predData.xRight = dgrC.cHigh[diag.compX];
predData.stepX =(dgrC.cHigh[diag.compX] - dgrC.cLow[diag.compX]) / nSteps;
predData.yBottom = dgrC.cLow[diag.compY];
predData.yTop = dgrC.cHigh[diag.compY];
predData.stepY =(dgrC.cHigh[diag.compY] - dgrC.cLow[diag.compY]) / nSteps;
// ---- Run the calculations on another Thread ----
jLabelStatus.setText("Please wait --");
finishedCalculations = false;
msg = "Starting the calculations...";
out.println(msg);
if(consoleOutput) {System.out.println(msg);}
tsk = new HaltaTask();
tsk.setPredData(predData);
tsk.execute();
} //doCalculations()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="private class HaltaTask">
/** A SwingWorker to perform tasks in the background.
* @see HaltaTask#doInBackground() doInBackground() */
public class HaltaTask extends javax.swing.SwingWorker<Boolean, Integer> {
private boolean getHaltaInstanceOK = true;
private boolean haltaError = false;
private int nbrTooLargeConcs = 0;
private int nbrHaltaErrors = 0;
private int nbrHaltaUncertain = 0;
private final StringBuilder failuresMsg = new StringBuilder();
private final java.util.Locale engl = java.util.Locale.ENGLISH;
private boolean tooManyAreaPoints = false;
private char[][] lineMap = null;
private PredomData predData = null;
/** Sets a local pointer to an instance of PredomData, where results will be stored.
* @param pd an instance of PredomData */
protected void setPredData(PredomData pd) {predData = pd;}
/** The instructions to be executed are defined here
* @return true if no error occurs, false otherwise
* @throws Exception */
@Override protected Boolean doInBackground() throws Exception {
if(predData == null) {
showMsg("Programming error in \"HaltaTask\" (SwingWorker):"+nl+"PredomData = null.", 0);
this.cancel(true);
return false;
}
//--- do the HaltaFall calculations
// create an instance of class HaltaFall
h = null;
try {h = new HaltaFall(cs,factor, out);}
catch (Chem.ChemicalParameterException ex) { // this should not occur, but you never know
showErrMsgBx(ex);
getHaltaInstanceOK = false; // skip the rest of the thread
}
if(!getHaltaInstanceOK) {this.cancel(true); return false;}
/** <code>line[n][1]</code> is the predominating species at point "n" (along the
* Y-axis) for the present calculation.<br>
* <code>line[n][0]</code> is the predominating species at point "n" (along the
* Y-axis) for the <i>previous</i> calculation.<br>
* The plot area is divided in "nSteps" which means nSteps+1 calculated
* positions, plus one over the top and one under the bottom, this gives
* (nSteps+3) for the size of line[][2].<br>
* The bottom and top values (or left and right if calculations are row-wise),
* that is, line[0][] and line[nSteps+2][], are always "-1",
* that is: no predominating species outside the plot area. */
int[][] line = new int[nSteps+3][2];
int iL;
int iL_1; // = iL -1
final int NOW = 1; final int PREVIOUS = 0;
for(iL=0; iL<line.length; iL++) {line[iL][PREVIOUS]=-1; line[iL][NOW]=-1;}
int i,j, n;
if(dbg) {
lineMap = new char[nSteps+1][nSteps+1];
for(j=0; j<lineMap.length; j++) {for(i=0; i<lineMap.length; i++) {lineMap[j][i] = ' ';}}
}
double xVal, yVal; // these are the position of the calculated point
predData.nPoint = -1;
boolean frontier;
double tolHalta0 = csC.tol;
final String f = "Calculation failed in \"HaltaFall.haltaCalc\" at point (%d,%d), x=%7.5f y=%7.5f"+nl+"%s";
final String d;
if(cs.Ms<=98) {d="%2d";} else if(cs.Ms<=998) {d="%3d";} else if(cs.Ms<=9998) {d="%4d";} else {d="%5d";}
// ----- The calculations are performed column-wise:
// all Y-values are calcualted for each X-value,
// starting from the left/bottom corner and going
// to the right and upwards
// The outer loop is along the X-axis and the inner loop along the Y-axis
nStepOuter = -1;
xVal = predData.xLeft - predData.stepX;
do_loopOuter:
do { // -------------------------------------- Outer Loop for X-axis
nStepOuter++;
publish((nStepOuter+1));
//if needed for debugging: sleep some milliseconds (wait) at each calculation point
//try {Thread.sleep(1);} catch(Exception ex) {}
xVal = xVal + predData.stepX;
j = diag.compX;
// --- input data for this calculation point
if(csC.kh[j] == 1) {
if(dgrC.hur[j] ==3) { // LTV
csC.tot[j] = Math.exp(ln10*xVal);
} else { // TV
csC.tot[j]=xVal;
}
} else { // kh[j] = 2
csC.logA[j]=xVal;
}
// For the 1st point at the bottom of the diagram, starting the calcs. using
// the last equilibrium composition (at the top of the diagram) might be a bad idea
csC.cont = false;
// csC.cont = false;
nStepInner = -1;
yVal = predData.yBottom - predData.stepY;
do { // -------------------------------------- Inner Loop for Y-axis
nStepInner++;
iL = nStepInner+1;
iL_1 = nStepInner; // iL_1 = iL-1
yVal = yVal + predData.stepY;
j = diag.compY;
// --- input data for this calculation point
if(csC.kh[j] == 1) {
if(dgrC.hur[j] ==3) { // LTV
csC.tot[j] = Math.exp(ln10*yVal);
} else { // TV
csC.tot[j]=yVal;
}
} else { // kh[j] = 2
csC.logA[j]=yVal;
}
if(finishedCalculations) {break do_loopOuter;} //user requests exit?
// ------ print debug output from HaltaFall only for the first point (first point = zero) ------
if(nStepOuter == 0 && nStepInner == 0) {
if(dbg || csC.dbg > Chem.DBGHALTA_DEF) {
out.println("Starting calculation 1 (of "+(nSteps+1)+"x"+(nSteps+1)+")");
}
} else {
csC.dbg = Chem.DBGHALTA_DEF;
/** // ########## ---------- ########## ---------- ########## ##?##
if(Math.abs(xVal+7.8)<0.005 && (Math.abs(yVal+38.7)<0.001)) {
csC.dbg = 6;
out.println("---- Note: x="+(float)xVal+", y="+(float)yVal+" (debug) ---- nStepInner="+nStepInner+", nStepOuter="+nStepOuter);
} // ########## ---------- ########## ---------- ########## ##?## */
}
// --- HaltaFall: do the calculations
// calculate the equilibrium composition of the system
try {
csC.tol = tolHalta0;
h.haltaCalc();
if(csC.isErrFlagsSet(2)) { // too many iterations when solving the mass balance equations
do {
csC.tol = csC.tol * 0.1; // decrease tolerance and try again
if(dbg || csC.dbg > Chem.DBGHALTA_DEF) {
out.println("Too many iterations when solving the mass balance equations"+nl+
" decreasing tolerance to: "+(float)csC.tol+" and trying again.");
}
h.haltaCalc();
} while (csC.isErrFlagsSet(2) && csC.tol >= 1e-9);
csC.tol = tolHalta0;
if(dbg || csC.dbg > Chem.DBGHALTA_DEF) {
out.println("Restoring tolerance to: "+(float)tolHalta0+" for next calculations.");
}
}
if(csC.isErrFlagsSet(3)) { // failed to find a satisfactory combination of solids
if(dbg || csC.dbg > Chem.DBGHALTA_DEF) {
out.println("Failed to find a satisfactory combination of solids. Trying again...");
}
csC.cont = false; // try again
h.haltaCalc();
}
} catch (Chem.ChemicalParameterException ex) {
String ms = "Error in \"HaltaFall.haltaCalc\", errFlags="+nl+csC.errFlagsGetMessages()+nl+
" at point: ("+(nStepInner+1)+","+(nStepOuter+1)+") at x="+(float)xVal+" y="+(float)yVal;
showMsg(ex);
showErrMsgBx(ms+nl+ex.getMessage(),1);
haltaError = true;
break do_loopOuter;
}
// ---
if(finishedCalculations) {break do_loopOuter;} //user request exit?
if(csC.isErrFlagsSet(1)) {nbrHaltaUncertain++;}
if(csC.isErrFlagsSet(5)) {nbrTooLargeConcs++;}
if(csC.isErrFlagsSet(2) || csC.isErrFlagsSet(3) || csC.isErrFlagsSet(4)
|| csC.isErrFlagsSet(6)) {
nbrHaltaErrors++;
frontier = false;
if(failuresMsg.length() >0) {failuresMsg.append(nl);}
failuresMsg.append(String.format(engl,f,(nStepInner+1),(nStepOuter+1),(float)xVal,(float)yVal,csC.errFlagsGetMessages()));
} else {
//--------------------------------------------------
findTopSpecies();
line[iL][NOW] = topSpecies;
//--------------------------------------------------
// Is this point a frontier between two areas ?
if(line[iL][NOW] != line[iL][PREVIOUS]) {
frontier = line[iL][NOW] != line[iL_1][NOW] ||
line[iL][NOW] != line[iL_1][PREVIOUS];
} else {
frontier = line[iL][NOW] != line[iL_1][NOW];
}
}
if(frontier) {
predData.nPoint++;
// store what species are involved
predData.pair[predData.nPoint][0] = line[iL][PREVIOUS];
if(nStepOuter ==0 && line[iL][NOW] != line[iL_1][NOW]) {
predData.pair[predData.nPoint][0] = line[iL_1][NOW];
}
predData.pair[predData.nPoint][1] = line[iL][NOW];
predData.pair[predData.nPoint][2] = line[iL_1][NOW];
// the position of the line separating the predominance areas
predData.xPl[predData.nPoint] = xVal;
predData.yPl[predData.nPoint] = yVal;
if(dbg) {lineMap[nStepInner][nStepOuter] = '+';}
} else { // not frontier
if(iL == (nSteps+1) || nStepOuter == nSteps) {
//Point at the margin of the diagram
// these are used only to determine the centre of each predominance area
predData.nPoint++;
predData.pair[predData.nPoint][0]=line[iL][PREVIOUS];
predData.pair[predData.nPoint][1]=-1; //the predominating species at this point
predData.pair[predData.nPoint][2]=line[iL][NOW];
predData.xPl[predData.nPoint] = xVal;
predData.yPl[predData.nPoint] = yVal;
if(dbg) {lineMap[nStepInner][nStepOuter] = '+';}
}
}//frontier?
// --------------------------------------------------
if(dbg && nStepOuter == 0 && nStepInner == 0 && diag.activityCoeffsModel >=0) {
err.flush(); out.flush();
out.println("First calculation step finished.");
factor.printActivityCoeffs(out);
}
} while(nStepInner < nSteps); // ------------ Inner Loop for 2nd-axis
if(dbg) { //-- print the predominance species map
if(nStepOuter==0) {out.println("---- Map of predominating species (from 1 \""+
namn.ident[0]+"\" to "+(cs.Ms-1)+" \""+namn.ident[cs.Ms-1]+"\") and X-variable."+nl+
" The leftmost column corresponds to Y="+(float)predData.yBottom+" and the rightmost column to Y="+(float)predData.yTop);}
for(i=0; i<(line.length-1); i++) {
if(line[i][NOW]>=0) {n=line[i][NOW]+1;} else {n=-1;}
out.print(String.format(d,n));
}
out.print(" "+(float)xVal);
out.println();
}
if(predData.nPoint >= predData.mxPNT) {
tooManyAreaPoints = true;
break; // do_loopOuter;
}
for(i =0; i<line.length; i++) {line[i][PREVIOUS] = line[i][NOW]; line[i][NOW] = -1;}
} while(nStepOuter < nSteps); // ------------ External Loop for 1st-axis
return true;
}
/** Performs some tasks after the calculations have been finished */
@Override protected void done() {
if(isCancelled()) {
if(dbg) {System.out.println("SwingWorker cancelled.");}
} else {
int i,j;
String msg;
if(!haltaError) {
if(tooManyAreaPoints) {
showErrMsgBx("Problem: Too many area-delimiting points were found."+nl+
"The diagram will be incomplete.", 1);
} // tooManyAreaPoints?
calculationTime = (System.nanoTime() - calculationStart)
/1000000; //convert nano seconds to milli seconds
msg = "--- Calculated "+(nSteps+1)+" x "+(nStepOuter+1)+" points, time="+millisToShortDHMS(calculationTime);
out.println(nl+msg);
System.out.println(msg);
System.out.flush();
msg = "";
if(nbrTooLargeConcs > 0) {
int percent = nbrTooLargeConcs*100 /((nSteps+1) * (nSteps+1));
if(percent >0) {
msg = percent+" % of the calculated points had some"+nl+
"concentrations > "+(int)Factor.MAX_CONC+" (molal); impossible in reality."+nl+nl;
if(calcActCoeffs) {msg = msg + "The activity coefficients are then WRONG"+nl+
"and the results unrealistic."+nl;}
else {msg = msg + "These results are unrealistic."+nl;}
}
}
if(nbrHaltaErrors <= 0 && nbrHaltaUncertain >0 && dbg) {
if(msg.length() >0) msg = msg+nl;
msg = msg+String.format("%d",nbrHaltaUncertain).trim()+" point(s) with round-off errors (not within tolerance).";
}
if(nbrHaltaErrors >0) {
if(msg.length() >0) msg = msg+nl;
msg = msg+String.format("Calculations failed for %d",nbrHaltaErrors).trim()+" point(s).";
}
if(msg.length() >0) {showErrMsgBx(msg, 1);}
if(nbrHaltaErrors >0 && failuresMsg != null && failuresMsg.length() >0) {// failuresMsg should not be empty...
out.println(LINE);
out.println(failuresMsg);
out.println(LINE);
}
if(dbg && lineMap != null) { //-- print the area limits map
out.println("---- Map of area limits (points to plot):");
for(i=0; i<lineMap.length; i++) {
for(j=0; j<lineMap.length; j++) {out.print(lineMap[j][i]);} out.println();
}
} //dbg
// --------------------------------------------------
// Determine the center of each area
// (where labels will be plotted)
plot.minMax(ch, predData);
// --------------------------------------------------
if(dbg) {
out.println("---- List of points to plot (including margins):"+nl+"point_nbr, pair[0,1,2], x-value, y-value");
for(i=0; i<predData.nPoint; i++) {
out.println(
String.format("%3d, %3d,%3d,%3d",i,predData.pair[i][0],predData.pair[i][1],predData.pair[i][2])+
", "+(float)predData.xPl[i]+", "+(float)predData.yPl[i]
);
}
out.println("----");
}
// --------------------------------------------------
// Take away plot margins (about: 4*nStep points)
// (the margins are needed to determine the center of each area)
int nPoints2 = -1;
for(i=0; i < predData.nPoint; i++) {
if(predData.pair[i][0] == -1 &&
(predData.pair[i][1] == predData.pair[i][2] || predData.pair[i][2] == -1
)) {continue;}
if(predData.pair[i][1] == -1) {continue;}
if(predData.pair[i][2] == -1 && predData.pair[i][0] == predData.pair[i][1]) {continue;}
nPoints2++;
predData.xPl[nPoints2] = predData.xPl[i];
predData.yPl[nPoints2] = predData.yPl[i];
//
// pair[][2] is not used when plotting, if pair[][0] = pair[][1] use pair[][2]
if(predData.pair[i][0] == predData.pair[i][1] &&
predData.pair[i][2] != -1) {predData.pair[i][0] = predData.pair[i][2];}
predData.pair[nPoints2][0] = predData.pair[i][0];
predData.pair[nPoints2][1] = predData.pair[i][1];
predData.pair[nPoints2][2] = predData.pair[i][2]; //not really neaded becaise pair[][2] is not used when plotting
} // for i
predData.nPoint = nPoints2;
// --------------------------------------------------
// Move the points halv step to the left and down
// to try to compensate for the column-wise
// calculation procedure
for(i=0; i<predData.nPoint; i++) {
if(Math.abs(predData.xPl[i]-predData.xLeft) > 1e-5 &&
Math.abs(predData.xPl[i]-predData.xRight) > 1e-5) {
predData.xPl[i] = predData.xPl[i]-0.5*predData.stepX;
}
if(Math.abs(predData.yPl[i]-predData.yBottom) > 1e-5 &&
Math.abs(predData.yPl[i]-predData.yTop) > 1e-5) {
predData.yPl[i] = predData.yPl[i]-0.5*predData.stepY;
}
}
// --------------------------------------------------
if(dbg) {
out.println("---- List of points to plot:"+nl+"point_nbr, pair[0,1,2], x-value, y-value");
for(i=0; i<=predData.nPoint; i++) {
out.println(
String.format("%3d, %3d,%3d,%3d",i,predData.pair[i][0],predData.pair[i][1],predData.pair[i][2])+
", "+(float)predData.xPl[i]+", "+(float)predData.yPl[i]
);
}
out.println("----");
}
out.println("Number of points to draw = "+(predData.nPoint+1));
// -------------------------------------------
out.println("Saving plot file \""+outputPltFile.getAbsolutePath()+"\"...");
try{plot.drawPlot(outputPltFile, ch, predData);}
catch (Exception ex) {
showErrMsgBx("Error: "+ex.getMessage()+nl+
"while saving plot file \""+outputPltFile.getAbsolutePath()+"\"", 1);
}
if(outputPltFile != null && outputPltFile.getName().length()>0) {
String msg3 = "Saved plot file: \""+outputPltFile.getAbsolutePath()+"\"";
out.println(msg3);
System.out.println(msg3);
}
// -------------------------------------------
} //haltaError?
// execute the following actions on the event-dispatching Thread
// after the "calculations" and the plotting are finished
if(getHaltaInstanceOK && !haltaError) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
jTabbedPane.setTitleAt(2, "<html><u>D</u>iagram</html>");
jTabbedPane.setEnabledAt(2, true);
jTabbedPane.setSelectedComponent(jPanelDiagram);
jTabbedPane.requestFocusInWindow();
restoreMenus(true);
}}); // invokeLater
}//if getHaltaInstanceOK
else {
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
jTabbedPane.setSelectedComponent(jScrollPaneMessg);
jTabbedPane.requestFocusInWindow();
restoreMenus(true);
}}); // invokeLater
}//if !getHaltaInstanceOK
if(dbg) {System.out.println("SwingWorker done.");}
}
out.println(LINE);
System.out.println(LINE);
finishedCalculations = true;
predomFrame.notify_All();
setCursorDef();
}
@Override protected void process(java.util.List<Integer> chunks) {
// Here we receive the values that we publish(). They may come grouped in chunks.
final int i = chunks.get(chunks.size()-1);
int nn = (int)Math.floor(Math.log10(nSteps+1))+1;
final String f = "now calculating loop: %"+String.format("%3d",nn).trim()
+"d (out of %"+String.format("%3d",nn).trim()+"d)";
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
jLabelProgress.setText(String.format(f,i,(nSteps+1)));
}}); // invokeLater
}
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="main">
/** The "main" method. Creates a new frame if needed.
* Errors and messages are sent to System.out and System.err.
* @param args the command line arguments */
public static void main(final String args[]) {
// ----
System.out.println(LINE+nl+progName+" (Predominance Area Diagrams), version: "+VERS);
// set LookAndFeel
//try {javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getCrossPlatformLookAndFeelClassName());}
//try {javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");}
try {javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());}
catch (Exception ex) {}
//---- for JOptionPanes set the default button to the one with the focus
// so that pressing "enter" behaves as expected:
javax.swing.UIManager.put("Button.defaultButtonFollowsFocus", Boolean.TRUE);
// and make the arrow keys work:
Util.configureOptionPane();
if(args.length <=0) {System.out.println("Usage: PREDOM [data-file-name] [-command=value]"+nl+
"For a list of possible commands type: PREDOM -?");}
else {
if(DBG_DEFAULT) {System.out.println("PREDOM "+java.util.Arrays.toString(args));}
}
//---- get Application Path
pathApp = Main.getPathApp();
if(DBG_DEFAULT) {System.out.println("Application path: \""+pathApp+"\"");}
//---- "invokeAndWait": Wait for either:
// - the main window is shown, or
// - perform the calculations and save the diagram
boolean ok = true;
String errMsg = "PREDOM construction did not complete successfully"+nl;
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {@Override public void run() {
// deal with some special command-line arguments
boolean doNotExit0 = false;
boolean doNotStop0 = false;
boolean dbg0 = DBG_DEFAULT;
boolean rev0 = false;
boolean h = false;
if(args.length > 0) {
for (String arg : args) {
if (arg.equalsIgnoreCase("-dbg") || arg.equalsIgnoreCase("/dbg")) {
dbg0 =true;
} else if (arg.equalsIgnoreCase("-keep") || arg.equalsIgnoreCase("/keep")) {
doNotExit0 =true;
} else if (arg.equalsIgnoreCase("-nostop") || arg.equalsIgnoreCase("/nostop")) {
doNotStop0 = true;
} else if (arg.equalsIgnoreCase("-rev") || arg.equalsIgnoreCase("/rev")) {
rev0 =true;
} else if (arg.equals("-?") || arg.equals("/?") || arg.equals("?")) {
h = true;
printInstructions(System.out);
} //if args[] = "?"
} //for arg
if(h && !doNotExit0) {return;} // exit after help if OK to exit
} //if args.length >0
predomFrame = new Predom(doNotExit0, doNotStop0, dbg0);//.setVisible(true);
predomFrame.start(rev0, h, args);
}}); //invokeAndWait
} catch (InterruptedException ex) {
ok = false; errMsg = errMsg + Util.stack2string(ex);
}
catch (java.lang.reflect.InvocationTargetException ex) {
ok = false; errMsg = errMsg + Util.stack2string(ex);
}
if(!ok) {
System.err.println(errMsg);
ErrMsgBox mb = new ErrMsgBox(errMsg, progName);
}
//-- wait, either for the calculations to finish, or
// for the window to be closed by the user
if(predomFrame != null) {
Thread t = new Thread() {@Override public void run(){
if(predomFrame.inputDataFileInCommandLine) {
predomFrame.synchWaitCalcs();
if(!predomFrame.doNotExit) {predomFrame.end_program();}
else{predomFrame.synchWaitProgramEnded();}
} else {
predomFrame.synchWaitProgramEnded();
}
}};// Thread t
t.start(); // Note: t.start() returns inmediately;
// statements here are executed inmediately.
try {t.join();} catch (InterruptedException ex) {} // wait for the thread to finish
if(predomFrame.dbg) {System.out.println(progName+" - finished.");}
}
//javax.swing.JOptionPane.showMessageDialog(null, "ready?", progName, javax.swing.JOptionPane.INFORMATION_MESSAGE);
} // main(args[])
//</editor-fold>
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroupDebug;
private javax.swing.JButton jButtonDoIt;
private javax.swing.JCheckBox jCheckActCoeff;
private javax.swing.JCheckBoxMenuItem jCheckBoxMenuPredomDebug;
private javax.swing.JCheckBox jCheckReverse;
private javax.swing.JComboBox jComboBoxModel;
private javax.swing.JComboBox jComboBoxTol;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabelBar;
private javax.swing.JLabel jLabelData;
private javax.swing.JLabel jLabelHD;
private javax.swing.JLabel jLabelHeight;
private javax.swing.JLabel jLabelIonicStr;
private javax.swing.JLabel jLabelIonicStrM;
private javax.swing.JLabel jLabelModel;
private javax.swing.JLabel jLabelNbrPText;
private javax.swing.JLabel jLabelP;
private javax.swing.JLabel jLabelPltFile;
private javax.swing.JLabel jLabelPointsNbr;
private javax.swing.JLabel jLabelPressure;
private javax.swing.JLabel jLabelProgress;
private javax.swing.JLabel jLabelStatus;
private javax.swing.JLabel jLabelT;
private javax.swing.JLabel jLabelTC;
private javax.swing.JLabel jLabelTemperature;
private javax.swing.JLabel jLabelTol;
private javax.swing.JMenuBar jMenuBar;
private javax.swing.JMenuItem jMenuCancel;
private javax.swing.JMenu jMenuDebug;
private javax.swing.JMenu jMenuFile;
private javax.swing.JMenuItem jMenuFileMakeD;
private javax.swing.JMenuItem jMenuFileOpen;
private javax.swing.JMenuItem jMenuFileXit;
private javax.swing.JMenu jMenuHelp;
private javax.swing.JMenuItem jMenuHelpAbout;
private javax.swing.JMenuItem jMenuSave;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanelActC;
private javax.swing.JPanel jPanelDiagram;
private javax.swing.JPanel jPanelFiles;
private javax.swing.JPanel jPanelParameters;
private javax.swing.JPanel jPanelStatusBar;
private javax.swing.JPanel jPanelT;
private javax.swing.JScrollBar jScrollBarHeight;
private javax.swing.JScrollBar jScrollBarNbrPoints;
private javax.swing.JScrollPane jScrollPaneMessg;
private javax.swing.JTabbedPane jTabbedPane;
private javax.swing.JTextArea jTextAreaA;
private javax.swing.JTextField jTextFieldDataFile;
private javax.swing.JTextField jTextFieldIonicStgr;
private javax.swing.JTextField jTextFieldPltFile;
// End of variables declaration//GEN-END:variables
} // class Predom
| 183,691 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
Plot_Predom.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/Predom/src/predominanceAreaDiagrams/Plot_Predom.java | package predominanceAreaDiagrams;
import lib.common.Util;
import lib.kemi.chem.Chem;
import lib.kemi.graph_lib.GraphLib;
/** Methods to create a chemical equilibrium diagram.
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class Plot_Predom {
private Predom pred = null;
private static final java.util.Locale engl = java.util.Locale.ENGLISH;
/** Where errors will be printed. It may be <code>System.err</code>.
* If null, <code>System.err</code> is used. */
private final java.io.PrintStream err;
/** Where messages will be printed. It may be <code>System.out</code>.
* If null, <code>System.out</code> is used. */
private final java.io.PrintStream out;
/** iFL[k] > 0 if the line pair[k][1/2] has been drawn to the point k, and
* iFL[k] = 0 if the line pair[k][1/2] starts at point k */
private int[] iFL;
/** true if the line pair[i][1/2] continues with another point */
private boolean lineContinued;
/** iOther[j] = how many neighbor points which are borderline between two
* areas, in one of which, species j predominates. */
private int[] iOther;
/** neighb[j][n] = number of the "n" neighbor point which is borderline
* between two areas, in one of which,
* species "j" predominates. */
private int[][] neighb;
private double[] ax;
private double[] ay;
private double[] ix;
private double[] iy;
private static final String nl = System.getProperty("line.separator");
/**
* Constructor.
* @param pred0 The PREDOM "frame".
* @param err0 Where errors will be printed. It may be <code>System.err</code>.
* If null, <code>System.err</code> is used.
* @param out0 Where messages will be printed. It may be <code>System.out</code>.
* If null, <code>System.out</code> is used. */
public Plot_Predom(Predom pred0, java.io.PrintStream err0, java.io.PrintStream out0) {
this.pred = pred0;
if(err0 != null) {this.err = err0;} else {this.err = System.err;}
if(out0 != null) {this.out = out0;} else {this.out = System.out;}
} //constructor
//<editor-fold defaultstate="collapsed" desc="minMax(ch)">
/** Gets the position of the center of each predominance area, even
* when the area is not rectangular or divided in two parts.
* The values are stored in pd.xCentre and pd.yCentre
* @param ch
* @param pd
*/
void minMax(Chem ch, PredomData pd){
if(pred.dbg) {
out.println("--- minMax"+nl+"Calculating the position of the centre of each predominance area");
}
Chem.ChemSystem cs = ch.chemSystem;
// ax and ix are the maximum and minimum x-coordinates, similarly for ay and iy
ax = new double[cs.Ms];
ay = new double[cs.Ms];
ix = new double[cs.Ms];
iy = new double[cs.Ms];
for(int i=0; i<cs.Ms; i++) {ax[i]=-50000; ay[i]=-50000; ix[i]=10000; iy[i]=10000;}
// ------------------------------------------------
// Maximum and Minimum X and Y values for each area
int j;
for (int i=0; i< pd.nPoint; i++) {
for(int k=0; k<=2; k++) {
j = pd.pair[i][k];
if(j>=0) {
if(pd.xPl[i] > ax[j]) {ax[j]=pd.xPl[i];}
if(pd.xPl[i] < ix[j]) {ix[j]=pd.xPl[i];}
if(pd.yPl[i] > ay[j]) {ay[j]=pd.yPl[i];}
if(pd.yPl[i] < iy[j]) {iy[j]=pd.yPl[i];}
} //pair[i][k] >=0
}
} //for nPoint
// ------------------------------------------------
// Get the position of the center of the area
// when the area is not rectangular
// or divided in two
double z2 = 0.001 * Math.abs(pd.stepY);
double zq = Math.abs(pd.stepX) + 0.001 * Math.abs(pd.stepX);
double zx5 = Math.abs(pd.xRight - pd.xLeft) / 10;
double zy5 = Math.abs(pd.yTop - pd.yBottom) / 10;
double distS = Math.sqrt(zx5*zx5 + zy5*zy5);
// number of lines belonging to area "i" that cross line X = xCentre[i]
int[] nCentr = new int[4];
// the Y-coordinates for each line belonging to area "i" that cross line X = xCentre[i]
double[] yCentr = new double[4];
int nLines; double last;
double w, w2, z1, z3, q1, q2, q3, q4, ay1, ay2, iy1, iy2, yCent1, yCent2, dist;
int ij, i2nd;
for(int i =0; i < cs.Ms; i++) { //loop through all possible areas
pd.xCentre[i] = (ax[i]+ix[i])/2;
pd.yCentre[i] = (ay[i]+iy[i])/2;
if(pd.xCentre[i] < -1000 || pd.yCentre[i] < -1000) {continue;}
if(pred.dbg) {
out.println(" Species "+i+", \""+cs.namn.ident[i]+"\", Centre = "+(float)pd.xCentre[i]+", "+(float)pd.yCentre[i]);
out.println(" X from = "+(float)ix[i]+" to "+(float)ax[i]+", Y from = "+(float)iy[i]+" to "+(float)ay[i]);
}
// if the area is small, finished
if((ay[i]-iy[i]) <= zy5 || (ax[i]-ix[i]) <= zx5) {continue;}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Find nLines = number of lines belonging to area "i"
// that cross line X = xCentre[i]
nLines = 0;
last = -10000;
w = pd.xCentre[i] + Math.abs(pd.stepX);
for(int ip=0; ip < pd.nPoint; ip++) {
if(pd.xPl[ip] < pd.xCentre[i] || pd.xPl[ip] >= w) {continue;}
// Check that the point belongs to the area "i"
if(pd.pair[ip][1] !=i && pd.pair[ip][0] !=i && pd.pair[ip][2] !=i) {continue;}
// Check that the point is not inmediately following the previous one
z1 = last + pd.stepY;
z3 = last;
last = pd.yPl[ip];
if(last == z3 || Math.abs(last-z1) < z2) {continue;}
nLines++;
nCentr[nLines-1] = ip;
yCentr[nLines-1] = pd.yPl[ip];
if(nLines >= 4) {break;}
} //for ip
i2nd = i + cs.Ms;
if(pred.dbg) { // debug printout
out.println(" nLines = "+nLines);
for(j=0; j<nLines; j++) {
ij = nCentr[j];
out.println(" point: "+ij+" species: "+pd.pair[ij][0]+","+
pd.pair[ij][1]+"/"+pd.pair[ij][2]+", x,y="+(float)pd.xPl[ij]+", "+(float)pd.yPl[ij]);
}
} //if dbg
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// how many lines go through X=xCentre ?
//if(nLines == 1) {} //continue;
//else
if(nLines == 2) {
//normal area
pd.yCentre[i]=(yCentr[0]+yCentr[1])/2.;
//continue;
}
else if(nLines == 0 || nLines == 3) {
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Species that has two predominance areas (i.e., area divided in two)
// one area to the left, one to the right
// Find max and min Y values for ax[i] and ix[i]
q1= ax[i] - zq; q2= ax[i] + zq; q3= ix[i] - zq; q4= ix[i] + zq;
ay1= -50000; iy1= 10000;
ay2= -50000; iy2= 10000;
for(int ip=0; ip <= pd.nPoint; ip++) {
if(pd.pair[ip][0] != i && pd.pair[ip][1] != i && pd.pair[ip][2] != i) {continue;}
if(pd.xPl[ip] >= q1 && pd.xPl[ip] <= q2) {
if(pd.yPl[ip] > ay1) {ay1 = pd.yPl[ip];}
if(pd.yPl[ip] < iy1) {iy1 = pd.yPl[ip];}
}
if(pd.xPl[ip] >= q3 && pd.xPl[ip] <= q4) {
if(pd.yPl[ip] > ay2) {ay2 = pd.yPl[ip];}
if(pd.yPl[ip] < iy2) {iy2 = pd.yPl[ip];}
}
} //for ip
yCent1 = (ay1+iy1)/2.;
yCent2 = (ay2+iy2)/2.;
pd.yCentre[i2nd] = pd.yCentre[i];
if(yCent1 > -1000) {pd.yCentre[i] = yCent1;}
if(yCent2 > -1000) {pd.yCentre[i2nd] = yCent2;}
pd.xCentre[i] = ax[i] - zx5/2.;
pd.xCentre[i2nd] = ix[i] + zx5/2.;
if(pred.dbg) {
out.println(" q1,q2,q3,q4 = "+(float)q1+", "+(float)q2+", "+(float)q3+", "+(float)q4);
out.println(" ay1,iy1,ay2,iy2 = "+(float)ay1+", "+(float)iy1+", "+(float)ay2+", "+(float)iy2);
out.println(" (x/y)Centr[i] = "+(float)pd.xCentre[i]+", "+(float)pd.yCentre[i]+
", (x/y)Centr[i2nd] = "+(float)pd.xCentre[i2nd]+", "+(float)pd.yCentre[i2nd]);
} //if dbg
// Check if the distance is too small
w = Math.pow(pd.xCentre[i] - pd.xCentre[i2nd], 2);
w2 = Math.pow(pd.yCentre[i] - pd.yCentre[i2nd], 2);
dist = Math.sqrt(w+w2);
if(dist <= distS) {
pd.xCentre[i] = (ax[i]+ix[i])/2.;
pd.yCentre[i] = (ay[i]+iy[i])/2.;
pd.xCentre[i2nd] = -30000;
pd.yCentre[i2nd] = -30000;
}
if(pred.dbg) {
out.println(" -- centres: "+(float)pd.xCentre[i]+", "+(float)pd.yCentre[i]+
" and "+(float)pd.xCentre[i2nd]+", "+(float)pd.yCentre[i2nd]);
}
// continue;
}
else if(nLines == 4) {
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Species that has two predominance areas (i.e., area divided in two)
// one area up, one area down
pd.yCentre[i] = (yCentr[0]+yCentr[1])/2.;
pd.yCentre[i2nd] = (yCentr[2]+yCentr[3])/2.;
pd.xCentre[i2nd] = pd.xCentre[i];
// Check if the distance in Y is too small
dist = Math.abs(pd.yCentre[i] - pd.yCentre[i2nd]);
if(dist <= distS) {
pd.yCentre[i] = (ay[i]+iy[i])/2.;
pd.xCentre[i2nd] = -30000;
pd.yCentre[i2nd] = -30000;
}
if(pred.dbg) {
out.println(" -- centres: "+(float)pd.xCentre[i]+", "+(float)pd.yCentre[i]+
" and "+(float)pd.xCentre[i2nd]+", "+(float)pd.yCentre[i2nd]);
}
// continue;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
} //for i
}//minMax(ch)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="drawPlot (plotFile, ch)">
/** Create a diagram. Saving the diagram information in a PltData() object
* and simultaneously store the data in a plot file.
* @param plotFile where the diagram will be saved
* @param ch where the data for the chemical system are stored
* @param diagP contains information on the diagram
*/
void drawPlot(java.io.File plotFile, Chem ch, PredomData diagP)
throws GraphLib.WritePlotFileException {
Chem.ChemSystem cs = ch.chemSystem;
Chem.ChemSystem.ChemConcs csC = cs.chemConcs;
Chem.ChemSystem.NamesEtc namn = cs.namn;
Chem.Diagr diag = ch.diag;
Chem.DiagrConcs dgrC = ch.diagrConcs;
out.println("--- Drawing the plot...");
//-- If true, the concentration is displayed as is.
// If false, the concentration is displayed as milli molal, micro molal, or nano molal.
boolean xMolal, yMolal;
//-- display of concentrations: units and notation
// default is that:
// 1- if the temperature is between 0 and 45 Celsius and the pressure
// is below 50 bars, then units = "M" (molar) and the notation is
// engineering (millimolar, micromolar, etc)
// 2- otherwise units = "molal" and the notation is engineering
// (10'-3` molal, 10'-6` molal, etc)
pred.conc_units = Math.min(2, Math.max(pred.conc_units, -1));
pred.conc_nottn = Math.min(2, Math.max(pred.conc_nottn, 0));
if(pred.conc_nottn == 0) {pred.conc_nottn = 2;} // engineering
if( (Double.isNaN(diag.temperature) || (diag.temperature >= 0 && diag.temperature <= 45))
&& (Double.isNaN(diag.pressure) || diag.pressure <=50)) {
// temperatures around 25 and low pressures
if(pred.conc_units == 0) {pred.conc_units = 2;} // units = "M"
}
String cUnit = pred.cUnits[(pred.conc_units+1)];
String mUnit = ("×10'-3` "+cUnit).trim();
String uUnit = ("×10'-6` "+cUnit).trim();
String nUnit = ("×10'-9` "+cUnit).trim();
if(pred.conc_units == 2) {mUnit = " mM"; uUnit = " $M"; nUnit = " nM";}
//---- Max and Min values in the axes: xLow,xHigh, yLow,yHigh
double xLow = dgrC.cLow[diag.compX];
double xHigh = dgrC.cHigh[diag.compX];
// Concentration types:
// hur =1 for "T" (fixed Total conc.)
// hur =2 for "TV" (Tot. conc. Varied)
// hur =3 for "LTV" (Log(Tot.conc.) Varied)
// hur =4 for "LA" (fixed Log(Activity) value)
// hur =5 for "LAV" (Log(Activity) Varied)
//if(dgrC.hur[diag.compX] ==3) { // LTV
// xLow = Math.log10(xLow);
// xHigh = Math.log10(xHigh);
//}
if(Util.isProton(namn.identC[diag.compX]) ||
Util.isElectron(namn.identC[diag.compX])) {
if(dgrC.hur[diag.compX] !=5) {diag.pInX = 0;} // not LAV: standard axis
else { // LAV
xLow = -xLow; xHigh = -xHigh;
if(diag.pInX == 3) {
xLow = pred.peEh * xLow;
xHigh = pred.peEh * xHigh;
}
} // if LAV
} // is H+ or engl-
// standard scale in X-axis
xMolal = true;
if(dgrC.hur[diag.compX] <=2) { // T or TV
if((pred.conc_nottn == 2 || (pred.conc_nottn == 0 && pred.conc_units == 2)) &&
Math.abs(xLow) <0.9 && Math.abs(xHigh) <0.9) {
//milli units in X-axis
xMolal = false;
xLow = xLow * 1000.; xHigh = xHigh * 1000.;
}
} //T or TV
//Values for the Y-axis
double yLow = dgrC.cLow[diag.compY];
double yHigh = dgrC.cHigh[diag.compY];
//if(dgrC.hur[diag.compY] ==3) { // LTV
// yLow = Math.log10(yLow);
// yHigh = Math.log10(yHigh);
//}
if(Util.isProton(namn.identC[diag.compY]) ||
Util.isElectron(namn.identC[diag.compY])) {
if(dgrC.hur[diag.compY] !=5) {diag.pInY = 0;} // not LAV
else { // LAV
yLow = -yLow; yHigh = -yHigh;
if(diag.pInY == 3) {
yLow = pred.peEh * yLow;
yHigh = pred.peEh * yHigh;
}
} // if LAV
} // is H+ or engl-
// standard scale in Y-axis
yMolal = true;
if(dgrC.hur[diag.compY] <=2) { // T or TV
if(pred.conc_nottn == 2 ||
(pred.conc_nottn == 0 && pred.conc_units == 2 &&
Math.abs(yLow) <0.9 && Math.abs(yHigh) <0.9)) {
//milli molal units in Y-axis
yMolal = false;
yLow = yLow * 1000.; yHigh = yHigh * 1000.;
}
} //T or TV
//---- Get the length of the axes labels
int nTextX = 6 + namn.nameLength[namn.iel[diag.compX]];
if(diag.pInX ==1 || diag.pInX ==2) {nTextX =2;} // pH or pe
else if(diag.pInX ==3) {nTextX =8;} // "E`SHE' / V"
int nTextY = 6 + namn.nameLength[namn.iel[diag.compY]];
if(diag.pInY ==1 || diag.pInY ==2) {nTextY =2;} // pH or pe
else if(diag.pInY ==3) {nTextY =8;} // "E`SHE' / V"
//---- Dimensions of the diagramData, Size of text: height. Origo: xOr,yOr
float xAxl =10; float yAxl = 10;
float heightAx = 0.035f * yAxl;
if(pred.tHeight > 0.0001) {heightAx = (float)pred.tHeight*heightAx;}
float xOr; float yOr;
//xOr = 7.5f * heightAx;
//yOr = 4.0f * heightAx;
//for Predom:
xOr = 4.5f;
yOr = 1.6f;
float xMx = xOr + xAxl; float yMx = yOr + yAxl;
// xL and yL are scale factors, according to
// the axis-variables (pH, pe, Eh, log{}, log[]tot, etc)
float xL = xAxl / (float)(xHigh - xLow); float xI = xL * (float)xLow - xOr;
float yL = yAxl / (float)(yHigh - yLow); float yI = yL * (float)yHigh - yMx;
if(!xMolal) {xL = xL * 1000;} // T or TV and "milli units"
if(!yMolal) {yL = yL * 1000;} // T or TV and "milli units"
// pInX=0 "normal" X-axis
// pInX=1 pH in X-axis
// pInX=2 pe in X-axis
// pInX=3 Eh in X-axis
if(diag.pInX ==1 || diag.pInX == 2) {xL = -xL;}
else if(diag.pInX ==3) {xL = -xL * (float)pred.peEh;}
if(diag.pInY ==1 || diag.pInY == 2) {yL = -yL;}
else if(diag.pInY ==3) {yL = -yL * (float)pred.peEh;}
// -------------------------------------------------------------------
// Create a PltData instance
pred.dd = new GraphLib.PltData();
// Create a GraphLib instance
GraphLib g = new GraphLib();
boolean textWithFonts = true;
try {g.start(pred.dd, plotFile, textWithFonts);}
catch (GraphLib.WritePlotFileException ex) {pred.showErrMsgBx(ex.getMessage(),1); g.end(); return;}
pred.dd.axisInfo = false;
g.setLabel("-- PREDOM DIAGRAM --");
// -------------------------------------------------------------------
// Draw Axes
g.setIsFormula(true);
g.setPen(1);
//g.setLabel("-- AXIS --");
g.setPen(-1);
// draw axes
try {g.axes((float)xLow, (float)xHigh, (float)yLow, (float)yHigh,
xOr,yOr, xAxl,yAxl, heightAx,
false, false, true);}
catch (GraphLib.AxesDataException ex) {pred.showMsg(ex); g.end(); return;}
//---- Write text under axes
// Concentration types:
// hur =1 for "T" (fixed Total conc.)
// hur =2 for "TV" (Tot. conc. Varied)
// hur =3 for "LTV" (Log(Tot.conc.) Varied)
// hur =4 for "LA" (fixed Log(Activity) value)
// hur =5 for "LAV" (Log(Activity) Varied)
// ---- Y-axis
float xP; float yP;
yP =((yAxl/2f)+yOr)-((((float)nTextY)/2f)*(1.3f*heightAx));
xP = xOr - 6.6f*heightAx;
String t;
if(dgrC.hur[diag.compY] ==5) { //"LAV"
if(diag.pInY ==0) {
if(Util.isGas(namn.identC[diag.compY])) {t = "Log P`"+namn.identC[diag.compY]+"'";}
else {t = "Log {"+namn.identC[diag.compY]+"}";} // not Gas
} // pInY=0
else if(diag.pInY ==1) {t="pH";}
else if(diag.pInY ==2) {t="pe";}
else //if(pInY ==3)
{t="E`SHE' / V";}
} //"LAV"
else if(dgrC.hur[diag.compY] ==2) { //"TV"
t = "["+namn.identC[diag.compY]+"]`TOT'";
if(yMolal) {t = t + " "+cUnit;}
else {t = t + " "+mUnit;}
} else { // if(dgrC.hur[diag.compY] ==3) "LTV"
t = "Log ["+namn.identC[diag.compY]+"]`TOT'";
}
if(dgrC.hur[diag.compY] ==2 || dgrC.hur[diag.compY] ==3 || dgrC.hur[diag.compY] ==5) {
g.setLabel("Y-AXIS TEXT");
g.moveToDrawTo(0, 0, 0);
g.sym((float)xP, (float)yP, (float)heightAx, t, 90, 0, false);
}
// ---- X-axis label (title)
yP = yOr - 3.6f*heightAx;
xP =((xAxl/2f)+xOr)-((((float)nTextX)/2f)*(1.1429f*heightAx));
if(dgrC.hur[diag.compX] ==5) { //"LAV"
if(diag.pInX ==0) {
if(Util.isGas(namn.identC[diag.compX])) {t = "Log P`"+namn.identC[diag.compX]+"'";}
else {t = "Log {"+namn.identC[diag.compX]+"}";} // not Gas
} // pInX=0
else if(diag.pInX ==1) {t="pH";}
else if(diag.pInX ==2) {t="pe";}
else //if(pInX ==3)
{t="E`SHE' / V";}
} //"LAV"
else if(dgrC.hur[diag.compX] ==2) { //"TV"
t = "["+namn.identC[diag.compX]+"]`TOT'";
if(xMolal) {t = t + " "+cUnit;}
else {t = t + " "+mUnit;}
} else { // if(dgrC.hur[diag.compX] ==3) "LTV"
t = "Log ["+namn.identC[diag.compX]+"]`TOT'";
}
if(dgrC.hur[diag.compX] ==2 || dgrC.hur[diag.compX] ==3 || dgrC.hur[diag.compX] ==5) {
g.setLabel("X-AXIS TEXT");
g.moveToDrawTo(0, 0, 0);
g.sym((float)xP, (float)yP, (float)heightAx, t, 0, 0, false);
}
// -------------------------------------------------------------------
// Draw the lines separating predominance areas
g.setLabel("-- PREDOMINANCE AREAS --"); g.moveToDrawTo(0, 0, 0);
g.setLabel("-- LINES --"); g.moveToDrawTo(0, 0, 0);
g.setPen(1);
//-- get the distance used to extimate if two points are neighbours
diagP.stepX = diagP.stepX * xL;
diagP.stepY = diagP.stepY * yL;
double xDMin = Math.sqrt((diagP.stepX*diagP.stepX)+(diagP.stepY*diagP.stepY));
xDMin = 1.3*xDMin + xDMin*0.05;
// iOther[j] = how many points that are borderline between two areas,
// in one of which species j predominates, are neighbours (within the xDMin distance)
iOther = new int[cs.Ms];
// neighb[j][n] = list of neighbour points which are borderline
// between two areas, in one of which, species "j" predominates.
// We assume that at most there will be 8 neighbours (for xDmin = 1x)
// at most there will be 24 neighbours (for xDmin = 2x)
// at most there will be 48 neighbours (for xDmin = 3x)
neighb = new int[cs.Ms][24];
// iFL[k] > 0 if the line pair[k][1/2] has been drawn to the point k, and
// iFL[k] = 0 if the line pair[k][1/2] starts at point k
iFL = new int[diagP.nPoint+1];
for(int i =0; i < iFL.length; i++) {iFL[i]=0;}
int j, now, ia, pairI0,pairI1, pairJ0,pairJ1, k;
int ipoint = -1;
double w1, w2, dist, dMin;
boolean b;
// ------------------------------------
// loop through all points to plot
//
// ---- Take a point ----
for(int i = 0; i <= diagP.nPoint; i++) {
pairI0 = diagP.pair[i][0];
pairI1 = diagP.pair[i][1];
if(pairI0 <= -1 || pairI1 <= -1) {continue;}
if(diag.oneArea >=0 &&
pairI0 != diag.oneArea && pairI1 != diag.oneArea) {continue;}
lineContinued = false;
iOther[pairI0] = 0; // no neighbouring points
iOther[pairI1] = 0;
now = -1;
// ---- Take another point ----
for(j = i+1; j <= diagP.nPoint; j++) {
pairJ0 = diagP.pair[j][0];
pairJ1 = diagP.pair[j][1];
//-- See that both points are within the minimum distance
w1 = Math.abs(diagP.xPl[i]-diagP.xPl[j])*xL;
w2 = Math.abs(diagP.yPl[i]-diagP.yPl[j])*yL;
dist = Math.sqrt((w1*w1)+(w2*w2));
if(dist > xDMin) {continue;}
if(!lineContinued || iFL[i] <= 1) {
// -- See that they belong to the same line
// (both species in pair[i][] are the same)
if(diag.oneArea >=0 &&
pairJ0 != diag.oneArea && pairJ1 != diag.oneArea) {continue;}
if(pairJ0 == pairI0 && pairJ1 == pairI1) {
//-- draw the line between the two points
if(now != i) {g.moveToDrawTo((diagP.xPl[i]*xL-xI), (diagP.yPl[i]*yL-yI), 0);}
g.moveToDrawTo((diagP.xPl[j]*xL-xI), (diagP.yPl[j]*yL-yI), 1);
now = j;
iFL[j]++;
lineContinued = true; //flag that the next "j" is a continuation
continue; //next j
} //else: not the same line
} // if !lineContinued || iFL[i] <=1
//-- Continuing the line,
// or points i and j do not belong to the same line:
// see if they have at least one species in common
k = -1;
if(pairJ0 == pairI0 || pairJ1 == pairI0) {k=pairI0;}
if(pairJ0 == pairI1 || pairJ1 == pairI1) {k=pairI1;}
if(k>=0) {
neighb[k][iOther[k]] = j;
iOther[k]++;
// continue;
}
} //for j
if(lineContinued && iFL[i] != 0) {continue;} //not continuing
// --- The line pair[i][1/2] did not continue further.
// Check if there is some neighbour points of any other lines
// with one species in common.
if(iOther[pairI0] > 0) {ia = pairI0;}
else if(iOther[pairI1] > 0) {ia = pairI1;}
else {continue;}
b = false;
do{
//this loop is performed once or twice,
// with "ia" either ia = pairI0 and/or ia = pairI1
if(b) {ia = pairI1;}
// Take the neighbour more far away from the center of the area
dMin = 0;
for(int ip = 0; ip < iOther[ia]; ip++) {
j = neighb[ia][ip];
w1 = Math.abs(diagP.xCentre[ia]-diagP.xPl[j]);
w2 = Math.abs(diagP.yCentre[ia]-diagP.yPl[j]);
dist = Math.sqrt((w1*w1)+(w2*w2));
if(dist < dMin) {continue;}
dMin = dist;
ipoint = j;
} //for ip
//-- draw the line between "i" and "ipoint"
j = ipoint;
if(now != i) {g.moveToDrawTo((diagP.xPl[i]*xL-xI), (diagP.yPl[i]*yL-yI), 0);}
g.moveToDrawTo((diagP.xPl[j]*xL-xI), (diagP.yPl[j]*yL-yI), 1);
now = j;
b = true;
} while (ia == pairI0 && iOther[pairI1] >0);
} //for i
// -------------------------------------------------------------------
// Labels for Predominating Species
g.setLabel("-- AREA LABELS --"); g.moveToDrawTo(0, 0, 0);
g.setPen(4);
g.setPen(-4);
double size = heightAx * 0.75;
double incrY = heightAx / 6;
boolean overlp;
int sign, incr;
double yCentre0;
int ii, ji;
for(int i = 0; i < cs.Ms+cs.Ms; i++) {
if(diagP.xCentre[i] < -1000) {continue;}
ii = i;
if(ii > cs.Ms) {ii = ii - cs.Ms;}
if(diag.oneArea >=0 && ii != diag.oneArea) {continue;}
diagP.xCentre[i] = (diagP.xCentre[i]*xL - xI) - (0.5*size*namn.nameLength[ii]);
diagP.yCentre[i] = (diagP.yCentre[i]*yL - yI) - (0.5*size);
// Check that labels do not overlap each other
if(i>0) {
yCentre0 = diagP.yCentre[i];
sign = -1;
incr = 1;
do {
overlp = false;
for(j = 0; j < i; j++) {
if(diagP.xCentre[j] < -1000) {continue;}
ji = j;
if(ji > cs.Ms) {ji = ji - cs.Ms;}
if(diagP.yCentre[i] > (diagP.yCentre[j]+2*size)) {continue;}
if(diagP.yCentre[i] < (diagP.yCentre[j]-2*size)) {continue;}
if(diagP.xCentre[i] > (diagP.xCentre[j]+size*namn.nameLength[ji])) {continue;}
if(diagP.xCentre[i] < (diagP.xCentre[j]-size*namn.nameLength[ji])) {continue;}
overlp = true; break;
} //for j
if(overlp) {
diagP.yCentre[i] = yCentre0 +(sign * incr * incrY);
sign = -sign;
if(sign == -1) {incr++;}
} //if overlp
} while (overlp);
} //if i>0
// plot the label
g.sym(diagP.xCentre[i], diagP.yCentre[i], size, namn.ident[ii], 0, 0, false);
} //for i
// -------------------------------------------------------------------
// Neutral pH - Dotted line
// for diagrams with pH in one axis
if(pred.neutral_pH && (diag.pInX ==1 || diag.pInY ==1)) {
if(Double.isNaN(diag.temperature)) {
pred.showMsg("Error: Neutral pH line requested but temperature NOT available.",0);
} else {
double pHn;
try {pHn = n_pH(diag.temperature, diag.pressure);}
catch (Exception ex) {
pred.showMsg(ex); pHn = -10;
}
if(pHn > 0) {
g.setLabel("-- DOT LINE: neutral pH --"); g.moveToDrawTo(0, 0, 0);
g.setPen(3);
g.setPen(-3);
g.lineType(5);
double[] lineX = new double[2];
double[] lineY = new double[2];
if(diag.pInX == 1) {
lineX[0]=pHn; lineX[1]=pHn;
lineY[0]=diagP.yTop; lineY[1]=diagP.yBottom;
} else {
lineX[0]=diagP.xLeft; lineY[1]=diagP.xRight;
lineY[0]=pHn; lineY[1]=pHn;
}
g.line(lineX, lineY);
g.lineType(0);
}
} // temperature OK
} // neutral_pH
// -------------------------------------------------------------------
// O2/H2O - H2/H2O lines
if(diag.pInX >0 && diag.pInY >0) {
// get equilibrium constants at the temperature (in Celsius) for:
// O2(g) + 4 H+ + 4 e- = 2 H2O(l) logK(1)=4pH+4pe
// H2(g) = 2 H+ + 2 e- (logK(2)=0 at every temp)
if(Double.isNaN(diag.temperature)) {
pred.showMsg("Temperature NOT available in a pH/(pe or Eh) diagram.",2);
} else {
double lgKO2;
final double CRITICAL_TC = 373.946;
if(Double.isNaN(diag.pressure)) {
if(diag.temperature >= 0 && diag.temperature < CRITICAL_TC) {
diag.pressure = Math.max(1.,lib.kemi.H2O.IAPWSF95.pSat(diag.temperature));
}
}
if(Double.isNaN(diag.pressure)) {diag.pressure = 1000;}
try {lgKO2 = logK_O2(diag.temperature, diag.pressure);}
catch (Exception ex) {pred.showMsg(ex); lgKO2 = -1;}
if(pred.dbg) {out.println("logK_O2("+diag.temperature+","+diag.pressure+") = "+lgKO2);}
if(!Double.isNaN(lgKO2) && lgKO2 > 0) {
g.setLabel("-- DASH LINES: O2(g) and H2(g) = 1 atm --"); g.moveToDrawTo(0, 0, 0);
g.setPen(4);
g.setPen(-5);
g.lineType(1);
double[] line_pH = new double[2];
double[] line_O2 = new double[2];
double[] line_H2 = new double[2];
//the pH range:
line_pH[0]=-10; line_pH[1]=+20;
if(diag.pInX == 3 || diag.pInY == 3) {w1 = pred.peEh;} else {w1 = 1;}
line_O2[0]= ((0.25*lgKO2) - line_pH[0]) * w1;
line_O2[1]= ((0.25*lgKO2) - line_pH[1]) * w1;
line_H2[0] = -line_pH[0] * w1;
line_H2[1] = -line_pH[1] * w1;
if(Util.isProton(namn.identC[diag.compX])) {
g.line(line_pH, line_O2);
g.line(line_pH, line_H2);
} else {
g.line(line_O2, line_pH);
g.line(line_H2, line_pH);
}
g.lineType(0);
}
} // temperature OK
} //both pInX and pInY
// -------------------------------------------------------------------
// Text with concentrations as a Heading
g.setLabel("-- HEADING --"); g.setPen(1); g.setPen(-1);
if(pred.dbg) {
out.print("Heading; concentration units: \""+pred.cUnits[pred.conc_units+1]+"\"");
if(pred.conc_nottn == 2 || (pred.conc_nottn == 0 && pred.conc_units == 2)) {out.print(", notation: engineering");}
if(pred.conc_nottn == 1 || (pred.conc_nottn == 0 && pred.conc_units != 2)) {out.print(", notation: scientific");}
out.println();
}
float headColumnX = 0.5f*heightAx;
int headRow = 0;
int headRowMax = Math.max(2,(1+cs.Na)/2);
yP = yMx + 0.5f*heightAx; // = yMx + heightAx in SED
float yPMx = yMx;
double w, wa;
// Concentration types:
// hur =1 for "T" (fixed Total conc.)
// hur =2 for "TV" (Tot. conc. Varied)
// hur =3 for "LTV" (Log(Tot.conc.) Varied)
// hur =4 for "LA" (fixed Log(Activity) value)
// hur =5 for "LAV" (Log(Activity) Varied)
int i;
for(j =0; j < cs.Na; j++) {
if(dgrC.hur[j] !=1 && dgrC.hur[j] !=4) {continue;} //"T" or "LA" only
if(dgrC.hur[j] ==4 && Util.isWater(namn.ident[j])) {continue;}
i = namn.iel[j];
yP = yP + 2f*heightAx;
headRow++;
if(headRow == headRowMax) {
headColumnX = headColumnX + (33f*heightAx);
yP = yMx + 2.5f*heightAx; // = yMx + 3f*heightAx in SED
}
yPMx = Math.max(yPMx,yP);
String value;
if(dgrC.hur[j] == 1) { //"T"
w = csC.tot[j]; wa = Math.abs(w);
// use engineering notation?
if(pred.conc_nottn == 2 || (pred.conc_nottn == 0 && pred.conc_units == 2)) {
if(wa < 1.E-99) {value = String.format(engl,"=%8.2f",(float)w);}
else if(wa < 1. && wa >= 0.9999E-4) {
w = w*1.E+3;
value = String.format(engl,"=%8.2f"+mUnit,(float)w);
} else if(wa < 0.9999E-4 && wa >= 0.9999E-7) {
w = w*1.E+6;
value = String.format(engl,"=%8.2f"+uUnit,(float)w);
} else if(wa < 0.9999E-7 && wa >= 0.9999E-10) {
w = w*1.E+9;
value = String.format(engl,"=%8.2f"+nUnit,(float)w);
} else if(wa <= 9999.99 && wa >= 0.99) {
value = String.format(engl,"=%8.2f "+cUnit,(float)w);
} else {
value = "= "+double2String(w)+" "+cUnit;
}
} else {
if(wa < 1.E-99) {value = String.format(engl,"=%8.2f",(float)w);}
else if(wa <= 9999.99 && wa >= 0.99) {
value = String.format(engl,"=%8.2f "+cUnit,(float)w);
} else {
value = "= "+double2String(w)+" "+cUnit;
}
}
t = "["+namn.ident[i]+"]`TOT' "+value;
} // hur=1: "T"
else //if(pred.hur[j] == 4) { //"LA"
{ String c;
boolean volt = false;
if(Util.isElectron(namn.ident[j])) {
w = -dgrC.cLow[j];
if(diag.Eh){c = "E`H' = "; w = w*pred.peEh; volt = true;}
else {c = "pe =";}
} //isElectron
else if(Util.isProton(namn.ident[i])) {
w = -dgrC.cLow[j]; c = "pH=";}
else if(Util.isGas(namn.ident[i])) {
w = dgrC.cLow[j]; c = "Log P`"+namn.ident[i]+"' =";}
else {w = dgrC.cLow[j]; c = "Log {"+namn.ident[i]+"} =";}
value = String.format(engl,"%7.2f",(float)w);
t = c + value;
if(volt) {t = t+" V";}
} //hur=4: "LA"
g.sym(headColumnX, yP, heightAx, t, 0f, -1, false);
} //for j
// ---- Ionic Strength
if(!Double.isNaN(diag.ionicStrength) &&
Math.abs(diag.ionicStrength) > 1.e-10) {
g.setLabel("-- Ionic Strength --");
g.setPen(-1);
yP = yP + 2f*heightAx;
headRow++;
if(headRow == headRowMax) {
headColumnX = headColumnX + (33f*heightAx);
yP = yMx + 2.5f*heightAx; // = yMx + 3f*heightAx in SED
}
if(yP > (yPMx + 0.1f*heightAx)) {headColumnX = (0.5f*heightAx); yPMx = yP;}
if(diag.ionicStrength > 0) {
t = String.format(engl,"I=%6.3f "+cUnit,diag.ionicStrength);
} else {t = "I= varied";}
g.sym(headColumnX, yP, heightAx, t, 0, -1, false);
} // if ionicStrength != NaN & !=0
// ---- Temperature and pressure
//if(!Double.isNaN(diag.temperature) && diag.temperature > -1.e-6) {
// g.setLabel("-- Temperature --");
// g.setPen(-1);
// t = String.format(engl,"t=%3d~C",Math.round((float)diag.temperature));
// w = 7; // 2.7 for program SED
// g.sym((float)(xMx+w*heightAx), (0.1f*heightAx), heightAx, t, 0, -1, false);
//} //if temperature_InCommandLine >0
// ---- Temperature + Pressure (in the heading)
if(!Double.isNaN(diag.temperature)) {
if(Double.isNaN(diag.pressure) || diag.pressure < 1.02) {
g.setLabel("-- Temperature --");
} else {g.setLabel("-- Temperature and Pressure --");}
g.setPen(-1);
t = String.format(engl,"t=%3d~C",Math.round((float)diag.temperature));
if(!Double.isNaN(diag.pressure) && diag.pressure > 1.02) {
if(diag.pressure < 220.64) {
t = t + String.format(java.util.Locale.ENGLISH,", p=%.2f bar",diag.pressure);
} else {
if(diag.pressure <= 500) {t = t + String.format(", p=%.0f bar",diag.pressure);}
else {t = t + String.format(java.util.Locale.ENGLISH,", p=%.1f kbar",(diag.pressure/1000.));}
}
}
yP = yP + 2f*heightAx;
headRow++;
if(headRow == headRowMax) {
headColumnX = headColumnX + (33f*heightAx);
yP = yMx + 2.5f*heightAx; // = yMx + 3f*heightAx in SED
}
if(yP > (yPMx + 0.1f*heightAx)) {headColumnX = (0.5f*heightAx); yPMx = yP;}
g.sym(headColumnX, yP, heightAx, t, 0, -1, false);
} //if temperature >0
yP = yPMx;
headColumnX = (float)(0.5d*heightAx);
if(pred.aqu) {
yP = yP + 2f*heightAx;
g.sym(headColumnX, yP, heightAx, "(aqueous species only)", 0, -1, false);
}
if(diag.oneArea >= 0) {
yP = yP + 2f*heightAx;
g.sym(headColumnX, yP, heightAx, "(one area only)", 0, -1, false);
}
// ---- Title
if(diag.title != null && diag.title.trim().length() > 0) {
g.setLabel("-- TITLE --");
g.setPen(2); g.setPen(-2);
g.sym(0, yPMx+(3.5f*heightAx), heightAx, diag.title, 0, -1, false);
} // plotTitle != null
// -------------------------------------------------------------------
// Finished
g.end();
} //drawPlot()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="n_pH(temperature)">
/** Returns the neutral pH at the given temperature and pressure.
* It uses the equation reported in
* Marshall W L, Franck E U (1981) Ion product of water substance, 0-1000 °C,
* 1-10,000 bars. New international formulation and its background.
* J. Phys. Chem. Ref. Data, vol.10, pp.295–304. doi:10.1063/1.555643
* @param tC temperature in Celsius (0 to 1000)
* @param pBar pressure in bar (1 to 10 000)
* @return neutral pH at the temperature t
* @throws chem.Chem.ChemicalParameterException */
private static double n_pH(double tC, double pBar) throws IllegalArgumentException,
ArithmeticException {
if(tC < 0 || tC > 1000) {
throw new IllegalArgumentException (nl+
"Error in procedure \"n_pH\": temperature = "+tC+"°C (min=0, max=1000).");
}
if(pBar < 1 || pBar > 10000) {
throw new IllegalArgumentException (nl+
"Error in procedure \"n_pH\": pressure = "+pBar+" bar (min=1, max=10000).");
}
if(pBar < 220){ // Critical pressure = 220.64 bar
if(tC >= 373) { // Critical temperature = 373.946 C
throw new IllegalArgumentException (nl+
"Error in procedure \"n_pH\":"+
" t = "+tC+", p = "+pBar+" bar (at (p < 220 bar) t must be < 373C).");
}
}
double rho = Double.NaN;
try {rho = lib.kemi.H2O.IAPWSF95.rho(tC, pBar);}
catch (Exception ex) {throw new ArithmeticException(ex.toString());}
double a = -4.098, b = -3245.2, c = 2.2362e5, d = -3.984e7;
double e = +13.957, f = -1262.3, g = +8.5641e5;
double tK = tC + 273.15, tK2 = tK*tK;
double npH = a + b/tK + c/tK2 + d/(tK2*tK) + (e + f/tK + g/tK2)*Math.log10(rho);
npH = npH / 2;
boolean dbg = false;
if(dbg) {System.out.println("--- n_pH("+tC+","+pBar+") = "+npH);}
return npH;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="logK_O2(tC,pbar)">
/** Calculates the equilibrium constant for reaction 2H2O = O2(g)+2H2(g)
* as a function of temperature and pressure. This reaction is equivalent to
* 2H2O = O2(g) + 4H+ + 4e-, because the equilibrium constant for H2(g) = 2H+ + 2e-
* is by definition zero at all temperatures and pressures. An equation is
* used based in the values calculated with the SUPCRT92 software.<b>
* Range of conditions: 1 to 5,000 bar, -35 to 600°C.
* It returns NaN (Not a Number) outside this range, or if
* water is frozen at the requested conditions.
* If pBar < 1 a value of pBar = 1 is used.
* If tC = 0 and pBar = 1, it returns the value at 0.01 Celsius and 1 bar.
* NOTE: values returned at tC <0 are extrapolations outside the valid range.
* @param tC temperature in Celsius
* @param pBar pressure in bar
* @return the equilibrium constant for the reaction 2H2O = O2(g)+2H2(g)
* @throws IllegalArgumentException
*/
private static double logK_O2(final double tC, final double pBar) throws IllegalArgumentException {
if(Double.isNaN(tC)) {throw new IllegalArgumentException("\"logK_O2\" tC = NaN.");}
if(Double.isNaN(pBar)) {throw new IllegalArgumentException("\"logK_O2\" pBar = NaN.");}
if(tC < -35 || tC > 1000.01 || pBar < 0 || pBar > 5000.01) {
throw new IllegalArgumentException("\"logK_O2\" tC = "+tC+", pBar = "+pBar+" (must be -35 to 1000 C and 0 to 5000 bar)");
}
// set minimum pressure to 1 bar
final double p_Bar = Math.max(pBar, 1.);
final double t_C;
// if pressure = 1 bar and temperature = 0, set temperature to 0.01 C (tripple point of water)
if(p_Bar >0.99999 && p_Bar < 1.00001 && Math.abs(tC) < 0.001) {t_C = 0.01;} else {t_C = tC;}
// Make sure that water is not frozen or steam.
String str = lib.kemi.H2O.IAPWSF95.isWaterLiquid(t_C, p_Bar); // ma
if(str.length() >0) {throw new IllegalArgumentException(str);}
// check if pressure is below the saturated vapor line
if(t_C > 0.01 && t_C < 373.946) {
final double pSat = lib.kemi.H2O.IAPWSF95.pSat(t_C);
if(p_Bar < (pSat*0.99)) {
throw new IllegalArgumentException("\"logK_O2\": pBar = "+p_Bar+ "(at tC = "+t_C+" pBar must be above "+(float)pSat+" bar)");
}
}
final double logK0 = 83.105; // from the SUPCRT92 software
final double tK = t_C + 273.15, tK0 = 298.15;
final double tK_tK0 = tK-tK0;
final double pBar_p0 = p_Bar - 1.;
if(Math.abs(tK_tK0) < 1 && p_Bar < 2) {return logK0;}
// final double R = 8.31446262; // gas constant
// final double ln10 = 2.302585093;
// final double Rln10 = 19.14475768082;
// final double deltaS0 = -327.77; // from the SUPCRT92 software
final double deltaS0_Rln10 = -17.06840094; // = deltaS0 / (R ln(10))
// the equation used is:
// logK = (T0/T)logK0 + (deltaS0/(R T ln10)) (T-T0) + a (- (T-T0)/T + ln(T/T0))
// + b (-1/(2T) (T^2-T0^2) + (T-T0)) + e ((1/T) (1/T - 1/T0) - (1/2)(1/T^2 - 1/T0^2))
// - (q1 + q2 T + q3 T^2) (1/T) (P-P0) + (u1 + u2 T + u3 T^2) (1/2T) (P-P0)^2
final double a = 5.585, b = -0.000404, e = -257000.;
final double q1 = 0.2443, q2 = -0.0004178, q3 = 7.357E-7;
final double u1 = 2.17E-5, u2 = -1.044E-7, u3 = 1.564E-10;
final double tK2 = tK*tK;
final double tK02 = 88893.4225; // = 298.15 x 298.15
double logK = (tK0/tK)*logK0 + (deltaS0_Rln10/tK)*(tK_tK0);
logK = logK + a * (-tK_tK0/tK + Math.log(tK/tK0));
logK = logK + b * (-(1./(2.*tK))*(tK2-tK02) + tK_tK0);
logK = logK + e * ((1./tK)*((1./tK)-(1./tK0)) - 0.5*((1./tK2)-(1./tK02)));
if(p_Bar < 2) {return logK;}
final double dq = q1 + q2*tK + q3*tK2;
final double du = u1 + u2*tK + u3*tK2;
logK = logK - dq * (1./tK)*pBar_p0 + du * (1./(2.*tK))*pBar_p0*pBar_p0;
return logK;
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="double2String">
/** Returns a text representing a double in the format
* 1.23×10'-1`.
* @param d
* @return a string such as 1.23×10'-1`
*/
private static String double2String(double d) {
if(Double.isNaN(d) || Double.isInfinite(d)) {return String.valueOf(d);}
if(d == 0) {return "0.00";}
boolean ok = true;
// txt = number_in_scientific_notation
final String txt = String.format(engl,"%10.2e",d).trim();
int e = txt.indexOf('e');
String exp = "", sign="";
if(e >= 0) {
exp = txt.substring(e+1);
final int length =exp.length();
if(length > 1) {
int i, j;
sign = exp.substring(0,1);
if(sign.equals("+") || sign.equals("-")) {j=1;} else {j=0; sign="";}
if(length > j+1) {
for (i = j; i < length-1; i++) {
if (exp.charAt(i) != '0') {break;}
}
exp = exp.substring(i);
} else {ok = false;}
} else {ok = false;}
} else {
ok = false;
}
int k;
try{k = Integer.parseInt(exp);} catch (Exception ex) {
System.err.println(ex.getMessage());
k=0;
ok = false;
}
if(ok && k == 0) {return txt.substring(0, e);}
if(ok && exp.length() >0) {
return txt.substring(0, e)+"×10'"+sign+exp+"`";
} else {return txt;}
}
//</editor-fold>
}// class Plot_Predom
| 43,511 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
PlotPDF.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/PlotPDF/src/plotPDF/PlotPDF.java | package plotPDF;
/** Convert a plt-file to PDF-format.
* The input file is assumed to be in the system-dependent default
* character encoding. The PDF file is written in "ISO-8859-1" character
* encoding (ISO Latin Alphabet No. 1).
*
* If an error occurs, a message is displayed to the console, and
* unless the command line argument -nostop is given, a message box
* displaying the error is also produced.
*
* Copyright (C) 2015-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class PlotPDF {
private static final String progName = "PlotPDF";
private static final String VERS = "2020-June-12";
private static boolean started = false;
/** print debug information? */
private boolean dbg = false;
/** if true the program does display dialogs with warnings or errors */
private boolean doNotStop = false;
/** the plot file to be converted */
private java.io.File pltFile;
/** the pdf file name (the converted plt file) */
private String pdfFile_name;
/** the pdf file (the converted plt file) */
private java.io.File pdfFile;
/** has the file conversion finished ? */
private boolean finished = false;
private java.io.BufferedReader bufReader;
private java.io.BufferedWriter outputFile;
/** has an error occurred? if so, delete the output file */
private boolean delete = false;
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
private static final String SLASH = java.io.File.separator;
private static final String DASH_LINE = "- - - - - -";
private static final java.util.Locale engl = java.util.Locale.ENGLISH;
private String[] colours = new String[11];
/** line widths: normal (0.282 mm), thick, very-thin, thin */
private final double[] WIDTHS = {2.82, 6.35, 0.07, 1.06}; // units: 100 = 1 cm
// -- PDF things --
/** =(72/2.54)/100 */
private final double SCALE_USER_SPACE = 0.283464566929;
/** MediaBox [0 0 593 792] */
private static final double MediaBox_X = 593;
/** MediaBox [0 0 593 792] */
private static final double MediaBox_Y = 792;
private static final double MARGIN_X = 20;
private static final double MARGIN_Y = 15;
/** The size (bytes) of the first 21 pdf-objects,
* excluding the end-of-line characters (which are system dependent).
* Object nbr.0 consists of the two first comment lines in the pdf-file:<pre>
* %PDF-1.1
* % see objects 21 and 22 below</pre> */
private int[] objBytesNoNewLine = { 37,
40, 47, 85, 90, 93,
97, 87, 92, 95,100,
70, 90, 90, 92, 96,
77, 60,186, 98, 76, 50};
/** The number of end-of-lines in each of the 21 pdf-objects.
* Used to calculate the size in bytes of each object.
* Object nbr.0 consists of the two first comment lines in the pdf-file:<pre>
* %PDF-1.1
* % see objects 21 and 22 below</pre> */
private int[] objNbrNewLines = { 2,
6, 7, 9, 9, 9,
9, 9, 9, 9, 9,
8, 9, 9, 9, 9,
8, 7, 22, 8, 8, 5};
/** number of characters in a end-of-line */
private static final int nlL = System.getProperty("line.separator").length();
private final int NBR_PDF_OBJECTS = objBytesNoNewLine.length;
/** are we in the middle of printing some text? */
private boolean startedPrintingText = false;
/** text used in the PDF file to change the font */
private String changeFontString;
/** the size of the font as a text string */
private String fontSizeTxt;
/** line widths: 0 = normal, 1 = thick, 2 = very-thin, 3 = thin */
private int penNow =0;
private int colorNow =0;
//TODO: change zx and zy to shiftX and shiftY
private double scaleX, scaleY, zx, zy;
private double xNow=-Double.MAX_VALUE, yNow=-Double.MAX_VALUE;
private double x1st=-Double.MAX_VALUE, y1st=-Double.MAX_VALUE;
/** -1 = start of program;<br>
* 0 = no drawing performed yet;<br>
* 1 = some move performed;<br>
* 2 = some move/line-draw performed. */
private int newPath = -1;
// -- data from the command-line arguments
private boolean pdfHeader = true;
/** Colours: 0=black/white; 1=Standard palette; 2="Spana" palette. */
private int pdfColors = 1;
private boolean pdfPortrait = true;
/** Font type: 0=draw; 1=Times; 2=Helvetica; 3=Courier. */
private int pdfFont = 2;
/** 0=Vector graphics; 1=Times-Roman; 2=Helvetica; 3=Courier. */
private final String[] FONTS = {"Vector graphics", "Times-Roman", "Helvetica", "Courier"};
private int pdfSizeX = 100;
private int pdfSizeY = 100;
private double pdfMarginB = 0;
private double pdfMarginL = 0;
//<editor-fold defaultstate="collapsed" desc="main: calls the Constructor">
/** @param args the command line arguments */
public static void main(String[] args) {
boolean h = false;
boolean doNotS = false, debg = false;
String msg = "GRAPHIC \"Portable Document Format (PDF)\" UTILITY "+VERS+nl+
"================================================== (Unicode UTF-8 vers.)"+nl;
System.out.println(msg);
if(args.length > 0) {
for(String arg : args) {
if (arg.equalsIgnoreCase("-dbg") || arg.equalsIgnoreCase("/dbg")) {
debg =true;
} else if (arg.equalsIgnoreCase("-nostop") || arg.equalsIgnoreCase("/nostop")) {
doNotS = true;
} else if (arg.equals("-?") || arg.equals("/?") || arg.equals("?")) {
h = true;
printInstructions(System.out);
} //if args[] = "?"
} //for arg : args
if(h) {return;} // exit after help
} //if args.length >0
else {
String t = "This program will convert a plot file (*.plt) into a PDF file."+nl+
"Usage: java -jar PlotPDF.jar [plot-file-name] [-command=value]"+nl+
"For a list of possible commands type: java -jar PlotPDF.jar -?";
System.out.println(t);
ErrMsgBx mb = new ErrMsgBx(msg + nl + "Note: This is a console application."+nl+t, progName);
System.exit(0);
}
PlotPDF pp;
try{
pp = new PlotPDF(debg, doNotS, args);
} catch (Exception ex) { // this should not happen
exception(ex, null, doNotS);
pp = null;
}
// ---- if needed: wait for the calculations to finish on a different thread
if(pp != null) {
final PlotPDF p = pp;
Thread t = new Thread() {@Override public void run(){
p.synchWaitConversion();
p.end_program();
}};// Thread t
t.start(); // Note: t.start() returns inmediately;
// statements here are executed inmediately.
try{t.join();} catch (java.lang.InterruptedException ex) {} // wait for the thread to finish
}
System.out.println("All done."+nl+DASH_LINE);
System.exit(0);
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="end_program, etc">
private void end_program() {
finished = true;
this.notify_All();
}
private synchronized void notify_All() {this.notifyAll();}
private synchronized void synchWaitConversion() {
while(!finished) {
try {this.wait();} catch(InterruptedException ex) {}
}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Constructor: runs the program itself">
/** Constructor: runs the program itself
* @param debg
* @param doNotS
* @param args */
public PlotPDF(boolean debg, boolean doNotS, final String[] args) {
if(debg) {dbg = true;}
doNotStop = doNotS;
//--- read the command line arguments
pltFile = null; pdfFile = null;
String msg = null;
boolean argErr = false;
if(args != null && args.length >0){
if(dbg) {System.out.println("Reading command-line arguments..."+nl);}
for(int i=0; i<args.length; i++) {
if(dbg){System.out.println("Command-line argument = \""+args[i]+"\"");}
if(i == 0 && !args[0].toLowerCase().startsWith("-p")) {
// Is it a plot file name?
boolean ok = true;
String name = args[0];
if(name.startsWith("\"") && name.endsWith("\"")) { //remove enclosing quotes
name = name.substring(1, name.length()-1);
}
if(!name.toLowerCase().endsWith(".plt")) {name = name.concat(".plt");}
java.io.File f = new java.io.File(name);
if(!f.exists()) {
if(dbg) {System.out.println("Not a plt-file: \""+f.getAbsolutePath()+"\"");}
ok = false;
} // it is not a file
if(ok && f.isDirectory()) {
msg = "Error: \""+f.getAbsolutePath()+"\" is a directory.";
ok = false;
}
if(ok && !f.canRead()) {
msg = "Error: can not open file for reading:"+nl+" \""+f.getAbsolutePath()+"\"";
ok = false;
}
// ok = true if it is an existing file that can be read
if(ok) {
if(dbg){System.out.println("Plot file: "+f.getPath());}
pltFile = f;
continue;
} else {
if(msg != null) {
if(doNotStop) {System.out.println(msg);} else {ErrMsgBx mb = new ErrMsgBx(msg,progName);}
}
}
} // if i=0
if(!parseArg(args[i].trim())) {argErr = true; break;}
} // for i
} // if args
if(dbg) {System.out.println(nl+"Command-line arguments ended."+nl);}
if(argErr) {end_program(); return;}
if(pltFile == null) {
msg = "No plot file name given in the command-line.";
if(doNotStop) {System.out.println(msg);} else {ErrMsgBx mb = new ErrMsgBx(msg,progName);}
end_program(); return;
}
if(pdfFile_name != null && pdfFile_name.trim().length() >0) {
if(pdfFile_name.contains(SLASH)) {
pdfFile = new java.io.File(pdfFile_name);
} else {
pdfFile = new java.io.File(pltFile.getParent(), pdfFile_name);
if(dbg) {
System.out.println("PDF-file: \""+pdfFile.getAbsolutePath()+"\""+nl);
}
}
}
if(pdfFile == null) {
String name = pltFile.getAbsolutePath();
int n = name.length();
name = name.substring(0, n-4)+".pdf";
pdfFile = new java.io.File(name);
}
if(pdfFile.exists() && (!pdfFile.canWrite() || !pdfFile.setWritable(true))) {
msg = "Error: can not write to file"+nl+" \""+pdfFile.toString()+"\""+nl+
"is the file locked?";
if(doNotStop) {System.out.println(msg);} else {ErrMsgBx mb = new ErrMsgBx(msg,progName);}
end_program(); return;
}
String o = "Portrait"; if(!pdfPortrait) {o = "Landscape";}
String c = "black on white";
if(pdfColors == 1) {c = "colours";} else if(pdfColors == 2) {c = "colours selected in \"Spana\"";}
System.out.println("plot file: "+maybeInQuotes(pltFile.getName())+nl+
"output file: "+maybeInQuotes(pdfFile.getName())+nl+
"options:"+nl+
" size "+pdfSizeX+"/"+pdfSizeY+" %;"+
" left, bottom margins = "+pdfMarginL+", "+pdfMarginB+" cm"+nl+
" orientation = "+o+"; font = "+FONTS[pdfFont]+nl+
" "+c);
System.out.print("converting to ");
System.out.println("PDF ...");
try{convert2PDF();}
catch(Exception ex) {
exception(ex, null, doNotStop);
delete = true;
}
// --- close streams
try{if(bufReader != null) {bufReader.close();}}
catch (java.io.IOException ex) {
exception(ex, "while closing file:"+nl+" \""+pltFile+"\"", doNotStop);
}
if(outputFile != null) {
try{
outputFile.flush();
outputFile.close();
} catch (java.io.IOException ex) {
exception(ex, "while closing file:"+nl+" \""+pdfFile+"\"", doNotStop);
}
}
if(delete) {pdfFile.delete();}
end_program();
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="parseArg">
/** Interpret a command-line argument
* @param arg String containing a command-line argument
* @return false if there was an error associated with the command argument
*/
private boolean parseArg(String arg) {
if(arg == null) {return true;}
if(arg.length() <=0) {return true;}
if(arg.equals("-?") || arg.equals("/?") || arg.equals("?")) {
printInstructions(System.out);
return true;
} //if args[] = "?"
String msg = null;
while(true) {
if(arg.equalsIgnoreCase("-dbg") || arg.equalsIgnoreCase("/dbg")) {
dbg = true;
System.out.println("Debug printout = true");
return true;
} // -dbg
else if(arg.equalsIgnoreCase("-nostop") || arg.equalsIgnoreCase("/nostop")) {
doNotStop = true;
if(dbg) {System.out.println("Do not show message boxes");}
return true;
} // -nostop
else if(arg.equalsIgnoreCase("-bw") || arg.equalsIgnoreCase("/bw")) {
if(dbg){System.out.println("Black on white");}
pdfColors = 0;
return true;
} // -bw
else if(arg.equalsIgnoreCase("-noh") || arg.equalsIgnoreCase("/noh")) {
if(dbg){System.out.println("No header");}
pdfHeader = false;
return true;
} // -noh
else if(arg.equalsIgnoreCase("-clr") || arg.equalsIgnoreCase("/clr")) {
if(dbg){System.out.println("Colours (default palette)");}
pdfColors = 1;
return true;
} // -clr
else if(arg.equalsIgnoreCase("-clr2") || arg.equalsIgnoreCase("/clr2")) {
if(dbg){System.out.println("Colours (\"Spana\" palette)");}
pdfColors = 2;
return true;
} // -clr2
else {
if(arg.length() >3) {
String arg0 = arg.substring(0, 2).toLowerCase();
if(arg0.startsWith("-p") || arg0.startsWith("/p")) {
if(arg.charAt(2) == '=' || arg.charAt(2) == ':') {
String name = arg.substring(3);
if(name.startsWith("\"") && name.endsWith("\"")) { //remove enclosing quotes
name = name.substring(1, name.length()-1);
}
if(!name.toLowerCase().endsWith(".plt")) {name = name.concat(".plt");}
java.io.File f = new java.io.File(name);
name = f.getAbsolutePath();
f = new java.io.File(name);
if(!f.exists()) {
msg = "Error: the plot file does not exist:"+nl+" \""+f.getAbsolutePath()+"\"";
break;
} // it is not a file
if(f.isDirectory()) {
msg = "Error: \""+f.getAbsolutePath()+"\" is a directory.";
break;
}
if(!f.canRead()) {
msg = "Error: can not open file for reading:"+nl+" \""+f.getAbsolutePath()+"\"";
break;
}
if(dbg){System.out.println("Plot file: "+f.getPath());}
pltFile = f;
return true;
}// = or :
} // if starts with "-p"
else if(arg0.startsWith("-b") || arg0.startsWith("/b")) {
if(arg.charAt(2) == '=' || arg.charAt(2) == ':') {
String t = arg.substring(3);
try {pdfMarginB = Double.parseDouble(t);
pdfMarginB = Math.min(20,Math.max(pdfMarginB,-5));
if(dbg) {System.out.println("Bottom margin = "+pdfMarginB);}
return true;
} //try
catch (NumberFormatException nfe) {
msg = "Error: Wrong numeric format for bottom margin in text \""+t+"\"";
pdfMarginB = Double.NaN;
break;
} //catch
}// = or :
} // if starts with "-b"
else if(arg0.startsWith("-l") || arg0.startsWith("/l")) {
if(arg.charAt(2) == '=' || arg.charAt(2) == ':') {
String t = arg.substring(3);
try {pdfMarginL = Double.parseDouble(t);
pdfMarginL = Math.min(20,Math.max(pdfMarginL,-5));
if(dbg) {System.out.println("Left margin = "+pdfMarginL);}
return true;
} //try
catch (NumberFormatException nfe) {
msg = "Error: Wrong numeric format for left margin in text \""+t+"\"";
pdfMarginL = Double.NaN;
break;
} //catch
}// = or :
} // if starts with "-l"
else if(arg0.startsWith("-s") || arg0.startsWith("/s")) {
if(arg.charAt(2) == '=' || arg.charAt(2) == ':') {
String t = arg.substring(3);
int size;
try {size = Integer.parseInt(t);
size = Math.min(300,Math.max(size,20));
if(dbg) {System.out.println("Output size = "+size+" %");}
pdfSizeX = size;
pdfSizeY = size;
return true;
} //try
catch (NumberFormatException nfe) {
msg = "Error: Wrong numeric format for output size in text \""+t+"\"";
size = 100;
pdfSizeX = size;
pdfSizeY = size;
break;
} //catch
}// = or :
} // if starts with "-s"
else if(arg0.startsWith("-o") || arg0.startsWith("/o")) {
if(arg.charAt(2) == '=' || arg.charAt(2) == ':') {
String t = arg.substring(3).toLowerCase();
if(t.equals("p")) {pdfPortrait = true;} else
if(t.equals("l")) {pdfPortrait = false;}
if(t.equals("p") || t.equals("l")) {
if(dbg) {
t = "Orientation = ";
if(pdfPortrait) {t = t + "Portrait";}
else {t = t + "Landscape";}
System.out.println(t);
}
return true;
} else {
msg = "Error: Wrong format for orientation in text \""+t+"\"";
break;
}
}// = or :
} // if starts with "-o"
else if(arg0.startsWith("-f") || arg0.startsWith("/f")) {
if(arg.charAt(2) == '=' || arg.charAt(2) == ':') {
String t = arg.substring(3);
int f;
try {f = Integer.parseInt(t);
if(f >= 1 && f <= 4) {
pdfFont = f-1;
if(dbg) {System.out.println("Output font = "+FONTS[pdfFont]);}
return true;
} else {
msg = "Error: Wrong font type in text \""+t+"\"";
pdfFont = 2;
break;
}
} catch (NumberFormatException nfe) {
msg = "Error: Wrong numeric format for output size in text \""+t+"\"";
pdfFont = 2;
break;
} //catch
}// = or :
} // if starts with "-f"
} // if length >3
if(arg.length() >4) {
String arg0 = arg.substring(0, 3).toLowerCase();
if(arg0.startsWith("-sx") || arg0.startsWith("/sx")) {
if(arg.charAt(3) == '=' || arg.charAt(3) == ':') {
String t = arg.substring(4);
int size;
try {size = Integer.parseInt(t);
size = Math.min(300,Math.max(size,20));
if(dbg) {System.out.println("Output X-size = "+size+" %");}
pdfSizeX = size;
return true;
} //try
catch (NumberFormatException nfe) {
msg = "Error: Wrong numeric format for output X-size in text \""+t+"\"";
size = 100;
pdfSizeX = size;
break;
} //catch
}// = or :
} // if starts with "-sx"
else if(arg0.startsWith("-sy") || arg0.startsWith("/sy")) {
if(arg.charAt(3) == '=' || arg.charAt(3) == ':') {
String t = arg.substring(4);
int size;
try {size = Integer.parseInt(t);
size = Math.min(300,Math.max(size,20));
if(dbg) {System.out.println("Output Y-size = "+size+" %");}
pdfSizeY = size;
return true;
} //try
catch (NumberFormatException nfe) {
msg = "Error: Wrong numeric format for output Y-size in text \""+t+"\"";
size = 100;
pdfSizeY = size;
break;
} //catch
}// = or :
} // if starts with "-sy"
} // if length >4
if(arg.length() >5) {
String arg0 = arg.substring(0, 4).toLowerCase();
if(arg0.startsWith("-pdf") || arg0.startsWith("/pdf")) {
if(arg.charAt(4) == '=' || arg.charAt(4) == ':') {
String name = arg.substring(5);
if(name.startsWith("\"") && name.endsWith("\"")) { //remove enclosing quotes
name = name.substring(1, name.length()-1);
}
if(!name.toLowerCase().endsWith(".pdf")) {name = name.concat(".pdf");}
if(dbg){System.out.println("PDF file: "+name);}
pdfFile_name = name;
return true;
}// = or :
} // if starts with "-pdf"
}
}
// nothing matches
break;
} //while
if(msg == null) {msg = "Error: can not understand command-line argument:"+nl+
" \""+arg+"\"";}
else {msg = "Command-line argument \""+arg+"\":"+nl+msg;}
if(doNotStop) {System.out.println(msg);} else {ErrMsgBx mb = new ErrMsgBx(msg,progName);}
System.out.println();
printInstructions(System.out);
return false;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="convert2PDF">
private void convert2PDF() {
// initialize the contents of some variables
scaleX = (double)pdfSizeX/100d + 1e-10;
scaleY = (double)pdfSizeY/100d + 1e-10;
zx = pdfMarginL * 100;
zy = pdfMarginB * 100;
newPath = -1;
x1st = -Double.MAX_VALUE; y1st = -Double.MAX_VALUE;
//--- The PDF file is written in ISO-LATIN-1 encoding
// Standard charsets: Every implementation of the Java platform is
// required to support the following standard charsets.
// Charset Description
// US-ASCII Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block
// of the Unicode character set
// ISO-8859-1 ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1
// UTF-8 Eight-bit UCS Transformation Format
// UTF-16BE Sixteen-bit UCS Transformation Format, big-endian byte order
// UTF-16LE Sixteen-bit UCS Transformation Format, little-endian byte order
// UTF-16 Sixteen-bit UCS Transformation Format, byte order identified by
// an optional byte-order mark
//--- make sure the output file can be written
String msg;
try{
outputFile = new java.io.BufferedWriter(
new java.io.OutputStreamWriter(
new java.io.FileOutputStream(pdfFile), "UTF8"));
} catch (java.io.FileNotFoundException ex) {
msg = "Error:"+nl+ex.getMessage()+nl+
"****************************************"+nl+
"** Is the output PDF-file locked? **"+nl+
"****************************************";
if(doNotStop) {System.out.println(msg);} else {ErrMsgBx mb = new ErrMsgBx(msg,progName);}
return;
} catch (java.io.UnsupportedEncodingException ex) {
msg = "while writing the PDF file:"+nl+
" \""+pdfFile.getAbsolutePath()+"\"";
exception(ex, msg, doNotStop);
return;
}
//--- files appear to be ok
setPalette();
//--- open the input plt-file
bufReader = getBufferedReader(pltFile, doNotStop);
if(bufReader == null) {return;}
//PDF files have the following parts: a one-line header, a body consisting
//of pdf-objects, a cross-reference table, and a short trailer
//Write pdf-objects 1 to 21 (fonts, etc)
pdf_Init(outputFile);
//The PDF output is written here into a "stream" in pdf-object nbr.22
//The length of the stream must preceede the stream itself.
//This is done by writing the stream into a memory character array,
//and after ending processing the input plot file, find out the
//length of the stream, writing the length to the pdf file, followed
//by the stream itself, and at the end the xref (cross-reference table).
pdfStreamStart();
if(pdfHeader) {
pdfStreamAppendTo("BT"+nl+"/F0 8 Tf"+nl+"1 0 0 1 30 770 Tm"+nl+"0 0 0 rg");
pdfStreamAppendTo("0 0 (File: "+fixTextSimple(maybeInQuotes(pltFile.getAbsolutePath()),false)+") \""+nl+
"1 0 0 1 30 760 Tm");
pdfStreamAppendTo("0 0 (Converted to pdf: "+getDateTime()+") \""+nl+"ET");
}
pdfStreamAppendTo("% - - - PlotPDF options:");
String or = "portrait"; if(!pdfPortrait) {or = "landscape";}
String c = "black on white";
if(pdfColors == 1) {c = "colours";} else if(pdfColors == 2) {c = "colours selected in \"Spana\"";}
pdfStreamAppendTo("% size "+pdfSizeX+"/"+pdfSizeY+" %; left, bottom margins = "+pdfMarginL+", "+pdfMarginB+" cm"+nl+
"% "+c+"; "+or+"; font = "+FONTS[pdfFont]+nl+
"% - - - - Plot file Start - - - -");
// ----------------------------------------------------
int i0, i1, i2;
String s0, s1, s2;
String line;
String comment;
boolean readingText = false;
/** -1=Left 0=center +1=right */
int align = 0, alignDef = 0;
// ----- read all lines
while(true) {
try {line = bufReader.readLine();}
catch (java.io.IOException ex) {
msg = "while reading the plot file:"+nl+
" \""+pltFile.getAbsolutePath()+"\"";
exception(ex, msg, doNotStop);
break;
}
if(line == null) {break;}
// --- get i0, i1, i2 and any comment
if(line.length() > 0) {s0= line.substring(0,1).trim();} else {s0 = "";}
if(line.length() > 4) {s1= line.substring(1,5).trim();} else {s1 = "";}
if(line.length() > 8) {s2= line.substring(5,9).trim();} else {s2 = "";}
if(s0.length() > 0) {i0 = readInt(s0);} else {i0 = -1;}
if(s1.length() > 0) {i1 = readInt(s1);} else {i1 = 0;}
if(s2.length() > 0) {i2 = readInt(s2);} else {i2 = 0;}
if(line.length() > 9) {
comment= line.substring(9).trim();
if(i0 != 0 || (!comment.startsWith("TextBegin") && !readingText)) {
pdfStreamAppendTo("% "+comment);
}
if(comment.equals("TextEnd")) {readingText = false; continue;}
} else {comment = "";}
if(readingText) {continue;}
if(comment.equals("-- HEADING --")) {alignDef = -1;}
// --- change pen or colour
if(i0!=0 && i0!=1) {
if(i0==5 || i0==8) {setPen(i0,i1);}
continue;
}
// at this point either i0 = 0 or i0 = 1
// --- line drawing
if(pdfFont ==0
|| i0 == 1
|| !comment.startsWith("TextBegin")) {
moveOrDraw(i0,(double)i1,(double)i2);
continue;
}
// --- is there a text to print?
// at this point: diagrConvertFont >0,
// i0 =0, and comment.startsWith("TextBegin")
boolean isFormula = false;
double txtSize, txtAngle;
if(i0 == 0 && comment.length()>41 && comment.startsWith("TextBegin")) {
if (comment.substring(9,10).equals("C")) {isFormula=true;}
txtSize = readDouble(comment.substring(17,24));
txtAngle = readDouble(comment.substring(35,42));
// get alignment
if(comment.length() > 42) {
String t = comment.substring(55,56);
if(t.equalsIgnoreCase("L")) {align = -1;}
else if(t.equalsIgnoreCase("R")) {align = 1;}
else if(t.equalsIgnoreCase("C")) {align = 0;}
} else {align = alignDef;}
// the text is in next line
try{line = bufReader.readLine();}
catch(java.io.IOException ex) {
msg = "while reading the plot file:"+nl+
" \""+pltFile.getAbsolutePath()+"\"";
exception(ex, msg, doNotStop);
break;
}
if(line != null) {
if(line.length() > 9) {
comment= rTrim(line.substring(9));
if(comment.startsWith(" ")) {comment = comment.substring(1);}
} else {comment = "";}
// print the text
printText(i1,i2,comment,isFormula,align,txtSize,txtAngle);
} // if line != null
// ------ read all lines until "TextEnd"
readingText = true;
} // if "TextBegin"
} //while
// --- finished reading the input plot file: write pdfStream to object 22
writeObject22(outputFile);
// --- write cross-reference table
writeXref(outputFile);
} //convert2PDF
//<editor-fold defaultstate="collapsed" desc="getBufferedReader">
private static java.io.BufferedReader getBufferedReader(java.io.File f, boolean noStop) {
String msg;
java.io.BufferedReader bufReader;
java.io.InputStreamReader isr;
try{
isr = new java.io.InputStreamReader(new java.io.FileInputStream(f) , "UTF-8");
bufReader = new java.io.BufferedReader(isr);
}
catch (java.io.FileNotFoundException ex) {
msg = "File not found:"+nl+" \""+f.getAbsolutePath()+"\"";
exception(ex, msg, noStop);
return null;
} catch (java.io.UnsupportedEncodingException ex) {
msg = "while reading the plot file:"+nl+
" \""+f.getAbsolutePath()+"\"";
exception(ex, msg, noStop);
return null;
}
return bufReader;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="readInt(String)">
private static int readInt(String t) {
int i;
try{i = Integer.parseInt(t);}
catch (java.lang.NumberFormatException ex) {
System.out.println(DASH_LINE+nl+"Error: "+ex.toString()+nl+
" while reading an integer from String: \""+t+"\""+nl+DASH_LINE);
i = 0;}
return i;
} //readInt(T)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="readDouble(String)">
private static double readDouble(String t) {
double d;
try{d = Double.parseDouble(t);}
catch (java.lang.NullPointerException ex) {
System.out.println(DASH_LINE+nl+"Error: "+ex.toString()+nl+
" while reading an floating-point number from String: \""+t+"\""+nl+DASH_LINE);
d = 0;}
return d;
} //readDouble(T)
//</editor-fold>
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="pdf_Init">
/** write pdf-objects 1 to 21 (fonts, etc)*/
private void pdf_Init(java.io.BufferedWriter o) {
/**
* €‚ƒ„…†‡^‰Š‹ŒŽ‘’“”•–—~™š›œžŸ¤¦¨©ª¬®¯°±²³´μ·¹º¼½¾ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ
* ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ
*/
try {
o.write("%PDF-1.1"+nl+"% see objects 21 and 22 below"+nl);
// -- print the first objects
o.write("1 0 obj"+nl+"<<"+nl+"/Type /Outlines"+nl+"/Count 0"+nl+">>"+nl+"endobj"+nl);
o.write("2 0 obj"+nl+"<<"+nl+"/Type /Encoding"+nl+"/Differences ["+nl);
pdfStreamStart();
pdfStreamAppendTo("128 /euro");
pdfStreamAppendTo("130 /quotesinglbase");
pdfStreamAppendTo("131 /florin");
pdfStreamAppendTo("132 /quotedblbase");
pdfStreamAppendTo("133 /ellipsis");
pdfStreamAppendTo("134 /dagger");
pdfStreamAppendTo("135 /daggerdbl");
pdfStreamAppendTo("136 /circumflex");
pdfStreamAppendTo("137 /perthousand");
pdfStreamAppendTo("138 /Scaron");
pdfStreamAppendTo("139 /guilsinglleft");
pdfStreamAppendTo("140 /OE");
pdfStreamAppendTo("142 /Zcaron");
pdfStreamAppendTo("145 /quoteleft");
pdfStreamAppendTo("146 /quoteright");
pdfStreamAppendTo("147 /quotedblleft");
pdfStreamAppendTo("148 /quotedblright");
pdfStreamAppendTo("149 /bullet");
pdfStreamAppendTo("150 /endash");
pdfStreamAppendTo("151 /emdash");
pdfStreamAppendTo("152 /tilde");
pdfStreamAppendTo("153 /trademark");
pdfStreamAppendTo("154 /scaron");
pdfStreamAppendTo("155 /guilsinglright");
pdfStreamAppendTo("156 /oe");
pdfStreamAppendTo("158 /zcaron");
pdfStreamAppendTo("159 /Ydieresis");
pdfStreamAppendTo("160 /space");
pdfStreamAppendTo("164 /currency");
pdfStreamAppendTo("166 /brokenbar");
pdfStreamAppendTo("168 /dieresis");
pdfStreamAppendTo("169 /copyright");
pdfStreamAppendTo("170 /ordfeminine");
pdfStreamAppendTo("172 /logicalnot");
pdfStreamAppendTo("173 /hyphen");
pdfStreamAppendTo("174 /registered");
pdfStreamAppendTo("175 /macron");
pdfStreamAppendTo("176 /degree");
pdfStreamAppendTo("177 /plusminus");
pdfStreamAppendTo("178 /twosuperior");
pdfStreamAppendTo("179 /threesuperior");
pdfStreamAppendTo("180 /acute");
pdfStreamAppendTo("181 /mu");
pdfStreamAppendTo("183 /periodcentered");
pdfStreamAppendTo("184 /cedilla");
pdfStreamAppendTo("185 /onesuperior");
pdfStreamAppendTo("186 /ordmasculine");
pdfStreamAppendTo("188 /onequarter");
pdfStreamAppendTo("189 /onehalf");
pdfStreamAppendTo("190 /threequarters");
pdfStreamAppendTo("192 /Agrave");
pdfStreamAppendTo("193 /Aacute");
pdfStreamAppendTo("194 /Acircumflex");
pdfStreamAppendTo("195 /Atilde");
pdfStreamAppendTo("196 /Adieresis");
pdfStreamAppendTo("197 /Aring");
pdfStreamAppendTo("198 /AE");
pdfStreamAppendTo("199 /Ccedilla");
pdfStreamAppendTo("200 /Egrave");
pdfStreamAppendTo("201 /Eacute");
pdfStreamAppendTo("202 /Ecircumflex");
pdfStreamAppendTo("203 /Edieresis");
pdfStreamAppendTo("204 /Igrave");
pdfStreamAppendTo("205 /Iacute");
pdfStreamAppendTo("206 /Icircumflex");
pdfStreamAppendTo("207 /Idieresis");
pdfStreamAppendTo("208 /Eth");
pdfStreamAppendTo("209 /Ntilde");
pdfStreamAppendTo("210 /Ograve");
pdfStreamAppendTo("211 /Oacute");
pdfStreamAppendTo("212 /Ocircumflex");
pdfStreamAppendTo("213 /Otilde");
pdfStreamAppendTo("214 /Odieresis");
pdfStreamAppendTo("215 /multiply");
pdfStreamAppendTo("216 /Oslash");
pdfStreamAppendTo("217 /Ugrave");
pdfStreamAppendTo("218 /Uacute");
pdfStreamAppendTo("219 /Ucircumflex");
pdfStreamAppendTo("220 /Udieresis");
pdfStreamAppendTo("221 /Yacute");
pdfStreamAppendTo("222 /Thorn");
pdfStreamAppendTo("223 /germandbls");
pdfStreamAppendTo("224 /agrave");
pdfStreamAppendTo("225 /aacute");
pdfStreamAppendTo("226 /acircumflex");
pdfStreamAppendTo("227 /atilde");
pdfStreamAppendTo("228 /adieresis");
pdfStreamAppendTo("229 /aring");
pdfStreamAppendTo("230 /ae");
pdfStreamAppendTo("231 /ccedilla");
pdfStreamAppendTo("232 /egrave");
pdfStreamAppendTo("233 /eacute");
pdfStreamAppendTo("234 /ecircumflex");
pdfStreamAppendTo("235 /edieresis");
pdfStreamAppendTo("236 /igrave");
pdfStreamAppendTo("237 /iacute");
pdfStreamAppendTo("238 /icircumflex");
pdfStreamAppendTo("239 /idieresis");
pdfStreamAppendTo("240 /eth");
pdfStreamAppendTo("241 /ntilde");
pdfStreamAppendTo("242 /ograve");
pdfStreamAppendTo("243 /oacute");
pdfStreamAppendTo("244 /ocircumflex");
pdfStreamAppendTo("245 /otilde");
pdfStreamAppendTo("246 /odieresis");
pdfStreamAppendTo("247 /divide");
pdfStreamAppendTo("248 /oslash");
pdfStreamAppendTo("249 /ugrave");
pdfStreamAppendTo("250 /uacute");
pdfStreamAppendTo("251 /ucircumflex");
pdfStreamAppendTo("252 /udieresis");
pdfStreamAppendTo("253 /yacute");
pdfStreamAppendTo("254 /thorn");
pdfStreamAppendTo("255 /ydieresis");
pdfStreamPrint(o);
objBytesNoNewLine[2] = objBytesNoNewLine[2] + (int)pdfStreanSize;
o.write("]"+nl+">>"+nl+"endobj"+nl);
// --- fonts:
o.write("3 0 obj"+nl+"<<"+nl+"/Type /Font"+nl+"/Subtype /Type1"+nl+
"/Name /F0"+nl+"/BaseFont /Courier"+nl+"/Encoding 2 0 R"+nl+">>"+nl+"endobj"+nl);
o.write("4 0 obj"+nl+"<<"+nl+"/Type /Font"+nl+"/Subtype /Type1"+nl+
"/Name /F1"+nl+"/BaseFont /Courier-Bold"+nl+"/Encoding 2 0 R"+nl+">>"+nl+"endobj"+nl);
o.write("5 0 obj"+nl+"<<"+nl+"/Type /Font"+nl+"/Subtype /Type1"+nl+
"/Name /F2"+nl+"/BaseFont /Courier-Oblique"+nl+"/Encoding 2 0 R"+nl+">>"+nl+"endobj"+nl);
o.write("6 0 obj"+nl+"<<"+nl+"/Type /Font"+nl+"/Subtype /Type1"+nl+
"/Name /F3"+nl+"/BaseFont /Courier-BoldOblique"+nl+"/Encoding 2 0 R"+nl+">>"+nl+"endobj"+nl);
o.write("7 0 obj"+nl+"<<"+nl+"/Type /Font"+nl+"/Subtype /Type1"+nl+
"/Name /F4"+nl+"/BaseFont /Helvetica"+nl+"/Encoding 2 0 R"+nl+">>"+nl+"endobj"+nl);
o.write("8 0 obj"+nl+"<<"+nl+"/Type /Font"+nl+"/Subtype /Type1"+nl+
"/Name /F5"+nl+"/BaseFont /Helvetica-Bold"+nl+"/Encoding 2 0 R"+nl+">>"+nl+"endobj"+nl);
o.write("9 0 obj"+nl+"<<"+nl+"/Type /Font"+nl+"/Subtype /Type1"+nl+
"/Name /F6"+nl+"/BaseFont /Helvetica-Oblique"+nl+"/Encoding 2 0 R"+nl+">>"+nl+"endobj"+nl);
o.write("10 0 obj"+nl+"<<"+nl+"/Type /Font"+nl+"/Subtype /Type1"+nl+
"/Name /F7"+nl+"/BaseFont /Helvetica-BoldOblique"+nl+"/Encoding 2 0 R"+nl+">>"+nl+"endobj"+nl);
o.write("11 0 obj"+nl+"<<"+nl+"/Type /Font"+nl+"/Subtype /Type1"+nl+
"/Name /F8"+nl+"/BaseFont /Symbol"+nl+">>"+nl+"endobj"+nl);
o.write("12 0 obj"+nl+"<<"+nl+"/Type /Font"+nl+"/Subtype /Type1"+nl+
"/Name /F9"+nl+"/BaseFont /Times-Roman"+nl+"/Encoding 2 0 R"+nl+">>"+nl+"endobj"+nl);
o.write("13 0 obj"+nl+"<<"+nl+"/Type /Font"+nl+"/Subtype /Type1"+nl+
"/Name /F10"+nl+"/BaseFont /Times-Bold"+nl+"/Encoding 2 0 R"+nl+">>"+nl+"endobj"+nl);
o.write("14 0 obj"+nl+"<<"+nl+"/Type /Font"+nl+"/Subtype /Type1"+nl+
"/Name /F11"+nl+"/BaseFont /Times-Italic"+nl+"/Encoding 2 0 R"+nl+">>"+nl+"endobj"+nl);
o.write("15 0 obj"+nl+"<<"+nl+"/Type /Font"+nl+"/Subtype /Type1"+nl+
"/Name /F12"+nl+"/BaseFont /Times-BoldItalic"+nl+"/Encoding 2 0 R"+nl+">>"+nl+"endobj"+nl);
o.write("16 0 obj"+nl+"<<"+nl+"/Type /Font"+nl+"/Subtype /Type1"+nl+
"/Name /F13"+nl+"/BaseFont /ZapfDingbats"+nl+">>"+nl+"endobj"+nl);
o.write("17 0 obj"+nl+"<<"+nl+"/Type /Catalog"+nl+
"/Pages 19 0 R"+nl+"/Outlines 1 0 R"+nl+">>"+nl+"endobj"+nl);
o.write("18 0 obj"+nl+"<<"+nl+"/ProcSet [ /PDF /Text ]"+nl+"/Font <<"+nl+
"/F0 3 0 R"+nl+"/F1 4 0 R"+nl+"/F2 5 0 R"+nl+"/F3 6 0 R"+nl+"/F4 7 0 R"+nl+"/F5 8 0 R"+nl+"/F6 9 0 R"+nl+
"/F7 10 0 R"+nl+"/F8 11 0 R"+nl+"/F9 12 0 R"+nl+"/F10 13 0 R"+nl+"/F11 14 0 R"+nl+"/F12 15 0 R"+nl+"/F13 16 0 R"+nl+
">>"+nl+">>"+nl+"endobj"+nl);
//MediaBox [0 0 593 792]
o.write("19 0 obj"+nl+"<<"+nl+"/Type /Pages"+nl+"/Count 1"+nl+
"/Kids [ 20 0 R ] "+nl+"/MediaBox [0 0 "+(int)MediaBox_X+" "+(int)MediaBox_Y+"]"+nl+
"/Resources 18 0 R"+nl+">>"+nl+"endobj"+nl);
o.write("20 0 obj"+nl+"<<"+nl+"/Type /Page"+nl+"/Parent 19 0 R"+nl+
"/Contents 22 0 R"+nl+"/Resources 18 0 R"+nl+">>"+nl+"endobj"+nl);
pdfStreamStart(); // this is not a "stream", but we want to count the bytes
o.write("21 0 obj"+nl+"<<"+nl+
"/CreationDate (D:"+pdfDate()+")"+nl);
pdfStreamAppendTo(
"/Producer (Plot-pdf [java] by I.Puigdomenech "+VERS+")"+nl+
"/Author ("+fixTextSimple(System.getProperty("user.name", "anonymous"),false)+")"+nl+
"/Title ("+fixTextSimple(maybeInQuotes(pltFile.getName()),false)+")");
pdfStreamPrint(o);
objBytesNoNewLine[21] = objBytesNoNewLine[21] + (int)pdfStreanSize;
o.write(">>"+nl+"endobj"+nl);
o.flush();
} catch (java.io.IOException ex) {
exception(ex, null, doNotStop);
delete = true;
}
}
/** get the date in pdf-format: 20120808115058 (length = 14) */
private String pdfDate() {
java.text.DateFormat df = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
java.util.Date now = new java.util.Date();
return df.format(now);
}
/** get the date and time in default format */
private String getDateTime() {
java.text.DateFormat df = java.text.DateFormat.getDateTimeInstance
(java.text.DateFormat.DEFAULT, java.text.DateFormat.DEFAULT,
java.util.Locale.getDefault());
java.util.Date now = new java.util.Date();
return df.format(now);
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="writeObject22">
/** write pdfStream. */
private void writeObject22(java.io.BufferedWriter o) {
if(startedPrintingText) { // end printing text if needed
pdfStreamAppendTo("ET");
startedPrintingText = false;
}
if(newPath == 2) { // stroke the graphic path if needed
if(Math.abs(x1st-xNow)<0.01 && Math.abs(y1st-yNow)<0.01) {
pdfStreamAppendTo("s");
} else {
pdfStreamAppendTo("S");
}
newPath = 0;
x1st = -Double.MAX_VALUE; y1st = -Double.MAX_VALUE;
}
pdfStreamAppendTo("% - - - - Plot file End - - - -");
String pdfStreamSizeTxt = Long.toString(pdfStreanSize).trim();
pdfStreamSizeTxtLength = pdfStreamSizeTxt.length();
try{
o.flush();
o.write("22 0 obj"+nl+"<<"+nl+"/Length "+pdfStreamSizeTxt+nl+">>"+nl+
"% If you make changes in the \"stream\" you must also change:"+nl+
"% - In the the trailer, the line below the keyword \"startxref\":"+nl+
"% update the byte offset from the beginning of the file to the"+nl+
"% beginning of the \"xref\" keyword."+nl+
"% - Update above the byte length of the \"stream\", including ends-of-line"+nl+
"stream"+nl);
o.write(pdfStream.toString());
o.write("endstream"+nl+"endobj"+nl);
} catch (java.io.IOException ex) {exception(ex, null, doNotStop); delete = true;}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="writeXref">
/** write the cross-reference table to output. */
private void writeXref(java.io.BufferedWriter o) {
String msg;
if(pdfStreanSize <= 0) {
msg = "Programming error in \"writeXref\": pdfStreanSize <= 0.";
if(doNotStop) {System.out.println(msg);} else {ErrMsgBx mb = new ErrMsgBx(msg,progName);}
return;
}
long[] objStart = new long[22];
long lng = 0;
for(int i = 0; i < NBR_PDF_OBJECTS; i++) {
lng = lng + (long)(objBytesNoNewLine[i] + (objNbrNewLines[i] * nlL));
objStart[i] = lng;
}
try{
o.flush();
o.write("xref"+nl+"0 23"+nl+"0000000000 65535 f"+nl);
String objStartTxt;
for(int i = 0; i < NBR_PDF_OBJECTS; i++) {
objStartTxt = String.format("%010d", objStart[i]);
o.write(objStartTxt+" 00000 n");
if(nlL ==1) {o.write(" ");}
o.write(nl);
}
long xrefStart = objStart[NBR_PDF_OBJECTS-1]
+ 18 +(2*nlL) + pdfStreamSizeTxtLength + nlL
+302 +(7*nlL) + pdfStreanSize + 15 + (2*nlL);
o.write("trailer"+nl+"<<"+nl+"/Size 23"+nl+
"/Info 21 0 R"+nl+"/Root 17 0 R"+nl+">>"+nl+
"startxref"+nl+xrefStart+nl+"%%EOF"+nl);
o.flush();
} catch (java.io.IOException ex) {
exception(ex, null, doNotStop);
delete = true;
}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="pdfStream">
private StringBuffer pdfStream = new StringBuffer();
private long pdfStreanSize = 0;
private int pdfStreamSizeTxtLength;
private synchronized void pdfStreamStart() {
pdfStream.delete(0, pdfStream.length());
pdfStreanSize = 0;
}
private synchronized void pdfStreamAppendTo(String t) {
if(t == null || t.length() <=0) {return;}
byte[] encodedBytes;
try{
encodedBytes = t.getBytes("ISO-8859-1");
pdfStreanSize = pdfStreanSize + encodedBytes.length;
pdfStream.append(t);
} catch (java.io.UnsupportedEncodingException ex) {
exception(ex, "while encoding to ISO-Latin-1 the text \""+t+"\"", doNotStop);
delete = true;
}
// add end-of-line
pdfStreanSize = pdfStreanSize + nlL;
pdfStream.append(nl);
}
private void pdfStreamPrint(java.io.BufferedWriter o) {
try{
o.write(pdfStream.toString());
o.flush();
} catch (java.io.IOException ex) {
exception(ex, "while writing \""+pdfStream.toString()+"\"", doNotStop);
delete = true;
}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="setPalette">
/** Set the values in "colours[]" depending on diagrConvertColors.
* if diagrConvertColors = 2, then the palete selected in "Spana" is used,
* if found. */
private void setPalette() {
if(pdfColors == 2) { // "Spana" palette
java.io.FileInputStream fis = null;
java.io.File f = null;
boolean ok = false;
while (true) { // if "Spana" palette not found: break
java.util.Properties propertiesIni = new java.util.Properties();
f = getSpana_Ini();
if(f == null) {
System.out.println("Warning: could not find file \".Spana.ini\""+nl+
"default colours will be used.");
break;
}
try {
fis = new java.io.FileInputStream(f);
propertiesIni.load(fis);
} //try
catch (java.io.FileNotFoundException e) {
System.out.println("Warning: file Not found: \""+f.getPath()+"\""+nl+
"default colours will be used.");
break;
} //catch FileNotFoundException
catch (java.io.IOException e) {
System.out.println("Error: \""+e.toString()+"\""+nl+
" while loading file:"+nl+
" \""+f.getPath()+"\""+nl+
"default colours will be used.");
break;
} // catch loading-exception
if(dbg) {System.out.println("Reading colours from \""+f.getPath()+"\".");}
int red, green, blue;
float r, g, b;
String rt, gt, bt;
try{
for(int ii=0; ii < colours.length; ii++) {
String[] c = propertiesIni.getProperty("Disp_Colour["+ii+"]").split(",");
if(c.length >0) {red =Integer.parseInt(c[0]);} else {red=0;}
if(c.length >1) {green =Integer.parseInt(c[1]);} else {green=0;}
if(c.length >2) {blue =Integer.parseInt(c[2]);} else {blue=0;}
r = Math.max(0f, Math.min(1f, (float)Math.max(0, Math.min(255, red))/255f));
g = Math.max(0f, Math.min(1f, (float)Math.max(0, Math.min(255, green))/255f));
b = Math.max(0f, Math.min(1f, (float)Math.max(0, Math.min(255, blue))/255f));
if(r < 0.000001) {rt ="0";} else if(r > 0.999999) {rt ="1";} else {rt = String.valueOf(r);}
if(g < 0.000001) {gt ="0";} else if(g > 0.999999) {gt ="1";} else {gt = String.valueOf(g);}
if(b < 0.000001) {bt ="0";} else if(b > 0.999999) {bt ="1";} else {bt = String.valueOf(b);}
colours[ii] = (rt+" "+gt+" "+bt).trim();
} //for ii
} catch (java.lang.NumberFormatException e) {
System.out.println("Error: \""+e.toString()+"\""+nl+
" while loading file:"+nl+
" \""+f.getPath()+"\""+nl+
"default colours will be used.");
break;
}
ok = true;
break;
} //while
if(!ok) {pdfColors = 1;} // use the standard colours instead
try{if(fis != null) {fis.close();}}
catch (java.io.IOException e) {
String msg = "Error: "+e.toString();
if(f != null) {msg = msg +nl+"while closing \""+f.getPath()+"\"";}
else {msg = msg+nl+"while closing \"null\"";}
System.out.println(msg);
}
}
if(pdfColors <=0 || pdfColors >2) {
for(int i =0; i < colours.length; i++) {
colours[i] = "0 0 0"; //Black
}
return;
}
if(pdfColors == 1) { // standard palette
colours[0] = "0 0 0"; //Black
colours[1] = "1 0 0"; //light Red
colours[2] = "0.5843 0.2627 0"; //Vermilion
colours[3] = "0 0 1"; //Blue
colours[4] = "0 0.502 0"; //Green
colours[5] = "0.7843 0.549 0"; //Orange
colours[6] = "1 0 1"; //Magenta
colours[7] = "0 0 0.502"; //dark Blue
colours[8] = "0.502 0.502 0.502";//Gray
colours[9] = "0 0.651 1"; //Sky Blue
colours[10]= "0.502 0 1"; //Violet
}
if(dbg) {
System.out.println("Colours in use;");
for(int ii=0; ii < colours.length; ii++) {
System.out.println(" colour["+ii+"] = \""+colours[ii]+"\"");
}
}
} // setPalette()
private java.io.File getSpana_Ini() {
java.io.File p;
boolean ok;
java.util.ArrayList<String> dirs = new java.util.ArrayList<String>(6);
String home = getPathApp();
if(home != null && home.trim().length() >0) {
p = new java.io.File(home);
if(p.exists()) {dirs.add(p.getAbsolutePath());}
}
String homeDrv = System.getenv("HOMEDRIVE");
String homePath = System.getenv("HOMEPATH");
if(homeDrv != null && homeDrv.trim().length() >0 && homeDrv.endsWith(SLASH)) {
homeDrv = homeDrv.substring(0, homeDrv.length()-1);
}
if(homePath != null && homePath.trim().length() >0 && !homePath.startsWith(SLASH)) {
homePath = SLASH + homePath;
}
if((homeDrv != null && homeDrv.trim().length() >0)
&& (homePath != null && homePath.trim().length() >0)) {
if(homePath.endsWith(SLASH)) {homePath = homePath.substring(0, homePath.length()-1);}
p = new java.io.File(homeDrv+homePath+SLASH+".config"+SLASH+"eq-diagr");
if(p.exists()) {dirs.add(p.getAbsolutePath());}
}
home = System.getenv("HOME");
if(home != null && home.trim().length() >0) {
if(home.endsWith(SLASH)) {home = home.substring(0, home.length()-1);}
p = new java.io.File(home+SLASH+".config"+SLASH+"eq-diagr");
if(p.exists()) {dirs.add(p.getAbsolutePath());}
}
home = System.getProperty("user.home");
if(home != null && home.trim().length() >0) {
if(home.endsWith(SLASH)) {home = home.substring(0, home.length()-1);}
p = new java.io.File(home+SLASH+".config"+SLASH+"eq-diagr");
if(p.exists()) {dirs.add(p.getAbsolutePath());}
}
java.io.File f = null;
for(String t : dirs) {
if(t.endsWith(SLASH)) {t = t.substring(0, t.length()-1);}
final String fileINIname = ".Spana.ini";
p = new java.io.File(t+SLASH+fileINIname);
if(p.exists() && p.canRead()) {
if(f != null && p.lastModified() > f.lastModified()) {f = p;}
}
} // for(dirs)
return f;
} // getSpana_Ini()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="setPen">
/** Emulates several pens with line width or colours.
* In black on white mode: if i=8 then the line thickness is changed,
* if i=5 nothing happens.
* In colour mode: if i=5 then the line colour is changed
* (gray scale in non-colour printers), if i=8 nothing happens
* @param i either 5 (change screen colour) or 8 (chenage plotter pen number)
* @param pen0 the colour/pen nbr */
private void setPen(int i, int pen0) {
if(i != 5 && i != 8) {return;}
int pen = Math.max(1, pen0);
pen--;
if(i == 5) { // Screen Colour
if(pdfColors <=0) { //black/white
colorNow = 0;
return;
}
while(pen >= colours.length) {
pen = pen - colours.length;
}
if(pen < 0) {pen = colours.length - pen;}
colorNow = pen;
}
if(i == 8) { // Pen Thickness
while(pen >= WIDTHS.length) {
pen = pen - WIDTHS.length;
}
if(pen < 0) {pen = WIDTHS.length - pen;}
penNow = pen;
}
} //setPen
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="moveOrDraw">
private void moveOrDraw (int i0, double x0, double y0) {
if(startedPrintingText) { // end printing text if needed
pdfStreamAppendTo("ET");
startedPrintingText = false;
}
// --- newPath: -1 = start of program;
// 0 = no drawing performed yet
// 1 = some move performed
// 2 = some move/line-draw performed
if(newPath < 0) {newPath = 0;}
double x, y, xPdf, yPdf, w;
x = (x0*scaleX + zx) * SCALE_USER_SPACE;
y = (y0*scaleY + zy) * SCALE_USER_SPACE;
//---- move-to: if a drawing has been done: stroke and newpath.
// if i0=0 do not output anything, only save position.
// if i0=-1 force a move-to (for example, before a text-output)
if(i0 == 0) {
// drawing done?
if(newPath == 2) {
if(Math.abs(x1st-xNow)<0.01 && Math.abs(y1st-yNow)<0.01) {
pdfStreamAppendTo("s");
} else {
pdfStreamAppendTo("S");
}
newPath = 0;
}
x1st = -Double.MAX_VALUE; y1st = -Double.MAX_VALUE;
} //move to
else if(i0 == 1) {
//---- draw-to: if necessary do a move-to, then a line-to
//line-draw after a 'move', 1st go to last point: xNow/yNow
if(newPath ==0) {
pdfStreamAppendTo(colours[colorNow]+" RG");
w = WIDTHS[penNow] * (scaleX+scaleY)/2;
w = Math.min(100,Math.max(0.05,w)) * SCALE_USER_SPACE;
pdfStreamAppendTo(String.format(engl,"%20.5f",w).trim()+" w");
//pdfStream.append("0 J"+nl); // lineCap = square
//pdfStream.append("1 j"+nl); // lineJoin = round
//pdfStream.append("[ ] 0 d"+nl); // lineDash = no dash solid pattern
pdfStreamAppendTo("0 J 1 j [ ] 0 d");
xPdf = xNow; yPdf = yNow;
if(pdfPortrait) {
xPdf = xPdf + MARGIN_X;
} else { // landscape
xPdf = MediaBox_X - yNow;
yPdf = xNow;
xPdf = xPdf - MARGIN_X;
}
yPdf = yPdf + MARGIN_Y;
pdfStreamAppendTo(toStr(xPdf)+" "+toStr(yPdf)+" m");
newPath = 1;
x1st = xNow; y1st = yNow;
} //if newPath =0
xPdf = x; yPdf = y;
if(pdfPortrait) {
xPdf = xPdf + MARGIN_X;
} else { //landscape
xPdf = MediaBox_X - y;
yPdf = x;
xPdf = xPdf - MARGIN_X;
}
yPdf = yPdf + MARGIN_Y;
pdfStreamAppendTo(toStr(xPdf)+" "+toStr(yPdf)+" l");
newPath = 2;
} //draw to
xNow = x;
yNow = y;
} // moveOrDraw
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="toStr(double)">
/** Write a double into a string. If possible, write it
* without the decimal point: 3.1 returns "3.1", while 3.0
* returns "3"
* @param d
* @return */
private static String toStr(double d) {
if(Double.isNaN(d)) {d = 0;}
d = Math.min(999999999999999.9d,Math.max(-999999999999999.9d,d));
String dTxt;
if(Math.abs(d-Math.round(d)) >0.001) {
dTxt = String.format(engl,"%20.3f", d);
} else {dTxt = Long.toString(Math.round(d));}
return dTxt.trim();
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="fixTextSimple">
/** Escape parenthesis and back-slash (that is, change "(" to "\(", etc);
* and change hyphen, "-", to endash.
* @param txt
* @param isFormula
* @return */
private String fixTextSimple(String txt, boolean isFormula) {
if(txt == null || txt.trim().length() <=0) {return txt;}
/**
* €γερΣΔ‚ƒ„…†‡^‰Š‹ŒŽ‘’“”•–—~™š›œžŸ¤¦¨©ª¬®¯°±²³´μ·¹º¼½¾ÀÁÂÃÄÅÆÇÈÉÊË
* ÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ
*/
StringBuilder t = new StringBuilder(txt);
int i = 0;
while(i < t.length()) {
// "\" change to "\\"
if(t.charAt(i) == '\\') {t.replace(i, i+1, "\\\\"); i++;}
else if(t.charAt(i) == '(') {t.replace(i, i+1, "\\("); i++;}
else if(t.charAt(i) == ')') {t.replace(i, i+1, "\\)"); i++;}
// for hyphen and minus sign
else if(t.charAt(i) == '-' || t.charAt(i) == '−') {t.replace(i, i+1, "\\226"); i = i+3;} //endash (150 dec = 226 octal)
// when it is a "formula" then tilde is 'degree sign' and circumflex is 'Delta'
else if(t.charAt(i) == '~' && !isFormula) {t.replace(i, i+1, "\\230"); i = i+3;} //tilde (152 dec)
else if(t.charAt(i) == '^' && !isFormula) {t.replace(i, i+1, "\\210"); i = i+3;} //circumflex (136 dec)
else if(t.charAt(i) == '×') {t.replace(i, i+1, "\\327"); i = i+3;} //multiply (215 dec)
else if(t.charAt(i) == '€') {t.replace(i, i+1, "\\200"); i = i+3;} //euro (128 dec)
else if(t.charAt(i) == '‚') {t.replace(i, i+1, "\\202"); i = i+3;} //quotesinglbase (130 dec)
else if(t.charAt(i) == 'ƒ') {t.replace(i, i+1, "\\203"); i = i+3;} //florin (131 dec)
else if(t.charAt(i) == '„') {t.replace(i, i+1, "\\204"); i = i+3;} //quotedblbase (132 dec)
else if(t.charAt(i) == '…') {t.replace(i, i+1, "\\205"); i = i+3;} //ellipsis (133 dec)
else if(t.charAt(i) == '†') {t.replace(i, i+1, "\\206"); i = i+3;} //dagger (134 dec)
else if(t.charAt(i) == '‡') {t.replace(i, i+1, "\\207"); i = i+3;} //daggerdbl (135 dec)
else if(t.charAt(i) == '‰') {t.replace(i, i+1, "\\211"); i = i+3;} //perthousand (137 dec)
else if(t.charAt(i) == 'Š') {t.replace(i, i+1, "\\212"); i = i+3;} //Scaron (138 dec)
else if(t.charAt(i) == '‹') {t.replace(i, i+1, "\\213"); i = i+3;} //guilsinglleft (139 dec)
else if(t.charAt(i) == 'Œ') {t.replace(i, i+1, "\\214"); i = i+3;} //OE (140 dec)
else if(t.charAt(i) == 'Ž') {t.replace(i, i+1, "\\216"); i = i+3;} //Zcaron (142 dec)
else if(t.charAt(i) == '‘') {t.replace(i, i+1, "\\221"); i = i+3;} //quoteleft (145 dec)
else if(t.charAt(i) == '’') {t.replace(i, i+1, "\\222"); i = i+3;} //quoteright (146 dec)
else if(t.charAt(i) == '“') {t.replace(i, i+1, "\\223"); i = i+3;} //quotedblleft (147 dec)
else if(t.charAt(i) == '”') {t.replace(i, i+1, "\\224"); i = i+3;} //quotedblright (148 dec)
else if(t.charAt(i) == '•') {t.replace(i, i+1, "\\225"); i = i+3;} //bullet (149 dec)
else if(t.charAt(i) == '–') {t.replace(i, i+1, "\\226"); i = i+3;} //endash (150 dec)
else if(t.charAt(i) == '—') {t.replace(i, i+1, "\\227"); i = i+3;} //emdash (151 dec)
else if(t.charAt(i) == '™') {t.replace(i, i+1, "\\231"); i = i+3;} //trademark (153 dec)
else if(t.charAt(i) == 'š') {t.replace(i, i+1, "\\232"); i = i+3;} //scaron (154 dec)
else if(t.charAt(i) == '›') {t.replace(i, i+1, "\\233"); i = i+3;} //guilsinglright (155 dec)
else if(t.charAt(i) == 'œ') {t.replace(i, i+1, "\\234"); i = i+3;} //oe (156 dec)
else if(t.charAt(i) == 'ž') {t.replace(i, i+1, "\\236"); i = i+3;} //zcaron (158 dec)
else if(t.charAt(i) == 'Ÿ') {t.replace(i, i+1, "\\237"); i = i+3;} //Ydieresis (159 dec)
else if(t.charAt(i) == '¤') {t.replace(i, i+1, "\\244"); i = i+3;} //currency (164 dec)
else if(t.charAt(i) == '¦') {t.replace(i, i+1, "\\246"); i = i+3;} //brokenbar (166 dec)
else if(t.charAt(i) == '¨') {t.replace(i, i+1, "\\250"); i = i+3;} //dieresis (168 dec)
else if(t.charAt(i) == '©') {t.replace(i, i+1, "\\251"); i = i+3;} //copyright (169 dec)
else if(t.charAt(i) == 'ª') {t.replace(i, i+1, "\\252"); i = i+3;} //ordfeminine (170 dec)
else if(t.charAt(i) == '¬') {t.replace(i, i+1, "\\254"); i = i+3;} //logicalnot (172 dec)
else if(t.charAt(i) == '®') {t.replace(i, i+1, "\\256"); i = i+3;} //registered (174 dec)
else if(t.charAt(i) == '¯') {t.replace(i, i+1, "\\257"); i = i+3;} //macron (175 dec)
else if(t.charAt(i) == '°') {t.replace(i, i+1, "\\260"); i = i+3;} //degree (176 dec)
else if(t.charAt(i) == '±') {t.replace(i, i+1, "\\261"); i = i+3;} //plusminus (177 dec)
else if(t.charAt(i) == '²') {t.replace(i, i+1, "\\262"); i = i+3;} //twosuperior (178 dec)
else if(t.charAt(i) == '³') {t.replace(i, i+1, "\\263"); i = i+3;} //threesuperior (179 dec)
else if(t.charAt(i) == '´') {t.replace(i, i+1, "\\264"); i = i+3;} //acute (180 dec)
else if(t.charAt(i) == 'μ') {t.replace(i, i+1, "\\265"); i = i+3;} //mu (181 dec)
else if(t.charAt(i) == '·') {t.replace(i, i+1, "\\267"); i = i+3;} //periodcentered (183 dec)
else if(t.charAt(i) == '¹') {t.replace(i, i+1, "\\271"); i = i+3;} //onesuperior (185 dec)
else if(t.charAt(i) == 'º') {t.replace(i, i+1, "\\272"); i = i+3;} //ordmasculine (186 dec)
else if(t.charAt(i) == '¼') {t.replace(i, i+1, "\\274"); i = i+3;} //onequarter (188 dec)
else if(t.charAt(i) == '½') {t.replace(i, i+1, "\\275"); i = i+3;} //onehalf (189 dec)
else if(t.charAt(i) == '¾') {t.replace(i, i+1, "\\276"); i = i+3;} //threequarters (190 dec)
else if(t.charAt(i) == 'À') {t.replace(i, i+1, "\\300"); i = i+3;} //Agrave (192 dec)
else if(t.charAt(i) == 'Á') {t.replace(i, i+1, "\\301"); i = i+3;} //Aacute (193 dec)
else if(t.charAt(i) == 'Â') {t.replace(i, i+1, "\\302"); i = i+3;} //Acircumflex (194 dec)
else if(t.charAt(i) == 'Ã') {t.replace(i, i+1, "\\303"); i = i+3;} //Atilde (195 dec)
else if(t.charAt(i) == 'Ä') {t.replace(i, i+1, "\\304"); i = i+3;} //Adieresis (196 dec)
else if(t.charAt(i) == 'Å') {t.replace(i, i+1, "\\305"); i = i+3;} //Aring (197 dec)
else if(t.charAt(i) == 'Æ') {t.replace(i, i+1, "\\306"); i = i+3;} //AE (198 dec)
else if(t.charAt(i) == 'Ç') {t.replace(i, i+1, "\\307"); i = i+3;} //Ccedilla (199 dec)
else if(t.charAt(i) == 'È') {t.replace(i, i+1, "\\310"); i = i+3;} //Egrave (200 dec)
else if(t.charAt(i) == 'É') {t.replace(i, i+1, "\\311"); i = i+3;} //Eacute (201 dec)
else if(t.charAt(i) == 'Ê') {t.replace(i, i+1, "\\312"); i = i+3;} //Ecircumflex (202 dec)
else if(t.charAt(i) == 'Ë') {t.replace(i, i+1, "\\313"); i = i+3;} //Edieresis (203 dec)
else if(t.charAt(i) == 'Ì') {t.replace(i, i+1, "\\314"); i = i+3;} //Igrave (204 dec)
else if(t.charAt(i) == 'Í') {t.replace(i, i+1, "\\315"); i = i+3;} //Iacute (205 dec)
else if(t.charAt(i) == 'Î') {t.replace(i, i+1, "\\316"); i = i+3;} //Icircumflex (206 dec)
else if(t.charAt(i) == 'Ï') {t.replace(i, i+1, "\\317"); i = i+3;} //Idieresis (207 dec)
else if(t.charAt(i) == 'Ð') {t.replace(i, i+1, "\\320"); i = i+3;} //Eth (208 dec)
else if(t.charAt(i) == 'Ñ') {t.replace(i, i+1, "\\321"); i = i+3;} //Ntilde (209 dec)
else if(t.charAt(i) == 'Ò') {t.replace(i, i+1, "\\322"); i = i+3;} //Ograve (210 dec)
else if(t.charAt(i) == 'Ó') {t.replace(i, i+1, "\\323"); i = i+3;} //Oacute (211 dec)
else if(t.charAt(i) == 'Ô') {t.replace(i, i+1, "\\324"); i = i+3;} //Ocircumflex (212 dec)
else if(t.charAt(i) == 'Õ') {t.replace(i, i+1, "\\325"); i = i+3;} //Otilde (213 dec)
else if(t.charAt(i) == 'Ö') {t.replace(i, i+1, "\\326"); i = i+3;} //Odieresis (214 dec)
else if(t.charAt(i) == 'Ø') {t.replace(i, i+1, "\\330"); i = i+3;} //Oslash (216 dec)
else if(t.charAt(i) == 'Ù') {t.replace(i, i+1, "\\331"); i = i+3;} //Ugrave (217 dec)
else if(t.charAt(i) == 'Ú') {t.replace(i, i+1, "\\332"); i = i+3;} //Uacute (218 dec)
else if(t.charAt(i) == 'Û') {t.replace(i, i+1, "\\333"); i = i+3;} //Ucircumflex (219 dec)
else if(t.charAt(i) == 'Ü') {t.replace(i, i+1, "\\334"); i = i+3;} //Udieresis (220 dec)
else if(t.charAt(i) == 'Ý') {t.replace(i, i+1, "\\335"); i = i+3;} //Yacute (221 dec)
else if(t.charAt(i) == 'Þ') {t.replace(i, i+1, "\\336"); i = i+3;} //Thorn (222 dec)
else if(t.charAt(i) == 'ß') {t.replace(i, i+1, "\\337"); i = i+3;} //germandbls (223 dec)
else if(t.charAt(i) == 'à') {t.replace(i, i+1, "\\340"); i = i+3;} //agrave (224 dec)
else if(t.charAt(i) == 'á') {t.replace(i, i+1, "\\341"); i = i+3;} //aacute (225 dec)
else if(t.charAt(i) == 'â') {t.replace(i, i+1, "\\342"); i = i+3;} //acircumflex (226 dec)
else if(t.charAt(i) == 'ã') {t.replace(i, i+1, "\\343"); i = i+3;} //atilde (227 dec)
else if(t.charAt(i) == 'ä') {t.replace(i, i+1, "\\344"); i = i+3;} //adieresis (228 dec)
else if(t.charAt(i) == 'å') {t.replace(i, i+1, "\\345"); i = i+3;} //aring (229 dec)
else if(t.charAt(i) == 'æ') {t.replace(i, i+1, "\\346"); i = i+3;} //ae (230 dec)
else if(t.charAt(i) == 'ç') {t.replace(i, i+1, "\\347"); i = i+3;} //ccedilla (231 dec)
else if(t.charAt(i) == 'è') {t.replace(i, i+1, "\\350"); i = i+3;} //egrave (232 dec)
else if(t.charAt(i) == 'é') {t.replace(i, i+1, "\\351"); i = i+3;} //eacute (233 dec)
else if(t.charAt(i) == 'ê') {t.replace(i, i+1, "\\352"); i = i+3;} //ecircumflex (234 dec)
else if(t.charAt(i) == 'ë') {t.replace(i, i+1, "\\353"); i = i+3;} //edieresis (235 dec)
else if(t.charAt(i) == 'ì') {t.replace(i, i+1, "\\354"); i = i+3;} //igrave (236 dec)
else if(t.charAt(i) == 'í') {t.replace(i, i+1, "\\355"); i = i+3;} //iacute (237 dec)
else if(t.charAt(i) == 'î') {t.replace(i, i+1, "\\356"); i = i+3;} //icircumflex (238 dec)
else if(t.charAt(i) == 'ï') {t.replace(i, i+1, "\\357"); i = i+3;} //idieresis (239 dec)
else if(t.charAt(i) == 'ð') {t.replace(i, i+1, "\\360"); i = i+3;} //eth (240 dec)
else if(t.charAt(i) == 'ñ') {t.replace(i, i+1, "\\361"); i = i+3;} //ntilde (241 dec)
else if(t.charAt(i) == 'ò') {t.replace(i, i+1, "\\362"); i = i+3;} //ograve (242 dec)
else if(t.charAt(i) == 'ó') {t.replace(i, i+1, "\\363"); i = i+3;} //oacute (243 dec)
else if(t.charAt(i) == 'ô') {t.replace(i, i+1, "\\364"); i = i+3;} //ocircumflex (244 dec)
else if(t.charAt(i) == 'õ') {t.replace(i, i+1, "\\365"); i = i+3;} //otilde (245 dec)
else if(t.charAt(i) == 'ö') {t.replace(i, i+1, "\\366"); i = i+3;} //odieresis (246 dec)
else if(t.charAt(i) == '÷') {t.replace(i, i+1, "\\367"); i = i+3;} //divide (247 dec)
else if(t.charAt(i) == 'ø') {t.replace(i, i+1, "\\370"); i = i+3;} //oslash (248 dec)
else if(t.charAt(i) == 'ù') {t.replace(i, i+1, "\\371"); i = i+3;} //ugrave (249 dec)
else if(t.charAt(i) == 'ú') {t.replace(i, i+1, "\\372"); i = i+3;} //uacute (250 dec)
else if(t.charAt(i) == 'û') {t.replace(i, i+1, "\\373"); i = i+3;} //ucircumflex (251 dec)
else if(t.charAt(i) == 'ü') {t.replace(i, i+1, "\\374"); i = i+3;} //udieresis (252 dec)
else if(t.charAt(i) == 'ý') {t.replace(i, i+1, "\\375"); i = i+3;} //yacute (253 dec)
else if(t.charAt(i) == 'þ') {t.replace(i, i+1, "\\376"); i = i+3;} //thorn (254 dec)
else if(t.charAt(i) == 'ÿ') {t.replace(i, i+1, "\\377"); i = i+3;} //ydieresis (255 dec)
i++;
} //while
return t.toString();
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="maybeInQuotes">
private String maybeInQuotes(String t) {
if(t == null || t.length() <=0) {return t;}
boolean encloseInQuotes = false;
final String[] q = {"\"","\""};
for(int i =0; i < t.length(); i++) {
if(Character.isWhitespace(t.charAt(i))) {encloseInQuotes = true;}
}
if(encloseInQuotes) {return (q[0]+t+q[1]);} else {return t;}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="printInstructions()">
private static void printInstructions(java.io.PrintStream out) {
if(out == null) {out = System.out;}
out.flush();
out.println("This program will convert a plot file (*.plt) into a PDF file."+nl+
"Usage: java -jar PlotPDF.jar [plot-file-name] [-command=value]");
out.println("Possible commands are:"+nl+
" -b=bottom-margin (in cm)"+nl+
" -bw (black on white output)"+nl+
" -clr (colours - standard palette)"+nl+
" -clr2 (colours selected in \"Spana\")"+nl+
" -dbg (output debug information)"+nl+
" -f=font-nbr (1:Vector_Graphics, 2:Times-Roman, 3:Helvetica, 4:Courier)"+nl+
" -l=left-margin (in cm)"+nl+
" -noh (do not make a header with file name and date)"+nl+
" -nostop (do not stop for warnings)"+nl+
" -o=P/L (P: portrait; L: landscape)"+nl+
" -p=plot-file-name (input \"plt\"-file in UTF-8 Unicode ecoding)"+nl+
" -pdf=output-file-name"+nl+
" -s=% (output size; integer %-value)"+nl+
" -sx=% and -sy=% (different vertical and horizontal scaling)"+nl+
"Enclose file-names with double quotes (\"\") it they contain blank space."+nl+
"Example: java -jar PlotPDF.jar \"Fe 53\" -PDF=\"pdf\\Fe 53.pdf\" -s:60 -clr -F:2");
} //printInstructions(out)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="methods to print text">
//<editor-fold defaultstate="collapsed" desc="printText">
/** Print a text string.
* @param i1 x-coordinate
* @param i2 y-coordinate
* @param txt the text to be printed
* @param isFormula if the text is to handled as a chemical formula,
* with super- and sub-scripts
* @param align -1=Left 0=center +1=right
* @param txtSize size in cm
* @param txtAngle angle in degrees */
private void printText(int i1, int i2, String txt,
boolean isFormula, int align, double txtSize, double txtAngle) {
final double[] FontScaleHeight={1.45, 1.35, 1.6};
final double[] FontScaleWidth ={0.7, 0.71, 0.88};
final String[] ALIGNMENTS = {"left","centre","right"};
ChemFormula cf = null;
if(newPath == 2) { // stroke the graphic path if needed
if(Math.abs(x1st-xNow)<0.01 && Math.abs(y1st-yNow)<0.01) {
pdfStreamAppendTo("s");
} else {
pdfStreamAppendTo("S");
}
newPath = 0;
x1st = -Double.MAX_VALUE; y1st = -Double.MAX_VALUE;
}
if(dbg) {
System.out.println("Print text \""+txt+"\""+nl+
" formula:"+isFormula+", align="+align+" size="+txtSize+" angle="+txtAngle);
}
if(txt == null || txt.trim().length() <=0) {return;}
txt = rTrim(txt);
// get angles between +180 and -180
while (txtAngle>360) {txtAngle=txtAngle-360;}
while (txtAngle<-360) {txtAngle=txtAngle+360;}
if(txtAngle>180) {txtAngle=txtAngle-360;}
if(txtAngle<-180) {txtAngle=txtAngle+360;}
// font size
double fontSize = 100 * ((scaleX+scaleY)/2)
* ((txtSize * FontScaleHeight[pdfFont-1]) + 0.001) * SCALE_USER_SPACE;
fontSize = Math.min(5000, fontSize);
fontSizeTxt = String.format(engl, "%15.2f",fontSize).trim();
align = Math.max(-1,Math.min(1,align));
String str= "% text at X,Y= "+String.valueOf(i1)+" "+String.valueOf(i2)+
"; size = "+toStr(txtSize)+"; angle = "+toStr(txtAngle)+"; is formula: "+isFormula+"; alignment:"+ALIGNMENTS[align+1];
pdfStreamAppendTo(str);
str = "% text is: "+txt;
pdfStreamAppendTo(str.trim());
if(fontSize <=0.01) {
pdfStreamAppendTo(str+nl+"% (size too small)");
return;
}
if(!startedPrintingText) {pdfStreamAppendTo("BT"); startedPrintingText = true;}
if(penNow == 1) {
changeFontString = setFontString(1); // bold
} else {
changeFontString = setFontString(0); // normal font
}
pdfStreamAppendTo(changeFontString);
pdfStreamAppendTo(colours[colorNow]+" rg");
boolean containsLetters = false;
char c;
for(int i =0; i < txt.length(); i++) {
c = txt.charAt(i);
if(Character.isDigit(c) || c == '-' || c == '+' || c == '.') {continue;}
containsLetters = true;
break;
}
// if it does not contain letters it can not be a chemical formula
if(!containsLetters || txt.length()<=1) {
isFormula = false;
//align = 0; // center-align?
}
// find out the length of the text, and sub- and super-scripts
int txtLength = txt.length();
if(isFormula && txtLength > 1) {
if(txt.equalsIgnoreCase("log (ai/ar")) {txt = "log (a`i'/a`ref'";}
cf = new ChemFormula(txt, new float[1]);
chemF(cf);
txtLength = cf.t.length();
}
// --- position ---
double xpl = (double)i1;
double ypl = (double)i2;
// --- recalculate position according to alignment etc ---
double rads = Math.toRadians(txtAngle);
double w;
// for non-chemical formulas:
// - left aligned: the start position is given
// - right aligned: the start position is
// "exactly" calculated from the text length
// - centre alignment is aproximately calculated
// from the text length, as the width varies
// for different characters
// for chemical formulas:
// alignment is always aproximately calculated
// from the text length, as the width varies
// for different characters
if(!isFormula) { // not a chemical formula
// for plain text: if right-aligned, move the origin
if(align == 1 || align == 0) { //right aligned or centred
if(align == 1) { //right aligned
w = txtLength; // advance the whole requested text length
} else { // if(align == 0) // approximate calculation
// advance the whole text length minus the "real" text length
w = txtLength * (1-FontScaleWidth[pdfFont-1]);
w = w /2; // centre means only half
}
w = w * txtSize * 100;
xpl = xpl + w * Math.cos(rads);
ypl = ypl + w * Math.sin(rads);
}
} else { // it is a chemical formula
if(Math.abs(txtAngle) < 0.01 && align == 0) {
// (only for text not in axis: no special texts like 'pH', etc)
// move the text up slightly (labels on curves look better if they
// do not touch the lines of the curve): increase y-value 0.2*txtSize.
// Also, move the text to the right a bit proportional to text
// length. (only for text not in axis (angle must be zero, or text
// only be numbers, and no special texts like 'pH', etc))
if(!(txt.equals("pH") ||txt.equals("pe") ||txt.startsWith("Log") ||txt.startsWith("E / V"))
&& !txt.contains("`TOT'")) {
// label on a curve or predominance area
ypl = ypl + 0.3*txtSize*100;
}
} //if angle =0
// advance the whole text length minus the "real" text length
w = txt.length() * (1-FontScaleWidth[pdfFont-1]);
// remove things not printed. For example, in [Fe 3+]`TOT' there are three
// characters not printed: the space before the electrical charge
// and the accents surrounding "TOT"
w = w - (txt.length()-txtLength);
if(align == 0) { w = w /2; }
if(align == 1 || align == 0) { //right aligned or centred
w = w * txtSize * 100;
xpl = xpl + w * Math.cos(rads);
ypl = ypl + w * Math.sin(rads);
}
} // if is formula
xpl = (xpl * scaleX + zx) * SCALE_USER_SPACE;
ypl = (ypl * scaleY + zy) * SCALE_USER_SPACE;
if(pdfPortrait) {
xpl = xpl + MARGIN_X;
} else { //landscape
double x,y;
x = xpl; y = ypl;
xpl = MediaBox_X - y;
ypl = x;
xpl = xpl - MARGIN_X;
txtAngle = txtAngle + 90;
rads = Math.toRadians(txtAngle);
}
ypl = ypl + MARGIN_Y;
// start position and angle:
str = toStr(xpl)+" "+toStr(ypl)+" Tm";
if(Math.abs(txtAngle) <= 0.05) {
pdfStreamAppendTo("1 0 0 1 "+str);
} else { // angle !=0
double cosine = Math.cos(rads);
double sine = Math.sin(rads);
String a1 = toStr(cosine);
String a2 = toStr(sine);
String a3 = toStr(-sine);
pdfStreamAppendTo(a1+" "+a2+" "+a3+" "+a1+" "+str);
} // angle?
// --- do the printing itself ---
if(isFormula && cf != null) {
String move;
String l2;
int n1 = 0;
int j = 1;
while (j < cf.t.length()) {
if(cf.d[j] != cf.d[j-1]) {
l2 = cf.t.substring(n1, j);
n1 = j;
move = toStr(cf.d[j-1]*10) + " Ts ";
l2 = "("+fixText(l2,isFormula)+") Tj";
if(move.length() >0) {pdfStreamAppendTo(move+l2);} else {pdfStreamAppendTo(l2);}
}
j++;
} //while
if(n1 <= cf.t.length()) {
l2 = cf.t.substring(n1);
move = toStr(cf.d[j-1]*10) + " Ts ";
l2 = "("+fixText(l2,isFormula)+") Tj 0 Ts";
if(move.length() >0) {pdfStreamAppendTo(move+l2);} else {pdfStreamAppendTo(l2);}
}
} else { // not a chemical formula
if(align > 0) { // right adjusted text
//move to the left first by setting
// negative horizontal scale and no text rendering
pdfStreamAppendTo("-100 Tz 3 Tr ("+fixText(txt,isFormula)+") Tj");
//then display the text with
// normal horizontal scale and text rendering
pdfStreamAppendTo("100 Tz 0 Tr ("+fixText(txt,isFormula)+") Tj");
} else {
pdfStreamAppendTo("0 Ts ("+fixText(txt,isFormula)+") Tj");
}
}
} // printText
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="setFontString">
/** Set the pdf-text to change a font
* @param type 0 = normal; 1 = bold; 2 = italics; 3 = symbol */
private String setFontString(int type) {
final String[] FONTN = {"/F9", "/F4","/F0"}; //normal
final String[] FONTBN = {"/F10","/F5","/F1"}; //bold
final String[] FONTIN = {"/F11","/F6","/F2"}; //italics
String msg = null;
if(type <0 || type >3) {
msg = "type = "+type+" shoud be 0 to 3.";
}
if(pdfFont <0 || pdfFont >3) {
msg = "diagrConvertFont = "+pdfFont+" shoud be 0 to 3.";
}
if(fontSizeTxt == null || fontSizeTxt.length() <=0) {
msg = "fontSizeTxt is empty.";
}
if(msg != null) {
msg = "Programming error in \"setFontString\":"+nl+msg;
if(doNotStop) {System.out.println(msg);} else {ErrMsgBx mb = new ErrMsgBx(msg,progName);}
return "";
}
String changeFontTxt;
if(type == 1) {//bold font
changeFontTxt = FONTBN[pdfFont-1];
} else if(type == 2) {//italics
changeFontTxt = FONTIN[pdfFont-1];
} else if(type == 3) {//symbol
changeFontTxt = "/F8";
} else {//normal font
changeFontTxt = FONTN[pdfFont-1];
}
changeFontTxt = changeFontTxt + " "+fontSizeTxt+" Tf";
return changeFontTxt;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="fixText">
/** Escape parenthesis and back-slash (that is, change "(" to "\(", etc);
* and change hyphen, "-", to endash, etc
* @param txt
* @param isFormula
* @return */
private String fixText(String txt, boolean isFormula) {
if(txt == null || txt.trim().length() <=0) {return txt;}
// change "\", "(" and ")" to "\\", "\(" and "\)"
StringBuilder t = new StringBuilder(fixTextSimple(txt,isFormula));
int i = 0;
while(i < t.length()) {
if(isFormula){
if(t.charAt(i) == '~') {t.replace(i, i+1, "\\260"); i = i+3; continue;} //degree
else if(t.charAt(i) == '$') {t.replace(i, i+1, "\\265"); i = i+3; continue;} //mu
}
// Delta:
if(t.charAt(i) == 'Δ' || t.charAt(i) == '∆' || (isFormula && t.charAt(i) == '^')) {
//String str = ") Tj /F8 "+fontSizeTxt+" Tf (D) Tj "+changeFontString+" (";
String str = ") Tj /F8 "+fontSizeTxt+" Tf (\\104) Tj "+changeFontString+" (";
t.replace(i, i+1, str);
i = i+str.length();
continue;
}
// versus:
if(i <= (t.length()-6) && t.substring(i).startsWith("versus")) {
changeFontString = setFontString(2); //italics
String str = ") Tj "+changeFontString+" (versus) Tj ";
if(penNow != 2) {changeFontString = setFontString(0);} else {changeFontString = setFontString(1);} // bold?
str = str + changeFontString + " (";
t.replace(i, i+6, str);
i = i+str.length();
continue;
}
// log: change to lower case
if(i <= (t.length()-4)
&& (t.substring(i).startsWith("Log ") || t.substring(i).startsWith("Log[")
|| t.substring(i).startsWith("Log{"))) {
t.replace(i, i+3, "log");
i = i+3;
continue;
}
// log P: change to lower case "log" and italics "p"
if(i <= (t.length()-5)
&& t.substring(i).toLowerCase().startsWith("log p")) {
changeFontString = setFontString(2); //italics
String str = "log ) Tj "+changeFontString+" (p) Tj ";
if(penNow != 2) {changeFontString = setFontString(0);} else {changeFontString = setFontString(1);} // bold?
str = str + changeFontString + " (";
t.replace(i, i+5, str);
i = i+str.length();
continue;
}
// Sum:
if(t.charAt(i) == 'Σ' || t.charAt(i) == '∑') {
String str = ") Tj /F8 "+fontSizeTxt+" Tf (\\123) Tj "+changeFontString+" (";
t.replace(i, i+1, str);
i = i+str.length();
continue;
}
// rho:
if(t.charAt(i) == 'ρ') {
String str = ") Tj /F8 "+fontSizeTxt+" Tf (\\162) Tj "+changeFontString+" (";
t.replace(i, i+1, str);
i = i+str.length();
continue;
}
// epsilon:γ
if(t.charAt(i) == 'ε') {
String str = ") Tj /F8 "+fontSizeTxt+" Tf (\\145) Tj "+changeFontString+" (";
t.replace(i, i+1, str);
i = i+str.length();
continue;
}
// gamma:
if(t.charAt(i) == 'γ') {
String str = ") Tj /F8 "+fontSizeTxt+" Tf (\\147) Tj "+changeFontString+" (";
t.replace(i, i+1, str);
i = i+str.length();
continue;
}
i++;
} //while
return t.toString();
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="rTrim">
/** Remove trailing white space. If the argument is null, the return value is null as well.
* @param text input String.
* @return text without trailing white space. */
private static String rTrim(String text) {
if(text == null) {return text;}
//another possibility: ("a" + text).trim().substring(1)
int idx = text.length()-1;
if (idx >= 0) {
//while (idx>=0 && text.charAt(idx) == ' ') {idx--;}
while (idx>=0 && Character.isWhitespace(text.charAt(idx))) {idx--;}
if (idx < 0) {return "";}
else {return text.substring(0,idx+1);}
}
else { //if length =0
return text;
}
} // rTrim
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="class ChemFormula">
/** Class used for input and output from method "chemF" */
static class ChemFormula {
/** t is a StringBuffer with the initial chemical formula given
* to method "chemF", and it will be modified on return
* from chemF, for example "Fe+2" may be changed to "Fe2+". */
StringBuffer t;
/** d float[] returned by method "chemF" with
* super- subscript data for each character position
* in the StringBuffer t returned by chemF. */
float[] d;
/** @param txt String
* @param d_org float[] */
ChemFormula(String txt, float[] d_org) { // constructor
t = new StringBuffer();
//if (t.length()>0) {t.delete(0, t.length());}
t.append(txt);
int nChar = txt.length();
d = new float[nChar];
System.arraycopy(d_org, 0, d, 0, d_org.length); }
} // class ChemFormula
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="chemF">
/** Purpose: given a "chemical formula" in StringBuffer <b>t</b> it returns
* an array <b>d</b> indicating which characters are super- or
* sub-scripted and a new (possibly modified) <b>t</b>.
* Both <b>t</b> and <b>d</b> are stored for input
* and output in objects of class ChemFormula. Note that <b>t</b> may
* be changed, e.g. from "Fe+2" to "Fe2+".
* <p>
* Stores in array <b>d</b> the vertical displacement of each
* character (in units of character height). In the case of HCO3-, for example,
* d(1..3)=0, d(4)=-0.4, d(5)=+0.4
* <p>
* Not only chemical formulas, but this method also "understands" math
* formulas: x'2`, v`i', log`10', 1.35'.`10'-3`
* <p>
* For aqueous ions, the electric charge may be written as either a space and
* the charge (Fe 3+, CO3 2-, Al(OH)2 +), or as a sign followed by a number
* (Fe+3, CO3-2, Al(OH)2+). For charges of +-1: with or without a space
* sepparating the name from the charge (Na+, Cl-, HCO3- or Na +, Cl -, HCO3 -).
* <p>
* Within this method, <b>t</b> may be changed, so that on return:
* <ul><li>formulas Fe+3, CO3-2 are converted to Fe3+ and CO32-
* <li>math formulas: x'2`, v`i', log`10', 1.35'.`10'-3`
* are stripped of "`" and "'"
* <li>@ is used to force next character into base line, and
* the @ is removed (mostly used for names containing digits and
* some math formulas)</ul>
* <p>
* To test:<br>
* <pre>String txt = "Fe(CO3)2-";
* System.out.println("txt = \""+txt+"\","+
* " new txt = \""+chemF(new ChemFormula(txt, new float[1])).t.toString()+"\","+
* " d="+Arrays.toString(chemF(new ChemFormula(txt, new float[1])).d));</pre></p>
*
* <p>Version: 2013-Apr-03.
*
* @param cf ChemFormula
* @return new instance of ChemFormula with d[] of super- subscript
* positions for each character and a modified StingBuffer t. */
private static void chemF(ChemFormula cf) {
int act; // list of actions:
final int REMOVE_CHAR = 0;
final int DOWN = 1;
final int NONE = 2;
final int UP = 3;
final int CONT = 4;
final int END = 6;
int nchr; char t1; char t2; int i;
float dm; float df;
final char M1='\u2013'; // Unicode En Dash
final char M2='\u2212'; // Minus Sign = \u2212
// The characters in the StringBuffer are stored in "int" variables
// Last, Next-to-last, Next-to-Next-to-last
// ow (present character)
// Next, Next-Next, Next-Next-Next
int L; int nL; int nnL; int now; int n; int n2; int n3;
// ASCII Table:
// -----------------------------------------------------------------------------
// 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
// ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9
// -----------------------------------------------------------------------------
// 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
// : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S
// -----------------------------------------------------------------------------
// 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 00 01 02 03 04 05 06 07 08 09
// T U V W X Y Z [ \ ] ^ _ ` a b c d e f g h i j k n m
// -----------------------------------------------------------------------------
//110 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
// n o p q r s t u v w x y z { | } ~
// -----------------------------------------------------------------------------
// If the string is too short: do nothing
StringBuffer t = new StringBuffer();
t.append(cf.t);
L = t.toString().trim().length();
if(L <= 1) {return;}
// Remove trailing space from the StringBuffer
L = t.length(); // total length
nchr = rTrim(t.toString()).length(); // length without trailing space
if(L > nchr) {t.delete(nchr, L);}
// create d and initialize it
float[] d = new float[nchr];
for(i = 0; i < d.length; i++) {d[i] = 0f;}
// set the non-existing characters to "space"
// Last, Next-to-last, Next-to-Next-to-last
L = 32; nL = 32; nnL = 32;
// get the ASCII code
now = t.charAt(0);
// get the following characters
n = 32; if (nchr >=2) {n = t.charAt(1);} // Next
n2 = 32; if (nchr >=3) {n2 = t.charAt(2);} // Next-Next
// dm (Displacement-Math) for '` sequences: 1.5'.`10'-12`, log p`CO2'
dm = 0f;
// df (Displacement-Formulas) in chemical formulas: CO3 2-, Fe 3+, Cl-, Na+
df = 0f;
//
// -----------------------------
// Main Loop
//
i = 0;
main_do_loop:
do {
n3 = 32;
if(nchr >=(i + 4)) {n3 = t.charAt(i + 3);} //Next-Next-Next
// Because a chemical formula only contains supersripts at the end
// (the electric charge), a superscrip character marks the end of a formula.
// Set df=0 after superscript for characters that are not 0:9 + or -
if(df > 0.001f) { // (if last was supercript, i.e. df>0)
if (now <43 || now >57 || now ==44 || now ==46 || now ==47) //not +- 0:9
{df = 0f;}
} //df > 0.001
checks: { // named block of statements to be used with "break"
// ---------------
// for @
// ---------------
// if the character is @, do nothing; if last char. was @, treat "now" as a
// "normal" char. (and therefore, if last char. was @, and "now" is a space,
// leave a blank space);
if(now ==64 && L !=64) { act =REMOVE_CHAR; break checks;}
if(L ==64) { // @
if(now ==32) {act =CONT;} else {act =NONE;}
break checks;
} // Last=@
// ---------------
// for Ctrl-B (backspace)
// ---------------
if(now ==2) {
now = n; n = n2; n2 = n3;
act =END; break checks;
} // now = backspace
// ---------------
// for ' or `
// ---------------
if(now ==39 || now ==96) {
// for '`, `' sequences: change the value of variable dm.
// if it is a ' and we are writing a "normal"-line, and next is either
// blank or s (like it's or it's.): write it normal
if(now ==39 && dm ==0
&& ( (n ==32 && L ==115)
|| (n ==115 && (n2==32||n2==46||n2==44||n2==58||n2==59||n2==63
||n2==33||n2==41||n2==93)) ) )
{act =CONT; break checks;}
if(now ==39) {dm = dm + 0.5f;}
if(now ==96) {dm = dm - 0.5f;}
act =REMOVE_CHAR; break checks;
} // now = ' or `
// ---------------
// for BLANK (space)
// ---------------
// Decide if the blank must be printed or not.
// In front of an electric charge: do not print (like CO3 2-, etc)
if(now ==32) {
// if next char. is not a digit (1:9) and not (+-), make a normal blank
if((n <49 && (n !=43 && n !=45 &&n!=M1&&n!=M2)) || n >57) {act =NONE; break checks;}
// Space and next is a digit or +-:
// if next is (+-) and last (+-) make a normal blank
if((n ==43 || n ==45 || n==M1||n==M2)
&& (L ==43 || L ==45 ||L==M1||L==M2)) {act =NONE; break checks;}
// if the 2nd-next is letter (A-Z, a-z), make a normal blank
if((n2 >=65 && n2 <=90) || (n2 >=97 && n2 <=122)) {act =NONE; break checks;}
// if next is a digit (1-9)
if(n >=49 && n <=57) { // 1:9
// and 2nd-next is also a digit and 3rd-next is +- " 12+"
if(n2 >=48 && n2 <=57) { // 0:9
if (n3 !=43 && n3 !=45 &&n3!=M1&&n3!=M2) {act =NONE; break checks;} // n3=+:-
} // n2=0:9
// if next is (1-9) and 2nd-next is not either + or -, make a blank
else if (n2 !=43 && n2 !=45 &&n2!=M1&&n2!=M2) {act =NONE; break checks;}
} // n=1:9
// if last char. was blank, make a blank
if(L ==32) {act =NONE; break checks;} // 110 //
// if last char. was neither a letter (A-Z,a-z) nor a digit (0:9),
// and was not )]}"'>, make a blank
if((L <48 || L >122 || (L >=58 && L <=64) || (L >=91 && L<= 96))
&& (L !=41 && L !=93 && L !=125 && L !=62 && L !=34 && L !=39))
{act =NONE; break checks;}
// Blanks followed either by + or -, or by a digit (1-9) and a + or -
// and preceeded by either )]}"'> or a letter or a digit:
// do not make a blank space.
act =REMOVE_CHAR; break checks;
} //now = 32
// ---------------
// for Numbers (0:9)
// ---------------
// In general a digit is a subscript, except for electric charges...etc
if(now >=48 && now <=57) {
// if last char. is either ([{+- or an impossible chem.name,
// then write it "normal"
if(L !=40 && L !=91 && L !=123 && L !=45 &&L!=M1&&L!=M2&& L !=43) { // Last not ([{+-
if((L ==106 || L ==74) || (L ==113 || L ==81)) {act =NONE; break checks;} // jJ qQ
if((L ==120 || L ==88) || (L ==122 || L ==90)) {act =NONE; break checks;} // xX zZ
//if last char. is )]} or a letter (A-Z,a-z): write it 1/2 line down
if((L >=65 && L <=90) || (L >=97 && L <=122)) {act =DOWN; break checks;} // A-Z a-z
if(L ==41 || L ==93 || L ==125) {act =DOWN; break checks;} // )]}
//if last char. is (0:9 or .) 1/2 line (down or up), keep it
if(df >0.01f && ((L >=48 && L <=57) || L ==46)) {act =CONT; break checks;}
if(df <-0.01f && (L ==46 || (L >=48 && L <=57))) {act =CONT; break checks;}
} // Last not ([{+-
// it is a digit and last char. is not either of ([{+-)]} or A:Z a:z
// is it an electric charge?
df = 0f; //125//
// if last char is space, and next char. is a digit and 2nd-next is a +-
// (like: W14O41 10+) then write it "up"
if(L ==32 && (n >=48 && n <=57)
&& (n2 ==43 || n2 ==45 ||n2 ==M1||n2 ==M2) && now !=48) {
//if 3rd-next char. is not (space, )]}), write it "normal"
if(n3 !=32 && n3 !=41 && n3 !=93 && n3 !=125) {act =CONT; break checks;} // )]}
act =UP; break checks;
}
// if last is not space or next char. is not one of +-, then write it "normal"
if(L !=32 || (n !=43 && n !=45 &&n!=M1&&n!=M2)) {act =CONT; break checks;} // +-
// Next is +-:
// if 2nd-next char. is a digit or letter, write it "normal"
if((n2 >=48 && n2 <=57) || (n2 >=65 && n2 <=90)
|| (n2 >=97 && n2 <=122)) {act =CONT; break checks;} // 0:9 A:Z a:z
// if last char. was a digit or a blank, write it 1/2 line up
// if ((L >=48 && L <=57) || L ==32) {act =UP; break checks;}
// act =CONT; break checks;
act =UP; break checks;
} // now = (0:9)
// ---------------
// for Signs (+ or -)
// ---------------
// Decide if it is an electric charge...
// and convert things like: CO3-2 to: CO3 2-
if(now ==43 || now ==45 ||now ==M1||now ==M2) {
// First check for charges like: Fe 2+ and W16O24 11-
// If last char. was a digit (2:9) written 1/2 line up, write it
// also 1/2 line up (as an electrical charge in H+ or Fe 3+).
if(L >=50 && L <=57 && df >0.01f) {act =UP; break checks;} // 2:9
// charges like: W16O24 11-
if((L >=48 && L <=57) && (nL >=49 && nL <=57)
&& (df >0.01f)) {act =UP; break checks;} // 0:9 1:9
//is it a charge like: Fe+3 ? ------------------------
if(n >=49 && n <=57) { // 1:9
// it is a +- and last is not superscript and next is a number:
// check for impossible cases:
// if 2nd to last was a digit or a period and next a digit: 1.0E-1, 2E-3, etc
if(((nL >=48 && nL <=57) || nL ==46) && (L ==69 || L==101)) {act =NONE; break checks;} // 09.E
if(L ==32) {act =NONE; break checks;} // space
if((L ==106 || L ==74) || (L ==113 || L ==81)) {act =NONE; break checks;} // jJ qQ
if((L ==120 || L ==88) || (L ==122 || L ==90)) {act =NONE; break checks;} // xX zZ
// if last was 0 and 2nd to last 1 and dm>0 (for 10'-3` 10'-3.1` or 10'-36`)
if(dm >0.01f && (L ==39 && nL ==48 && nnL ==49)
&& (n >=49 && n <=57)
&& (n2 ==46 || n2 ==96 || (n2 >=48 && n2 <=57))) {act =NONE; break checks;}
// allowed in L: numbers, letters and )]}"'
// 1st Line: !#$%&(*+,-./ 2nd line: {|~:;<=?@ 3rd Line: [\^_`
if((L <48 && L !=41 && L !=34 && L !=39)
|| (L >122 && L !=125) || (L >=58 && L <=64 && L !=62)
|| (L >=91 && L <=96 && L !=93)) {act =NONE; break checks;}
if((L ==41 || L ==93 || L ==125 || L ==34 || L ==39)
&& (nL ==32 || nL <48 || nL >122 || (nL >=58 && nL <=64)
|| (nL >=91 && nL <=96))) {act =NONE; break checks;} // )]}"'
// allowed in n2: numbers and space )']`}
// 1st Line: !"#$%&(*+,-./ 2nd Line: except ]`}
if((n2 <48 && n2 !=41 && n2 !=32 && n2 !=39)
|| (n2 >57 && n2 !=93 && n2 !=96 && n2 !=125)) {act =NONE; break checks;}
//it is a +- and last is not superscript and next is a number:
// is it a charge like: W14O41-10 ?
if((n >=49 && n <=57) && (n2 >=48 && n2 <=57)) { // 1:9 0:9
// characters allowed after the electric charge: )]}`'@= space and backsp
if(n3 !=32 && n3 !=2 && n3 !=41 && n3 !=93 && n3 !=125
&& n3 !=96 && n3 !=39 && n3 !=64 && n3 !=61) {act =NONE; break checks;}
// it is a formula like "W12O41-10" convert to "W12O41 10-" and move "up"
t1 = t.charAt(i+1); t2 = t.charAt(i+2);
t.setCharAt(i+2, t.charAt(i));
t.setCharAt(i+1, t2);
t.setCharAt(i, t1);
int j1 = n; int j2 = n2;
n2 = now;
n = j2; now = j1;
act =UP; break checks;
} // 1:9 0:9
// is it a charge like Fe+3, CO3-2 ?
if(n >=50 && n <=57) { // 2:9
//it is a formula of type Fe+3 or CO3-2
// convert it to Fe3+ or CO32- and move "up"
t1 = t.charAt(i+1);
t.setCharAt(i+1, t.charAt(i));
t.setCharAt(i, t1);
int j = n; n = now; now = j;
act =UP; break checks;
} // 2:9
} // 1:9
// it is a +- and last is not superscript and: next is not a number:
// write it 1/2 line up (H+, Cl-, Na +, HCO3 -), except:
// 1) if last char. was either JQXZ, or not blank-letter-digit-or-)]}, or
// 2) if next char. is not blank or )}]
// 3) if last char. is blank or )]}"' and next-to-last is not letter or digit
if(L ==106 || L ==74 || L ==113 || L ==81) {act =NONE; break checks;} // jJ qQ
if(L ==120 || L ==88 || L ==122 || L ==90) {act =NONE; break checks;} // xX zZ
if(L ==32 || L ==41 || L ==93 || L ==125) { // space )]}
//1st Line: !"#$%&'(*+,-./{|}~ 2nd Line: :;<=>?@[\^_`
if(nL ==32 || (nL <48 && nL !=41) || (nL >122)
|| (nL >=58 && nL <=64)
|| (nL >=91 && nL <=96 && nL !=93)) {act =NONE; break checks;}
act =UP; break checks;
} // space )]}
// 1st Line: !#$%&(*+,-./{|~ 2nd Line: :;<=>?@[\^_`
if((L <48 && L !=41 && L !=34 && L !=39)
|| (L >122 && L !=125) || (L >=58 && L <=64)
|| (L >=91 && L <=96 && L !=93)) {act =NONE; break checks;}
if(n !=32 && n !=41 && n !=93 && n !=125 && n !=61
&& n !=39 && n !=96) {act =NONE; break checks;} // )]}=`'
act =UP; break checks;
} // (+ or -)
// ---------------
// for Period (.)
// ---------------
if (now ==46) {
// if last char was a digit (0:9) written 1/2 line (down or up)
// and next char is also a digit, continue 1/2 line (down or up)
if((L >=48 && L <=57) && (n >=48 && n <=57)) {act =CONT; break checks;} // 0:9
act =NONE; break checks;
} // (.)
act =NONE;
} // --------------- "checks" (end of block name)
switch_action:
switch (act) {
case REMOVE_CHAR:
// ---------------
// take OUT present character //150//
if(i <nchr) {t.deleteCharAt(i);}
nchr = nchr - 1;
nnL = nL; nL = L; L = now; now = n; n = n2; n2 = n3;
continue; // main_do_loop;
case DOWN:
df = -0.4f; // 170 //
break; // switch_action;
case NONE:
df = 0.0f; // 180 //
break; // switch_action;
case UP:
df = 0.4f; // 190 //
break; // switch_action;
case CONT:
case END:
default:
} // switch_action
if(act != END) {// - - - - - - - - - - - - - - - - - - - // 200 //
nnL = nL;
nL = L;
L = now;
now = n;
n = n2;
n2 = n3;
}
d[i] = dm + df; //201//
i = i + 1;
} while (i < nchr); // main do-loop
// finished
// store results in ChemFormula cf
if(cf.t.length()>0) {cf.t.delete(0, cf.t.length());}
cf.t.append(t);
cf.d = new float[nchr];
System.arraycopy(d, 0, cf.d, 0, nchr);
// return;
} // ChemFormula chemF
//</editor-fold>
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="exception(Exception ex)">
/** return the message "msg" surrounded by lines, including the calling method.
* @param ex
* @param msg
* @param doNotStop
*/
private static void exception(Exception ex, String msg, boolean doNotStop) {
final String ERR_START = "============================";
String errMsg = ERR_START;
String exMsg = ex.toString();
if(exMsg == null || exMsg.length() <=0) {exMsg = "Unknown error.";} else {exMsg = "Error: "+exMsg;}
errMsg = errMsg +nl+ exMsg;
if(msg != null && msg.trim().length() >0) {errMsg = errMsg + nl + msg;}
errMsg = errMsg + nl +stack2string(ex) + nl + ERR_START;
if(doNotStop) {System.out.println(errMsg);} else {ErrMsgBx mb = new ErrMsgBx(errMsg,progName);}
} //error(msg)
//<editor-fold defaultstate="collapsed" desc="stack2string(Exception e)">
/** returns a <code>printStackTrace</code> in a String, surrounded by two dash-lines.
* @param e Exception
* @return printStackTrace */
private static String stack2string(Exception e) {
try{
java.io.StringWriter sw = new java.io.StringWriter();
java.io.PrintWriter pw = new java.io.PrintWriter(sw);
e.printStackTrace(pw);
String t = sw.toString();
if(t != null && t.length() >0) {
int i = t.indexOf("Unknown Source");
int j = t.indexOf("\n");
if(i>0 && i > j) {
t = t.substring(0,i);
j = t.lastIndexOf("\n");
if(j>0) {t = t.substring(0,j)+nl;}
}
}
return "- - - - - -"+nl+
t +
"- - - - - -";
}
catch(Exception e2) {
return "Internal error in \"stack2string(Exception e)\"";
}
} //stack2string(ex)
//</editor-fold>
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="getPathApp">
/** Get the path where an application is located.
* @return the directory where the application is located,
* or "user.dir" if an error occurs
* @version 2014-Jan-17 */
private static class C {private static void C(){}}
public static String getPathApp() {
C c = new C();
String path;
java.net.URI dir;
try{
dir = c.getClass().
getProtectionDomain().
getCodeSource().
getLocation().
toURI();
if(dir != null) {
String d = dir.toString();
if(d.startsWith("jar:") && d.endsWith("!/")) {
d = d.substring(4, d.length()-2);
dir = new java.net.URI(d);
}
path = (new java.io.File(dir.getPath())).getParent();
} else {path = System.getProperty("user.dir");}
}
catch (java.net.URISyntaxException e) {
if(!started) {
ErrMsgBx emb = new ErrMsgBx("Error: "+e.toString()+nl+
" trying to get the application's directory.", progName);
}
path = System.getProperty("user.dir");
} // catch
started = true;
return path;
} //getPathApp()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="ErrMsgBx">
/** Displays a "message box" modal dialog with an "OK" button.<br>
* Why is this needed? For any java console application: if started using
* javaw.exe (on Windows) or through a ProcessBuilder, no console will appear.
* Error messages are then "lost" unless a log-file is generated and the user
* reads it. This class allows the program to stop running and wait for the user
* to confirm that the error message has been read.
* <br>
* A small frame (window) is first created and made visible. This frame is
* the parent to the modal "message box" dialog, and it has an icon on the
* task bar (Windows). Then the modal dialog is displayed on top of the
* small parent frame.
* <br>
* Copyright (C) 2015 I.Puigdomenech.
* @author Ignasi Puigdomenech
* @version 2015-July-14 */
static class ErrMsgBx {
/** Displays a "message box" modal dialog with an "OK" button and a title.
* The message is displayed in a text area (non-editable),
* which can be copied and pasted elsewhere.
* @param msg will be displayed in a text area, and line breaks may be
* included, for example: <code>new MsgBox("Very\nbad!",""); </code>
* If null or empty nothing is done.
* @param title for the dialog. If null or empty, "Error:" is used
* @version 2014-July-14 */
public ErrMsgBx(String msg, String title) {
if(msg == null || msg.trim().length() <=0) {
System.out.println("--- MsgBox: null or empty \"message\".");
return;
}
//--- Title
if(title == null || title.length() <=0) {title = " Error:";}
java.awt.Frame frame = new java.awt.Frame(title);
//--- Icon
String iconName = "images/ErrMsgBx.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
if(imgURL != null) {frame.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());}
else {System.out.println("--- Error in MsgBox constructor: Could not load image = \""+iconName+"\"");}
frame.pack();
//--- centre Window frame on Screen
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int left; int top;
left = Math.max(55, (screenSize.width - frame.getWidth() ) / 2);
top = Math.max(10, (screenSize.height - frame.getHeight()) / 2);
frame.setLocation(Math.min(screenSize.width-100, left), Math.min(screenSize.height-100, top));
//---
final String msgText = wrapString(msg.trim(),80);
//System.out.println("--- MsgBox:"+nl+msgText+nl+"---");
frame.setVisible(true);
//javax.swing.JOptionPane.showMessageDialog(frame, msg, title, javax.swing.JOptionPane.ERROR_MESSAGE);
MsgBoxDialog msgBox = new MsgBoxDialog(frame, msgText, title, true);
msgBox.setVisible(true); // becase the dialog is modal, statements below will wait
msgBox.dispose();
frame.setVisible(false);
frame.dispose();
}
/** Returns an input string, with lines that are longer than <code>maxLength</code>
* word-wrapped and indented. *
* @param s input string
* @param maxLength if an input line is longer than this length,
* the line will be word-wrapped at the first white space after <code>maxLength</code>
* and indented with 4 spaces
* @return string with long-lines word-wrapped
*/
public static String wrapString(String s, int maxLength) {
String deliminator = "\n";
StringBuilder result = new StringBuilder();
StringBuffer wrapLine;
int lastdelimPos;
for (String line : s.split(deliminator, -1)) {
if(line.length()/(maxLength+1) < 1) {
result.append(line).append(deliminator);
}
else { //line too long, try to split it
wrapLine = new StringBuffer();
lastdelimPos = 0;
for (String token : line.trim().split("\\s+", -1)) {
if (wrapLine.length() - lastdelimPos + token.length() > maxLength) {
if(wrapLine.length()>0) {wrapLine.append(deliminator);}
wrapLine.append(" ").append(token);
lastdelimPos = wrapLine.length() + 1;
} else {
if(wrapLine.length() <=0) {wrapLine.append(token);}
else {wrapLine.append(" ").append(token);}
}
}
result.append(wrapLine).append(deliminator);
}
}
return result.toString();
}
//<editor-fold defaultstate="collapsed" desc="MsgBoxDialog">
private static class MsgBoxDialog extends java.awt.Dialog {
private java.awt.Button ok;
private java.awt.Panel p;
private final java.awt.TextArea text;
/** Creates new form NewDialog */
public MsgBoxDialog(java.awt.Frame parent, String msg, String title, boolean modal) {
super(parent, (" "+title), modal);
addWindowListener(new java.awt.event.WindowAdapter() {
@Override public void windowClosing(java.awt.event.WindowEvent evt) {
MsgBoxDialog.this.setVisible(false);
}
});
setLayout(new java.awt.BorderLayout());
p = new java.awt.Panel();
p.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER));
ok = new java.awt.Button();
// find out the size of the message (width and height)
final int wMax = 85; final int hMax=20;
final int wMin = 5; final int hMin = 1;
int w = wMin;
int h=hMin; int i=0; int j=wMin;
final String eol = "\n"; char c;
final String nl = System.getProperty("line.separator");
while (true) {
c = msg.charAt(i);
String s = String.valueOf(c);
if(s.equals(eol) || s.equals(nl)) {
h++; j=wMin;
} else {
j++; w = Math.max(j,w);
}
i++;
if(i >= msg.length()-1) {break;}
}
// create a text area
int scroll = java.awt.TextArea.SCROLLBARS_NONE;
if(w > wMax && h <= hMax) {scroll = scroll & java.awt.TextArea.SCROLLBARS_HORIZONTAL_ONLY;}
if(h > hMax && w <= wMax) {scroll = scroll & java.awt.TextArea.SCROLLBARS_VERTICAL_ONLY;}
if(w > wMax && h > hMax) {scroll = java.awt.TextArea.SCROLLBARS_BOTH;}
w = Math.min(Math.max(w,10),wMax);
h = Math.min(h,hMax);
text = new java.awt.TextArea(msg, h, w, scroll);
text.setEditable(false);
//text.setBackground(java.awt.Color.white);
text.addKeyListener(new java.awt.event.KeyAdapter() {
@Override public void keyPressed(java.awt.event.KeyEvent evt) {
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER
|| evt.getKeyCode() == java.awt.event.KeyEvent.VK_ESCAPE) {closeDialog();}
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_TAB) {ok.requestFocusInWindow();}
}
});
text.setBackground(java.awt.Color.WHITE);
text.setFont(new java.awt.Font("monospaced", java.awt.Font.PLAIN, 12));
add(text, java.awt.BorderLayout.CENTER);
ok.setLabel("OK");
ok.addActionListener(new java.awt.event.ActionListener() {
@Override public void actionPerformed(java.awt.event.ActionEvent evt) {
closeDialog();
}
});
ok.addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER
|| evt.getKeyCode() == java.awt.event.KeyEvent.VK_ESCAPE) {closeDialog();}
}
});
p.add(ok);
add(p, java.awt.BorderLayout.SOUTH);
pack();
ok.requestFocusInWindow();
//--- centre Window frame on Screen
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int left; int top;
left = Math.max(55, (screenSize.width - getWidth() ) / 2);
top = Math.max(10, (screenSize.height - getHeight()) / 2);
setLocation(Math.min(screenSize.width-100, left), Math.min(screenSize.height-100, top));
}
private void closeDialog() {this.setVisible(false);}
} // private static class MsgBoxDialog
//</editor-fold>
} // static class ErrMsgBx
//</editor-fold>
} | 118,156 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
Version.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibChemDiagr/src/lib/Version.java | package lib;
/** Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class Version {
static final String VERSION = "2020-06-17";
public static String version() {return VERSION;}
}
| 894 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
JarClassLoader.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibChemDiagr/src/lib/huvud/JarClassLoader.java | package lib.huvud;
import lib.common.MsgExceptn;
/** A class loader for loading jar files, both local and remote.
*
* Copyright (C) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
* Modified by I.Puigdomenech (20014-2020)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle or the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
public class JarClassLoader extends java.net.URLClassLoader {
private final java.net.URL url;
/** Creates a new JarClassLoader for the specified url.
* @param url the url of the jar file */
public JarClassLoader(java.net.URL url) {
super(new java.net.URL[] { url });
this.url = url;
}
/** Returns the name of the jar file main class, or null if
* no "Main-Class" manifest attributes is defined.
* @return
* @throws java.io.IOException */
public String getMainClassName() throws java.io.IOException {
String nl = System.getProperty("line.separator");
//The syntax for the URL of a JAR file is:
// jar:http://www.zzz.yyy/jarfile.jar!/
java.net.URL u = new java.net.URL("jar", "", url + "!/");
// modified by I.Puigdomenech to catch cast problems
java.net.JarURLConnection uc = null;
try{uc = (java.net.JarURLConnection)u.openConnection();}
catch (Exception | Error ex) {MsgExceptn.exception(ex.toString());}
if(uc == null) {return null;}
java.util.jar.Attributes attr = uc.getMainAttributes();
return attr != null ? attr.getValue(java.util.jar.Attributes.Name.MAIN_CLASS) : null;
}
/** Invokes the application in this jar file given the name of the
* main class and an array of arguments. The class must define a
* static method "main" which takes an array of String arguments
* and is of return type "void".
*
* @param name the name of the main class
* @param args the arguments for the application
* @exception ClassNotFoundException if the specified class could not
* be found
* @exception NoSuchMethodException if the specified class does not
* contain a "main" method
* @exception java.lang.reflect.InvocationTargetException if the application raised an
* exception
*/
public void invokeClass(String name, String[] args)
throws ClassNotFoundException,
NoSuchMethodException,
java.lang.reflect.InvocationTargetException {
Class<?> c = findLoadedClass(name); // added by Ignasi Puigdomenech // added "<?>" (Ignasi Puigdomenech)
if(c == null) {c = loadClass(name);}
if(args == null) {args = new String[]{""};} // added by Ignasi Puigdomenech
// java.lang.reflect.Method m = c.getMethod("main", new Class[] { args.getClass() });
java.lang.reflect.Method m = c.getMethod("main", new Class<?>[] { String[].class }); // changed by I.Puigdomenech
m.setAccessible(true);
int mods = m.getModifiers();
if (m.getReturnType() != void.class ||
!java.lang.reflect.Modifier.isStatic(mods) ||
!java.lang.reflect.Modifier.isPublic(mods))
{throw new NoSuchMethodException("main");}
try {
m.invoke(null, new Object[] { args });
} catch (IllegalAccessException e) {
// This should not happen, as we have disabled access checks
}
} // invokeClass(name, args[])
} | 4,963 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
RunProgr.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibChemDiagr/src/lib/huvud/RunProgr.java | package lib.huvud;
import lib.common.MsgExceptn;
import lib.common.Util;
/** Has one method: "runProgramInProcess". It uses a ProcessBuilder to run
* the process.
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @see RunProgr#runProgramInProcess(java.awt.Component, java.lang.String, java.lang.String[], boolean, boolean, java.lang.String) runProgramInProcess
* @see RunJar#runJarLoadingFile(java.awt.Component, java.lang.String, java.lang.String[], boolean, java.lang.String) runJarLoadingFile
* @author Ignasi Puigdomenech */
public class RunProgr {
private static final String nl = System.getProperty("line.separator");
private static final String SLASH = java.io.File.separator;
//<editor-fold defaultstate="collapsed" desc="runProgramInProcess">
/** Starts a system process to execute either a program or
* the "main" method in a jar-file. Error messages are printed
* to "System.err".
* @param parent The calling frame, used to link error-message boxes.
* The cursor (wait or default) is left unmodified.
* May be "null".
* @param prgm the name of the program or jar file to run. It can include
* a full path. If no path is specified, the directory given in the
* <code>path</code> variable is assumed.
* @param a array with the command-line parameters. If needed the user must
* enclose individual parameters in quotes.
* @param waitForCompletion if true the method will wait for the
* execution of the program to finish
* @param dbg if true debug information will be written to "System.out"
* @param path the working directory.
* If no path is given in <code>prgm</code> (the name of the program
* or jar file to run) then this path is used.
* @return false if an error occurs
* @see RunJar#runJarLoadingFile(java.awt.Component, java.lang.String, java.lang.String[], boolean, java.lang.String) runJarLoadingFile
*/
public static boolean runProgramInProcess(final java.awt.Component parent,
String prgm,
String[] a,
final boolean waitForCompletion,
final boolean dbg,
String path) {
if(prgm == null || prgm.trim().length() <=0) {
String msg = "Programming error detected in \"runProgramInProcess\""+nl;
if(prgm == null) {
msg = msg + " program or jar file name is \"null\".";
} else {msg = msg + " program or jar file name is empty.";}
MsgExceptn.showErrMsg(parent,msg,1);
return false;
}
if(dbg) {
System.out.println("- - - - - - - - - - - - - - - - - - - - - - - - - - -"+nl+
"runProgramInProcess:"+nl+" "+prgm);
if(a.length>0) {
for(int i=0; i < a.length; i++) {System.out.print(" "+a[i]);}
System.out.println();
}
System.out.println(" waitForCompletion = "+waitForCompletion+", debug = "+dbg);
if(path != null && path.trim().length() >0) {
System.out.println(" path = "+path);
} else {System.out.println(" path = (not given)");}
System.out.flush();
}
//remove enclosing quotes
if(prgm.length() >2 && prgm.startsWith("\"") && prgm.endsWith("\"")) {
prgm = prgm.substring(1, prgm.length()-1);
}
final String prgmFileName;
if(!prgm.contains(SLASH) && path != null && path.trim().length() >0) {
String dir;
if(path.endsWith(SLASH)) {dir = path.substring(0,path.length()-1);} else {dir = path;}
prgmFileName = dir + SLASH + prgm;
} else {prgmFileName = prgm;}
if(!(new java.io.File(prgmFileName).exists())) {
MsgExceptn.showErrMsg(parent,"Error: Program or jar file:"+nl+
" "+prgmFileName+nl+
" does NOT exist.",1);
return false;
}
// create the operating-system command to run a program or jar-file
java.util.List<String> command = new java.util.ArrayList<String>();
if(prgmFileName.toLowerCase().endsWith(".jar")) {
command.add("java");
command.add("-jar");
} else if(prgmFileName.toLowerCase().endsWith(".app")
&& System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
command.add("/usr/bin/open");
command.add("-n");
}
command.add(prgmFileName);
if(a == null) {a = new String[0];}
if(a.length>0) {
for (String a1 : a) {
if (a1 != null && a1.length() > 0) {
//remove enclosing quotes: spaces will be taken care by ProcessBuilder
if(a1.length() >2 && a1.startsWith("\"") && a1.endsWith("\"")) {
a1 = a1.substring(1, a1.length()-1);
}
command.add(a1);
}
}
}
if(dbg) {
System.out.println("starting process:");
if(command.size()>0) { // it should be >0...
for(int i=0; i < command.size(); i++) {System.out.println(" "+command.get(i));}
}
System.out.flush();
}
ProcessBuilder builder = new ProcessBuilder(command);
//java.util.Map<String, String> environ = builder.environment();
if(path != null && path.trim().length()>0) {
if(dbg) {
System.out.println(" --- setting working directory to: "+path);
System.out.flush();
}
builder = builder.directory(new java.io.File(path));
}
System.out.flush();
if(!waitForCompletion) {builder = builder.redirectErrorStream(true);}
try { // Start the program.
if(dbg) {System.out.println(" --- starting the process..."); System.out.flush();}
final Process p = builder.start();
if(waitForCompletion) {
if(dbg) {System.out.println(" --- waiting for process to terminate...");}
// Get the output
java.io.BufferedReader stdInput = new java.io.BufferedReader(
new java.io.InputStreamReader(p.getInputStream()));
java.io.BufferedReader stdError = new java.io.BufferedReader(
new java.io.InputStreamReader(p.getErrorStream()));
String s;
while ((s = stdInput.readLine()) != null) {System.out.println(s);}
while ((s = stdError.readLine()) != null) {System.err.println(s);}
//if needed for debugging: sleep some milliseconds (wait)
//try {Thread.sleep(3000);} catch(Exception ex) {}
p.waitFor();
} else {
// Get the output
new Thread(new StreamEater(p.getInputStream())).start();
}
if(dbg) {System.out.println("- - - - - - - - - - - - - - - - - - - - - - - - - - -");}
}
catch (InterruptedException e) {
MsgExceptn.showErrMsg(parent,Util.stack2string(e),1);
return false;}
catch (java.io.IOException e) {
MsgExceptn.showErrMsg(parent,Util.stack2string(e),1);
return false;}
return true;
} // runProgramInProcess
//<editor-fold defaultstate="collapsed" desc="private StreamEater">
private static class StreamEater implements Runnable {
private final java.io.InputStream stream;
StreamEater(java.io.InputStream stream) {this.stream = stream;}
@Override public void run() {
byte[] buf = new byte[32];
try{while (stream.read(buf) != -1) {}} catch (java.io.IOException e) {e.printStackTrace();}
}
}
// </editor-fold>
// </editor-fold>
}
| 8,810 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
SortedProperties.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibChemDiagr/src/lib/huvud/SortedProperties.java | package lib.huvud;
/** Sort Properties when saving.
* The SortedProperties class extends the regular Properties class.
* It overrides the keys() method to return the sorted keys instead.
* From Real Gagnon (http://www.rgagnon.com/javadetails/java-0614.html) */
public class SortedProperties extends java.util.Properties {
@Override
@SuppressWarnings("unchecked")
public synchronized java.util.Enumeration<java.lang.Object> keys() {
java.util.Enumeration keysEnum = super.keys();
//java.util.Vector keyList = new java.util.Vector();
java.util.ArrayList keyList2 = new java.util.ArrayList();
while(keysEnum.hasMoreElements()){
keyList2.add(keysEnum.nextElement());
}
java.util.Collections.sort(keyList2);
//return keyList.elements();
return java.util.Collections.enumeration(keyList2);
} // keys()
}
| 922 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
SortedListModel.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibChemDiagr/src/lib/huvud/SortedListModel.java | package lib.huvud;
import java.util.*;
import javax.swing.AbstractListModel;
/**
* From http://www.java2s.com
*
*/
public class SortedListModel extends AbstractListModel {
SortedSet<Object> model;
public SortedListModel() {
model = new TreeSet<Object>();
}
@Override
public int getSize() {
return model.size();
}
@Override
public Object getElementAt(int index) {
return model.toArray()[index];
}
public void add(Object element) {
if (model.add(element)) {
fireContentsChanged(this, 0, getSize());
}
}
public void addAll(Object elements[]) {
Collection<Object> c = Arrays.asList(elements);
model.addAll(c);
fireContentsChanged(this, 0, getSize());
}
public void clear() {
model.clear();
fireContentsChanged(this, 0, getSize());
}
public boolean contains(Object element) {
return model.contains(element);
}
public Object firstElement() {
return model.first();
}
public Iterator iterator() {
return model.iterator();
}
public Object lastElement() {
return model.last();
}
public boolean removeElement(Object element) {
boolean removed = model.remove(element);
if (removed) {
fireContentsChanged(this, 0, getSize());
}
return removed;
}
}
| 1,354 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
RedirectedFrame.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibChemDiagr/src/lib/huvud/RedirectedFrame.java | package lib.huvud;
import lib.common.Util;
/** A Java Swing class that captures error output to the console
* (eg, <code>System.err.println</code>).
*
* From http://www.rgagnon.com/javadetails/java-0435.html
*
* http://tanksoftware.com/juk/developer/src/com/
* tanksoftware/util/RedirectedFrame.java
* A Java Swing class that captures output to the command line
** (eg, System.out.println)
* RedirectedFrame
* <p>
* This class was downloaded from:
* Java CodeGuru (http://codeguru.earthweb.com/java/articles/382.shtml) <br>
* The origional author was Real Gagnon (real.gagnon@tactika.com);
* William Denniss has edited the code, improving its customizability
*
* In brief, this class captures all output to the system and prints it in
* a frame. You can choose whether or not you want to catch errors, log
* them to a file and more.
* For more details, read the constructor method description
*
* Modified by Ignasi Puigdomenech (2014-2020) to use a rotating Logger, etc
*
* @author Real Gagnon */
public class RedirectedFrame extends javax.swing.JFrame {
//http://tanksoftware.com/juk/developer/src/com/
// tanksoftware/util/RedirectedFrame.java
private final ProgramConf pc;
private javax.swing.JFrame parentFrame;
private RedirectedFrame f;
private boolean loading;
private boolean popupOnErr = true;
private final java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
java.io.PrintStream errPrintStream =
new java.io.PrintStream(
new errFilteredStream(
new java.io.ByteArrayOutputStream()));
java.io.PrintStream outPrintStream =
new java.io.PrintStream(
new outFilteredStream(
new java.io.ByteArrayOutputStream()));
//<editor-fold defaultstate="collapsed" desc="Constructor">
/** <p>Creates a new <code>RedirectedFrame</code>. From the moment
* it is created, all System.out messages and error messages are diverted
* to this frame and appended to the log file.
* For example:</p>
* <pre><code>RedirectedFrame outputFrame =
* new RedirectedFrame(700, 600);</code></pre>
* this will create a new <code>RedirectedFrame</code> with the
* dimentions 700x600. Can be toggled to visible or hidden by a controlling
* class by <code>outputFrame.setVisible(true|false)</code>.
* @param width the width of the frame
* @param height the height of the frame
* @param pc0 */
public RedirectedFrame(int width, int height, ProgramConf pc0) {
initComponents();
this.pc = pc0;
parentFrame = null;
loading = true;
setTitle(pc.progName+" - Error and Debug output:");
setSize(width,height);
this.setLocation(80, 28);
setDefaultCloseOperation(javax.swing.JFrame.DO_NOTHING_ON_CLOSE);
// ---- if main frame visible: change focus on ESC key
javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE");
javax.swing.Action escAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(parentFrame != null && parentFrame.isVisible()) {
if((parentFrame.getExtendedState() & javax.swing.JFrame.ICONIFIED)
== javax.swing.JFrame.ICONIFIED) {
parentFrame.setExtendedState(javax.swing.JFrame.NORMAL);
} // if minimized
parentFrame.toFront();
parentFrame.requestFocus();
}
}};
getRootPane().getActionMap().put("ESCAPE", escAction);
// ---- Alt-S close window
javax.swing.KeyStroke altSKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altSKeyStroke,"ALT_S");
javax.swing.Action altSAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jButtonClose.doClick();
}};
getRootPane().getActionMap().put("ALT_S", altSAction);
//--- Icon
String iconName;
if(pc.progName.equalsIgnoreCase("spana")) {
iconName = "images/Warn_RedTriangl_Blue.gif";
} else if(pc.progName.equalsIgnoreCase("database")) {
iconName = "images/Warn_RedTriangl_Yellow.gif";
} else {iconName = "images/Warn_RedTriangl.gif";}
java.net.URL imgURL = this.getClass().getResource(iconName);
if (imgURL != null) {
this.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());
}
else {System.out.println("Could not load image: \""+iconName+"\"");}
// --- set text and background colours
if(pc.progName.equalsIgnoreCase("spana")) {
aTextArea.setBackground(new java.awt.Color(220,220,255));
aTextArea.setForeground(new java.awt.Color(0,0,102));
} else if(pc.progName.equalsIgnoreCase("database")) {
aTextArea.setBackground(new java.awt.Color(255,255,204));
aTextArea.setForeground(java.awt.Color.black);
} else {
aTextArea.setBackground(java.awt.Color.black);
aTextArea.setForeground(new java.awt.Color(102,255,0));
}
aTextArea.selectAll(); aTextArea.replaceRange("", 0, aTextArea.getSelectionEnd());
jLabel1.setVisible(parentFrame != null);
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
f = RedirectedFrame.this;
loading = false;
}}); //invokeLater(Runnable)
System.setOut(outPrintStream); // catches System.out messages
System.setErr(errPrintStream); // catches error messages
} // constructor
// </editor-fold>
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jButtonClose = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
aTextArea = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addWindowFocusListener(new java.awt.event.WindowFocusListener() {
public void windowGainedFocus(java.awt.event.WindowEvent evt) {
formWindowGainedFocus(evt);
}
public void windowLostFocus(java.awt.event.WindowEvent evt) {
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentMoved(java.awt.event.ComponentEvent evt) {
formComponentMoved(evt);
}
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
jLabel1.setText("(press [ESC] to focus the main window)");
jButtonClose.setMnemonic('S');
jButtonClose.setText(" do not Show ");
jButtonClose.setToolTipText("hide frame (alt-S)");
jButtonClose.setAlignmentX(0.5F);
jButtonClose.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonClose.setIconTextGap(2);
jButtonClose.setMargin(new java.awt.Insets(2, 2, 2, 2));
jButtonClose.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonCloseActionPerformed(evt);
}
});
jScrollPane1.setFont(new java.awt.Font("Monospaced", 0, 13)); // NOI18N
aTextArea.setBackground(new java.awt.Color(227, 227, 254));
aTextArea.setColumns(20);
aTextArea.setForeground(new java.awt.Color(0, 0, 102));
aTextArea.setRows(5);
aTextArea.setText("This is a test");
aTextArea.setToolTipText(""); // NOI18N
aTextArea.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
aTextAreaKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
aTextAreaKeyTyped(evt);
}
});
jScrollPane1.setViewportView(aTextArea);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButtonClose))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonClose)
.addComponent(jLabel1))
.addGap(0, 0, 0)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 283, Short.MAX_VALUE)
.addGap(0, 0, 0))
);
pack();
}// </editor-fold>//GEN-END:initComponents
//<editor-fold defaultstate="collapsed" desc="Events">
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
Object[] opt0 = {"Hide window", "Terminate!", "Cancel"};
int n = javax.swing.JOptionPane.showOptionDialog(this,
"Hide this window?"+nl+nl+
"\"Terminate\" will stop the program without"+nl+
"closing connections or closing files, etc."+nl+
"Terminate only if the program is not responding!"+nl,
pc.progName, javax.swing.JOptionPane.YES_NO_CANCEL_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE, null, opt0, null);
if(n == javax.swing.JOptionPane.YES_OPTION) { //the first button is "hide"
RedirectedFrame.this.setVisible(false);
}
else if(n == javax.swing.JOptionPane.NO_OPTION) { //second button is "terminate"
Object[] opt1 = {"Cancel", "Yes"};
//note that the buttons are reversed: "cancel" is the first button
// and "yes" is the second
n = javax.swing.JOptionPane.showOptionDialog(this,
"Are you really sure?",
pc.progName, javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.ERROR_MESSAGE, null, opt1, null);
if(n == javax.swing.JOptionPane.NO_OPTION) { //the second button is "yes"
System.out.println("Program Terminated by the User.");
System.exit(1);
}
}
}//GEN-LAST:event_formWindowClosing
private void aTextAreaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_aTextAreaKeyTyped
evt.consume();
}//GEN-LAST:event_aTextAreaKeyTyped
private void aTextAreaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_aTextAreaKeyPressed
if(!Util.isKeyPressedOK(evt)) {evt.consume();}
}//GEN-LAST:event_aTextAreaKeyPressed
private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
if(loading || this.getExtendedState()==javax.swing.JFrame.ICONIFIED) {return;}
if(this.getExtendedState()!=javax.swing.JFrame.MAXIMIZED_BOTH) {
if(this.getHeight()<100){this.setSize(this.getWidth(), 100);}
if(this.getWidth()<280){this.setSize(280,this.getHeight());}
}
}//GEN-LAST:event_formComponentResized
private void formComponentMoved(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentMoved
if(loading || this.getExtendedState()==javax.swing.JFrame.ICONIFIED) {return;}
if(this.getExtendedState()!=javax.swing.JFrame.MAXIMIZED_BOTH) {
if(this.getX()<0) {this.setLocation(2,this.getY());}
if(this.getX() > screenSize.width-100){this.setLocation(screenSize.width-100,this.getY());}
if(this.getY()<0) {this.setLocation(this.getX(),2);}
if(this.getY() > screenSize.height-30){this.setLocation(this.getX(),screenSize.height-30);}
}
}//GEN-LAST:event_formComponentMoved
private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus
aTextArea.requestFocusInWindow();
}//GEN-LAST:event_formWindowGainedFocus
private void jButtonCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCloseActionPerformed
if(parentFrame != null && parentFrame.isVisible()) {
RedirectedFrame.this.setVisible(false);
if((parentFrame.getExtendedState() & javax.swing.JFrame.ICONIFIED)
== javax.swing.JFrame.ICONIFIED) {
parentFrame.setExtendedState(javax.swing.JFrame.NORMAL);
}
parentFrame.toFront();
parentFrame.requestFocus();
}
}//GEN-LAST:event_jButtonCloseActionPerformed
// </editor-fold>
/** set the parent frame so that Alt-S and Escape will switch to it
* @param parent the parent frame */
public void setParentFrame(javax.swing.JFrame parent) {
this.parentFrame = parent;
jLabel1.setVisible(true);
}
public void setCursorWait() {
this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
aTextArea.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
}
public void setCursorDef() {
this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
aTextArea.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
}
/** Enquire the behaviour of the redirected frame when a message is printed
* on "<code>System.err</code>". Returns <code>true</code> if the redirected
* frame is made visible when an error message is printed, and <code>false</code> otherwise.
* @return <code>true</code> if the frame "pops up" when a \"System.err\" message
* is printed; <code>false</code> otherwise
* @see lib.huvud.RedirectedFrame#setPopupOnErr(boolean) setPopupOnErr */
public boolean isPopupOnErr() {return popupOnErr;}
/** Sets the behaviour of the redirected frame when a message is printed
* on "<code>System.err</code>".
* @param popOnErr <code>serVisible(popOnErr)</code> will be effectuated
* when a message is printed on "<code>System.err</code>", that is,<ul>
* <li>if <code>true</code> the frame will beccome visible if the frame
* was not visible; if the frame was visible it will remain so.</li>
* <li>if <code>false</code> the redirected frame will <i>not</i> become
* visible; if the frame was visible before the error message is printed,
* it will remain visible</li></ul>
* @see lib.huvud.RedirectedFrame#isPopupOnErr() isPopupOnErr */
public void setPopupOnErr(boolean popOnErr) {popupOnErr = popOnErr;}
//<editor-fold defaultstate="collapsed" desc="errFilteredStream">
class errFilteredStream extends java.io.FilterOutputStream {
public errFilteredStream(java.io.OutputStream aStream) {
super(aStream);
} // constructor
@Override
public synchronized void write(byte b[]) throws java.io.IOException {
String aString = new String(b);
if(popupOnErr) {f.setVisible(true);}
aTextArea.append(aString);
aTextArea.setSelectionStart(Integer.MAX_VALUE);
}
@Override
public synchronized void write(byte b[], int off, int len) throws java.io.IOException {
String aString = new String(b , off , len);
if(popupOnErr) {f.setVisible(true);}
aTextArea.append(aString);
aTextArea.setSelectionStart(Integer.MAX_VALUE);
} // write
} // class errFilteredStream
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="outFilteredStream">
class outFilteredStream extends java.io.FilterOutputStream {
public outFilteredStream(java.io.OutputStream aStream) {
super(aStream);
} // constructor
@Override
public synchronized void write(byte b[]) throws java.io.IOException {
String aString = new String(b);
aTextArea.append(aString);
aTextArea.setSelectionStart(Integer.MAX_VALUE);
}
@Override
public synchronized void write(byte b[], int off, int len) throws java.io.IOException {
String aString = new String(b , off , len);
aTextArea.append(aString);
aTextArea.setSelectionStart(Integer.MAX_VALUE);
} // write
} // class outFilteredStream
// </editor-fold>
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextArea aTextArea;
private javax.swing.JButton jButtonClose;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration//GEN-END:variables
} | 18,258 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
RunJar.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibChemDiagr/src/lib/huvud/RunJar.java | package lib.huvud;
import lib.common.MsgExceptn;
import lib.common.Util;
/** Has two methods: "runJarLoadingFile" and "jarDone"
* It uses JarClassLoader.
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @see RunJar#runJarLoadingFile(java.awt.Component, java.lang.String, java.lang.String[], boolean, java.lang.String) runJarLoadingFile
* @see RunJar#jarDone() jarDone
* @see RunProgr#runProgramInProcess(java.awt.Component, java.lang.String, java.lang.String[], boolean, boolean, java.lang.String) runProgramInProcess
* @author Ignasi Puigdomenech */
public class RunJar {
/** A SwingWorker to perform tasks in the background. It invokes the "main"-method
* of a jar-file, with an array of arguments. It is like typing<<pre>
* java -jar file.jar arg1 arg2 arg3</pre>
* but as a background task within this java virtual machine. */
private WorkTask tsk;
private static final String SLASH = java.io.File.separator;
private static final String nl = System.getProperty("line.separator");
private JarClassLoader jcl;
private String jarFileName;
private String[] argsCopy;
private String mainClassName;
private boolean dbg;
private boolean finished = false;
//<editor-fold defaultstate="collapsed" desc="runJarLoadingFile">
/** Loads a jar file, which may be local or remote, and executes its "main" method.
* This method waits while the daughter application runs in the background
* using a SwingWorker.
* @param parent The calling frame, used to link error-message boxes.
* The cursor (wait or default) is left unmodified.
* May be "null".
* @param jar the name of the jar-file whose "main" method is to be executed
* @param args arguments to the "main" method of the jar-file
* @param debug true to output debug information
* @param path the path of the application calling this procedure.
* If no path is given in <code>prgm</code> (the name of the program or jar file to run)
* then the application's path is used.
* @see #jarDone() jarDone
* @see RunProgr#runProgramInProcess(java.awt.Component, java.lang.String, java.lang.String[], boolean, boolean, java.lang.String) runProgramInProcess
*/
public void runJarLoadingFile(final java.awt.Component parent,
final String jar,
final String[] args,
final boolean debug,
String path) {
//--- check the jar file
if(jar == null || jar.trim().length() <=0) {
MsgExceptn.exception("Programming error detected in \"runJarLoadingFile(jar)\""+nl+
" jar-file name is either \"null\" or empty.");
return;}
if(!jar.toLowerCase().endsWith(".jar")) {
MsgExceptn.exception("Programming error detected in"+nl+
" \"runJarLoadingFile("+jar+")"+nl+
" The name does not end with \".jar\"");
return;}
dbg = debug;
if(args == null) {
argsCopy = new String[0];
} else {
java.util.List<String> commandArgs = new java.util.ArrayList<String>();
//System.arraycopy( args, 0, argsCopy, 0, args.length );
//for(int i=0; i<args.length; i++) {
for (String a1 : args) {
if(a1 != null && a1.length()>0) {
// -- remove enclosing quotes
if(a1.length() >2 && a1.startsWith("\"") && a1.endsWith("\"")) {
a1 = a1.substring(1, a1.length()-1);
}
commandArgs.add(a1);
} //if a1
} //for i
argsCopy = new String[commandArgs.size()];
argsCopy = commandArgs.toArray(argsCopy);
}
if(dbg) {System.out.println("- - - - - - - - - - - - - - - - - - - - - - - - - - -"+nl+
"Loading jar file: \""+jar+"\" with arguments:");
for (String argsCopy1 : argsCopy) {System.out.println(" " + argsCopy1);}
System.out.flush();
}
if(jar.contains(SLASH) || path == null || path.length() <=0) {
jarFileName = jar;
} else {
if(path.endsWith(SLASH)) {path = path.substring(0,path.length()-1);}
jarFileName = path + SLASH + jar;
}
final java.io.File jarFile = new java.io.File(jarFileName);
if(!jarFile.exists()) {
String msg = "Error: file Not found:"+nl+
" \""+jarFile.getAbsolutePath()+"\""+nl+
" Can not \"run\" jar-file.";
MsgExceptn.showErrMsg(parent,msg,1);
return;
}
// --- jar ok, invoke the "main" method
//if needed for debugging: sleep some milliseconds (wait)
//try {Thread.sleep(3000);} catch(Exception ex) {}
java.net.URL url;
try {url = jarFile.toURI().toURL();}
catch (java.net.MalformedURLException ex) {
String msg = "Error: \""+ex.toString()+"\""+nl+
" while attempting to access file:"+nl+
" \""+jarFileName+"\"";
MsgExceptn.showErrMsg(parent,msg,1);
return;
}
if(dbg) {System.out.println("jar file full path: "+url.getPath());}
// Create the class loader for the jar file
jcl = new JarClassLoader(url);
// Get the application's main class name
try {mainClassName = jcl.getMainClassName();}
catch (java.io.IOException ex) {
String msg = "Error: \""+ex.toString()+"\""+nl+
" while attempting to open file:"+nl+
" \""+jarFileName+"\"";
MsgExceptn.showErrMsg(parent,msg,1);
return;
}
if(mainClassName == null) {
String msg = "Error: the 'Main-Class' manifest attribute"+nl+
" is Not found in jar file:"+nl+
" \""+jarFileName+"\"";
MsgExceptn.showErrMsg(parent,msg,1);
return;
}
// Invoke application's main class
if(dbg) {System.out.println("executing task...");}
finished = false;
tsk = new WorkTask();
tsk.execute(); // this returns inmediately
// but the SwingWorker proceeds...
waitForTask(); // wait for the SwingWorker to end
/* An alternative method to to execute code <i>after</i> the daughter
* application has finished, do as follows:<pre>
* class MyClass
* private javax.swing.Timer tmr;
* ...
* void myMethod() {
* final RunJar rj = new RunJar();
* rj.runJarLoadingFile(this, "test.jar", null, true,"D:\\myPath\\dist");
* tmr = new javax.swing.Timer(500, new java.awt.event.ActionListener() {
* public void actionPerformed(java.awt.event.ActionEvent e) {
* if(rj.jarDone()) {
* if(tmr != null) {tmr.stop();}
* // put here tasks to run after the daughter application has finished
* javax.swing.JOptionPane.showMessageDialog(this, "Finished!");
* }}});
* tmr.start();
* }</pre>
*/
if(dbg) {System.out.println("--- RunJar returns..."); System.out.flush();}
} // runJarLoadingFile
// </editor-fold>
private synchronized void waitForTask() {
while(!finished) { try {wait();} catch (InterruptedException ex) {} }
}
private synchronized void notify_All() {notifyAll();}
/** Returns true if the SwingWorker running the jar-file is done, or if it is cancelled
* @return true if the SwingWorker running the jar-file is done, or if it is cancelled;
* false otherwise
* @see #runJarLoadingFile(java.awt.Component, java.lang.String, java.lang.String[], boolean, java.lang.String) runJarLoadingFile
* @see RunProgr#runProgramInProcess(java.awt.Component, java.lang.String, java.lang.String[], boolean, boolean, java.lang.String) runProgramInProcess
*/
public boolean jarDone() {
if(tsk == null) {return true;}
return (tsk.isDone() || tsk.isCancelled());
}
//<editor-fold defaultstate="collapsed" desc="class WorkTask">
/** A SwingWorker to perform tasks in the background.
* @see WorkTask#doInBackground() doInBackground() */
private class WorkTask extends javax.swing.SwingWorker<Boolean, String> {
/** The instructions to be executed are defined here: it invokes the "main"-method
* of a jar-file, with an array of arguments. It is like
* typing<<pre>
* java -jar file.jar arg1 arg2 arg3
* </pre>but in this java virtual machine as a background task.
* @return true if no error occurs, false otherwise
* @throws Exception */
@Override protected Boolean doInBackground() throws Exception {
boolean ok;
String msg = null;
try {
jcl.invokeClass(mainClassName, argsCopy);
ok = true;
}
catch (ClassNotFoundException e) {
msg = "Error: Class not found: \"" + mainClassName +"\""+nl+
" in jar file:"+nl+
" \""+jarFileName+"\"";
ok = false;
}
catch (NoSuchMethodException e) {
msg = "Error: Class \"" + mainClassName +"\""+nl+
" in jar file:"+nl+
" \""+jarFileName+"\""+nl+
" does not define a 'main' method";
ok = false;
}
catch (java.lang.reflect.InvocationTargetException e) {
msg = "Error: \"" + e.getTargetException().toString() +"\""+nl+
" in class \""+mainClassName+"\""+nl+
" in jar file:"+nl+
" \""+jarFileName+"\"";
msg = msg + nl + Util.stack2string(e);
ok = false;
}
if(msg != null) {MsgExceptn.exception(msg); System.out.flush();}
return ok;
} //doInBackground()
/** It wakes up the waitng thread and it prints a message if in debug "mode". */
@Override protected void done() {
if(dbg) {
if(isCancelled()) {
System.out.println("SwingWorker cancelled.");
} else {
System.out.println("SwingWorker done.");
}
System.out.flush();
}
finished = true;
notify_All();
}
/* There is no "publish()" in doInBackground(), so this is not needed.
@Override protected void process(java.util.List<String> chunks) {
// Here we receive the values that we publish().
// They may come grouped in chunks.
//jLabelCount.setText(chunks.get(chunks.size()-1));
//System.out.println(chunks.get(chunks.size()-1));
} */
} //class WorkTask
// </editor-fold>
} | 11,236 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
Div.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibChemDiagr/src/lib/huvud/Div.java | package lib.huvud;
/** A collection of static methods used by the libraries and
* by the software "Chemical Equilibrium Diagrams".
*
* Copyright (C) 2014 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class Div {
private static final String SLASH = java.io.File.separator;
private static final String nl = System.getProperty("line.separator");
//<editor-fold defaultstate="collapsed" desc="getFileNameWithoutExtension">
/**
* @param fileName a file name with or without the directory path
* @return the argument (<code>fileName</code>) without the extension.
* If the file name corresponds to an existing directory,
* or if there is no extension, <code>fileName</code> is returned.
* It returns <code>null</code> if the file name is <code>null</code>.
* It returns "" if the file name is exactly ".".
*/
public static String getFileNameWithoutExtension(String fileName) {
if(fileName == null || fileName.length() <= 0) {return fileName;}
if(fileName.length() == 1) {
if(fileName.equals(".")) {return "";} else {return fileName;}
}
java.io.File f = new java.io.File(fileName);
if(f.isDirectory()) {return fileName;}
int dot = fileName.lastIndexOf(".");
if(dot <= 0) {return fileName;} //no extension in name
// check that the last dot is in the name part, and not in the path (as in C:/dir.1/fileName)
String ext;
if(dot <= fileName.length()) {ext = fileName.substring(dot+1);} else {ext = "";}
if(ext.contains(SLASH)) {return fileName;} else {return fileName.substring(0,dot);}
} // getFileNameWithoutExtension(fileName)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="getFileNameExtension">
/** Returns the extension (without a ".").
* It returns <code>null</code> if the file name is <code>null</code>.
* It returns "" if:<br>
* .- the file name corresponds to an existing directory<br>
* .- there is no "." in the file name<br>
* .- the file name ends with "."<br>
* .- there is no "." after the last slash (java.io.File.separator)<br>
* @param fileName
* @return */
public static String getFileNameExtension(String fileName) {
java.io.File f = new java.io.File(fileName);
if(f.isDirectory()) {return "";}
if(fileName == null) {return fileName;}
if(fileName.length() <= 1 || fileName.endsWith(".")) {return "";}
int dot = fileName.lastIndexOf(".");
if(dot <= 0) {return "";} //no extension
// check that the last dot is in the name part, and not in the path (as in C:/dir.1/fileName)
String ext;
if(dot <= fileName.length()) {ext = fileName.substring(dot+1);} else {ext = "";}
if(ext.contains(SLASH)) {return "";} else {return ext;}
} // getFileNameExtension(fileName)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="myLogger(pattern, progName)">
public static java.util.logging.Logger myLogger(final String pattern, final String progName) {
if(pattern == null || pattern.length() <=0 || progName == null || progName.length() <=0) {
return null;
}
java.util.logging.Logger lggr;
try {
int limit = 1000000; // 1 Mb
int numLogFiles = 2;
// %h = user.home; %g = generation number for rotated logs
// %u = unique number to resolve conflicts
java.util.logging.FileHandler fh =
new java.util.logging.FileHandler(pattern,limit,numLogFiles);
fh.setFormatter(
new java.util.logging.Formatter() {@Override
public String format(java.util.logging.LogRecord rec) {
StringBuilder buf = new StringBuilder(1000);
//buf.append(new java.util.Date()+" ");
//buf.append(rec.getLevel()+" ");
buf.append(formatMessage(rec));
//buf.append(nl);
return buf.toString();
} //format(rec)
}
); // setFormatter
lggr = java.util.logging.Logger.getLogger(progName);
lggr.addHandler(fh);
//To suppress the logging output to the console :
java.util.logging.Logger rootLogger = java.util.logging.Logger.getLogger("");
java.util.logging.Handler[] handlers = rootLogger.getHandlers();
if(handlers[0] instanceof java.util.logging.ConsoleHandler) {
rootLogger.removeHandler(handlers[0]);
}
} // try
catch (java.io.IOException e) {
e.printStackTrace();
lggr = null;
}
return lggr;
} //myLogger
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="progExists, progSEDexists, progPredomExists">
/**
* @param dir a directory or a full-path file name
* @return true if either of the files "SED.jar" or "SED.exe" (under Windows)
* exist in "dir", or if "dir" ends with either of these two file names. False otherwise. */
public static boolean progSEDexists(java.io.File dir) {
if(dir == null || !dir.exists()) {return false;}
if(progExists(dir, "SED","jar")) {return true;}
if(System.getProperty("os.name").toLowerCase().startsWith("windows")) {
if(progExists(dir, "SED","exe")) {return true;}
}
return false;
}
/**
* @param dir a directory or a full-path file name
* @return true if either of the files "Predom.jar", "Predom.exe" (on Windows), or
* "Predom2.exe" (on Windows) exist in "dir",
* or if "dir" ends with either of these three file names. False otherwise. */
public static boolean progPredomExists(java.io.File dir) {
if(dir == null || !dir.exists()) {return false;}
if(progExists(dir, "Predom","jar")) {return true;}
if(System.getProperty("os.name").toLowerCase().startsWith("windows")) {
if(progExists(dir, "Predom","exe") || progExists(dir, "Predom2","exe")) {return true;}
}
return false;
}
/**
* @param dir a directory or a full-path file name
* @param prog a file name without extension
* @param ext an extension, with or without initial ".". For example "jar".
* @return true if "dir/prog.ext" exists, or if "dir" ends with "prog.ext" and it exists */
public static boolean progExists(java.io.File dir, String prog, String ext) {
if(dir == null || prog == null || ext == null) {return false;}
if(!dir.exists()) {return false;}
if(!ext.startsWith(".")) {ext = "."+ext;}
String name;
if(dir.isDirectory()) {
String path = dir.getAbsolutePath();
if(path.endsWith(SLASH)) {path = path.substring(0,path.length()-1);}
name = path + SLASH + prog + ext;
java.io.File f = new java.io.File(name);
if(f.exists() && f.isFile()) {return true;}
} else { //"dir" is a file
name = dir.getName();
if(name.equalsIgnoreCase(prog + ext)) {return true;}
}
return false;
} //progExists
//</editor-fold>
//</editor-fold>
}
| 7,669 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
LicenseFrame.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibChemDiagr/src/lib/huvud/LicenseFrame.java | package lib.huvud;
/** Show a window frame with the GNU General Public License.
*
* Copyright (C) 2014-2018 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class LicenseFrame extends javax.swing.JFrame {
private boolean finished = false;
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
/** Creates new form LicenseFrame
* @param parentFrame */
public LicenseFrame(final javax.swing.JFrame parentFrame) {
initComponents();
setDefaultCloseOperation(javax.swing.JFrame.DO_NOTHING_ON_CLOSE);
//--- ESC: close frame - if parent frame visible: request focus
javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE");
javax.swing.Action escAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(parentFrame != null && parentFrame.isVisible()) {parentFrame.requestFocus();}
closeWindow();
}};
getRootPane().getActionMap().put("ESCAPE", escAction);
//--- Alt-X eXit
javax.swing.KeyStroke altXKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altXKeyStroke,"ALT_X");
getRootPane().getActionMap().put("ALT_X", escAction);
//--- Alt-Q quit
javax.swing.KeyStroke altQKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altQKeyStroke,"ALT_Q");
getRootPane().getActionMap().put("ALT_Q", escAction);
// ---- Title, etc
//getContentPane().setBackground(new java.awt.Color(255, 255, 153));
this.setTitle(" GNU General Public License");
// ---- Icon
String iconName = "images/GNU_32x32.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
if(imgURL != null) {this.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());}
else {System.out.println("Error: Could not load image = \""+iconName+"\"");}
//---- Centre window on parent/screen
int left,top;
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
if(parentFrame != null) {
left = Math.max(0,(parentFrame.getX() + (parentFrame.getWidth()/2) - this.getWidth()/2));
top = Math.max(0,(parentFrame.getY()+(parentFrame.getHeight()/2)-this.getHeight()/2));
} else {
left = Math.max(0,(screenSize.width-this.getWidth())/2);
top = Math.max(0,(screenSize.height-this.getHeight())/2);
}
this.setLocation(Math.min(screenSize.width-this.getWidth()-20,left),
Math.min(screenSize.height-this.getHeight()-20, top));
// ----
java.net.URL licenseURL = LicenseFrame.class.getResource("GPL.html");
if (licenseURL != null) {
try {
jEditorPane.setPage(licenseURL);
} catch (java.io.IOException e) {
System.err.println("Attempted to read a bad URL: " + licenseURL);
}
} else {
System.err.println("Couldn't find file: GPL.html");
if(parentFrame != null && parentFrame.isVisible()) {parentFrame.requestFocus();}
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
closeWindow();
}}); //invokeLater(Runnable)
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane = new javax.swing.JScrollPane();
jEditorPane = new javax.swing.JEditorPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jEditorPane.setEditable(false);
jEditorPane.setContentType("text/html"); // NOI18N
jEditorPane.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jEditorPaneKeyPressed(evt);
}
});
jScrollPane.setViewportView(jEditorPane);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 544, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
closeWindow();
}//GEN-LAST:event_formWindowClosing
private void jEditorPaneKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jEditorPaneKeyPressed
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {evt.consume(); closeWindow();}
}//GEN-LAST:event_jEditorPaneKeyPressed
public void closeWindow() {
this.setVisible(false);
finished = true; //return from "waitFor()"
this.notify_All();
this.dispose();
} // closeWindow()
/** this method will wait for this window to be closed */
public synchronized void waitFor() {
while(!finished) {
try {wait();} catch (InterruptedException ex) {}
} // while
} // waitFor()
private synchronized void notify_All() { //needed by "waitFor()"
notifyAll();
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JEditorPane jEditorPane;
private javax.swing.JScrollPane jScrollPane;
// End of variables declaration//GEN-END:variables
}
| 7,484 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
ProgramConf.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibChemDiagr/src/lib/huvud/ProgramConf.java | package lib.huvud;
import lib.common.MsgExceptn;
/** Class to store "configuration" information about the DataBase and Spana programs.
* These data are stored in the configuration file.
* The class is used to retrieve data in diverse methods
*
* Copyright (C) 2015-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class ProgramConf {
/** The name of the program, either "Spana" or "DataBase" */
public String progName = null;
/** The path where the application (jar-file) is located */
public String pathAPP;
/** true if debug printout is to be made. Messages and errors are directed
* to a message frame */
public boolean dbg = false;
/** <code>true</code> if the ini-file is to be saved (or read) in the
* applications path only, for example if running from a USB-memory
* (or a portable drive). Note: if the application directory is
* write-protected, then if this parameter is <true>true</true> an ini-file
* will NOT be written, while if <code>false</code> the ini-file will be written
* elsewhere (for example in the user's home directory).*/
public boolean saveIniFileToApplicationPathOnly = false;
/** default directory for opening and writing input and ouput files.
* Note that it may end with the file separator character, e.g. "D:\" */
public StringBuffer pathDef = new StringBuffer();
public static final String HELP_JAR = "Chem_Diagr_Help.jar";
private static final String SLASH = java.io.File.separator;
private static final String nl = System.getProperty("line.separator");
public ProgramConf() {dbg = false; saveIniFileToApplicationPathOnly = false;}
public ProgramConf(String pgName) {
progName = pgName;
dbg = false;
saveIniFileToApplicationPathOnly = false;
}
//<editor-fold defaultstate="collapsed" desc="setPathDef">
/** Set the variable "pathDef" to the user directory ("user.home", system dependent) */
public void setPathDef() {
String t = System.getProperty("user.home");
setPathDef(t);
}
/** Set the variable "pathDef" to the path of a file name.
* Note that "pathDef" may end with the file separator character, e.g. "D:\"
* @param fName String with the file name */
public void setPathDef(String fName) {
java.io.File f = new java.io.File(fName);
setPathDef(f);
}
/** Sets the variable "pathDef" to the path of a file.
* Note that "pathDef" may end with the file separator character, e.g. "D:\"
* @param f File */
public void setPathDef(java.io.File f) {
if(pathDef == null) {pathDef = new StringBuffer();}
java.net.URI uri;
if(f != null) {
if(!f.getAbsolutePath().contains(SLASH)) {
// it is a bare file name, without a path
if(pathDef.length()>0) {return;}
}
try{uri = f.toURI();}
catch (Exception ex) {uri = null;}
} else {uri = null;}
if(pathDef.length()>0) {pathDef.delete(0, pathDef.length());}
if(uri != null) {
if(f != null && f.isDirectory()) {
pathDef.append((new java.io.File(uri.getPath())).toString());
} else {
pathDef.append((new java.io.File(uri.getPath())).getParent().toString());
} //directory?
} else { //uri = null: set Default Path = Start Directory
java.io.File currDir = new java.io.File("");
try {pathDef.append(currDir.getCanonicalPath());}
catch (java.io.IOException e) {
try{pathDef.append(System.getProperty("user.dir"));}
catch (Exception e1) {pathDef.append(".");}
}
} //uri = null
} // setPathDef(File)
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="Cfg-file">
/** Read program options (configuration file)<br>
* Exceptions are reported only to the console:
* The program's functionality is not affected if this method fails
* @param fileNameCfg
* @param pc */
public static void read_cfgFile(java.io.File fileNameCfg, ProgramConf pc) {
if(fileNameCfg == null) {System.err.println("Error: fileNameCfg =null in routine \"read_cfgFile\""); return;}
if(pc == null) {System.err.println("Error: pc =null in routine \"read_cfgFile\""); return;}
java.util.Properties cfg = new java.util.Properties();
java.io.FileInputStream fis = null;
java.io.BufferedReader r = null;
boolean loadedOK = false;
try {
fis = new java.io.FileInputStream(fileNameCfg);
r = new java.io.BufferedReader(new java.io.InputStreamReader(fis,"UTF8"));
cfg.load(r);
loadedOK = true;
} //try
catch (java.io.FileNotFoundException e) {
System.out.println("Warning: file Not found: \""+fileNameCfg.getPath()+"\""+nl+
"using default program options.");
write_cfgFile(fileNameCfg, pc);
return;
}
catch (java.io.IOException e) {
MsgExceptn.exception("Error: \""+e.getMessage()+"\""+nl+
" while loading config.-file:"+nl+
" \""+fileNameCfg.getPath()+"\"");
loadedOK = false;
}
try {if(r != null) {r.close();} if(fis != null) {fis.close();}}
catch (java.io.IOException e) {
MsgExceptn.exception("Error: \""+e.getMessage()+"\""+nl+
" while closing config.-file:"+nl+
" \""+fileNameCfg.getPath()+"\"");
}
if(loadedOK) {
try {
System.out.println("Reading file: \""+fileNameCfg.getPath()+"\"");
if(cfg.getProperty("Debug") != null &&
cfg.getProperty("Debug").equalsIgnoreCase("true")) {
pc.dbg = true;
}
pc.saveIniFileToApplicationPathOnly = cfg.getProperty("SaveIniFileToApplicationPathOnly") != null &&
cfg.getProperty("SaveIniFileToApplicationPathOnly").equalsIgnoreCase("true");
}
catch (Exception ex) {
MsgExceptn.msg("Error: \""+ex.getMessage()+"\""+nl+
" while reading file: \""+fileNameCfg.getPath()+"\"");
write_cfgFile(fileNameCfg, pc);
}
} // if (loadedOK)
} // read_cfgFile()
/** Write program options (configuration file).<br>
* Exceptions are reported to the console. */
private static void write_cfgFile(java.io.File fileNameCfg, ProgramConf pc) {
java.io.FileOutputStream fos = null;
java.io.Writer w = null;
try {
fos = new java.io.FileOutputStream(fileNameCfg);
w = new java.io.BufferedWriter(new java.io.OutputStreamWriter(fos,"UTF8"));
}
catch (java.io.IOException e) {
MsgExceptn.msg("Error: \""+e.getMessage()+"\""+nl+
" trying to write config.-file: \""+fileNameCfg.toString()+"\"");
try{if(w != null) {w.close();} if(fos != null) {fos.close();}}
catch (Exception e1) {
MsgExceptn.msg("Error: \""+e1.getMessage()+"\""+nl+
" trying to close config.-file: \""+fileNameCfg.toString()+"\"");
}
return;
} //catch
try{
w.write(
"# Next parameter should be \"true\" if running from a USB-memory"+nl+
"# (or a portable drive): then the ini-file will ONLY be saved in"+nl+
"# the application directory. If the application directory"+nl+
"# is write-protected, then no ini-file will be written."+nl+
"# If not \"true\" then the ini-file is saved in one of the"+nl+
"# following paths (depending on which environment variables"+nl+
"# are defined and if the paths are not write-protected):"+nl+
"# The installation directory"+nl+
"# %HOMEDRIVE%%HOMEPATH%"+nl+
"# %HOME%"+nl+
"# the user's home directory (system dependent)."+nl+
"# Except for the installation directory, the ini-file will"+nl+
"# be writen in a sub-folder named \".config\\eq-diagr\"."+nl);
if(pc.saveIniFileToApplicationPathOnly) {
w.write("SaveIniFileToApplicationPathOnly=true"+nl);
} else {
w.write("SaveIniFileToApplicationPathOnly=false"+nl);
}
w.write(
"# Change next to \"true\" to output debugging information"+nl+
"# to the messages window."+nl);
if(pc.dbg) {w.write("Debug=true"+nl);}
else {w.write("Debug=false"+nl);}
w.flush(); w.close(); fos.close();
if(pc.dbg) {System.out.println("Written: \""+fileNameCfg.toString()+"\"");}
}
catch (Exception ex) {
MsgExceptn.showErrMsg(null,ex.getMessage()+nl+
" trying to write config.-file: \""+fileNameCfg.toString()+"\"",1);
}
} // write_cfgFile()
//</editor-fold>
} | 9,442 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
Splash.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibChemDiagr/src/lib/huvud/Splash.java | package lib.huvud;
/**
* Copyright (C) 2015-2018 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class Splash extends javax.swing.JFrame {
/**
* Creates new form Splash
* @param i0
*/
public Splash(int i0) {
initComponents();
//---- Centre window on parent/screen
int left,top;
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
left = Math.max(0,(screenSize.width-this.getWidth())/2);
top = Math.max(0,(screenSize.height-this.getHeight())/2);
this.setLocation(Math.min(screenSize.width-this.getWidth()-20,left),
Math.min(screenSize.height-this.getHeight()-20, top));
jLabelDatabaseIcon.setVisible(false);
jLabelSpanaIcon.setVisible(false);
if(i0 == 0) {jLabelDatabaseIcon.setVisible(true);} else if(i0 == 1) {jLabelSpanaIcon.setVisible(true);}
javax.swing.border.Border bevelBorder = javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED);
getRootPane().setBorder(bevelBorder);
this.setVisible(true);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel2 = new javax.swing.JLabel();
jLabelSpanaIcon = new javax.swing.JLabel();
jLabelDatabaseIcon = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
setUndecorated(true);
setResizable(false);
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel2.setText("Loading, please wait ...");
jLabelSpanaIcon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/lib/huvud/images/Spana_icon_32x32.gif"))); // NOI18N
jLabelDatabaseIcon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/lib/huvud/images/DataBase.gif"))); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(jLabelSpanaIcon)
.addGap(0, 0, 0)
.addComponent(jLabelDatabaseIcon)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel2)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(32, 32, 32)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelDatabaseIcon)
.addComponent(jLabelSpanaIcon)))
.addGroup(layout.createSequentialGroup()
.addGap(42, 42, 42)
.addComponent(jLabel2)))
.addContainerGap(39, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabelDatabaseIcon;
private javax.swing.JLabel jLabelSpanaIcon;
// End of variables declaration//GEN-END:variables
}
| 4,679 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
GraphLib.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibChemDiagr/src/lib/kemi/graph_lib/GraphLib.java | package lib.kemi.graph_lib;
import lib.common.Util;
/** Class used as a plotter driver. The plot is to be displayed in a
* Java Swing jPannel component when the "paint" method is invoked
* by Java. The methods in this class also save the graphic information
* in a plot file so that it can be displayed in another occasion.
*
* To display the plot using the "paint" method, the methods in this
* class store the graphic information in a "PltData" instance.
* When finished, after calling "end()", you call the
* "DiagrPaintUtility.paintDiagram" method from within the "paint" method
* of the jPannel usung the PltData instance as argument.
* The "paintDiagram" method will read the "PltData" instance and
* re-paint the jPannel when needed.
*
* The output plot file is a text file that may later be displayed by the
* user, or for example sent by e-mail, etc.
*
* The graphic information is a vector format ("go to", "draw to",
* "change colour", "display a text"). The units are to be thought as "cm",
* but during the painting events they are scaled to the size of the
* painted component.
*
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class GraphLib {
// display text outline? (for debug purposes, if sketch = false)
private static final boolean OUTLINE_DRAW = false;
// this should be = true; that is, save texts in plot-files both as
// line sketches and font information
private static final boolean CHARACTER_SKETCH = true;
/** true if a text is being sketched, but texts are painted with a font
* (then the line sketches should not be displayed) */
private boolean sketching;
/** true if texts are to be displayed on the JPanel using a font, that is,
* not by using the line-sketches stored in the plot file.<br>
* If true, text sketch information is not stored in the PlotStep ArrayList
* of the PltData instance */
private boolean textWithFonts;
// ----
private PltData pd;
/** the current value for the colour for drawing on the screen */
private int screenColour;
/** the current value for the plotter pen */
private int plotPen;
private boolean isFormula;
private String label;
private boolean save;
/** The output file */
private java.io.Writer w;
private double xL =1; private double yL =1;
private double xI =0; private double yI =0;
private double sizeSym =0;
private java.awt.geom.Rectangle2D.Double clippingArea;
private int i2Last = Integer.MIN_VALUE;
private int i3Last = Integer.MIN_VALUE;
private static java.util.Locale engl = java.util.Locale.ENGLISH;
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
// ---- may be used to set the steps in the axes
public double stpXI =0;
public double stpYI =0;
// --------------------------
/** Create an instance */
public void GraphLib() {
save = false; xL =1; yL =1; xI =0; yI =0; sizeSym =0;
screenColour =1; plotPen =1; isFormula = false;
textWithFonts = true;
sketching = false;
} //constructor
//<editor-fold defaultstate="collapsed" desc="class PltData">
/** Class to store data from a "plt" file, and other data needed,
* for the Paint method */
public static class PltData {
/** the plot file name from which the data in this instance was read. */
public String pltFile_Name;
/** last modification date for the plot file from which the data in this instance was read. */
public java.util.Date fileLastModified;
/** the plot steps (move to / draw to) */
public java.util.ArrayList<PlotStep> pltFileAList = new java.util.ArrayList<PlotStep>();;
/** the texts in the plot */
public java.util.ArrayList<PlotText> pltTextAList = new java.util.ArrayList<PlotText>();
/** the maximum values for x and y in user coordinates (0.1 mm) */
public java.awt.Point userSpaceMax = new java.awt.Point(Integer.MIN_VALUE,Integer.MIN_VALUE);
/** the minimum values for x and y in user coordinates (0.1 mm) */
public java.awt.Point userSpaceMin = new java.awt.Point(Integer.MAX_VALUE,Integer.MAX_VALUE);
public boolean axisInfo = false;
public float xAxisL, yAxisL;
public float xAxis0, yAxis0;
public float xAxisMin, yAxisMin;
public float xAxisMax, yAxisMax;
//these are used when displaying the xy-label
// when the user clicks the mouse button on a diagram
public float xAxisMin_true;
public float xAxisMax_true;
public float yAxisMin_true;
public float yAxisMax_true;
public float xAxisScale;
public float yAxisScale;
//<editor-fold defaultstate="collapsed" desc="class PlotStep">
/** Class to store data to perform either a "move to" or a "draw to" */
public static class PlotStep {
public int i0 = 0;
public int i1 = 0;
public int i2 = 0;
/** Data to perform either a "move to" or a "draw to"
* @param i0 int =0 for "move to" and =1 for "draw to"
* @param i1 int the new x-position
* @param i2 int the new y-position */
public PlotStep(int i0, int i1, int i2) {this.i0 = i0; this.i1 = i1; this.i2 = i2;}
}// class PlotStep
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="class PlotText">
/** Class to store data to draw a text string */
public static class PlotText {
public int i1 = 0;
public int i2 = 0;
public boolean isFormula = false;
/** -1=Left 0=center +1=right */
public int alignment = 0;
public float txtSize = 0.4f;
public float txtAngle = 0f;
public String txtLine;
public int pen = 5;
public int color = 1;
/** Data to draw a text string
* @param i1 int the new x-position
* @param i2 int the new y-position
* @param isFormula boolean
* @param align int alignment: -1=Left, 0=center, +1=right.
* @param txtSize float
* @param txtAngle float
* @param txtLine String
* @param pen int: the pen number
* @param clr int: the colour number */
public PlotText(int i1, int i2, boolean isFormula, int align,
float txtSize, float txtAngle,
String txtLine, int pen, int clr)
{this.i1=i1; this.i2=i2; this.isFormula=isFormula;
alignment = Math.max(-1, Math.min(align, 1));
this.txtSize=txtSize; this.txtAngle=txtAngle; this.txtLine=txtLine;
this.pen=pen; color=clr;}
}// class PlotText
//</editor-fold>
} // class PltData
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="start(PltData, java.io.File)">
/** Open the output plot file; set the PltData for storing the graphic
* @param pD where the graphic information will be stored
* for painting events. If null, the diagram will neither be saved
* nor displayed
* @param plotFile for storing graphic information, it may be "null".
* If an error occurs while opening the file for writing, an exception is
* thrown, the file will not be saved, but the diagram will be displayed.
* @param txtWithFonts true if texts are to be displayed on the JPanel using
* a font, that is, not by using the line-sketches stored in the plot file.<br>
* If true, text sketch information is not stored in the PlotStep ArrayList
* of the PltData instance.
* @throws lib.kemi.graph_lib.GraphLib.OpenPlotFileException */
public void start(PltData pD, java.io.File plotFile, boolean txtWithFonts)
throws WritePlotFileException {
if(pD == null) {return;}
this.pd = pD;
this.textWithFonts = txtWithFonts;
String msg = null;
if(plotFile != null && plotFile.getName().length()>0) {
w = null;
try{
w = new java.io.BufferedWriter(
new java.io.OutputStreamWriter(new java.io.FileOutputStream(plotFile),"UTF8"));
pd.pltFile_Name = plotFile.getPath();
save = true;
} catch (java.io.IOException ex) {
msg = "Error: \""+ex.toString()+"\","+nl+
" in Graphics Library,"+nl+
" while opening output file" +nl+
" \""+plotFile.getPath()+"\"";
pd.pltFile_Name = null;
save = false;}
} else {pd.pltFile_Name = null; save = false;}
if (msg != null) {throw new WritePlotFileException(msg);}
//return;
} //start(pD, plotFile)
public static class WritePlotFileException extends Exception {
public WritePlotFileException() {}
public WritePlotFileException(String txt) {super(txt);}
} //openPlotFileException
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="end()">
/** Close the output plot file;
* Checks that the "user graphic space" is not zero. */
public void end() throws WritePlotFileException {
// check the "UserSpace" dimensions
if(pd.userSpaceMax.x == Integer.MIN_VALUE) {pd.userSpaceMax.x = 2100;}
if(pd.userSpaceMin.x == Integer.MAX_VALUE) {pd.userSpaceMin.x = 0;}
if(pd.userSpaceMax.y == Integer.MIN_VALUE) {pd.userSpaceMax.y = 1500;}
if(pd.userSpaceMin.y == Integer.MAX_VALUE) {pd.userSpaceMin.y = 0;}
float xtra = 0.02f; //add 1% extra space all around
float userSpace_w = Math.abs(pd.userSpaceMax.x - pd.userSpaceMin.x);
int xShift = Math.round(Math.max( (100f-userSpace_w)/2f, userSpace_w*xtra ) );
pd.userSpaceMax.x = pd.userSpaceMax.x + xShift;
pd.userSpaceMin.x = pd.userSpaceMin.x - xShift;
userSpace_w = Math.abs(pd.userSpaceMax.y - pd.userSpaceMin.y);
int yShift = Math.round(Math.max( (100f-userSpace_w)/2f, userSpace_w*xtra ) );
pd.userSpaceMax.y = pd.userSpaceMax.y + yShift;
pd.userSpaceMin.y = pd.userSpaceMin.y - yShift;
try{if(label != null && save) {w.write("0 0 0 "+label+nl);}}
catch(Exception ex) {
save = false;
pd.pltFile_Name = null;
throw new WritePlotFileException("Error: \""+ex.getMessage()+"\","+nl+
" in Graphics Library,"+nl+
" while closing output file" +nl+
" \""+pd.pltFile_Name+"\"");
}
// close output file
if(w != null) {
save = false;
try{w.flush(); w.close();}
catch(Exception ex) {
pd.pltFile_Name = null;
throw new WritePlotFileException("Error: \""+ex.getMessage()+"\","+nl+
" in Graphics Library,"+nl+
" while closing output file" +nl+
" \""+pd.pltFile_Name+"\"");
}
}
//return;
} // end()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="setLabel">
/** A comment to be written to the output file
* @param txt String */
public void setLabel(String txt) throws WritePlotFileException {
if(label != null && save) {
try{w.write("0 0 0 "+label+nl);}
catch(Exception ex) {
save = false;
pd.pltFile_Name = null;
throw new WritePlotFileException("Error: \""+ex.getMessage()+"\","+nl+
" in Graphics Library \"setLabel\","+nl+
" while writing output file" +nl+
" \""+pd.pltFile_Name+"\"");
}
}
label = txt;
//return;
} //setLabel(txt)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="setPen">
/** Set either the "plotter" pen number or the screen colour for
* further painting.
* @param pen int larger than zero to set the plotter pen number;
* zero or negative to set the screen colour */
public void setPen(int pen) throws WritePlotFileException {
int n; int i;
if(pen >=0) {n=8; plotPen = Math.min(pen,9999); i=plotPen;}
else {n=5; screenColour = Math.min(-pen,9999); i=screenColour;}
pd.pltFileAList.add(new PltData.PlotStep(n,i,0));
if(save) {
try{
if(label != null) {
w.write(String.format("%1d%4d %s%n", n,i,label));
label = null;
} else {w.write(String.format("%1d%4d%n", n,i));}
w.flush();
} catch (Exception ex) {
save = false;
pd.pltFile_Name = null;
throw new WritePlotFileException("Error: \""+ex.getMessage()+"\","+nl+
" in Graphics Library \"setPen\","+nl+
" while writing output file" +nl+
" \""+pd.pltFile_Name+"\"");
}
} //if save
} // setPen(pen)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="sym">
/** @param b booleat true if all following calls to "sym" should handle the
* text strings to be plotted (painted) as chemical formulas.
* False to handle all subsequent strings as plain texts. */
public void setIsFormula(boolean b) {isFormula = b;}
/** Display (and save to the output plot file) a text string.
* @param xP float: x-position
* @param yP float: y-position
* @param tHeight float: size of text
* @param t String: text to be displayed
* @param angle float, in degrees
* @param alignment int: -1=left 0=center +1=right
* @param axesCoord boolean: if true the (x,y)-values are taken
* to be in the same scale as previously drawm axes */
public void sym(float xP, float yP, float tHeight, String t, float angle,
int alignment, boolean axesCoord) throws WritePlotFileException {
sym((double)xP, (double)yP, (double)tHeight, t, (double)angle,
alignment, axesCoord);
} //sym(float)
/** Display (and save to the output plot file) a text string.
* @param xP double: x-position
* @param yP double: y-position
* @param tHeight double: size of text (between 0.05 and 99 cm)
* @param t String: text to be displayed
* @param angle double, in degrees,
* internally it will be converted to a value between +180 to -180
* @param alignment int: -1=left 0=center +1=right
* @param axesCoord boolean: if true the (x,y)-values are taken
* to be in the same scale as previously drawm axes */
public void sym(double xP, double yP, double tHeight, String t, double angle,
int alignment, boolean axesCoord) throws WritePlotFileException {
if(t == null) {return;}
if(t.trim().length() < 1) {return;}
if(Math.abs(tHeight) < 0.05) {return;} // less than 0.5 mm size?
// --------------------------
// alignment: -1=Left 0=center +1=right
int align = Math.max(-1, Math.min(alignment, 1));
String txt;
//
sizeSym = Math.min(99,Math.abs(tHeight));
double angleDegr = angle;
//get angle between +180 and -180
while (angleDegr>360) {angleDegr=angleDegr-360;}
while (angleDegr<-360) {angleDegr=angleDegr+360;}
if(angleDegr>180) {angleDegr=angleDegr-360;}
if(angleDegr<-180) {angleDegr=angleDegr+360;}
double angleR = Math.toRadians(angleDegr);
double sCos = sizeSym*Math.cos(angleR);
double sSin = sizeSym*Math.sin(angleR);
double x0 = xP; double y0 = yP;
if(axesCoord) {
if(xL ==0) {xL = 1;}
if(yL ==0) {yL = 1;}
x0 = x0 * xL + xI; y0 = y0 * yL + yI;
} //axesCoord
//---- Remove white space at the start of the String
// by moving the text to the right
int i;
int len = t.length();
for(i=0; i<len; i++) {
if(!Character.isWhitespace(t.charAt(i))) {break;}
}
i = Math.min(i, len-1);
if(i>0) {
t = t.substring(i);
len = t.length();
//move the starting position (all angles are between +180 and -180)
x0 = x0 + i*sCos;
y0 = y0 + i*sSin;}
int isFormulaLen = len;
if(isFormula) {isFormulaLen = isFormulaLength(t);}
//---- If aligned center or right, remove space in formulas
// by moving the text to the right
float diff = (float)(len - isFormulaLen)+0.00001f;
if(align != -1 && isFormula && diff > 0.1) {
if(align == 0) {diff = diff/2f;}
x0 = x0 + diff*sCos;
y0 = y0 + diff*sSin;
} // if align != -1
//---- Write information about the text on the output file
if(save) {
String c; String al;
if(isFormula) {c="C";} else {c=" ";}
if(align == -1) {al="L";} else if(align == +1) {al="R";} else {al="C";}
txt = String.format(engl,
"TextBegin"+c+" size=%7.2f cm, angle=%8.2f, alignment: "+al,sizeSym,angleDegr);
setLabel(txt);}
moveToDrawTo(x0, y0, 0);
if(save) {setLabel(t);} //write the text
int l;
if(isFormula) {l = isFormulaLen;} else {l = len;}
if(CHARACTER_SKETCH) {
sketch(x0,y0,t, angleDegr);
}
if(!CHARACTER_SKETCH || OUTLINE_DRAW) {
int m;
if(OUTLINE_DRAW) {m = 1;} else {m = 0;} //"draw" outline?
moveToDrawTo(x0, y0, 0);
moveToDrawTo(x0+l*sCos, y0+l*sSin, m);
moveToDrawTo(x0+l*sCos-sSin, y0+l*sSin+sCos, m);
moveToDrawTo(x0-sSin, y0+sCos, m);
moveToDrawTo(x0, y0, m);
}
if(save) {
setLabel("TextEnd");
moveToDrawTo(0, 0, 0);
}
//---- save the text in the PltData arrayList
int i2 = Math.round((float)(x0*100));
int i3 = Math.round((float)(y0*100));
i2 = Math.max(-999, Math.min(i2, 9999));
i3 = Math.max(-999, Math.min(i3, 9999));
pd.pltTextAList.add(new PltData.PlotText(i2, i3, isFormula, align,
(float)sizeSym, (float)angleDegr, t, plotPen, screenColour));
//return;
} // sym(x,y,h,txt,a)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="sketch">
//<editor-fold defaultstate="collapsed" desc="sketch data">
// the integers in SK (QnnNN) incorporate three values: the last two digits (NN),
// the previous 2 digits (nn) and an optional flag (Q)
// The last two (NN) are the x-coordinate of the character stroke;
// the previous two digits (nn) are the y-coordinate, and the flag (Q) is
// either "0"= draw to (x,y), "1"= move to (x,y), and
// "2" = draw to (x,y) and end of character
private static final int[] SK =
{10010,9040,70,13060,23020, //A [0-4
10010,9010,9060,8070,6070,5060,5010,15060,4070,1070,60,20010, //B [5-16
18070,9060,9020,8010,1010,20,60,21070, //C [17-24
10010,9010,9050,7070,2070,50,20010, //D [25-31
10070,10,9010,9070,15010,25050, //E [32-37
10010,9010,9070,15010,25050, //F [38-42
18070,9060,9020,8010,1010,20,60,1070,4070,24050, //G [43-52
19010,10,19070,70,15010,25070, //H [53-58
19030,9050,19040,40,10030,20050, //I [59-64
19060,1060,50,20,1010,22010, 19010,10,19060,5010,20070, //J [65-70 K [71-75
19010,10,20070, 10010,9010,5040,9070,20070, //L [76-78 M [79-83
10010,9010,70,29070, //N [84-87
10020,1010,8010,9020,9060,8070,1070,60,20020, //O [88-96
10010,9010,9060,8070,6070,5060,25010, //P [97-103
10020,1010,8010,9020,9060,8070,1070,60,20,12050,20070, //Q [104-114
10010,9010,9060,8070,6070,5060,5010,15050,20070, //R [115-123
11010,20,60,1070,4070,5060,5020,6010,8010,9020,9060,28070, //S [124-135
19010,9070,19040,20040, 19010,1010,20,60,1070,29070, //T [136-139 U [140-145
19010,40,29070, 19010,10,4040,70,29070, //W [146-148 V [149-153
19010,70,10010,29070, 19010,5040,9070,15040,20040, //X [154-157 Y [158-162
19010,9070,10,20070, // Z [163-166
12070,40,20,1010,5010,6035,6070,20070, //a [167-174
16010,6060,5070,1070,60,10,29910, //b [175-181
15070,6060,6020,5010,1010,20,20070, //c [182-188
16070,6020,5010,1010,20,70,29970, //d [189-195
13010,3070,5070,6060,6020,5010,1010,20,20070, //e [196-204
10020,7520,9035,9055,7570,14010,24055, //f [205-211
-12010,-3060,-2070,5070,6060,6020,5010,2010,1020,1060,22070, //g [212-222
10010,9910,16010,6060,5070,20070, //h [223-228
16020,6035,35,10020,50, 18033,8037,8437,8433,28033, //i [229-238
-12010,-3020,-3040,-2050,6050,18550,9050,9055,8555,28550, //j [239-248
10010,9010,13010,6050,14530,20060, //k [249-254
19020,9035,35,10020,20050, //l [255-259
10010,6010,15010,6040,40,15040,6070,20070, //m [260-267
10010,6010,15010,6055,5070,20070, //n [268-273
15070,1070,60,20,1010,5010,6020,6060,25070, //o [274-282
-13010,6010,6060,5070,2070,1060,21010, //p [283-289
-13070,6070,6020,5010,2010,1020,21070, //q [290-296
10010,6010,14510,6040,6060,25070, //r [297-302
11010,20,60,1070,2070,3060,3020,4010,5010,6020,6060,25070, //s [303-314
19030,1030,45,55,1070,16020,26060, //t [315-321
16020,1020,30,60,1070,26070, 16010,40,26070, //u [322-327 v [328-330
16010,20,3040,60,26070, //w [331-335
10010,6070,16010,20070, -13000,-3010,6060,16010,21030, //x [336-339 y [340-344
16010,6070,10,20070, //z [345-348
10020,1010,8010,9020,9060,8070,1070,60,20020, //0 [349-357
17030,9040,40,10030,20050, //1 [358-362
18010,9020,9060,8070,5570,1510,10,20070, //2 [363-370
18010,9020,9060,8070,5570,4560,4520,14560,3570,1070,60,20,21010, //3 [371-383
10060,9060,3010,23070, //4 [384-387
11010,20,60,1070,4070,5060,5010,9010,29070, //5 [388-396
14010,5020,5060,4070,1070,60,20,1010,8010,9020,29060, //6 [397-407
10020,9070,9010,28010, //7 [408-411
15020,4010,1010,20,60,1070,4070,5060,5020,6010,8010,9020,9060,8070,6070,25060, //8 [412-427
10020,10020,60,1070,8070,9060,9020,8010,5010,4020,4060,25070, //9 [428-439
15010,25070, 12040,8040,15010,25070, //- [440-441 + [442-445
15020,5060,13050,7030,17050,23030, 10010,29070, //* [446-451 / [452-453
-11050,40,2530,7030,9540,30550, //( [454-459
-11030,40,2550,7050,9540,30530, //) [460-465
19950,9930,-1030,-21050, -11030,-1050,9950,29930, //[ [466-469 ] [470-473
11520,1565,15520,25565, //= [474-477
-11050,40,4040,5030,6040,9940,31050, //{ [478-484
-11030,40,4040,5050,6040,9940,31030, //} [485-491
10030,40,1040,1030,20030, //. [492-496
-11525,1040,1030,30,-21525, //, [497-501
-11010,2020,6020,12020,1030,1060,2070,6070,12070,21080, //µ(micro) [502-511
19960,7240,9950,29960, 19920,7240,9930,29920, //' [512-515 ` [516-519
19970,7260,9960,9970,19940,7030,9930,29940, //" [520-527
19033,3033,10030,35,535,530,20030, //! [528-534
18010,9020,9060,8070,6070,4040,3040,10040,45,545,540,20040,//? [535-546
-12000,-22099, //_ [547-548
10030,40,1040,1030,30,14030,4040,5040,5030,24030, //: [549-558
-11525,1040,1030,30,-1525,14030,4040,5040,5030,24030, //; [559-568
17070,4010,21070, 11010,4070,27010, //< [569-571 > [572-574
13020,3060,15060,5020,17030,1030,11050,27050, //# [575-582
16010,8010,8030,6030,6010,10010,9070,13070,1070,1050,3050,23070, //% [583-594
14074,550,033,1818,4030,6057,7060,8054,8040,7032,6232,20080, //& [595-606
17020,8530,7060,28570, //~ [607-610
10080,10,9060,20080, //Δ [611-614
19010,20070, 19033,20033, //\ [615-616 | [617-618
17030,9045,27060, //^ [619-621
16030,6040,7050,8050,9040,9030,8020,7020,26030, //° [622-630
10020,1010,7010,8020,8060,7070,1070,60,20, 19230,9220,
9920,9930,9230, 19260,9250,9950,9960,29260, //Ö [631-649
11010,5010,6020,6060,5070,1070,60,20,1010, 17525,
7520,8020,8025,7525, 17560,7555,8055,8060,27560, //ö [650-668
10010,9040,70, 13060,3020, 19247,9233,9933,9947,29247, //Å [669-678
12070,40,20,1010,5010,6035,6070,70, 17552,9052,9038,7538,27552, //å [679-691
10010,9040,70, 13060,3020, 19230,9220,9920,9930,9230,
19260,9250,9950,9960,29260, //Ä [692-706
12070,40,20,1010,5010,6035,6070,70,
17525,7520,8020,8025,7525, 17560,7555,8055,8060,27560, //ä [707-724
13040,7040,15020,5060,11020,21060, //± [725-730
14040,4050,5050,5040,24040, //· [731-735
11010,20,60,1070,4070,5060,5020,6010,8010,9020,9060,8070,
-11040,29940, //$ [736-749
12070,40,30,1020,5020,6035,6070, 10080,1070,6570,7560,7520,
6005,1005,-1020,-21040, //@ [750-765
11010,7070,17010,21070}; //× [766-769]
private int[] ADDRES =
//' ' A B C D E F G H I J K L M N O P Q R
{-1,0,5,17,25,32,38,43,53,59,65,71,76,79,84,88,97,104,115, //0-18
// S T U V W X Y Z a b c d e f g
124,136,140,146,149,154,158,163,167,175,182,189,196,205,212, //19-33
// h i j k l m n o p q r s t u v
223,229,239,249,255,260,268,274,283,290,297,303,315,322,328, //34-48
// w x y z 0 1 2 3 4 5 6 7 8 9 -
331,336,340,345,349,358,363,371,384,388,397,408,412,428,440, //49-63
// + * / ( ) [ ] = { } . , ' " !
442,446,452,454,460,466,470,474,478,485,492,497,512,520,528, //64-78
// ? _ : ; < > # % & ` ~ ^ µ $
535,547,549,559,569,572,575,583,595,516,607,619,502,736, //79-92
//bcksp @ \ | Ö ö Å å Ä ä º ° ± ·
-1,750,615,617, 631,650, 669,679, 692,707,622,622,725,731, //93-106
// • – − µ Δ ∆ ´ ×
731,440,440,502,611,611,512,766}; //107-114
//</editor-fold>
private void sketch(double x0, double y0, String txt, double angleDegr)
throws WritePlotFileException {
//Characters recognized:
char[] CHR =
{' ','A', 'B','C','D','E','F','G','H','I','J','K','L','M','N', // 0-14
'O','P', 'Q','R','S','T','U','V','W','X','Y','Z','a','b','c', //15-29
'd','e', 'f','g','h','i','j','k','l','m','n','o','p','q','r', //30-44
's','t', 'u','v','w','x','y','z','0','1','2','3','4','5','6', //45-59
'7','8', '9','-','+','*','/','(',')','[',']','=','{','}','.', //60-74
',','\'','"','!','?','_',':',';','<','>','#','%','&','`','~', //75-89
'^','μ','$',' ','@','\\','|','Ö','ö','Å','å','Ä','ä', //90-102
'º','°','±','·','•','–','−','µ','Δ','∆','´','×'}; //103-114
int nRecn = CHR.length;
/* to convert a character to ASCII code and back:
* char x = '−';
* int cast = (int)x;
* System.out.println("String.valueOf("+x+") = \""+String.valueOf(x)+"\"");
* int codePoint = String.valueOf(x).codePointAt(0);
* char again = (char)codePoint;
* System.out.printf("x = %s cast = %d codePoint = %d again = %s%n",
* x, cast, codePoint, again);
*/
// Backspace is Ctrl-B (=CHR(93)) bcksp
int bcksp = 2; CHR[93]=(char)bcksp; //Ctrl-B
ADDRES[89]=607; //~
ADDRES[90]=619; //^
ADDRES[92]=736; //$
if(isFormula) {
ADDRES[89]=622; //~ = degree sign
ADDRES[90]=611; //^ = Delta
ADDRES[92]=502; //$ = µ(mu)
} // if isFormula
sketching = textWithFonts;
//---- get super- and sub-scripts for chemical formulas
boolean isFormulaOld = isFormula;
DiagrPaintUtility.ChemFormula cf;
float[] d;
int n = txt.length();
if (isFormula) {
cf = new DiagrPaintUtility.ChemFormula(txt, new float[1]);
DiagrPaintUtility.chemF(cf);
txt = cf.t.toString();
n = txt.length();
d = new float[n];
System.arraycopy(cf.d, 0, d, 0, n);
isFormula = false;
for (int i=0; i<n; i++)
{if(Math.abs(d[i])>0.01f) {isFormula = true;} }
} // isFormula
else {d = new float[n];
for(int i=0; i<n; i++) {d[i]=0f;}}
// ---- Loop through the characters ----
int iNow = -1;
int iCHR;
boolean stopIt;
int action;
double x = 0; double y = 0; double height = sizeSym;
double xPrev; double yPrev;
double xPlt, yPlt, radius, angle;
int iP;
do {
iNow++;
iCHR = 0;
for(int j=0; j<nRecn; j++) {
if(txt.charAt(iNow) == CHR[j]) {iCHR=j; break;}
}
if(isFormula && Math.abs(d[iNow]) >0.01f) {height = 0.8*sizeSym;}
xPrev = x; yPrev = y; stopIt = false;
if(iCHR == 93) { // bcksp
x = -1; y = 0;
}
else if (iCHR == 0 || ADDRES[iCHR] <= -1) { // blank
x = 1; y = 0;
}
else // !(bcksp|blank)
{
iP = ADDRES[iCHR] - 1;
for_j:
for(int j=0; j<3001; j++) { // do all strokes of the sketch
iP++;
x = (double)SK[iP]/100d;
//action = 1 draw to x,y
// = 2 move to x,y
// = 3 draw to x,y and end of character
action = 1;
if(Math.abs(x) > 99.999) {action = 2;}
if(Math.abs(x) > 199.999) {action = 3;}
if(action == 2) { //move to x,y
if(x > 0) {x=x-100;}
if(x < 0) {x=x+100;}
} else if(action == 3) { //draw to x,y and end of character
if(x > 0) {x=x-200;}
if(x < 0) {x=x+200;}
}
y = (int)x;
x = Math.abs(x-y);
y = y/100;
x = x*height + xPrev;
y = y*height + yPrev + d[iNow]*sizeSym;
while(true) {
xPlt =x; yPlt = y;
if(Math.abs(angleDegr) >0.001) {
radius = x*x + y*y;
if(radius > 0) {
radius = Math.sqrt(radius);
angle = Math.asin(y/radius) + Math.toRadians(angleDegr);
xPlt = radius*Math.cos(angle);
yPlt = radius*Math.sin(angle);
} //if radius >0
} // if angleDegr !=0
xPlt = xPlt + x0;
yPlt = yPlt + y0;
if(stopIt) {break for_j;}
int i =1; if(action ==2) {i=0;}
//
moveToDrawTo(xPlt, yPlt, i);
//
if(action != 3) {continue for_j;}
// end of character
x = 1; y=0;
x = x*height + xPrev; y = y*height + yPrev;
stopIt = true;
// action = 2; //move to x,y
} //while(true)
} //for j
} // if !(bcksp|blank)
if(iCHR == 93 || iCHR == 0 || ADDRES[iCHR] <= -1) { // bcksp | blank
x = x * sizeSym + xPrev; y = y * sizeSym + yPrev;
//action = 2; //move to x,y
//xPlt = x; yPlt = y;
if(Math.abs(angleDegr) > 0.001) {
//radius = Math.sqrt(x*x + y*y);
//angle = Math.asin(y/radius) + Math.toRadians(angleDegr);
//xPlt = radius*Math.cos(angle);
//yPlt = radius*Math.sin(angle);
} // if angleDegr !=0
//xPlt = xPlt + x0;
//yPlt = yPlt + y0;
} // if (bcksp|blank)
} while (iNow < (n-1));
isFormula = isFormulaOld;
sketching = false;
//return;
} //sketch
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="moveToDrawTo">
/** "Move to" or "Draw to"
* @param x float, X-position, should be between -9.99 and 99.99
* @param y float, Y-position, should be between -9.99 and 99.99
* @param flag int, must be zero (0) for "move to" or one (1) for "draw to".
* If not =1 then zero is assumed. */
public void moveToDrawTo(float x, float y, int flag) throws WritePlotFileException {
moveToDrawTo((double)x, (double)y, flag);
//return;
} //moveToDrawTo(float)
/** "Move to" or "Draw to"
* @param x double, X-position, should be between -9.99 and 99.99
* @param y double, Y-position, should be between -9.99 and 99.99
* @param flag int, must be zero (0) for "move to" or one (1) for "draw to".
* If not =1 then zero is assumed. */
public void moveToDrawTo(double x, double y, int flag) throws WritePlotFileException {
int i0;
if(flag != 1) {i0 = 0;} else {i0 = 1;}
x = Math.min(99.999, Math.max(-9.999, x));
y = Math.min(99.999, Math.max(-9.999, y));
int i1 = Math.round((float)(x*100));
int i2 = Math.round((float)(y*100));
i1 = Math.max(-999, Math.min(i1, 9999));
i2 = Math.max(-999, Math.min(i2, 9999));
if(i1 == i2Last && i2 == i3Last && label == null) {return;}
i2Last = i1; i3Last = i2;
if(save) {
try{
if(label != null) {
w.write(String.format("%1d%4d%4d %s%n", i0,i1,i2,label));
label = null; }
else {w.write(String.format("%1d%4d%4d%n", i0,i1,i2));}
w.flush();
} catch (Exception ex) {
save = false;
pd.pltFile_Name = null;
throw new WritePlotFileException("Error: \""+ex.getMessage()+"\","+nl+
" in Graphics Library \"moveToDrawTo\","+nl+
" while writing output file" +nl+
" \""+pd.pltFile_Name+"\"");
}
} //if(save)
if(!sketching) {pd.pltFileAList.add(new PltData.PlotStep(i0, i1, i2));}
if(i1<pd.userSpaceMin.x) {pd.userSpaceMin.x = i1;}
if(i1>pd.userSpaceMax.x) {pd.userSpaceMax.x = i1;}
if(i2<pd.userSpaceMin.y) {pd.userSpaceMin.y = i2;}
if(i2>pd.userSpaceMax.y) {pd.userSpaceMax.y = i2;}
//return;
} // moveToDrawTo(x,y,i)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="axes">
/** Display (X,Y)-axes (and save to the output plot file).
* @param xMinI float, minimum X-value. For a log-axis xMinI = log10(min. X-value)
* @param xMaxI float, maximum X-value. For a log-axis xMaxI = log10(max. X-value)
* @param yMinI float, minimum Y-value. For a log-axis yMinI = log10(min. Y-value)
* @param yMaxI float, maximum X-value. For a log-axis yMaxI = log10(max. Y-value)
* @param xOr float, X-position of the axes origin
* @param yOr float, Y-position of the axes origin
* @param xAxL float, length of X-axis
* @param yAxL float, length of Y-axis
* @param size float, size of axes tick labels
* @param logX boolean, true if X-axis should be log10 scale
* @param logY boolean, true if Y-axis should be log10 scale
* @param frame boolean, true for a framed graph, with bottom and top X-axes
* and left and right Y-axes.
* @throws lib.kemi.graph_lib.GraphLib.AxesDataException */
public void axes(float xMinI, float xMaxI, float yMinI, float yMaxI,
float xOr, float yOr, float xAxL, float yAxL, float size,
boolean logX, boolean logY, boolean frame)
throws AxesDataException, WritePlotFileException {
axes((double)xMinI, (double)xMaxI, (double)yMinI, (double)yMaxI,
(double)xOr, (double)yOr, (double)xAxL, (double)yAxL,
(double)size, logX, logY, frame);
} //axes(float)
/** Display (X,Y)-axes (and save to the output plot file).
* @param xMinI double, minimum X-value. For a log-axis xMinI = log10(min. X-value)
* @param xMaxI double, maximum X-value. For a log-axis xMaxI = log10(max. X-value)
* @param yMinI double, minimum Y-value. For a log-axis yMinI = log10(min. Y-value)
* @param yMaxI double, maximum X-value. For a log-axis yMaxI = log10(max. Y-value)
* @param xOr double, X-position of the axes origin
* @param yOr double, Y-position of the axes origin
* @param xAxL double, length of X-axis
* @param yAxL double, length of Y-axis
* @param size double, size of axes tick labels
* @param logX boolean, true if X-axis should be log10 scale
* @param logY boolean, true if Y-axis should be log10 scale
* @param frame boolean, true for a framed graph, with bottom and top X-axes
* and left and right Y-axes.
* @throws lib.kemi.graph_lib.GraphLib.AxesDataException */
public void axes(double xMinI, double xMaxI, double yMinI, double yMaxI,
double xOr, double yOr, double xAxL, double yAxL, double size,
boolean logX, boolean logY, boolean frame)
throws AxesDataException, WritePlotFileException {
// Draw axes.
// The spacing between numbering in the axes can be controlled by the
// variables stpXI,stpYI. Valid input values are 0, 0.5, 1.0 and 2.0
// If zero, standard spacing between axes labels is used.
// Uses logTxt (as well as setIsFormula, sym and moveToDrawTo).
double anglX = 0; double anglY =0; double o = 5.E-6d;
double w;
//Check input values
if(Math.abs(stpXI - 2)>1E-6 && Math.abs(stpXI - 1)>1E-6 &&
Math.abs(stpXI - 0.5)>5E-7 && Math.abs(stpXI - 0.2)>2E-7) {stpXI=0;}
if(Math.abs(stpYI - 2)>1E-6 && Math.abs(stpYI - 1)>1E-6 &&
Math.abs(stpYI - 0.5)>1E-6 && Math.abs(stpYI - 0.2)>1E-6) {stpYI=0;}
xAxL = Math.max(2,Math.min(xAxL, 50));
yAxL = Math.max(2,Math.min(yAxL, 50));
double shift = Math.max(0.1,Math.min(size,0.6));
// ---- DRAW THE AXES
setLabel("-- AXIS --");
setPen(Math.min(-1, screenColour));
double x_Mx = xOr + xAxL; double y_Mx = yOr + yAxL;
String t = String.format(engl,"Size, X/Y length & origo: %7.3f %7.3f %7.3f %7.3f %7.3f",
size,xAxL,yAxL,xOr,yOr);
setLabel(t);
setPen(Math.max(1, plotPen));
t = String.format(engl, "X/Y low and high:%11.4g%11.4g%11.4g%11.4g",
xMinI,xMaxI,yMinI,yMaxI);
setLabel(t);
moveToDrawTo(xOr,y_Mx,0);
moveToDrawTo(xOr,yOr, 1);
moveToDrawTo(x_Mx,yOr,1);
if(frame) {moveToDrawTo(x_Mx,y_Mx,1);
moveToDrawTo(xOr,y_Mx, 1);}
// check for infinity values
double Xmx_i = Math.min(Math.abs(xMaxI),1.e35)*Math.signum(xMaxI);
double Xmn_i = Math.min(Math.abs(xMinI),1.e35)*Math.signum(xMinI);
double Ymx_i = Math.min(Math.abs(yMaxI),1.e35)*Math.signum(yMaxI);
double Ymn_i = Math.min(Math.abs(yMinI),1.e35)*Math.signum(yMinI);
double xPl; double yPl; String txt; boolean b;
double wMn; double wMx; double v; double tl; double rtl; double scaleMaxX = -1;
int j, iStep, k, kAbs, kLength;
boolean xAxis;
// The steps in log-10 scale:
// 2 4 6 10
double[] logSt ={0.3010,0.3010,0.1761,0.2219};
// 2 3 4 5 6 7 8 9 10
double[] logS = {0.301030,0.176091,0.124939,0.096910,0.079181,0.066947,0.057992,0.051153,0.045757};
// use chemical formulas
boolean isFormulaOld = isFormula;
setIsFormula(true);
// ---------------- X-AXIS ----------------
// check that the range is wide enough. If not, try to enlarge it:
boolean xAxisErr = false; String errTxtX = null;
w = Math.abs(Xmx_i - Xmn_i);
if(logX)
{if(w <= 0.5) {if(Xmx_i < Xmn_i) {Xmx_i = Xmx_i - (0.5+o-w);}
else {Xmx_i = Xmx_i + (0.5+o-w);}}}
else //not logX
{if(w < 1.E-30) {if(Xmx_i < Xmn_i) {Xmx_i = Xmx_i - Math.max(Xmx_i*5.01E-4, 1.000001E-30);}
else {Xmx_i = Xmx_i + Math.max(Xmx_i*5.01E-4, 1.000001E-30);}}}
// check that the rage is really OK
w = Math.abs(Xmx_i - Xmn_i);
if(logX) {
if(w < 0.5) {xAxisErr = true;
errTxtX = "abs(xMax-xMin) must be > 0.5";}
} else { //!logX
if(w < 1.E-30) {xAxisErr = true;
errTxtX = "abs(xMax-xMin) must be > 1E-30";}
if(!xAxisErr) {
w = w / Math.max( Math.abs(Xmx_i), Math.abs(Xmn_i) );
if (w <= 4.999999E-4) {xAxisErr = true;
errTxtX = "abs(xMax-xMin)/max(xMax,xMin) must be > 5E-4";}
}
} //logX?
if(!xAxisErr) { //draw labels and tick marks only if the range is large enough
boolean reverseX =false;
if(xMinI > xMaxI) {reverseX =true;}
// X-Scaling Factors
xL = xAxL / (Xmx_i - Xmn_i);
xI = xL * Xmn_i - xOr;
//---- Decide Scale for X-Axis
// expX is the power of ten for the difference
// between xMax and xMin, thus for xMin=10 and xMax=100, expX=1
// while for xMax=1000, expX=2. For xMin=10010 and xMax=10100,
// expX is =1 as well.
double xMa; double xMi; double potX;
long expX = 2 + Math.round( Math.log10(Math.abs(Xmx_i-Xmn_i)) );
while (true) {
expX--;
potX = Math.pow(10,expX);
wMn = (Xmn_i/potX); wMx = (Xmx_i/potX);
if(Math.abs(wMx - wMn) >= 0.999999) {break;}
} //while
long lowX = Math.round( ((Math.abs(wMn)+o) * Math.signum(Xmn_i)) );
if(logX) {lowX = Math.round( (((long)((double)lowX*potX))/potX ));}
if(lowX < 0 && (double)lowX < (wMn-o)) {lowX++;}
double stpX = 1;
w = Math.abs(wMx-wMn);
if(w > 7) {stpX = 2;}
if(logX) {
if(w <= 1.050001) {stpX = 0.2;}
if(expX == 1 && w <= 2.000001) {stpX = 0.2;}
} else {
if(w <= 3.000001) {stpX = 0.5;}
if(w <= 1.400001) {stpX = 0.2;}
}
if(stpXI > 0) {stpX = stpXI;}
double spanX = 0;
if(logX) {spanX = potX * stpX;}
w = 3*o*potX;
if(!reverseX) {xMa = Xmx_i + w; xMi = Xmn_i - w;}
else {xMa = Xmx_i - w; xMi = Xmn_i + w;}
String formX;
if(logX) {formX=" %8.4f";} //width=12
else {
formX = " %8.1f"; //width=9
if((expX == -1 && stpX < 1) || (expX == -2 && stpX >= 1)) {formX=" %8.2f";} //width=10
if((expX == -2 && stpX < 1) || (expX == -3 && stpX >= 1)) {formX=" %8.3f";}//width=11
if(expX == -3 && stpX < 1) {formX=" %8.4f";} //width=12
}
// ---- Write Scale in X-Axis
b = (Math.abs(xMa)<1E5 & Math.abs(xMi)<1E5);
yPl = yOr -(2.2-shift)*size;
xAxis = true;
iStep=0;
j=1; if(expX == -1) {j=10;}
w = -20*stpX;
while (true) {
if(logX && spanX < 1) {
w = w + logSt[iStep]*j;
iStep++;
if(iStep > (logSt.length-1)) {iStep=0;}
} else {w = w + stpX;}
if(!reverseX)
{xPl = lowX + w;}
else { //reverseX:
if(logX && (spanX < 1 && w>1E-4 && w<0.9999))
{xPl = lowX -(1-w);} else {xPl = lowX - w;}
} // reverseX?
if(xPl >= -1E-6) {xPl = xPl + o;} else {xPl = xPl - o;}
v = xPl;
xPl = xPl*potX;
if(!reverseX) {
if(xPl > xMa) {break;}
if(xPl < xMi) {continue;}
} else {
if(xPl < xMa) {break;}
if(xPl > xMi) {continue;}
}
if(expX >= 1 && expX <= 4 && b) {k =(int)xPl;} else {k =(int)v;}
double xPlTxt;
if(!((expX >= 0 || expX < -3) && (stpX > 0.5)) &&
!(expX >= 1 && expX <= 4 && b)) {
if(!(expX >= 0 || expX < -3)) {v = xPl;}
txt = String.format(engl, formX, v);
xPlTxt = xPl*xL-xI - 7.4*size;
} else {
txt = String.format(" %8d", k);
kAbs= Math.abs(k);
if(kAbs < 10) {kLength=1;}
else if(kAbs > 9 && kAbs < 100) {kLength=2;}
else if(kAbs > 99 && kAbs < 1000) {kLength=3;}
else if(kAbs > 999 && kAbs < 10000) {kLength=4;}
else {kLength=5;} //if kAbs > 9999
xPlTxt = xPl*xL-xI - (8.9-((double)kLength/2))*size;
}
rtl = (double)Util.rTrim(txt).length();
if(logX) {
txt = logTxt(txt,xAxis);
rtl = (double)Util.rTrim(txt).length();
int p = txt.indexOf(".");
if(p > -1)
{xPlTxt = (xPl*xL-xI) - ((double)p -0.5) * size;}
else
{tl = (double)txt.trim().length();
xPlTxt = (xPl*xL-xI) - ((rtl-tl) + (tl/2)) * size;} //p > -1 ?
} //logX?
sym(xPlTxt, yPl, size, txt, anglX, 0, false); //align center
scaleMaxX = Math.max(scaleMaxX, ((xPl*xL-xI)+rtl*size));
} //while (true)
// ---- Draw X-Axis Power of 10 (if any)
b = (Math.abs(xMa) < 1.E5 & Math.abs(xMi) < 1.E5);
if(!(expX >= 1 && expX <= 4 && b) &&
!(expX <= 0 && expX >= -3)) {
yPl = yOr-(2.2-shift)*size;
xPl = Math.max(x_Mx,scaleMaxX) +2*size;
//txt = "*10";
//sym(xPl, yPl, size, txt, anglY, 1, false);
//yPl = yPl + size/2;
//if(expX > 9 || expX < -9) {xPl = xPl + size;}
//if(expX > 99 || expX < -99) {xPl = xPl + size;}
//if(expX < 0) {xPl = xPl + size;}
txt = String.format("%4d", expX);
txt = "×10'"+txt.trim()+"`";
sym(xPl, yPl, size, txt, anglX, -1, false);
}
// ---- X-axis divisions
b = false;
if(logX) {b = (spanX <= 2.000001 & expX <= 0);}
iStep=0;
if(reverseX) {iStep = logS.length-1;}
w = -40*stpX;
while (true) {
if(!b) {
w = w +(stpX/2);
} else {
w = w + logS[iStep]/potX;
if(!reverseX) {iStep++;} else {iStep--;}
if(iStep > (logS.length-1)) {iStep = 0;}
if(iStep < 0) {iStep = logS.length-1;}
}
if(!reverseX) {
xPl = (lowX + w)*potX;
if(xPl > xMa) {break;}
if(xPl < xMi) {continue;}
} else {
xPl = (lowX - w)*potX;
if(xPl < xMa) {break;}
if(xPl > xMi) {continue;}
}
xPl = xPl*xL-xI;
v = 0.5;
if((!reverseX && b && iStep == 0) ||
(reverseX && b && iStep == (logS.length-1))) {v = 0.8;}
moveToDrawTo(xPl, yOr, 0);
moveToDrawTo(xPl, yOr+v*size, 1);
if(frame) {moveToDrawTo(xPl, y_Mx, 0);
moveToDrawTo(xPl, y_Mx-v*size, 1);}
} //while (true)
} //if !xAxisErr
// ---------------- Y-AXIS ----------------
// check that the range is wide enough. If not, try to enlarge it:
boolean yAxisErr = false; String errTxtY = null;
w = Math.abs(Ymx_i - Ymn_i);
if(logY)
{if(w <= 0.5) {if(Ymx_i < Ymn_i) {Ymx_i = Ymx_i - (0.5+o-w);}
else {Ymx_i = Ymx_i + (0.5+o-w);}}}
else //not logY
{if(w <1.E-30) {if(Ymx_i < Ymn_i) {Ymx_i = Ymx_i - Math.max(Ymx_i*5.01E-4, 1.000001E-30);}
else {Ymx_i = Ymx_i + Math.max(Ymx_i*5.01E-4, 1.000001E-30);}}}
// check that the rage is really OK
w = Math.abs(Ymx_i - Ymn_i);
if(logY) {
if(w < 0.5) {yAxisErr = true;
errTxtY = "abs(yMax-yMin) must be > 0.5";}
} else { //!logY
if(w < 1.E-30) {yAxisErr = true;
errTxtY = "abs(yMax-yMin) must be > 1E-30";}
if(!yAxisErr) {
w = w / Math.max( Math.abs(Ymx_i), Math.abs(Ymn_i) );
if (w <= 4.999999E-4) {xAxisErr = true;
errTxtY = "abs(yMax-yMin)/max(yMax,yMin) must be > 5E-4";}
}
} //logY?
if(!yAxisErr) { //draw labels and tick marks only if the range is large enough
boolean reverseY =false;
if(yMinI > yMaxI) {reverseY =true;}
// Y-Scaling Factors
yL = yAxL / (Ymx_i - Ymn_i);
yI = yL * Ymx_i - y_Mx;
// ---- Decide Scale for Y-Axis
// expY is the power of ten for the difference
// between yMax and yMin, thus for yMin=10 and yMax=100, expY=1
// while for yMax=1000, expY=2. For yMin=10010 and yMax=10100,
// expY is =1 as well.
double yMa; double yMi;
long expY = 2 + Math.round( Math.log10(Math.abs(Ymx_i-Ymn_i)) );
double potY;
while (true) {
expY--;
potY = Math.pow(10,expY);
wMn = (Ymn_i/potY); wMx = (Ymx_i/potY);
if(Math.abs(wMx - wMn) >= 0.999999) {break;}
} //while
long lowY = Math.round( (Math.abs(wMn)+o) * Math.signum(Ymn_i) );
if(logY) {lowY = Math.round( ((long)((double)(lowY)*potY))/potY );}
if(lowY < 0 && (double)lowY < (wMn-o)) {lowY++;}
double stpY = 1;
w = Math.abs(wMx-wMn);
if(w > 7) {stpY = 2;}
if(logY) {
if(w <= 1.050001) {stpY = 0.2;}
if(expY == 1 && w <= 2.000001) {stpY = 0.2;}
} else {
if(w <= 3.000001) {stpY = 0.5;}
if(w <= 1.400001) {stpY = 0.2;}
}
if(stpYI > 0) {stpY = stpYI;}
double spanY = 0;
if(logY) {spanY = potY * stpY;}
w = 3*o*potY;
if(!reverseY) {yMa = Ymx_i + w; yMi = Ymn_i - w;}
else {yMa = Ymx_i - w; yMi = Ymn_i + w;}
String formY;
if(logY) {formY=" %8.4f";}
else{
formY = " %8.1f";
if((expY == -1 && stpY < 1) || (expY == -2 && stpY >= 0.999999)) {formY=" %8.2f";}
if((expY == -2 && stpY < 1) || (expY == -3 && stpY >= 0.999999)) {formY=" %8.3f";}
if((expY == -3 && stpY < 1) ) {formY=" %8.4f";}
}
// ---- Wrtie Scale in Y-Axis
b =(Math.abs(yMa)<1.E5 & Math.abs(yMi)<1.E5);
xAxis=false;
iStep=0;
j=1; if(expY == -1) {j=10;}
w = -20*stpY;
while (true) {
if(logY && spanY < 1) {
w = w + logSt[iStep]*j;
iStep++;
if(iStep > (logSt.length-1)) {iStep=0;}
} else {w = w + stpY;}
if(!reverseY)
{yPl = lowY + w;}
else {//reverseY:
if((logY && spanY < 1) && (w>1E-4 && w<0.9999))
{yPl = lowY - (1-w);} else {yPl = lowY - w;}
} //reverseY?
if(yPl >= -1E-6) {yPl = yPl +o;} else {yPl = yPl -o;}
v = yPl;
yPl = yPl*potY;
if(!reverseY) {
if(yPl > yMa) {break;}
if(yPl < yMi) {continue;}
} else {
if(yPl < yMa) {break;}
if(yPl > yMi) {continue;}
}
if(expY >= 1 && expY <= 4 && b) {k =(int)yPl;} else {k =(int)v;}
if(!((expY >= 0 || expY < -3) && (stpY > 0.5)) &&
!(expY >= 1 && expY <= 4 && b)) {
if(!(expY >= 0 || expY < -3)) {v=yPl;}
txt = String.format(engl, formY, v);
} else {
txt = String.format(" %8d", k);
}
if(logY) {txt = logTxt(txt,xAxis);}
yPl = yPl*yL-yI - size/2;
if(yPl < yOr) {yPl = yPl +0.6*size;}
xPl = xOr - ((Util.rTrim(txt).length() +1) - shift) * size;
sym(xPl, yPl, size, txt, anglY, 1, false); //align right
} //while (true)
// ---- Draw Y-Axis Power of 10 (if any)
b = (Math.abs(yMa) < 1.E5 & Math.abs(yMi) < 1.E5);
if(!(expY >= 1 && expY <= 4 && b) &&
!(expY <= 0 && expY >= -3)) {
xPl = xOr;
yPl = y_Mx +0.8*size;
//txt = "*10";
//sym(xPl, yPl, size, txt, anglY, 1, false);
//yPl = yPl + size/2;
//if(expY > 9 || expY < -9) {xPl = xPl + size;}
//if(expY > 99 || expY < -99) {xPl = xPl + size;}
//if(expY < 0) {xPl = xPl + size;}
txt = String.format("%4d", expY);
txt = "×10'"+txt.trim()+"`";
sym(xPl, yPl, size, txt, anglY, -1, false);
}
// ---- Y-axis divisions
b = false;
if(logY) {b = (spanY <= 2.000001 & expY <= 0);}
iStep=0;
if(reverseY) {iStep = logS.length-1;}
w = -40*stpY;
while (true) {
if(!b) {
w = w + (stpY/2);
} else {
w = w + logS[iStep]/potY;
if(reverseY) {iStep--;} else {iStep++;}
if(iStep > (logS.length-1)) {iStep=0;}
if(iStep < 0) {iStep = logS.length-1;}
}
if(!reverseY) {
yPl = (lowY + w)*potY;
if(yPl > yMa) {break;}
if(yPl < yMi) {continue;}
} else {
yPl = (lowY - w)*potY;
if(yPl < yMa) {break;}
if(yPl > yMi) {continue;}
}
yPl = yPl*yL-yI;
v = 0.5;
if((!reverseY && b && iStep == 0) ||
(reverseY && b && iStep == (logS.length-1))) {v = 0.8;}
moveToDrawTo(xOr, yPl, 0);
moveToDrawTo(xOr+v*size, yPl, 1);
if(frame) {moveToDrawTo(x_Mx, yPl, 0);
moveToDrawTo(x_Mx-v*size, yPl, 1);}
} // while (true)
} //if !yAxisErr
// errors?
if(xAxisErr) {
throw new AxesDataException ("Error: can Not draw X-axis - range too narrow"+nl
+ errTxtX);}
if(yAxisErr) {
throw new AxesDataException ("Error: can Not draw Y-axis - range too narrow"+nl
+ errTxtY);}
// reset character set
setIsFormula(isFormulaOld);
// set limits for clip-window when drawing lines with method "line"
double x = Math.min(Xmn_i,Xmx_i); double y = Math.min(Ymn_i,Ymx_i);
double width = Math.max(Xmx_i,Xmn_i) - x;
double height = Math.max(Ymx_i,Ymn_i) - y;
clippingArea = new java.awt.geom.Rectangle2D.Double(x,y,width,height);
//return;
} //axes
//<editor-fold defaultstate="collapsed" desc="AxesDataException">
public class AxesDataException extends Exception {
public AxesDataException() {}
public AxesDataException(String txt) {super(txt);}
} //DataFileException
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="logTxt">
/** Convert a tick label representing a log10-value, for example "23", to a
* non-log10 representation, that is, "10'23`". Input values between -3 and +3
* are converted to: 0.001, 0.01, ... , 100, 1000.<br>
* Floating point numbers with a fractional part: If the input value
* is n.301, n.6021 or n.7782 (or -n.6990, -n.3979, -n.2219) then
* the output is "2.10'n`", "4.10'n`", "6.10'n`" (or "2.10'(n-1)`" etc).
* For example, "-3.398" is converted to "4.10'-4`".<br>
* If the input text contains any other fractional part ("n.m") then output text
* is: "10'n.m`".
*
* @param cDum String: on input it contains the value to be plotted as an axis
* tick label; for example "5" or "5.0".
* @param xAxis boolean =true if the String cDum will be used as an X-axis tick
* label, =false for Y-axis tick labels. Y-axis labels are right-adjusted.
* @return String tick label
*/
private String logTxt(String cDum, boolean xAxis) {
String[] numb = {"0","1","2","3","4","5","6"};
// 012345678901234567
StringBuilder form = new StringBuilder(" %1d'.`10'%1d`");
boolean integr; double w; long k; int coef; int exponent; int width;
integr = true; coef =1;
//-- check for real or integer
for(int n = 0; n < cDum.length(); n++)
{ if(cDum.charAt(n) == '.') {integr = false; break;} } //for n
if(integr) {k = Long.parseLong(cDum.trim()); w = (double)k;}
else {w = Double.parseDouble(cDum.trim()); k = (long)w;}
if(!integr) { // -- Floating point values:
width = 1;
if(w > 9.99999 || w < -9.1) {width = 2;}
if(w > 99.99999 || w < -99.1) {width = 3;}
if(w < 0) {width++;}
form.replace(15, 16, numb[width]); //width might be 1,2,3 or 4
if(!xAxis) {form.delete(0,width);} //shorten the output string
if(w > 0.) {exponent = (int)(w+0.00001);}
else {exponent = (int)(w-0.00001);}
w = w - exponent;
if(w < -3.E-5) {
//if w was negative; for example -5.699: convert -0.699 to +0.301
w = w +1; exponent--;
}
if(w <= 3.E-5) { //it is an exact power of ten, write it as 10'exponent`
cDum = String.format(" %8d", exponent);
} else { //w > 3.E-5; get the coef, to write for example 2.10'-5`
coef = -1;
if(Math.abs(w-0.3010) <=(Math.max(Math.abs(w),Math.abs(0.3010))*1E-4)) {coef=2;}
if(Math.abs(w-0.6020) <=(Math.max(Math.abs(w),Math.abs(0.6020))*1E-4)) {coef=4;}
if(Math.abs(w-0.7781) <=(Math.max(Math.abs(w),Math.abs(0.7781))*1E-4)) {coef=6;}
if(coef <=0) { //this should not happen
//System.err.println("Error in logTxt: w,exponent= "+w+", "+exponent);
coef = 2;
}
if(coef > 0 && Math.abs(exponent) > 3) {
cDum = String.format(form.toString(), coef, exponent);
//length=13, for example: " 2'.`10'3`"; width=5
return cDum;}
} //if w <= 3.E-5
} //if not integr
else { //if !integr
exponent = (int)k;
} // integr?
//-- Integers & exact floats below -3 or above 3 (below 0.001 or above 1000)
if(Math.abs(exponent) > 3 | coef < 0) {
// get first non-blank
int n;
for(n =0; n < cDum.length(); n++) {
if(cDum.charAt(n) != ' ') {break;} }//for n
//n = Math.max(3, Math.min(n, cDum.length()));
// and insert 10' at the begining
if(n <3) {cDum = "10'" + cDum.substring(n);}
else {cDum = cDum.substring(0, n-3) + "10'" + cDum.substring(n);}
// insert "`" at the UserSpaceMin
// get last non-blank
int len;
for(len = cDum.length()-1; len >= 0; len--)
{ if(cDum.charAt(len) != ' ') {break;} }//for len
if(len <0) {len=0;}
cDum = cDum.substring(0,len+1)+"`";
return cDum;
} //if abs(exponent)>3 or coef < 0
//-- Integers & floats between -3 and 3 (between 0.001 and 1000)
String cDum1 = " ";
if(exponent == -3) {cDum1="0.001";}
else if(exponent == -2) {cDum1=" 0.01";}
else if(exponent == -1) {cDum1=" 0.1";}
else if(exponent == 0) {cDum1=" 1";}
else if(exponent == 1) {cDum1=" 10";}
else if(exponent == 2) {cDum1=" 100";}
else if(exponent == 3) {cDum1=" 1000";}
// write for example 0.02, 0.04 etc
if(xAxis) {
if(integr) {
if(exponent == -3 || exponent == -2) cDum = " "+cDum1;
if(exponent == 0 || exponent == 1) cDum = " " +cDum1;
if(exponent == -1 || exponent == 2 ||
exponent == 3) cDum = " " +cDum1;
return cDum;
}
if(exponent == -3 || exponent == -2) cDum = " " +cDum1;
if(exponent == 0 || exponent == 1) cDum = " " +cDum1;
if(exponent == -1 || exponent == 2 ||
exponent == 3) cDum = " " +cDum1;}
else {//not xAxis
cDum = " " +cDum1;
} //xAxis
if(integr) return cDum;
// Substitute the "1", in for example "0.1" or "100", for the correct number
for(int n =0; n < cDum.length(); n++) {
if(cDum.charAt(n) == '1') {
cDum = cDum.substring(0,n)+ numb[coef] + cDum.substring(n+1);
break;}
}
return cDum;
} // logTxt()
//</editor-fold>
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="isFormulaLength">
/**
* @param cDum String
* @return the length of the text string without leading or
* trailing white space and without counting the characters "'", "´" or "`".
* For example for "10'4`" returns 3.
* In addition for a "simple" chemical name with charge, removes from the length any
* space associated with the charge. For example for "H +" returns 2, and
* for "CO3 2-" returns 5. Note however that for "(CO3 2-)" it returns 8.
*/
public static int isFormulaLength(String cDum) {
cDum = cDum.trim();
int len = cDum.length();
if(len<=0) {return 0;}
int start, nbr, i;
nbr = 0;
i=Math.max(cDum.indexOf("+"),Math.max(cDum.indexOf("-"),
// Unicode En Dash and Minus Sign
Math.max(cDum.indexOf('\u2013'),cDum.indexOf('\u2212'))));
if(i>=(len-3) && i>1) { //found + or - at the right place
if(i==(len-1) && len >2) {
if(Character.isWhitespace(cDum.charAt(i-1))) {nbr++;} //"H +"
else if(len >3 && cDum.charAt(i-1)>='2'&& cDum.charAt(i-1)<='9'
&& Character.isWhitespace(cDum.charAt(i-2))) {nbr++;} //"S 2-"
if(len >4 && cDum.charAt(i-1)>='0'&& cDum.charAt(i-1)<='9'
&& cDum.charAt(i-2)>='1'&& cDum.charAt(i-2)<='9'
&& Character.isWhitespace(cDum.charAt(i-3))) {nbr++;} //"S 12-"
}
else
if(len >3 && i==(len-2) && Character.isWhitespace(cDum.charAt(i-1))
&& (cDum.charAt(i+1)>='2'&& cDum.charAt(i+1)<='9')) //"S -2"
{nbr++;}
else
if(len>4 && i==(len-3) && Character.isWhitespace(cDum.charAt(i-1))
&& (cDum.charAt(i+1)>='1'&& cDum.charAt(i+1)<='9')
&& (cDum.charAt(i+2)>='0'&& cDum.charAt(i+2)<='9')) //"S -12"
{nbr++;}
} // found + or -
start = 0;
while(true) {
i=cDum.indexOf("'", start);
if(i<0) {break;}
nbr++; start = i+1;
if(start > len) {break;}
}
start = 0;
while(true) {
i=cDum.indexOf("´", start);
if(i<0) {break;}
nbr++; start = i+1;
if(start > len) {break;}
}
start = 0;
while(true) {
i=cDum.indexOf("`", start);
if(i<0) {break;}
nbr++; start = i+1;
if(start > len) {break;}
}
len = len - nbr;
return len;
} // isFormulaLength(String)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="line">
/** Set the style for the lines drawn using the method "line"
* @param lineStyle int 0=continous, 1-5=dashed. */
public void lineType(int lineStyle) throws WritePlotFileException {
this.lineStyle = Math.max(0,Math.min(5,lineStyle));
if(nDash !=0) {dashIt();}
nDash = 0;
if(lineStyle ==1) {dash[0]=0.35; dash[1]=0.25; dash[2]=0; dash[3]=0;}
else if(lineStyle ==2) {dash[0]=0.20; dash[1]=0.30; dash[2]=0; dash[3]=0;}
else if(lineStyle ==3) {dash[0]=0.30; dash[1]=0.10; dash[2]=0; dash[3]=0;}
else if(lineStyle ==4) {dash[0]=0.30; dash[1]=0.20; dash[2]=0.07; dash[3]=0.2;}
else if(lineStyle ==5) {dash[0]=0.07; dash[1]=0.20; dash[2]=0; dash[3]=0;}
else {dash[0]=0; dash[1]=0; dash[2]=0; dash[3]=0;}
//return;
} //lineType(int)
/** Draw a line using the type (continuous or dashed) specified by
* previous call to lineType(i).
* @param x double[] x-coordinates
* @param y double[] y-coordinates */
public void line(double[] x, double[] y) throws WritePlotFileException {
int n = Math.min(x.length, y.length);
if(n <=1) {return;}
double oldX = Double.NEGATIVE_INFINITY;
double oldY = Double.NEGATIVE_INFINITY;
double x1; double y1;
double x2=Double.NaN; double y2=Double.NaN;
java.awt.geom.Line2D lineToClip;
// draw the line
for(int j = 1; j < n; j++) {
x1 = x[j-1]; y1 = y[j-1];
x2 = x[j]; y2 = y[j];
lineToClip = new java.awt.geom.Line2D.Double(x1,y1, x2,y2);
lineToClip = myClip(lineToClip, clippingArea);
if(lineToClip == null) {continue;}
x1 = lineToClip.getX1(); y1 = lineToClip.getY1();
x2 = lineToClip.getX2(); y2 = lineToClip.getY2();
if(oldX != x1 || oldY != y1) {
x1 = x1*xL-xI; y1 = y1*yL-yI;
lineMoveToDrawTo(x1,y1,0);
}
oldX = x2; oldY = y2;
x2 = x2*xL-xI; y2 = y2*yL-yI;
lineMoveToDrawTo(x2,y2,1);
} //for j
//if a dash line has been plotted: close and draw
if(!Double.isNaN(x2) && !Double.isNaN(y2)) {lineMoveToDrawTo(x2,y2,0);}
//return;
} //line(double[],double[])
//<editor-fold defaultstate="collapsed" desc="line methods">
// fields used in dash lines
private int lineStyle = 0;
private int nDash = 0;
private double[] xDash = new double[100];
private double[] yDash = new double[100];
private double[] dash = {0,0,0,0};
//<editor-fold defaultstate="collapsed" desc="dash-line methods">
private void lineMoveToDrawTo(double x, double y, int n) throws WritePlotFileException {
if(lineStyle == 0) {moveToDrawTo(x, y, n); return;}
if(n == 0 && nDash >0) {dashIt();}
nDash++;
xDash[nDash-1] = x; yDash[nDash-1] = y;
if(nDash >= xDash.length-1) {dashIt();}
//return;
} //lineMoveToDrawTo(x,y,n)
private void dashIt() throws WritePlotFileException {
if(nDash <=1) {nDash=0; return;}
boolean down;
double xP = xDash[0]; double yP = yDash[0];
double xOld = xP; double yOld = yP;
double cuLength = 0;
double x; double y;
int k;
for(k = 0; k < nDash-1; k++) {
x = xDash[k+1]-xDash[k];
y = yDash[k+1]-yDash[k];
cuLength = cuLength + Math.sqrt(x*x + y*y);
} //for k
double dLength = dash[0]+dash[1]+dash[2]+dash[3];
int noDash = (int)((cuLength-dash[0])/dLength);
if(noDash <=0) {
for(k=0; k < nDash-1; k++) {
xP = xDash[k+1]; yP=yDash[k+1];
moveToDrawTo(xOld, yOld, 0);
moveToDrawTo(xP, yP, 1);
xOld = xP; yOld = yP;
} //for k
nDash = 0; return;
} //if noDash <=0
double f = noDash * dLength /(cuLength-dash[0]);
double[] dash2 = {0,0,0,0};
dash2[0] = dash[0]/f; dash2[1] = dash[1]/f;
dash2[2] = dash[2]/f; dash2[3] = dash[3]/f;
double del; double left; double lenP;
double incr; double l; double d22;
k =0;
down = true;
while(down) {
for(int i =0; i < 4; i++) {
del = dash2[i]; left = del;
lenP = 0;
while((lenP < del) && (k < nDash-1)) {
x = xDash[k+1] - xP;
y = yDash[k+1] - yP;
incr = Math.sqrt(x*x + y*y);
lenP = lenP + incr;
if(lenP < del) {
k++;
xP = xDash[k]; yP = yDash[k];
if(down) {
moveToDrawTo(xOld, yOld, 0);
moveToDrawTo(xP, yP, 1);
} //if down
xOld = xP; yOld = yP;
left = left - incr;
} //if(lenP < del)
} //while (lenP < del) & (k < nDash)
if(del < lenP) {
l = lenP - del;
d22 = left/(left + l);
xP = xP + d22*(xDash[k+1]-xP); yP = yP + d22*(yDash[k+1]-yP);
if(down) {moveToDrawTo(xOld, yOld, 0);
moveToDrawTo(xP, yP, 1);}
xOld = xP; yOld = yP;
}//if(del < lenP)
down = !down;
if(k >= (nDash-1)) {nDash = 0; return;}
} //for i
} //while(down)
nDash = 0;
//return;
} //dashIt()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Cohen-Sutherland Clip">
//<editor-fold defaultstate="collapsed" desc="class CodeData">
/** Class used to retrieve information from method "code" */
private class CodeData {
int c = 0; int i1 = 0; int i2 = 0; int i3 = 0; int i4 = 0;
CodeData(int c, int i1, int i2, int i3, int i4)
{this.c = c; this.i1=i1; this.i2=i2; this.i3=i3; this.i4=i4;}
CodeData() {}
} // class CodeData
//</editor-fold>
/** Clip with the Cohen-Sutherlands method.
* @param lineToClip Line2D
* @param clippingArea Rectangle2D
* @return Line2D: the "lineToClip" clipped into the "clippingArea"
*/
private java.awt.geom.Line2D myClip(java.awt.geom.Line2D lineToClip,
java.awt.geom.Rectangle2D clippingArea) {
double x1, y1, x2, y2;
x1= lineToClip.getX1(); y1= lineToClip.getY1();
x2= lineToClip.getX2(); y2= lineToClip.getY2();
java.awt.geom.Line2D lineClipped;
CodeData cd1 = new CodeData();
CodeData cd2 = new CodeData();
cd1 = code(x1,y1, cd1, clippingArea);
cd2 = code(x2,y2, cd2, clippingArea);
while (true) {
if(cd1.c == 0 && cd2.c == 0) { //Draw the line
lineToClip = new java.awt.geom.Line2D.Double(x1,y1, x2,y2);
return lineToClip;
}
if(bitMultipl(cd1.i1, cd2.i1, cd1.i2, cd2.i2,
cd1.i3, cd2.i3, cd1.i4, cd2.i4) !=0) {
return null; //Do Not draw the line
}
int c = cd1.c;
if(c ==0) {c = cd2.c;}
double x = x1, y = y1;
if(c >= 1000) {
x = x1+(x2-x1)*(clippingArea.getMaxY()-y1)/(y2-y1);
y = clippingArea.getMaxY();
}
if(c < 1000 && c >= 100) {
x = x1+(x2-x1)*(clippingArea.getMinY()-y1)/(y2-y1);
y = clippingArea.getMinY();
}
if(c < 100 && c >= 10) {
y = y1+(y2-y1)*(clippingArea.getMaxX()-x1)/(x2-x1);
x = clippingArea.getMaxX();
}
if(c < 10) {
y = y1+(y2-y1)*(clippingArea.getMinX()-x1)/(x2-x1);
x = clippingArea.getMinX();
}
if(c != cd2.c) {
x1 = x; y1 = y;
cd1 = code(x1,y1, cd1, clippingArea);
} else {
x2 = x; y2 = y;
cd2 = code(x2,y2, cd2, clippingArea);
}
} //while(true)
} // myClip
private CodeData code(double x, double y, CodeData cd,
java.awt.geom.Rectangle2D clippingArea) {
cd.c = 0; cd.i1 =0; cd.i2 =0; cd.i3 =0; cd.i4 =0;
if(x < clippingArea.getMinX()) {cd.c =1; cd.i1 =1;}
if(x > clippingArea.getMaxX()) {cd.c =10; cd.i2 =1;}
if(y < clippingArea.getMinY()) {cd.c =cd.c+100; cd.i3 =1;}
if(y > clippingArea.getMaxY()) {cd.c =cd.c+1000; cd.i4 =1;}
return cd;
} //code
private int bitMultipl(int i1_1, int i1_2, int i2_1, int i2_2,
int i3_1, int i3_2, int i4_1, int i4_2) {
int bitMult =0;
if((i1_1 !=0 && i1_2 !=0) ||
(i2_1 !=0 && i2_2 !=0) ||
(i3_1 !=0 && i3_2 !=0) ||
(i4_1 !=0 && i4_2 !=0)) {bitMult =1;}
return bitMult;
} //bitMultipl
//</editor-fold>
//</editor-fold>
//</editor-fold>
} | 65,320 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
DiagrPaintUtility.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibChemDiagr/src/lib/kemi/graph_lib/DiagrPaintUtility.java | package lib.kemi.graph_lib;
import lib.common.Util;
/** Paints a graphic context (for example a JPanel or a Printer)
* using the data stored in a PltData object.
*
* Copyright (C) 2014-2015 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class DiagrPaintUtility {
public static final int MAX_COLOURS = 11;
public java.awt.Color[] colours =
{new java.awt.Color(0,0,0), //black
new java.awt.Color(255,35,35), //red
new java.awt.Color(149,67,0), //vermilion
new java.awt.Color(47,47,255), //light blue
new java.awt.Color(0,151,0), //green
new java.awt.Color(200,140,0), //orange
new java.awt.Color(255,0,255), //magenta
new java.awt.Color(0,0,128), //blue
new java.awt.Color(128,128,128),//gray
new java.awt.Color(0,166,255), //sky blue
new java.awt.Color(128,0,255)};//violet
/** 0-2: Colour; BW (black/white); WB (white/black) */
public int colourType = 0;
public boolean useBackgrndColour = false;
public java.awt.Color backgrnd = java.awt.Color.WHITE;
public boolean printColour = true;
public boolean printHeader = true;
/** 0 = OFF; 1 = ON; 2 = DEFAULT */
public int antiAliasing = 1;
/** 0 = OFF; 1 = ON; 2 = DEFAULT */
public int antiAliasingText = 0;
public boolean fixedSize = false;
public float fixedSizeWidth = 21f;
public float fixedSizeHeight = 15f;
public boolean keepAspectRatio = false;
public float penThickness = 1;
public float printPenThickness = 1;
public int fontSize = 8;
/** 0-4: Serif, SansSerif, Monospaced, Dialog, DialogInput */
public int fontFamily = 1;
/** 0-2: PAIN, BOLD, ITALIC */
public int fontStyle = 0;
/** true if texts are to be displayed on the JPanel using a font, that is,
* not by using the line-sketches stored in the plot file. */
public boolean textWithFonts = true;
//<editor-fold defaultstate="collapsed" desc="class ChemFormula">
/** Class used for input and output from method "chemF" */
static class ChemFormula {
/** t is a StringBuffer with the initial chemical formula given
* to method "chemF", and it will be modified on return
* from chemF, for example "Fe+2" may be changed to "Fe2+". */
StringBuffer t;
/** d float[] returned by method "chemF" with
* super- subscript data for each character position
* in the StringBuffer t returned by chemF. */
float[] d;
/** @param txt String
* @param d_org float[] */
ChemFormula(String txt, float[] d_org) { // constructor
t = new StringBuffer();
//if (t.length()>0) {t.delete(0, t.length());}
t.append(txt);
int nChar = txt.length();
d = new float[nChar];
System.arraycopy(d_org, 0, d, 0, d_org.length); }
} // class ChemFormula
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="class FontInfo">
/** Class used to store information: input and output for method "changeFont".
* Having this class avoids creating new instances of font and fontmetrics
* every time the size is changed. */
private class FontInfo {
java.awt.Font f;
java.awt.FontMetrics fm;
float fontScale;
float txtSize;
float oldTxtSize = Float.MIN_VALUE;
/** a rectangle to store temporary information */
java.awt.geom.Rectangle2D rect;
/** width of an "H" */
float width_H;
/** Class used to store information: input and output from
* method "changeFont".
* @param fnt
* @param fmtr
* @param fontScale
* @param txtSize; the height and width of text in cm
* @param rect a rectangle to store temporary information
* @param widthH float the width of a capital letter "H" */
FontInfo(java.awt.Font fnt, java.awt.FontMetrics fmtr,
float fontScale, float txtSize,
java.awt.geom.Rectangle2D rect, float widthH) { // constructor
this.f = fnt;
this.fm = fmtr;
this.fontScale = fontScale;
this.txtSize = txtSize;
this.oldTxtSize = Float.MIN_VALUE;
this.rect = rect;
this.width_H = widthH;}
FontInfo() { // constructor
f = new java.awt.Font("Monospaced", java.awt.Font.PLAIN, fontSize);
fm = null;
fontScale = Float.NaN;
txtSize = 0.35f;
oldTxtSize = Float.MIN_VALUE;
rect = null;
width_H = 12f;}
} // class FontInfo
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="paintDiagram">
/** Paints a diagram into graphics context "g2D" using the data
* in an object of class PltData
@param g2D Graphics2D context
@param compDim Dimension of the Component to be painted
@param pltD PltData containing the data needed to plot the diagram
@param printing boolean (printing or painting on the screen?) */
public void paintDiagram (java.awt.Graphics2D g2D,
java.awt.Dimension compDim,
GraphLib.PltData pltD, boolean printing) {
if (compDim.width <=5 || compDim.height <=5) {return;}
int i1, i2;
GraphLib.PltData.PlotStep ps;
GraphLib.PltData.PlotText pt;
int x_min; int x_max; int y_min; int y_max;
if(pltD == null || (fixedSize && !keepAspectRatio && !printing)) {
x_min = -10; y_min = -10; // = -1mm
x_max = Math.round(fixedSizeWidth*100f)+10; //add 1mm
y_max = Math.round(fixedSizeHeight*100f)+10;
} else {
x_min = pltD.userSpaceMin.x; x_max = pltD.userSpaceMax.x;
y_min = pltD.userSpaceMin.y; y_max = pltD.userSpaceMax.y;
}
if(keepAspectRatio || printing)
{if (Math.abs((float)compDim.width / (float)(x_max - x_min)) <
Math.abs((float)compDim.height / (float)(y_max - y_min)))
{y_max = 10 + Math.round((float)x_max * (float)compDim.height/(float)compDim.width);}
else
{x_max = 10 + Math.round((float)y_max * (float)compDim.width/(float)compDim.height);}
} // if keepAspectRatio
//System.out.println("The JPanel dimmension: width = "+compDim.getWidth()+", heght = "+compDim.getHeight());
float xScale, yScale; int xScale0, yScale0;
float userWidth = (float)Math.abs(x_max - x_min);
float userHeight = (float)Math.abs(y_max - y_min);
xScale = (float)compDim.width / userWidth;
yScale = (float)compDim.height / userHeight;
//System.out.println("The user space is:\n"+
// " x-min = "+x_min+", x-max = "+x_max+", y-min = "+y_min+", y-max = "+y_max+
// " x-range = "+((int)userWidth)+", y-range = "+((int)userHeight)+"\n");
if(pltD == null) {
xScale0 = Math.round(-10f*xScale);
yScale0 = Math.round(-10f*yScale);
} else {
xScale0 = Math.round((float)pltD.userSpaceMin.x*xScale);
yScale0 = Math.round((float)pltD.userSpaceMin.y*yScale);
}
//---- paint background
if(printing) {
if(printColour) {
g2D.setColor(backgrnd);
g2D.fillRect(0, 0, compDim.width, compDim.height);
g2D.setColor(java.awt.Color.BLACK);}
}
else // not printing
{// background colour
switch (colourType)
{case 1: // BW (black on white)
g2D.setColor(java.awt.Color.WHITE);
g2D.fillRect(0, 0, compDim.width, compDim.height);
g2D.setColor(java.awt.Color.BLACK);
break;
case 2: // WB (white on black)
g2D.setColor(java.awt.Color.BLACK);
g2D.fillRect(0, 0, compDim.width, compDim.height);
g2D.setColor(java.awt.Color.WHITE);
break;
default:
if(useBackgrndColour) {
g2D.setColor(backgrnd);
g2D.fillRect(0, 0, compDim.width, compDim.height);
}
g2D.setColor(java.awt.Color.BLACK);
} // switch
} // if printing and colour printing
//---- if Printing: Header with file name
// get a font
java.awt.Font f = new java.awt.Font("Monospaced", java.awt.Font.PLAIN, 7);
g2D.setFont(f);
// print Header with file name
if(printing && printHeader) {
g2D.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING,
java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
//get the size of an upper case "H"
final float H = 1.2f*(float)g2D.getFontMetrics().getStringBounds("H", g2D).getWidth();
g2D.setColor(java.awt.Color.BLACK);
java.util.Date today = new java.util.Date();
java.text.DateFormat formatter = java.text.DateFormat
.getDateTimeInstance(java.text.DateFormat.DEFAULT,
java.text.DateFormat.DEFAULT);
//String printDateOut = formatter.format(today);
//String lastModDateOut = formatter.format(pltD.fileLastModified);
if(pltD != null) {
g2D.drawString("File: \""+pltD.pltFile_Name+"\"", 0f, H);
g2D.drawString(
"File last modified: "+formatter.format(pltD.fileLastModified)+
"; Printed: "+formatter.format(today)+")", 0f, (2f*H+0.5f*H));
}
} // if printing & printHeader
//------------------------
//---- paint all lines
// antiAliasing
if(antiAliasing == 1) { g2D.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING,
java.awt.RenderingHints.VALUE_ANTIALIAS_ON);}
else if(antiAliasing == 2) { g2D.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING,
java.awt.RenderingHints.VALUE_ANTIALIAS_DEFAULT);}
else { g2D.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING,
java.awt.RenderingHints.VALUE_ANTIALIAS_OFF);}
//line thickness
java.awt.BasicStroke stroke; float pen;
if(!printing) {pen = penThickness;} else {pen = printPenThickness;}
stroke = new java.awt.BasicStroke(pen,
java.awt.BasicStroke.CAP_SQUARE, java.awt.BasicStroke.JOIN_BEVEL);
g2D.setStroke(stroke);
int ix_start = 0, iy_start = 0;
if(pltD != null) {
if(pltD.pltFileAList.size() > 0) {
ps = pltD.pltFileAList.get(0);
ix_start = ps.i1;
iy_start = ps.i2;
}
for(int j=0; j < pltD.pltFileAList.size(); j++) {
ps = pltD.pltFileAList.get(j);
//if(ps == null) {break;}
int i0 = ps.i0;
if (i0 == 1) {// draw line
int ix_new = ps.i1;
int iy_new = ps.i2;
int x0 = Math.round((float)(ix_start)*xScale) -xScale0;
int y0 = compDim.height - (Math.round((float)(iy_start)*yScale) -yScale0);
int x1 = Math.round((float)(ix_new)*xScale) -xScale0;
int y1 = compDim.height - (Math.round((float)(iy_new)*yScale) -yScale0);
//draw
g2D.drawLine(x0, y0, x1, y1);
ix_start = ix_new; iy_start = iy_new; } // I0=1
else if (i0 == 0) { // move to
ix_start = ps.i1;
iy_start = ps.i2; } // I0=0
else if ( (i0 ==5 || i0 ==8)
&& ((colourType ==0 && !printing) || (printing && printColour)) ) { // set colour
i1 = ps.i1 - 1;
if(i1<0) {i1=0;}
while (i1 >= MAX_COLOURS) {i1 = i1 - MAX_COLOURS;}
if (i1<0) {i1=0;}
g2D.setColor(colours[i1]);
} // I0 = 5 or 8
} // for j
} // if(pltD != null)
//------------------------
//---- paint all texts
if (pltD == null || pltD.pltTextAList.size()<=0 || !textWithFonts) {return;}
int oldColour = -1;
// -- get a font
String diagrFontFamily;
if (fontFamily == 1) {diagrFontFamily = java.awt.Font.SANS_SERIF;}
else if (fontFamily == 2) {diagrFontFamily = java.awt.Font.MONOSPACED;}
else if (fontFamily == 3) {diagrFontFamily = java.awt.Font.DIALOG;}
else if (fontFamily == 4) {diagrFontFamily = java.awt.Font.DIALOG_INPUT;}
else {diagrFontFamily = java.awt.Font.SERIF;}
int diagrFontStyle;
if (fontStyle == 1) {diagrFontStyle = java.awt.Font.BOLD;}
else if (fontStyle == 2) {diagrFontStyle = java.awt.Font.ITALIC;}
else {diagrFontStyle = java.awt.Font.PLAIN;}
f = new java.awt.Font(diagrFontFamily, diagrFontStyle, fontSize);
g2D.setFont(f);
if(antiAliasingText == 1) {
g2D.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING,
java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_ON);}
else if(antiAliasingText == 2) {
g2D.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING,
java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT);}
else {
g2D.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING,
java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);}
// -- get information needed by method "changeFont"
java.awt.FontMetrics fm = g2D.getFontMetrics(f);
// Note: using stringWidth gave StackOverflowError with earlier version of jVectClipboard
java.awt.geom.Rectangle2D mBnds = fm.getStringBounds("H", g2D);
// Store information needed by method "changeFont" into "fi"
FontInfo fi = new FontInfo(f,fm,0f,0.35f,mBnds,(float)mBnds.getWidth());
//fontScale gives a font with point size = fontSize
// for a text size = 0.35cm with UserSpace width = 2100
// and window width of 350 pixels
fi.fontScale = (fontSize/35f)*(2100f/userWidth)
*((float)compDim.width/350f);
// -- Scale the font (squeeze or expand vertically/horizontally):
double wH =(double)compDim.width/(double)compDim.height;
double wHuserSpace = (double)userWidth/(double)userHeight;
double scaleXY = wHuserSpace / wH;
java.awt.geom.AffineTransform original;// = new java.awt.geom.AffineTransform();
original = g2D.getTransform();
g2D.scale(1,scaleXY); // from now on the user space coordinates are scaled
// -- loop through all texts
for (int j=0; j < pltD.pltTextAList.size(); j++) {
String txt = pltD.pltTextAList.get(j).txtLine;
if(txt != null && txt.length() > 0) {
if ((!printing && colourType ==0) || (printing && printColour)) {
// set colour to a value between 0 to "MAX_COLOURS"
int iColour = pltD.pltTextAList.get(j).color -1;
if (iColour<0) {iColour=0;}
while (iColour >= MAX_COLOURS) {iColour = iColour - MAX_COLOURS;}
if (iColour<0) {iColour=0;}
// change colour if needed
if (iColour != oldColour)
{g2D.setColor(colours[iColour]); oldColour = iColour;}
} // if (!printing & colourType =0) | (printing & printColour)
//
pt = pltD.pltTextAList.get(j);
boolean isFormula = pt.isFormula;
int align = pltD.pltTextAList.get(j).alignment;
// Size and Angle
// multiply by 100 = convert to user coordinate units
float textSize = 100f * pltD.pltTextAList.get(j).txtSize;
float txtAngleDegr = pltD.pltTextAList.get(j).txtAngle;
float txtAngleRad = (float)Math.toRadians(txtAngleDegr);
// position
i1 = pt.i1;
i2 = pt.i2;
int ix1 = Math.round((float)i1*xScale) -xScale0;
int iy1 = compDim.height -(Math.round((float)i2*yScale) -yScale0);
// correct y-position for the scaling
iy1 = (int)Math.round((double)iy1/scaleXY);
// scale factor to align texts
float scaleAlignX = xScale;
float scaleAlignY = yScale/(float)scaleXY;
PrintFormula(g2D,txt,ix1,iy1,
isFormula,align,textSize,txtAngleRad,
fi, scaleAlignX, scaleAlignY);
} // if txt.length()>0
} // for j
//To scale back to original
g2D.setTransform(original);
} // paintDiagram
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="PrintFormula">
private void PrintFormula (java.awt.Graphics2D g2D,
String textLine, int ix, int iy,
boolean isFormula0, int align,
float tSize, float txtAngleRad,
FontInfo fi,
float scaleAlignX, float scaleAlignY) {
int n0 = textLine.length();
if (n0 <= 0 || textLine.trim().length() <= 0) {return;}
int ix1 = ix;
int iy1 = iy;
// size
float normalSize = tSize;
float subSize = 0.9f * tSize;
fi.txtSize = tSize;
if (normalSize != fi.oldTxtSize) {changeFont(g2D, fi); fi.oldTxtSize = normalSize;}
// ------------------------------------------
// ---- initial adjustments and checks ----
if (isFormula0) {
if (textLine.indexOf('~')>=0) {textLine = textLine.replace('~', '°');}
if (textLine.indexOf('$')>=0) {textLine = textLine.replace('$', 'µ');}
if (textLine.indexOf('^')>=0) {textLine = textLine.replace('^', 'Δ');}
}
// ---- Check if the text is really a chemical formula
// does TxtLine contain only numbers (and/or: +-.)?
boolean isFormula = isFormula0;
int i;
if (isFormula0) {
boolean onlyDigits = true; int j;
for (i = 0; i <n0; i++) {
j = textLine.charAt(i);
// > 9 or <0 and
if((j>57 || j<48) &&
// not . + - unicode en dash or minus
j!=46 && j!=43 && j!=45 && j!='\u2013' && j!='\u2212')
{onlyDigits = false;}
} //for i
// does TxtLine NOT contain numbers or `' +-?
// (a chemical formula must contain numbers in sub-indeces etc)
boolean notDigits = true;
for (i = 0; i <n0; i++) {
j = textLine.charAt(i);
if (j >=48 && j <=57) {notDigits = false;}
if (j ==39 || j ==96) {notDigits = false;}
if (j ==36 || j ==94 || j ==126) {notDigits = false;}
if (j ==43 || j ==45 || j=='\u2013' || j=='\u2212') {notDigits = false;}
} //for i
if (onlyDigits || notDigits) {isFormula = false;}
} // isFormula0
// ---- Get super/sub-scripts
float[] d; int n = n0;
if (isFormula) {
ChemFormula cf = new ChemFormula(textLine, new float[1]);
chemF(cf);
textLine = cf.t.toString();
n = textLine.length();
d = new float[n];
System.arraycopy(cf.d, 0, d, 0, n);
isFormula = false;
for (i=0;i<n;i++) {if(Math.abs(d[i])>0.01f) {isFormula = true;} }
} // isFormula
else {d = new float[1]; d[0]=0f;} //otherwise the compiler complains that
// d[] might not have been initialised
// --------------------------------
// ---- Draw the text String ----
// ---- Get starting position to plot the text: ix1 and iy1
float shift; float q;
// --- align horizontally: -1=Left; 0=Center; +1=Right.
// note that for chemical formulas the x-position is already
// adjusted in procedure "sym"
if(align != -1) { // if Not left align
float w =1f; if(align == 0) {w = 0.5f;} // center
fi.rect = fi.fm.getStringBounds(textLine, g2D);
float txtWidth = (float)fi.rect.getWidth();
float startWidth = (float)n * tSize;
q = startWidth * scaleAlignX;
shift = q - txtWidth;
if (Math.abs(shift) > 0.01f) {
ix1 = ix1 + Math.round(w*shift);
} //shift !=0
} //if Not left align
// --- align vertically
// is the target vertical size of the text > a displayed "H"'s width?
q = tSize * scaleAlignY;
shift = q - fi.width_H;
//Note that "y" increases downwards; zero = upper left corner
if(Math.abs(shift) > 0.01f) {
iy1 = iy1 - Math.round(shift/2f);
} // if shift !=0
// ---- Rotate
if(Math.abs(txtAngleRad)>0.001) {g2D.rotate(-txtAngleRad, ix, iy);}
// ---- Draw String
float newSize;
if (!isFormula) {
newSize = normalSize;
if (newSize != fi.oldTxtSize) {
fi.txtSize = newSize;
changeFont (g2D, fi);
fi.oldTxtSize=newSize;
}
g2D.drawString(textLine, ix1, iy1);
} else { // isFormula
float d0 = d[0];
int i0=0;
int ix2 = ix1;
int iy2;
for(i=1;i<n;i++) {
if(d[i]!=d0) {
if(Math.abs(d0)>0.001f) {newSize = subSize;} else {newSize = normalSize;}
if(newSize != fi.oldTxtSize)
{fi.txtSize = newSize;
changeFont (g2D, fi);
fi.oldTxtSize=newSize;}
iy2 = iy1 - Math.round(d0 * fi.width_H);
String txt = textLine.substring(i0,i);
g2D.drawString(txt, ix2,iy2);
fi.fm = g2D.getFontMetrics();
fi.rect = fi.fm.getStringBounds(txt, g2D);
int txtW = Math.round((float)fi.rect.getWidth());
ix2 = ix2 + txtW;
i0 = i; d0 = d[i];
} // if d[] is changed
} //for i
if (Math.abs(d0)>0.001f) {newSize = subSize;}
else {newSize = normalSize;}
if (newSize != fi.oldTxtSize)
{fi.txtSize = newSize;
changeFont (g2D, fi);
fi.oldTxtSize=newSize;}
iy2 = iy1 - Math.round(d0 * fi.width_H);
String txt = textLine.substring(i0,n);
g2D.drawString(txt, ix2,iy2);
} // isFormula
// ---- Rotate back
if(Math.abs(txtAngleRad)>0.001) {g2D.rotate(txtAngleRad, ix, iy);}
}// PrintFormula
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="changeFont">
/** Changes the size of the font of a graphics context (g2D).
* Returns information on the new font in an instance of FontInfo.
* @param g2D Graphics2D
* @param fi FontInfo
* @return FontInfo with new calculated width_H (the width of a capital letter "H") */
private FontInfo changeFont (java.awt.Graphics2D g2D, FontInfo fi) {
//The point size of the font is changed depending on
// the Dimension of the component where the text is displayed.
float txtSizePts = fi.txtSize * fi.fontScale;
int pts =Math.round(Math.max(4f, Math.min(76f,txtSizePts)));
fi.f = g2D.getFont();
fi.f = new java.awt.Font(fi.f.getFontName(), fi.f.getStyle(), pts);
g2D.setFont(fi.f);
//Get the FontMetrics
fi.fm = g2D.getFontMetrics();
//Get the size of an upper case "H"
fi.rect = fi.fm.getStringBounds("H", g2D);
// Note: stringWidth made StackOverflowError with an earlier version of jVectClipboard
// width_H = (float)fm.stringWidth("H");
fi.width_H = (float)fi.rect.getWidth();
return fi;
}// changeFont
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="chemF">
/** Purpose: given a "chemical formula" in StringBuffer <b>t</b> it returns
* an array <b>d</b> indicating which characters are super- or
* sub-scripted and a new (possibly modified) <b>t</b>.
* Both <b>t</b> and <b>d</b> are stored for input
* and output in objects of class ChemFormula. Note that <b>t</b> may
* be changed, e.g. from "Fe+2" to "Fe2+".
* <p>
* Stores in array <b>d</b> the vertical displacement of each
* character (in units of character height). In the case of HCO3-, for example,
* d(1..3)=0, d(4)=-0.4, d(5)=+0.4
* <p>
* Not only chemical formulas, but this method also "understands" math
* formulas: x'2`, v`i', log`10', 1.35'.`10'-3`
* <p>
* For aqueous ions, the electric charge may be written as either a space and
* the charge (Fe 3+, CO3 2-, Al(OH)2 +), or as a sign followed by a number
* (Fe+3, CO3-2, Al(OH)2+). For charges of +-1: with or without a space
* sepparating the name from the charge (Na+, Cl-, HCO3- or Na +, Cl -, HCO3 -).
* <p>
* Within this method, <b>t</b> may be changed, so that on return:
* <ul><li>formulas Fe+3, CO3-2 are converted to Fe3+ and CO32-
* <li>math formulas: x'2`, v`i', log`10', 1.35'.`10'-3`
* are stripped of "`" and "'"
* <li>@ is used to force next character into base line, and
* the @ is removed (mostly used for names containing digits and
* some math formulas)</ul>
* <p>
* To test:<br>
* <pre>String txt = "Fe(CO3)2-";
* System.out.println("txt = \""+txt+"\","+
* " new txt = \""+chemF(new ChemFormula(txt, new float[1])).t.toString()+"\","+
* " d="+Arrays.toString(chemF(new ChemFormula(txt, new float[1])).d));</pre></p>
*
* <p>Version: 2013-Apr-03.
*
* @param cf ChemFormula
* @return new instance of ChemFormula with d[] of super- subscript
* positions for each character and a modified StingBuffer t. */
static void chemF(ChemFormula cf) {
int act; // list of actions:
final int REMOVE_CHAR = 0;
final int DOWN = 1;
final int NONE = 2;
final int UP = 3;
final int CONT = 4;
final int END = 6;
int nchr; char t1; char t2; int i;
float dm; float df;
final char M1='\u2013'; // Unicode En Dash
final char M2='\u2212'; // Minus Sign = \u2212
// The characters in the StringBuffer are stored in "int" variables
// Last, Next-to-last, Next-to-Next-to-last
// ow (present character)
// Next, Next-Next, Next-Next-Next
int L; int nL; int nnL; int now; int n; int n2; int n3;
// ASCII Table:
// -----------------------------------------------------------------------------
// 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
// ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9
// -----------------------------------------------------------------------------
// 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
// : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S
// -----------------------------------------------------------------------------
// 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 00 01 02 03 04 05 06 07 08 09
// T U V W X Y Z [ \ ] ^ _ ` a b c d e f g h i j k n m
// -----------------------------------------------------------------------------
//110 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
// n o p q r s t u v w x y z { | } ~
// -----------------------------------------------------------------------------
// If the string is too short: do nothing
StringBuffer t = new StringBuffer();
t.append(cf.t);
L = t.toString().trim().length();
if(L <= 1) {return;}
// Remove trailing space from the StringBuffer
L = t.length(); // total length
nchr = Util.rTrim(t.toString()).length(); // length without trailing space
if(L > nchr) {t.delete(nchr, L);}
// create d and initialize it
float[] d = new float[nchr];
for(i = 0; i < d.length; i++) {d[i] = 0f;}
// set the non-existing characters to "space"
// Last, Next-to-last, Next-to-Next-to-last
L = 32; nL = 32; nnL = 32;
// get the ASCII code
now = t.charAt(0);
// get the following characters
n = 32; if (nchr >=2) {n = t.charAt(1);} // Next
n2 = 32; if (nchr >=3) {n2 = t.charAt(2);} // Next-Next
// dm (Displacement-Math) for '` sequences: 1.5'.`10'-12`, log p`CO2'
dm = 0f;
// df (Displacement-Formulas) in chemical formulas: CO3 2-, Fe 3+, Cl-, Na+
df = 0f;
//
// -----------------------------
// Main Loop
//
i = 0;
main_do_loop:
do {
n3 = 32;
if(nchr >=(i + 4)) {n3 = t.charAt(i + 3);} //Next-Next-Next
// Because a chemical formula only contains supersripts at the end
// (the electric charge), a superscrip character marks the end of a formula.
// Set df=0 after superscript for characters that are not 0:9 + or -
if(df > 0.001f) { // (if last was supercript, i.e. df>0)
if (now <43 || now >57 || now ==44 || now ==46 || now ==47) //not +- 0:9
{df = 0f;}
} //df > 0.001
checks: { // named block of statements to be used with "break"
// ---------------
// for @
// ---------------
// if the character is @, do nothing; if last char. was @, treat "now" as a
// "normal" char. (and therefore, if last char. was @, and "now" is a space,
// leave a blank space);
if(now ==64 && L !=64) { act =REMOVE_CHAR; break checks;}
if(L ==64) { // @
if(now ==32) {act =CONT;} else {act =NONE;}
break checks;
} // Last=@
// ---------------
// for Ctrl-B (backspace)
// ---------------
if(now ==2) {
now = n; n = n2; n2 = n3;
act =END; break checks;
} // now = backspace
// ---------------
// for ' or `
// ---------------
if(now ==39 || now ==96) {
// for '`, `' sequences: change the value of variable dm.
// if it is a ' and we are writing a "normal"-line, and next is either
// blank or s (like it's or it's.): write it normal
if(now ==39 && dm ==0
&& ( (n ==32 && L ==115)
|| (n ==115 && (n2==32||n2==46||n2==44||n2==58||n2==59||n2==63
||n2==33||n2==41||n2==93)) ) )
{act =CONT; break checks;}
if(now ==39) {dm = dm + 0.5f;}
if(now ==96) {dm = dm - 0.5f;}
act =REMOVE_CHAR; break checks;
} // now = ' or `
// ---------------
// for BLANK (space)
// ---------------
// Decide if the blank must be printed or not.
// In front of an electric charge: do not print (like CO3 2-, etc)
if(now ==32) {
// if next char. is not a digit (1:9) and not (+-), make a normal blank
if((n <49 && (n !=43 && n !=45 &&n!=M1&&n!=M2)) || n >57) {act =NONE; break checks;}
// Space and next is a digit or +-:
// if next is (+-) and last (+-) make a normal blank
if((n ==43 || n ==45 || n==M1||n==M2)
&& (L ==43 || L ==45 ||L==M1||L==M2)) {act =NONE; break checks;}
// if the 2nd-next is letter (A-Z, a-z), make a normal blank
if((n2 >=65 && n2 <=90) || (n2 >=97 && n2 <=122)) {act =NONE; break checks;}
// if next is a digit (1-9)
if(n >=49 && n <=57) { // 1:9
// and 2nd-next is also a digit and 3rd-next is +- " 12+"
if(n2 >=48 && n2 <=57) { // 0:9
if (n3 !=43 && n3 !=45 &&n3!=M1&&n3!=M2) {act =NONE; break checks;} // n3=+:-
} // n2=0:9
// if next is (1-9) and 2nd-next is not either + or -, make a blank
else if (n2 !=43 && n2 !=45 &&n2!=M1&&n2!=M2) {act =NONE; break checks;}
} // n=1:9
// if last char. was blank, make a blank
if(L ==32) {act =NONE; break checks;} // 110 //
// if last char. was neither a letter (A-Z,a-z) nor a digit (0:9),
// and was not )]}"'>, make a blank
if((L <48 || L >122 || (L >=58 && L <=64) || (L >=91 && L<= 96))
&& (L !=41 && L !=93 && L !=125 && L !=62 && L !=34 && L !=39))
{act =NONE; break checks;}
// Blanks followed either by + or -, or by a digit (1-9) and a + or -
// and preceeded by either )]}"'> or a letter or a digit:
// do not make a blank space.
act =REMOVE_CHAR; break checks;
} //now = 32
// ---------------
// for Numbers (0:9)
// ---------------
// In general a digit is a subscript, except for electric charges...etc
if(now >=48 && now <=57) {
// if last char. is either ([{+- or an impossible chem.name,
// then write it "normal"
if(L !=40 && L !=91 && L !=123 && L !=45 &&L!=M1&&L!=M2&& L !=43) { // Last not ([{+-
if((L ==106 || L ==74) || (L ==113 || L ==81)) {act =NONE; break checks;} // jJ qQ
if((L ==120 || L ==88) || (L ==122 || L ==90)) {act =NONE; break checks;} // xX zZ
//if last char. is )]} or a letter (A-Z,a-z): write it 1/2 line down
if((L >=65 && L <=90) || (L >=97 && L <=122)) {act =DOWN; break checks;} // A-Z a-z
if(L ==41 || L ==93 || L ==125) {act =DOWN; break checks;} // )]}
//if last char. is (0:9 or .) 1/2 line (down or up), keep it
if(df >0.01f && ((L >=48 && L <=57) || L ==46)) {act =CONT; break checks;}
if(df <-0.01f && (L ==46 || (L >=48 && L <=57))) {act =CONT; break checks;}
} // Last not ([{+-
// it is a digit and last char. is not either of ([{+-)]} or A:Z a:z
// is it an electric charge?
df = 0f; //125//
// if last char is space, and next char. is a digit and 2nd-next is a +-
// (like: W14O41 10+) then write it "up"
if(L ==32 && (n >=48 && n <=57)
&& (n2 ==43 || n2 ==45 ||n2 ==M1||n2 ==M2) && now !=48) {
//if 3rd-next char. is not (space, )]}), write it "normal"
if(n3 !=32 && n3 !=41 && n3 !=93 && n3 !=125) {act =CONT; break checks;} // )]}
act =UP; break checks;
}
// if last is not space or next char. is not one of +-, then write it "normal"
if(L !=32 || (n !=43 && n !=45 &&n!=M1&&n!=M2)) {act =CONT; break checks;} // +-
// Next is +-:
// if 2nd-next char. is a digit or letter, write it "normal"
if((n2 >=48 && n2 <=57) || (n2 >=65 && n2 <=90)
|| (n2 >=97 && n2 <=122)) {act =CONT; break checks;} // 0:9 A:Z a:z
// if last char. was a digit or a blank, write it 1/2 line up
// if ((L >=48 && L <=57) || L ==32) {act =UP; break checks;}
// act =CONT; break checks;
act =UP; break checks;
} // now = (0:9)
// ---------------
// for Signs (+ or -)
// ---------------
// Decide if it is an electric charge...
// and convert things like: CO3-2 to: CO3 2-
if(now ==43 || now ==45 ||now ==M1||now ==M2) {
// First check for charges like: Fe 2+ and W16O24 11-
// If last char. was a digit (2:9) written 1/2 line up, write it
// also 1/2 line up (as an electrical charge in H+ or Fe 3+).
if(L >=50 && L <=57 && df >0.01f) {act =UP; break checks;} // 2:9
// charges like: W16O24 11-
if((L >=48 && L <=57) && (nL >=49 && nL <=57)
&& (df >0.01f)) {act =UP; break checks;} // 0:9 1:9
//is it a charge like: Fe+3 ? ------------------------
if(n >=49 && n <=57) { // 1:9
// it is a +- and last is not superscript and next is a number:
// check for impossible cases:
// if 2nd to last was a digit or a period and next a digit: 1.0E-1, 2E-3, etc
if(((nL >=48 && nL <=57) || nL ==46) && (L ==69 || L==101)) {act =NONE; break checks;} // 09.E
if(L ==32) {act =NONE; break checks;} // space
if((L ==106 || L ==74) || (L ==113 || L ==81)) {act =NONE; break checks;} // jJ qQ
if((L ==120 || L ==88) || (L ==122 || L ==90)) {act =NONE; break checks;} // xX zZ
// if last was 0 and 2nd to last 1 and dm>0 (for 10'-3` 10'-3.1` or 10'-36`)
if(dm >0.01f && (L ==39 && nL ==48 && nnL ==49)
&& (n >=49 && n <=57)
&& (n2 ==46 || n2 ==96 || (n2 >=48 && n2 <=57))) {act =NONE; break checks;}
// allowed in L: numbers, letters and )]}"'
// 1st Line: !#$%&(*+,-./ 2nd line: {|~:;<=?@ 3rd Line: [\^_`
if((L <48 && L !=41 && L !=34 && L !=39)
|| (L >122 && L !=125) || (L >=58 && L <=64 && L !=62)
|| (L >=91 && L <=96 && L !=93)) {act =NONE; break checks;}
if((L ==41 || L ==93 || L ==125 || L ==34 || L ==39)
&& (nL ==32 || nL <48 || nL >122 || (nL >=58 && nL <=64)
|| (nL >=91 && nL <=96))) {act =NONE; break checks;} // )]}"'
// allowed in n2: numbers and space )']`}
// 1st Line: !"#$%&(*+,-./ 2nd Line: except ]`}
if((n2 <48 && n2 !=41 && n2 !=32 && n2 !=39)
|| (n2 >57 && n2 !=93 && n2 !=96 && n2 !=125)) {act =NONE; break checks;}
//it is a +- and last is not superscript and next is a number:
// is it a charge like: W14O41-10 ?
if((n >=49 && n <=57) && (n2 >=48 && n2 <=57)) { // 1:9 0:9
// characters allowed after the electric charge: )]}`'@= space and backsp
if(n3 !=32 && n3 !=2 && n3 !=41 && n3 !=93 && n3 !=125
&& n3 !=96 && n3 !=39 && n3 !=64 && n3 !=61) {act =NONE; break checks;}
// it is a formula like "W12O41-10" convert to "W12O41 10-" and move "up"
t1 = t.charAt(i+1); t2 = t.charAt(i+2);
t.setCharAt(i+2, t.charAt(i));
t.setCharAt(i+1, t2);
t.setCharAt(i, t1);
int j1 = n; int j2 = n2;
n2 = now;
n = j2; now = j1;
act =UP; break checks;
} // 1:9 0:9
// is it a charge like Fe+3, CO3-2 ?
if(n >=50 && n <=57) { // 2:9
//it is a formula of type Fe+3 or CO3-2
// convert it to Fe3+ or CO32- and move "up"
t1 = t.charAt(i+1);
t.setCharAt(i+1, t.charAt(i));
t.setCharAt(i, t1);
int j = n; n = now; now = j;
act =UP; break checks;
} // 2:9
} // 1:9
// it is a +- and last is not superscript and: next is not a number:
// write it 1/2 line up (H+, Cl-, Na +, HCO3 -), except:
// 1) if last char. was either JQXZ, or not blank-letter-digit-or-)]}, or
// 2) if next char. is not blank or )}]
// 3) if last char. is blank or )]}"' and next-to-last is not letter or digit
if(L ==106 || L ==74 || L ==113 || L ==81) {act =NONE; break checks;} // jJ qQ
if(L ==120 || L ==88 || L ==122 || L ==90) {act =NONE; break checks;} // xX zZ
if(L ==32 || L ==41 || L ==93 || L ==125) { // space )]}
//1st Line: !"#$%&'(*+,-./{|}~ 2nd Line: :;<=>?@[\^_`
if(nL ==32 || (nL <48 && nL !=41) || (nL >122)
|| (nL >=58 && nL <=64)
|| (nL >=91 && nL <=96 && nL !=93)) {act =NONE; break checks;}
act =UP; break checks;
} // space )]}
// 1st Line: !#$%&(*+,-./{|~ 2nd Line: :;<=>?@[\^_`
if((L <48 && L !=41 && L !=34 && L !=39)
|| (L >122 && L !=125) || (L >=58 && L <=64)
|| (L >=91 && L <=96 && L !=93)) {act =NONE; break checks;}
if(n !=32 && n !=41 && n !=93 && n !=125 && n !=61
&& n !=39 && n !=96) {act =NONE; break checks;} // )]}=`'
act =UP; break checks;
} // (+ or -)
// ---------------
// for Period (.)
// ---------------
if (now ==46) {
// if last char was a digit (0:9) written 1/2 line (down or up)
// and next char is also a digit, continue 1/2 line (down or up)
if((L >=48 && L <=57) && (n >=48 && n <=57)) {act =CONT; break checks;} // 0:9
act =NONE; break checks;
} // (.)
act =NONE;
} // --------------- "checks" (end of block name)
switch_action:
switch (act) {
case REMOVE_CHAR:
// ---------------
// take OUT present character //150//
if(i <nchr) {t.deleteCharAt(i);}
nchr = nchr - 1;
nnL = nL; nL = L; L = now; now = n; n = n2; n2 = n3;
continue; // main_do_loop;
case DOWN:
df = -0.4f; // 170 //
break; // switch_action;
case NONE:
df = 0.0f; // 180 //
break; // switch_action;
case UP:
df = 0.4f; // 190 //
break; // switch_action;
case CONT:
case END:
default:
} // switch_action
if(act != END) {// - - - - - - - - - - - - - - - - - - - // 200 //
nnL = nL;
nL = L;
L = now;
now = n;
n = n2;
n2 = n3;
}
d[i] = dm + df; //201//
i = i + 1;
} while (i < nchr); // main do-loop
// finished
// store results in ChemFormula cf
if(cf.t.length()>0) {cf.t.delete(0, cf.t.length());}
cf.t.append(t);
cf.d = new float[nchr];
System.arraycopy(d, 0, cf.d, 0, nchr);
// return;
} // ChemFormula chemF
//</editor-fold>
} | 40,596 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
Dielectric.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibChemDiagr/src/lib/kemi/H2O/Dielectric.java | package lib.kemi.H2O;
/** A set of routines used to calculate the dielectric constant of water, etc<br>
* Fernández, D.P., Goodwin, A.R.H., Lemmon, E.W., Levelt Sengers, J.M.H.,
* Williams, R.C., 1997. A formulation for the static permittivity of water and
* steam at temperatures from 238 K to 873 K at pressures up to 1200 MPa,
* including derivatives and Debye–Hückel coefficients.
* Journal of Physical and Chemical Reference Data 26, 1125–1166.
* doi:10.1063/1.555997<br>
*
* Copyright (C) 2019-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class Dielectric {
public Dielectric(){};
/** Zero Celsius = 273.15 K */
public static final double T0 = 273.15; // K
/** triple point temperature = 273.16 K (= 0.01 C)*/
public static final double TRIPLE_POINT_T = 273.16; // K
/** triple point temperature = 0.01 C (= 273.16 K) */
public static final double TRIPLE_POINT_TC = 0.01; // C
/** Critical temperature = 647.096 (+/- 0.01) K (= 373.946 C) */
public static final double CRITICAL_T = 647.096; // K
/** Critical temperature = 373.946 C (=647.096 K) */
public static final double CRITICAL_TC = 373.946; // C
/** temperature of melting ice Ih at highest pressure = 251.165 K (at p = 2085.66 bar) */
private static final double MELTING_T_ICE_Ih_AT_HIGH_P = 251.165;
//<editor-fold defaultstate="collapsed" desc="epsSat(tC)">
/** Returns the static permitivity of water (dielectric constant)
* at the liquid-vapor saturated pressure, calculated using the
* equations reported in:<br>
* Fernández, D.P., Goodwin, A.R.H., Lemmon, E.W., Levelt Sengers, J.M.H.,
* Williams, R.C., 1997. A formulation for the static permittivity of water and
* steam at temperatures from 238 K to 873 K at pressures up to 1200 MPa,
* including derivatives and Debye–Hückel coefficients.
* Journal of Physical and Chemical Reference Data 26, 1125–1166.
* doi: 10.1063/1.555997<br>
*
* If tC = 0 it returns 87.956, the value at the triple point (0.01 C and 0.00611657 bar).
* Range of conditions: 0.01°C (triple point) to 373.9°C (critical point).
* It throws an exception outside this range.
*
* @param tC the temperature in degrees Celsius
* @return the dielectric constant of water (unitless) at the vapor saturated
* pressure
* @throws IllegalArgumentException
* @see lib.kemi.H2O.Dielectric#epsJN(double, double) epsJN
* @see lib.kemi.H2O.Dielectric#eps(double, double) eps
*/
static public double epsSat(final double tC) throws IllegalArgumentException {
if(Double.isNaN(tC)) throw new IllegalArgumentException("\"epsSat(t)\": tC = NaN");
if(tC == 0) {return 87.95631;} // the value at the triple point: 0.01 C and pBar = 0.00611657 bar
if(tC < 0.01 || tC >= CRITICAL_TC) throw new IllegalArgumentException("\"epsSat(t)\": tC = "+tC+" (must be zero or >=0.01 and < 373.946 C)");
final double T = tC + T0;
// Table 8 in Fernandez et al (1997)
final double[] L = new double[]{
2.725384249466,
1.090337041668,
21.45259836736,
-47.12759581194,
4.346002813555,
237.5561886971,
-417.7353077397,
249.3834003133};
// Eqns. (35) and (36) in Fernandez et al (1997)
final double theta = Math.pow((1.-(T/CRITICAL_T)),(1./3.));
double epsLiq = 1.;
for (int i=0; i < L.length; i++) {
epsLiq = epsLiq + L[i] * Math.pow(theta,(i+1.));
}
return epsLiq * 5.36058;
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="eps(tC,pbar)">
/** Returns the static permitivity of water (dielectric constant)
* calculated using the equations reported in:<br>
* Fernández, D.P., Goodwin, A.R.H., Lemmon, E.W., Levelt Sengers, J.M.H.,
* Williams, R.C., 1997. A formulation for the static permittivity of water and
* steam at temperatures from 238 K to 873 K at pressures up to 1200 MPa,
* including derivatives and Debye–Hückel coefficients.
* J. Phys. Chem. Ref. Data 26, 1125–1166. doi:10.1063/1.555997<br>
*
* <p>Range of conditions: 0 to 12,000 bar, -35 to 600°C.
* It throws an exception outside this range, or if
* water is frozen at the requested conditions.
* If tC = 0 and pBar = 1, it returns the value at 0.01 Celsius and 1 bar.
* <p>If the temperature is below the critical point and the pressure
* corresponds to the vapor saturation (within 0.5%),
* then epsSat is called.
* @param tC the temperature in degrees Celsius
* @param pBar the pressure in bar
* @return the dielectric constant of liquid (or supercritical fluid) water (unitless)
* @throws IllegalArgumentException
* @see lib.kemi.H2O.Dielectric#epsSat(double) epsSat
* @see lib.kemi.H2O.Dielectric#eps(double, double) eps
*/
static public double eps(final double tC, final double pBar) throws IllegalArgumentException {
if(Double.isNaN(tC)) throw new IllegalArgumentException("\"eps(t,p)\": tC = NaN");
if(tC < -35. || tC > 600.001) throw new IllegalArgumentException("\"eps(t,p)\": tC = "+tC+" (must be >-35 and <= 600 C)");
if(Double.isNaN(pBar)) throw new IllegalArgumentException("\"eps(t,p)\": pBar = NaN");
if(pBar > 10000.01 || pBar <= 0.) throw new IllegalArgumentException("\"eps(t,p)\": pBar = "+pBar+" (must be >0 and <= 10 kbar)");
final double t_C;
// if pressure = 1 bar and temperature = 0, set temperature to 0.01 C (tripple point of water)
if(pBar >0.99999 && pBar < 1.00001 && Math.abs(tC) < 0.001) {t_C = 0.01;} else {t_C = tC;}
String str = lib.kemi.H2O.IAPWSF95.isWaterLiquid(t_C, pBar);
if(str.length() >0) throw new IllegalArgumentException("\"eps(t,p)\": "+str);
if(t_C >= 0.01 && t_C < CRITICAL_TC) {
final double pSat;
try {pSat= lib.kemi.H2O.IAPWSF95.pSat(t_C);}
catch (Exception ex) {throw new IllegalArgumentException("\"epsJN(t,p)\": "+ex.getMessage());}
if(pBar < (pSat*0.995)) {throw new IllegalArgumentException("\"epsJN(t,p)\": tC = "+tC+", pBar = "+pBar+" (pBar must be >= "+pSat+")");}
// if temperature >= 100 C and pressure = pSat (+/-0.5%) use epsSat-function
// (so, if tC = 25 (or 0.01) and pBar = 1, the full calculation is made)
if(pBar < (pSat*1.005) && t_C > 99.61) {
try {return epsSat(t_C);}
catch (Exception ex) {throw new IllegalArgumentException("\"epsJN(t,p)\": "+ex.getMessage());}
}
}
// Permittivity of free space (C^2 J^-1 m^-1)
final double eps_0 = 1./(4e-7 * Math.PI * Math.pow(299792458,2));
// Mean molecular polarizability (C^2 J^-1 m^2)
final double alpha = 1.636e-40;
// Molecular dipole moment (C m)
final double mu = 6.138e-30;
// Boltzmann's constant (J K^-1)
final double k = 1.380658e-23;
// Avogadro's number (mol^-1)
final double N_A = 6.0221367e23;
// Molar mass of water (kg/mol)
final double M_w = 0.018015268;
// Table 5 in Fernandez et al (1997)
final double[] N = new double[]{
0.978224486826,
-0.957771379375,
0.237511794148,
0.714692244396,
-0.298217036956,
-0.108853472196,
0.949327488264e-1,
-0.980469816509e-2,
0.165167634970e-4,
0.937359795772e-4,
-0.123179218720e-9};
final double N12 = 0.196096504426e-2;
// Table 5 in Fernandez et al (1997)
final double[] i = new double[]{ 1,1, 1, 2, 3, 3, 4,5,6, 7, 10};
final double[] j = new double[]{0.25,1,2.5,1.5,1.5,2.5,2,2,5,0.5,10};
final double Tc = CRITICAL_T;
final double T = t_C + T0;
final double rho_c = 322 / M_w; // mol/m3
final double rho;
try {rho = lib.kemi.H2O.IAPWSF95.rho(t_C, pBar) * 1000. // // change to kg/m3
/ M_w; // change to mol/m3
} catch (Exception ex) {throw new IllegalArgumentException("\"eps(t,p)\": "+ex.getMessage());}
if(Double.isNaN(rho)) {throw new IllegalArgumentException("\"eps(t,p)\": could not calculate density at tC = "+tC+", pBar = "+pBar);}
// Eqn. (34) in Fernandez et al (1997)
double g = 1.;
double rho_rho_c = rho/rho_c, Tc_T = Tc/T;
for(int h=0; h < N.length; h++) {
g = g + N[h] * Math.pow(rho_rho_c,i[h]) * Math.pow(Tc_T,j[h]);
}
int h = 0;
g = g + N12 * (rho_rho_c) * Math.pow(((T/228.)-1.),-1.2);
// Eqns. (23)+(24) in Fernandez et al (1997)
final double A = N_A * mu*mu * rho * g / (eps_0 * k * T);
final double B = N_A * alpha * rho / (3 * eps_0);
// Eqn. (26) in Fernandez et al (1997)
double w = 9. + 2.*A + 18.*B + A*A + 10.*A*B + 9.*B*B;
double eps = (1.+ A + 5.*B + Math.sqrt(w)) / (4. - 4.*B);
return eps;
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="epsJN(tC,pbar)">
/** * Returns the static permitivity of water (dielectric constant)
* calculated using the equations reported in:<br>
* Johnson J W, Norton D (1991) Critical phenomena in hydrothermal systems:
* state, thermodynamic, electrostatic, and transport properties of H2O in the
* critical region. American Journal of Science, 291, 541–648.
* doi: 10.2475/ajs.291.6.541<br>
*
* see also eqns. (36) and (40)-(44) and Table 1 in:
* Johnson J W, Oelkers E H, Helgeson H C (1992) SUPCRT92: A software package
* for calculating the standard molal thermodynamic properties of minerals,
* gases, aqueous species, and reactions from 1 to 5000 bar and 0 to 1000°C.
* Computers & Geosciences, 18, 899–947. doi:10.1016/0098-3004(92)90029-Q<br>
*
* Range of conditions: 1 to 5000 bar, 0 to 1000°C, density >0.05 g/cm3
* and pressures above the vaporization boundary (if temperature is below
* the critical point).
* It throws an exception outside this range.
* If tC = 0 and pBar = 1, it returns the value at 0.01 Celsius and 1 bar.
* <p>If the temperature is below the critical point and the pressure
* corresponds to the vapor saturation (within 0.5%),
* then epsSat is called.
*
* @param tC the temperature in degrees Celsius
* @param pBar the pressure in bar
* @return the dielectric constant of water (unitless)
* @throws IllegalArgumentException
* @see lib.kemi.H2O.Dielectric#epsSat(double) epsSat
* @see lib.kemi.H2O.Dielectric#eps(double, double) eps
*/
public static double epsJN(final double tC, final double pBar) throws IllegalArgumentException {
if(Double.isNaN(tC)) throw new IllegalArgumentException("\"epsJN(t,p)\": tC = NaN");
if(tC < 0 || tC > 1000.001) throw new IllegalArgumentException("\"epsJN(t,p)\": tC = "+tC+" (must be >=0 and <= 1000 C)");
if(Double.isNaN(pBar)) throw new IllegalArgumentException("\"epsJN(t,p)\": pBar = NaN");
if(pBar > 5000.01 || pBar <= 0.) throw new IllegalArgumentException("\"epsJN(t,p)\": pBar = "+pBar+" (must be >0 and <= 5 kbar)");
final double t_C;
// if pressure = 1 bar and temperature = 0, set temperature to 0.01 C (tripple point of water)
if(pBar >0.99999 && pBar < 1.00001 && Math.abs(tC) < 0.001) {t_C = 0.01;} else {t_C = tC;}
if(t_C >= 0.01 && t_C < CRITICAL_TC) {
final double pSat;
try {pSat= lib.kemi.H2O.IAPWSF95.pSat(t_C);}
catch (Exception ex) {throw new IllegalArgumentException("\"epsJN(t,p)\": "+ex.getMessage());}
if(pBar < (pSat*0.995)) {throw new IllegalArgumentException("\"epsJN(t,p)\": tC = "+tC+", pBar = "+pBar+" (pBar must be >= "+pSat+")");}
// if temperature >= 100 C and pressure = pSat (+/-0.5%) use epsSat-function
// (so, if tC = 25 (or 0.01) and pBar = 1, the full calculation is made)
if(pBar < (pSat*1.005) && t_C > 99.61) {
try {return epsSat(t_C);}
catch (Exception ex) {throw new IllegalArgumentException("\"epsJN(t,p)\": "+ex.getMessage());}
}
}
final double rho;
try {rho = lib.kemi.H2O.IAPWSF95.rho(t_C, pBar);}
catch (Exception ex) {throw new IllegalArgumentException("\"epsJN(t,p)\": "+ex.getMessage());}
if(Double.isNaN(rho)) {throw new IllegalArgumentException("\"epsJN(t,p)\": could not calculate density at tC = "+tC+", pBar = "+pBar);}
if( // rho > 1.1 || // see Fig.2 in SUPCRT92 (Jonhson et al 1992)
rho < 0.05) {throw new IllegalArgumentException("\"epsJN(t,p)\": calculated density = "+rho+" at tC = "+tC+", pBar = "+pBar+" (must be >0.05 g/cm3)");}
final double[] a = new double[]{
0.1470333593E+2,
0.2128462733E+3,
-0.1154445173E+3,
0.1955210915E+2,
-0.8330347980E+2,
0.3213240048E+2,
-0.6694098645E+1,
-0.3786202045E+2,
0.6887359646E+2,
-0.2729401652E+2};
final double Tr = 298.15;
final double T = t_C + 273.15;
final double T_=T/Tr, T_2 = T_*T_;
final double rho2 = rho*rho;
final double k1 = a[0]/T_;
final double k2 = a[1]/T_ + a[2] + a[3]*T_;
final double k3 = a[4]/T_ + a[5]*T_ + a[6]*T_2;
final double k4 = a[7]/T_2 + a[8]/T_ + a[9];
double eps = 1. + k1*rho + k2*rho2 + k3*rho2*rho + k4*rho2*rho2;
return eps;
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="gHKF(tC,pbar)">
/** HKF (Helgeson-Krikham-Flowers) model:
* g designates a P/T-dependent solvent function that provides for dielectric
* saturation and the compressibility of the solvent at high temperatures and
* pressures. With this function the temperature and pressure dependence of the
* effective electrostatic radii of aqueous ions can be calculated.
* See eqns.(49) to (52) and Tables 2 and 3 in:<br>
*
* Johnson J W, Oelkers E H, Helgeson H C, (1992) SUPCRT92: A software package
* for calculating the standard molal thermodynamic properties of minerals,
* gases, aqueous species, and reactions from 1 to 5000 bar and 0 to 1000°C.
* Computers & Geosciences, 18, 899–947. doi: 10.1016/0098-3004(92)90029-Q<br>
*
* as well as eqns. (25), (26), (32), (33) and Table 5 in:<br>
* Shock E L, Oelkers E H, Johnson J W, Sverjensky D A, Helgeson H C, (1992)
* Calculation of the thermodynamic properties of aqueous species at high
* pressures and temperatures. Effective electrostatic radii, dissociation
* constants and standard partial molal properties to 1000°C and 5 kbar.
* J. Chem. Soc., Faraday Transactions, 88, 803–826. doi:10.1039/FT9928800803<br>
* Range of conditions: 0 to 5000 bar, 0 to 1000°C, density 0.35 to 1 g/cm3
* and pressures above the vaporization boundary
* (if temperature is below the critical point).
*
* @param tC the temperature in degrees Celsius
* @param pBar the pressure in bar
* @return the g-function of the HKF model in metres (m)
* @throws IllegalArgumentException
*/
public static double gHKF(double tC, double pBar) throws IllegalArgumentException {
if(Double.isNaN(tC)) throw new IllegalArgumentException("\"gHKF(t,p)\": tC = NaN");
if(Double.isNaN(pBar)) throw new IllegalArgumentException("\"gHKF(t,p)\": pBar = NaN");
if(tC > 1000 || pBar <= 0 || pBar > 5000) throw new IllegalArgumentException("\"gHKF(t,p)\": tC = "+tC+", pBar = "+pBar+" (must be < 1000 C and zero to 5 kbar)");
//--------
if(tC <= 100.01) {return 0;}
//--------
double pSat = Double.NaN;
if(tC >= 0.01 && tC < CRITICAL_TC) {
try {pSat= lib.kemi.H2O.IAPWSF95.pSat(tC);}
catch (Exception ex) {throw new IllegalArgumentException("\"gHKF(t,p)\": "+ex.getMessage());}
if(pBar < (pSat*0.995)) {throw new IllegalArgumentException("\"gHKF(t,p)\": tC = "+tC+", pBar = "+pBar+" (pBar must be >= "+pSat+")");}
}
final double rho;
try {rho = lib.kemi.H2O.IAPWSF95.rho(tC, pBar);}
catch (Exception ex) {throw new IllegalArgumentException("\"gHKF(t,p)\": "+ex.getMessage());}
if(Double.isNaN(rho)) throw new IllegalArgumentException("\"gHKF(t,p)\": could not calculate density at tC = "+tC+", pBar = "+pBar);
if( //rho < 0.35) { // limit given in Johnson et al (1992)
rho < 0.15) {
throw new IllegalArgumentException("\"gHKF(t,p)\": calculated density = "+rho+" at tC = "+tC+", pBar = "+pBar+" (must be >0.15 g/cm3)");
}
if(rho > 1.) {return 0;}
// Expressions in Johnson et al (1992)
// g = a (1 − ρ*)^b − f(T,P) (eq.49)
// a = a1 + a2 T + a3 T^2 (eq.50)
// b = b1 + b2 T + b3 T^2 (eq.51)
// ρ* = ρ(T,P) / (1 g/cm3)
// f(T,P) = [ ((T-155)/300)^(4.8)
// + c1 ((T-155)/300)^16 ]
// ×[c2 (1000−P)^3 + c3 (1000−P)^4] (eq.52)
//Table 2 in Johnson et al (1992)
double a1 = -2.037662, b1 = 6.107361;
double a2 = 5.747000E-3, b2 = -1.074377E-2;
double a3 = -6.557892E-6, b3 = 1.268348E-5;
//Table 3 in Johnson et al (1992)
double c1 = 36.6666, c2 = -1.504956E-10, c3 = 5.01799E-14;
double T = tC, P = pBar;
double f, w;
if(T < 155 || T > 355 || P < pSat || P > 1000) {f = 0;}
else {w = (T-155.)/300.;
f = (Math.pow(w,4.8) + c1*Math.pow(w,16.))
* ((c2*Math.pow((1000.-P),3.))+(c3*(Math.pow((1000.-P),4.))));}
double ag = (a1+a2*T+a3*T*T), bg = (b1+b2*T+b3*T*T);
return 1.e-10*((ag*(Math.pow((1.-rho),bg)))-f); // Convert Angstrom to metres
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="A_gamma(tC,pbar)">
/** Calculates the Debye-Hückel slope as defined in eqn(30) of:<br>
* Staples, B.R., Nuttall, R.L., 1977.The activity and osmotic coefficients of
* aqueous calcium chloride at 298.15 K.J. Phys. Chem. Ref. Data vol.6, p.385–407.<br>
* See also eqn(2-2) in:<br>
* Hamer, W.J. and Wu, Y.-C., 1972. Osmotic coefficients and mean activity
* coefficients of uni-univalent electrolytes in water at 25 °C.
* J. Phys. Chem. Ref. Data, vol.1, p.1047–1099.
*
* @param tC the temperature in degrees Celsius
* @param rho the density of water in g/cm3
* @param eps the dielectric constant of water at the given temperature and density (unitless)
* @return the Debye-Hückel slope in units of (kg/mol)^0.5
*/
static public double A_gamma(final double tC, final double rho, final double eps) {
if(Double.isNaN(tC) || Double.isNaN(rho) || Double.isNaN(eps)) {return Double.NaN;}
final double T = tC + T0;
// The Debye-Hückel slope is:
// ((1/ln(10))*(2*π*Na*ρ))^0.5
// * (e^2 / (4*π*ε0*ε*k*T))^(3/2)
// where:
// Na = 6.02214076e23 1/mol (Avogadro's number)
// ε0 = 8.8541878128e-12 F/m (permittivity of vacuum)
// e = 1.602176634e-19 C (elementary charge)
// k = 1.380649e-23 J/K (Boltzmann's constant)
// ρ = the density of water in g/cm^3
// ε = the dielectric constant of water
// T = the temperature in Kelvin
final double A = 1.8248117e6;
return A * Math.sqrt(rho) / Math.pow((eps * T),(3./2.));
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="B_gamma(tC,pbar)">
/** Calculates the Debye-Hückel slope as defined by eqn(35) in:<br>
* Staples, B.R., Nuttall, R.L., 1977. The activity and osmotic coefficients of
* aqueous calcium chloride at 298.15 K. J. Phys. Chem. Ref. Data, vol.6, p.385–407.<br>
* See also eqn(2-5) in:<br>
* Hamer, W.J. and Wu, Y.-C., 1972. Osmotic coefficients and mean activity
* coefficients of uni-univalent electrolytes in water at 25 °C.
* J. Phys. Chem. Ref. Data, vol.1, p.1047–1099.
*
* @param tC the temperature in degrees Celsius
* @param rho the density of water in g/cm3
* @param eps the dielectric constant of water at the given temperature and density (unitless)
* @return the Debye-Hückel parameter "B" in units of ((kg/mol)^0.5 * Å^-1)
*/
static public double B_gamma(final double tC, final double rho, final double eps) {
if(Double.isNaN(tC) || Double.isNaN(rho) || Double.isNaN(eps)) {return Double.NaN;}
final double T = tC + T0;
// The Debye-Hückel [B*å] constant is:
// ((8*π * Na * 1000)^(0.5) * e
// / (4*π*ε0*ε*k*T))^(0.5) * (ρ^0.5) * å
// where:
// Na = 6.02214076e23 1/mol (Avogadro's number)
// e = 1.602176634e-19 C (elementary charge)
// ε0 = 8.8541878128e-12 F/m (permittivity of vacuum)
// k = 1.380649e-23 J/K (Boltzmann's constant)
// ρ = the density of water in g/cm^3
// ε = the dielectric constant of water
// T = the temperature in Kelvin
// å = distance parameter in units of metres
final double B = 5.0290371e1;
return B * Math.sqrt(rho/(eps * T));
}
// </editor-fold>
}
| 20,739 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
IAPWSF95.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibChemDiagr/src/lib/kemi/H2O/IAPWSF95.java | package lib.kemi.H2O;
/** A set of routines used to calculate<ul>
* <li>The density of fluid water, using the "H2O" model in:<br>
* Wagner, W, Pruß, A (2002) The IAPWS Formulation 1995 for the thermodynamic
* properties of ordinary water substance for general and scientific use;
* Journal of Physical and Chemical Reference Data 31, 387–535. doi:10.1063/1.1461829.
* </li>
* <li>The dielectric constant of water<br>
* Fernández, D.P., Goodwin, A.R.H., Lemmon, E.W., Levelt Sengers, J.M.H.,
* Williams, R.C., 1997. A formulation for the static permittivity of water and
* steam at temperatures from 238 K to 873 K at pressures up to 1200 MPa,
* including derivatives and Debye–Hückel coefficients.
* Journal of Physical and Chemical Reference Data 26, 1125–1166.
* doi:10.1063/1.555997
* </li></ul>
* Copyright (C) 2015-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class IAPWSF95 {
public IAPWSF95() {}
/** Zero Celsius = 273.15 K */
public static final double T0 = 273.15; // K
/** triple point temperature = 273.16 K (= 0.01 C)*/
public static final double TRIPLE_POINT_T = 273.16; // K
/** triple point temperature = 0.01 C (= 273.16 K) */
public static final double TRIPLE_POINT_TC = 0.01; // C
/** triple point pressure = 611.657 Pa (= 0.0061 bar) */
public static final double TRIPLE_POINT_P = 611.657; // Pa
/** triple point pressure = 0.00611657 bar (= 611.657 Pa) */
public static final double TRIPLE_POINT_pBar = 0.00611657; // Pa
/** Critical temperature = 647.096 (+/- 0.01) K (= 373.946 C) */
public static final double CRITICAL_T = 647.096; // K
/** Critical temperature = 373.946 C (=647.096 K) */
public static final double CRITICAL_TC = 373.946; // C
/** Critical pressure = 22.064 (+/- 0.27) MPa (= 220.64 bar) */
public static final double CRITICAL_p = 22.064; // MPa
/** Critical pressure = 220.64 bar (= 22.064 MPa) */
public static final double CRITICAL_pBar = 220.64; // bar
/** Critical density = 322 (+/- 3) kg/m3 (= 0.322 g/cm3) */
public static final double CRITICAL_rho = 322; // kg/m3
//<editor-fold defaultstate="collapsed" desc="private constants">
/** temperature of melting ice Ih at highest pressure = 251.165 K (= -20.95 C) at p = 2085.66 bar */
private static final double MELTING_T_ICE_Ih_AT_HIGH_P = 251.165;
/** temperature of melting ice III at highest pressure = 256.164 K (=-16.986 C) at p = 3501 bar */
private static final double MELTING_T_ICE_III_AT_HIGH_P = 256.164;
/** temperature of melting ice V at highest pressure = 273.31 K (=+0.16 C) at p = 6324 bar */
private static final double MELTING_T_ICE_V_AT_HIGH_P = 273.31;
/** temperature of melting ice VI at highest pressure = 355 K (=+81.85 C) at p = 22 160 bar */
private static final double MELTING_T_ICE_VI_AT_HIGH_P = 355;
/** pressure of melting ice Ih at highest pressure = 208.566 MPa (=2085.66 bar) at T = 251.165 K (=-20.95C) */
private static final double MELTING_P_ICE_Ih_AT_HIGH_P = 208.566;
/** pressure of melting ice III at highest pressure = 350.1 MPa (=3501 bar) at T = 256.164 K (=-16.986 C) */
private static final double MELTING_P_ICE_III_AT_HIGH_P = 350.1;
/** pressure of melting ice V at highest pressure = 632.4 MPa (=6324 bar) at T = 273.31 K (=+0.16 C) */
private static final double MELTING_P_ICE_V_AT_HIGH_P = 632.4;
/** pressure of melting ice VI at highest pressure = 2216 MPa (=22160 bar) at T = 355 K (=+81.85 C) */
private static final double MELTING_P_ICE_VI_AT_HIGH_P = 2216;
/** the gas constant (kJ/(kg K)) for a molar mass for water = 18.015268 g/mol */
private static final double R = 0.46151805;
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="pSat(tC)">
/** Returns the saturation pressure (bar) of ordinary water substance, that is,
* the pressure at the vapor–liquid phase boundary, for a given temperature (in
* degrees Celsius). Uses eqn. (2.5) in Wagner, W., Pruß, A., 2002. "The IAPWS
* formulation 1995 for the thermodynamic properties of ordinary water substance
* for general and scientific use. Journal of Physical and Chemical Reference
* Data 31, 387–535. doi: 10.1063/1.1461829.<br>
* Note: it returns pressures below 1 bar at tC below 99.6059 C.
* If tC = 0, the pressure (0.00611657 bar) at the triple point (0.01 C) is returned.
* Range of conditions: 0.01 to 373.946 °C.
* It throws an exception outside this range.
*
* @param tC input temperature in degrees Celsius (>= 0 and < 373.946)
* @return the pressure in units of bar
* @throws IllegalArgumentException
*/
static public double pSat(final double tC) throws IllegalArgumentException {
if(Double.isNaN(tC)) throw new IllegalArgumentException("\"pSat\": tC = NaN");
if(tC == 0.) {return TRIPLE_POINT_pBar;}
else if(Math.abs(tC-25.)<0.01) {return 0.031698246;}
// Critical temperature = 647.096 (+/- 0.01) K (= 373.946 C)
if(tC < TRIPLE_POINT_TC || tC >= CRITICAL_TC) throw new IllegalArgumentException("\"pSat\": tC = "+tC+" (must be zero or >=0.01 and <373.946 C )");
final double a1 = -7.85951783, a2 = 1.84408259, a3 = -11.7866497, a4 = 22.6807411, a5 = -15.9618719,
a6 = 1.80122502;
final double tK = tC + T0;
double ϑ = 1.-(tK/CRITICAL_T);
double ln_pSat = Math.log(CRITICAL_p) + // CRITICAL_p = 22.064
(CRITICAL_T/tK)*
(a1*ϑ + a2*Math.pow(ϑ,1.5) + a3*Math.pow(ϑ,3)
+ a4*Math.pow(ϑ,3.5) + a5*Math.pow(ϑ,4) + a6*Math.pow(ϑ,7.5));
return Math.exp(ln_pSat)*10.; // convert MPa to bar
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="rhoSat(tC)">
/** Returns the density (g/cm3) of ordinary water substance at the
* vapor–liquid phase boundary, for a given temperature in
* degrees Celsius. Uses eqn. (2.6) in Wagner, W., Pruß, A., 2002. "The IAPWS
* formulation 1995 for the thermodynamic properties of ordinary water substance
* for general and scientific use. Journal of Physical and Chemical Reference
* Data 31, 387–535. DOI: 10.1063/1.1461829.<br>
* If tC = 0, the density (0.9997891 g/cm3) at the triple point
* (0.01 C and 0.00611657 bar) is returned.
* Range of conditions: 0.01 to 373.946 °C.
* It throws an exception outside this range.
*
* @param tC input temperature in degrees Celsius (>=0 and < 373.946)
* @return the density in units of g/cm3
* @throws IllegalArgumentException
*/
static public double rhoSat(final double tC)
throws IllegalArgumentException {
if(Double.isNaN(tC)) throw new IllegalArgumentException("\"rhoSat\": tC = NaN");
if(tC == 0.) {return 0.9997891;} // the calculated density at 0.01 C and 0.00611657 bar
else if(Math.abs(tC-25.)<0.01) {return 0.9969994;}
if(tC < TRIPLE_POINT_TC || tC >= CRITICAL_TC) throw new IllegalArgumentException("\"rhoSat\": tC = "+tC+" (must be zero or >=0.01 and <373.946 C )");
final double b1 = 1.99274064, b2 = 1.09965342, b3 = -0.510839303, b4 = -1.75493479,
b5 = -45.5170352, b6 = -6.74694450e+5;
final double tK = tC + T0;
final double ϑ = 1.-(tK/CRITICAL_T);
double rho = CRITICAL_rho *
(1.0 + b1*Math.pow(ϑ,(1./3.)) + b2*Math.pow(ϑ,(2./3.)) + b3*Math.pow(ϑ,(5./3.))
+ b4*Math.pow(ϑ,(16./3.)) + b5*Math.pow(ϑ,(43./3.)) + b6*Math.pow(ϑ,(110./3.)));
return rho/1000.;
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="rho(tC,pbar)">
/** Calculates the density (g/cm3) of liquid (or supercritical fluid) water
* at a given pressure (bar) and temperature (Celsius) using an iterative
* procedure and the "H2O" model in:
* Wagner, W., Pruß, A. (2002) The IAPWS Formulation 1995 for the thermodynamic
* properties of ordinary water substance for general and scientific use.
* Journal of Physical and Chemical Reference Data 31, 387–535. DOI: 10.1063/1.1461829.
* <p>
* Range of conditions: 0 to 10,000 bar, -30 to 1000°C.
* Throws an exception if outside this range, or if
* water is frozen at the requested conditions.
* If tC = 0 and pBar = 1, it returns the value at 0.01 Celsius and 1 bar.
* @param tC the input temperature in degrees Celsius
* @param pBar the input temperature in bar
* @return the density (g/cm3) of liquid (or supercritical fluid) water calculated
* with the equations of Wagner and Pruß, (2002).
* @throws IllegalArgumentException
* @throws ArithmeticException
*/
static public double rho(final double tC, final double pBar)
throws IllegalArgumentException, ArithmeticException {
// ---- debug print-out
boolean dbg = false;
// ----
if(Double.isNaN(tC)) throw new IllegalArgumentException("\"rho(T,P)\" tC = NaN");
if(tC < -30. || tC > 1000.001) throw new IllegalArgumentException("\"rho(T,P)\" tC = "+tC+" (must be >=-30 and <=1000 C)");
if(Double.isNaN(pBar)) throw new IllegalArgumentException("\"rho(T,P)\" pBar = NaN");
if(pBar > 10000.01 || pBar <= 0.) throw new IllegalArgumentException("\"rho(T,P)\" pBar = "+pBar+" (must be >=-30 and <=1000 C)");
final double t_C;
// if pressure = 1 bar and temperature = 0, set temperature to 0.01 C (tripple point of water)
if(pBar >0.99999 && pBar < 1.00001 && Math.abs(tC) < 0.001) {t_C = 0.01;} else {t_C = tC;}
String str = isWaterLiquid(t_C, pBar);
if(str.length() >0) throw new IllegalArgumentException("\"rho(T,P)\" "+str);
if(dbg) System.out.println("rho(T,P): input tC="+(float)t_C+", pbar="+(float)pBar);
double step = 0.010, r = 1.000, rMax = 2.000, rMin = 0, pMax = 1e25, pMin = -1e25, pCalc;
double rTop = 2.000, rBottom = 0;
double tolP = pBar*1e-7; // tolerance
if(t_C >= 0 && t_C <= CRITICAL_TC && pBar < CRITICAL_pBar) {
rMin = rhoSat(t_C); // g/cm3.
pCalc = pSat(t_C);
if(Math.abs(pBar-pCalc)<=tolP) {return rMin;}
rBottom = rMin*0.9;
}
// ---- Find two values of rho (rMin and rMax) separated less than 5 units (kg/m3), such
// that they give calculated pressures (pMin and pMax) above and below pbar
int sign, iter = 0, iterMax = 200;
while (Math.abs(rMax-rMin) > 0.005 || pMin < 0) {
r = Math.min(Math.max(r, rBottom),rTop);
if(r>0) {pCalc = p4rhoT(r, t_C, false) * 10.;} // convert MPa to bar
else {pCalc = 0;}
iter++;
if(Math.abs(pCalc-pBar) <= tolP || iter > iterMax) break;
if(pCalc < pBar) {
sign = +1;
if((pBar-pCalc) <= (pBar-pMin)) {pMin = pCalc; rMin = r;}
} else {
sign = -1;
if((pCalc-pBar) <= (pMax-pBar)) {pMax = pCalc; rMax = r;}
}
if(dbg) {System.out.println("iter="+iter+" r="+(float)r+" step="+(float)step+
", pCalc="+(float)pCalc+", pMin="+(float)pMin+
", pMax="+(float)pMax+", rMin="+(float)rMin+", rMax="+(float)rMax+", sign*step = "+(sign*step));}
if(pMin != -1e25 && pMax != 1e25) {step = 0.5*step;}
r = r + sign*step;
if(iter > iterMax) {
throw new ArithmeticException("\"rho("+(float)t_C+","+(float)pBar+")\": too many iterations."+
" rhoMin = "+(float)rMin+" at pMin="+(float)pMin+
", rhoMax = "+(float)rMax+" at pMax="+(float)pMax);
}
} // while
// ---- Now use "cord shooting"
double rOld = r, tolRho = Math.abs(r*1e-6);
iter = 0;
while(Math.abs(pMax-pMin)>tolP && Math.abs(rMax-rMin)>tolRho) {
iter++;
if(iter > iterMax) break;
r = rMin + (pBar - pMin) * ((rMax - rMin) / (pMax-pMin));
pCalc = p4rhoT(r, t_C, false) * 10.; // convert MPa to bar
if(pCalc < pBar) {
pMin = pCalc; rMin = r;
} else {
pMax = pCalc; rMax = r;
}
tolRho = Math.abs(r*1e-5);
if(Math.abs(r-rOld)<tolRho && Math.abs(pBar-pCalc)<tolP) {break;}
rOld = r;
if(iter > iterMax) {
throw new ArithmeticException("\"rho\": too many iterations."+
" rhoMin = "+(float)rMin+" at pMin="+(float)pMin+
", rhoMax = "+(float)rMax+" at pMax="+(float)pMax+"; target p="+(float)pBar);
}
if(dbg) System.out.println("iter="+iter+", r="+(float)r);
}
return r; // g/cm3
}
//<editor-fold defaultstate="collapsed" desc="p4rhoT(rho,tC,dbg)">
/** Calculates the pressure (MPa) at a given density (g/cm3) and temperature (Celsius)
* using the "H2O" model in:
* Wagner, W., Pruß, A. (2002) The IAPWS Formulation 1995 for the thermodynamic
* properties of ordinary water substance for general and scientific use.
* Journal of Physical and Chemical Reference Data 31, 387–535. DOI: 10.1063/1.1461829
*
* @param rho_gcm3 the input density in g/cm3
* @param tC the input temperature in degrees Celsius
* @param dbg if true then results of intermediate calculations are printed
* @return the pressure in MPa
*/
static private double p4rhoT(final double rho_gcm3, final double tC, boolean dbg) {
//<editor-fold defaultstate="collapsed" desc="(parameters)">
// the parameters in Table 6.2 of Wagner and Pruß, (2002)
final double[] n = new double[]{
0.12533547935523e-1,
0.78957634722828e1,
-0.87803203303561e1,
0.31802509345418,
-0.26145533859358,
-0.78199751687981e-2,
0.88089493102134e-2,
-0.66856572307965,
0.20433810950965,
-0.66212605039687e-4,
-0.19232721156002,
-0.25709043003438,
0.16074868486251,
-0.40092828925807e-1,
0.39343422603254e-6,
-0.75941377088144e-5,
0.56250979351888e-3,
-0.15608652257135e-4,
0.11537996422951e-8,
0.36582165144204e-6,
-0.13251180074668e-11,
-0.62639586912454e-9,
-0.10793600908932,
0.17611491008752e-1,
0.22132295167546,
-0.40247669763528,
0.58083399985759,
0.49969146990806e-2,
-0.31358700712549e-1,
-0.74315929710341,
0.47807329915480,
0.20527940895948e-1,
-0.13636435110343,
0.14180634400617e-1,
0.83326504880713e-2,
-0.29052336009585e-1,
0.38615085574206e-1,
-0.20393486513704e-1,
-0.16554050063734e-2,
0.19955571979541e-2,
0.15870308324157e-3,
-0.16388568342530e-4,
0.43613615723811e-1,
0.34994005463765e-1,
-0.76788197844621e-1,
0.22446277332006e-1,
-0.62689710414685e-4,
-0.55711118565645e-9,
-0.19905718354408,
0.31777497330738,
-0.11841182425981,
-0.31306260323435e2,
0.31546140237781e2,
-0.25213154341695e4,
-0.14874640856724,
0.31806110878444 };
final double[] a = new double[56];
final double[] b = new double[56];
final double[] B = new double[56];
final double[] C = new double[56];
final double[] D = new double[56];
final double[] A = new double[56];
final double[] α = new double[54];
final double[] β = new double[56];
final double[] γ = new double[54];
final double[] ε = new double[54];
for(int i=0; i<56; i++){
a[i]=Double.NaN;
b[i]=Double.NaN;
B[i]=Double.NaN;
C[i]=Double.NaN;
D[i]=Double.NaN;
A[i]=Double.NaN;
β[i]=Double.NaN;
if(i >= 54) continue;
α[i]=Double.NaN;
γ[i]=Double.NaN;
ε[i]=Double.NaN;
}
α[51]=20; β[51]=150; γ[51]=1.21; ε[51]=1;
α[52]=20; β[52]=150; γ[52]=1.21; ε[52]=1;
α[53]=20; β[53]=250; γ[53]=1.25; ε[53]=1;
a[54]=3.5; b[54]=0.85; B[54]=0.2; C[54]=28; D[54]=700; A[54]=0.32; β[54]=0.3;
a[55]=3.5; b[55]=0.95; B[55]=0.2; C[55]=32; D[55]=800; A[55]=0.32; β[55]=0.3;
final double[] c = new double[]{
Double.NaN,
Double.NaN,
Double.NaN,
Double.NaN,
Double.NaN,
Double.NaN,
Double.NaN,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
2,
2,
2,
2,
2,
2,
2,
2,
2,
2,
2,
2,
2,
2,
2,
2,
2,
2,
2,
2,
3,
3,
3,
3,
4,
6,
6,
6,
6,
Double.NaN,
Double.NaN,
Double.NaN };
final double[] d = new double[]{
1,
1,
1,
2,
2,
3,
4,
1,
1,
1,
2,
2,
3,
4,
4,
5,
7,
9,
10,
11,
13,
15,
1,
2,
2,
2,
3,
4,
4,
4,
5,
6,
6,
7,
9,
9,
9,
9,
9,
10,
10,
12,
3,
4,
4,
5,
14,
3,
6,
6,
6,
3,
3,
3 };
final double[] t = new double[]{
-0.5,
0.875,
1,
0.5,
0.75,
0.375,
1,
4,
6,
12,
1,
5,
4,
2,
13,
9,
3,
4,
11,
4,
13,
1,
7,
1,
9,
10,
10,
3,
7,
10,
10,
6,
10,
10,
1,
2,
3,
4,
8,
6,
9,
8,
16,
22,
23,
23,
10,
50,
44,
46,
50,
0,
1,
4 };
// </editor-fold>
double Δ, θ, ψ, δ_1_2, dψ_dδ,dΔbi_dδ,dΔ_dδ;
double sum7 = 0, sum51 = 0, sum54 = 0, sum56 = 0;
double tK = tC + T0; // absolute temperature
double τ = CRITICAL_T/tK; // inverse reduced temperature
final double rho = rho_gcm3 * 1000.; // convert to kg/m3
double δ = rho/CRITICAL_rho; // reduced density
// The first equation of Table 6.3 of Wagner and Pruß, (2002):
// p = (rho * R * tK) * ( 1 + δ * φr_δ );
// where φr_δ is the partial derivative of the residual part (φr) of
// the dimensionless Helmholtz free energy with respect to δ at constant τ
// This derivative is given as the second expresion in Table 6.5
// of Wagner and Pruß (2002). See also the derivatives of the
// distance function Δ^b[i] and of the exponential function ψ at the
// end of that table.
if(dbg) System.out.println("tK="+tK+", τ="+(float)τ+", δ="+(float)δ);
for(int i=54; i<56; i++) {
δ_1_2 = Math.pow(δ-1.,2.);
ψ = Math.exp(-C[i]*δ_1_2 -D[i]*Math.pow(τ-1.,2.));
θ = (1.-τ)+ A[i]*Math.pow(δ_1_2,(1./(2.*β[i])));
Δ = Math.pow(θ,2.) + B[i]*Math.pow(δ_1_2,a[i]);
dψ_dδ = -2.*C[i]*(δ-1.)*ψ;
dΔ_dδ = (δ-1.)*( A[i]*θ*(2./β[i])*Math.pow(δ_1_2,(1./(2.*β[i]))-1.)
+ 2.*B[i]*a[i]*Math.pow(δ_1_2,(a[i]-1.)) );
dΔbi_dδ = b[i]*Math.pow(Δ,b[i]-1.)*dΔ_dδ;
if(dbg) System.out.println("i="+i+", θ="+(float)θ+", ψ="+(float)ψ+", Δ="+(float)Δ
+", dψ_dδ="+(float)dψ_dδ+", dΔ_dδ="+(float)dΔ_dδ+", dΔbi_dδ="+(float)dΔbi_dδ);
sum56 = sum56 +n[i]
* ( Math.pow(Δ,b[i])*(ψ+δ*(dψ_dδ)) + dΔbi_dδ *δ*ψ );
}
for(int i=0; i<7; i++) {
sum7 = sum7 +n[i]*d[i]*Math.pow(δ,(d[i]-1.))*Math.pow(τ,t[i]);
}
for(int i=7; i<51; i++) {
sum51 = sum51 +n[i]*Math.exp(-Math.pow(δ,c[i]))
*( Math.pow(δ,(d[i]-1.))*Math.pow(τ,t[i])
*(d[i]-c[i]*Math.pow(δ,c[i])) );
}
for(int i=51; i<54; i++) {
sum54 = sum54 +n[i]*Math.pow(δ,d[i])*Math.pow(τ,t[i])
* Math.exp(-α[i]*Math.pow(δ-ε[i],2.)-β[i]*Math.pow(τ-γ[i],2.))
* ( (d[i]/δ)-2.*α[i]*(δ-ε[i]) );
}
// Add up "φr_δ": the partial derivative of the residual part (φr)
// with respect to δ at constant τ
double φr_δ = sum7 + sum51 + sum54 + sum56;
if(dbg) System.out.println("φr_δ="+(float)φr_δ);
// Calcuate the pressure using the first equation of Table 6.3
// of Wagner and Pruß, (2002)
double p = (rho * R * tK) * ( 1 + δ * φr_δ );
// System.out.println("( 1 + δ * φr_δ )="+( 1 + δ * φr_δ ));
return p/1000.; // convert to MPa units (the constant R is given in kJ instead of J)
}
// </editor-fold>
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="isWaterLiquid(tC,pbar)">
/** Finds out if water is liquid at the given input values of temperature and pressure.
* Uses the eqns.(6), (7), (8), (9) and (10) in:<br>
* Wagner, W., Riethmann, T., Feistel, R., Harvey, A.H., 2011. New equations for
* the sublimation pressure and melting pressure of H2O ice Ih. Journal of
* Physical and Chemical Reference Data vol.40, 043103. DOI:10.1063/1.3657937.<br>
*
* Note: to check if the pressure is below the water-saturated equilibrium line,
* the pressure is increased by 0.1 percent, so that if t=100°C and p=1.014 bar
* it does not return that steam is the stable phase in such conditions.
* @param tC the temperature in degrees Celsius
* @param pbar the pressure in bar
* @return an empty text string ("") if water is liquid at the given temperature
* and pressure, or a text sting specifying which phase (steam or ice) is
* stable for the given temperature and pressure
*/
static public String isWaterLiquid(final double tC, final double pbar) {
if(Double.isNaN(tC) || tC <= -T0) {
return "\"isWaterLiquid\": input temperature t="+tC+" C, must be > (-273.15) C.";}
if(Double.isNaN(pbar) || pbar > 206000. || pbar <= 0) {
return "\"isWaterLiquid\": input pressure p="+pbar+" bar, must be >0 and <206000 bar.";
}
if(Math.abs(25.-tC)<0.01 && pbar > 0.03169 && pbar < 9668.3) {return "";}
final double pMPa = pbar * 0.1; // convert to MPa
final double tK = tC + T0;
double p;
if(pbar < TRIPLE_POINT_pBar) {
return "Water exists as either steam or ice-Ih at p = "+pbar+" bar (pressure below the tripple point).";
}
if(pMPa <= CRITICAL_p && tK >= TRIPLE_POINT_T && tK <= CRITICAL_T) {
// above pSat = liquid, below pSat = steam
if(pbar*1.001 < pSat(tC)) {
return "Water exists as steam at: t = "+tC+" C and p = "+pbar+" bar.";
}
}
// --- divide the t-p diagram area into pressure intervals for the stability
// of the differend ice phases (Ih, III, V, VI and VII).
// Note that ice Ih melts when pressure is increased, while the other
// ice phases become more stable when pressure is increased.
if(pMPa < MELTING_P_ICE_Ih_AT_HIGH_P) { // ---- Ice Ih ----
if(tK >= TRIPLE_POINT_T) { // temperature above the tripple point
// whe have already excluded above the steam t-p area of stability...
// so above the tripple point it must be liquid
return "";
} else { // temperature below the tripple point but in the ice-Ih pressure range
p = p_melt_ice_Ih(tC);
if(!Double.isNaN(p) && pbar >= p) {
// ice-Ih melts when the pressure is increased;
// at higher pressures water is liquid
return "";
} else {
// the temperature is below the tripple point
// and the pressure is less than the melting point
if(Double.isNaN(p)) {return "Ice-Ih is the stable phase at t = "+tC+" C and p = "+pbar+" bar.";}
return "Ice-Ih is the stable phase at t = "+tC+" C and p = "+pbar+" bar (melting pressure: "+(float)p+" bar).";
}
}
} else if(pMPa < MELTING_P_ICE_III_AT_HIGH_P) { // ---- Ice III ----
// pressure above Ice Ih and in the Ice III pressure range
// (this is always above the critical point)
// For Ice III, V, VI and VII, the stability is increased with pressure
p = p_melt_ice_III(tC);
if(tK > MELTING_T_ICE_III_AT_HIGH_P || (!Double.isNaN(p) && pbar < p)) {return "";} else {
return "Ice-III is the stable phase at t = "+tC+" C and p = "+pbar+" bar.";
}
} else if(pMPa < MELTING_P_ICE_V_AT_HIGH_P) { // ---- Ice V ----
// pressure above Ice III and in the Ice V pressure range
// (this is always above the critical point)
// For Ice III, V, VI and VII, the stability is increased with pressure
p = p_melt_ice_V(tC);
if(tK > MELTING_T_ICE_V_AT_HIGH_P || (!Double.isNaN(p) && pbar < p)) {return "";} else {
return "Ice-V is the stable phase at t = "+tC+" C and p = "+pbar+" bar.";
}
} else if(pMPa < MELTING_P_ICE_VI_AT_HIGH_P) { // ---- Ice VI ----
// pressure above Ice V and in the Ice VI pressure range
// (this is always above the critical point)
// For Ice III, V, VI and VII, the stability is increased with pressure
p = p_melt_ice_VI(tC);
if(tK > MELTING_T_ICE_VI_AT_HIGH_P || (!Double.isNaN(p) && pbar < p)) {return "";} else {
return "Ice-VI is the stable phase at t = "+tC+" C and p = "+pbar+" bar.";
}
} else { // ---- Ice VII ----
// pressure above Ice VI and therefore in the Ice VII pressure range
// (this is always above the critical point)
// For Ice III, V, VI and VII, the stability is increased with pressure
p = p_melt_ice_VII(tC);
if(tK > 715 || (!Double.isNaN(p) && pbar < p)) {return "";} else {
return "Ice-VII is the stable phase at t = "+tC+" C and p = "+pbar+" bar.";
}
}
}
//<editor-fold defaultstate="collapsed" desc="private methods">
/** Returns the melting pressure of ice Ih, from the tripple point (273.16 K) to the
* boundary with ice III (251.165 K). Uses eqn.(6) in:
* Wagner, W., Riethmann, T., Feistel, R., Harvey, A.H., 2011. New equations for
* the sublimation pressure and melting pressure of H2O ice Ih. Journal of
* Physical and Chemical Reference Data vol.40, 043103. DOI:10.1063/1.3657937.
*
* @param tC the input temperature in degrees Celsius
* @return the melting pressure of ice Ih in bar
*/
static private double p_melt_ice_Ih(double tC) {
if(tC < (MELTING_T_ICE_Ih_AT_HIGH_P-T0-1e-5) || tC > (TRIPLE_POINT_TC+1e-5)) {return Double.NaN;}
final double a1 = 0.119539337e7, a2 = 0.808183159e5, a3 = 0.333826860e4,
b1 = 0.300000e1, b2 = 0.257500e2, b3 = 0.103750e3;
final double tK = tC + T0;
final double θ = (tK/TRIPLE_POINT_T);
double pi = 1.0 + a1*(1.-Math.pow(θ,b1)) + a2*(1.-Math.pow(θ,b2)) + a3*(1.-Math.pow(θ,b3));
return pi*TRIPLE_POINT_P*1.e-5; // convert to bar
}
/** Returns the melting pressure of ice III, from the boundary with ice Ih
* (251.165 K) to the boundary with ice V (256.164 K). Uses eqn.(7) in:
* Wagner, W., Riethmann, T., Feistel, R., Harvey, A.H., 2011. New equations for
* the sublimation pressure and melting pressure of H2O ice Ih. Journal of
* Physical and Chemical Reference Data vol.40, 043103. DOI:10.1063/1.3657937.
*
* @param tC the input temperature in degrees Celsius
* @return the melting pressure of ice III in bar
*/
static private double p_melt_ice_III(double tC) {
if(tC < (MELTING_T_ICE_Ih_AT_HIGH_P-T0-1e-5) || tC > (MELTING_T_ICE_III_AT_HIGH_P-T0+1e-5)) {return Double.NaN;}
final double tK = tC + T0;
final double θ = (tK/MELTING_T_ICE_Ih_AT_HIGH_P);
double pi = 1.0 - 0.299948 * (1.-Math.pow(θ,60.));
return pi*MELTING_P_ICE_Ih_AT_HIGH_P*10.; // convert to bar
}
/** Returns the melting pressure of ice V, from the boundary with ice III
* (256.164 K) to the boundary with ice VI (273.31 K). Uses eqn.(8) in:
* Wagner, W., Riethmann, T., Feistel, R., Harvey, A.H., 2011. New equations for
* the sublimation pressure and melting pressure of H2O ice Ih. Journal of
* Physical and Chemical Reference Data vol.40, 043103. DOI:10.1063/1.3657937.
*
* @param tC the input temperature in degrees Celsius
* @return the melting pressure of ice V in bar
*/
static private double p_melt_ice_V(double tC) {
if(tC < (MELTING_T_ICE_III_AT_HIGH_P-T0-1e-5) || tC > (MELTING_T_ICE_V_AT_HIGH_P-T0+1e-5)) {return Double.NaN;}
final double tK = tC + T0;
final double θ = (tK/MELTING_T_ICE_III_AT_HIGH_P);
double pi = 1.0 - 1.18721 * (1.-Math.pow(θ,8.));
return pi*MELTING_P_ICE_III_AT_HIGH_P*10.; // convert to bar
}
/** Returns the melting pressure of ice VI, from the boundary with ice V
* (273.31 K) to the boundary with ice VII (355 K). Uses eqn.(9) in:
* Wagner, W., Riethmann, T., Feistel, R., Harvey, A.H., 2011. New equations for
* the sublimation pressure and melting pressure of H2O ice Ih. Journal of
* Physical and Chemical Reference Data vol.40, 043103. DOI:10.1063/1.3657937.
*
* @param tC the input temperature in degrees Celsius
* @return the melting pressure of ice VI in bar
*/
static private double p_melt_ice_VI(double tC) {
if(tC < (MELTING_T_ICE_V_AT_HIGH_P-T0-1e-5) || tC > (MELTING_T_ICE_VI_AT_HIGH_P-T0+1e-5)) {return Double.NaN;}
final double tK = tC + T0;
final double θ = (tK/MELTING_T_ICE_V_AT_HIGH_P);
double pi = 1.0 - 1.07476 * (1.-Math.pow(θ,4.6));
return pi*MELTING_P_ICE_V_AT_HIGH_P*10.; // convert to bar
}
/** Returns the melting pressure of ice VII, from the boundary with ice V
* (273.31 K) to the boundary with ice VII (355 K). Uses eqn.(10) in:
* Wagner, W., Riethmann, T., Feistel, R., Harvey, A.H., 2011. New equations for
* the sublimation pressure and melting pressure of H2O ice Ih. Journal of
* Physical and Chemical Reference Data vol.40, 043103. DOI:10.1063/1.3657937.
*
* @param tC the input temperature in degrees Celsius
* @return the melting pressure of ice VII in bar
*/
static private double p_melt_ice_VII(double tC) {
if(tC < (MELTING_T_ICE_VI_AT_HIGH_P-T0-1e-5) || tC > (715-T0+1e-5)) {return Double.NaN;}
final double tK = tC + T0;
final double θ = (tK/MELTING_T_ICE_VI_AT_HIGH_P);
double lnPi = 1.73683 * (1.-(1/θ)) - 0.0544606 * (1.-Math.pow(θ,5))
+ 0.806106e-7 * (1.-Math.pow(θ,22));
return Math.exp(lnPi)*2216.*10.; // convert to bar
}
// </editor-fold>
// </editor-fold>
}
| 31,264 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
Interpolate.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibChemDiagr/src/lib/kemi/interpolate/Interpolate.java | package lib.kemi.interpolate;
/** Interpolation methods.
*
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class Interpolate {
private static final String nl = System.getProperty("line.separator");
//<editor-fold defaultstate="collapsed" desc="logKinterpolateTP">
/** Returns the value of logK at the requested tC and pBar, interpolated
* from a provided array grid, at temperatures (0 to 600 C)
* and pressures (1 to 5000 bar).
* @param tC the input temperature in degrees Celsius
* @param pBar the input pressure in bar
* @param logKarray an array of logK values (logKarray[5][14])
* with pressures as the first index {pSat, 500, 1000, 3000 and 5000} and
* temperatures as the second index
* {0,25,50,100,150,200,250,300,350,400,450,500,550,600}, where pSat is the
* liquid-vapour saturated pressure (for temperatures below the critical point).
* <b>Note:</b> provide NaN (Not-a-Number) where no data is available,
* for example at a pressure = 500 bar and temperatures above 450C, etc.
* @return the value of logK interpolated at the provided values of tC and pBar
*/
public static float logKinterpolateTP(final float tC, final float pBar,
final float[][] logKarray) throws IllegalArgumentException {
//-------------------
boolean dbg = false;
//-------------------
// index: 0 1 2 3 4 5 6 7 8 9 10 11 12 13
final float[] temperatures = new float[]{0f,25f,50f,100f,150f,200f,250f,300f,350f,400f,450f,500f,550f,600f};
// index: 0 1 2 3 4
final float[] pressures = new float[]{1f,500f,1000f,3000f,5000f};
// index: 0 1 2 3 4 5 6 7 8 9 10 11 12 13
// temperature: 0 25 50 100 150 200 250 300 350 C 400C 450C 500C 550C 600C
final float[] pSat = new float[]{1f, 1f, 1f,1.0141f,4.7615f,15.549f,39.762f,85.878f,165.29f, 300f,500f,650f,800f,950f};
if(logKarray == null) {
throw new IllegalArgumentException("\"interpolate3D\": logKarray = \"null\"");}
if(Float.isNaN(tC) || Float.isNaN(pBar)) {
throw new IllegalArgumentException("\"interpolate3D\": tC = "+tC+", pBar = "+pBar+"; both must be numbers");}
if(tC < 0 || tC > temperatures[temperatures.length-1]) {
throw new IllegalArgumentException("\"interpolate3D\": tC = "+tC+", must be >"+temperatures[0]+" and <"+temperatures[temperatures.length-1]);}
if(pBar < 1 || pBar > pressures[pressures.length-1]) {
throw new IllegalArgumentException("\"interpolate3D\": pBar = "+pBar+", must be >"+pressures[0]+" and <"+ pressures[pressures.length-1]);}
if(logKarray.length != pressures.length) {
throw new IllegalArgumentException("\"interpolate3D\": length of logKarray must be "+pressures.length);}
for(int i = 0; i < pressures.length; i++) {
if(logKarray[i] == null) {throw new IllegalArgumentException("\"interpolate3D\": logKarray["+i+"] = \"null\"");}
}
// --- Locate the place in the tables of temperatures and pressures,
// given tC and pBar (at which the logK evaluation is desired).
java.awt.Point indx = indexer3D(tC,pBar,temperatures,pressures, dbg);
int iT = indx.x, iP = indx.y;
// --- The values of "iT,iP" define a 3x3 matrix of temperature and pressure
// (iT-2, iT-1, iT)x(iP,iP+1,iP+2). The values of tC and pBar are inside
// this sub-grid of logKarray. If a NaN value for logK is found at some
// of the edges of this 3x3: grid move the grid (if possible).
int iTnew = iT, iPnew = iP;
double[] press = new double[pressures.length];
for(int i = 0; i < pressures.length; i++) {press[i] = pressures[i];}
for(int i = iT-2; i <= iT; i++) {
if(i == iT-1) {continue;}
for(int j = iP; j <= iP+2; j++) {
if(j == iP+1) {continue;}
if(temperatures[i] <= 400 && press[j] < 1.1) {press[j] = pSat[i];}
else if(temperatures[i] > 450 && press[j] > 500 && press[j] <= 1000) {press[j] = pSat[i];}
if(Double.isNaN(logKarray[j][i])) {
if(j == iP) {
if(pBar >= press[iP] && iP+3 < pressures.length) {iPnew++; break;}
} else if(j == iP+2) {
if(pBar <= press[iP+2] && iP > 0) {iPnew--; break;}
}
if(i == iT-2) {
if(tC >= temperatures[iT-2] && iT+1 < temperatures.length) {iTnew++; break;}
} else if(i == iT) {
if(tC <= temperatures[iT] && iT > 2) {iTnew--; break;}
}
}
}
if(iT != iTnew || iP != iPnew) {break;}
}
iT = iTnew; iP = iPnew;
if(dbg){if(temperatures[iT] <= 400 && press[iP] < 1.1) {press[iP] = pSat[iT];}
else if(temperatures[iT] > 450 && press[iP] > 500 && press[iP] <= 1000) {press[iP] = pSat[iT];}
System.out.println("\"interpolate3D\": tC="+tC+", pBar="+pBar+
", new x="+iT+", y="+iP+";"+
" t["+iT+"]="+temperatures[iT]+","+
" p["+iP+"]="+press[iP]);}
// Get three (3) interpolated logK's at the selected pressure,
// at the three temperatures bracketing the selected temperature.
// Note that lowest iT value passed by indexer3D is 2 and the
// lowest iP value passed is 0.
// The highest values are (temperatures.length-1) and (pressures.length-3).
float sum, logK,pK,pJ;
float[] lgK = new float[3];
for(int i = 0; i < lgK.length; i++) {lgK[i] = 0f;}
logK = 0f;
int i,j,k,l = 0;
for(i = iT-2; i <= iT; i++) {
for(j = iP; j <= iP+2; j++) {
sum = logKarray[j][i];
for(k = iP; k <= iP+2; k++) {
if(k != j) {
pK = pressures[k]; pJ = pressures[j];
if(temperatures[i] <= 400) {
// 1st pressure (="1"): at tC < 400C use pSat instead of "1"
if(k == 0) {pK = pSat[i];} else if(j == 0) {pJ = pSat[i];}
}
if(temperatures[i] > 450) {
// 2nd pressure (="500"): at tC > 450C use the pSat array
if(k == 1) {pK = pSat[i];} else if(j == 1) {pJ = pSat[i];}
}
sum = sum *(pBar-pK)/(pJ-pK);
}
}
lgK[l] = lgK[l] + sum;
}
l++;
}
if(dbg) {
System.out.println("tC="+tC+", pBar="+pBar+", iT="+iT+", iP="+iP+" lgK 0 to 2 = "+java.util.Arrays.toString(lgK));
System.out.println("temperatures 0 to "+(temperatures.length-1)+", pressures 0 to "+(pressures.length-1));
}
// Interpolate logK at the selected temperature using
// the three temperature values in lgK[]
k = 0;
for(i = iT-2; i <= iT; i++) {
sum = lgK[k];
for(j = iT-2; j <= iT; j++) {
if(j != i) {sum = sum *(tC-temperatures[j])/(temperatures[i]-temperatures[j]);}
}
logK = logK + sum;
k++;
}
if(dbg) {System.out.println("tC="+tC+", pBar="+pBar+", iT="+iT+", iP="+iP+" logK = "+logK);}
return logK;
}
//<editor-fold defaultstate="collapsed" desc="indexer3D">
/** Returns array indices using the specified temperature and pressure.
*
* For <b>temperature</b>, the minimum value returned is 2 so that the first
* three temperature values may be used for the subsequent extrapolation.
* For example, if the temperature array is [0, 25, 50, 100, 150], with indices
* 0 to 4, then if tC=5 or tC=45, the returned index value is 2, but if tC=85,
* the returned value is 3 (so that temperatures 25, 50 and 100 may be used
* for the extrapolation).
*
* For <b>pressure</b>, the returned value is always less
* than (length-3), so that the last three pressures may be used for the
* subsequent extrapolation. For example if the pressure array is
* [1, 500, 1000, 3000, 5000], with indices 0 to 4, then if pBar = 4500
* the returned "y" value is 2 (so that the pressures 1000, 3000 and 5000 may
* be used for the subsequent extrapolation), but if pBar = 50, the returned
* value is 0 (pressures 1, 500 and 1000 may be used for the extrapolation).
*
* @param tC temperature in degrees C
* @param pBar pressure in bar
* @param temperatures array of temperature values
* @param pressures array of pressure values
* @return the index for the temperature as "x" and the index for the pressure
* as the "y" fields */
private static java.awt.Point indexer3D(final float tC, final float pBar,
final float[] temperatures, final float[] pressures, final boolean dbg)
throws IllegalArgumentException {
int iT,iP;
if(temperatures.length <=3 || pressures.length <= 3) {
throw new IllegalArgumentException("\"indexer3D\": "+
"the length of the temperature and pressure arrays must be >3.");}
int jLow = 0, jUpp = temperatures.length-1, jMid;
if(tC < temperatures[jLow] || tC > temperatures[jUpp]) {
throw new IllegalArgumentException("\"indexer3D\": t = "+tC+
" must be >="+temperatures[jLow]+" and <="+temperatures[jUpp]);}
if(tC == temperatures[jLow]) {iT = jLow;}
else if(tC == temperatures[jUpp]) {iT = jUpp;}
else{
while((jUpp - jLow) > 1) {
jMid = (jLow + jUpp) /2;
if(tC > temperatures[jMid]) {jLow = jMid;} else {jUpp = jMid;}
}
iT = jUpp;
}
iT = Math.min(temperatures.length-1,Math.max(2, iT));
jLow = 0; jUpp = pressures.length-1;
if(pBar < pressures[jLow] || pBar > pressures[jUpp]) {
throw new IllegalArgumentException("\"indexer3D\": p = "+pBar+
" must be >="+pressures[jLow]+" and <="+pressures[jUpp]);}
if(pBar <= pressures[jLow]) {iP = jLow;}
else if(pBar > pressures[jUpp]) {iP = jUpp;}
else{
while((jUpp - jLow) > 1) {
jMid = (jLow + jUpp) /2;
if(pBar >= pressures[jMid]) {jLow = jMid;} else {jUpp = jMid;}
}
iP = jLow;
}
iP = Math.min(pressures.length-3,Math.max(0, iP));
if(dbg) {System.out.println("\"indexer3D\": tC="+tC+", pBar="+pBar+
", returns x="+iT+", y="+iP+";"+
" t["+iT+"]="+temperatures[iT]+","+
" p["+iP+"]="+pressures[iP]);}
java.awt.Point indexes = new java.awt.Point();
indexes.x = iT;
indexes.y = iP;
return indexes;
}
//</editor-fold>
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="logKinterpolatePsat">
/** Returns the value of logK at the requested tC, interpolated
* from the provided array, at temperatures 0 to 350 C
* @param tC the input temperature in degrees Celsius
* @param logKarray an array of logK values (logKarray[9]) at
* the temperatures {0,25,50,100,150,200,250,300,350} corresponding
* to saturated vapor pressure. Set absent logK values to not-a-number (NaN).
* @return the value of logK interpolated at the provided tC value */
public static float logKinterpolatePsat(final float tC, final float[] logKarray) {
// index: 0 1 2 3 4 5 6 7 8
final float[] temperatures = new float[]{0f,25f,50f,100f,150f,200f,250f,300f,350f};
if(logKarray.length != temperatures.length) {
throw new IllegalArgumentException("\"interpolate2D\": the length of logKarray must be "+temperatures.length+".");
}
// Locate the place in the table of temperatures
// of tC (at which the logK evaluation is desired).
int min = 0, max = temperatures.length-1;
for (int i = 0; i < temperatures.length; i++) {
if(!Float.isNaN(logKarray[i])) {min = i; break;}
}
for (int i = temperatures.length-1; i > -1; i--) {
if(!Float.isNaN(logKarray[i])) {max = i; break;}
}
for (int i = min; i <= max; i++) {
if(Float.isNaN(logKarray[i])) {
throw new IllegalArgumentException("\"interpolate2D\": found NaN value in logKarray["+i+"], in between two numeric values.");
}
}
// -----------------
// Special cases
// -----------------
// --- out of range?
if(tC < 0 || tC > temperatures[max]+50
|| tC > 370) { // the critical temperature is 374 C
return Float.NaN;
}
// --- only logK data at one temperature is given (25C), and tC "close to" this temperature
if(min == max) {
if(tC >= (temperatures[min]-15) && tC <= (temperatures[min]+15)) {
//System.out.println("\"interpolate2D\": tC="+tC+", only logK data at 25C provided, and tC \"close to\" 25C");
return logKarray[min];
}
else {return Float.NaN;}
}
// --- only two logK values are given
// if tC is between them use linear interpolation
if((max-min) == 1) {
// data at 25 and 50C given, and tC between 0 and 75 C
if((min == 1 && max ==2 && tC >= 0 && tC <= 75)
// or tC within the two temperature values +/- 15C
|| (tC >= (temperatures[min]-15) && tC <= (temperatures[max]+15))) {
//System.out.println("\"interpolate2D\": tC="+tC+", only logK data at 25 and 50C provided, and tC between 0 and 75 C");
return logKarray[min]
+(tC-temperatures[min])*(logKarray[max]-logKarray[min])
/(temperatures[max]-temperatures[min]);
} else {return Float.NaN;}
}
// -----------------------------------
// General case:
// three or more logK values given
// -----------------------------------
int iT = min;
for(int i = min; i < max; i++) {
if(tC > temperatures[i] && tC <=temperatures[i+1]) {iT = i; break;}
}
if(tC > temperatures[max]) {iT = max-1;}
//System.out.println("\"interpolate2D\": tC="+tC+", iT="+iT+", logKarray["+iT+"]="+logKarray[iT]+", min="+min+" max="+max);
float sum, lgK = 0;
int forMin, forMax;
// --- if tC <= the second temperature value, use the 3 smallest temperature values
if(iT <= min) {forMin = min; forMax = min+2;}
// --- if tC >= next to last temperature value, use the 3 largest temperature values
else if(iT >= max-1) {forMin = max-2; forMax = max;}
// --- else use two temperature values below and one above tC
else {forMin = iT-1; forMax = iT+1;}
// ---
for(int i = forMin; i <= forMax; i++) {
sum = logKarray[i];
for(int j=forMin; j <= forMax; j++) {
if(j != i) {
sum = sum*(tC-temperatures[j])/(temperatures[i]-temperatures[j]);
}
}
lgK = lgK + sum;
}
//System.out.println("\"interpolate2D\": returns "+lgK);
return lgK;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="not used">
//<editor-fold defaultstate="collapsed" desc="interpolate">
/** Given arrays x[] and y[], each of the same length, with the
* x[] values sorted, and given a value xx,
* this procedure returns an interpolated value yy.
* @param x array of x-values
* @param y the corresponding y-values
* @param xx the target
* @return the interpolated y-value corresponding to the target x-value.
* Returns NaN (not-a-number) if xx is outside the range of x[]
//
public static float interpolate(final float[] x, final float[] y, final float xx)
throws IllegalArgumentException {
if(y.length != x.length) {
throw new IllegalArgumentException("\"interpolation\": the length of y-array must be "+x.length+".");
}
// Locate the place in the table of x-values
// of xx (at which the evaluation of y is desired).
int min = 0, max = x.length-1;
for (int i = 0; i < x.length; i++) {
if(!Float.isNaN(y[i])) {min = i; break;}
}
for (int i = x.length-1; i > -1; i--) {
if(!Float.isNaN(y[i])) {max = i; break;}
}
for (int i = min; i <= max; i++) {
if(Float.isNaN(y[i])) {
throw new IllegalArgumentException("\"interpolation\": found NaN value in y["+i+"], between two numeric values.");
}
}
// -----------------
// Special cases
// -----------------
// --- out of range?
if(xx < x[min] || xx > x[max]) {return Float.NaN;}
// --- only y value at one x value is given, and xx "close to" this x value
if(min == max) {
if(xx >= (x[min]*0.95) && xx <= (x[min]+1.05)) {
//System.out.println("\"interpolation\": xx="+xx+" and only \"y\" data at x="+x[min]+" provided.");
return y[min];
}
else {return Float.NaN;}
}
// --- only two y values are given
// if xx is between them use linear interpolation
if((max-min) == 1) {
if(xx >= (x[min]-0.95) && xx <= (x[max]+1.05)) {
//System.out.println("\"interpolation\": xx="+xx+", only \"y\" data x = "+x[min]+" and "+x[max]+" provided.");
return y[min]
+(xx-x[min])*(y[max]-y[min])
/(x[max]-x[min]);
} else {return Float.NaN;}
}
// -----------------------------------
// General case:
// three or more y values given
// -----------------------------------
int ix = min;
for(int i = min; i < max; i++) {
if(xx > x[i] && xx <=x[i+1]) {ix = i; break;}
}
if(xx > x[max]) {ix = max-1;}
//System.out.println("\"interpolation\": xx="+xx+", ix="+ix+", y["+ix+"]="+y[ix]+", min="+min+" max="+max);
float sum, yy = 0;
int forMin, forMax;
// --- if xx <= the second y value, use the 3 smallest y values
if(ix <= min) {forMin = min; forMax = min+2;}
// --- if xx >= next to last y value, use the 3 largest y values
else if(ix >= max-1) {forMin = max-2; forMax = max;}
// --- else use two y values below and one above xx
else {forMin = ix-1; forMax = ix+1;}
// ---
for(int i = forMin; i <= forMax; i++) {
sum = y[i];
for(int j=forMin; j <= forMax; j++) {
if(j != i) {
sum = sum*(xx-x[j])/(x[i]-x[j]);
}
}
yy = yy + sum;
}
//System.out.println("\"interpolation\": returns "+yy);
return yy;
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="rationalInterpolation">
/** Rational interpolation (1-dimensional interpolation):
* Given arrays xTable and yTable, each of the same length, with the
* xTable values sorted, and given a value x,
* this procedure returns an interpolated value y.
* @param xTable array of x-values
* @param yTable the corresponding y-values
* @param x the target
* @return the interpolated y-value corresponding to the target x-value
public static double rationalInterpolation(double[] xTable, double[] yTable, double x)
throws IllegalArgumentException, ArithmeticException {
//adapted from: NUMERICAL RECIPES. THE ART OF SCIENTIFIC COMPUTING.
// by W.H.Press, B.P.Flannery, S.A.Teukolsky and W.T.Vetterling
// Cambridge University Press, Cambridge (1987), p. 85
if(xTable == null) {
throw new IllegalArgumentException(
"Error in \"rationalInterpolation\"; xTable = \"null\"");
}
int nTable = xTable.length;
if(nTable < 2) { // at least two points needed for an interpolation
throw new IllegalArgumentException(
"Error in \"rationalInterpolation\"; length of array < 2.");
}
for(int i=0; i < nTable; i++) {
if(Double.isNaN(xTable[i])) {
throw new IllegalArgumentException(
"Error in \"rationalInterpolation\"; xTable["+i+"] = NaN.");
}
}
for(int i=1; i < nTable; i++) {
if(xTable[i] < xTable[i-1]) {
throw new IllegalArgumentException(
"Error in \"rationalInterpolation\"; x-values not in ascending order.");
}
}
if(x > xTable[nTable-1] || x < xTable[0]) {
throw new IllegalArgumentException(
"Error in \"rationalInterpolation\"; x = "+x+nl+
" is outside interpolation range.");
}
if(yTable == null) {
throw new IllegalArgumentException(
"Error in \"rationalInterpolation\"; yTable = \"null\"");
}
if(yTable.length != nTable) {
throw new IllegalArgumentException(
"Error in \"rationalInterpolation\"; length of arrays are not equal.");
}
for(int i=0; i < nTable; i++) {
if(Double.isNaN(yTable[i])) {
throw new IllegalArgumentException(
"Error in \"rationalInterpolation\"; yTable["+i+"] = NaN.");
}
}
double y;
double tiny = 1e-25; // a small number
double dist, t;
//-- yErr = error estimate
double yErr;
double[] c = new double[nTable];
double[] d = new double[nTable];
//-- get closest table entry
double delta =Math.abs(x-xTable[0]);
int nClose = 0;
for(int i=0; i < nTable; i++) {
dist = Math.abs(x-xTable[i]);
if(dist <= 0) {
y = yTable[i];
return y;
}
if(dist < delta) {nClose = i; delta = dist;}
c[i] = yTable[i];
d[i] = yTable[i] + tiny; // "tiny" is needed to prevent a rare zero-over-zero condition
} //for i
y = yTable[nClose];
nClose--;
for(int m =1; m < nTable; m++) {
for(int i =0; i < nTable-m; i++) {
dist = xTable[i+m] -x; // can't be zero, we checked above
t = (xTable[i]-x)*d[i]/dist;
delta = t - c[i+1];
if(delta == 0) {
throw new ArithmeticException(
"Error in \"rationalInterpolation\": Pole at the requested value of x="+x);
}
delta = (c[i+1]-d[i]) / delta;
d[i] = c[i+1] * delta;
c[i] = t * delta;
} //for i
if(2*nClose < nTable - m) {
yErr = c[nClose+1];
} else {
yErr = d[nClose]; nClose--;
}
y = y + yErr;
} //for m
return y;
} //rationalInterpolation()
//</editor-fold>
*/
//</editor-fold>
}
| 22,796 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
ReadDataLib.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibChemDiagr/src/lib/kemi/readDataLib/ReadDataLib.java | package lib.kemi.readDataLib;
import lib.common.Util;
/** Read data from an input file where data is separated by commas,
* white space, or end-of-line. The procedures used are <code>readA</code>,
* <code>readI</code>, <code>readR</code> and <code>readLine</code>.
*
* Comments may be added to any line after a "/" if it is the 1st
* non-blank character in the line, or if "/" follows either a comma or a blank.
*
* Text strings begin at the 1st non-blank character and must end either
* with a comma, an End-Of-Line or an End-Of-File.
* Therefore text strings may contain blank space, but not commas.
* Also text strings may not contain the sequence " /" (which indicates the
* beginning of a comment)
*
* A comma following another comma or following an end-of-line is taken
* to be either a zero or an empty string.
*
* Comments may be retrieved with the variable <code>dataLineComment</code>,
* which contains the comment in the input line for the last data item retrieved
* (using either <code>readA</code>, <code>readI</code> or <code>readR</code>).
* This means that a comment written in a line by itself can only be retrieved
* using the procedure <code>readLine</code>.
*
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class ReadDataLib {
//--- public ---
/** Provided by the user before calling the "readI()", "readR()", etc,
* so that info if an error occurs may be provided. */
public String nowReading;
/** Set by this class to the name of the intput data file. Not to be changed */
public String dataFileName;
/** It will contain the comment (if any) corresponding to the line read from
* the input file when reading the last data value. Not to be changed. */
public StringBuffer dataLineComment;
/** Set by this class to:
* <pre> =1 if the comment at the end of the first line contains
* either "HYDRA" or "DATABASE";
* =2 if the comment contains either "MEDUSA" or "SPANA";
* =0 otherwise.</pre>
* Not to be changed
* @see lib.kemi.chem.Chem.Diagr#databaseSpanaFile databaseSpanaFile
*/
public int fileIsDatabaseOrSpana;
//--- private ---
private String temperatureString = null;
/** what units are given after the temperature in the comment
* in the first line:<br>
* false = given as "t=25" (no units) or "t=25 C" (Celsius = default)<br>
* true = given as "t=298 K"<br>
* Note: the units for temperature are not case-sensitive
* (it is OK to write: T=298k). */
private boolean temperatureUnitsK = false;
private String temperatureDataLineNextOriginal = null;
private String pressureString = null;
/** what units are given after the pressure in the comment
* in the first line:<br>
* 0= given as "p=1" (no units) or "p=1 bar" (bar = default)<br>
* 1= given as "p=1 atm"<br>
* 2= given as "p=1 MPa"<br>
* Note: the units for pressure are not case-sensitive. */
private int pressureUnits = 0;
private String pressureDataLineNextOriginal = null;
private java.io.BufferedReader inputBuffReader;
/** this is a temporary working string where data separated by commas are read.
* Comments have been removed. When a value is read, the corresponding part
* (at the left) of <code>thisDataLine</code> is removed. For example,
* if <code>thisDataLine</code> contains "3,5,1," and a value is read then
* <code>thisDataLine</code> will contain "5,1," and the value read is 3. */
private StringBuffer thisDataLine;
/** the original line in the data file that was read. Comments included.
* Used for example in error reporting. */
private StringBuffer thisDataLineOriginal;
private StringBuffer nextDataLine;
private StringBuffer nextDataLineOriginal;
private String nextDataLineComment;
private boolean reading1stLine;
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
//<editor-fold defaultstate="collapsed" desc="ReadDataLib constructor">
/** Create an instance of this class associated with an input data file.
* @param inpF Input text file.
* @throws lib.kemi.readDataLib.ReadDataLib.DataFileException
*/
public ReadDataLib(java.io.File inpF) throws DataFileException {
if(inpF == null) {
throw new DataFileException("Error in \"ReadDataLib\": input file is \"null\"!");
}
dataFileName = inpF.getPath();
if(!inpF.exists()) {
throw new DataFileException("Error in \"ReadDataLib\": input file does not exist"+nl+" \""+dataFileName+"\"");
}
if(!inpF.canRead()) {
throw new DataFileException("Error in \"ReadDataLib\": can not read input file"+nl+" \""+dataFileName+"\"");
}
inputBuffReader = null;
try {inputBuffReader = new java.io.BufferedReader(
new java.io.InputStreamReader(new java.io.FileInputStream(inpF),"UTF8"));
} catch(Exception ex) {
throw new DataFileException("Error in \"ReadDataLib\": "+ex.getMessage()+nl+
" with input file:\""+dataFileName+"\"");}
temperatureDataLineNextOriginal = null;
temperatureString = null;
temperatureUnitsK = false;
pressureDataLineNextOriginal = null;
pressureString = null;
pressureUnits = 0;
fileIsDatabaseOrSpana = 0;
reading1stLine = true;
nowReading = null;
thisDataLine = null;
thisDataLineOriginal = null;
nextDataLine = new StringBuffer();
nextDataLineOriginal = new StringBuffer();
dataLineComment = new StringBuffer();
} //ReadDataLib constructor
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="close()">
/** Close the input file
* @throws lib.kemi.readDataLib.ReadDataLib.ReadDataLibException
*/
public void close() throws ReadDataLibException {
try {if (inputBuffReader != null) {inputBuffReader.close();}}
catch (java.io.IOException ex) {
throw new ReadDataLibException("Error in \"ReadDataLib.close\": "+ex.getMessage());
}
finally {
dataFileName = null;
nowReading = null;
thisDataLine = null;
thisDataLineOriginal = null;
dataLineComment = null;
nextDataLine = null;
nextDataLineOriginal = null;
nextDataLineComment = null;
pressureDataLineNextOriginal = null;
pressureString = null;
temperatureDataLineNextOriginal = null;
temperatureString = null;
}
} // close()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="String readA()">
/** Read a text string from the input file.
* Note that a text begins with the first non-blank character and it
* ends with either a comma or an end-of-line: it may contain embedded spaces.
* @return the next text string from the input file.
* @throws lib.kemi.readDataLib.ReadDataLib.DataReadException
* @throws lib.kemi.readDataLib.ReadDataLib.DataEofException
*/
public String readA() throws DataReadException, DataEofException {
if(inputBuffReader == null) {return null;} // do we have a BufferedReader?
if(nowReading == null) {nowReading = "a text string";}
getThisDataLine();
if (thisDataLine.length() <=0) {nowReading = null; return null;} // an error occurred
// at this point: thisDataLine.length()>0
// where does next number or text beguin?
int j = thisDataLine.indexOf(","); // j is between 0 and (thisDataLine.length()-1)
int k = thisDataLine.length();
if(j>-1 && j<k) {k=j;}
// is there a next number or text in this line?
if(k >-1 && k < thisDataLine.length()) { //there is a comma in thisDataLine (there should be!)
String txt = thisDataLine.substring(0,k).trim();
thisDataLine.delete(0,k);
if(thisDataLine.length()>0) { // remove the comma marking the end of the text
if(thisDataLine.charAt(0) == ',') {thisDataLine.deleteCharAt(0);}
}
// remove whitespace around the remains of the input line
thisDataLine = new StringBuffer(thisDataLine.toString().trim());
nowReading = null;
return txt;
} else { //there is no comma in thisDataLine (this should not happen because
// checkNextDataLine() adds a comma at the end of the line)
String txt = thisDataLine.toString().trim();
thisDataLine.delete(0, thisDataLine.length());
nowReading = null;
return txt;
}
} //readA()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="int readI()">
/** Reads an integer from the input file. Data may be separated by commas,
* blanks or end-of-line.
* @return the next integer in the input file.
* @throws lib.kemi.readDataLib.ReadDataLib.DataReadException
* @throws lib.kemi.readDataLib.ReadDataLib.DataEofException
*/
public int readI() throws DataReadException, DataEofException {
if(inputBuffReader == null) {return Integer.MIN_VALUE;} // do we have a BufferedReader?
if(nowReading == null) {nowReading = "an integer";}
getThisDataLine();
if (thisDataLine.length() <=0)
{nowReading = null; return Integer.MIN_VALUE;} // an error occurred
// at this point: thisDataLine.length()>0
int i = thisDataLine.indexOf(" "); // i is between 0 and (thisDataLine.length()-1)
int j = thisDataLine.indexOf(",");
int k = thisDataLine.length();
if(i>-1 && i<k) {k=i;}
if(j>-1 && j<k) {k=j;}
String txt;
if(k >-1 && k < thisDataLine.length()) { //there is a comma or space in thisDataLine (there should be!)
txt = thisDataLine.substring(0,k).trim();
thisDataLine.delete(0,(k+1));
//remove whitespace at the end and beginning of the line
thisDataLine = new StringBuffer(thisDataLine.toString().trim());
if(thisDataLine.length()>0) {
// if there was a space followed by comma
// after the number remove the comma
if(thisDataLine.charAt(0) == ',') {thisDataLine.deleteCharAt(0);}
}
//remove whitespace at the end and beginning of the line
// (after removing leading comma)
thisDataLine = new StringBuffer(thisDataLine.toString().trim());
} else { //there is no comma or space in thisDataLine (this should not happen because
// checkNextDataLine() adds a comma at the end of the line)
txt = thisDataLine.toString().trim();
thisDataLine.delete(0, thisDataLine.length());
}
int value = Integer.MIN_VALUE;
if(txt.length() == 0) {value = 0;}
else {
try{value = Integer.valueOf(txt);}
catch(NumberFormatException ex) {throw new DataReadException(
"Error:"+nl+
"NumberFormatException reading an integer from input string: \""+txt+"\""+nl+
"when reading: "+nowReading+nl+
"in line: \""+thisDataLineOriginal.toString()+"\""+nl+
"in file: \""+dataFileName+"\".");}
catch(NullPointerException ex) {throw new DataReadException(
"Error:"+nl+
"NullPointerException reading an integer from input string: \""+txt+"\""+nl+
"when reading: "+nowReading+nl+
"in line: \""+thisDataLineOriginal.toString()+"\""+nl+
"in file: \""+dataFileName+"\".");}
} // txt = ""?
nowReading = null;
return value;
} //readI
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="float readR()">
/** Read a float from the input file. Data may be separated by commas,
* blanks or end-of-line.
* @return the next float from the input file.
* @throws lib.kemi.readDataLib.ReadDataLib.DataReadException
* @throws lib.kemi.readDataLib.ReadDataLib.DataEofException
*/
public float readR() throws DataReadException, DataEofException {
float f = (float) readD();
if(Math.abs(f) < Float.MIN_VALUE) {f = 0f;}
return f;
} //readR
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="double readD()">
/** Read a double from the input file. Data may be separated by commas,
* blanks or end-of-line.
* @return the next double from the input file.
* @throws lib.kemi.readDataLib.ReadDataLib.DataReadException
* @throws lib.kemi.readDataLib.ReadDataLib.DataEofException
*/
public double readD() throws DataReadException, DataEofException {
if(inputBuffReader == null) {return Double.NaN;} // do we have a BufferedReader?
if(nowReading == null) {nowReading = "a double (floating point value)";}
getThisDataLine();
if (thisDataLine.length() <=0)
{nowReading = null; return Double.NaN;} // an error occurred
// at this point: thisDataLine.length()>0
int i = thisDataLine.indexOf(" "); // i is between 0 and (thisDataLine.length()-1)
int j = thisDataLine.indexOf(",");
int k = thisDataLine.length();
if(i>-1 && i<k) {k=i;}
if(j>-1 && j<k) {k=j;}
String txt;
if(k >-1 && k < thisDataLine.length()) { //there is a comma or space in thisDataLine (there should be!)
txt = thisDataLine.substring(0,k).trim();
thisDataLine.delete(0,(k+1));
//remove whitespace at the end and beginning of the line
thisDataLine = new StringBuffer(thisDataLine.toString().trim());
if(i == k && thisDataLine.length()>0) {
// if there was a space followed by comma
// after the number remove the comma
if(thisDataLine.charAt(0) == ',') {thisDataLine.deleteCharAt(0);}
}
//remove whitespace at the end and beginning of the line
// (after removing leading comma)
thisDataLine = new StringBuffer(thisDataLine.toString().trim());
} else { //there is no comma or space in thisDataLine (this should not happen because
// checkNextDataLine() adds a comma at the end of the line)
txt = thisDataLine.toString().trim();
thisDataLine.delete(0, thisDataLine.length());
}
double value = Double.NaN;
if(txt.length() == 0) {value = 0;}
else {
try{value = Double.valueOf(txt);}
catch(NumberFormatException ex) {throw new DataReadException(
"Error:"+nl+
"NumberFormatException reading a float value from input string: \""+txt+"\""+nl+
"when reading: "+nowReading+nl+
"in line: \""+thisDataLineOriginal.toString()+"\""+nl+
"in file: \""+dataFileName+"\".");}
catch(NullPointerException ex) {throw new DataReadException(
"Error:"+nl+
"NullPointerException reading a float value from input string: \""+txt+"\""+nl+
"when reading: "+nowReading+nl+
"in line: \""+thisDataLineOriginal.toString()+"\""+nl+
"in file: \""+dataFileName+"\".");}
} // txt = ""?
nowReading = null;
if(Math.abs(value) < Double.MIN_VALUE) {value = 0;}
return value;
} //readD
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="String readLine()">
/** Read a text line from the input file. Note:<br>
* - any values not yet read in the current input line are discarded!<br>
* - it reads a complete line, including comments.
* @return the next text line from the input file.
* @throws lib.kemi.readDataLib.ReadDataLib.DataReadException
* @throws lib.kemi.readDataLib.ReadDataLib.DataEofException
*/
public String readLine() throws DataReadException, DataEofException {
if(inputBuffReader == null) {return null;} // do we have a BufferedReader?
// clean up
nextDataLineComment = null;
if(thisDataLineOriginal != null && thisDataLineOriginal.length() >0) {thisDataLineOriginal.delete(0, thisDataLineOriginal.length());}
if(thisDataLine != null && thisDataLine.length() >0) {thisDataLine.delete(0, thisDataLine.length());}
if(dataLineComment == null) {dataLineComment = new StringBuffer();}
else {if(dataLineComment.length() >0) {dataLineComment.delete(0, dataLineComment.length());}}
//
if(nowReading == null) {nowReading = "a text line";}
getNextDataLine();
nowReading = null;
if(nextDataLineOriginal == null) {
throw new DataEofException("Error: reached the End-Of-File,"+nl+
"when reading: "+nowReading+nl+
"in file: \""+dataFileName+"\".");
}
return nextDataLineOriginal.toString();
} //readLine()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="double getTemperature">
/** Returns the temperature (in degrees Celcius) if it is found in a
* comment in the first line of the input data file.
* @return the temperature in degrees Celsius. Returns NaN if:
* a) the call is made before the first line has been read;
* b) there is no comment with the temperature;
* @throws lib.kemi.readDataLib.ReadDataLib.DataReadException
*/
public double getTemperature() throws DataReadException {
if(temperatureString == null ||
temperatureString.length() <=0) {return Double.NaN;}
int i;
for(i =0; i < temperatureString.length(); i++) {
if(!Character.isDigit(temperatureString.charAt(i)) &&
temperatureString.charAt(i) != 'E' && //the string is uppercase
temperatureString.charAt(i) != '.' &&
temperatureString.charAt(i) != '-' &&
temperatureString.charAt(i) != '+') {break;}
} //for i
if(i <=0) {return Double.NaN;}
if(i < temperatureString.length()-1) {
temperatureString = temperatureString.substring(0, i);
}
Double w;
try{w = Double.parseDouble(temperatureString);}
catch (NumberFormatException ex) {
throw new DataReadException("Error:"+nl+
"NumberFormatException while reading the temperature in line:"+nl+
"\""+temperatureDataLineNextOriginal+"\""+nl+
"in file \""+dataFileName+"\"");
}
if(temperatureUnitsK) {w = w - 273.15;}
return w;
} //getTemperature()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="double getPressure">
/** Returns the pressure (in "bar") if it is found in a comment in
* the first line of the input data file.
* @return the tpressure in bar. Returns NaN if:
* a) the call is made before the first line has been read;
* b) there is no comment with the pressure;
* @throws lib.kemi.readDataLib.ReadDataLib.DataReadException
*/
public double getPressure() throws DataReadException {
if(pressureString == null ||
pressureString.length() <=0) {return Double.NaN;}
int i;
for(i =0; i < pressureString.length(); i++) {
if(!Character.isDigit(pressureString.charAt(i)) &&
pressureString.charAt(i) != 'E' && //the string is uppercase
pressureString.charAt(i) != '.' &&
pressureString.charAt(i) != '+') {break;}
} //for i
if(i <=0) {return Double.NaN;}
if(i < pressureString.length()-1) {
pressureString = pressureString.substring(0, i);
}
Double w;
try{w = Double.parseDouble(pressureString);}
catch (NumberFormatException ex) {
throw new DataReadException("Error:"+nl+
"NumberFormatException while reading the pressure in line:"+nl+
"\""+pressureDataLineNextOriginal+"\""+nl+
"in file \""+dataFileName+"\"");
}
if(pressureUnits == 1) {w = w*1.013;} //atm
else if(pressureUnits == 2) {w = w/10;} //MPa
return w;
} //getPressure()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="private methods">
//<editor-fold defaultstate="collapsed" desc="getThisDataLine()">
/** If <code>thisDataLine</code> is empty read the next (not empty) line
* from the input file. Otherwise do nothing.<br>
* This procedure is called at the beginning of <code>readA</code>, <code>readI</code> and
* <code>readR</code>; but NOT from <code>readLine</code>.
* @throws readDataLib.ReadDataLib.DataReadException
* @throws readDataLib.ReadDataLib.DataEofException
*/
private void getThisDataLine() throws DataReadException, DataEofException {
if(thisDataLine == null) {thisDataLine = new StringBuffer();}
while(thisDataLine.length() <=0) { //get a non-empty line
// clean contents:
if(thisDataLineOriginal == null) {thisDataLineOriginal = new StringBuffer();}
else {if(thisDataLineOriginal.length() >0) {thisDataLineOriginal.delete(0, thisDataLineOriginal.length());}}
if(dataLineComment == null) {dataLineComment = new StringBuffer();}
else {if(dataLineComment.length() >0) {dataLineComment.delete(0, dataLineComment.length());}}
// move next line it into "thisDataLine" and get a new "next" data line
//read "next" non-empty line from the input file or until end-of-file
while(true) {
getNextDataLine(); //note that nextDataLine might be an empty or "null"
if(nextDataLine == null) {
String t = "reached the End-Of-File,"+nl;
if(nowReading != null && nowReading.length()>0) {t = t+"when reading: "+nowReading+nl;}
t = t+"in file: \""+dataFileName+"\".";
throw new DataEofException(t);
}
if(nextDataLine.length() >0) {break;}
}
thisDataLine.append(nextDataLine);
thisDataLineOriginal.append(nextDataLineOriginal);
if(nextDataLineComment != null) {dataLineComment.append(nextDataLineComment);}
nextDataLineComment = null;
} //while thisDataLine empty
} // getThisDataLine()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="getNextDataLine()">
/** Read next line. Store the information in variables
* <code>nextDataLine</code> and <code>nextDataLineOriginal</code>.<br>
* Note that the next line in the data file may be empty or only contain comments,
* if so <code>nextDataLine</code> and/or <code>nextDataLineOriginal</code>
* will be empty too.<br>
* @throws readDataLib.ReadDataLib.DataReadException
*/
private void getNextDataLine() throws DataReadException {
if(nextDataLine == null) {return;} // this occurs after End-Of-File
//clean variables
nextDataLine.delete(0, nextDataLine.length());
if(nextDataLineOriginal == null) {nextDataLineOriginal = new StringBuffer();}
else {if(nextDataLineOriginal.length() >0) {nextDataLineOriginal.delete(0, nextDataLineOriginal.length());}}
//read next line from the input file
String nextLine = null;
try {nextLine = inputBuffReader.readLine();}
catch (java.io.IOException ex) {
String t = ex.getMessage()+ " in \"getNextDataLine()\""+nl;
if(nowReading != null && nowReading.length()>0) {t = t+"when reading: "+nowReading+nl;}
t = t + "in file: \""+dataFileName+"\".";
throw new DataReadException(t);
}
if(nextLine == null) { //end-of-file encountered
nextDataLineOriginal = null;
nextDataLine = null; //end of file
} else { //nextLine != null
nextLine = Util.rTrim(nextLine);
nextDataLine.append(nextLine);
nextDataLineOriginal.append(nextLine);
try {checkNextDataLine();} //this could set nextDataLine = ""
catch(Exception ex) {
String t = ex.getMessage()+ " in \"getNextDataLine()\""+nl;
if(nowReading != null && nowReading.length()>0) {t = t+"when reading: "+nowReading+nl;}
t = t + "in line: \""+nextLine+"\""+nl+"in file: \""+dataFileName+"\".";
throw new DataReadException(t);
}
} // nextLine != null?
} //getNextDataLine()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="checkNextDataLine()">
/** Modify <code>nextDataLine</code>:<br>
* - Remove any comment at the end of <code>nextDataLine</code> and
* store the comment in variable <code>nextDataLineComment</code>.<br>
* - Read temperature/pressure from <code>nextDataLineComment</code>.<br>
* - Remove whitespace from <code>nextDataLine</code> and make sure it ends with "," (comma). */
private void checkNextDataLine() {
nextDataLineComment = null;
if(nextDataLine.length() <=0) {return;}
// Comments: after "/" if it is 1st character in the line
// or if it follows either space, tab or comma
int i =0; int imax =nextDataLine.length();
int i1,i2,i3,i4,i5;
do {
i = nextDataLine.indexOf("/", i);
if(i >0) {
char c = nextDataLine.charAt(i-1);
if(c == ',' || c == ' ' || c == '\t') {
nextDataLineComment = nextDataLine.substring(i+1); // skip the slash
nextDataLine.delete(i, imax);
break;
}
if(i>imax) {break;}
i = i+1;
} //if "/" found
else if(i == 0) {
nextDataLineComment = nextDataLine.toString();
nextDataLine.delete(0, nextDataLine.length());
break;
} //if i=0
else {break;}
} while(true);
//--- read temperature and pressure. Is it a DataBase/Spana or Hydra/Medusa file?
if(reading1stLine && nextDataLineComment != null) {
// is this a DataBase/Hydra or Spana/Medusa file?
if(nextDataLineComment.indexOf("HYDRA") > -1
|| nextDataLineComment.indexOf("DATABASE") > -1) {
fileIsDatabaseOrSpana = 1;
} else if(nextDataLineComment.indexOf("MEDUSA") > -1
|| nextDataLineComment.indexOf("SPANA") > -1) {
fileIsDatabaseOrSpana = 2;
}
// store information on temperature if found
String commentUC = nextDataLineComment.toUpperCase();
i1 = commentUC.indexOf("T=");
i2 = commentUC.indexOf("T =");
i = i1;
if( i2 >-1 && ((i1 >-1 && i2 <i1) || i1 <0)) {i = i2;}
if (i >-1) {
commentUC = commentUC.substring(i);
i = commentUC.indexOf("="); //get the "=" in "T="
if(i <(commentUC.length()-1)) {
commentUC = commentUC.substring(i+1).trim();
i1 = commentUC.indexOf("C");
if(i1>0) {
// remove degree sign, as in: t=25°C; quote, as in: t=25"C; etc
String s = commentUC.substring(i1-1,i1);
if(s.equals("°") || s.equals("\"") || s.equals("'")) {i1--;}
}
i2 = commentUC.indexOf("K");
i4 = commentUC.indexOf(" ");
i5 = commentUC.indexOf(",");
i = i1;
if (i2 >-1 && ((i >-1 && i2 <i) || i <0)) {i = i2;}
if (i4 >-1 && ((i >-1 && i4 <i) || i <0)) {i = i4;}
if (i5 >-1 && ((i >-1 && i5 <i) || i <0)) {i = i5;}
if(i>-1) {commentUC = commentUC.substring(0,i).trim();}
temperatureString = commentUC;
if(i2 >-1 && (i1<=-1 || (i1 > i2))) {temperatureUnitsK = true;}
temperatureDataLineNextOriginal = nextDataLineOriginal.toString();
} //if i <(commentUC.length()-1)
} // if found "T="
// store information on pressure if found
commentUC = nextDataLineComment.toUpperCase();
i1 = commentUC.indexOf("P=");
i2 = commentUC.indexOf("P =");
i = i1;
if( i2 >-1 && ((i1 >-1 && i2 <i1) || i1 <0)) {i = i2;}
if (i >-1) {
commentUC = commentUC.substring(i);
i = commentUC.indexOf("=");
if(i <(commentUC.length()-1)) {
commentUC = commentUC.substring(i+1).trim();
i1 = commentUC.indexOf("BAR");
i2 = commentUC.indexOf("ATM");
i3 = commentUC.indexOf("MPA");
i4 = commentUC.indexOf(" ");
i5 = commentUC.indexOf(",");
i = i1;
if (i2 >-1 && ((i >-1 && i2 <i) || i <0)) {i = i2;}
if (i3 >-1 && ((i >-1 && i3 <i) || i <0)) {i = i3;}
if (i4 >-1 && ((i >-1 && i4 <i) || i <0)) {i = i4;}
if (i5 >-1 && ((i >-1 && i5 <i) || i <0)) {i = i5;}
if(i>-1) {commentUC = commentUC.substring(0,i).trim();}
pressureString = commentUC;
pressureUnits = 0;
if(i2 >-1 && (i1<=-1 || (i1 > i2)) && (i3<=-1 || (i3 > i2))) {
pressureUnits = 1;
}
if(i3 >-1 && (i1<=-1 || (i1 > i3)) && (i2<=-1 || (i2 > i3))) {
pressureUnits = 2;
}
pressureDataLineNextOriginal = nextDataLineOriginal.toString();
} //if i <(commentUC.length()-1)
} // if found "P="
} // read temperature and pressure if reading 1st line and nextDataLineComment !=null
reading1stLine = false;
//remove whitespace at the end and beginning of the line
nextDataLine = new StringBuffer(nextDataLine.toString().trim());
//if the line is empty:
if(nextDataLine.length() <= 0) {return;}
// change any character lower than space to space
for(i=0; i <nextDataLine.length(); i++) {
if((int)nextDataLine.charAt(i) < 32) {nextDataLine.setCharAt(i,' ');}
}
//remove whitespace at the end
String t = Util.rTrim(nextDataLine.toString());
if(t.length() <= 0) {return;}
nextDataLine.delete(0, nextDataLine.length());
nextDataLine.append(t);
// add comma at the end if necessary
if(nextDataLine.charAt(nextDataLine.length()-1) != ',') {
nextDataLine.append(",");
}
} // checkNextDataLine()
//</editor-fold>
//</editor-fold>
/** an exception occurred within the "ReadDataLib" procedures */
public class ReadDataLibException extends Exception {
public ReadDataLibException() {}
public ReadDataLibException(String txt) {super(txt);}
} //ReadDataLibException
/** an exception occurred while thrying either to open or to close the input data file */
public class DataFileException extends ReadDataLibException {
public DataFileException() {}
public DataFileException(String txt) {super(txt);}
} //DataFileException
/** wrong numeric format while reading either some integer or some double */
public class DataReadException extends ReadDataLibException {
public DataReadException() {}
public DataReadException(String txt) {super(txt);}
} //DataReadException
/** End-Of-File encountered while trying to read some value */
public class DataEofException extends ReadDataLibException {
private DataEofException() {}
private DataEofException(String txt) {super(txt);}
} //DataEofException
} | 30,784 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
Chem.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibChemDiagr/src/lib/kemi/chem/Chem.java | package lib.kemi.chem;
import lib.common.Util;
/** Chem: a class with nested classes to store data.
* Mainly intended to be used by HaltaFall:<ul>
* <li> a class "ChemSystem" defining the thermodynamic data and
* the stoichiometry of a chemical system
* <li> an inner class "ChemConcs" with the concentrations and
* instructions to do the calculations
* <li> a class "NamesEtc" with the names of chemical species,
* their electric charges, etc. These data is also used to calculate
* activity coefficients in HaltaFall.</ul>
* Other programs (SED, Predom, etc) also use the following classes:<ul>
* <li> two classes "Diagr" and "DiagrConcs" with data on how the
* diagram is to be drawn, etc
* </ul>
* Each instance of this class contains one instance of the inner classes.
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class Chem {
/** Default value for debug output in HaltaFall: <code>DBGHALTA_DEF</code> =1 (output errors only).
* @see ChemSystem.ChemConcs#dbg Chem.ChemSystem.ChemConcs.dbg */
public static final int DBGHALTA_DEF = 1;
/** the default tolerance in programs SED and Predom */
public static final double TOL_HALTA_DEF = 1E-4;
/** A class that contains thermodynamic and stoichiometric information for a chemical system. */
public ChemSystem chemSystem = null;
/** A class that contains diverse information (except arrays) associated with a chemical
* diagram: what components in the axes, diagram type, etc. */
public Diagr diag = null;
/** A class that contains diverse information (arrays) associated with a chemical
* diagram: concentration ranges and how the concentrations are varied for
* each component in the diagram. */
public DiagrConcs diagrConcs = null;
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
/** A container class: its inner classes are ChemSystem, NamesEtc,
* Diagr and DiagrConcs. These inner classes store information on
* chemical system and the diagram to draw.<br>
* When an object of this class is created, an object of each inner class
* is also created.<br>
* However, more objects of each of the inner classes may be created later
* if needed, and these new objects may describe different chemical systems
* (different array sizes, etc).
* @param Na int number of chemical components
* @param Ms int the total number of species: components (soluble + solid)
* + soluble complexes + solids.
* @param mSol int the number of solids (reaction products + components)
* @param solidC int how many of the components are solid
* @throws lib.kemi.chem.Chem.ChemicalParameterException */
public Chem(int Na, int Ms, int mSol, int solidC)
throws ChemicalParameterException {
if(Na<0 || Ms<0 || mSol<0 || solidC<0) {
throw new ChemicalParameterException(
"Error in \"Chem\"-constructor: Na="+Na+", Ms="+Ms+", mSol="+mSol+", solidC="+solidC+nl+" All must be >=0.");
}
if(Ms < (Na+mSol)) {
throw new ChemicalParameterException(
"Error in \"Chem\"-constructor: Ms="+Ms+", and Na="+Na+", mSol="+mSol+nl+" Ms must be >=(Na+mSol).");
}
if(solidC > Na) {
throw new ChemicalParameterException(
"Error in \"Chem\"-constructor: solidC="+solidC+", and Na="+Na+nl+" solidC must be < Na.");
}
//create objects of the inner classes
chemSystem = new ChemSystem(Na,Ms,mSol,solidC);
diag = new Diagr();
diagrConcs = new DiagrConcs(Na);
// eps = new SITepsilon(Ms - mSol);
} // Chem constructor
/** The parameters supplied to a constructor are invalid: either outside the
* allowed range or incompatible with each other.
* The constractor can not be executed. */
public static class ChemicalParameterException extends Exception {
/** The parameters supplied to a constructor are invalid: either outside the
* allowed range or incompatible with each other.
* The constractor can not be executed. */
public ChemicalParameterException() {}
/** The parameters supplied to a constructor are invalid: either outside the
* allowed range or incompatible with each other.
* The constractor can not be executed.
* @param txt text description */
public ChemicalParameterException(String txt) {super(txt);}
} //ChemicalParameterException
//<editor-fold defaultstate="collapsed" desc="class ChemSystem + inner classes: ChemConcs + NamesEtc">
/** A class to store the minimum information needed to define a chemical
* system. It contains two inner classes: "<code>ChemConcs</code>" with the
* concentrations and instructions to do the calculations with <code>HaltaFall</code>.
* And "<code>NamesEtc</code>" with the names, electrical charge, etc of all
* species in the chemical system.
* @see lib.kemi.chem.Chem.ChemSystem.ChemConcs ChemConcs
* @see lib.kemi.chem.Chem.ChemSystem.NamesEtc NamesEtc
* @see lib.kemi.haltaFall.HaltaFall HaltaFall */
public class ChemSystem{
/** number of chemical components */
public int Na;
/** total number of species (components (soluble + solid)
* + soluble complexes + solid products) */
public int Ms;
/** number of solids (components + reaction products)
* <pre> Note: If some component is a solid phase:
* for each solid component a new solid complex is added.
* If the number of solid components is "solidC",
* Increase Ms (nbr of species) and mSol (nbr solids) by solidC:
* mSol = (solid products)+solidC
* Ms = (Tot. nbr. species)+solidC
* Then the solid reaction product "i" are added as follows:
* for all i = 0 ... (solidC-1):
* j = (Ms-Na-solidC)+i;
* k = (Na-solidC)+i;
* lBeta[j] = 0;
* and for all n (0...(Na-1)):
* a[j][n]=0.; except
* a[j][n]=1.; if n = k
* and set noll[k] = true;
* (the solid component is not a soluble species)</pre> */
public int mSol;
/** Nbr of soluble (non-solid) complexes (nx = Ms - Na - mSol) */
public int nx;
/** How many of the components are solids.
* <pre> Note: If some of the components is a solid phase,
* for each solid component a new solid complex is added.
* Increase Ms (nbr of species) and mSol (nbr solids) by solidC:
* mSol = (solid reaction products)+solidC
* Ms = (Tot. nbr. species)+solidC
* Then the solid reaction products "i" are added as follows:
* for all i = 0 ... (solidC-1):
* j = (Ms-Na-solidC)+i;
* k = (Na-solidC)+i;
* lBeta[j] = 0;
* and for all n (0...(Na-1)):
* a[j][n]=0.; except
* a[j][n]=1.; if n = k
* and set noll[k] = true;
* (the solid component is not a soluble species)</pre> */
public int solidC = 0;
// ------------------------------------------------------------
/** a[i][j] = formula units for species i and component j
* (i=0...(Ms-Na-1), j=0...(Na-1)) */
public double[][] a;
/** lBeta[i] = log10(Beta) for complex i (Beta = global equilibrium
* constant of formation, i=0...Ms-Na-1);
* solid phases are those with: i = Ms-mSol ... (Ms-1) */
public double[] lBeta;
/** noll[i] = True if the concentration of this species is zero ("e-", etc);
* False if this is a normal species (i=0...(Ms-1)) */
public boolean[] noll;
/** Which of the components in the chemical system is "water";
* -1 if water is not present. Water is identified in <code>readChemSystAndPlotInfo</code>
* as the component with a name in <code>identC[]</code> of either "H2O" or
* "H2O(l)".
* @see lib.kemi.haltaFall.Factor#osmoticCoeff haltaFall.Factor.osmoticCoeff
* @see lib.kemi.haltaFall.Factor#log10aH2O haltaFall.Factor.log10aH2O */
public int jWater = -1;
/** A class that contains the chemical concentrations associated
* with a chemical system. */
public ChemConcs chemConcs;
/** A class that contains diverse information associated with a chemical system,
* such as names of species and electric charge. */
public NamesEtc namn = null;
/** A class to store the minimum information needed to define a chemical
* system. When an object of this class is created, an object of the
* inner class "ChemConcs" is also created. ALthough more "ChemConcs" objects
* could be created later if needed, these new objects exist within
* the same chemical systems (the same array sizes, etc).
* @param Na int number of chemical components
* @param Ms int the total number of species: components (soluble + solid)
* + soluble complexes + solids.
* @param mSol int the number of solids (reaction products + components)
* @param solidC int how many of the components are solid
* @see lib.kemi.chem.Chem.ChemSystem.ChemConcs ChemConcs
* @see lib.kemi.haltaFall.HaltaFall HaltaFall
* @throws lib.kemi.chem.Chem.ChemicalParameterException */
public ChemSystem(int Na, int Ms, int mSol, int solidC)
throws ChemicalParameterException {
if(Na<=0 || Ms<=0) {
throw new ChemicalParameterException(
"Error in \"ChemSystem\"-constructor: Na="+Na+", Ms="+Ms+nl+" All must be >0.");
}
if(mSol<0) {
throw new ChemicalParameterException(
"Error in \"ChemSystem\"-constructor: mSol="+mSol+nl+" must be >=0.");
}
if(Ms < (Na+mSol)) {
throw new ChemicalParameterException(
"Error in \"ChemSystem\"-constructor: Na="+Na+", Ms="+Ms+", mSol="+mSol+nl+" Ms must be >=(Na+mSol).");
}
this.Na = Na; this.Ms = Ms; this.mSol = mSol; this.solidC = solidC;
nx = Ms - Na - mSol;
a = new double[Ms-Na][Na];
lBeta = new double[Ms-Na];
noll = new boolean[Ms];
for(int i = 0; i < noll.length; i++)
{noll[i] = false;} // for i
chemConcs = new ChemConcs();
namn = new NamesEtc(Na, Ms, mSol);
} // ChemSystem(Na, Ms, mSol)
//<editor-fold defaultstate="collapsed" desc="printChemSystem">
/** Print the data defining a chemical system
* @param out a PrintStrem, such as <code>System.out</code>.
* If null, <code>System.out</code> is used. */
public void printChemSystem(java.io.PrintStream out) {
if(out == null) {out = System.out;}
out.flush();
java.util.Locale e = java.util.Locale.ENGLISH;
final String LINE = "-------------------------------------";
int j=0,js=0;
String t, t2=" ", tjs;
int n0, nM, iPl, nP;
out.println(LINE);
out.println("Chemical System: Na, Nx, Msol, solidC = "+Na+", "+nx+", "+mSol+", "+solidC);
if(solidC>0) {
out.println("Components (the last "+solidC+" are solids), name and noll:");
} else {out.println("Components, name and noll:");}
n0 = 0; //start index to print
nM = Na-1; //end index to print
iPl = 1; nP= nM-n0; //items_Per_Line and number of items to print
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
if(namn != null && namn.ident[kjj] != null) {
if(namn.ident[kjj].isEmpty()) {t="\"\"";} else {t=namn.ident[kjj];}
} else {t="\"null\"";}
out.format(e,"%3d %20s, %5b",j,t,noll[kjj]); j++;
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); // out.print(" ");
} //for ijj
out.println("reaction products: name, logBeta, noll, a[]=");
for(int i = 0; i <nx; i++) {
if(namn != null && namn.ident[i+Na] != null) {
if(namn.ident[i+Na].isEmpty()) {t="\"\"";} else {t=namn.ident[i+Na];}
} else {t="\"null\"";}
out.format(e,"%3d%4s %20s, %10.5f %5b ",j,t2,t,lBeta[i],noll[i+Na]); j++;
n0 = 0; //start index to print
nM = Na-1; //end index to print
iPl = 8; nP= nM-n0; //items_Per_Line and number of items to print
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %8.3f",a[i][kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
} //for i
for(int i = nx; i <(nx+mSol); i++) {
if(namn != null && namn.ident[i+Na] != null) {
if(namn.ident[i+Na].isEmpty()) {t="\"\"";} else {t=namn.ident[i+Na];}
} else {t="\"null\"";}
tjs=Integer.toString(js);
t2="(";
t2= t2.concat(tjs.trim()).concat(")");
out.format(e,"%3d%4s %20s, %10.5f %5b ",j,t2,t,lBeta[i],noll[i+Na]); j++; js++;
n0 = 0; //start index to print
nM = Na-1; //end index to print
iPl = 8; nP= nM-n0; //items_Per_Line and number of items to print
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %8.3f",a[i][kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
} //for i
out.println(LINE);
out.flush();
} //printChemSystem
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="inner class ChemConcs">
/** A class to store the chemical concentrations associated
* with a chemical system. Used by <code>HaltaFall</code>.
* @see lib.kemi.chem.Chem.ChemSystem ChemSystem
* @see lib.kemi.haltaFall.HaltaFall HaltaFall */
public class ChemConcs{
/** <code>kh[i] (i=0...(Na-1))</code>
* <ul><li><code>kh =1</code> if the total concentration is given as
* input to HaltaFall in array tot[]. The mass-balance equation has then
* to be solved in HaltaFall; the tolerance is given in tol (e.g. 1e-4)</li>
* <li><code>kh =2</code> if log10(activity) is given as input to HaltaFall in array logA[].
* The total concentration will be calculated by HaltaFall</li></ul>
* @see lib.kemi.chem.Chem.ChemSystem.ChemConcs#tot tot
* @see lib.kemi.chem.Chem.ChemSystem.ChemConcs#tol tol
* @see lib.kemi.chem.Chem.ChemSystem.ChemConcs#cont cont */
public int[] kh;
/** logA[i] = log10(activity) for component i (i=0...(Na-1));
* needed only if kh[i]=2)
* @see lib.kemi.chem.Chem.ChemSystem.ChemConcs#kh kh */
public double[] logA;
/** tot[i] = total concentration for component i (i=0...(Na-1));
* needed only if kh[i]=1)
* @see lib.kemi.chem.Chem$ChemSystem.ChemConcs#kh kh */
public double[] tot;
/** relative maximum tolerance to solve the mass balance equations; used only for
* components with kh[i]=1. For example: 1e-4. Must be between 1e-9 and 1e-2.
* If the total concentration of a component is zero, then a small absolute
* tolerance is used, which depends on the total concentrations for the other
* components, for example = 1e-8 times tol.
* @see lib.kemi.chem.Chem.ChemSystem.ChemConcs#kh kh */
public double tol;
/** solub[i]= calculated solubility for component i (i=0...(Na-1)) */
public double[] solub;
/** c(i) = calculated concentration for species i (i=0...(Ms-1)) */
public double[] C;
/** logF(i) = log10(activity coefficient) for species i (i=0...(Ms-1)) */
public double[] logf;
/** when calling HaltaFall set <code>dbg</code> equal to zero or one on a normal run,
* and to a larger value for debug print-out:<br>
* <code>dbg</code> =0 do not output anything<br>
* =1 output errors, but no debug information<br>
* =2 errors and results<br>
* =3 errors, results and input<br>
* =4 errors, results, input and debug for procedure <code>fasta()</code><br>
* =5 errors, results, input and debug for activity coefficients<br>
* >=6 errors, results, input and full debug print-out<br>
* Default = Chem.DBGHALTA_DEF = 1 (report errors only)
* @see Chem#DBGHALTA_DEF Chem.DBGHALTA_DEF */
public int dbg;
/** set <code>cont = true</code> before calling procedure <code>haltaCalc</code>
* if the same set of equilibrium solids obtained from the last call to
* <code>haltaCalc</code> are to be tested first;<br>
* set <code>cont = false</code> to discard the set of solids at equilibrium found
* in the last calculation.<br>
* <b>Note:</b> For the first call to <code>haltaCalc</code> there is no previous set of solids,
* so <code>cont = true</code> has no effect.<br>
* If the array <code>kh[]</code> is changed since the last calculation, then
* the last set of solids is discarded, and setting <code>cont = true</code> has no effect.<br>
* If there are no errors, <code>haltaCalc</code> sets <code>cont=true</code> else,
* if the calculation fails it is set to <code>false</code>. So in general the
* user does not need to change this parameter.
* @see lib.kemi.haltaFall.HaltaFall#haltaCalc() haltaCalc()
* @see lib.kemi.chem.Chem.ChemSystem.ChemConcs#errFlags errFlags
* @see lib.kemi.chem.Chem.ChemSystem.ChemConcs#kh kh */
public boolean cont;
/** If the HaltaFall calculation succeeds, this variable is zero.<br>
* If the calculation fails, up to 6 error flags are set bitwise
* in this variable.<br>
* The meaning of the different flags:<br>
* 1: the numerical solution is uncertain (round-off errors).<br>
* 2: too many iterations when solving the mass balance equations.<br>
* 3: failed to find a satisfactory combination of solids.<br>
* 4: too many iterations trying to find the solids at equilibrium.<br>
* 5: some aqueous concentration(s) are too large (>20): uncertain activity coefficients<br>
* 6: activity factors did not converge.<br>
* 7: calculation interrupted by the user.<br>
* @see lib.kemi.chem.Chem.ChemSystem.ChemConcs#errFlagsSet(int) errFlagsSet
* @see lib.kemi.chem.Chem.ChemSystem.ChemConcs#errFlagsClear(int) errFlagsClear
* @see lib.kemi.chem.Chem.ChemSystem.ChemConcs#isErrFlagsSet(int) isErrFlagsSet
* @see lib.kemi.chem.Chem.ChemSystem.ChemConcs#errFlagsToString() errFlagsToString
* @see lib.kemi.chem.Chem.ChemSystem.ChemConcs#errFlagsGetMessages() errFlagsGetMessages
* @see lib.kemi.haltaFall.Factor#MAX_CONC MAX_CONC */
public int errFlags;
/** If it is <b><code>true</code></b> activity coefficients (ionic strength effects) will
* be calculated by <code>HaltaFall</code> using using the provided instance of
* <code>Factor</code>. If it is <b><code>false</code></b> then the calculations in
* <code>HaltaFall</code> are made for ideal solutions (all activity coefficients = 1)
* and <code>Factor</code> is never called by <code>HaltaFall</code> during the iterations.
* @see lib.kemi.chem.Chem.Diagr#activityCoeffsModel Chem.Diagr.activityCoeffsModel
* @see lib.kemi.chem.Chem.Diagr#ionicStrength Chem.Diagr.ionicStrength
* @see lib.kemi.haltaFall.Factor#ionicStrengthCalc haltaFall.Factor.ionicStrengthCalc */
public boolean actCoefCalc = false;
/** The tolerance (log-10 scale) being used to iterate activity coefficient calculations.
* For systems where the highest concentration for a ionic species is less
* than 1 (mol/L), the tolerance is 0.001 in log-10 scale. If one or more
* concentrations for a ionic species <nobr>(C[i])</nobr> is larger than one, then
* <nobr><code>tolLogF = 0.001*C[i]</code>.</nobr> For example, if the highest
* concentration is 12 mol/L, then <code>tolLogF = 0.012</code>.
* @see #actCoefCalc actCoefCalc
* @see #logf logf
* @see lib.kemi.haltaFall.HaltaFall#TOL_LNG TOL_LNG */
public double tolLogF;
/** An inner class to store the chemical concentrations associated
* with a chemical system. Used by <code>HaltaFall</code>.
* @see lib.kemi.chem.Chem.ChemSystem ChemSystem
* @see lib.kemi.haltaFall.HaltaFall HaltaFall
* @throws lib.kemi.chem.Chem.ChemicalParameterException */
private ChemConcs() throws ChemicalParameterException {
/** number of chemical components */
int na = ChemSystem.this.Na;
/** the total number of species: components (soluble + solid)
* + soluble complexes + solid products */
int ms = ChemSystem.this.Ms;
if(na<0 || ms<0) { //this should not occur if the enclosing class is ok
throw new ChemicalParameterException(
"Error in \"ChemConcs\"-constructor: na="+na+", ms="+ms+nl+" All must be >=0.");
}
if(na>ms) { //this should not occur if the enclosing class is ok
throw new ChemicalParameterException(
"Error in \"ChemConcs\"-constructor: na="+na+", ms="+ms+nl+" ms must be >= na.");
}
this.kh = new int[na];
this.tot = new double[na];
this.tol = 1e-4;
this.solub = new double[na];
this.C = new double[ms];
this.logA = new double[ms];
this.logf = new double[ms];
this.dbg = DBGHALTA_DEF;
this.cont = false;
this.errFlags = 0;
this.actCoefCalc = false;
}
//<editor-fold defaultstate="collapsed" desc="errFlagsSet(i)">
/** Sets an error flag
* @param i the error flag: a value between 1 and 7
* @see lib.kemi.chem.Chem.ChemSystem.ChemConcs#errFlags errFlags */
public void errFlagsSet(int i) {
if(i ==1) {errFlags |=1;}
else if(i ==2) {errFlags |=2;}
else if(i ==3) {errFlags |=4;}
else if(i ==4) {errFlags |=8;}
else if(i ==5) {errFlags |=16;}
else if(i ==6) {errFlags |=32;}
else if(i ==7) {errFlags |=64;}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="isErrFlagsSet(i)">
/** Returns true if the error flag is set, false otherwise
* @param i the error flag: a value between 1 and 7
* @return true if the error flag is set, false otherwise
* @see lib.kemi.chem.Chem.ChemSystem.ChemConcs#errFlags errFlags */
public boolean isErrFlagsSet(int i) {
boolean b = false;
if(i ==1) {if((errFlags & 1) == 1) {b = true;}}
else if(i ==2) {if((errFlags & 2) == 2) {b = true;}}
else if(i ==3) {if((errFlags & 4) == 4) {b = true;}}
else if(i ==4) {if((errFlags & 8) == 8) {b = true;}}
else if(i ==5) {if((errFlags & 16) == 16) {b = true;}}
else if(i ==6) {if((errFlags & 32) == 32) {b = true;}}
else if(i ==7) {if((errFlags & 64) == 64) {b = true;}}
return b;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="errFlagsClear(i)">
/** Clears an error flag
* @param i the error flag: a value between 1 and 7
* @see lib.kemi.chem.Chem.ChemSystem.ChemConcs#errFlags errFlags */
public void errFlagsClear(int i) {
if(i ==1) {errFlags &= ~1;}
else if(i ==2) {errFlags &= ~2;}
else if(i ==3) {errFlags &= ~4;}
else if(i ==4) {errFlags &= ~8;}
else if(i ==5) {errFlags &= ~16;}
else if(i ==6) {errFlags &= ~32;}
else if(i ==7) {errFlags &= ~64;}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="errFlagsToString()">
/** Returns a text line with the error flags, bitwise as 0 or 1
* @return the message "errFlags (1 to 6): 0000000" with zeros replaced by "1"
* for each flag that is set.
* @see lib.kemi.chem.Chem.ChemSystem.ChemConcs#errFlags errFlags */
public String errFlagsToString() {
String t = "errFlags (1 to 6): ";
if((errFlags & 1) == 1) {t = t+ "1";} else {t = t + "0";}
if((errFlags & 2) == 2) {t = t+ "1";} else {t = t + "0";}
if((errFlags & 4) == 4) {t = t+ "1";} else {t = t + "0";}
if((errFlags & 8) == 8) {t = t+ "1";} else {t = t + "0";}
if((errFlags &16) ==16) {t = t+ "1";} else {t = t + "0";}
if((errFlags &32) ==32) {t = t+ "1";} else {t = t + "0";}
if((errFlags &64) ==64) {t = t+ "1";} else {t = t + "0";}
return t;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="errFlagsGetMessages()">
/** Returns a message with one text line for each error flag that is set,
* separated with new-lines
* @return the error messages or <code>null</code> ir no errFlags are set
* @see lib.kemi.chem.Chem.ChemSystem.ChemConcs#errFlags errFlags */
public String errFlagsGetMessages() {
if(errFlags <= 0) {return null;}
String t = "";
if((errFlags & 1) == 1) {
t = t+ "The numerical solution is uncertain (round-off errors).";
}
if((errFlags & 2) == 2) {
if(t.length()>0) {t=t+nl;}
t = t+ "Too many iterations when solving the mass balance equations.";
}
if((errFlags & 4) == 4) {
if(t.length()>0) {t=t+nl;}
t = t+ "Failed to find a satisfactory combination of solids.";
}
if((errFlags & 8) == 8) {
if(t.length()>0) {t=t+nl;}
t = t+ "Too many iterations trying to find the solids at equilibrium.";
}
if((errFlags &16) ==16) {
if(t.length()>0) {t=t+nl;}
t = t+ "Some aqueous concentration(s) too large (>50): uncertain activity coefficients.";
}
if((errFlags &32) ==32) {
if(t.length()>0) {t=t+nl;}
t = t+ "Activity factors did not converge.";
}
if((errFlags &64) ==64) {
if(t.length()>0) {t=t+nl;}
t = t+ "Calculation interrupted by the user.";
}
if(t.trim().length()<=0) {return null;} else {return t;}
}
//</editor-fold>
} // class ChemConcs
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="inner class NamesEtc">
/** An inner class to "Chem" that contains diverse information associated
* with a chemical system: names of species, electric charge, etc */
public class NamesEtc {
/** Names of the chemical components */
public String[] identC;
/** Names of all species ident[ms]
* @see lib.kemi.chem.Chem.ChemSystem#Ms Ms
*/
public String[] ident;
/** The length of the name of a species excluding spaces between name
* and charge. For example for "Fe 3+" nameLength = 4. */
public int[] nameLength;
/** Which species are the components: this is needed for GASOL (SolgasWater);
* but in HaltaFall the components are the 1st Na species. */
public int[] iel;
/** The electric charges of all aqueous species. Plus the electric charge of
* two fictive species (Na+ and Cl-) that are used to ensure electrically neutral
* aqueous solutions (electroneutrality) when calculating the ionic strength and
* activity coefficients */
public int[] z;
/** The comment in the input file (if any) corresponding to this species */
public String[] comment;
/** An inner class that contains diverse information associated
* with a chemical system: the names of the species and the components, the
* electric charge of each species, informatio on the diagram to be drawn, etc.
* @param na int number of chemical components
* @param ms int the total number of species: components (soluble + solid)
* + soluble complexes + solid products
* @param mSol int the number of solids (components + reaction products)
* @throws lib.kemi.chem.Chem.ChemicalParameterException */
public NamesEtc (int na, int ms, int mSol) throws ChemicalParameterException {
if(na<0 || ms<0 || mSol<0) {
throw new ChemicalParameterException(
"Error in \"NamesEtc\"-constructor: na="+na+", ms="+ms+", mSol="+mSol+nl+" All must be >=0.");
}
if(ms<na || ms<mSol) {
throw new ChemicalParameterException(
"Error in \"NamesEtc\"-constructor: na="+na+", ms="+ms+", mSol="+mSol+nl+" ms must be >na and >mSol.");
}
identC = new String[na];
ident = new String[ms];
comment = new String[ms];
nameLength = new int[ms];
// ---- Which species are the components
// (this is needed for GASOL; in HALTA the components
// are the first "na" species of the list)
iel = new int[na];
for(int i =0; i < na; i++) {iel[i] =i;}
int nx = ms - na - mSol; // soluble complexes
int nIons = na + nx; // = (ms-mSol)
//Note: The number of soluble species is (nIons+2). Must add the
// electric charge of two fictive species (Na+ and Cl-)
// that are used to ensure electrically neutral aqueous solutions
// when calculating the ionic strength and activity coefficients
z = new int[nIons+2]; // add two electroneutrality species (Na+ and Cl-)
} // constructor
//<editor-fold defaultstate="collapsed" desc="printNamesEtc">
/** Print data defining a chemical system
* @param out a PrintStrem, such as <code>System.out</code>.
* If null, <code>System.out</code> is used. */
public void printNamesEtc(java.io.PrintStream out) {
if(out == null) {out = System.out;}
out.flush();
java.util.Locale e = java.util.Locale.ENGLISH;
//access the enclosing class from the inner class
int Na = Chem.this.chemSystem.Na;
int Ms = Chem.this.chemSystem.Ms;
int mSol = Chem.this.chemSystem.mSol;
int n0, nM, iPl, nP;
out.println("components: names="); out.print(" ");
n0 = 0; //start index to print
nM = Na-1; //end index to print
iPl = 5; nP= nM-n0; if(nP >=0) { //items_Per_Line and itemsto print
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %15s",identC[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
int nx = Ms - Na - mSol; // soluble complexes
out.println("complexes: names="); out.print(" ");
n0 = Na; //start index to print
nM = Na+nx+mSol-1; //end index to print
iPl = 5; nP= nM-n0; if(nP >=0) {
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %15s",ident[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
out.println("soluble species: z="); out.print(" ");
n0 = 0; //start index to print
nM = Na+nx+2-1; //end index to print
iPl = 20; nP= nM-n0; if(nP >=0) {
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %3d",z[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
out.flush();
} //printNamesEtc()
//</editor-fold>
} // class NamesEtc
//</editor-fold>
} // class ChemSystem
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="inner class Diagr">
/** An inner class that contains diverse information associated
* with a diagram: components in the axes, diagram type, etc.
* A sister class, DiagrConcs, contains array data. */
public class Diagr implements Cloneable {
/** <pre>plotType=0 Predom diagram; compMain= main component
plotType=1 fraction diagram; compY= main component
plotType=2 log solubility diagram
plotType=3 log (conc) diagram
plotType=4 log (ai/ar) diagram; compY= reference species
plotType=5 pe in Y-axis
plotType=6 pH in Y-axis
plotType=7 log (activity) diagram
plotType=8 H-affinity diagram</pre> */
public int plotType;
/** the component in the X-axis in the diagram */
public int compX;
/** the component in the Y-axis in a Predom diagram.
* For a SED diagram it is either the component for which the fractions
* are calculated, or it is the reference species in a relative activity diagram. */
public int compY;
/** the "main" component in a Predom diagram: the component for which the
* dominating species or existing solids are determined and plotted */
public int compMain;
/** For a Predominance area diagram: if <code>oneArea</code> >=0 this value indicates
* which species the user has requested (in the input file) to plot as a single
* predominance area. <code>oneArea</code> <= -1 if the user made no such request. */
public int oneArea;
/** the lowest value in the Y-axis */
public double yLow;
/** the highest value in the Y-axis */
public double yHigh;
/** Eh: true if Eh is displayed either in the axes or in the caption;
* false if "pe" is used instead. */
public boolean Eh;
/** a line of text used as title (caption) above the diagram.
* It is the first line of text (if any) found after the plot information in the input data file
* @see lib.kemi.chem.Chem.Diagr#endLines endLines */
public String title;
/** any lines of text that may be found after the title line in the input data file
* @see lib.kemi.chem.Chem.Diagr#title title */
public String endLines;
/** <pre> =1 if the comment at the end of the first line contains
* either "HYDRA" or "DATABASE";
* =2 if the comment contains either "MEDUSA" or "SPANA";
* =0 otherwise.</pre>
* Not to be changed
* @see lib.kemi.readDataLib.ReadDataLib#fileIsDatabaseOrSpana fileIsDatabaseOrSpana */
public int databaseSpanaFile;
/** True if the range of values in the Y-axis is given in the input data file */
public boolean inputYMinMax;
/** pInX: 0 = "normal" axis; 1 = pH in axis; 2 = pe in axis;
* 3 = Eh in axis. */
public int pInX;
/** pInY: 0 = "normal" axis; 1 = pH in axis; 2 = pe in axis;
* 3 = Eh in axis. */
public int pInY;
/** which species is H+ */
public int Hplus;
/** which species is OH- */
public int OHmin;
/** True if the species names indicate that this system is an aqueous system,
* (and not a gaseous phase, etc) */
public boolean aquSystem;
/** temperature in Celsius */
public double temperature;
/** pressure in bar */
public double pressure;
/** The ionic strength given by the user.
* If the ionic strength is negative (e.g. =-1) then it is calculated.
* This variable is checked in SED and Predom when plotting a heading in the
* diagram. If it is zero or NaN (Not a Number) then it is not displayed
* in the plot.
* @see lib.kemi.chem.Chem.Diagr#activityCoeffsModel Chem.Diagr.activityCoeffsModel
* @see lib.kemi.haltaFall.Factor#ionicStrengthCalc haltaFall.Factor.ionicStrengthCalc */
public double ionicStrength;
/** The ionic strength calculated in <code>Factor</code>.
* @see lib.kemi.chem.Chem.Diagr#activityCoeffsModel Chem.Diagr.activityCoeffsModel
* @see lib.kemi.chem.Chem.Diagr#ionicStrength ionicStrength */
public double ionicStrCalc;
/** The osmotic coefficient of water, calculated in <code>Factor</code>.
* @see lib.kemi.chem.Chem.ChemSystem#jWater Chem.ChemSystem.jWater
* @see lib.kemi.haltaFall.Factor#log10aH2O haltaFall.Factor.log10aH2O
* @see lib.kemi.chem.Chem.Diagr#activityCoeffsModel Chem.Diagr.activityCoeffsModel
* @see lib.kemi.haltaFall.Factor#ionicStrengthCalc haltaFall.Factor.ionicStrengthCalc */
public double phi;
/** sum of molalities of all species in the aqueous solution
* @see lib.kemi.chem.Chem.Diagr#activityCoeffsModel Chem.Diagr.activityCoeffsModel
* @see lib.kemi.haltaFall.Factor#ionicStrengthCalc haltaFall.Factor.ionicStrengthCalc */
public double sumM;
/** Model to calculate activity coefficents (ionic strength effects):<ul>
* <li> <0 for ideal solutions (all activity coefficients = 1)
* <li> =0 Davies eqn.
* <li> =1 SIT (Specific Ion interaction "Theory")
* <li> =2 Simplified HKF (Helson, Kirkham and Flowers)
* </ul>
* @see lib.kemi.chem.Chem.Diagr#ionicStrength Chem.Diagr.ionicStrength
* @see lib.kemi.haltaFall.Factor#ionicStrengthCalc haltaFall.Factor.ionicStrengthCalc */
public int activityCoeffsModel = -1;
/** the minimum fraction value that a species must reach
* to be displayed in a fraction diagram. A value of 0.03 means that
* a species must have a fraction above 3% in order to be displayed
* in a fraction diagram. */
public float fractionThreshold = 0.03f;
/** An inner class that contains diverse information associated
* with a diagram: components in the axes, diagram type, etc */
public Diagr(){
// predom = false;
plotType = -1;
compX = -1; compY = -1; compMain = -1;
oneArea = -1;
yLow = Double.NaN; yHigh = Double.NaN;
Eh = true;
title = null;
endLines = null;
databaseSpanaFile = 0;
inputYMinMax = false;
pInX =0; pInY =0;
Hplus = -1; OHmin = -1;
aquSystem = false;
ionicStrength = 0;
temperature = 25;
pressure = 1;
activityCoeffsModel = -1;
fractionThreshold = 0.03f;
} // constructor
@Override public Object clone() throws CloneNotSupportedException {
super.clone();
Diagr d = new Diagr();
d.plotType = this.plotType;
d.compX = this.compX;
d.compY = this.compY;
d.compMain = this.compMain;
d.oneArea = this.oneArea;
d.yLow = this.yLow;
d.yHigh = this.yHigh;
d.Eh = this.Eh;
d.title = this.title;
d.endLines = this.endLines;
d.databaseSpanaFile = this.databaseSpanaFile;
d.inputYMinMax = this.inputYMinMax;
d.pInX = this.pInX;
d.pInY = this.pInY;
d.Hplus = this.Hplus;
d.OHmin = this.OHmin;
d.aquSystem = this.aquSystem;
d.ionicStrength = this.ionicStrength;
d.temperature = this.temperature;
d.pressure = this.pressure;
d.fractionThreshold = this.fractionThreshold;
return d;
} // clone()
public boolean isEqualTo(Diagr another) {
return another != null &&
this.plotType == another.plotType &&
this.compX == another.compX &&
this.compY == another.compY &&
this.compMain == another.compMain &&
this.oneArea == another.oneArea &&
this.yLow == another.yLow &&
this.yHigh == another.yHigh &&
this.Eh == another.Eh &&
Util.stringsEqual(this.title, another.title) &&
Util.stringsEqual(this.endLines, another.endLines) &&
this.databaseSpanaFile == another.databaseSpanaFile &&
this.inputYMinMax == another.inputYMinMax &&
this.pInX == another.pInX &&
this.pInY == another.pInY &&
this.Hplus == another.Hplus &&
this.OHmin == another.OHmin &&
this.aquSystem == another.aquSystem &&
this.ionicStrength == another.ionicStrength &&
this.temperature == another.temperature &&
this.pressure == another.pressure &&
this.fractionThreshold == another.fractionThreshold;
}
/** @param out a PrintStrem, such as <code>System.out</code>.
* If null, <code>System.out</code> is used. */
public void printPlotType(java.io.PrintStream out) {
if(out == null) {out = System.out;}
out.flush();
//access the enclosing class from the inner class
int Na = Chem.this.chemSystem.Na;
out.println("Plot data:");
String[] plotTypes = {"Predom","Fraction","log solub.","log conc.","log (ai/ar)","calc.pe","calc.pH","log act.","H-aff."};
String t; if(plotType >=0 && plotType <=8) {t = plotTypes[plotType];} else {t = "undefined";}
out.print(" plot type = "+plotType+" ("+t+");");
if(!Double.isNaN(yLow)) {out.print(" yLow = "+yLow);} else {out.print(" yLow = NaN");}
if(!Double.isNaN(yHigh)) {out.println(" yHigh = "+yHigh);} else {out.println(" yHigh = NaN");}
out.println(" compX = "+compX+" compY = "+compY+" compMain = "+compMain);
out.println(" oneArea = "+oneArea+" fractionThreshold = "+fractionThreshold);
out.flush();
} //printPlotType()
} // class Diagr
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="inner class DiagrConcs">
/** An inner class containing arrays with information on the concentrations
* for each component in a diagram and how ("hur" in Swedish) they are varied.
* A sister class, Diagr, contains non-array data: which components are
* in the axes, diagram type, etc */
public class DiagrConcs implements Cloneable {
/** Concentration types for each component:
<pre>hur =1 for "T" (fixed Total conc.)
hur =2 for "TV" (Tot. conc. Varied)
hur =3 for "LTV" (Log(Tot.conc.) Varied)
hur =4 for "LA" (fixed Log(Activity) value)
hur =5 for "LAV" (Log(Activity) Varied)</pre> */
public int[] hur;
/** For each component either:<ul>
* <li>the fixed total concentration, if hur[i]=1
* <li>the fixed log(activity), if hur[i]=4
* <li>the lowest value for either the total concentration, the log(Tot.Conc.)
* or the log(activity) when these are varied, if hur[i]=2, 3 or 5, respectively
* </ul> */
public double[] cLow;
/** For each component either:<ul>
* <li>undefined, if hur[i]=1 or 4
* <li>the highest value for either the total concentration, the log(Tot.Conc.)
* or the log(activity) when these are varied, if hur[i]=2, 3 or 5, respectively
* </ul> */
public double[] cHigh;
/** An inner class to "Chem" containing arrays with information on the
* concentrations for each component in a diagram and how (hur) they are varied.
* A sister class, Diagr, contains non-array data: which components are
* in the axes, diagram type, etc
* @param Na int number of chemical components
* @throws lib.kemi.chem.Chem.ChemicalParameterException */
public DiagrConcs(int Na) throws ChemicalParameterException {
if(Na<0) {
throw new ChemicalParameterException(
"Error in \"DiagrConcs\"-constructor: Na="+Na+". Must be >=0.");
}
hur = new int[Na];
cLow = new double[Na];
cHigh = new double[Na];
for(int i = 0; i < Na; i++) {hur[i]=-1; cLow[i]=Double.NaN; cHigh[i]=Double.NaN;}
} // constructor
@Override public Object clone() throws CloneNotSupportedException {
super.clone();
int Na = this.hur.length;
DiagrConcs dc;
try {dc = new DiagrConcs(Na);}
catch(ChemicalParameterException ex) {
//this should not happen
return null;
}
System.arraycopy(this.hur, 0, dc.hur, 0, Na);
System.arraycopy(this.cLow, 0, dc.cLow, 0, Na);
System.arraycopy(this.cHigh, 0, dc.cHigh, 0, Na);
return dc;
} // clone()
public boolean isEqualTo(DiagrConcs another) {
if(another != null) {
boolean ok = true;
if(!java.util.Arrays.equals(this.hur, another.hur)) {
//System.out.println(" hur not equal");
ok = false;
}
if(ok && cLow.length != another.cLow.length) {
//System.out.println("cLow length not equal");
ok = false;
}
if(ok && cHigh.length != another.cHigh.length) {
//System.out.println("cHigh length not equal");
ok = false;
}
if(ok && cLow.length >0) {
for(int i=0; i < cLow.length; i++) {
if(!Util.areEqualDoubles(cLow[i], another.cLow[i])) {
//System.out.println("cLow not equal i="+i+", cLow[i]="+cLow[i]+", another.cLow[i]="+another.cLow[i]);
ok = false; break;}
} //for i
//if(!ok) {System.out.println("cLow not equal");}
}
if(ok && cHigh.length >0) {
for(int i=0; i < cHigh.length; i++) {
if(!Util.areEqualDoubles(cHigh[i], another.cHigh[i])) {ok = false; break;}
} //for i
//if(!ok) {System.out.println("cHigh not equal");}
}
return ok;
}
return false;
} // isEqualTo(DiagrConcs)
@Override
public String toString() {
//access the enclosing class from the inner class
int Na = Chem.this.chemSystem.Na;
String txt = "concentrations for components:";
String[] concTypes = {" - ","T","TV","LTV","LA","LAV"};
String t;
for(int i=0; i < Na; i++) {
if(hur[i] >=1 && hur[i] <=5) {t = concTypes[hur[i]];} else {t = concTypes[0];}
txt = txt + nl +
" i="+i+" hur = "+hur[i]+" ("+t+"), cLow="+cLow[i]+", cHigh="+cHigh[i];
}//for i
return txt;
}
} //class DiagrConcs
//</editor-fold>
} | 43,622 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
HaltaFall.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibChemDiagr/src/lib/kemi/haltaFall/HaltaFall.java | package lib.kemi.haltaFall;
import lib.kemi.chem.Chem;
/** <code>HaltaFall</code> ("Concentrations and precipitates" in Swedish)
* calculates the equilibrium composition of a chemical system with
* fluid and solid phases. It is essentially the Java translation of
* the <code>HALTAFALL</code> program, published in:<ul>
* <li> N.Ingri, W.Kakolowicz, L.G.Sillen and B.Warnqvist, "High-Speed Computers
* as a Supplement to Graphical Methods - V. HALTAFALL, a General Program
* for Calculating the Composition of Equilibrium Mixtures".
* <i>Talanta</i>, <b>14</b> (1967) 1261-1286
* <li> N.Ingri, W.Kakolowicz, L.G.Sillen and B.Warnqvist, "Errata".
* <i>Talanta</i>, <b>15</b> (1968) xi-xii
* <li> R.Ekelund, L.G.Sillen and O.Wahlberg, "Fortran editions of Haltafall and
* Letagrop". <i>Acta Chemica Scandinavica</i>, <b>24</b> (1970) 3073
* <li> B.Warnqvist and N.Ingri, "The HALTAFALL program - some corrections, and
* comments on recent experience".
* <i>Talanta</i>, <b>18</b> (1971) 457-458
* </ul>
* However, in this version the supersaturated solid phases are picked-up
* one at a time, instead of all at once.
* <p>
* The input data is supplied through an instance of <code>Chem.ChemSystem</code>
* and its nested class <code>Chem.ChemSystem.ChemConcs</code>. The equilibrium composition
* is calculated by method <code>haltaCalc</code> and stored in the arrays of
* the <code>ChemConcs</code> instance.
* <b>Note</b> that if the contents of <code>ChemSystem</code> is
* changed <i>after</i> the creation of the <code>HaltaFall</code> object,
* unpredictable results and errors may occur. The contents of <code>ChemConcs</code>
* should however be changed <i>before</i> every call to method <code>haltaCalc</code>.
* <p>
* A <code>HaltaFall</code> object is also associated with an instance of
* a class <code>Factor</code> having a method <code>factor</code> that
* calculates the activity coefficients. In its simplest form:
* <pre>
* public class Factor {
* public Factor() {}
* public void factor(double[] C, double[] lnf) {
* for(int i=0; i<lnf.length; i++) {lnf[i]=0.;}
* }
* }
* </pre>
*
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
* @see lib.kemi.chem.Chem.ChemSystem ChemSystem
* @see lib.kemi.chem.Chem.ChemSystem.ChemConcs ChemConcs
* @author Ignasi Puigdomenech */
public class HaltaFall {
//<editor-fold defaultstate="collapsed" desc="private fields">
/** an instance of a class to store data defining a chemical system */
private Chem.ChemSystem cs;
/** an instance of a class to store concentration data about a chemical system */
private Chem.ChemSystem.ChemConcs c;
/** where messages will be printed. It may be "System.out" */
private java.io.PrintStream out;
/** an instance of class <code>Factor</code> used to calculate activity coefficients */
private Factor factor = null;
/** If <code>true</code> only one solid is allowed to precipitate at
* each call of <code>fasta()</code>; if <code>false</code> all supersaturated
* solids are allowed to precipitate. In many cases 10-20 solids are found to
* be supersaturated in a system with less than 5 chemical components.
* This leads to long iterations trying to select the few solids that
* precipitate and to reject the 15 or more solids that do not precipitate. */
private final boolean ONLY_ONE_SOLID_AT_A_TIME = true;
/** Used in procedure <code>kille()</code>: When the stepwise changes of x
* are smaller than <code>STEGBYT</code> the procedure switches to
* the chord method. Should be small enough to avoid rounding errors.
* It must not be smaller than STEGBYT.
* @see lib.kemi.haltaFall.HaltaFall#x x
* @see lib.kemi.haltaFall.HaltaFall#y y
* @see lib.kemi.haltaFall.HaltaFall#y0 y0
* @see lib.kemi.haltaFall.HaltaFall#STEG0 STEG0
* @see lib.kemi.haltaFall.HaltaFall#steg steg
* @see lib.kemi.haltaFall.HaltaFall#catchRoundingErrors catchRoundingErrors
* @see lib.kemi.haltaFall.HaltaFall#kille() kille() */
private final double STEGBYT = 0.005;
/** starting value of steg[] in the iterations of procedure kille
* when dealing with a new chemical system, that is, when
* <code>c.cont = false</code>.
* @see lib.kemi.chem.Chem.ChemSystem.ChemConcs#cont cont
* @see lib.kemi.haltaFall.HaltaFall#kille() kille()
* @see lib.kemi.haltaFall.HaltaFall#x x
* @see lib.kemi.haltaFall.HaltaFall#y y
* @see lib.kemi.haltaFall.HaltaFall#y0 y0
* @see lib.kemi.haltaFall.HaltaFall#STEG0_CONT STEG0_CONT
* @see lib.kemi.haltaFall.HaltaFall#STEGBYT STEGBYT
* @see lib.kemi.haltaFall.HaltaFall#steg steg */
private final double STEG0 = 0.1;
/** starting value of steg[] in the iterations of procedure kille
* when dealing with the same chemical system as last calculation, that is,
* when <code>c.cont = true</code>. It must not be smaller than STEGBYT.
* @see lib.kemi.chem.Chem.ChemSystem.ChemConcs#cont cont
* @see lib.kemi.haltaFall.HaltaFall#kille() kille()
* @see lib.kemi.haltaFall.HaltaFall#x x
* @see lib.kemi.haltaFall.HaltaFall#y y
* @see lib.kemi.haltaFall.HaltaFall#y0 y0
* @see lib.kemi.haltaFall.HaltaFall#STEG0 STEG0
* @see lib.kemi.haltaFall.HaltaFall#STEGBYT STEGBYT
* @see lib.kemi.haltaFall.HaltaFall#steg steg */
private final double STEG0_CONT = 0.01;
/** maximum number of iterations in procedure kille */
private static final int ITER_MAX =60; // it is perhaps ok with 40
/** maximum number of iterations when calculating activity coefficients */
private static final int ITERAC_MAX = 100;
/** maximum number of "InFall" iterations in procedure fasta() */
private static final int ITER_FASTA_MAX = 100;
/** The default value for the tolerance (in natural log scale) when iterating
* activity coefficients (lnG[]).<br>
* <code>TOL_LNG = 0.0023026</code> (=0.001 in log10 scale).
* @see #lnG lnG
* @see lib.kemi.chem.Chem.ChemSystem.ChemConcs#tolLogF tolLogF
* @see #actCoeffs() actCoeffs() */
private final double TOL_LNG = 0.0023026; // =0.001 in log10 scale
private final int MXA; // nax nbr components
private final int MXX; // max nbr species
private final int MXS; // max nbr of solids
private final int MXC; //= MXX-MXA-MXS; // max nbr aqueous complexes
private final int MXAQ; //= MXX-MXS; // max nbr aqueous species (comps.+complexes)
//-- booleans in alphabetical order:
/** if <b><code>true</code></b> the ongoing calculations will be stopped at
* the earliest oportunity.
* @see lib.kemi.haltaFall.HaltaFall#haltaCancel() haltaCancel() */
private boolean panic = false;
/** <b><code>true</code></b> if matrix "ruta" in procedure fasta() has come out singular
* @see lib.kemi.haltaFall.HaltaFall#ruta ruta */
private boolean singFall;
//-- integers in alphabetical order:
/** component for which tot[ivar] is being tested and lnA[ivar] adjusted
* @see lib.kemi.haltaFall.HaltaFall#iva iva
* @see lib.kemi.haltaFall.HaltaFall#ivaBra ivaBra
* @see lib.kemi.haltaFall.HaltaFall#ivaNov ivaNov */
private int ivar;
/** iteration counter when performing activity coefficient calculations */
private int iterAc;
/** iterations counter when calling procedure fasta(), that is,
* how many different sets of mass balance equations have been solved */
private int iterFasta;
/** flag to indicate degrees of success or failure from some procedures */
private int indik;
/** The routine Fasta cycles through chunks of code in the original code,
* using the value of nextFall as a guide in each case. The meanings
* of nextFall on return to this routine are as follows:
* nextFall Next Routine Line No. in original HaltaFall
* 0 Exit to PROV, 9000, 10000, 25000
* indik set to ready
* 1 fallProv 14000
* 2 beFall 16000
* 3 anFall 24000
* 4 utFall 17000
* 5 sing 18000
* 6 fUtt 20000 */
private int nextFall;
/** number of solids present at equilibrium
* @see lib.kemi.haltaFall.HaltaFall#nvaf nvaf */
private int nfall;
/** nbr of solids indicated at INFALL in procedure fasta() */
private int nfSpar = 0;
/** number of "ions", that is, species for which the activity coefficients
* need to be calculated */
private int nIon;
/** number of solids systematically eliminated at some stage while singFall
* is true in procedure fasta()
* @see lib.kemi.haltaFall.HaltaFall#fut fut
* @see lib.kemi.haltaFall.HaltaFall#singFall singFall */
private int nUt;
/** nr of mass balance equations for tot[ia] to be tested (lnA[ivar] to be varied)
* in absence of solids at equilibrium */
private int nva;
/** nbr of mass balance equations for tot[ia] to be tested (lnA[ivar] to be varied)
* in the presence of solids at equilibrium (nvaf = nva - nfall)
* @see lib.kemi.haltaFall.HaltaFall#nfall nfall
* @see lib.kemi.haltaFall.HaltaFall#nva nva */
private int nvaf;
//-- doubles in alphabetical order:
/** independent variable in y(x)=y0 (in procedure kille)
* @see lib.kemi.haltaFall.HaltaFall#kille() kille()
* @see lib.kemi.haltaFall.HaltaFall#y y
* @see lib.kemi.haltaFall.HaltaFall#y0 y0 */
private double x;
/** dependent variable in y(x)=y0 (in procedure kille)
* @see lib.kemi.haltaFall.HaltaFall#kille() kille()
* @see lib.kemi.haltaFall.HaltaFall#x x
* @see lib.kemi.haltaFall.HaltaFall#y0 y0 */
private double y;
/** value for y aimed at in y(x)=y0 (in procedure kille)
* @see lib.kemi.haltaFall.HaltaFall#kille() kille()
* @see lib.kemi.haltaFall.HaltaFall#x x
* @see lib.kemi.haltaFall.HaltaFall#y y */
private double y0;
/** The minimum value of the tolY[] array.
* In some calculations where the tolerance is high, a solid
* might be found both supersaturated and with zero or slightly negative
* concentration, and this leads to a loop. To avoid this situation, if
* the negative concentration of the solid is (in absolute value) less
* than this tolerance, the concentration is assumed to be zero.
* @see lib.kemi.haltaFall.HaltaFall#tolY tolY
* @see lib.kemi.chem.Chem.ChemSystem.ChemConcs#tol ChemConcs.tol */
private double tolFasta;
//-- boolean arrays in alphabetical order:
/** true if lnA[] is calculated from a solubility product (eqn.(14))
* @see lib.kemi.haltaFall.HaltaFall#ibe ibe */
private boolean[] ber;
/** true if the solid is assumed to be present at equilibrium */
private boolean[] fall;
/** true if the component is assumed to occur in one or more solids at equilibrium */
private boolean[] falla;
/** mono[] = true for components that only take part in mononuclear soluble
* complexes (a[ix][ia]=0 or +1 for all ix)
* @see lib.kemi.chem.Chem.ChemSystem#a Chem.ChemSystem.a */
private boolean[] mono;
/** true if any of the stoichiometric coeffients involving this component are positive (>0) */
private boolean[] pos;
/** true if any of the stoichiometric coeffients involving this component are negative (<0) */
private boolean[] neg;
/** true if it has been requested to solve the mass balance equation for this component
* (that is, kh=1) but the calculation is not possible as seen from the
* stoichimotric coefficients
* @see lib.kemi.chem.Chem.ChemSystem.ChemConcs#kh Chem.ChemSystem.ChemConcs.kh */
private boolean[] noCalc;
/** the value of logA when noCalc is true */
private final double NOCALC_LOGA = -9999.;
/** true if the two components are independent as seen from the stoichimotric coefficients
* (no complex or solid contains both components)
* @see lib.kemi.haltaFall.HaltaFall#nober nober */
private boolean[][] ober;
//-- integer arrays in alphabetical order:
/** control number used in procedures <code>kille</code> and <code>totBer</code>
* to catch numerical rounding errors: If two <i>practivally equal</i> lnA[ivar]
* are found (x1 and x2), that correspond to calculated values (y1 and y2) higher
* and lower, respectively, than the given tot[ivar] (y0), then x (=lnA[iva])
* can not be further adjusted, because x1 and x2 are equal. This occurs often
* if STEGBYT is too large.
* @see lib.kemi.haltaFall.HaltaFall#kille() kille()
* @see lib.kemi.haltaFall.HaltaFall#STEGBYT STEGBYT */
private int[] catchRoundingErrors;
/** fut[i] = ifSpar number of the i'th solid to be eliminated at some stage in
* systematic variation during <code>singFall</code> in procedure <code>fasta()</code>
* @see lib.kemi.haltaFall.HaltaFall#nUt nUt
* @see lib.kemi.haltaFall.HaltaFall#ifSpar ifSpar
* @see lib.kemi.haltaFall.HaltaFall#singFall singFall */
private int[] fut;
/** component numbers for which tot[ia] is to be calculated
* by means of the solutbility product (0 to nfall-1)
* @see lib.kemi.haltaFall.HaltaFall#nva nva */
private int[] ibe;
/** <code>iber[j]</code> = j'th of <code>iva</code> numbers to be an <code>ibe</code>
* <code>(ibe[j] = iva[iber[j]], j= 0 to nfall-1)</code>
* @see lib.kemi.haltaFall.HaltaFall#nfall nfall
* @see lib.kemi.haltaFall.HaltaFall#ibe ibe
* @see lib.kemi.haltaFall.HaltaFall#iva iva */
private int[] iber;
/** numbers of the solids present at equilibrium (0 to nfall-1)
* @see lib.kemi.haltaFall.HaltaFall#nfall nfall */
private int[] ifall;
/** nbr of the solids indicated as possible after INFALL in procedure <code>fasta()</code>,
* (needed when <code>singFall</code>)
* @see lib.kemi.haltaFall.HaltaFall#nUt nUt
* @see lib.kemi.haltaFall.HaltaFall#fut fut
* @see lib.kemi.haltaFall.HaltaFall#singFall singFall */
private int[] ifSpar;
/** control number used in procedures <code>kille</code> and <code>totBer</code>
* to catch too many iterations */
private int[] iter;
/** components numbers for which the mass balance equation has to be solved
* (lnA to be varied) when some solids are present at equilibrium (0 to nvaf-1)
* @see lib.kemi.haltaFall.HaltaFall#nfall nfall
* @see lib.kemi.haltaFall.HaltaFall#nvaf nvaf
* @see lib.kemi.haltaFall.HaltaFall#ibe ibe */
private int[] ivaf;
/** components numbers for which the mass balance equation has to be solved
* (lnA to be varied) in absence of solids (0 to nva-1)
* @see lib.kemi.haltaFall.HaltaFall#ivaf ivaf
* @see lib.kemi.haltaFall.HaltaFall#nva nva */
private int[] iva;
/** ivaBra[ivar]= the component number to be tested after ivar,
* if the mass balance for tot[ivar] is satisfied
* @see lib.kemi.haltaFall.HaltaFall#ivar ivar
* @see lib.kemi.haltaFall.HaltaFall#iva iva
* @see lib.kemi.haltaFall.HaltaFall#ivaNov ivaNov */
private int[] ivaBra;
/** ivaNov[ivar]= the component number to be tested after ivar,
* if the mass balance for tot[ivar] is not satisfied
* @see lib.kemi.haltaFall.HaltaFall#ivar ivar
* @see lib.kemi.haltaFall.HaltaFall#iva iva
* @see lib.kemi.haltaFall.HaltaFall#ivaBra ivaBra */
private int[] ivaNov;
/** control number for solving the equations in procedure kille
* @see lib.kemi.haltaFall.HaltaFall#kille() kille() */
private int[] karl;
/** number of other components which are independent of this one
* @see lib.kemi.haltaFall.HaltaFall#ober ober */
private int[] nober;
//-- double arrays in alphabetical order:
/** scale factor for solid phases, used when evaluating supersaturation */
private double[] fscal;
/** natural logarithm of the activity of the components */
private double[] lnA;
/** part of ln(c[]) independent of lnA[ivar] (eqn. 4, procedure lnaBas) */
private double[] lnBA;
/** natural logarithm of the formation equilibrium constant of a complex */
private double[] lnBeta;
/** ln(activity coeff.): natural logarithm of the single-ion activity coefficients */
private double[] lnG;
/** natural logarithm of the equilibrium constant for the dissolution of a solid */
private double[] lnKf;
/** term in lnKf', reduced lnKf (eqn 14a, procedure lnaBer) */
private double[] lnKmi;
/** the ln(activity coeff.) from the previous iteration of activity coefficient
* calculations using procedure <code>factor</code> */
private double[] oldLnG;
/** matrix combining stoichiometric coefficients and "rut1" (eqn.16b)
* at ANFALL in procedure fasta()
* @see lib.kemi.haltaFall.HaltaFall#rut1 rut1 */
private double[][] pva;
/** matrix combining stoichiometric coefficients and "ruta" (eqns 16a, 16b)
* at ANFALL in procedure fasta()
* @see lib.kemi.haltaFall.HaltaFall#ruta ruta */
private double[][] rut1;
/** matrix with stoichiometric coefficients for solid phases for the components
* that are "be", that is, those components for which the lnA[] are calculated
* from the solubility products (eqns 11m', 14, 15) at UTFALL in procedure fasta().
* Note that ruta must be inverted.
* @see lib.kemi.haltaFall.HaltaFall#singFall singFall */
private double[][] ruta;
/** step for adjusting lnA in procedure kille
* @see lib.kemi.haltaFall.HaltaFall#kille() kille()
* @see lib.kemi.haltaFall.HaltaFall#STEG0 STEG0
* @see lib.kemi.haltaFall.HaltaFall#STEGBYT STEGBYT */
private double[] steg;
/** tolerance when solving the mass balance equations for tot[] */
private double[] tolY;
/** For some reason the calculations go faster if they are performed in two steps,
* first with a small tolerance (1.E-3) and then with the user-requested tolerance.
* This is accomplished with the loop "loopTol".
* This variable is either 1 or 2 (first and second loops).
* @see lib.kemi.haltaFall.HaltaFall#tolY tolY
* @see lib.kemi.chem.Chem.ChemSystem.ChemConcs#tol ChemConcs.tol */
private int tolLoop;
/** <code>totBe[i]</code> = term for component <code>ibe[i]</code> (eqn. 15) used for calculating
* <i>cf</i> after FallProv in procedure fasta() */
private double[] totBe;
/** term of reduced total concentration in the
* presence of solids at equilibrium (eqn. 16a, procedure lnaBer) */
private double[] totVA;
/** value for x below the right value (in procedure kille)
* @see lib.kemi.haltaFall.HaltaFall#kille() kille()
* @see lib.kemi.haltaFall.HaltaFall#x x
* @see lib.kemi.haltaFall.HaltaFall#y1 y1 */
private double[] x1;
/** value for x above the right value (in procedure kille)
* @see lib.kemi.haltaFall.HaltaFall#kille() kille()
* @see lib.kemi.haltaFall.HaltaFall#x x
* @see lib.kemi.haltaFall.HaltaFall#y2 y2 */
private double[] x2;
/** the value of x obtained during the last iteration (in procedure kille)
* @see lib.kemi.haltaFall.HaltaFall#kille() kille()
* @see lib.kemi.haltaFall.HaltaFall#x x */
private double[] xOld;
/** value for y corresponding to x1 (in procedure kille)
* @see lib.kemi.haltaFall.HaltaFall#kille() kille()
* @see lib.kemi.haltaFall.HaltaFall#x1 x1 */
private double[] y1;
/** value for y corresponding to x2 (in procedure kille)
* @see lib.kemi.haltaFall.HaltaFall#kille() kille()
* @see lib.kemi.haltaFall.HaltaFall#x2 x2 */
private double[] y2;
/** natural logarithm of 10 */
private static final double ln10 = Math.log(10);
/** English locale for debug print-out */
private java.util.Locale e = java.util.Locale.ENGLISH;
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
// dbg-values, i.e. for debug print-out:
private static final int ERR_ONLY_1 = 1;
private static final int ERR_RESULTS_2 = 2;
private static final int ERR_RESL_INPUT_3 = 3;
private static final int ERR_DEBUG_FASTA_4 = 4;
private static final int ERR_DEBUG_ACT_COEF_5 = 5;
private static final int ERR_XTRA_DEBUG_6 = 6;
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="HaltaFall - constructor">
/** Constructs an instance of <code>HaltaFall</code>.
* @param cs an instance of chem.Chem.ChemSystem
* @param factor an instance of haltaFall.Factor
* @param ut where messages will be printed. It may be "System.out" or null
* @throws lib.kemi.chem.Chem.ChemicalParameterException
* @see lib.kemi.chem.Chem.ChemSystem ChemSystem
* @see lib.kemi.haltaFall.Factor Factor
* @see lib.kemi.haltaFall.HaltaFall HaltaFall
*/
public HaltaFall (Chem.ChemSystem cs, Factor factor,
java.io.PrintStream ut)
throws Chem.ChemicalParameterException {
if(ut != null) {this.out = ut;} else {this.out = System.out;}
this.cs = cs; // get the chemical system and concentrations
this.c = cs.chemConcs;
this.factor = factor;
if(c.dbg >=ERR_RESL_INPUT_3) {out.println(nl+"HaltaFall - object Constructor"+nl+
" debug level = "+c.dbg);}
c.errFlags = 0;
// NYKO
//check the chemical system
if(cs.Na <=0 || cs.mSol <0 || cs.nx < 0 || cs.solidC < 0) {
throw new Chem.ChemicalParameterException(
"Error in \"HaltaFall\": Na, nx, mSol, solidC ="+cs.Na+", "+cs.nx+", "+cs.mSol+", "+cs.solidC+nl+
" Na must be >0; nx, mSol and solidC must be >=0.");
}
if(cs.nx != (cs.Ms - cs.Na - cs.mSol)) {
throw new Chem.ChemicalParameterException(
"Error in \"HaltaFall\": nx ="+cs.nx+", must be = "+(cs.Ms - cs.Na - cs.mSol)+" (= Ms-Na-mSol)");
}
//check length of arrays
//note that species with names starting with "*" are removed,
// so length of arrays may be larger than needed
if(cs.lBeta.length < (cs.Ms-cs.Na)) {
throw new Chem.ChemicalParameterException(
"Error in \"HaltaFall\": lBeta.length ="+cs.lBeta.length+
" must be >= "+(cs.Ms-cs.Na)+" (= Ms-Na)");
}
if(cs.noll.length < cs.Ms) {
throw new Chem.ChemicalParameterException(
"Error in \"HaltaFall\": noll.length ="+cs.noll.length+
" must be >= "+cs.Ms+" (= Ms)");
}
if(c.kh.length != cs.Na) {
throw new Chem.ChemicalParameterException(
"Error in \"HaltaFall\": kh.length ="+c.kh.length+
" must be = "+cs.Na+" (= Na)");
}
if(c.logA.length < cs.Ms) {
throw new Chem.ChemicalParameterException(
"Error in \"HaltaFall\": logA.length ="+c.logA.length+
" must be >= "+cs.Ms+" (= Ms)");
}
//check values of kh[]
for(int i =0; i < cs.Na; i++) {
if(c.kh[i] <1 || c.kh[i] >2) {
throw new Chem.ChemicalParameterException(
"Error in \"HaltaFall\": kh["+i+"]="+c.kh[i]+
" (must be = 1 or 2). Note: component numbers start at zero.");
} } //for i
if(c.dbg >= ERR_RESL_INPUT_3) {
out.println("Debug output requested from HaltaFall at level "+c.dbg+nl+
" Note that arrays start at \"zero\": numbers for"+nl+
" components, complexes and solids start with 0.");
}
MXA = cs.Na; // nbr components
MXS = cs.mSol; // nbr of solids
MXX = cs.Ms; // nbr species
MXC = cs.Ms -cs.Na -cs.mSol; // nbr aqueous complexes
MXAQ = cs.Ms -cs.mSol; // nbr aqueous species (comps.+complexes)
// create working arrays
karl = new int[MXA];
iter = new int[MXA];
catchRoundingErrors = new int[MXA];
x1 = new double[MXA]; x2 = new double[MXA]; xOld = new double[MXA];
y1 = new double[MXA]; y2 = new double[MXA];
steg = new double[MXA];
ibe = new int[MXA];
ifall = new int[MXS];
iva = new int[MXA+1];
ivaf = new int[MXA];
ivaBra = new int[MXA+1]; ivaNov = new int[MXA+1];
lnBeta = new double[MXC];
lnA = new double[MXX];
lnBA = new double[MXC];
lnG = new double[MXAQ];
tolY = new double[MXA];
totVA = new double[MXA];
mono = new boolean[MXA];
ber = new boolean[MXA];
falla = new boolean[MXA];
if(MXS >0) {
lnKf = new double[MXS];
lnKmi = new double[MXS];
fall = new boolean[MXS];
ruta = new double[MXS][MXS];
rut1 = new double[MXA][MXA];
fscal = new double[MXS];
}
pos = new boolean[MXA];
neg = new boolean[MXA];
ober = new boolean[MXA][MXA];
nober = new int[MXA];
noCalc = new boolean[MXA];
pva = new double[MXA][MXC];
oldLnG = new double[MXAQ];
for(int lix =0; lix <MXAQ; lix++) {oldLnG[lix] = 0.;}
fut = new int[MXS];
iber = new int[MXA+1];
ifSpar = new int[MXS];
totBe = new double[MXA];
// The first time HaltaFall is called, a plan is made to solve the mass
// balance equations, some variables are initialized, etc.
nIon = cs.Na + cs.nx;
int liax, liaf;
for(int lix =0; lix <cs.nx; lix++) {lnBeta[lix] = ln10*cs.lBeta[lix];}
if(cs.mSol != 0) {
for(int lif=0; lif <cs.mSol; lif++) {
liaf = cs.nx +lif;
lnKf[lif] = -cs.lBeta[liaf]*ln10;
fscal[lif] = 1.;
liax = cs.Na +cs.nx +lif;
if(!cs.noll[liax]) {
for(int lia =0; lia < cs.Na; lia++) {
fscal[lif] = fscal[lif] +Math.abs(cs.a[liaf][lia]);
}
}
} // for lif
} // mSol !=0
for(int lia =0; lia < cs.Na; lia++) {
mono[lia] = true;
pos[lia] = false;
if(!cs.noll[lia]) {pos[lia] = true;}
neg[lia] = false;
for(int lix=cs.Na; lix < cs.Ms; lix++) {
liax = lix -cs.Na;
if(cs.noll[lix]) {continue;}
if(Math.abs(cs.a[liax][lia]) > 0.00001
&& Math.abs(cs.a[liax][lia]-1) > 0.00001) {mono[lia] = false;}
if(cs.a[liax][lia] > 0) pos[lia] = true;
if(cs.a[liax][lia] < 0) neg[lia] = true;
} // for lix
} // for i
double xm;
for(int li=0; li <cs.Na; li++) {
for(int lj=0; lj <cs.Na; lj++) {
ober[li][lj] = li != lj;
for(int lix=0; lix <cs.nx; lix++) {
if(cs.noll[cs.Na+lix]) {continue;}
xm = cs.a[lix][li]*cs.a[lix][lj];
if(Math.abs(xm) > 0.00001) {ober[li][lj] = false;}
} // for lix
if(cs.mSol == 0) {continue;}
for(int lif=0; lif <cs.mSol; lif++) {
if(cs.noll[nIon+lif]) {continue;}
liaf = cs.nx +lif;
xm = cs.a[liaf][li]*cs.a[liaf][lj];
if(Math.abs(xm) > 0.00001) {ober[li][lj] = false;}
} // for lif
} // for lj
} // for li
for(int li=0; li <cs.Na; li++) {
nober[li]=0;
for(int lj=0; lj <cs.Na; lj++) {
if(ober[li][lj]) nober[li] = nober[li] +1;
} // for lj
} // for li
for(int ia=0; ia <cs.Na; ia++) {
if(c.kh[ia] == 2) {continue;} //calculation not requested
noCalc[ia] = false; // that is, calc = true, calculation is possible
if(!(pos[ia] && neg[ia]) &&
!(pos[ia] && c.tot[ia] > 0) &&
!(neg[ia] && c.tot[ia] < 0)) {
noCalc[ia] = true; //calculation is not possible
c.logA[ia] = NOCALC_LOGA;
}
} // for ia
haltaGetIva();
if(c.dbg >=ERR_RESL_INPUT_3){
printInput();
out.println("HaltaFall object constructor ends");
}
} // HaltaFall - constructor
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="haltaCalc">
/** Calculates the equilibrium composition of a Chemical System.<br>
* Error reporting: Exceptions are thrown if needed, and the variable
* "<code>Chem.ChemSystem.ChemConncs.errFlags</code>" is set.
* Output is written to a user-specified PrintStream provided to the constructor.
* @see lib.kemi.haltaFall.HaltaFall HaltaFall
* @see lib.kemi.haltaFall.HaltaFall#HaltaFall(lib.kemi.chem.Chem.ChemSystem, lib.kemi.haltaFall.Factor, java.io.PrintStream) HaltaFall(chemSystem, factor, printStream)
* @see lib.kemi.haltaFall.HaltaFall#haltaCancel() haltaCancel()
* @throws lib.kemi.chem.Chem.ChemicalParameterException */
public void haltaCalc()
throws Chem.ChemicalParameterException {
int ia; int rva; boolean tjat; double w;
if(c.dbg >=ERR_RESL_INPUT_3) {out.println("haltaCalc(concs): Starting calculation with new concentrations."+nl+
" debug level = "+c.dbg);}
panic = false;
/** A note on activity coefficient calculations. It would seem logic to add
* an activity coefficient calculation loop after step (after each cBer() call).
* However, "kille" takes large steps in lnA and soon a value of lnA for a
* component implies very large activities for the individual species, which
* in turn results in unrealistic ionic strengths. The result is that the activity
* coefficient calculation do not converge.
*
* The approach adopted here is to first get the equilibrium composition at a
* fixed value of the activity coefficients, then calculate new activity
* coefficients based on the new equilibrium composition, and iterate until
* the activity coefficients do not vary.
*/
/** For some reason the calculations go faster if they are performed in two steps,
* first with a large tolerance (e.g. 1.E-3) and then with the user-requested
* tolerance. This is accomplished with "loopTol".
* To remove this loop, set TOL0 <= 1.E-10 in next line */
final double TOL0 = 5.01187233E-3; // log10(TOL0) = -2.3
double tol;
final String[] msg = new String[] {" (preliminary calculation with higher tolerance)"," (with user-requested tolerance)"};
tolLoop = 0;
loopTol:
do {
tol = Math.min(Math.max(Math.abs(c.tol),1.e-9),1.e-2); // something between 1.E-9 and 1.E-2
if(tolLoop == 0) {
if(tol < TOL0) {tol = TOL0;} else {tolLoop++;}
}
tolLoop++;
if(c.dbg >=ERR_RESL_INPUT_3 && TOL0 > 1.e-10) {
out.println("- - - - - Tolerance loop: "+tolLoop+" (of 2)"+msg[tolLoop-1]);
}
c.errFlags = 0; // clear all error flags
haltaInit();
boolean firstLoop = true;
singFall = false;
iterFasta = 1;
// NYA: get lnA[] and/or tolY[]
//Smaller tolerances are set to components solved in "inner" iteration loops.
// The maximum decrease in the tolerance is "MAXtolSPAN" (in log-units).
// For example, if tol=1.e-5, the tolerance for the component in the inner
// loop might be 1.e-7, depending on the number of equations to solve (nva).
final int MAXtolSPAN;
if(nva <= 3) {MAXtolSPAN = 1;} else {MAXtolSPAN = 2;} //log10-units
double logTol = Math.log10(tol);
if(c.dbg >=ERR_RESL_INPUT_3) {out.println("Max tolerance to solve mass-balance eqns. (log) = "+(float)logTol+", max tolerance span (log) = "+MAXtolSPAN);}
// Get tolStep (tolerance step) from tolSpan, minTot and maxTot:
// minTot will contain the smallest absolute value of non-zero total concentration
// maxTot will contain the largest absolute value of non-zero total concentration
double minTot = Double.MAX_VALUE;
// tolStep is the step size in log-units for the change in tol between components
double tolStep = 0.;
if(nva > 1) {
// get a value between 1 and 3
// if nva = 2 then tolSpan = 1
// if nva = 3 then tolSpan = 2
// if nva >= 4 then tolSpan = 3
int tolSpan = Math.min(MAXtolSPAN, nva-1);
// if nva = 2 then tolSteg = 1
// if nva = 3 then tolSteg = 1
// if nva = 4 then tolSteg = 1
// if nva = 5 then tolSteg = 0.75
// if nva = 6 then tolSteg = 0.6 etc
tolStep = (double)tolSpan/(double)(nva-1);
// get minTot and maxTot: the smallest and largest absolute value non-zero total concentrations
for(ia=0; ia <cs.Na; ia++) {
if(c.kh[ia]==1 && c.tot[ia]!=0. && !noCalc[ia]) {
minTot = Math.min(Math.abs(c.tot[ia]),minTot);
}
}
}
// minTot value is used to calculate tolerance when a tot.conc.=0;
// use 1e-7 as minimum concentration if the smallest non-zero total concentration is too high
minTot = Math.min(minTot, 1.e-7);
if(c.dbg >=ERR_RESL_INPUT_3){out.println("Mass-balance tolerances (relative):");}
int ivaIndex;
tolFasta = Double.MAX_VALUE;
for(ia=0; ia <cs.Na; ia++) {
if(c.kh[ia] == 1 && !noCalc[ia]) {
w = logTol;
if(nva > 1) {
ivaIndex = 0;
for(ivar=0; ivar < nva; ivar++) {
if(iva[ivar] == ia) {ivaIndex = ivar; break;}
}
ivaIndex = (nva-1) - ivaIndex;
w = logTol - tolStep*(double)ivaIndex;
}
w = Math.pow(10,w);
if(c.dbg >=ERR_RESL_INPUT_3){out.print(" "+(float)w);}
// if the total concentration is zero, use a minimum value
tolY[ia] = w * Math.max(Math.abs(c.tot[ia]),minTot);
// if(tolLoop>1) out.println("w="+(float)w+", minTot="+(float)minTot+", c.tot["+ia+"]="+(float)c.tot[ia]+", tolY["+ia+"]="+(float)tolY[ia]); // ##
tolFasta = Math.min(tolFasta, tolY[ia]);
} //if kh =1
else {
if(c.dbg >=ERR_RESL_INPUT_3) {out.print(" NaN");}
tolY[ia]=Double.NaN;
}
lnA[ia] = ln10 * c.logA[ia];
} //for ia
if(c.dbg >=ERR_RESL_INPUT_3){ // ---- debug ----
out.println(nl+"Mass-balance tolerances (absolute):");
for(ia=0; ia <cs.Na; ia++) {out.print(" "+(float)tolY[ia]);}
out.println();
out.println("Continuation run: "+c.cont+", STEG0= "+STEG0+", STEG0_CONT= "+STEG0_CONT+", STEGBYT= "+STEGBYT);
}
if(nva <= 0) { // NVA=0 No mass balance eqn. needs to be solved
if(c.dbg >=ERR_DEBUG_FASTA_4) {out.println(" nva = 0");}
//java: changed ivar=1 to =0
ivar = 0;
iterFasta = 0;
x = lnaBas(ivar);
iterAc = 0; c.errFlagsClear(6);
while(true) {
cBer(ivar);
if(!c.actCoefCalc || actCoeffs()) {break;} // ok!
if(c.isErrFlagsSet(6)) {break;} // activity factors did not converge
}
fasta();
nog();
if(c.dbg >=ERR_DEBUG_FASTA_4) {out.println("haltaCalc returns;"+nl);}
return;
} //if nva =0
//SLINGOR: ("loops" in Swedish)
// Either:
// 1- calculation starts (a first guess is made for the unknown lnA[])
// 2- after fasta()-ANFALL when a different set of solids is found,
// this is the starting point to find the new lnA[] with the new set of solids
// 3- after activity coefficient corrections, find the new lnA[]
Slingor:
while(true) {
if(panic) {break;} //Slingor
if(c.dbg >=ERR_RESL_INPUT_3){out.println("--- haltaCalc at Slingor; nva="+nva+", nfall="+nfall+"; nvaf="+nvaf);}
if(c.dbg >=ERR_DEBUG_FASTA_4) {
printArrays(true,false); //print iva[], ivaBra[], ivaNov[]
if(nvaf>0) {printArraysFasta(true, false,false,false,false, true, false,false);} //print ifall and ivaf[]
}
for(rva =0; rva < nva; rva++) {
ia = iva[rva];
karl[ia] = 1;
if(!c.cont) {steg[ia] = STEG0;} else {steg[ia] = STEG0_CONT;}
iter[ia]=0;
catchRoundingErrors[ia]=0;
} //for rva
ivar =iva[0]; //java: changed iva[1] to iva[0]
if(c.dbg >= ERR_DEBUG_FASTA_4) {
out.println(" haltaCalc at Slingor; new ivar="+ivar);
}
if(nfall >0) {lnaBer1();}
x = lnaBas(ivar);
if(ber[ivar]) { //calculate lnA from a solubility product
if(c.dbg >= ERR_DEBUG_FASTA_4) {
out.println(" ber["+ivar+"]=true; x="+x+"; tjat=false;");
printArrays(false,true); //print lnA
}
cBer(ivar);
if(nvaf >0) {lnaBer2();}
tjat = false;
} //if ber[ivar]
else {
tjat = true;
if(cs.nx == 0 && cs.noll[ivar]) {lnA[ivar]=1.; tjat = false;} //added 2011-sept.
if(c.dbg >= ERR_DEBUG_FASTA_4) {out.println(" ber["+ivar+"]=false; tjat="+tjat);}
}
//TJAT ( = "repeat" or "nagg" in Swedish)
// Solve the mass balance equations through iterations
Tjat:
while(true) {
if(panic) {break Slingor;}
if(c.dbg >= ERR_DEBUG_FASTA_4) {out.println("--- haltaCalc at Tjat; ivar="+ivar+", tjat="+tjat);}
goToProv: {
if(tjat) {
lnA[ivar] =x;
if(falla[ivar]) {
lnaBer1();
x = lnaBas(ivar);
}
if(ivar != ivaNov[ivar]) {
// Clear "too Many Iterations" for "inner" loops if they are "dependent" with this ivar
for(rva=0; rva < nva; rva++) {
if(iva[rva] != ivar) {continue;}
if(rva == 0) {break;} // do not clear anything for the 1st iva
for(int n=0; n < rva; n++) {
ia = iva[n];
if(ia != ivar && !ober[ivar][ia]) {
if(c.dbg >= ERR_XTRA_DEBUG_6) {out.println(" setting iter["+ia+"]=0 and catchRoundingErrors["+ia+"]=0");}
iter[ia] = 0; catchRoundingErrors[ia]=0;
}
}
break; //for
}
ivar = ivaNov[ivar];
if(c.dbg >=ERR_XTRA_DEBUG_6) {out.println("--- haltaCalc at Tjat; new ivar="+ivar);}
x = lnaBas(ivar);
if(ber[ivar]) {
cBer(ivar);
if(nvaf >0) lnaBer2();
break goToProv;
} //if ber[ivar]
}
cBer(ivar);
if(nvaf >0) {lnaBer2();}
totBer(); /* Returns a value for indik
* indik=1 not ok but it is a component only involved in
* mononuclear reactions and there are no solids present
* indik=2 ok (the Y is equal to Y0 within the tolerance)
* indik=3 not ok and it is either not a mono component or
* there are solids present
* indik=4 if too many iterations (iter[ivar] is then > ITER_MAX+1) */
if(indik ==1) {continue;} //Tjat
else if(indik ==2 || indik ==4) {break goToProv;}
else if(indik ==3) {
kille();
continue; //Tjat
}
} //if tjat
else {
if(c.actCoefCalc) {actCoeffs();}
tjat = true;
}
} //goToProv:
//PROV ( = "test" in Swedish)
Prov: //The mass balance for component "ivar" was satisfied
while(true) {
if(panic) {break Slingor;}
if(c.dbg >= ERR_DEBUG_FASTA_4) {
out.println("--- haltaCalc at Prov; old ivar="+ivar+", new ivar="+ivaBra[ivar]);
printArrays(false,true); //print lnA
}
ivar = ivaBra[ivar];
//java: changed ivar==0 to ivar==-1
if(ivar == -1) {
// This was the last ivar: check activity coefficients and the solid phases
// Calculate activity coefficients
if(firstLoop) {
if(c.actCoefCalc && !actCoeffs()) {
// act.coeffs. changed
singFall = false; // solid phases might change as well...
continue Slingor;
}
}
// ok, act.coeffs. not changed
firstLoop = false;
//if(!c.isErrFlagsSet(6)) {iterc = 0;}
// check for "too many iterations" of the outer loop
if(iter[iva[nva-1]] > ITER_MAX+1) {break Slingor;}
// Solid phases
fasta(); /* Returns
* indik=2 if a new set of solids is chosen
* indik=3 if ok: either no solids precipitate in the system,
* or no solubility products are exceeded and no solid
* assumed present has zero or negative concentration
* indik=4 if too may solid phase combinations have been tested
* indik=1 if "tji" (all combinations of solids give unsoluble equations,
* i.e. negative determinants). */
if(panic) {break Slingor;}
if(indik !=2) { // "ok" (or can not go on) in fasta()
if(c.dbg >= ERR_DEBUG_FASTA_4) {
out.println("haltaCalc at Prov after fasta()");
printArrays(false,true); //print lnA
}
if(indik ==4) {break Slingor;} // too may solid phase iterations
// Calculate activity coefficients
if(!c.actCoefCalc || actCoeffs()) { // ok: act.coeffs. not changed
iterAc = 0; c.errFlagsClear(6);
break Slingor;
} else { // not ok: act.coeffs. changed
singFall = false; // solid phases might also change
continue Slingor;
}
} else if(indik ==2) { // not "ok" in fasta()
// new set of solids: clear the "too many iterations" flag
c.errFlagsClear(1); // the numerical solution is uncertain
c.errFlagsClear(2); // too many iterations when solving the mass balance equations
c.errFlagsClear(5); // some aqueous concentration(s) are too large (>20): uncertain activity coefficients
c.errFlagsClear(6); // activity factors did not converge.
iterAc = 0;
continue Slingor;
}
} //if ivar=-1
if(ber[ivar]) { // ber[]=true if lnA is calculated from a solid
continue; //Prov
}
x = lnaBas(ivar);
totBer(); /* Returns a value for indik
* indik=1 not ok but it is a component only involved in
* mononuclear reactions and there are no solids present
* indik=2 ok (the Y is equal to Y0 within the tolerance)
* indik=3 not ok and it is either not a mono component or
* there are solids present
* indik=4 if too many iterations (iter[ivar] is then > ITER_MAX+1) */
if(indik ==1) {continue Tjat;}
else if(indik ==2) {continue;} //Prov
else if(indik ==3) {kille(); continue Tjat;}
else if(indik ==4) {iter[ivar] = 0; catchRoundingErrors[ivar]=0; continue;} //Prov
break Slingor; // this statement should not be executed
} //while Prov:
} //while Tjat:
} //while Slingor:
//NOG ( = "enough" in Swedish)
if(c.dbg >=ERR_RESL_INPUT_3) {out.println("--- haltaCalc at NOG, errFlags = "+c.errFlagsToString());}
if(panic) {
c.errFlagsSet(7); // calculation interrupted by the user
if(c.dbg >=ERR_ONLY_1) {out.println(" ***** Interrupted by the user! *****");}
break loopTol;
}
nog();
} while (tolLoop <= 1); // loopTol:
for(rva=0; rva < nva; rva++) {
if(catchRoundingErrors[iva[rva]]==3) {c.errFlagsSet(1);}
if(iter[iva[rva]] > ITER_MAX+1) {c.errFlagsSet(2);}
}
if(c.dbg >=ERR_RESL_INPUT_3) {
out.println("---- haltaCalc(concs) returns; cont = "+c.cont+nl+
" outer-loop iterations: "+iter[iva[nva-1]]+", solid combinations = "+iterFasta+nl+
" activity coefficient iterations: "+iterAc);
String t = "";
for(rva=0; rva < nva; rva++) {
if(catchRoundingErrors[iva[rva]]==3) {if(!t.isEmpty()) {t=t+", ";} t=t+String.valueOf(iva[rva]);}
}
if(!t.isEmpty()) {out.println(" round-off errors for component(s) "+t);}
t = "";
for(rva=0; rva < nva; rva++) {
if(iter[iva[rva]] > (ITER_MAX+1)) {if(!t.isEmpty()) {t=t+", ";} t=t+String.valueOf(iva[rva]);}
}
if(!t.isEmpty()) {out.println(" too many iterations for component(s) "+t);}
out.println();
}
if(c.dbg >=ERR_RESULTS_2) {printConcs();} // ---- debug ----
/** 1: the numerical solution is uncertain (round-off errors)
* 2: too many iterations when solving the mass balance equations
* 3: failed to find a satisfactory combination of solids
* 4: too many iterations trying to find the solids at equilibrium
* 5: some aqueous concentration(s) are too large (20) uncertain activity coefficients
* 6: activity factors did not converge.
* 7: calculation interrupted by the user. */
c.cont = !c.isErrFlagsSet(2) && !c.isErrFlagsSet(3) && !c.isErrFlagsSet(4) &&
!c.isErrFlagsSet(6) && !c.isErrFlagsSet(7);
} // haltaCalc
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="haltaCancel()">
/** Cancels (stops) any ongoing calculation of the equilibrium composition
* The variable <code>Chem.ChemSystem.ChemConncs.errFlags</code>" is set.
* @see lib.kemi.haltaFall.HaltaFall HaltaFall
* @see lib.kemi.haltaFall.HaltaFall#HaltaFall(lib.kemi.chem.Chem.ChemSystem, lib.kemi.haltaFall.Factor, java.io.PrintStream) HaltaFall(chemSystem, factor, printStream)
* @see lib.kemi.haltaFall.HaltaFall#haltaCalc() haltaCalc()
*/
public void haltaCancel() {panic = true;}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="printConcs">
/** Prints the data stored the instance of <code>Chem.ChemSystem.ChemConcs</code>
* that is associated with this instance of <code>HaltaFall</code>. If called
* <i>after</i> method <code>haltaCalc</code> it will print the calculated
* chemical equilibrium composition.
* Output is written to the user-specified <code>PrintStream</code> provided to the constructor.
* @see lib.kemi.haltaFall.HaltaFall#haltaCalc() haltaCalc()
* @see lib.kemi.haltaFall.HaltaFall#HaltaFall(lib.kemi.chem.Chem.ChemSystem, lib.kemi.haltaFall.Factor, java.io.PrintStream) HaltaFall()
* @see lib.kemi.haltaFall.HaltaFall HaltaFall */
public void printConcs() {
int n0, nM, iPl, nP;
out.flush();
boolean failed = c.errFlags >0 && (c.isErrFlagsSet(2) || c.isErrFlagsSet(3) ||
c.isErrFlagsSet(4) || c.isErrFlagsSet(6));
if(failed) {out.println("--- HaltaFall - Output composition"+nl+"... Failed calculation: "+nl+c.errFlagsGetMessages());}
else {
out.println("--- HaltaFall - Calculated equilibrium composition:");
if(c.isErrFlagsSet(1)) {out.println(" (round-off errors - not within given tolerances)");}
}
out.println("Components:");
n0 = 0; //start index to print
nM = cs.Na-1; //end index to print
iPl = 4; nP= nM-n0; if(nP >=0) { //items_Per_Line and itemsto print
out.print(" tot conc =");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %13.5g",c.tot[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
n0 = 0;
nM = cs.Na-1;
iPl = 4; nP= nM-n0; if(nP >=0) {
out.print("solubility=");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %13.5g",c.solub[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
n0 = 0;
nM = cs.Na-1;
iPl = 4; nP= nM-n0; if(nP >=0) {
out.print(" log Act=");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %13.5g",c.logA[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
out.println("Aqu.Species (all components + aqu.complexes):");
n0 = 0;
nM = nIon-1;
iPl = 4; nP= nM-n0; if(nP >=0) {
out.print(" Conc =");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %13.5g",c.C[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
n0 = 0;
nM = nIon-1;
iPl = 4; nP= nM-n0; if(nP >=0) {
out.print(" log f=");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %13.5g",c.logf[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
out.println("Solid Phases:");
n0 = nIon;
nM = cs.Ms-1;
iPl = 4; nP= nM-n0; if(nP >=0) {
out.print(" Conc =");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %13.5g",c.C[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
n0 = nIon;
nM = cs.Ms-1;
iPl = 4; nP= nM-n0; if(nP >=0) {
out.print(" log Act =");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %13.5g",c.logA[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
out.println("Tolerances used (absolute):");
for(int ia=0; ia <cs.Na; ia++) {out.print((float)tolY[ia]+" ");}
out.println();
if(failed) {out.println("--- HaltaFall - End of output composition (failed calculation).");}
else {out.println("--- HaltaFall - End of equilibrium composition.");}
out.flush();
} //printConcs()
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="private procedures">
//<editor-fold defaultstate="collapsed" desc="nog()">
/** Enough:
* Calculate logA[], logf[], tot[] and solub[]
*/
private void nog() {
if(c.dbg >=ERR_XTRA_DEBUG_6) {out.println("nog() in;");}
int lia, lix, liax, liaf;
for(lia =0; lia < cs.Na; lia++) {
c.logf[lia] = lnG[lia]/ln10; //activity coeff.
c.solub[lia] = 0.;
if(!cs.noll[lia]) {c.solub[lia] = c.C[lia];}
for(lix =0; lix <cs.nx; lix++) {
liax = cs.Na +lix;
if(!cs.noll[liax]) {
c.solub[lia] = c.solub[lia] +cs.a[lix][lia]*c.C[liax];
}
} //for lix
if(c.kh[lia] ==2) { //logA given as input
//for water (H2O) the activity might have been changed
//when calculating activity coefficients
if(lia == cs.jWater) {c.logA[lia] = lnA[lia]/ln10;}
c.tot[lia] = c.solub[lia];
if(cs.mSol > 0) {
for(lix =0; lix < cs.mSol; lix++) {
liax = nIon +lix;
liaf = cs.nx +lix;
if(!cs.noll[liax]) {
c.tot[lia] = c.tot[lia] +cs.a[liaf][lia]*c.C[liax];
}
} //for lix
} //if mSol >0
} //if kh =2
else { // Total Concentration given as input
c.logA[lia] = lnA[lia]/ln10;
} //if kh =1
} //for i
for(lix =0; lix <cs.nx; lix++) {
liax = cs.Na + lix;
c.logf[liax] = lnG[liax]/ln10;
c.logA[liax] = lnA[liax]/ln10;
} //for lix
if(cs.mSol >0) {
for(lix =0; lix <cs.mSol; lix++) {
liax = nIon + lix;
c.logA[liax] = lnA[liax]/ln10;
} //for lix
} //if mSol >0
if(c.dbg >=ERR_XTRA_DEBUG_6) {out.println("nog() returns;");}
} // nog
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="haltaInit">
/**
* Checks if for some component the total concentration has changed in a way
* that makes the mass-balance equations to have no solution.
*/
private void haltaInit() {
if(c.dbg >= ERR_RESL_INPUT_3) {out.println("haltaInit() in");}
boolean ok = c.cont;
c.tolLogF = TOL_LNG / ln10;
for(int ia =0; ia <cs.Na; ia++) {
iter[ia] = 0;
catchRoundingErrors[ia] = 0;
xOld[ia] = Double.MAX_VALUE;
if(c.kh[ia] == 2 || (pos[ia] && neg[ia])) {continue;}
if((pos[ia] && c.tot[ia]>0) || (neg[ia] && c.tot[ia]<0)) {
if(!noCalc[ia]) {continue;} //calculation was possible
ok = false;
noCalc[ia] = false; //calculation is possible
c.logA[ia] = -10.;
if(c.tot[ia] >0) {c.logA[ia] = Math.log10(c.tot[ia]) -2.;}
} //if pos | neg
else {
if(!noCalc[ia]) {ok = false;} //calculation was possible
noCalc[ia] = true; //calculation is not possible
c.logA[ia] = NOCALC_LOGA;
}
} //for ia
if(c.dbg >= ERR_RESL_INPUT_3) {
int n0 = 0;
int nM = cs.Na-1;
int iPl = 20; int nP= nM-n0; if(nP >=0) {
out.print(" noCalc[]=");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %6b",noCalc[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
}
if(!ok) {haltaGetIva();}
if(c.dbg >=ERR_RESL_INPUT_3) {
int n0, nM, iPl, nP;
n0 = 0;
nM = cs.Na-1;
iPl = 12; nP= nM-n0; if(nP >=0) {
out.print("mono[]= ");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %6b",mono[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
n0 = 0;
nM = cs.Na-1;
iPl = 20; nP= nM-n0; if(nP >=0) {
out.print("nober[]= ");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %3d",nober[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
for(int ia=0; ia < cs.Na; ia++) {
n0 = 0;
nM = cs.Na-1;
iPl = 12; nP= nM-n0; if(nP >=0) {
out.print("ober["+ia+"][]= ");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %6b",ober[ia][kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
}
printArrays(true, false);
n0 = 0;
nM = cs.Na-1;
iPl = 12; nP= nM-n0; if(nP >=0) {
out.print("noCalc[]= ");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %6b",noCalc[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
}
// use provided act.coeffs.
for(int lix =0; lix <cs.nx; lix++) {lnG[lix] = ln10*c.logf[lix];}
if(c.dbg >=ERR_RESL_INPUT_3) {out.println("haltaInit() returns");}
} // haltaInit
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="haltaGetIva()">
/** Makes a plan made to solve the mass balance equations,
* initializes some variables, etc. */
private void haltaGetIva() {
if(c.dbg >=ERR_RESL_INPUT_3) {out.println("haltaGetIva() in at NYA");}
// NYA
nfall = 0;
for(int ia=0; ia <cs.Na; ia++) {
ber[ia] = false;
falla[ia] = false;
} // for ia
if(cs.mSol>0) {
for(int lif=0; lif <cs.mSol; lif++) {fall[lif] = false;}
}
nva = 0;
for(int ia = 0; ia <cs.Na; ia++) {
if(c.kh[ia] != 2 && !noCalc[ia]) { // calculation requested and possible
nva = nva +1;
iva[nva-1] = ia; //java: changed iva[nva] to iva[nva-1]
}
} // for ia
// PLAN
if(c.dbg >=ERR_RESL_INPUT_3) {out.println("haltaGetIva() at PLAN;");}
if(nva >1) {
int m;
do {
m = 0;
for(int li = 0; li <(nva-1); li++) {
if(nober[iva[li+1]] > nober[iva[li]]) {
m = iva[li];
iva[li] = iva[li+1];
iva[li+1] = m;
} else {
if(mono[iva[li+1]] && !mono[iva[li]] &&
nober[iva[li+1]] == nober[iva[li]]) {
m = iva[li];
iva[li] = iva[li+1];
iva[li+1] = m;
}
}
} // for li
} while(m!=0);
} // if nva >1
iva[nva]=-1; ivaBra[nva]=-1; //java: changed from iva and ivaBra [nva+1]=0 to [nva]=-1
if(nva >0) {
for(int li=0; li<nva; li++) {
ivar = iva[li];
ivaBra[ivar] = iva[li+1];
int i = -1;
// HOPP ("jump" in Swedish)
while (true) {
i = i+1;
if(!ober[ivar][iva[i]]) {ivaNov[ivar] = iva[i]; break;}
}//while(true)
} // for li
} //if nva >0
if(c.dbg >=ERR_RESL_INPUT_3) {out.println("haltaGetIva() returns");}
} // haltaGetIva()
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="kille">
/** Kille: Solving the mass balance equation of component <code>ivar</code>,
* which forms polynuclear complexes. Locating the solution by giving
* steg[ivar]=0.5,1,2,4,8,16,32,64,... until a pair of x1 and x2 is found
* (when karl[ivar]=2 or 3). Then decreasing steg[ivar] (=steg[ivar]/2,
* when karl[ivar]=4) until x1 and x2 are separated less than STEGBYT; at
* that point a chord method is used.
* @see lib.kemi.haltaFall.HaltaFall#x x
* @see lib.kemi.haltaFall.HaltaFall#y y
* @see lib.kemi.haltaFall.HaltaFall#y0 y0
* @see lib.kemi.haltaFall.HaltaFall#x1 x1
* @see lib.kemi.haltaFall.HaltaFall#x2 x2
* @see lib.kemi.haltaFall.HaltaFall#y1 y1
* @see lib.kemi.haltaFall.HaltaFall#y2 y2
* @see lib.kemi.haltaFall.HaltaFall#karl karl
* @see lib.kemi.haltaFall.HaltaFall#STEG0 STEG0
* @see lib.kemi.haltaFall.HaltaFall#steg steg
* @see lib.kemi.haltaFall.HaltaFall#STEGBYT STEGBYT
* @see lib.kemi.haltaFall.HaltaFall#catchRoundingErrors catchRoundingErrors */
private void kille() {
// VARIABLES----------------------------------------------------------------
// x= independent variable in the equation y0=y(x)
// y= dependent variable
// y0= value aimed at in y0=y(x)
// x1(ia) and x2(ia)= values for x below and above the aimed value
// y1(ia) and y2(ia)= values for y corresponding to x1 and x2
//--------------------------------------------------------------------------
boolean yL;
double w, w1;
if(c.dbg >=ERR_XTRA_DEBUG_6) {
out.println("kille() in; ivar="+ivar+", karl["+ivar+"]="+karl[ivar]+", x="+x+", steg="+steg[ivar]+" (STEGBYT="+STEGBYT+")"+nl+
" x1["+ivar+"]="+x1[ivar]+", x2["+ivar+"]="+x2[ivar]+", y="+y+", y0="+y0+nl+
" y1["+ivar+"]="+y1[ivar]+", y2["+ivar+"]="+y2[ivar]);}
// Locating the solution by giving steg(Ivar)=0.5,1,2,4,8,16,32,64,...
// until a pair of x1 and x2 is found (in karl(ivar)=2 or 3). Then
// decreasing steg(ivar) (=steg(ivar)*0.5, in karl(ivar)=4) until
// x1 and x2 are separated less than STEGBYT
yL = (y > y0);
if(yL) {
x2[ivar] =x;
y2[ivar] =y;
} //if yL
else {
x1[ivar] =x;
y1[ivar] =y;
} //if !yL
switch (karl[ivar]) {
case 1: { //karl =1 the beginning
if(yL) {karl[ivar]=3; x = x -steg[ivar];}
else {karl[ivar]=2; x = x +steg[ivar];}
break;
} //karl = 1
case 2: { //karl =2 it was y<y0
if(yL) {karl[ivar] =4;}
else{
steg[ivar] = steg[ivar] + steg[ivar];
x = x +steg[ivar];}
break;
} //karl = 2
case 3: { //karl =3 it was y>y0
if(!yL) {karl[ivar] =4;}
else {
steg[ivar] = steg[ivar] + steg[ivar];
x = x -steg[ivar];}
break;
} //karl = 3
case 4: { //karl =4 we have x1 and x2 corresponding to y<y0 and y>y0
if(steg[ivar] >= STEGBYT) {
steg[ivar] = 0.5 * steg[ivar];
if(!yL) {x = x + steg[ivar];} else {x = x - steg[ivar];}
break;
} //if steg > STEGBYT
//KORDA: aproximating the solution by chord shooting ('secant method')
if(c.dbg >= ERR_XTRA_DEBUG_6) {out.println("Korda: y0,y1,y2 = "+y0+", "+y1[ivar]+", "+y2[ivar]+", x="+x);}
w = y0 - y1[ivar];
w1 = x2[ivar] - x1[ivar];
x = x1[ivar] + w * w1 / (y2[ivar]-y1[ivar]);
if(c.dbg >= ERR_XTRA_DEBUG_6) {out.println(" x1,x2="+x1[ivar]+", "+x2[ivar]+", new x="+x);}
// --- Avoid rounding errors
if(Math.abs(1.-(xOld[ivar]/x)) < 1.e-12) {
if(c.dbg >= ERR_XTRA_DEBUG_6) {out.println(" ---- catchRoundingErrors["+ivar+"]="+(catchRoundingErrors[ivar]+1)+
", x="+x+" old x="+xOld[ivar]);}
if(catchRoundingErrors[ivar]==0) {
x = x + 1.e-8*Math.abs(x);
} else if(catchRoundingErrors[ivar]==1) {
x = x - 2.e-8*Math.abs(x);
}
if(catchRoundingErrors[ivar] < 3) { // catchRoundingErrors[] may be 0,1,2, or 3
catchRoundingErrors[ivar]++;
if(c.dbg >= ERR_XTRA_DEBUG_6) {out.println(" new x="+x);}
}
}
break;
} //karl = 4
default: { //this should not happen
out.println("!? Programming error in \"HaltaFall\"; karl[ivar]="+karl[ivar]);
karl[ivar]=1;
break;}
} //switch (lq)
xOld[ivar] = x;
if(c.dbg >=ERR_XTRA_DEBUG_6) {out.println("kille() returns, karl["+ivar+"]="+karl[ivar]+"; indik="+indik+"; x="+x);}
} // kille()
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="fasta">
//<editor-fold defaultstate="collapsed" desc="fasta()">
/**
* Finds out what solids are present in the system at equilibrium.
* Returns <b><code>indik</code><b><br>
* = 2 if a new set of solids is chosen<br>
* = 3 if ok (either no solids precipitate in the system, or no solubility
* products are exceeded and no solid assumed present has zero or negative
* concentration)<br>
* = 4 if too may solid phase combinations tested<br>
* = 1 if "tji" (all combinations of solids give unsoluble equations,
* i.e. negative determinants).
*/
private void fasta() {
// VARIABLES -----------------------------------------------
// nfall= nr of solids present at equilibrium
// nfspar= nr of solids indicated at FallProv
// nvaf= nr of mass balance equations to be solved in presence of solids
// singFall= true if the matrix "ruta" has come out singular
// nUt= nr of solids systematically eliminated at some stage while
// singFall is true.
// ber[ia]=true if lnA[ia] is calculated by means of the solubility product
// in procedure lnaBer
// fall[if]=true if the solid 'if' is assumed present at equilibrium
// falla[ia]=true if the component 'ia' is assumed to occur in one or more
// solids at equilibrium
// fut[i]= ifspar number of i'th solid to be eliminated at some stage in
// systematic variation during singFall= true
// ibe[m]= 'ia' number for m'th lnA[ia] to be calculated with the solubility
// product in procedure lnaBer (m=0 to nfall-1)
// iber[j]= j'th of 'iva' numbers to be an 'ibe' (ibe[j]=iva[iber[j]], (j=0 to
// nfall-1)
// ifall[m]= number of the m'th solid present at equilibrium (m=0 to nfall-1)
// ifspar[m]= number of the m'th solid indicated as possible a FallProv
// iva[m]= 'ia' number for m'th component to be tested in absence of solids
// (m=0 to nva)
// ivaf[m]='ia' number for m'th component to be tested in presence of solids
// (m=0 to nvaf)
// ---------------------------------------------------------
// Master routine for solid phase calculations. The routine cycles through
// chunks of code in the original FASTA routine, using the value of nextFall
// as switch. The meanings of nextFall on return to this routine
// are as follows:
// nextFall next routine line No. in original programme
// 0 Exit to PROV, 9000, 10000, 25000
// "indik" set ready
// 1 fallProv_InFall 14000
// 2 beFall 16000
// 3 anFall 24000
// 4 utFall 17000
// 5 sing 18000
// 6 fUtt 20000
// 7 hoppFut 21000
// 8 inFut 22000
// 9 uppNut 23000
nextFall = 1;
do {
if(panic) {break;}
switch (nextFall) {
case 1: {fallProv_InFall(); break;} // Tests for changes in the number of solids calculated with the given lnA[] values
case 2: {beFall(); break;} // Initialises iber[]
case 3: {anFall(); break;} // Calculates ibe[], ivaf[], rut1[][] and pva[][] arrays
case 4: {utFall(); break;} // Calculates ruta[][] and inverts the array
case 5: {sing_Hopsi(); break;}
case 6: {fUtt(); break;}
case 7: {hoppFut(); break;}
case 8: {inFut(); break;}
case 9: {uppNut(); break;}
} //switch nextFall
} while (nextFall > 0);
} // fasta()
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="fallProv_InFall()">
/**
* Tests for changes in the number of solids
* calculated with the given lnA[] values.
*/
private void fallProv_InFall() {
boolean bra, foundOne;
int nyfall, lj, lq, lf, lqa, ia, li, lia, lix, lif, liax, liaf;
double w;
double zMax; int kMax;
// ---------------------------------------------------------
// FALLPROV: Check that the solubility product is not exeeded
// for any solid phase assumed to be absent.
// Find ifall[] and fall[] for new solids appearing.
// ---------------------------------------------------------
if(c.dbg >= ERR_DEBUG_FASTA_4) {
out.println("--- Fasta() in at FallProv; nfall="+nfall);
//print ifall
printArraysFasta(true,false,false,false,false,false,false,false);
out.println("Testing that no additional solid is supersaturated and that the formal"+nl+
"concentration is not negative for any solid assumed to be present.");
}
bra = true; // "bra" means "good" or "ok" in Swedish
nyfall = 0;
// zMax and kMax are used with ONLY_ONE_SOLID_AT_A_TIME
// to find which of the supersaturated solids is to be included
// in the equilibrium system
zMax = -1.e+50; kMax = -1;
for(lif =0; lif < cs.mSol; lif++) {
liax = nIon + lif;
if(!fall[lif]) {
liaf = cs.nx + lif;
c.C[liax] =0.;
w =0.;
for(lia =0; lia < cs.Na; lia++) {w = w + cs.a[liaf][lia]*lnA[lia];}
lnA[liax] = w -lnKf[lif]; // lnA is now the (over)saturation index
if(w <= lnKf[lif] || cs.noll[liax] || nva == 0) {continue;}
// ---- Block added 2013-Jan.
// Solids may be oversaturated that can not be allowed to
// precipitate. For example:
// let us say C(s) is oversaturated at low redox potential,
// if HCO3- is the component and its total conc. is given,
// then C(s) may precipitate; but if CO2(g) is the component
// and the partial pressure of CO2(g) is given, then C(s)
// may NOT be present at equilibrium.
foundOne = false;
// loop through components for which the total conc. is given
for(lia =0; lia < nva; lia++) {
// is the stoichiometric coefficient non-zero?
if(Math.abs(cs.a[liaf][iva[lia]]) >0.00001) {foundOne = true; break;}
}
if(!foundOne) {continue;} // all coefficients zero?
// calculate the scaled oversaturation
w = lnA[liax]/fscal[lif];
if(w < tolFasta) {
if(c.dbg >= ERR_DEBUG_FASTA_4) {
out.println("FallProv solid nbr: "+lif+", lnA["+liax+"]="+(float)lnA[liax]+", scaling factor = "+fscal[lif]+", lnA/fscal = "+(float)w+nl+
" tolerance = "+(float)tolFasta+". Accepting the oversaturation of solid "+lif+" as zero within the tolerance...");
}
continue;
}
// ---- Block end
if(ONLY_ONE_SOLID_AT_A_TIME) {
if(w > zMax) {zMax = w; kMax = lif;}
} else {
bra = false;
fall[lif]= true;
nyfall++;
//java: changed ifall[nfall+nyfall] to ifall[nfall+nyfall-1]
ifall[nfall + nyfall -1] = lif;
}
} //if !fall[lif]
else {lnA[liax] = 0.;}
} //for lif
if(ONLY_ONE_SOLID_AT_A_TIME && kMax > -1) {
bra = false;
fall[kMax]= true;
nyfall = 1;
ifall[nfall] = kMax;
}
if(!bra && c.dbg >= ERR_DEBUG_FASTA_4) {
out.print("FallProv nyfall="+nyfall+", ");
if(ONLY_ONE_SOLID_AT_A_TIME) {out.println("new solid nbr. is: "+ifall[nfall]+", lnA["+(nIon+ifall[nfall])+"]="+lnA[((nIon+ifall[nfall]))]);}
else {printArraysFasta(true, false, false, false, false, false, false, false);} //print ifall[]
}
// ---- Block added 2018-March.
// When singFall is true, solids are removed one at a time until
// a set is found that gives a non-singular matrix ruta. When
// testing a reduced set of solids, if a new solid becomes
// supersaturated which was not in the list "ifspar", then the
// new solid is tested by setting singFall = false
if(ONLY_ONE_SOLID_AT_A_TIME && kMax > -1) {
singFallInterrupt: {
if(singFall) {
for(lif =0; lif < nfall; lif++) {if(ifSpar[lif] == kMax) {break singFallInterrupt;}}
if(c.dbg >= ERR_DEBUG_FASTA_4) {out.println("The new solid is not among the \"ifSpar\" list. Setting singFall=false.");}
singFall = false;
}
}
}
// ---- Block end
// for java:
if(nfall+nyfall >0 && nfall+nyfall < ifall.length) {
for(lif = nfall+nyfall; lif < ifall.length; lif++) {ifall[lif]=-1;}
}
if(nva == 0) {
if(c.dbg >=ERR_DEBUG_FASTA_4) {out.println("Fasta() returns (nva=0)");}
nextFall = 0;
return;
}
// Check that the quantity of solid is not negative for any solid
// assumed to be present
if(nfall > 0) {
for(li =0; li < nfall; li++) {
ia = ibe[li];
w = c.tot[ia] - c.C[ia];
for(lix =0; lix < cs.nx; lix++) {
liax = cs.Na + lix;
w = w - cs.a[lix][ia]*c.C[liax];
}
totBe[li] = w;
}
for(li =0; li < nfall; li++) {
w = 0.;
for(lj =0; lj < nfall; lj++) {w = w + ruta[li][lj] * totBe[lj];}
lq = ifall[li];
lqa = nIon + lq;
c.C[lqa] = w;
if(c.C[lqa] < 0) {
if(c.dbg >= ERR_DEBUG_FASTA_4) {
out.println("Fasta(): for solid "+lq+" the concentration is <0, c.C["+lqa+"]="+(float)w+", tolerance="+(float)tolFasta);
}
if(-c.C[lqa] > tolFasta) {
fall[lq] = false;
c.C[lqa] = 0.;
bra = false; // not "ok"
} else {
if(c.dbg >= ERR_DEBUG_FASTA_4) {
out.println(" accepting the concentration of solid "+lq+" as zero within the tolerance...");
}
}
}
}
} //if nfall >0
if(bra) { // if "ok"
indik =3;
if(c.dbg >= ERR_DEBUG_FASTA_4) {
out.println("HaltaFall.fasta() returns OK (to nog()); indik =3; nfall="+nfall+"; iterFasta="+iterFasta);
//print most arrays
printArraysFasta(true,true,true,true,true, false,false,false);
}
nextFall = 0;
return;
}
if(iterFasta > ITER_FASTA_MAX) {
indik =4;
c.errFlagsSet(4); // too many iterations trying to find the solids at equilibrium
if(c.dbg >=ERR_DEBUG_FASTA_4) {
out.println("Error in HaltaFall.fasta(): "+ITER_FASTA_MAX+
" different solid phase combinations"+nl+
"were tested and found NOT satisfactory (too many iterations).");
out.println("Fasta() returns (to nog()); indik =4; "+c.errFlagsToString());
}
nextFall = 0;
return;
}
iterFasta++;
// ---------------------------------------------------------
// INFALL: find new: nfall, ifall[nfall]
// ---------------------------------------------------------
// The lnA[] were not consistent with the solid phases.
// Either nyfall new solid phases appeared, or some solids assumed
// present had negative C[]. At first it is assumed at BEFALL that
// the first nfall of the iva[] are the ibe[] to be calculated.
// If the determinant of "ruta" is found to be zero at UTFALL,
// the ibe are changed systematically at SING-HOPPSI by means of
// array iber[], until a non-zero determinant is found.
// Then at ANFALL, the arrays rut1 and pva are calculated, and
// the new mass balance equations are solved at SLINGOR.
nfall = nfall + nyfall;
li = -1;
do {
li++;
if(fall[ifall[li]]) {continue;}
nfall--;
if(nfall != 0) {for(lj = li; lj < nfall; lj++) {ifall[lj] = ifall[lj+1];}}
li--;
} while (li < (nfall-1));
if(c.dbg >= ERR_DEBUG_FASTA_4) {
out.println("Fasta() at InFall; nfall="+nfall+", nyfall="+nyfall+
", nva="+nva+", singFall="+singFall);
//print ifall
printArraysFasta(true, false,false,false,false,false,false,false);
if(singFall) { //print ifSpar
printArraysFasta(false,false,false,false,false,false,true,false);
}
}
if(nfall <= 0) {
nextFall = 3; // no solid phases, goto ANFALL;
return;
}
//nfall >0
if(!singFall) {
for(li =0; li < nfall; li++) {ifSpar[li] = ifall[li];}
nfSpar = nfall;
nUt =0;
if(nfall > nva) {
nUt = nfall - nva -1;
if(c.dbg >= ERR_DEBUG_FASTA_4) {
out.println(" nfall (="+nfall+") is > nva (="+nva+")"+
" & !singFall"+nl+" nfSpar = "+nfSpar);
printArraysFasta(false,false,false,false,false,false,true,false);
out.println(" setting singFall=true");
}
singFall = true;
nextFall = 9; // goto UPPNUT;
return;
} //if nfall > nva
} else { //if singFall
if(nfall >= nva) {
if(c.dbg >= ERR_DEBUG_FASTA_4) {
out.println(" nfall (="+nfall+") is >= nva (="+nva+")"+
" & singFall = "+singFall+nl+
" nfSpar = "+nfSpar+" nUt = "+nUt);
}
nfall = nfSpar -nUt;
for(lf =0; lf < cs.mSol; lf++) { // ---- for(lf) added April-2013
fall[lf] = false;
for(li =0; li < nfSpar; li++) {
if(ifSpar[li] == lf) {fall[lf] =true; break;}
}
} // ---- for(lf) added April-2013
nextFall = 7; // goto HOPPFUT:
return;
}
}
nextFall = 2; // solids present: goto BEFALL then UTFALL
} // fallProv()
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="beFall()">
/**
* Initialises iber[].
*/
private void beFall() {
int li;
if(c.dbg >= ERR_DEBUG_FASTA_4) {
out.println("Fasta() at BeFall, nfall="+nfall);
//print array "ifall"
//printArraysFasta(true,false,false,false,false,false,false,false);
}
for(li =0; li < nfall; li++) {iber[li]=li;}
iber[nfall] = -1; //java: changed from iber[nfall+1]=0
nextFall = 4; // goto UTFALL
} // beFall()
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="anFall()">
/**
* Calculates ibe[], ivaf[], rut1[][] and pva[][] arrays.
*/
private void anFall() {
int lia, li, liaf, lix, lj, lm, lq, lz;
double w;
// ---------------------------------------------------------
// ANFALL:
// A set of nfall solids has been found with a non-zero determinant
// for the array "ruta". Some variables are changed, and the arrays
// rut1 and pva are calculated.
if(c.dbg >= ERR_DEBUG_FASTA_4) {
out.println("Fasta() at Anfall; nfall="+nfall);
}
for(lia =0; lia < cs.Na; lia++) {falla[lia]=false; ber[lia]=false;}
if(nfall > 0) {
//Get falla[], ber[] and ibe[] (from ifall and fall)
for(li = 0; li < nfall; li++) {
liaf = cs.nx + ifall[li];
if(fall[ifall[li]]) {
for(lia =0; lia < cs.Na; lia++) {
if(cs.a[liaf][lia] != 0) {falla[lia]=true;}}
}
ibe[li] = iva[iber[li]];
ber[ibe[li]] = true;
} //for li
// set up ivaf[]
nvaf = 0;
if(nva > 0) {
// Find nvaf and ivaf[]
for(li =0; li < nva; li++) {
lia = iva[li];
if(ber[lia]) {continue;}
nvaf++;
ivaf[nvaf-1] = lia; //java
}
if(c.dbg >= ERR_DEBUG_FASTA_4) {
out.println(" nvaf="+nvaf);
//print arrays "ber" and "ivaf"
printArraysFasta(false,false,false,false,true,true,false,false);
}
// Calculate rut1[][]
if(nvaf > 0) {
for(li =0; li < nvaf; li++) {
for(lj =0; lj < nfall; lj++) {
w = 0.;
for(lm =0; lm < nfall; lm++) {
lq = ivaf[li];
lz = cs.nx + ifall[lm];
w = w + cs.a[lz][lq]*ruta[lm][lj];
} //for lm
rut1[li][lj] = w;
} //for lj
} //for li
// Calculate pva[ia][ix]
for(li =0; li < nvaf; li++) {
for(lix =0; lix < cs.nx; lix++) {
lia = ivaf[li];
w = cs.a[lix][lia];
if(nfall > 0) {
for(lm =0; lm < nfall; lm++) {
lq = ibe[lm];
w = w - cs.a[lix][lq]*rut1[li][lm];
} //for lm
} //if nfall >0
pva[lia][lix] = w;
} //for lix
} //for li
} //if nvaf >0
} //if nva >0
} //if nfall >0
//SLINGOR(IN)
indik = 2;
if(c.dbg >= ERR_DEBUG_FASTA_4) {
out.println("HaltaFall.fasta() returns to Slingor(In); indik =2, nfall="+nfall+"; iterFasta="+iterFasta);
//print most arrays
printArraysFasta(true,true,true,true,true, false,false,false);
}
nextFall = 0; // exit to Slingor
} // anFall()
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="utFall()">
/**
* Calculates ruta[][] and inverts the array.
*/
private void utFall() {
//Calculate "ruta[][]" and check that it is not singular
int ia, li, lj, lf;
if(c.dbg >= ERR_DEBUG_FASTA_4) {
out.println("Fasta() at UtFall, nfall="+nfall);
// print array "ifall" and "iber"
printArraysFasta(true, true, false,false,false,false,false,false);
}
for(li =0; li < nfall; li++) {
ia = iva[iber[li]];
for(lj =0; lj < nfall; lj++) {
lf = cs.nx + ifall[lj];
ruta[li][lj] = cs.a[lf][ia];
} //for lj
} //for li
invert(ruta, nfall); // sets indik =0 (ok) or =1 (matrix singular)
if(indik == 1) {
nextFall = 5; //matrix singular, goto SING:
} else {
nextFall = 3; //matrix inverted, goto ANFALL:
}
} // utFall()
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="sing()">
/** Deals with the case of singular ruta[]. */
private void sing_Hopsi() {
// the matrix ruta[][] was singular
// --------
// SING:
// --------
if(c.dbg >= ERR_DEBUG_FASTA_4) {out.println("Fasta() at Sing-HoppSi");}
// --------
// HOPPSI:
// --------
// Bump up iber[] indices one at a time to give all combinations of nfall
// "be" components from the set of nva
if(hopp(iber,nva)) {
// all iber[] sets used up: move to FUTT to remove a solid phase
if(c.dbg >= ERR_DEBUG_FASTA_4) {
out.println(" ruta[][] was singular for all possible iber[] "+
"combinations; setting singFall = true");
}
singFall = true;
// note that nfspar and ifspar[] are already set at INFALL
nextFall = 6; // FUTT
} else {
// move to UTFALL to try the new iber[] set
nextFall = 4; // UTFALL
}
if(c.dbg >= ERR_DEBUG_FASTA_4) {out.println(" Sing-HoppSi returns");}
} // sing()
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="fUtt()">
/** Routine to handle systematic removal of solid phases in cases where no
* consistent set can be found. */
private void fUtt() {
// ---------------------------------------------------------
// FUTT:
// ---------------------------------------------------------
// iber[] sets are exausted. Either:
// - It has been proved inpossible to pick out a group of nfall
// components iber[] such that the array "ruta" has a non zero
// determinant,
// - Or more solids are indicated than there are logA[] values
// to vary (nfall > nva).
// One must try systematically combinations of a smaller number
// (nfall-nUt) of solid phases, until a non-zero determinant for
// "ruta" is found. This is done at labels FUTT, INFUT and UPPNUT
// using the array fut[]. To avoid going into a loop, the program
// sets singFall=true and remembers the first set of solids
// (ifspar[nfspar]) which gave only zero determinants.
// ---------------------------------------------------------
// Changes by I.Puigdomenech in 2011-Jan.:
// Curiously, the FUTT-HOPPFUT-INFUT-UPPNUT system published in 1967
// does not work when nfSpar=1, because setting nUt=1 means that all
// solids (i.e. the only one) are "striked out".
// The changes are at UPPNUT and at INFUT.
// ---------------------------------------------------------
if(c.dbg >= ERR_DEBUG_FASTA_4) {
out.println("Fasta() at Futt; nUt="+nUt+
", nfall="+nfall+", nfspar="+nfSpar);
//print arrays "ifspar" and "fut"
printArraysFasta(false,false,false,false,false,false, true, true);
}
if(nUt == 0) {
nextFall = 9; // goto UPPNUT:
} else {
nextFall = 7; // goto HOPPFUT:
}
} // fUtt()
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="hoppFut()">
/**
* Selects a new fut[].
*/
private void hoppFut() {
boolean hoppKlart;
// ---------
// HOPPFUT:
// ---------
// if nUt >0 call HOPP to pick a new fut[] array,
// if all used, then increment nUt at UPPNUT;
// else goto INFUT, BEFALL, UTFALL, ANFALL, and back to Slingor
if(c.dbg >= ERR_DEBUG_FASTA_4) {out.println("Fasta() at HoppFut");}
hoppKlart = hopp(fut,nfSpar);
if(c.dbg >= ERR_DEBUG_FASTA_4) {//print array "fut"
printArraysFasta(false,false,false,false,false,false,false, true);
}
if(hoppKlart) {
nextFall = 9; // goto UPPNUT
} else {
nextFall = 8; // goto INFUT:
}
} // hoppFut()
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="inFut()">
/**
* Select new fall[] and ifall[] for the reduced group of solids.
*/
private void inFut() {
int j, li;
// ---------
// INFUT:
// ---------
// find new fall[] and ifall[] for the reduced group of solids
if(c.dbg >= ERR_DEBUG_FASTA_4) {
out.println("Fasta() at InFut; nfall="+nfall+
", nfSpar="+nfSpar+", nUt="+nUt);
//print array "fut"
printArraysFasta(false,false,false,false,false,false,false, true);
}
for(li =0; li < nfSpar; li++) {fall[ifSpar[li]] = true;}
if(nUt > 0) {
for(li =0; li < nUt; li++) {fall[ifSpar[fut[li]]] = false;}
}
if(nfSpar > 1) { // ---- line added 2011-Jan.
j = -1; //java
for(li =0; li < nfSpar; li++) {
if(fall[ifSpar[li]]) {
j++;
ifall[j] = ifSpar[li];
}
} //for li
nfall = j+1; // ---- line added 2011-Jan.
} // if nfSpar > 1
// ---- next line added 2011-Jan.
else if(nfall==1 && nfSpar==1) {ifall[0] = ifall[1];}
if(c.dbg >= ERR_DEBUG_FASTA_4) {
out.println(" after InFut: nfall="+nfall);
//print arrays "ifall"
printArraysFasta(true, false, false, false,false,false,false,false);
} //if debug
if(nfall == 0) {
nextFall = 3; // goto ANFALL and then Slingor
} else {
nextFall = 2; // goto BEFALL, UTFALL, ANFALL, and back to Slingor
}
} // inFut()
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="uppNut()">
/**
* Increments nUt and sets initial fut[] values.
*/
private void uppNut() {
int li, lf, ia;
// ---------
// UPPNUT:
// ---------
// Increment nUt and set initial fut[] values for this nUt.
// Exit in confusion if nUt > nfSpar
nUt++;
nfall = nfSpar -nUt;
if(c.dbg >= ERR_DEBUG_FASTA_4) {
out.println("Fasta() at UppNut; nUt="+nUt+", nfSpar="+nfSpar+
", nfall="+nfall+"(=nfSpar-nUt)");
}
if(nfall > 0) {
for(li =0; li < nUt; li++) {fut[li] = li;}
fut[nUt] = -1; //java changed fut[nUt+1]=0 to fut[nUt] = -1
if(c.dbg >= ERR_DEBUG_FASTA_4) { //print array "fut"
printArraysFasta(false,false,false,false,false,false,false, true);
}
}
// ---- Block added 2011-Jan.
else if(nfall == 0 && nfSpar == 1) {
nfall = 1; fut[0] = 0; fut[1] = -1;
if(c.dbg >= ERR_DEBUG_FASTA_4) { //print array "fut"
printArraysFasta(false,false,false,false,false,false,false, true);
}
}
// ---- Block end
else {
// --------
// "TJI" (Tji is Romani (Gypsy) and means "not, nothing")
// --------
nfall = 0; nvaf = 0; // ---- line added 2013-Jan.
for(lf =0; lf < cs.mSol; lf++) {fall[lf] =false;}
for(ia =0; ia < cs.Na; ia++) {ber[ia] =false; falla[ia] =false;}
if(c.dbg >=ERR_ONLY_1) { // ---- error ----
out.println("Error in HaltaFall.fasta(): "+
"The "+nfSpar+
" solids found give only zero determinants (\"Tji\")."+
nl+"List of solids (array ifSpar):");
// print array "ifSpar"
printArraysFasta(false,false,false,false,false,false, true, false);
} // ---- error ----
indik = 1;
c.errFlagsSet(3); // failed to find a satisfactory combination of solids.
if(c.dbg >= ERR_DEBUG_FASTA_4) {
out.println("HaltaFall.fasta() returns at \"Tji\", indik =1, "+
c.errFlagsToString()+", nvaf = "+nvaf+", iterFasta="+iterFasta+nl+
"Failed to find a satisfactory combination of solids.");}
nextFall = 0;
return; // NYP (IN)
}
nextFall = 8; // goto INFUT;
} // uppNut()
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="hopp(lista,max)">
/**
* Moves to the next permutation of variables in the array list.
* @param lista array to move
* @param max
* @return false if a new permutation has been found;
* true if the last permutation has already been used
*/
private boolean hopp(int lista[], int max) {
int lj, i;
i = -1;
while(true) {
i++;
if(c.dbg >= ERR_XTRA_DEBUG_6) {out.println("Fasta() at Hopp, max="+max+", i="+i);}
if(lista[i] == max-1) {
return true;
} else {
if(lista[i+1] == lista[i]+1) {continue;}
lista[i] = lista[i] +1;
if(i > 0) {
for(lj=0; lj <= (i-1); lj++) {lista[lj] = lj;}
}
return false;
}
} //while
} // hopp(lista,max)
// </editor-fold>
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="invert">
/** Invert: Matrix inversion.<br>
* Adapted from "www.csee.umbc.edu/~squire/".<br>
* Sets variable indik = 1 (matrix is singular)
* otherwise indik = 0 (ok). */
private void invert(double a[][], int n) {
int row[] = new int[n];
int col[] = new int[n];
double temp[] = new double[n];
int hold , iPivot , jPivot;
double pivot;
if(c.dbg >= ERR_DEBUG_FASTA_4) {out.println("invert(ruta[][],"+n+") in");}
// set up row and column interchange vectors
for(int k=0; k<n; k++) {row[k] = k ; col[k] = k ;}
// begin main reduction loop
for(int k=0; k<n; k++) {
// find largest element for pivot
pivot = a[row[k]][col[k]] ;
iPivot = k;
jPivot = k;
for(int i=k; i<n; i++) {
for(int j=k; j<n; j++) {
if(Math.abs(a[row[i]][col[j]]) > Math.abs(pivot)) {
iPivot = i;
jPivot = j;
pivot = a[row[i]][col[j]];
}
}
}
if(Math.abs(pivot) < 1.0e-10) {
indik = 1;
if(c.dbg >= ERR_DEBUG_FASTA_4) {
out.println("invert() returns; indik =1 (matrix singular)");
}
return;
}
hold = row[k];
row[k]= row[iPivot];
row[iPivot] = hold ;
hold = col[k];
col[k]= col[jPivot];
col[jPivot] = hold ;
// reduce about pivot
a[row[k]][col[k]] = 1.0 / pivot ;
for(int j=0; j<n; j++) {
if(j != k) {a[row[k]][col[j]] = a[row[k]][col[j]] * a[row[k]][col[k]];}
}
// inner reduction loop
for(int i=0; i<n; i++) {
if(k != i) {
for(int j=0; j<n; j++) {
if(k != j) {
a[row[i]][col[j]] = a[row[i]][col[j]]
- a[row[i]][col[k]] * a[row[k]][col[j]];
}
}
a[row[i]][col [k]] = - a[row[i]][col[k]] * a[row[k]][col[k]];
}
}
}
// end main reduction loop
// unscramble rows
for(int j=0; j<n; j++) {
for(int i=0; i<n; i++) {temp[col[i]] = a[row[i]][j];}
for(int i=0; i<n; i++) {a[i][j] = temp[i];}
}
// unscramble columns
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {temp[row[j]] = a[i][col[j]];}
System.arraycopy(temp, 0, a[i], 0, n);
}
indik = 0;
if(c.dbg >= ERR_DEBUG_FASTA_4) {
out.println("invert() returns; indik ="+indik+" (ok)");
}
} // end invert
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="invert0">
/** Invert0: Matrix inversion */
/**
private void invert0(double a[][], int n) {
if(c.dbg >= ERR_DEBUG_FASTA_4) {out.println("invert0(a[][],"+n+") in");}
int[] iPivot = new int[n];
double[] pivot = new double[n];
int[][] indx = new int[n][2];
double swap, zmax, t;
int j, i, k, l, l1;
int row, column;
// Initialization
for(i = 0; i < n; i++) {iPivot[i] = 0;}
// Search for pivot element
column =-1;
row =-1;
for(i = 0; i < n; i++) {
zmax = 0.;
for(j = 0; j < n; j++) {
if(iPivot[j] == 1) {continue;}
for(k = 0; k < n; k++) {
if(iPivot[k] == 1) {continue;}
if(iPivot[k] > 1) {
indik = 1;
if(c.dbg >= ERR_DEBUG_FASTA_4) {out.println("invert0() returns; indik =1 (matrix singular)!");}
return;}
if(Math.abs(a[j][k]) > Math.abs(zmax)) {
row =j;
column =k;
zmax = a[j][k];
} //if
} //for k
} // for j
iPivot[column] = iPivot[column] +1;
// Interchange rows to put pivot element on diagonal
if(row != column) {
for(l = 0; l < n; l++) {
swap = a[row][l];
a[row][l] = a[column][l];
a[column][l] = swap;
} //for l
} //if row != column
indx[i][0] = row; indx[i][1] = column;
pivot[i] = a[column][column];
// Divide pivot row by pivot element
if(Math.abs(zmax) < 1.0E-10) {
indik =1;
if(c.dbg >= ERR_DEBUG_FASTA_4) {out.println("invert0() returns; indik =1 (matrix singular)");}
return;} //abs(zmax) =0
a[column][column] = 1;
for(l = 0; l < n; l++) {a[column][l] = a[column][l] / pivot[i];}
// Reduce non-pivot rows
for(l1 = 0; l1 < n; l1++) {
if(l1 == column) {continue;}
t = a[l1][column];
a[l1][column] = 0.;
for(l = 0; l < n; l++) {a[l1][l] = a[l1][l] - a[column][l] * t;}
} //for l1
} //for i
// Interchange columns
for(i =0; i < n; i++) {
//java: changed L=N+1-I to L=(N-1)-I
l = (n-1) - i;
//java: changed indx[][1] and [][2] to [][0] and [][1]
if(indx[l][0] == indx[l][1]) {continue;}
row = indx[l][0];
column = indx[l][1];
for(k =0; k < n; k++) {
swap = a[k][row];
a[k][row] = a[k][column];
a[k][column] = swap;
} //for k
} //for i
indik = 0;
if(c.dbg >= ERR_DEBUG_FASTA_4) {out.println("invert0() returns; indik ="+indik+" (ok)");}
} // invert0
*/
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="cBer">
/** CBER:
* 1.- Calculation of the activity of soluble complexes.
* 2.- Calculation of the concentrations of all soluble species
* with old values for activity coefficients.
* @param ivar
*/
private void cBer(int ivar) {
if(c.dbg >=ERR_XTRA_DEBUG_6) {out.println("cBer("+ivar+") in");}
// Calculate activities of soluble complexes
int lix, liax, lia;
double q;
for(lix =0; lix <cs.nx; lix++) {
liax = cs.Na +lix;
if(noCalc[ivar]) {
q = Math.abs(cs.a[lix][ivar]);
} else {
q = cs.a[lix][ivar];
}
lnA[liax] = lnBA[lix] + q * lnA[ivar];
} //for lix
// Calculate Concentrations:
// components and soluble complexes
double lnC;
for(lia =0; lia <nIon; lia++) {
c.C[lia] = 0.;
if(!cs.noll[lia]) {
lnC = lnA[lia] - lnG[lia];
if(lnC > 81.) {lnC = 81.;} //max concentration 1.5E+35
if(lnC > -103.) { // min concentration 1.8E-45
c.C[lia] = Math.exp(lnC);
}
} //if !noll
} //for i
if(c.dbg >=ERR_XTRA_DEBUG_6) {out.println("cBer() returns");}
} // cBer()
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="lnaBer1">
/**
* lnaBer - Part1
* Calculates lnKmi and lnA[ibe[]] when some solid phase is assumed to be present.
*/
private void lnaBer1() {
int li, iF, liaf, lia, lj, ia;
double w;
if(c.dbg >=ERR_XTRA_DEBUG_6) {out.println("lnaBer1() in, nfall="+nfall);}
// Calculate lnKmi
for(li = 0; li < nfall; li++) {
iF = ifall[li];
liaf = cs.nx + iF;
w = lnKf[iF];
for (lia = 0; lia <cs.Na; lia++) {
if(!ber[lia]) {w = w - cs.a[liaf][lia]*lnA[lia];}
} //for i
lnKmi[li] = w;
} //for li
// Calculate lnA[ibe[]]
for(li = 0; li < nfall; li++) {
w = 0.;
for(lj = 0; lj < nfall; lj++) {
w = w + lnKmi[lj] * ruta[lj][li];
} //for lj
ia = ibe[li];
lnA[ia] = w;
} //for li
if(c.dbg >=ERR_XTRA_DEBUG_6) {out.println("lnaBer1() returns");}
} // lnaBer1()
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="lnaBas">
/** LNABAS: calculates those parts of the activity of the soluble complexes
* that are independent of Lna(Ivar), (the Lna varied) and stores them in
* lnBA(ix). This method is called once every time the value of ivar is changed.
*
* @param ivar
* @return x
*/
private double lnaBas(int ivar) {
int lix; int li;
if(c.dbg >=ERR_XTRA_DEBUG_6) {out.println("lnaBas("+ivar+") in, lnA["+ivar+"] = "+lnA[ivar]);}
double w = lnA[ivar];
double q;
for(lix = 0; lix < cs.nx; lix++) {
lnBA[lix] = lnBeta[lix];
for(li = 0; li < cs.Na; li++) {
if(li != ivar) {
if(noCalc[li]) {q = Math.abs(cs.a[lix][li]);} else {q = cs.a[lix][li];}
lnBA[lix] = lnBA[lix] + q*lnA[li];
}
} //for li
} //for lix
if(c.dbg >=ERR_XTRA_DEBUG_6) {out.println("lnaBas() returns, x = "+w);}
return w;
} // lnaBas(ivar)
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="totBer">
/** TotBer (TotCalc): Calculates Y and compares it with Y0.
* Calculates the total concentration (Y) of a component given the free
* concentrations of all components (logA[]). The procedure is different
* if there are solid phases present or not.<br>
* Returns <b><code>indik</code>:</b><br>
* =1 not ok but it is a component only involved in
* mononuclear reactions and there are no solids present<br>
* =2 if ok (the Y is equal to Y0 within the tolerance)<br>
* =3 not ok and it is either not a mono component or there are solids present
* =4 if too many iterations (iter[ivar] larger than ITER_MAX+1) */
private void totBer() {
int lix, liax;
double w = 0.;
if(c.dbg >=ERR_XTRA_DEBUG_6) {out.println("totBer() in, ivar="+ivar+", indik="+indik);}
try { //catch too many iterations
y = c.C[ivar];
if(nfall > 0) { // Some solid is assumed to be present
for (lix =0; lix < cs.nx; lix++) {
liax = cs.Na + lix;
y = y + pva[ivar][lix] * c.C[liax];
} //for lix
y = y - totVA[ivar];
y0 = 0.;
w = Math.abs(y-y0);
if(tolY[ivar] >0 &&
Math.abs(totVA[ivar]) > 1. &&
w < Math.abs(tolY[ivar]*totVA[ivar])) {w = 0.;}
} //if nfall !=0
else { // No solid phase assumed to be present
for (lix =0; lix < cs.nx; lix++) {
liax = cs.Na + lix;
y = y + cs.a[lix][ivar] * c.C[liax];
} //for lix
y0 = c.tot[ivar];
w = Math.abs(y-y0);
} //if nfall >0
// Compare Y with Y0
if(tolY[ivar] < w) { // It was not OK
if(catchRoundingErrors[ivar] == 3) { //the solution can not be made better: it is uncertain
indik = 2; // ok
karl[ivar] = 1;
steg[ivar] = STEG0_CONT;
//iter[ivar] = 0;
if(c.dbg >=ERR_XTRA_DEBUG_6) {prnt(); out.println("totBer() returns; indik = 2 (ok), but \"rounding errors\"; iter["+ivar+"]="+iter[ivar]);}
return;
}
if(mono[ivar] && nfall == 0) { // mononuclear component
if(y0 <= 0. || y <= 0.) {
indik = 3;
iter[ivar]++;
if(iter[ivar] >= ITER_MAX) {throw new TooManyIterationsException();}
if(c.dbg >=ERR_XTRA_DEBUG_6) {prnt(); out.println("totBer() returns; indik =3 (not ok & not mono or solids); iter["+ivar+"]="+iter[ivar]);}
return;
}
lnA[ivar] = lnA[ivar] + Math.log(y0) - Math.log(y);
x = lnA[ivar];
indik = 1; // goto TJAT
iter[ivar]++;
if(iter[ivar] >= ITER_MAX) {throw new TooManyIterationsException();}
if(c.dbg >=ERR_XTRA_DEBUG_6) {prnt(); out.println("totBer() returns; indik =1 (not ok & mono & no solids), mono["+ivar+"]=true, iter["+ivar+"]="+iter[ivar]);}
//return;
} else { // !mono or nfall !=0
indik = 3;
iter[ivar]++;
if(iter[ivar] >= ITER_MAX) {throw new TooManyIterationsException();}
if(c.dbg >=ERR_XTRA_DEBUG_6) {prnt(); out.println("totBer() returns; indik =3 (not ok & not mono or solids); iter["+ivar+"]="+iter[ivar]);}
//return;
} //if !mono | nfall !=0
} else { // OK
indik = 2; // goto PROV
karl[ivar] = 1;
steg[ivar] = STEG0_CONT;
iter[ivar]++;
if(c.dbg >=ERR_XTRA_DEBUG_6) {prnt(); out.println("totBer() returns; indik =2 (ok); iter["+ivar+"]="+iter[ivar]);}
//return;
} //if OK
}
catch (TooManyIterationsException ex) {
if(c.dbg >=ERR_XTRA_DEBUG_6) {out.println("--- Too many iterations for ivar="+ivar);}
if(ivaBra[ivar] == -1) { // only print error message for the "outer" loop component
if(c.dbg >= ERR_DEBUG_FASTA_4) {printTooManyIterations(w);} //debug print-out
}
if(iter[ivar] > (ITER_MAX+1)) {
indik = 4; // break the iterations
karl[ivar] = 1;
if(!c.cont) {steg[ivar] = STEG0;} else {steg[ivar] = STEG0_CONT;}
}
if(c.dbg >=ERR_XTRA_DEBUG_6) {prnt(); out.println("totBer() returns; indik ="+indik+"; iter["+ivar+"]="+iter[ivar]+", too many iterations.");}
} //catch //catch
} // totBer()
private class TooManyIterationsException extends Exception {
public TooManyIterationsException() {}
public TooManyIterationsException(String txt) {super(txt);}
} //TooManyIterationsException
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="lnaBer2">
/** lnaBer - Part 2
* Calculate totVA when a solid phase is assumed to be present. */
private void lnaBer2() {
if(c.dbg >=ERR_XTRA_DEBUG_6) {out.println("lnaBer2() in, nfall="+nfall);}
int li, ia, lj;
double w;
double[] totMi = new double[MXA];
for (li=0; li < nfall; li++) {
ia = ibe[li];
totMi[li] = c.tot[ia] - c.C[ia];
} //for li
for (li=0; li < nvaf; li++) {
ia = ivaf[li];
w = c.tot[ia];
for (lj=0; lj < nfall; lj++) {
w = w - rut1[li][lj] * totMi[lj];
} //for lj
totVA[ia] = w;
} //for li
if(c.dbg >=ERR_XTRA_DEBUG_6) {out.println("lnaBer2() return");}
} // lnaBer2()
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="actCoeffs">
/** Calculates activity coefficients (array lnG[]).
* If the activity coefficients (which depend on the composition of the
* fluid) have changed since they were last calculated, then
* the equilibrium composition must be recalculated.
* @return false if the activity coefficients have changed since last
* call (not ok); true if the calculations have converged (ok).
*/
private boolean actCoeffs() {
/* Especially adapted to avoid some oscillatoty behaviour found in some
* concentrated aqueous solutions, like AlCl3, etc, where the activity
* coefficients and the aqueous composition are affecting each other in a
* strong way. The procedure does give slightly slower convergence for
* solutions of NaCl for example, but it seems more reliable to converge.
* However, ITERC_MAX must be sufficiently large (perhaps 100?).
*/
/* If one of the components is water (H2O), it complicates things:
* if H2O is consumed, for example through the precipitation of a
* hydrous solid, the mass of the fluid phase decreases and the
* concentrations must be increased accordingly.
*/
double diff, newDiff, absDiff, maxAbsDiff, f;
int i, iMaxDiff;
if(c.dbg >= ERR_DEBUG_ACT_COEF_5) {out.println("actCoeffs() in, iterAc = "+iterAc);}
boolean ok;
// --- get lnG[]= natural log of activity coefficient ---
try {factor.factor(c.C, lnG);}
catch (Exception ex) {
for(i =0; i <nIon; i++) {lnG[i]=0.;}
if(cs.jWater >= 0) {lnA[cs.jWater] = 0.;}
if(c.dbg >= ERR_DEBUG_ACT_COEF_5) {
out.println("actCoeffs() returns. Activity factor calculation failed.");
}
lib.common.MsgExceptn.showErrMsg(null, ex.getMessage(), 1);
return true;
}
if(cs.jWater >= 0) { //for H2O
lnA[cs.jWater] = lnG[cs.jWater];
//lnG[cs.jWater] = 0.;
}
// --- decide what tolerances in the lnG[] to use
double tolLnG = TOL_LNG, w;
for(i =0; i <nIon; i++) {
if(cs.namn.z[i] !=0 && !cs.noll[i]) {
tolLnG = Math.max(tolLnG, TOL_LNG*c.C[i]*cs.namn.z[i]);
}
}
tolLnG = Math.min(tolLnG,0.1);
c.tolLogF = (tolLnG / ln10);
//print C[], lnG and diff =lnG-oldLnG
if(c.dbg >= ERR_DEBUG_ACT_COEF_5) {printLnG(0);}
ok = true;
iMaxDiff = -1;
maxAbsDiff = -1;
for(i =0; i <nIon; i++) {
if(c.C[i] < tolFasta) {oldLnG[i] = lnG[i]; continue;}
diff = lnG[i] - oldLnG[i];
absDiff = Math.abs(diff);
if(absDiff > tolLnG) {
ok = false;
if(maxAbsDiff < absDiff) {iMaxDiff = i; maxAbsDiff = absDiff;}
// ---- instead of going ahead and use the new activity coefficients in
// a new iteration step, for species with "large" contribution to
// the ionic strength we do not apply the full change:
// it is scaled down to avoid oscillations
final double cLim=0.25, fL=0.50;
// f = fraction giving how much change in lnG should be applied
w = cs.chemConcs.C[i]*cs.namn.z[i]*cs.namn.z[i];
if(w > cLim) {
f = fL/(Math.sqrt(w));
// --- f is less than one
newDiff = diff * f;
if(c.dbg >= ERR_DEBUG_ACT_COEF_5) {
out.println("note, for \""+cs.namn.ident[i]+"\" C["+i+"] = "
+(float)cs.chemConcs.C[i]+" diff="+(float)diff
+" f="+(float)f+" applying lnG-change = "+(float)newDiff);
}
lnG[i] = oldLnG[i] + newDiff;
}
}
oldLnG[i] = lnG[i];
} //for i
if(c.dbg >= ERR_DEBUG_ACT_COEF_5) {
if(iterAc >0 && !ok) {out.println("New values:"); printLnG(1);}
if(maxAbsDiff > 0) {
out.println("Max abs(diff) for \""+cs.namn.ident[iMaxDiff]
+"\", abs(diff["+iMaxDiff+"])="+(float)maxAbsDiff);
}
}
iterAc++;
if(ok) { // some aqueous concentration(s) too large?
for(i =0; i <nIon; i++) {
if(c.C[i] >20) {
if(c.dbg >= ERR_DEBUG_ACT_COEF_5) {
out.println("note: C["+i+"]="+(float)c.C[i]+" >"+(int)Factor.MAX_CONC+" (too large)");}
c.errFlagsSet(5); // some aqueous concentration(s) are too large (>20): uncertain activity coefficients
break;
}
}
} else {
if(iterAc > ITERAC_MAX) {ok = true; c.errFlagsSet(6);} // activity factors did not converge
}
if(c.dbg >= ERR_DEBUG_FASTA_4) {
if(ok) {
if(c.isErrFlagsSet(6)) { // activity factors did not converge
out.print("--- actCoeffs() returns Ok after too many iterations");
} else {
out.print("--- actCoeffs() returns OK after "+iterAc+" iterations");
}
} else {
out.print("--- actCoeffs() returns NOT OK. Iter nbr."+iterAc);
}
out.println(", tol="+(float)c.tolLogF +", I="+(float)factor.ionicStr +", el.bal.="+(float)factor.electricBalance);
}
return ok;
} // actCoeffs()
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="print arrays, etc">
private void prnt() {
printArrays(false,true); //print lnA
out.println(" x="+x+", y="+y+", y0="+y0+", tolY["+ivar+"]="+(float)tolY[ivar]);
}
//<editor-fold defaultstate="collapsed" desc="printTooManyIterations">
private void printTooManyIterations(double w) {
int n0, nM, iPl, nP;
out.flush();
if(iter[ivar] >= ITER_MAX) {
out.println("Error: too many iterations with ivar = "+ivar);
out.println("Component nbrs. in the order they are iterated (starting with zero):");
printArrays(true, false); // print iva[]
n0 = 0;
nM = cs.Na-1;
iPl = 5; nP= nM-n0; if(nP >=0) {
out.print("tot[]= ");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %15.7g",c.tot[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
n0 = 0; //start index to print
nM = nIon + cs.mSol -1; //end index to print
iPl = 5; nP= nM-n0; if(nP >=0) { //items_Per_Line and itemsto print
out.print("C[]= ");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %15.7g",c.C[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
out.flush();
} //if iter[ivar] >= ITER_MAX
out.println("Component: "+ivar+", iteration: "+iter[ivar]);
printArrays(false, true); // print lnA[]
n0 = 0; //start index to print
nM = cs.Na -1; //end index to print
iPl = 5; nP= nM-n0; if(nP >=0) { //items_Per_Line and itemsto print
out.print(" ln f[]=");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %15.7g",lnG[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
if(nfall == 0) {
out.format(" Tot(calc) = %17.9g, Tot(input) = %17.9g, tolerance = %10.2g%n",y,y0,tolY[ivar]);
if(!mono[ivar]) {
out.format(e," low LnA= %23.16g, high LnA= %23.16g%n low Tot(calc)= %17.9g, high Tot(calc)= %17.9g%n",
x1[ivar],x2[ivar],y1[ivar],y2[ivar]);
} //if !mono
} //if nfall=0
else {
out.println("Nbr. solids: "+nfall+", error in tot.conc. = "+w+", tolerance ="+tolY[ivar]);
out.format(e," low LnA= %23.16g, high LnA= %23.16g%n"+
" low Tot(calc)= %17.9g, high Tot(calc)= %17.9g%n",
x1[ivar], x2[ivar], y1[ivar], y2[ivar] );
} //if nfall>0
out.flush();
} //printTooManyIterations()
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="printLnG">
/** print lnG[] and diff =lnG[]-oldLnG[]
* @param printDiffs controls printout:<br>
* =0 print C[] + lnG[] + diffs[] (=lnG[]-oldLnG[])<br>
* =1 print lnG[]<br>
* else print lnG[] + diffs[] (=lnG[]-oldLnG[])
*/
private void printLnG(final int printDiffs) {
int n0, nM, iPl, nP;
out.flush();
if(cs.jWater >= 0) {out.format(e,"lnA[H2O]= %10.6f%n",lnA[cs.jWater]);}
n0 = 0;
nM = nIon-1;
iPl = 7; nP= nM-n0; if(nP >=0) {
if(printDiffs == 0) {
out.print(" C[]=");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %10.2g",c.C[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
out.print("old lnG[]=");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %10.6f",oldLnG[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
out.print(" lnG[]=");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %10.6f",lnG[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
if(printDiffs == 1) {return;}
out.print("diffs[]=");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %10.6f",Math.abs(oldLnG[kjj]-lnG[kjj]));
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
out.println("tolerance (log10)= "+(float)(c.tolLogF)+", I = "+(float)factor.ionicStr+
", electric balance = "+(float)factor.electricBalance);
}
} //printLnG()
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="printArrays">
private void printArrays(boolean print_iva, boolean print_lnA) {
int n0, nM, iPl, nP;
out.flush();
if(print_iva) {
n0 = 0; //start index to print
nM = nva-1; //end index to print
iPl = 20; nP= nM-n0; if(nP >=0) { //items_Per_Line and itemsto print
out.print(" iva[]=");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %3d",iva[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
n0 = 0; //start index to print
nM = nva-1; //end index to print
iPl = 20; nP= nM-n0; if(nP >=0) { //items_Per_Line and itemsto print
out.print("ivaBra[]=");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %3d",ivaBra[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
n0 = 0; //start index to print
nM = nva-1; //end index to print
iPl = 20; nP= nM-n0; if(nP >=0) { //items_Per_Line and itemsto print
out.print("ivaNov[]=");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %3d",ivaNov[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
}
if(print_lnA) {
n0 = 0;
nM = cs.Na-1;
iPl = 7; nP= nM-n0; if(nP >=0) {
out.print(" lnA[]=");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %10.6f",lnA[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
}
out.flush();
} //printArrays()
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="printInput">
private void printInput() {
int n0, nM, iPl, nP;
out.flush();
out.println("--- HaltaFall - input data:");
cs.printChemSystem(out);
out.println("components: kh=");
n0 = 0; //start index to print
nM = cs.Na-1; //end index to print
iPl = 12; nP= nM-n0; if(nP >=0) { //items_Per_Line and itemsto print
out.print(" ");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %5d",c.kh[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
out.println("components: tot=");
n0 = 0; //start index to print
nM = cs.Na-1; //end index to print
iPl = 7; nP= nM-n0; if(nP >=0) { //items_Per_Line and itemsto print
out.print(" ");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %10.2g",c.tot[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
out.println("components: loga=");
n0 = 0; //start index to print
nM = cs.Na-1; //end index to print
iPl = 7; nP= nM-n0; if(nP >=0) { //items_Per_Line and itemsto print
out.print(" ");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %10.2f",c.logA[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
out.println("components: tol="+(float)c.tol);
out.println("--- HaltaFall - end of input data.");
out.flush();
} //printInput()
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="printArraysFasta()">
/** print arrays ifall, iber, fall, fallA, ber, ivaf, ifSpar, fut */
private void printArraysFasta(
boolean _ifall, boolean _iber, boolean _fall,
boolean _fallA, boolean _ber, boolean _ivaf,
boolean _ifSpar, boolean _fut) {
int n0, nM, iPl, nP;
out.flush();
if(_ifall) {
n0 = 0; //start index to print
nM = nfall-1; //end index to print
iPl = 20; nP= nM-n0; if(nP >=0) { //items_Per_Line and itemsto print
out.print(" ifall[]=");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %3d",ifall[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
}
if(_iber) {
n0 = 0;
nM = nfall-1;
iPl = 20; nP= nM-n0; if(nP >=0) {
out.print(" iber[]=");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %3d",iber[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
}
if(_fall) {
n0 = 0;
nM = cs.mSol-1;
iPl = 15; nP= nM-n0; if(nP >=0) {
out.print(" fall[]=");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %1b",fall[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
}
if(_fallA) {
n0 = 0;
nM = cs.Na-1;
iPl = 20; nP= nM-n0; if(nP >=0) {
out.print(" fallA[]=");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %1b",falla[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
}
if(_ber) {
n0 = 0;
nM = cs.Na-1;
iPl = 20; nP= nM-n0; if(nP >=0) {
out.print(" ber[]=");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %1b",ber[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
}
if(_ivaf) {
n0 = 0;
nM = nvaf-1;
iPl = 20; nP= nM-n0; if(nP >=0) {
out.print(" ivaf[]=");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %3d",ivaf[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
}
if(_ifSpar) {
n0 = 0;
nM = nfSpar-1;
iPl = 15; nP= nM-n0; if(nP >=0) {
out.print(" ifSpar[]=");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(" %4d",ifSpar[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
}
if(_fut) {
n0 = 0; //start index to print
nM = nUt-1; //end index to print
iPl = 15; nP= nM-n0; if(nP >=0) {//items_Per_Line and itemsto print
out.print(" fut[]=");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl +jjj);
out.format(" %4d",fut[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
}
out.flush();
} //printArraysFasta()
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="printMatrix(matrix,length) -- not used --">
/**
private void printMatrix(double matrix[][], int length) {
int n0, nM, iPl, nP;
out.flush();
for(int lf = 0; lf < length; lf++) {
n0 = 0; //start index to print
nM = length-1; //end index to print
iPl = 7; nP= nM-n0; if(nP >=0) { //items_Per_Line and itemsto print
out.print(" matrix["+lf+"][]=");
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(e," %10.3f",ruta[lf][kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for j
out.println(); out.print(" ");} //for ijj
}
}
out.flush();
} //printMatrix(matrix,length)
*/
// </editor-fold>
// </editor-fold>
// /** Throw a NullPointerException: <code>simulateErr(null);</code>
// * @param n must be "<code>null</code>" to throw an Exception */
// private static void throwErr(Integer n) {int a = n*2;}
// </editor-fold>
} | 121,192 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
Factor.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibChemDiagr/src/lib/kemi/haltaFall/Factor.java | package lib.kemi.haltaFall;
import lib.common.Util;
import lib.kemi.chem.Chem;
import lib.kemi.readDataLib.ReadDataLib;
/** A class to calculate single ion activity coefficients in aqueous solutions.
* The method "factor(double[] C, double[] lnf)" is to be called repeatedly by
* "HaltaFall": it should be as fast as possible. The calculation model is
* defined in <code>c.diag.activityCoeffsModel</code> when this class is
* instantiated.
* Three (3) models are implemented: Davies eqn., SIT, and simplified HKF.<br>
* The methods of this class may throw exceptions.<br>
* A value for the ionic strength, "I", is needed as input (stored in
* <code>chem.Chem.Diagr.ionicStrength</code>):
* <ul>
* <li>if I>0 then the activity coefficients are calculated and stored.
* For models that only depend on ionic strength (Davies and HKF) on subsequent
* calls to "factor" the activity coefficients are not calculated if the
* ionic strength has not changed.</li>
* <li>if I=0 (or if I = NaN, that is, not a number = undefined)
* then all activity coefficients = 1.</li>
* <li>if I<0 then the ionic strength is calculated at each time for
* an electrically neutral aqueous solution.</li>
* </ul>
* If an instance of this class, <code>Factor</code>, is constructed without
* providing a pointer to an instance of <code>chem.Chem.Diagr</code>, then
* an ideal aqueous solution (I=0) is used.<br>
*
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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 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/
*
* @author Ignasi Puigdomenech */
public class Factor {
/** The osmotic coefficient of water, calculated in this class.
* @see lib.kemi.chem.Chem.ChemSystem#jWater Chem.ChemSystem.jWater
* @see lib.kemi.haltaFall.Factor#log10aH2O haltaFall.Factor.log10aH2O */
public double osmoticCoeff = Double.NaN;
/** The log10 of the activity of water, calculated in this class.
* @see lib.kemi.chem.Chem.ChemSystem#jWater Chem.ChemSystem.jWater
* @see lib.kemi.haltaFall.Factor#osmoticCoeff haltaFall.Factor.osmoticCoeff */
public double log10aH2O = Double.NaN;
/** The electrical balance of the aqueous solutions:
* the sum of cationic charges plus sum of anionic charges. Calculated in
* <code>Factor</code> from the concns. and the charge of each species. */
public double electricBalance = Double.NaN;
/** Debye-Hückel parameter */
public double Agamma = Double.NaN;
/** the extended Debye-Hückel parameter in the HKF model */
public double bgi = 0;
/** Debye-Hückel parameter including the size parameter (=Bgamma x å) */
public double rB = 0;
//<editor-fold defaultstate="collapsed" desc="private fields">
// ------------------------
// ---- private data: ----
/** the "first time" some checks are made, and it is decided which species
* require activity coefficients, for example, gases are excluded */
private boolean begin = true;
/** If any of the SIT files contains as a first line "NoDefaults" then
* this variable will be <code>false</code> and default values for
* SIT coefficients will be zero. Otherwise it will be <code>true</code>
* and non-zero default values will be used for the SIT coefficients */
private boolean setDefaultValues = true;
/** true if a reference to a chem.Chem instance is not available */
private boolean dataNotSupplied = true;
/** where messages will be printed. It may be "System.out" */
private java.io.PrintStream out;
private Chem c;
private Chem.ChemSystem cs;
/** Object of a class with input temperature and ionic strength */
private Chem.Diagr diag;
/** Object of a class containing the array "z" with electric charges */
private Chem.ChemSystem.NamesEtc namn;
private SITeps eps; // class with ion interaction coefficients
/** directories to search for the SIT-file */
private String[] pathToSITdataFile = new String[3];
private final String SIT_FILE = "SIT-coefficients.dta";
/** nIon = Na + Nx (nbr of "ions" = number of components
* + number of soluble products) */
private int nIon = -1;
/** For each species: true if this species is either gas, liquid or solid, or
* if noll[] = true. Then the activity coefficient does not need to be
* calculated. False otherwise. */
private boolean[] gas;
/** the temperature given by the user the last time this procedure was executed
* @see lib.kemi.chem.Chem.Diagr#temperature Chem.Diagr.temperature */
private double lastTemperature = Float.MAX_VALUE;
/** the pressure given by the user the last time this procedure was executed
* @see lib.kemi.chem.Chem.Diagr#pressure Chem.Diagr.pressure */
private double lastPressure = Float.MAX_VALUE;
/** the ionic strength given by the user the last time this procedure was executed
* @see lib.kemi.haltaFall.Factor#ionicStr haltaFall.Factor.ionicStr
* @see lib.kemi.chem.Chem.Diagr#ionicStrength Chem.Diagr.ionicStrength */
private double lastIonicStr = 0;
/** The ionic strength, either provided by the user
* in <code>diag.ionicStrength</code>, or calculated
* (if <code>diag.ionicStrength</code> is negative).
* @see lib.kemi.chem.Chem.Diagr#ionicStrength Chem.Diagr.ionicStrength */
public double ionicStr = Double.NaN;
/** the square root of the ionic strength */
private double rootI = 0;
/** The dielectric constant of water */
private double eps_H2O = Double.NaN;
/** The density of water in units of g/cm3 */
private double rho = Double.NaN;
/** Debye-Hückel parameter */
private double Bgamma = Double.NaN;
/** the g-function in the HKF model, in units of Å */
private double g_function = 0;
/** the coefficient in Davies eqn. */
private final double DAVIES = 0.3;
/** sum of molalities of all species in the aqueous solution */
private double sumM;
private double sumPrd;
private double phiDH;
/** = 55.508 = 1000/(15.9994+2*1.00794) */
private static final double molH2Oin1kg = 1000/(15.9994+2*1.00794);
/** ln(10)= 2.302585092994046 */
private static final double ln10 = 2.302585092994046;
/** The cut-off abs value for a log10 of the activity coefficients: MAX_LOG_G = 3 */
private static final double MAX_LOG_G = 3; // = 6.90776 in ln-units
/** The cut-off abs value for log10aH2O: MAX_LOGAH2O = 3.999 */
private static final double MAX_LOGAH2O = 3.999; // = 9.21 in ln-units
/** The cut-off concentration when calculating the ionic strength etc
* to avoid "unreasonable" results: MAX_CONC = 20 */
public static final double MAX_CONC = 20;
private static final String dashLine="- - - - - - - - - - - - - - - - - - -";
private static final String nl = System.getProperty("line.separator");
private static final java.util.Locale engl = java.util.Locale.ENGLISH;
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="constructors">
/** A class to calculate single ion activity coefficients in aqueous solutions.
* Without arguments all activity coefficients are = 1.
* That is, the calculations will be done for an ideal aqueous solution */
public Factor() {out = System.out; dataNotSupplied = true;}
/** A class to calculate single ion activity coefficients in aqueous solutions.
* Activity coefficients will be calculated using the information stored in
* the <code>chem.Chem</code> instance.
* The calculation model is defined in: c.diag.activityCoeffsModel.
* @param c pointer to an object of storing the chemical data
* @throws IllegalArgumentException
* @see lib.kemi.chem.Chem.Diagr#activityCoeffsModel
* Chem.Diagr.activityCoeffsModel */
public Factor(Chem c) throws IllegalArgumentException {
out = System.out;
try{beginFactor(c, null, null, null);}
catch (Exception ex) {throw new IllegalArgumentException(ex.getMessage());}
}
/** A class to calculate single ion activity coefficients in aqueous solutions.
* Activity coefficients will be calculated using the information stored in
* the <code>chem.Chem</code> instance.
* The calculation model is defined in: c.diag.activityCoeffsModel.
* <br>
* <code>Path1</code>, <code>path2</code> and <code>path3</code> are
* directories where the SIT-file will be searched. The intention
* is that <code>path1</code> should be set to the path where the
* application is located, <code>path2</code> set to the user directory
* and <code>path3</code> set to the "current" directory. If the SIT-file
* is found in two or more of these paths, then the data in
* <code>path3</code> supersedes that of <code>path2</code>, etc.
* @param c pointer to an object storing the chemical data
* @param path1 a directory where a copy of the SIT-file is found.
* It may be null.
* @param path2 a directory where a copy of the SIT-file is found.
* It may be null.
* @param path3 a directory where a copy of the SIT-file is found.
* It may be null.
* @param out0 where messages will be printed. It may be
* <code>System.out</code>. If null, <code>System.out</code> is used
* @throws IllegalArgumentException
* @see lib.kemi.chem.Chem.Diagr#activityCoeffsModel
* Chem.Diagr.activityCoeffsModel */
public Factor(Chem c,
String path1, String path2, String path3,
java.io.PrintStream out0) throws IllegalArgumentException {
if(out0 != null) {this.out = out0;} else {this.out = System.out;}
try{beginFactor(c, path1, path2, path3);}
catch (Exception ex) {throw new IllegalArgumentException(ex.getMessage());}
}
//<editor-fold defaultstate="collapsed" desc="private beginFactor">
private void beginFactor(Chem c, String path1, String path2, String path3)
throws IllegalArgumentException {
if(c != null) {
dataNotSupplied = false;
// get the chemical system and concentrations
this.c = c;
//-----------------------------------------------------------
// factor uses the variables:
// cs.Na, cs.Nx, cs.jWater, cs.noll
// and when printing activity coefficients:
// cs.chemConcs.tolLogF
// cs.chemConcs.logA[]
// cs.chemConcs.logf[]
// cs.chemConcs.C[]
this.cs = c.chemSystem;
nIon = cs.Na + cs.nx;
gas = new boolean[nIon];
//-----------------------------------------------------------
// factor uses the variables: namn.z, namn.ident
this.namn = cs.namn;
//-----------------------------------------------------------
// factor uses the variables:
// diag.activityCoeffsModel, diag.ionicStrength,
// diag.tempererature, diag.pressure
this.diag = c.diag;
lastIonicStr = 0;
try{checks_and_start();}
catch (Exception ex) {
diag.activityCoeffsModel = -1;
diag.ionicStrength = Double.NaN; diag.ionicStrCalc = Double.NaN;
diag.phi = Double.NaN; diag.sumM = Double.NaN;
throw new IllegalArgumentException(ex.getMessage());
}
}
pathToSITdataFile[0] = path1;
pathToSITdataFile[1] = path2;
pathToSITdataFile[2] = path3;
}
/** Makes a few checks and calculates rho, eps_H2O, Agamma and g_function.
* @throws IllegalArgumentException
* @throws ArithmeticException */
private void checks_and_start() throws IllegalArgumentException, ArithmeticException {
if(dataNotSupplied || diag.activityCoeffsModel < 0) {
diag.activityCoeffsModel = -1;
diag.ionicStrength = Double.NaN; diag.ionicStrCalc = Double.NaN;
diag.phi = Double.NaN; diag.sumM = Double.NaN;
return;
}
//--- make some checks
if(nIon <=0) {
throw new IllegalArgumentException("\"haltaFall.Factor\": nIon="+nIon+" (must be >0)");
}
if(namn.z.length < nIon || namn.ident.length < nIon || cs.noll.length < nIon) {
throw new IllegalArgumentException(
"\"haltaFall.Factor\": z.length="+namn.z.length+" noll.length="+cs.noll.length+", both must be >="+nIon+" (nIon)");
}
// --- Find out which species need activity coeffs.
// those with gas[] = false
// gas[] = true if noll[]=true
// or if the name ends with either "(g)" or "(l)"
for(int i = 0; i < nIon; i++) {
gas[i] = false;
if(cs.noll[i]) {gas[i] = true; continue;}
if(namn.z[i] != 0) {continue;}
if(isGasOrLiquid(namn.ident[i])) {gas[i]=true;}
}
lastTemperature = diag.temperature;
lastPressure = diag.pressure;
try{rho = lib.kemi.H2O.IAPWSF95.rho(diag.temperature, diag.pressure);}
catch (Exception ex) {
throw new ArithmeticException("\"haltaFall.Factor\": "+ex.getMessage());
}
try{eps_H2O = lib.kemi.H2O.Dielectric.epsJN(diag.temperature, diag.pressure);}
catch (Exception ex) {eps_H2O = Double.NaN;}
if(Double.isNaN(eps_H2O)) {
try{eps_H2O = lib.kemi.H2O.Dielectric.eps(diag.temperature, diag.pressure);}
catch (Exception ex) {
throw new IllegalArgumentException("\"haltaFall.Factor\": "+ex.getMessage());
}
}
Agamma = lib.kemi.H2O.Dielectric.A_gamma(diag.temperature, rho, eps_H2O);
if(diag.activityCoeffsModel == 2) { // HKF model
try{g_function = lib.kemi.H2O.Dielectric.gHKF(diag.temperature,diag.pressure)*1.e+10;} // convert to Å
catch (Exception ex) {
throw new IllegalArgumentException("\"haltaFall.Factor\": "+ex.getMessage());
}
}
}
// </editor-fold>
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="factor">
/** Calculates the natural log of the activity coefficients for a given
* chemical system. This method is called repeatedly by class "HaltaFall":
* it should be as fast as possible. The calculation model is defined in
* <code>c.diag.activityCoeffsModel</code> when this class is instantiated.
* If c.diag.ionicStrength is < 0, then the ionic strength
* is calculated. <b>It is expected that the length of the arrays will not
* be changed between iterations.</b>
* @param C array with the concentration of each species (ions)
* @param lnf array where calculated values of the natural logs of the
* individual ion activity coefficients will be stored
* @see lib.kemi.chem.Chem.Diagr#activityCoeffsModel
* Chem.Diagr.activityCoeffsModel
* @throws IllegalArgumentException
* @throws lib.kemi.haltaFall.Factor.SITdataException */
public void factor(double[] C, double[] lnf)
throws IllegalArgumentException, ArithmeticException, SITdataException {
boolean tChanged, iChanged;
//-----------------------------------------------------------
// Define upper and lower bounds on the concentrations if concentrations far
// from the equilibrium values can cause exponents out of the range allowed
//-----------------------------------------------------------
//-----------------------------------------------------------
// --- make some tests about the parameters (arguments)
if(begin) { // the first time this procedure is run...
begin = false;
int nlnf = lnf.length;
if(nlnf <=0) {
diag.activityCoeffsModel = -1;
diag.ionicStrength = Double.NaN; diag.ionicStrCalc = Double.NaN;
diag.phi = Double.NaN; diag.sumM = Double.NaN;
throw new IllegalArgumentException("\"haltaFall.Factor\": lnf.length must be > 0");
}
if(C.length <=0) {
diag.activityCoeffsModel = -1;
diag.ionicStrength = Double.NaN; diag.ionicStrCalc = Double.NaN;
diag.phi = Double.NaN; diag.sumM = Double.NaN;
throw new IllegalArgumentException("\"haltaFall.Factor\": C.length="+C.length+" (must be >0)");
}
if(nlnf < nIon || C.length < nIon) {
diag.activityCoeffsModel = -1;
diag.ionicStrength = Double.NaN; diag.ionicStrCalc = Double.NaN;
diag.phi = Double.NaN; diag.sumM = Double.NaN;
throw new IllegalArgumentException( "\"haltaFall.Factor\": "+
"lnf.length="+nlnf+", C.length="+C.length+", must be >= "+nIon+" (= Na + Nx = "+cs.Na+" + "+cs.nx+")");
}
} //if begin
//-----------------------------------------------------------
// --- ideal solution
if(dataNotSupplied || diag.activityCoeffsModel < 0) {
diag.ionicStrength = Double.NaN; diag.ionicStrCalc = Double.NaN;
diag.phi = Double.NaN; diag.sumM = Double.NaN;
for(int i = 0; i < lnf.length; i++) {lnf[i] = 0;}
lastIonicStr = 0;
return;
}
//-----------------------------------------------------------
// To speed-up things, if the ionic strength and temperature-pressure do
// not change, and the model to calculate activity coefficients depends
// only on the ionic strength and (T,P) (i.e. Davies and HKF), then the
// activity coeffs are not recalculated.
//-----------------------------------------------------------
// Has the user changed the ionic strength for the calculation?
// (or is this the first time?)
if(Double.isNaN(diag.ionicStrength)) {iChanged = true; ionicStr = 0; sumM =0; electricBalance =0;}
else if(diag.ionicStrength ==0) {iChanged = (lastIonicStr ==0); ionicStr = 0; sumM =0; electricBalance =0;}
else if(diag.ionicStrength >0) {iChanged = (Math.abs(1-(lastIonicStr/diag.ionicStrength)) > 1e-3); ionicStr = Math.min(diag.ionicStrength,200);}
else {iChanged = true; ionicStr = -1;} // diag.ionicStrength < 0
tChanged = (Math.abs(lastTemperature - diag.temperature) > 0.1 ||
(Math.abs((lastPressure - diag.pressure)/diag.pressure)) > 0.001);
// find the temperature-dependent values of A-gamma
if(tChanged) {
lastTemperature = diag.temperature;
lastPressure = diag.pressure;
try{rho = lib.kemi.H2O.IAPWSF95.rho(diag.temperature, diag.pressure);}
catch (Exception ex) {
diag.activityCoeffsModel = -1;
diag.ionicStrength = Double.NaN; diag.ionicStrCalc = Double.NaN;
diag.phi = Double.NaN; diag.sumM = Double.NaN;
throw new ArithmeticException("\"haltaFall.Factor\": "+ex.getMessage());
}
try{eps_H2O = lib.kemi.H2O.Dielectric.epsJN(diag.temperature, diag.pressure);}
catch (Exception ex) {eps_H2O = Double.NaN;}
if(Double.isNaN(eps_H2O)) {
try{eps_H2O = lib.kemi.H2O.Dielectric.eps(diag.temperature, diag.pressure);}
catch (Exception ex) {
diag.activityCoeffsModel = -1;
diag.ionicStrength = Double.NaN; diag.ionicStrCalc = Double.NaN;
diag.phi = Double.NaN; diag.sumM = Double.NaN;
throw new IllegalArgumentException("\"haltaFall.Factor\": "+ex.getMessage());
}
}
Agamma = lib.kemi.H2O.Dielectric.A_gamma(diag.temperature, rho, eps_H2O);
}
// calculate: ionicStrength, electricBalance and sumM.
if(ionicStr < 0) {ionicStr = calcIonicStr(C,namn.z);}
// ionicStr should now be >=0
rootI = 0;
if(ionicStr > 0) {rootI = Math.sqrt(ionicStr);}
// ---- Calculate activity coefficients
if(diag.activityCoeffsModel == 0) { //Davies
if(tChanged || iChanged) {
try{calcDavies(lnf, namn.z);}
catch (Exception ex) {
diag.activityCoeffsModel = -1;
diag.ionicStrength = Double.NaN; diag.ionicStrCalc = Double.NaN;
diag.phi = Double.NaN; diag.sumM = Double.NaN;
throw new IllegalArgumentException("\"haltaFall.Factor\": "+ex.getMessage());
}
}
} //Davies
if(diag.activityCoeffsModel == 1) { //SIT
if(tChanged) {
Bgamma = lib.kemi.H2O.Dielectric.B_gamma(diag.temperature, rho, eps_H2O);
// this gives 1.5 at 25°C
rB = 4.56899 * Bgamma;
}
// With the SIT the activity coefficients may change even if the
// ionic strength does not change: they depend on the composition.
// Hence, the values of lnf[] will NOT be calculated correctly
// in "calcSIT" unless the values of C[] are correct!
try{calcSIT(C, lnf, namn.z);}
catch (Exception ex) {
diag.activityCoeffsModel = -1;
diag.ionicStrength = Double.NaN; diag.ionicStrCalc = Double.NaN;
diag.phi = Double.NaN; diag.sumM = Double.NaN;
throw new IllegalArgumentException("\"haltaFall.Factor\": "+ex.getMessage());
}
} //SIT
if(diag.activityCoeffsModel == 2) { //HKF
if(tChanged || iChanged) {
if(tChanged) {
g_function = 0;
try{
// use distance of closest approach for NaCl (HKF-4, Table 3)
// Shock et al., 1992 J. Chem. Soc., Faraday Trans., 88, 803–826. doi: 10.1039/FT9928800803
// Table 9(b) r_e(Cl-)=1.81, Table 9(a) r_e(Na+)=1.91 (=0.97+0.94)
// Eqs.(3)-(5) where kz = 0.94 for cations and zero for anions.
g_function = lib.kemi.H2O.Dielectric.gHKF(diag.temperature, diag.pressure)*1.e+10; // convert to Å
bgi = b_gamma_NaCl(diag.temperature, diag.pressure, eps_H2O, g_function);
} catch (Exception ex) {
diag.activityCoeffsModel = -1;
diag.ionicStrength = Double.NaN; diag.ionicStrCalc = Double.NaN;
diag.phi = Double.NaN; diag.sumM = Double.NaN;
throw new IllegalArgumentException("\"haltaFall.Factor\": "+ex.getMessage());
}
rB = lib.kemi.H2O.Dielectric.B_gamma(diag.temperature, rho, eps_H2O)
* ( (1.81+g_function) + (0.97 + (0.94+g_function)) );
}
calcHKF(lnf, namn.z);
}
} //HKF
lastIonicStr = ionicStr;
diag.ionicStrCalc = ionicStr;
//return;
} // factor
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="calcDavies">
private void calcDavies(double[] lnf, int[] z) {
if(ionicStr <=0) {return;}
// the number "1" assumed to be temperature independent
double w = - Agamma *((rootI/(1. + rootI)) -(DAVIES * ionicStr));
double logf; int zz;
for(int i = 0; i < lnf.length; i++) {
if(!gas[i]) {
if(z[i] != 0) {
zz = z[i]*z[i];
logf = zz * w;
logf = Math.max(-MAX_LOG_G*zz,Math.min(logf,MAX_LOG_G*zz));
lnf[i] = ln10 * logf;
} else {lnf[i] = 0;}
//lg_ACF(I)=lg_ACF(I) + LNW
} else {lnf[i] = 0;}
}
if(cs.jWater < 0) {return;}
// Debye-Huckel term for phi
phiDH = ((2d*ln10)/3d) * Agamma * ionicStr * rootI * sigma(rootI);
osmoticCoeff = 1;
if(sumM > 1e-15) {
osmoticCoeff =
1 - (phiDH/sumM)
+ (ln10 * Agamma * DAVIES * Math.pow(ionicStr,2))/sumM;
}
// Calculate Water Activity
log10aH2O =
Math.max(-MAX_LOGAH2O,
Math.min(MAX_LOGAH2O,
(-osmoticCoeff * sumM / (ln10* molH2Oin1kg)) ) );
lnf[cs.jWater] = ln10 * log10aH2O;
diag.phi = osmoticCoeff;
diag.sumM = sumM;
} //calcDavies
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="calcHKF">
/** <pre>Calculation of activity coefficients with:
* log f(i) = - (Aγ(T) Z(i)² √I)/(1 + r B(T) √I) + Γ + (bγ(T) I)
* where: Γ = -log(1+0.0180153 Σm).</pre>
* These eqns. are an approximation to the HKF model
* (Helgeson, Kirkham and Flowers),
* see Eqs.121,165-167,297,298 in: H.C.Helgeson, D.H.Kirkham and G.C.Flowers,
* Amer.Jour.Sci., 281 (1981) 1249-1516, Eqs.22 & 23 in: E.H.Oelkers and
* H.C.Helgeson, Geochim.Cosmochim.Acta, 54 (1990) 727-738, etc.
* @param lnf
* @param z
*/
private void calcHKF(double[] lnf, int[] z) {
if(ionicStr <= 0) {return;}
// note that "sumM" is not used in this verions of HKF
double w = -Agamma * (rootI/(1+(rB*rootI)));
double gamma = Math.log10(1+(0.0180153*ionicStr)); // sumM));
double logf; int zz;
for(int i = 0; i < lnf.length; i++) {
if(!gas[i]) {
logf = 0;
if(z[i] != 0) {
zz = z[i]*z[i];
logf = zz * w - gamma + bgi*ionicStr;
logf = Math.max(-MAX_LOG_G*zz,Math.min(logf,MAX_LOG_G*zz));
} //if z != 0
lnf[i] = ln10 * logf;
} else { lnf[i] = 0; }
}
if(cs.jWater < 0) {return;}
// Debye-Huckel term for phi
phiDH = ((2d*ln10)/3d) * Agamma * ionicStr * rootI * sigma(rB*rootI);
osmoticCoeff = 1;
if(ionicStr > 1e-15) { // sumM
osmoticCoeff =
(ln10 * gamma / (0.0180153*ionicStr)) // sumM))
- (phiDH/ionicStr) // sumM)
+ (ln10 * bgi * 0.5 * ionicStr);
}
// Calculate Water Activity
log10aH2O =
Math.max(-MAX_LOGAH2O,
Math.min(MAX_LOGAH2O, (-osmoticCoeff * ionicStr // sumM
/ (ln10* molH2Oin1kg)) ) );
lnf[cs.jWater] = ln10 * log10aH2O;
diag.phi = osmoticCoeff;
diag.sumM = sumM;
} //calcHKF
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="SIT">
//<editor-fold defaultstate="collapsed" desc="calcSIT">
/** Calculate single-ion activity coefficients using the SIT (Specific Ion
* Interaction model)
* @param C concentration of each species
* @param lnf the calculated natural logarithm of the
* single ion activity coefficient
* @param z the charge of each aqueous species
* @throws lib.kemi.haltaFall.Factor.SITdataException */
private void calcSIT(double[] C, double[] lnf, int[] z) throws SITdataException {
// --- Check if there is a need to get "epsilon" values
try {readSITdataFiles();}
catch (Exception ex) {
throw new SITdataException("\"haltaFall.Factor.calcSIT\": "+nl+ex.getMessage());
}
if(ionicStr <= 0) {return;}
double elBal = Math.abs(electricBalance);
float ε; //epsilon
double DH = -Agamma * rootI/(1. + (rB * rootI));
double sumEpsM, Ci, logf;
int zz;
// --- Calculate the individual ionic activity coefficients
// For neutral species this program uses ε(i,MX)*[M] + ε(i,MX)*[X]
// As a consequence:
// for a MX electrolyte: ε(i,M)*[MX] + ε(i,X)*[MX]
// for a M2X (or MX2) electrolyte: ε(i,M)*2*[M2X] + ε(i,X)*[M2X]
// (or ε(i,M)*[MX2] + ε(i,X)*2*[MX2])
// In the SIT-file you must enter ε = ε(i,MX)/2 (or ε = ε(i,M2X)/3)
for(int i = 0; i < nIon; i++) {
if(gas[i]) {lnf[i] = 0; continue;}
sumEpsM = 0;
if(z[i] ==0) {
ε = getEpsilon(i,i);
Ci = Math.max(0, Math.min(MAX_CONC, C[i]));
sumEpsM = ε * Ci;
} else if(elBal > 1e-10) {
ε = 0;
if(electricBalance < -1e-10) {ε = getEpsilon(nIon,i);}
else if(electricBalance > -1e-10) {ε = getEpsilon(nIon+1,i);}
sumEpsM = sumEpsM + ε * Math.max(0, Math.min(MAX_CONC, elBal));
}
for(int j=0; j<nIon; j++) {
if(j==i || z[i]*z[j] >0) {continue;}
ε = getEpsilon(i,j);
Ci = Math.max(0, Math.min(MAX_CONC, C[j]));
sumEpsM = sumEpsM + ε * Ci;
} //for j
zz = z[i]*z[i];
logf = zz*DH + sumEpsM;
// lg_ACF(I) = lg_ACF(I) + LNW
logf = Math.max(-MAX_LOG_G*zz, Math.min(logf,MAX_LOG_G*zz));
lnf[i] = ln10 * logf;
} //for i =0 to (nIon-1)
// --- Calculate Osmotic Coeff.
if(cs.jWater < 0) {return;}
osmoticCoeff = 1;
// Debye-Huckel term for phi
phiDH = ((2d*ln10)/3d) * Agamma * ionicStr*rootI * sigma(rB*rootI);
//Calculte the sum of ions and the sum of products of conc. times epsilon
double Cj;
sumPrd = 0;
double sumPrd_i;
// loop through cations and neutral species
for(int i = 0; i < nIon; i++) {
if(gas[i]) {continue;}
Ci = Math.max(0, Math.min(MAX_CONC, C[i]));
sumPrd_i = 0;
if(z[i] < 0) {continue;} // skip anions
// --- neutral species ---
if(z[i] == 0) {
for(int j = 0; j < nIon; j++) {
Cj = Math.max(0, Math.min(MAX_CONC, C[j]));
if(z[j]==0) {
ε = getEpsilon(i,i);
sumPrd_i = sumPrd_i + (ε * Ci * Cj)/2;
continue;
}
ε = getEpsilon(i,j);
sumPrd_i = sumPrd_i + ε * Ci * Cj;
} //for j=0 to (nIon-1)
if(elBal > 1e-10) {
ε = getEpsilon(i,nIon); //interaction with Na+ (elec.balance)
sumPrd_i = sumPrd_i + ε * Ci * elBal;
}
} else {
// --- cations ---
for(int j = 0; j < nIon; j++) {
if(i==j) {continue;}
if(z[j] < 0) {
Cj = Math.max(0, Math.min(MAX_CONC, C[j]));
ε = getEpsilon(i,j);
sumPrd_i = sumPrd_i + ε * Ci * Cj;
}
} //for j=0 to (nIon-1)
if(electricBalance > 1e-10) {
ε = getEpsilon(i,nIon+1); //interaction with Cl- (elec.balance)
sumPrd_i = sumPrd_i + ε * Ci * electricBalance;
}
} // --- cations
sumPrd = sumPrd + sumPrd_i;
} //for i=0 to (nIon-1)
// the remaining cation is Na+ "added" for electic balance
if(electricBalance < -1e-10) {
for(int i = 0; i < nIon; i++) {
if(z[i] >= 0 || gas[i]) {continue;}
ε = getEpsilon(i,nIon);
Ci = Math.max(0, Math.min(MAX_CONC, C[i]));
sumPrd = sumPrd - ε * electricBalance * Ci;
} //for i=0 to (nIon-1)
}
if(sumM > 1e-15) {
osmoticCoeff = 1 - (phiDH/sumM) + (ln10 * sumPrd)/sumM;
}
// Calculate Water Activity
log10aH2O =
Math.max(-MAX_LOGAH2O,
Math.min(MAX_LOGAH2O,
(-osmoticCoeff * sumM / (ln10* molH2Oin1kg)) ) );
lnf[cs.jWater] = ln10 * log10aH2O;
diag.phi = osmoticCoeff;
diag.sumM = sumM;
}
private double sigma(double x) {
if(x<0) {return Double.NaN;}
else if(x<1e-10) {return 1;}
else {return (3/Math.pow(x, 3)) * ((1+x) - 2*Math.log(1+x) - (1/(1+x)));}
} //sigma
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="readSITdata">
//<editor-fold defaultstate="collapsed" desc="readSITdataFiles">
/** The SIT-file(s) are read for user supplied epsilon values
* (SIT coefficients). Then default values for SIT ion interaction
* coefficients are set for empty (non-user supplied) values.
* @throws lib.kemi.haltaFall.Factor.SITdataException */
private void readSITdataFiles() throws SITdataException {
// create the arrays
if(eps == null) {
try{eps = new SITeps(nIon);}
catch (Exception ex) {
throw new SITdataException("Error in \"haltaFall.Factor.readSITdataFiles\" "+nl+ex.getMessage());
}
}
// --- If the arrays in c.eps are already initialised, skip the rest
if(!Float.isNaN(eps.eps0[0][0])) {return;}
String line = "- - - - - - - - -";
// --- Read the input files and
// get user-supplied specific ion interaction coefficients
// set all coefficients to "empty" values
for(int i = 0; i < nIon+2; i++) {
for(int j=0; j<(i+1); j++) {setEpsilon(i,j, Float.NaN, 0f, 0f);}
}
boolean someFile = false;
for(String pathToSITdataFile1 : pathToSITdataFile) {
if (pathToSITdataFile1 == null) {continue;}
// --- prepare the file for reading:
java.io.File pathToSITfile = new java.io.File(pathToSITdataFile1);
if(!pathToSITfile.exists() || !pathToSITfile.isDirectory()) {
out.println(nl+line+nl+"Error in \"haltaFall.Factor.readSITdataFile\":"+nl+
" path = \""+pathToSITfile.getPath()+"\""+nl+
" either does not exist or it is not a directory."+nl+line);
continue; // try to read next path
}
java.io.File SITdata = new java.io.File(pathToSITdataFile1
+ java.io.File.separator + SIT_FILE);
// create a ReadDataLib instance
ReadDataLib rd;
try {rd = new ReadDataLib(SITdata);}
catch (ReadDataLib.DataFileException ex) {
out.println("Note - SIT file NOT found: \""+SITdata+"\"");
continue; // try to read next path: read next SIT-file if any
}
someFile = true;
out.println("Reading SIT data from \""+SITdata+"\"");
// --- Search the SIT-file
// (compare names such as "Fe+2" and "Fe 2+")
try {readSITfileSection(1,rd);}
catch (ReadDataLib.DataEofException | ReadDataLib.DataReadException ex) {throw new SITdataException(ex.getMessage());}
catch (SITdataException ex) {
throw new SITdataException(ex.getMessage()+nl+"reading file \""+SITdata+"\".");
}
// --- Search the SIT-file for epsilon-values for neutral species with MX
// (compare names with and without "(aq)", etc)
try {readSITfileSection(2,rd);}
catch (ReadDataLib.DataEofException | ReadDataLib.DataReadException ex) {throw new SITdataException(ex.getMessage());}
catch (SITdataException ex) {
throw new SITdataException(ex.getMessage()+nl+"reading file \""+SITdata+"\".");
}
// --- Search the SIT-file for epsilon-values for neutral species with
// themselves or other neutral species
// (compare names with and without "(aq)", etc)
try {readSITfileSection(3,rd);}
catch (ReadDataLib.DataEofException | ReadDataLib.DataReadException ex) {throw new SITdataException(ex.getMessage());}
catch (SITdataException ex) {
throw new SITdataException(ex.getMessage()+nl+"reading file \""+SITdata+"\".");
}
// --- The End
try{rd.close();}
catch (Exception ex) {}
} //for i=0 to <pathToSITdataFile.length
if(!someFile) {
throw new SITdataException("SIT model for activity coefficients requested,"+nl+
" but no SIT data file found.");
} else {out.println("Finished reading SIT data.");}
// --- Set Default values for the specific ion interaction coefficients:
// Because epsilon values are symmetric (eps(M,X) = eps(X,M)) only
// half of the values need to be assigned
if(!setDefaultValues) {
out.println("Setting \"empty\" SIT-coefficients to zero"
+" (default SIT-coefficients NOT used).");
// Set all "empty" coefficients to zero
for(int i = 0; i < nIon+2; i++) {
for(int j=0; j<=i; j++) {
if(Float.isNaN(getEpsilon(i,j))) {setEpsilon(i,j, 0f, 0f, 0f);}
}
}
return;
}
out.println("Setting \"empty\" SIT-coefficients to default values.");
float w; int k;
//Set the default values according to Hummel (2009) for interactions with
// ClO4, Cl- and Na+
//For eps(Na+,Cl-) and eps(Na+,ClO4-) the default values for Cl- and ClO4-
// are used (instead of the default for Na+)
final String identClO4 = "ClO4";
final String identCl = "Cl";
final String identNa = "Na";
String species1, species2;
boolean ClO41, Cl1, Na1, ClO42, Cl2, Na2;
for(int i = 0; i < nIon+2; i++) {
if(i < nIon && gas[i]) {continue;}
if(i<nIon) {
species1 = Util.nameOf(namn.ident[i]);
if(species1.equals(identClO4) && namn.z[i] == -1) {
ClO41 = true; Cl1 = false; Na1 = false;
}
else if(species1.equals(identCl) && namn.z[i] == -1) {
ClO41 = false; Cl1 = true; Na1 = false;
}
else if(species1.equals(identNa) && namn.z[i] == +1) {
ClO41 = false; Cl1 = false; Na1 = true;
}
else {ClO41= false; Cl1 = false; Na1 = false;}
}
else if(i==nIon) {
//species1 = "Na";
ClO41 = false; Cl1 = false; Na1 = true;
}
else if(i==nIon+1) {
//species1 = "Cl";
ClO41 = false; Cl1 = true; Na1 = false;
}
else {
//species1 = "(gas)";
ClO41 = false; Cl1 = false; Na1 = false;
}
for(int j=0; j<(i+1); j++) {
if(namn.z[i]*namn.z[j] >=0) {continue;}
if(j<nIon) {
species2 = Util.nameOf(namn.ident[j]);
if(species2.equals(identClO4) && namn.z[j] == -1) {
ClO42 = true; Cl2 = false; Na2 = false;
}
else if(species2.equals(identCl) && namn.z[j] == -1) {
ClO42 = false; Cl2 = true; Na2 = false;
}
else if(species2.equals(identNa) && namn.z[j] == +1) {
ClO42 = false; Cl2 = false; Na2 = true;
}
else {ClO42= false; Cl2 = false; Na2 = false;}
}
else if(j==nIon) {
//species2 = "Na";
ClO42 = false; Cl2 = false; Na2 = true;
}
else if(j==nIon+1) {
//species2 = "Cl";
ClO42 = false; Cl2 = true; Na2 = false;}
else {
// species2 = "?";
ClO42 = false; Cl2 = false; Na2 = false;
}
// note that if ClO41 is true, then ClO42 can not be true, etc
if(ClO41) {
if(Float.isNaN(getEpsilon(i,j))) {
setEpsilon(i,j, (0.2f * namn.z[j]),0f,0f);
}
} // ClO4-
else if(ClO42) {
if(Float.isNaN(getEpsilon(i,j))) {
setEpsilon(i,j, (0.2f * namn.z[i]),0f,0f);
}
} // ClO4-
else if(Cl1) {
if(Float.isNaN(getEpsilon(i,j))) {
setEpsilon(i,j, (0.1f * namn.z[j])-0.05f,0f,0f);
}
} // Cl-
else if(Cl2) {
if(Float.isNaN(getEpsilon(i,j))) {
setEpsilon(i,j, (0.1f * namn.z[i])-0.05f,0f,0f);
}
} // Cl-
else if(Na1) {
if(Float.isNaN(getEpsilon(i,j))) {
setEpsilon(i,j, (0.05f * namn.z[j]),0f,0f);
}
} // Na+
else if(Na2) {
if(Float.isNaN(getEpsilon(i,j))) {
setEpsilon(i,j, (0.05f * namn.z[i]), 0f, 0f);
}
} // Na+
// species2 = "?";
} //for j
} //for i
// other epsilon defaults
for(int i = 0; i < nIon+2; i++) {
// default values:
if((i < nIon && !gas[i]) || i >= nIon) {
for(int j=0; j<(i+1); j++) {
if(namn.z[i]*namn.z[j] <0) {
// default values: eps(M^+z, X^-y) = 0.15 + 0.15 (z + y)
if(namn.z[i]*namn.z[j] < -1
&& (namn.z[i] == +1 || namn.z[j] == +1)) {
// Z = +1 and Z < -1
if(namn.z[j]<0) {k = j;} else {k = i;}
w = 0.0500001f*namn.z[k];
}
else { // either Z=+1 and Z=-1 or Z > +1 and Z <= -1
if(namn.z[i]>0) {k = i;} else {k = j;}
w = -0.05000001f + 0.1f*namn.z[k];
}
if(Float.isNaN(getEpsilon(i,j))) {setEpsilon(i,j,w,0f,0f);}
}
} //for j
} //!gas
} //for i
// Set all remaining "empty" coefficients to zero
for(int i = 0; i < nIon+2; i++) {
for(int j=0; j<=i; j++) {
if(Float.isNaN(getEpsilon(i,j))) {setEpsilon(i,j, 0f, 0f, 0f);}
}
}
out.println("SIT-coefficients assigned.");
// return;
} //readSITdataFiles
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="readSITfileSection">
/** Read a section of the SIT file. The SIT file has three sections:
* 1) "normal" epsilon values; 2) epsilon values for neutral species with
* electrolytes; and 3) epsilon values for neutral species with neutral species
*
* @param section the section to read, 1, 2 or 3
* @param rd a reference to the class used for reading the SIT-file
* @throws lib.kemi.haltaFall.Factor.SITdataException
* @throws lib.kemi.readDataLib.ReadDataLib.ReadDataLib.DataReadException
* @throws lib.kemi.readDataLib.ReadDataLib.ReadDataLib.ReadDataLib.DataEofException */
private void readSITfileSection(int section, ReadDataLib rd)
throws SITdataException, ReadDataLib.DataReadException, ReadDataLib.DataEofException {
if(section < 1 || section > 3) {
throw new SITdataException("Error in \"haltaFall.Factor.readSITfileSection\": section = "
+section+" (must be 1,2 or 3).");
}
if(rd == null) {
throw new SITdataException(
"Error in \"haltaFall.Factor.readSITfileSection\":"
+" instance of ReadDataLib is \"null\"");
}
// --- Search the SIT-file
// (compare names such as "Fe+2" and "Fe 2+")
int zCat;
int zAn = 0;
float w0, w1, w2;
String identNa = "Na"; String identCl = "Cl";
String cation, identCation;
String anion ="", identAnion ="";
String identI;
boolean firstLine = true;
loopWhile:
while (true) {
//-- get the cation (or neutral species)
rd.nowReading = "Cation name";
if(section > 1) {rd.nowReading = "Neutral species name";}
cation = rd.readA();
if(cation.equalsIgnoreCase("NoDefaults") && firstLine) {
setDefaultValues = false;
continue; // loopWhile
}
firstLine = false;
if(cation.equalsIgnoreCase("END")) {break;} // loopWhile
zCat = Util.chargeOf(cation);
if(section < 2 && zCat<=0) {
throw new SITdataException(
"Error reading file \""+SIT_FILE+"\":"+nl+
" Trying to read a cation name, found: \""+cation+"\""+nl+
" but the charge is: "+zCat+" (must be >0)");
} else if(section >= 2 && zCat!=0) {
throw new SITdataException(
"Error reading file \""+SIT_FILE+"\":"+nl+
" Trying to read a neutral species name, found: \""+cation+"\""+nl+
" but the charge is: "+zCat+" (must be zero)");
}
//get name without charge, and without "(aq)", etc
identCation = Util.nameOf(cation);
if(section == 1) {
//-- get the anion
rd.nowReading = "Anion name";
anion = rd.readA();
zAn = Util.chargeOf(anion);
if(zAn>=0) {
throw new SITdataException(
"Error reading file \""+SIT_FILE+"\":"+nl+
" Trying to read an anion name, found: \""+anion+"\""+nl+
" but the charge is: "+zAn+" (must be <0)");
}
identAnion = Util.nameOf(anion);
}
//-- get three parameters for the interaction coefficient
// epsilon = eps0 + eps1 * T + eps2 * T*T (T = temperature in Kelvins)
if(section == 1) {
rd.nowReading = "SIT interaction coefficient eps0["+cation+","+anion+"]";
w0 = (float)rd.readR();
if(Math.abs(w0)>=10f) {
throw new SITdataException(
"Error reading file \""+SIT_FILE+"\":"+nl+
" Trying to read the SIT coefficient eps0["+cation+","+anion+"]"+nl+
" but the value is: "+w0+" (must be between <10 and >-10)");
}
rd.nowReading = "SIT interaction coefficient eps1["+cation+","+anion+"]";
w1 = (float)rd.readR();
rd.nowReading = "SIT interaction coefficient eps2["+cation+","+anion+"]";
w2 = (float)rd.readR();
//-- search the chemical system for this cation-anion couple
loopForI:
for(int i=0; i<nIon; i++) {
// if Z>0 and the cation is the same as that in the SIT-file
// Find out if the anion is also in the chemical system.
// If yes get epsilon(cation,anion)
// Find also: epsilon(cation,Cl-)
// if Z<0 and the cation is the same as that in the SIT-file
// find only: epsilon(Na+,anion)
if(gas[i]) {continue;}
identI = Util.nameOf(namn.ident[i]);
if(namn.z[i]<0) { // is this the anion in the SIT-file?
if(!identI.equalsIgnoreCase(identAnion)
|| namn.z[i] != zAn) {continue;}
if(!identCation.equalsIgnoreCase(identNa)
|| zCat != 1) {continue;}
//found anion and cation is Na+
setEpsilon(nIon, i, w0, w1, w2);
} else
{ //z[i]>0 is this the cation in the SIT-file?
if(!identI.equalsIgnoreCase(identCation)
|| namn.z[i] != zCat) {continue;}
// found the cation, check for Cl-
if(identAnion.equalsIgnoreCase(identCl) && zAn == -1) {
//found cation and anion is Cl-
setEpsilon(nIon+1, i, w0, w1, w2);
}
//found the cation, look in chemical system for all anions
String identI2;
for(int i2=0; i2<nIon; i2++) {
if(gas[i]) {continue;}
identI2 = Util.nameOf(namn.ident[i2]);
if(!identI2.equalsIgnoreCase(identAnion)
|| namn.z[i2] != zAn) {continue;}
// found both cation and anion, get value and quit search
setEpsilon(i, i2, w0, w1, w2);
break loopForI;
} //for i2
} //if z[i]>0
} //for i
// look for epsilon(Na+,Cl-)
if(identCation.equalsIgnoreCase(identNa) && zCat == 1 &&
identAnion.equalsIgnoreCase(identCl) && zAn == -1) {
setEpsilon(nIon, nIon+1, w0, w1, w2);
}
} //if(section == 1)
else
if(section == 2) {
rd.nowReading = "SIT interaction coefficient eps0["+cation+",MX]";
w0 = (float)rd.readR();
if(Math.abs(w0)>=10f) {
throw new SITdataException(
"Error reading file \""+SIT_FILE+"\":"+nl+
" When trying to read the SIT coefficient eps["+cation+",MX]"+nl+
" but the value is: "+w0+" (must be <10 and >-10)");
}
rd.nowReading = "SIT interaction coefficient eps1["+cation+",MX]";
w1 = (float)rd.readR();
rd.nowReading = "SIT interaction coefficient eps2["+cation+",MX]";
w2 = (float)rd.readR();
for(int i=0; i<nIon; i++) {
if(cs.noll[i] || namn.z[i] != 0) {continue;}
identI = Util.nameOf(namn.ident[i]);
if(!identI.equalsIgnoreCase(identCation)) {continue;}
// found the neutral species
for(int i2=0; i2<nIon; i2++) {
if(cs.noll[i2] || namn.z[i2] == 0) {continue;}
setEpsilon(i, i2, w0, w1, w2);
} //for i2
setEpsilon(i, nIon, w0, w1, w2);
setEpsilon(i, nIon+1, w0, w1, w2);
} //for i
} //if(section == 3)
else
if(section == 3) {
rd.nowReading = "SIT interaction coefficient eps["+cation+",neutral]";
w0 = (float)rd.readR();
if(Math.abs(w0)>=10f) {
throw new SITdataException(
"Error reading file \""+SIT_FILE+"\":"+nl+
" When trying to read the SIT coefficient eps["+cation+",neutral]"+nl+
" but the value is: "+w0+" (must be <10 and >-10)");
}
rd.nowReading = "SIT interaction coefficient eps1["+cation+",MX]";
w1 = (float)rd.readR();
rd.nowReading = "SIT interaction coefficient eps2["+cation+",MX]";
w2 = (float)rd.readR();
for(int i=0; i<nIon; i++) {
if(cs.noll[i] || namn.z[i] != 0) {continue;}
identI = Util.nameOf(namn.ident[i]);
if(!identI.equalsIgnoreCase(identCation)) {continue;}
setEpsilon(i, i, w0, w1, w2);
} //for i
} //if(section == 4)
} //while
} //readSITfileSection
// </editor-fold>
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="printEpsilons">
/** Prints a table with the epsilon values
* @param out0 where the table will be printed. It may be
* <code>System.out</code>. If null, <code>System.out</code> is used.
*/
private void printEpsilons(java.io.PrintStream out0) {
java.io.PrintStream o;
if(out0 != null) {o = out0;} else {o = System.out;}
o.println("List of \"epsilon\" values:");
// --- print a title line with names
o.print(" ");
for(int i = 0; i < nIon; i++) {
if(namn.ident[i].length() <=10) {o.format("%-10s",namn.ident[i]);}
else {o.format("%-10s",namn.ident[i].substring(0,10));}
} //for i
o.format("%-10s%-10s%s","Na+","Cl-",nl);
// --- table body:
for(int i = 0; i < nIon+2; i++) {
if(i<nIon) {
if(namn.ident[i].length() <=10) {o.format("%-10s",namn.ident[i]);}
else {o.format("%-10s",namn.ident[i].substring(0,10));}
}
else if(i==nIon) {o.format("%-10s","Na+");}
else if(i==(nIon+1)) {o.format("%-10s","Cl-");}
for(int j=0; j <= i ; j++) {
o.format(engl, " %6.3f ", getEpsilon(i,j));
} //for j
o.println();
} //for i
o.println(
"Note that eps[i,j]=eps[j,i], and esp[i,j]=0 if z[i]*z[j]>0"+nl+
"(equal charge sign), and eps[i,i] is used only if z[i]=0."+nl+
"The last two rows/columns, Na+ and Cl-, are used only"+nl+
"if the aqueous solution is not electrically neutral.");
} //printEpsilons()
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="getEpsilon">
/** Retrieves a value corresponding to an element in a
* square diagonal-symmetric matrix array using an equivalent triangular array.
* If either <code>row</code> or <code>col</code> are negative,
* <code>NaN</code> is returned.
* @param row in the square matrix. If <code>row</code> is negative,
* <code>NaN</code> is returned.
* @param col the column in the square matrix. If <code>col</code> is negative,
* <code>NaN</code> is returned.
* @return the value retrieved
* @see lib.kemi.haltaFall.Factor#setEpsilon(int, int, float, float, float)
* setEpsilon
* @see lib.kemi.haltaFall.Factor#printEpsilons(java.io.PrintStream)
* printEpsilons
*/
private float getEpsilon(int row, int col) {
if(row <0 || col <0 || eps == null) {return Float.NaN;}
int i,j;
float tKelvin;
if(row > col) {
i = row; j = col;
} else {
i = col; j = row;
}
float epsilon = eps.eps0[i][j];
if(!Float.isNaN(epsilon)) {
tKelvin = (float)(diag.temperature + 273.15);
if(eps.eps1[i][j] != 0f) {
epsilon = epsilon + eps.eps1[i][j] * tKelvin;
}
if(eps.eps2[i][j] != 0f) {
epsilon = epsilon + eps.eps2[i][j] * tKelvin * tKelvin;
}
}
return epsilon;
} // getEpsilon(row,col)
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="setEpsilon">
/** Stores SIT values corresponding to an element in a square,
* diagonal-symmetric matrix array, using an equivalent triangular array.
* If either <code>row</code> or <code>col</code> are negative,
* nothing is performed.
* @param row in the square matrix. If <code>row</code> is negative
* nothing is performed.
* @param col the column in the square matrix. If <code>col</code> is negative
* nothing is performed.
* @param val0 a value to store
* @param val1 a value to store
* @param val2 a value to store
* @see lib.kemi.haltaFall.Factor#getEpsilon(int, int) getEpsilon
* @see lib.kemi.haltaFall.Factor#printEpsilons(java.io.PrintStream)
* printEpsilons
*/
private void setEpsilon(int row, int col, float val0, float val1, float val2) {
if(row <0 || col <0) {return;}
if(row > col) {
eps.eps0[row][col] = val0;
eps.eps1[row][col] = val1;
eps.eps2[row][col] = val2;
} else {
eps.eps0[col][row] = val0;
eps.eps1[col][row] = val1;
eps.eps2[col][row] = val2;
}
} // setEpsilon(row,col, val)
// </editor-fold>
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="factorPrint">
/** Prints the equations for the model used to calculate the log of the
* activity coefficients.
* @param verbose if false a single line is printed
* @throws IllegalArgumentException
* @throws lib.kemi.haltaFall.Factor.SITdataException */
public void factorPrint(boolean verbose)
throws IllegalArgumentException, SITdataException {
if(verbose) {out.println(dashLine);}
if(dataNotSupplied || diag.activityCoeffsModel < 0) { // ideal solution
if(verbose) {
out.println("\"haltaFall.factor\" (activity coefficient calculations):"+nl+
" dataNotSupplied = "+dataNotSupplied+", activityCoeffsModel = "+diag.activityCoeffsModel);
}
out.println("Activity coefficient calulations will not be performed.");
if(verbose) {out.println(dashLine);}
return;
} // ideal solution
// rho and eps_H2O and Agamma are calculated by the constructor
if(Double.isNaN(rho) || Double.isNaN(eps_H2O) || Double.isNaN(Agamma)) {
try{checks_and_start();}
catch(Exception ex) {
diag.activityCoeffsModel = -1;
diag.ionicStrength = Double.NaN; diag.ionicStrCalc = Double.NaN;
diag.phi = Double.NaN; diag.sumM = Double.NaN;
throw new IllegalArgumentException("\"haltaFall.factor\" (activity coefficient calculations):"+nl+
" "+ex.toString()+nl+
"Activity coefficient calulations will not be performed.");
}
}
String I;
double iStr = 0;
if(!Double.isNaN(diag.ionicStrength)) {iStr = diag.ionicStrength;}
final String sigma ="where sigma(x) = (3/x^3) {(1+x) - 1/(1+x) - 2 ln(1+x)}";
if(diag.activityCoeffsModel == 0) { //Davies
if(verbose) {
if(iStr < 0) {I="varied";}
else {I=Double.toString(iStr);}
String At = String.format(engl, "%8.4f", Agamma).trim();
String Dt = String.format(engl, "%8.2f", DAVIES).trim();
out.println(
"Calculation of activity coefficients with I = "+I+
"; t = "+diag.temperature+"°C"+nl+
"using Davies eqn.:"+nl+
" log f(i) = -"+At+" Zi^2 ( I^0.5 / (1 + I^0.5) - " + Dt +" I)");
if(cs.jWater >= 0) {
out.println(
"The activity of water is calculated according to"+nl+
" log(a(H2O)) = - phi Sum[m] /(ln(10) 55.508)"+nl+
"the osmotic coefficient \"phi\" is calculated from:"+nl+
" phi = 1 - (2/3) (ln(10)/Sum[m]) "+At+" I^(3/2) sigma(I^0.5)" +nl+
" + (ln(10)/Sum[m]) (" +At + " x " + Dt + ") I^2"
+nl+ sigma + ".");
}
} else {out.println("Davies eqn. for activity coefficient calculations.");}
} //Davies
else if(diag.activityCoeffsModel == 1) { //SIT
String S;
if(iStr < 0) {I="varied"; S="Sum[m]";}
else {I=Double.toString(iStr); S="I";}
Bgamma = lib.kemi.H2O.Dielectric.B_gamma(diag.temperature, rho, eps_H2O);
rB = 4.56899 * Bgamma; // this gives 1.5 at 25°C
if(verbose) {
String At = String.format(engl, "%8.4f", Agamma).trim();
String Bt = String.format(engl, "%5.2f", rB).trim();
out.println(
"Calculation of activity coefficients with I = "+I+", and t = "
+diag.temperature+"°C."+nl+
"using the SIT model:"+nl+
" log f(i) = -("+At+" Zi^2 I^0.5 / (1 + "+Bt+" I^0.5))"+
" + Sum[ eps(i,j) m(j) ]"+nl+
"for all \"j\" with Zj*Zi<=0; where eps(i,j) is a"
+" specific ion interaction"+nl+
"parameter (in general independent of I).");
if(cs.jWater >= 0) {
out.println(
"The activity of water is calculated according to"+nl+
" log(a(H2O)) = - phi Sum[m] /(ln(10) 55.508)"+nl+
"the osmotic coefficient \"phi\" is calculated from:"+nl+
" phi = 1 - (2/3) (ln(10)/Sum[m]) "+At+" I^(3/2)"+
" sigma("+Bt+" I^0.5)" + nl +
" + (ln(10)/Sum[m]) Sum_i[ Sum_j[ eps(i,j) m(i) m(j) ]]"+nl+
sigma + ";" +nl+
"and where \"i\" are cations or neutral species and \"j\" are anions.");
}
} else {out.println("SIT method for activity coefficient calculations.");}
// --- Check if there is a need to get "epsilon" values
if(nIon > 0) {
if(eps == null || Float.isNaN(eps.eps0[0][0])) {
try{readSITdataFiles();}
catch (Exception ex) {
diag.activityCoeffsModel = -1;
diag.ionicStrength = Double.NaN; diag.ionicStrCalc = Double.NaN;
diag.phi = Double.NaN; diag.sumM = Double.NaN;
throw new SITdataException("\"haltaFall.factor\" (activity coefficient calculations):"+nl+
ex.getMessage()+nl+"Activity coefficient calulations will not be performed.");
}
}
if(verbose) {printEpsilons(out);}
}
} //SIT
else if(diag.activityCoeffsModel == 2) { //HKF
String S;
if(iStr < 0) {I="varied"; S="I";}
else {
I=Double.toString(iStr);
S="I) = "+(-(float)Math.log10(1+0.0180153*iStr));
}
try{bgi = b_gamma_NaCl(diag.temperature, diag.pressure, eps_H2O, g_function);}
catch (Exception ex) {
diag.activityCoeffsModel = -1;
diag.ionicStrength = Double.NaN; diag.ionicStrCalc = Double.NaN;
diag.phi = Double.NaN; diag.sumM = Double.NaN;
throw new IllegalArgumentException("\"haltaFall.factor\" (activity coefficient calculations):"+nl+
" "+ex.toString()+nl+
"Activity coefficient calulations will not be performed.");
}
// use distance of closest approach for NaCl (HKF-4, Table 3)
rB = lib.kemi.H2O.Dielectric.B_gamma(diag.temperature, rho, eps_H2O) *
( (1.81+g_function) + (0.97 + (0.94+g_function)) );
if(verbose) {
String At = String.format(engl, "%9.5f", Agamma).trim();
String Bt = String.format(engl, "%6.3f", rB).trim();
String bgit = String.format(engl, "%7.4f", bgi).trim();
out.println(
"Calculation of activity coefficients with I = "+I+
"; t = "+diag.temperature+"°C"+nl+
"using simplified Helgeson, Kirkham & Flowers model:"+nl+
" log f(i) = -("+At+" Zi^2 I^0.5) / (1 + "+Bt+" I^0.5)"+
" + Gamma + ("+bgit+" I)"+nl+
"where: Gamma = -log(1+0.0180153 "+S+")");
if(cs.jWater >= 0) {
out.println(
"The activity of water is calculated according to"+nl+
" log(a(H2O)) = - phi Sum[m] /(ln(10) 55.508)"+nl+
"the osmotic coefficient \"phi\" is calculated from:"+nl+
" phi = (ln(10) Gamma / (0.0180153 "+S+"))" + nl +
" - (2/3) (ln(10)/Sum[m]) "+At+" I^(3/2)"+
" sigma("+Bt+" I^0.5)" + nl +
" + (ln(10) (1/2) " + bgit + " I)" + nl +
sigma + ".");
}
} else {
out.println("\"HKF\" model for activity coefficient calculations.");
}
} //HKF
if(verbose) {out.println(dashLine);}
} //factorPrint
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="printActivityCoeffs">
/** Prints the calculated activity coefficients, the ionic strength,
* and the sum of solute concentrations
* @param out0 where messages will be printed. It may be
* <code>System.out</code>. If null, <code>System.out</code> is used.
*/
public void printActivityCoeffs(java.io.PrintStream out0) {
java.io.PrintStream o;
if(out0 != null) {o = out0;} else {o = System.out;}
if(diag.activityCoeffsModel <0 || diag.activityCoeffsModel >2) {
o.println("No activity coefficient calculations performed (ideal solutions).");
return;
}
else {
String t = "Activity coefficients calculated using ";
if(diag.activityCoeffsModel == 0) {o.println(t+"Davies eqn.");}
else if(diag.activityCoeffsModel == 1) {o.println(t+"SIT model.");}
else if(diag.activityCoeffsModel == 2) {
o.println(t+"the simplified HKF model.");
}
}
if(Double.isNaN(diag.ionicStrength) || diag.ionicStrength < 0) {
o.print("Ionic Strength (calculated) = "+(float)ionicStr);
} else {out.print("Ionic Strength (provided by the user) = "+(float)diag.ionicStrength);}
o.println();
o.format(engl,"Electrical balance: %-+14.6g%s",electricBalance,nl);
o.println("Tolerance = "+(float)cs.chemConcs.tolLogF+" (when calculating log10(f)).");
o.println("List of calculated activity coefficients:"+nl
+" nbr species z log10(f) Conc.");
for(int j = 0; j < nIon; j++) {
if(j == cs.jWater) {
o.format(engl,"%4d %-20s a(H2O) =%7.4f phi =%7.4f%s",j,namn.ident[j],
Math.pow(10,cs.chemConcs.logA[j]),osmoticCoeff,nl);
} else {
o.format(engl,"%4d %-20s %3d %9.4f %9.2g%s",j,namn.ident[j],
namn.z[j],cs.chemConcs.logf[j],cs.chemConcs.C[j],nl);
}
} //for j
o.format(engl,"Sum of concentrations, Sum[m] = %-14.6g%s",sumM,nl);
} //printActivityCoeffs
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="calcIonicStr">
/** Calculates <code>ionicStr</code>, <code>electricBalance</code> and
* <code>sumM</code>.<br>
* First the Electrical Balance is calculated. To maintain an electrically
* neutral solution: If <code>electricBalance</code> > 0, then an inert
* anion (X-) is added. If <code>electricBalance</code> < 0, then an
* inert cation (M+) is added.
* @param C concentrations
* @param z electric charges
* @return the calculated value for the ionic strength
*/
private double calcIonicStr(double[] C, int[] z) {
double ionicStrengthCalc = 0;
sumM = 0;
electricBalance = 0;
double Ci;
for(int i =0; i < nIon; i++) {
if(gas[i]) {continue;}
//Ci = Math.max(0, Math.min(MAX_CONC, C[i]));
Ci = Math.max(0, Math.min(1.e+35, C[i]));
sumM = sumM + Ci;
if(z[i] == 0) {continue;}
// Ci = Math.max(0, Math.min(1e35, C[i])); // max. concentration
electricBalance = electricBalance + z[i]*Ci;
ionicStrengthCalc = ionicStrengthCalc + z[i]*z[i]*Ci;
}
ionicStrengthCalc = 0.5 * (Math.abs(electricBalance) + ionicStrengthCalc);
sumM = sumM + Math.abs(electricBalance);
//sumM = Math.min(50, sumM);
//ionicStrengthCalc = Math.min(200, ionicStrengthCalc); // max = 20 molal ThCl4 -> I=200
return ionicStrengthCalc;
} //calcIonicStr
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="isGasOrLiquid(String)">
private static boolean isGasOrLiquid(String t0) {
if(t0 == null) {return false;}
if(t0.length() > 3) {
return (t0.toUpperCase().endsWith("(G)")
|| t0.toUpperCase().endsWith("(L)"));
}
return false;
} //isGasOrLiquid(String)
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="b_gamma_NaCl">
/** Returns b_gamma_NaCl in the HKF model of activity coefficients.
* Range of conditions: < 5,000 bar, -35 to 1000°C.
* It throws an exception outside this range.
* If pBar < 1 a value of pBar = 1 is used.
* If tC = 0 it returns the value at 0.01 Celsius.
* NOTE: values returned at tC <0 are extrapolations outside the valid range.
* It requires a vlues of <code>eps_H2O</code> and of <code>g_function</code>
* @param tC temperature in Celsius
* @param pBar pressure in bar
* @param epsH2O the dielectric constant
* @param gf the g-function (in units of Å) in the HKF model
* @return b_gamma_NaCl in the HKF model of activity coefficients
* @throws IllegalArgumentException
*/
public static double b_gamma_NaCl(final double tC, final double pBar,
final double epsH2O, final double gf)
throws IllegalArgumentException {
/** b_gamma_NaCl is “defined” in Eqn. (173) of Helgeson, Kirkham and Flowers (1981)
* values at 25°C and 1 bar are listed in Tables 5 and 6, while Table 26 gives
* values at temps up to 325°C and Psat (pressures corresponding to the
* liquid-vapor equilibrium) and Table 27 lists values at temperatures up to
* 500°C and pressures up to 5000 bar.
* <p>
* See also eqn.(22) in Oelkers and Helgeson (1990) where "bγ,NaCl" is given in
* Table A-2, and the eqn. (B-12) and parameters in Table A-1. Note that the
* values at 3 kbar and temps. of 800-1000°C in the Table A-2 are wrong:
* they must be multiplied by 10. Note also that eqn.(B-13) in that paper
* is wrong. The same expression for bγ may be found as eqns.(2) and (31)-(32)
* in Pokrovskii and Helgeson (1997).
* <p>
* To calculate values in Table A-2 of Oelkers and Helgeson (1990) using eqn (B-12)
* or the equivalent eqns. (31)-(32) in Pokrovskii and Helgeson (1997) one needs
* values of the dielectric constant (ε) and of ω, which requires values of the
* g-function (see e.g. eqn.(15) in Pokrovskii and Helgeson 1997).
* <p>
* Values of the relative permittivity of water (dielectric constant ε) are
* calculated using the equations of Johnson and Norton (1991). See also
* Johnson et al (1992) and Shock et al (1992) which lists values of ε in Table C2.
* <p>
* The g-function is described in Johnson et al (1992), eqns. (49)-(51) and
* parameters in Tables 2 and 3. See also Shock et al. (1992), where values of
* g are given in Table 5.
* <p>
* References
* Helgeson, Kirkham and Flowers, Amer. J. Sci. 281 (1981) 1249-1516, doi: 10.2475/ajs.281.10.1249
* Oelkers and Helgeson, Geochim. Cosmochim. Acta 54 (1990) 727-738 doi: 10.1016/0016-7037(90)90368-U
* Johnson, Norton. Amer. J. Sci., 291 (1991) 541–648. doi: 10.2475/ajs.291.6.541
* Johnson, Oelkers, Helgeson. Computers & Geosciences, 18 (1992) 899–947. doi: 10.1016/0098-3004(92)90029-Q
* Shock, Oelkers, Johnson, Sverjensky, Helgeson. J. Chem. Soc., Faraday Trans., 88 (1992) 803–826. doi: 10.1039/FT9928800803
* Pokrovskii and Helgeson, Geochim. Cosmochim. Acta 61 (1997) 2175-2183 doi: 10.1016/S0016-7037(97)00070-7
*/
if(Double.isNaN(tC) || Double.isNaN(pBar)) {
throw new IllegalArgumentException("\"haltaFall.Factor.b_gamma_NaCl\": tC="+tC+", pBar="+pBar+" (must be a number)");
}
if(tC < -35 || tC > 1000.01 || pBar < 0 || pBar > 5000.01) {
throw new IllegalArgumentException("\"haltaFall.Factor.b_gamma_NaCl\": tC="+tC+", pBar="+pBar+" (must be -35 to 1000 C and 0 to 5 kbar)");
}
if(Double.isNaN(epsH2O) || Double.isNaN(gf)) {
throw new IllegalArgumentException("\"haltaFall.Factor.b_gamma_NaCl\": eps(H2O)="+epsH2O+", g-function="+gf+" (must be a number)");
}
final double p_Bar = Math.max(1., pBar);
final double t_C;
// if temperature = 0, set temperature to 0.01 C (tripple point of water)
if(Math.abs(tC) < 0.001) {t_C = 0.01;} else {t_C = tC;}
final double tK = t_C + 273.15;
final double tr = 298.15;
final double eta = 1.66027e5;
final double r_c = 0.97, r_a = 1.81;
final double a1 = 0.030056, a2 = -202.55, a3 = -2.9092, a4 = 20302;
final double a5 = -0.206, c1 = -1.50, c2 = 53300., omg = 178650.;
final double bg = -174.623, bs = 2.164;
final double r_eff_c = r_c + (0.94+gf);
final double r_eff_a = r_a + gf;
final double omgpt = eta*( (1./r_eff_c) + (1./r_eff_a) );
final double f1T = tK*Math.log(tK/tr) - tK + tr;
final double f2T = ((1./(tK-228.))-(1./(tr-228.))) * ((228.-tK)/228.) -(tK/(228.*228.))
* Math.log((tr*(tK-228.))/(tK*(tr-228.)));
final double f1P = p_Bar-1.;
final double f2P = Math.log((2600.+p_Bar)/(2600.+1.));
final double f1PT = (p_Bar-1.)/(tK-228.);
final double f2PT = (1./(tK-228.))*Math.log((2600.+p_Bar)/(2600.+1.));
/**
System.out.println("r_eff_c = "+(float)r_eff_c+", r_eff_a = "+(float)r_eff_a);
System.out.println("eps = "+(float)epsH2O+", g = "+(float)(gf*10000.)+", omgpt = "+(float)omgpt);
System.out.println("- bg + bs*(tK-298.15) = "+(float)(- bg + bs*(tK-tr)));
System.out.println("c1*( f1T ) = "+(float)(c1*( f1T )));
System.out.println("c2*( f2T ) = "+(float)(c2*( f2T )));
System.out.println("a3*( f1PT ) + a4*( f2PT )= "+(float)(a3*( f1PT )+ a4*( f2PT )));
// */
final double nbg = - bg + bs*(tK-tr)
- c1*( f1T ) - c2*( f2T )
+ a1*( f1P ) + a2*( f2P )
+ a3*( f1PT ) + a4*( f2PT )
+ a5*(omgpt*((1./epsH2O)-1.) - omg*((1./78.244)-1.) + (-5.799e-5)*omg*(tK-tr));
final double bgam = nbg/(2.*ln10*(1.98720426)*tK); // gas constant in cal/(K mol)
return bgam;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="inner class SITeps">
/** <p>A class to store SIT specific ion interaction coefficients
* (usually called "epsilon") for a given chemical system.
* <p>The number of epsilon coefficients needed is (nIons+2) to achieve
* electroneutrality. Aqueous solutions are made electrically neutral
* by adding two fictive species (Na+ or Cl-) in method "factor",
* and therefore epsilon values for the two species Na+ and Cl- must be
* added to any chemical system. */
public class SITeps {
/** <ul><li>
* <code>eps0[i][j]</code> = temperature-independent term for the
* specific ion interaction coefficient between a cation <code>i</code> and
* an anion <code>j</code>.<li>
* <code>eps0[n][n]</code> = T-independent term for the specific ion
* interaction coefficient between a neutral species <code>n</code> and
* other neutral species</ul>
* The specific ion interaction coefficient are temperature-dependent:
* epsilon = <code>eps0 + eps1 * T + eps2 * T*T</code>;
* where <code>T</code> is the temperature in Kelvins */
public float[][] eps0;
/** specific ion interaction coefficients: <code>eps1[][]</code> = temperature
* dependence term: epsilon = <code>eps0 + eps1 * T + eps2 * T*T</code>;
* where <code>T</code> is the temperature in Kelvins
* @see lib.kemi.chem.Chem.SITepsilon#eps0 eps0 */
public float[][] eps1;
/** specific ion interaction coefficients: <code>eps2[][]</code> = temperature
* dependence term: epsilon = <code>eps0 + eps1 * T + eps2 * T*T</code>;
* where <code>T</code> is the temperature in Kelvins
* @see lib.kemi.chem.Chem.SITepsilon#eps0 eps0 */
public float[][] eps2;
/** Create an instance of a class to store SIT specific ion interaction
* coefficients, usually called "epsilon", for a given chemical system.
* @param nIons
* @throws lib.kemi.haltaFall.Factor.SITdataException */
public SITeps (int nIons) throws SITdataException {
if(nIons<=0) {
throw new SITdataException(
"Error in \"SITepsilon\"-constructor: nIons="+nIons+". Must be >0.");
}
// The number of epsilon coefficients needed is (nIons+2). This is because
// aqueous solutions are made electrically neutral by adding (Na+ or Cl-)
// in method "factor". For electroneutrality the 2 species Na+ and Cl-
// must be added to any chemical system. This means that the array "z" also
// has the dimension (nIons+2).
//
// The SIT coefficients are symmetric: eps[i][j] = eps[j][i].
// To save memory a triangular array is used. The diagonal is kept
// to store interaction coefficients of neutral species with themselves
//
// Make the triangular arrays
eps0 = new float[nIons+2][];
eps1 = new float[nIons+2][];
eps2 = new float[nIons+2][];
for(int i = 0; i< (nIons+2); i++) {
eps0[i] = new float[i+2];
eps1[i] = new float[i+2];
eps2[i] = new float[i+2];
}
eps0[0][0] = Float.NaN; // flag that data is not initialised yet
} //constructor
} //class SITepsilon
//</editor-fold>
/** Exception when dealing with SIT (Specific Ion interaction Theory) data */
public static class SITdataException extends Exception {
/** Exception when dealing with SIT
* (Specific Ion interaction Theory) data. */
public SITdataException() {}
/** Exception when dealing with SIT
* (Specific Ion interaction Theory) data
* @param txt text description */
public SITdataException(String txt) {super(txt);}
}
} | 71,581 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
ReadChemSyst.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibChemDiagr/src/lib/kemi/readWriteDataFiles/ReadChemSyst.java | package lib.kemi.readWriteDataFiles;
import lib.common.Util;
import lib.kemi.chem.Chem;
import lib.kemi.readDataLib.ReadDataLib;
/** Read an input data file accessed through an instance of class ReadDataLib.
* The data is read with a minimum of checks: if the format is correct no error
* will occur. The data is stored in an instance of class Chem.
* <p>This is the minimum amount of work needed to be able to write the data
* again to another data file. Checks of data suitability are made within the
* programs SED or Predom.
*
* Copyright (C) 2015-2018 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class ReadChemSyst {
private static java.util.Locale engl = java.util.Locale.ENGLISH;
/** New-line character(s) to substitute "\n". */
private static String nl = System.getProperty("line.separator");
private static final String LINE = "-------------------------------------";
//<editor-fold defaultstate="collapsed" desc="readChemSystAndPlotInfo">
/** Read an input data file accessed through an instance of class ReadDataLib.
* The data is read with a minimum of checks: if the format is correct no error
* will occur.
* <p>This is the minimum amount of work needed to be able to write the data
* again to another data file. Checks of data suitability are made within the
* programs SED or predom.
* @param rd an instance of class ReadDataLib to read the input file
* @param dbg boolean true if debug information is to be printed
* @param warn = true if errors while reading the plot or
* the concentrations parts of the input file should be
* reported as a warning instead of as an error. Useful when reading
* files from within Spana/Medusa as that program can recover from such errors.
* For example, files created by DataBase/Hydra do not contain plot or
* concentration data. But they can be used in Spana/Medusa.
* @param out where messages will be printed.
* If null, <code>System.out</code> will be used.
* @return a reference to an instance of inner class Chem.ChemSystem
* with the data read. The reference is null if an error occurs
* while reading the file.
* @throws lib.kemi.readWriteDataFiles.ReadChemSyst.DataLimitsException
* @throws lib.kemi.readWriteDataFiles.ReadChemSyst.ReadDataFileException
* @throws lib.kemi.readWriteDataFiles.ReadChemSyst.PlotDataException
* @throws lib.kemi.readWriteDataFiles.ReadChemSyst.ConcDataException
*/
public static Chem readChemSystAndPlotInfo (ReadDataLib rd,
boolean dbg, boolean warn,
java.io.PrintStream out)
throws DataLimitsException, ReadDataFileException,
PlotDataException, ConcDataException {
if(out == null) {out = System.out;}
if(dbg) {out.println("Reading the chemical system...");}
// ------------------------
// READ CHEMICAL SYSTEM
// ------------------------
int na; // number of chemical components given in input file
int nx; // soluble complexes given in input file
int nrSol; // number of solid products given in input file
int solidC; // solid components given in input file
int ms; // total number of species (components (soluble + solid)
// + soluble complexes + solid reaction products)
int mSol; // number of solids (components + reaction products)
int mg; // total number of "soluble" species
rd.nowReading = "Nbr of components (Na)";
try{na = rd.readI();}
catch(ReadDataLib.DataReadException ex) {
throw new ReadDataFileException(ex.getMessage());
} catch (ReadDataLib.DataEofException ex) {
throw new ReadDataFileException(ex.getMessage());
}
if(na<1 || na>1000) {
throw new DataLimitsException(
"Error: Number of components is: "+na+nl+
" must be >0 and <1000."+nl+
" Reading data file:"+nl+
" \""+rd.dataFileName+"\"");
}
rd.nowReading = "Nbr of complexes (Nx)";
try{nx = rd.readI();}
catch(ReadDataLib.DataReadException ex) {
throw new ReadDataFileException(ex.getMessage());
} catch (ReadDataLib.DataEofException ex) {
throw new ReadDataFileException(ex.getMessage());
}
if(nx < 0 || nx > 1000000) {
throw new DataLimitsException(
"Error: Number of soluble complexes is: "+nx+nl+
" must be >=0 and < 1 000 000."+nl+
" Reading data file:"+nl+
" \""+rd.dataFileName+"\"");
}
rd.nowReading = "Nbr of solid reaction products (nrSol)";
try{nrSol = rd.readI();}
catch(ReadDataLib.DataReadException ex) {
throw new ReadDataFileException(ex.getMessage());
}
catch (ReadDataLib.DataEofException ex) {
throw new ReadDataFileException(ex.getMessage());
}
if(nrSol < 0 || nrSol > 100000) {
throw new DataLimitsException(
"Error: Number of solid reaction products is: "+nrSol+nl+
" must be >=0 and < 100 000."+nl+
" Reading data file:"+nl+
" \""+rd.dataFileName+"\"");
}
rd.nowReading = "Nbr of solid components (solidC)";
try{solidC = rd.readI();}
catch(ReadDataLib.DataReadException ex) {
throw new ReadDataFileException(ex.getMessage());
} catch (ReadDataLib.DataEofException ex) {
throw new ReadDataFileException(ex.getMessage());
}
if(solidC<0 || solidC>na) {
throw new DataLimitsException(
"Error: Number of solid components is: "+solidC+nl+
" must be >=0 and <= "+na+" (the nbr of components)."+nl+
" Reading data file:"+nl+
" \""+rd.dataFileName+"\"");
}
// ---- number of solids (components + reaction products)
// because in Halta the solid components are assumed to be
// fictive soluble components with "zero" concentration
// (setting noll[] = true) and the corresponding solid complex
// is added to the list of solids.
mSol = solidC + nrSol;
// ----
ms = na + nx + mSol; // total number of chemical species
// nx = ms - na - mSol;
// mg = total number of soluble species in the aqueous solution:
// all components + soluble complexes
mg = na + nx; // = ms - mSol;
// --- create instances of the classes that store the data
Chem ch = null;
try{ch = new Chem(na, ms, mSol, solidC);}
catch (Chem.ChemicalParameterException ex) {
throw new DataLimitsException(ex.getMessage());
}
Chem.ChemSystem cs = ch.chemSystem;
Chem.ChemSystem.NamesEtc namn = cs.namn;
Chem.DiagrConcs dgrC = ch.diagrConcs;
Chem.Diagr diag = ch.diag;
// ------------------------
// READ NAMES OF COMPONENTS
for(int ia=0; ia <cs.Na; ia++) {
rd.nowReading = "Name of component nbr "+String.valueOf(ia+1);
try{namn.identC[ia] = rd.readA();}
catch(ReadDataLib.DataReadException ex) {
throw new ReadDataFileException(ex.getMessage());
} catch (ReadDataLib.DataEofException ex) {
throw new ReadDataFileException(ex.getMessage());
}
namn.comment[ia] = rd.dataLineComment.toString();
} // for ia
// ------------------------
// is this a file created by DataBase/Spana or Hydra/Medusa?
diag.databaseSpanaFile = rd.fileIsDatabaseOrSpana;
// ---------------------------
// READ DATA FOR THE COMPLEXES
double[] temp = new double[cs.Na];
String identTemp; double w;
String comment;
int i = -1;
int ki;
int shift = cs.Na;
doMs:
do {
i++;
// for components
if(i < cs.Na) {namn.ident[i] = namn.identC[i];}
else if(i >= (cs.Ms - solidC)) {
int ic = cs.Na - (cs.Ms - i);
namn.ident[i] = namn.identC[ic];}
else { // for reactions
String species = "solid";
if(i < mg) {species = "soluble";}
rd.nowReading = "Name of "+species+" reaction product "+String.valueOf(i+1);
try{identTemp = rd.readA();}
catch(ReadDataLib.DataReadException ex) {
throw new ReadDataFileException(ex.getMessage());
} catch (ReadDataLib.DataEofException ex) {
throw new ReadDataFileException(ex.getMessage());
}
comment = rd.dataLineComment.toString();
rd.nowReading = "Formation Equilibrium Constant for "+species+" complex \""+identTemp+"\"";
try{w = rd.readD();}
catch(ReadDataLib.DataReadException ex) {
throw new ReadDataFileException(ex.getMessage());
} catch (ReadDataLib.DataEofException ex) {
throw new ReadDataFileException(ex.getMessage());
}
for(int ia =0; ia < cs.Na; ia++) {
rd.nowReading = "Stoichiometric coeff. "+String.valueOf(ia+1)+" for "+species+" complex \""+identTemp+"\"";
try{temp[ia] = rd.readD();}
catch(ReadDataLib.DataReadException ex) {
throw new ReadDataFileException(ex.getMessage());
} catch (ReadDataLib.DataEofException ex) {
throw new ReadDataFileException(ex.getMessage());
}
} //for ia
namn.ident[i] = identTemp;
if(!Util.stringsEqual(comment,rd.dataLineComment.toString())) {
comment = comment + rd.dataLineComment.toString();
} else if(comment == null || comment.length()<=0) {comment = rd.dataLineComment.toString();}
namn.comment[i] = comment;
ki = i - shift;
cs.lBeta[ki] = w;
//for(int ia =0; ia < cs.Na; ia++) {cs.a[ki][ia] = temp[ia];}
System.arraycopy(temp, 0, cs.a[ki], 0, cs.Na);
} // for reactions
} while (i < (cs.Ms-1)); // doMs:
// for HALTA - solid components:
// the data for the extra fictive solid reaction products
// equilibrium contstant of formation = 1.
// and set stoichiometric coefficients for components
// Note: this must be undone if you save a "data file" from the
// information stored in the Chem classes
addFictiveSolids(cs);
// --- is there H2O?
for(i = 0; i < cs.Na; i++) {
if(Util.isWater(namn.identC[i])) {cs.jWater = i;}
}
// -------------------------
// READ PLOT INFORMATION
// -------------------------
boolean canBePredomFile = false;
int found;
if(dbg) {out.println("Reading plot definition...");}
diag.inputYMinMax = false;
diag.Eh = false; diag.plotType = -1;
// --------
// Y-axis
// --------
String tmp0, tmpUC, ide, ideC, errMsg;
diag.yLow = Double.MAX_VALUE; diag.yHigh = Double.MIN_VALUE;
diag.oneArea = -1;
while(true) {
rd.nowReading = "Plot information for the Y-axis";
try {tmp0 = rd.readA();}
catch(ReadDataLib.DataReadException ex) {
if(!warn) {throw new PlotDataException(ex.getMessage());}
else {diag.plotType = -1; return ch;}
} catch (ReadDataLib.DataEofException ex) {
if(!warn) {throw new PlotDataException(ex.getMessage());}
else {diag.plotType = -1; return ch;}
}
if(!tmp0.equalsIgnoreCase("EH") && !tmp0.equalsIgnoreCase("ONE AREA")) {break;}
if(tmp0.equalsIgnoreCase("EH")) {diag.Eh = true;}
else { //tmp0.equalsIgnoreCase("ONE AREA")
rd.nowReading = "Species name to be plotted as \"One Area\"";
try{tmp0 = rd.readA();}
catch(ReadDataLib.DataReadException ex) {
if(!warn) {throw new PlotDataException(ex.getMessage());}
else {diag.plotType = -1; return ch;}
} catch (ReadDataLib.DataEofException ex) {
if(!warn) {throw new PlotDataException(ex.getMessage());}
else {diag.plotType = -1; return ch;}
}
tmpUC = tmp0.toUpperCase();
if(tmpUC.startsWith("*")) {tmpUC = tmpUC.substring(1);}
found = -1;
for(i = 0; i < cs.Ms; i++) {
ideC = namn.ident[i];
if(ideC.startsWith("*")) {ideC = ideC.substring(1);}
if(tmpUC.equalsIgnoreCase(ideC)) {found = i; break;}
} //for i
if(found < 0) {
errMsg = "Error in data file:"+nl+
" \""+rd.dataFileName+"\""+nl+
"\"One Area\" given, but \""+tmp0+"\" is NOT a species.";
out.println(LINE+nl+errMsg);
printDescriptionYaxis(namn.identC, out);
if(!warn) {throw new PlotDataException(errMsg);}
else {diag.plotType = -1; return ch;}
} // not found
else {diag.oneArea = found;}
} //if tmp0.equalsIgnoreCase("ONE AREA")
} // while (true);
// Values for the Y-axis
// plotType=0 Predom diagram compMain = main component
// plotType=1 fraction diagram compY= main component
// plotType=2 log solubility diagram
// plotType=3 log (conc) diagram
// plotType=4 log (ai/ar) diagram compY= reference species
// plotType=5 pe in Y-axis
// plotType=6 pH in Y-axis
// plotType=7 log (activity) diagram
// plotType=8 H-affinity diagram
diag.plotType = -1;
diag.compX = -1; diag.compY = -1; diag.compMain = -1;
found = -1; ide = tmp0;
if(ide.startsWith("*")) {ide = ide.substring(1);}
for(i = 0; i < cs.Na; i++) {
ideC = namn.identC[i];
if(ideC.startsWith("*")) {ideC = ideC.substring(1);}
if(ide.equalsIgnoreCase(ideC)) {found = i; break;}
} // for i
if(found >= 0) {
diag.plotType=1;
diag.compY = found;
} //fraction diagram
else {
tmpUC = tmp0.toUpperCase();
if(tmpUC.equals("S")) { //log(solubility)
diag.plotType=2;}
else if(tmpUC.equals("LS")) { //log(solubility) with Ymin,Ymax
diag.plotType=2;
diag.inputYMinMax = true;}
else if(tmpUC.equals("L")) { //log(conc)
diag.plotType=3;}
else if(tmpUC.equals("LC")) { //log(conc) with Ymin,Ymax
diag.plotType=3;
diag.inputYMinMax = true;}
else if(tmpUC.equals("LAC")) { //log(activity) with Ymin,Ymax
diag.plotType=7;
diag.inputYMinMax = true;}
else if(tmpUC.equals("PE")) { // Eh-calc.
diag.plotType=5;
diag.inputYMinMax = true;}
else if(tmpUC.equals("PH")) { // pH-calc.
diag.plotType=6;
diag.inputYMinMax = true;}
else if(tmpUC.equals("R")) { //log (ai/ar)
diag.plotType=4;
diag.inputYMinMax = true;
rd.nowReading = "Reference species name for a relative activity diagram";
try{tmp0 = rd.readA();}
catch(ReadDataLib.DataReadException ex) {
if(!warn) {throw new PlotDataException(ex.getMessage());}
else {diag.plotType = -1; return ch;}
} catch (ReadDataLib.DataEofException ex) {
if(!warn) {throw new PlotDataException(ex.getMessage());}
else {diag.plotType = -1; return ch;}
}
tmpUC = tmp0.toUpperCase();
if(tmpUC.startsWith("*")) {tmpUC = tmpUC.substring(1);}
found = -1;
for(i = 0; i < cs.Ms; i++) {
ideC = namn.ident[i];
if(ideC.startsWith("*")) {ideC = ideC.substring(1);}
if(tmpUC.equalsIgnoreCase(ideC)) {found = i; break;}
} //for i
if (found < 0) {
errMsg = "Error in data file:"+nl+
" \""+rd.dataFileName+"\""+nl+
"Relative diagram, but \""+tmp0+"\" is NOT a species.";
out.println(LINE+nl+errMsg);
printDescriptionYaxis(namn.identC, out);
if(!warn) {throw new PlotDataException(errMsg);}
else {diag.plotType = -1; return ch;}
} // not found
else {diag.compY = found;}
} //if log(ai/ar)
else if(tmpUC.equals("PS")) { // H-affinity
diag.plotType=8;
diag.Hplus = -1;
for(i = 0; i < cs.Na; i++) {
ideC = namn.ident[i];
if(ideC.startsWith("*")) {ideC = ideC.substring(1);}
if(Util.isProton(ideC)) {diag.Hplus = i; break;}
} //for i
if(diag.Hplus <0) {
errMsg = "Error in data file:"+nl+
" \""+rd.dataFileName+"\""+nl+
"H-affinity diagram but no \"H+\" component found.";
out.println(LINE+nl+errMsg);
printDescriptionYaxis(namn.identC, out);
if(!warn) {throw new PlotDataException(errMsg);}
else {diag.plotType = -1; return ch;}
} // not found
diag.OHmin = -1;
for(i = 0; i < cs.Ms; i++) {
if(namn.ident[i].equalsIgnoreCase("OH-") ||
namn.ident[i].equalsIgnoreCase("OH -")) {
diag.OHmin = i; break;
}
} //for i
} // if H-affinity
} // not a fraction diagram
if(diag.plotType <= 0) {
errMsg = "Error in data file:"+nl+
" \""+rd.dataFileName+"\""+nl+
"\""+tmp0+"\" is NOT a valid description for the variable in Y-axis.";
out.println(LINE+nl+errMsg);
printDescriptionYaxis(namn.identC, out);
if(!warn) {throw new PlotDataException(errMsg);}
else {diag.plotType = -1; return ch;}
}
else if(diag.plotType == 1) {canBePredomFile = true;}
else if(diag.plotType > 1) {canBePredomFile = false;}
//--- read y-min and y-max
double y;
if(diag.inputYMinMax) {
rd.nowReading = "Minimum value for the Y-axis";
try{diag.yLow = rd.readD();}
catch(ReadDataLib.DataReadException ex) {
if(!warn) {throw new PlotDataException(ex.getMessage());}
else {
out.println(LINE+nl+ex.getMessage());
diag.plotType = -1; return ch;}
} catch (ReadDataLib.DataEofException ex) {
if(!warn) {throw new PlotDataException(ex.getMessage());}
else {
out.println(LINE+nl+ex.getMessage());
diag.plotType = -1; return ch;}
}
rd.nowReading = "Maximum value for the Y-axis";
try{diag.yHigh = rd.readD();}
catch(ReadDataLib.DataReadException ex) {
if(!warn) {throw new PlotDataException(ex.getMessage());}
else {
out.println(LINE+nl+ex.getMessage());
diag.plotType = -1; return ch;}
} catch (ReadDataLib.DataEofException ex) {
if(!warn) {throw new PlotDataException(ex.getMessage());}
else {
out.println(LINE+nl+ex.getMessage());
diag.plotType = -1; return ch;}
}
w = Math.abs(diag.yLow - diag.yHigh);
y = Math.max(Math.abs(diag.yHigh), Math.abs(diag.yLow));
if((y != 0 && (w/y) < 1e-6) || (w < 1e-6)) { // yLow = yMax
String msg = "Error in data file:"+nl+
" \""+rd.dataFileName+"\""+nl+
"Min-value = Max-value in Y-axis !";
if(!warn) {throw new PlotDataException(msg);}
else {out.println(LINE+nl+msg); diag.plotType = -1; return ch;}
}
if(diag.yLow > diag.yHigh) {
w = diag.yLow;
diag.yLow = diag.yHigh;
diag.yHigh = w;}
} //if inputYMinMax
// ---------
// X-axis
// ---------
while(true) {
rd.nowReading = "Plot information for the X-axis (a component name)";
try{tmp0 = rd.readA();}
catch(ReadDataLib.DataReadException ex) {
if(!warn) {throw new PlotDataException(ex.getMessage());}
else {
out.println(LINE+nl+ex.getMessage());
diag.plotType = -1; return ch;}
} catch (ReadDataLib.DataEofException ex) {
if(!warn) {throw new PlotDataException(ex.getMessage());}
else {
out.println(LINE+nl+ex.getMessage());
diag.plotType = -1; return ch;}
}
if(!tmp0.equalsIgnoreCase("EH")) {break;}
diag.Eh = true;
} //while (true);
found = -1; ide = tmp0;
if(ide.startsWith("*")) {ide = ide.substring(1);}
for(i = 0; i < cs.Na; i++) {
ideC = namn.identC[i];
if(ideC.startsWith("*")) {ideC = ideC.substring(1);}
if(ide.equalsIgnoreCase(ideC)) {found = i; break;}
}
if(found >= 0) {diag.compX = found;}
else {
errMsg = "Error in data file:"+nl+
" \""+rd.dataFileName+"\""+nl+
"\""+tmp0+"\" is neither a component for the X-axis, nor \"EH\".";
out.println(LINE+nl+errMsg);
printDescriptionXaxis(namn.identC, out);
if(!warn) {throw new PlotDataException(errMsg);}
else {diag.plotType = -1; return ch;}
}
// --------------------------------
// is this a Predom input file?
// try to read the MAIN COMPONENT
// --------------------------------
if(canBePredomFile) {
while(true) {
rd.nowReading =
"Either the main component name for a Predom diagram, or"+nl+
"conc. data for component nbr 1 ("+namn.identC[0]+")";
try {tmp0 = rd.readA();}
catch(ReadDataLib.DataReadException ex) {
if(!warn) {throw new PlotDataException(ex.getMessage());}
else {
out.println(LINE+nl+ex.getMessage());
diag.plotType = -1; return ch;}
} catch (ReadDataLib.DataEofException ex) {
if(!warn) {throw new PlotDataException(ex.getMessage());}
else {
out.println(LINE+nl+ex.getMessage());
diag.plotType = -1; return ch;}
}
if(!tmp0.equalsIgnoreCase("EH")) {break;}
diag.Eh = true;
} //while (true);
found = -1; ide = tmp0;
if(ide.startsWith("*")) {ide = ide.substring(1);}
for(i = 0; i < cs.Na; i++) {
ideC = namn.identC[i];
if(ideC.startsWith("*")) {ideC = ideC.substring(1);}
if(ide.equalsIgnoreCase(ideC)) {found = i; break;}
}
if(found >= 0) { // it is a component name: a Predom input file
diag.plotType=0; // Predominance area diagram
diag.compMain = found;
tmp0 = null;
}
// If the file was for a SED-fraction diagram then component is not found,
// the text read from the input file is stored in tmp0.
} // if canBePredomFile
else {tmp0 = null;} // if it is a SED file
// -----------------------------------------
// READ CONCENTRATION FOR EACH COMPONENT
// -----------------------------------------
if(dbg) {out.println("Reading the concentrations for each component...");}
dgrC.hur = new int[cs.Na];
// Concentration types for each component:
// hur =1 for "T" (fixed Total conc.)
// hur =2 for "TV" (Tot. conc. Varied)
// hur =3 for "LTV" (Log(Tot.conc.) Varied)
// hur =4 for "LA" (fixed Log(Activity) value)
// hur =5 for "LAV" (Log(Activity) Varied)</pre>
for(int ia =0; ia < cs.Na; ia++) {
dgrC.hur[ia] = -1;
if(tmp0 == null) { // if it is a fraction diagram:
// --- read the type of concentration
rd.nowReading = "Concentration type for component nbr "+String.valueOf(ia+1)+" ("+namn.identC[ia]+")";
try {tmp0 = rd.readA();}
catch(ReadDataLib.DataReadException ex) {
if(!warn) {throw new ConcDataException(ex.getMessage());}
else {
out.println(LINE+nl+ex.getMessage());
diag.plotType = -1; return ch;}
} catch (ReadDataLib.DataEofException ex) {
if(!warn) {throw new ConcDataException(ex.getMessage());}
else {
out.println(LINE+nl+ex.getMessage());
diag.plotType = -1; return ch;}
}
} // if tmp0 = null
if(tmp0.equalsIgnoreCase("T")) {dgrC.hur[ia] =1;}
if(tmp0.equalsIgnoreCase("TV")) {dgrC.hur[ia] =2;}
if(tmp0.equalsIgnoreCase("LTV")) {dgrC.hur[ia] =3;}
if(tmp0.equalsIgnoreCase("LA")) {dgrC.hur[ia] =4;}
if(tmp0.equalsIgnoreCase("LAV")) {dgrC.hur[ia] =5;}
if(dgrC.hur[ia] <= 0) {
String msg = "Error in data file:"+nl+
" \""+rd.dataFileName+"\""+nl+
"\""+tmp0+"\" is NOT any of: T,TV,LTV,LA or LAV."+nl+
" Reading concentration data for component nbr "+String.valueOf(ia+1)+" ("+namn.identC[ia]+")";
if(!warn) {throw new ConcDataException(msg);}
else {
out.println(LINE+nl+msg);
diag.plotType = -1; return ch;}
}
// --- Read the concentration (min and max if varied)
String t;
if(dgrC.hur[ia] ==1 || dgrC.hur[ia] ==4) { //T or LA
if(dgrC.hur[ia] ==1) {t="total conc.";} else {t="log(activity)";}
rd.nowReading =
"The value for the "+t+" for component nbr "+String.valueOf(ia+1)+" ("+namn.identC[ia]+")";
try {dgrC.cLow[ia] = rd.readD();}
catch(ReadDataLib.DataReadException ex) {
if(!warn) {throw new ConcDataException(ex.getMessage());}
else {
out.println(LINE+nl+ex.getMessage());
diag.plotType = -1; return ch;}
} catch (ReadDataLib.DataEofException ex) {
if(!warn) {throw new ConcDataException(ex.getMessage());}
else {
out.println(LINE+nl+ex.getMessage());
diag.plotType = -1; return ch;}
}
dgrC.cHigh[ia] = Double.NaN;
} //if T or LA
else { //if TV, LTV or LAV
if(dgrC.hur[ia] ==2) {t="total conc.";}
else if (dgrC.hur[ia] ==3) {t="log(tot.conc.)";}
else {t="log(activity)";}
rd.nowReading =
"The lowest value for the "+t+" for component nbr "+String.valueOf(ia+1)+" ("+namn.identC[ia]+")";
try {dgrC.cLow[ia] = rd.readD();}
catch(ReadDataLib.DataReadException ex) {
if(!warn) {throw new ConcDataException(ex.getMessage());}
else {
out.println(LINE+nl+ex.getMessage());
diag.plotType = -1; return ch;}
} catch (ReadDataLib.DataEofException ex) {
if(!warn) {throw new ConcDataException(ex.getMessage());}
else {
out.println(LINE+nl+ex.getMessage());
diag.plotType = -1; return ch;}
}
rd.nowReading =
"The highest value for the "+t+" for component nbr "+String.valueOf(ia+1)+" ("+namn.identC[ia]+")";
try {dgrC.cHigh[ia] = rd.readD();}
catch(ReadDataLib.DataReadException ex) {
if(!warn) {throw new ConcDataException(ex.getMessage());}
else {
out.println(LINE+nl+ex.getMessage());
diag.plotType = -1; return ch;}
} catch (ReadDataLib.DataEofException ex) {
if(!warn) {throw new ConcDataException(ex.getMessage());}
else {
out.println(LINE+nl+ex.getMessage());
diag.plotType = -1; return ch;}
}
} //if TV, LTV or LAV
tmp0 = null;
} //for ia
//--- is there a title?
rd.nowReading = "Diagram title";
try {diag.title = rd.readLine();}
catch (ReadDataLib.DataEofException ex) {
diag.title = null;
}
catch (ReadDataLib.DataReadException ex) {
diag.title = null;
throw new ReadDataFileException(ex.getMessage());
}
//--- any other lines...
StringBuilder t = new StringBuilder();
rd.nowReading = "Any comment lines after the diagram title";
while(true) {
try {t.append(rd.readLine()); t.append(nl);}
catch (ReadDataLib.DataEofException ex) {break;}
catch (ReadDataLib.DataReadException ex) {throw new ReadDataFileException(ex.getMessage());}
}
if(t.length() >0) {diag.endLines = t.toString();} else {diag.endLines = null;}
// ---------------------------
return ch;
} //readChemSystAndPlotInfo(inputFile)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="printDescription">
private static void printDescriptionYaxis(String[] identC, java.io.PrintStream out) {
if(out == null) {out = System.out;}
String description =
"General format for Y-axis plot-data is: to obtain:"+nl+
" component-name, either fraction diagram, or"+nl+
" predominance area diagram"+nl+
" L, log(conc) diagram"+nl+
" LC, max-Y-value, min-Y-value, -\"-"+nl+
" LAC, max-Y-value, min-Y-value, log(activity) diagram"+nl+
" S, log(solubility) diagram"+nl+
" LS, max-Y-value, min-Y-value, -\"-"+nl+
" pe, max-Y-value, min-Y-value, pe-calc. in Y-axis"+nl+
" pH, max-Y-value, min-Y-value, pH-calc. in Y-axis"+nl+
" R, species-name, Y-max, Y-min, log(ai/ar) diagram"+nl+
" PS, H+ affinity diagram"+nl+
"You may preceede this with \"Eh,\" in order to use the redox potential"+nl+
"instead of \"pe\" in the diagram. For a predominance area diagram, you"+nl+
"may also preceede the Y-axis plot-data with \"ONE AREA, species-name\","+nl+
"to only show the predominance area of the given species.";
out.println();
out.println(description);
listComponents(identC, out);
out.println("Error in input plot-data for: Y-axis");
} // printDescriptionYaxis()
private static void printDescriptionXaxis(String[] identC, java.io.PrintStream out){
if(out == null) {out = System.out;}
String description =
"General format for X-axis plot-data is:"+nl+
"A component name, for which the concentration is varied. You may"+nl+
"preceede this with \"Eh,\" in order to use the redox potential"+nl+
"instead of \"pe\" in the diagram.";
out.println();
out.println(description);
listComponents(identC, out);
out.println("Error in input plot-data for: X-axis");
} // printDescriptionXaxis()
private static void listComponents(String[] identC, java.io.PrintStream out){
if(out == null) {out = System.out;}
out.println("The names of the components are:");
int n0, nM, iPl, nP;
out.print(" ");
n0 = 0; //start index to print
nM = identC.length - 1; //end index to print
iPl = 7; nP= nM-n0; //items_Per_Line and number of items to print
print_1: for(int ijj=0; ijj<=nP/iPl; ijj++) { for(int jjj=0; jjj<iPl; jjj++) { int kjj = n0+(ijj*iPl+jjj);
out.format(engl," \"%s\",",identC[kjj]);
if(kjj >(nM-1)) {out.println(); break print_1;}} //for ia
out.println(); out.print(" ");} //for ijj
} //listComponents()
//</editor-fold>
/** the number of components, complexes, solids, etc, were
* either less than zero, our unrealistically large */
public static class DataLimitsException extends Exception {
public DataLimitsException() {}
public DataLimitsException(String txt) {super(txt);}
} //DataLimitsException
/** problem found while reading the input data file */
public static class ReadDataFileException extends Exception {
public ReadDataFileException() {}
public ReadDataFileException(String txt) {super(txt);}
} //ReadDataFileException
/** problem found while reading the plot information from the input data file */
public static class PlotDataException extends Exception {
public PlotDataException() {}
public PlotDataException(String txt) {super(txt);}
} //PlotDataException
/** problem found while reading the concentrations from the input data file */
public static class ConcDataException extends Exception {
public ConcDataException() {}
public ConcDataException(String txt) {super(txt);}
} //ConcDataException
//<editor-fold defaultstate="collapsed" desc="addFictiveSolids">
public static boolean addFictiveSolids(Chem.ChemSystem cs) {
if(cs == null) {return false;}
// for HALTA - solid components:
// the data for the extra fictive solid reaction products
// equilibrium contstant of formation = 1.
// and set stoichiometric coefficients for components
// Note: this must be undone if you save a "data file" from the
// information stored in the Chem classes
if(cs.solidC >0) {
int j, k, ji;
for(int m =0; m < cs.solidC; m++) {
// j= (Ms-Na)-solidC ...(Ms-Na)-1
j = (cs.Ms - cs.Na - cs.solidC) + m;
// k = (Na-solidC)...(Na-1)
k = (cs.Na - cs.solidC) + m;
cs.noll[k] = true; // solid components are not aqueous specie
cs.lBeta[j] = 0.; // equilibrium contstant of formation = 1.
for(int n = 0; n < cs.Na; n++) {
cs.a[j][n] = 0.;
if(n == k) {cs.a[j][n] = 1.;}
} // for n
ji = j + cs.Na;
cs.namn.ident[ji] = cs.namn.identC[k];
if(cs.namn.ident[ji].startsWith("*")) {
cs.namn.ident[ji] = cs.namn.ident[ji].substring(1);
cs.noll[ji] = true;
}
} // for m = 0 ... (solidC-1)
} //if solidC >0
return true;
}
//</editor-fold>
} | 34,626 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
DefaultPlotAndConcs.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibChemDiagr/src/lib/kemi/readWriteDataFiles/DefaultPlotAndConcs.java | package lib.kemi.readWriteDataFiles;
import lib.common.Util;
import lib.kemi.chem.Chem;
/** If a data file does not contain a plot definition, nor the concentrations
* for each chemical component, the static methods in this class will assign
* default values for a plot type and for the concentrations.
*
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class DefaultPlotAndConcs {
public DefaultPlotAndConcs() {} //a constructor
//<editor-fold defaultstate="collapsed" desc="setDefaultPlot">
/** Sets a default plot type (log(conc) in the Y-axis) and chooses a default
* component for the X-axis.
* @param cs a reference to an instance of Chem.ChemSystem
* @param diag a reference to an instance of Chem.Diagr
* @param dgrC a reference to an instance of Chem.DiagrConcs
*/
public static void setDefaultPlot (
Chem.ChemSystem cs,
Chem.Diagr diag,
Chem.DiagrConcs dgrC) {
//--- default plot type
diag.plotType = 3; // log(conc) in the Y-axis
diag.yLow = -9; diag.yHigh = 1;
diag.compY = -1;
diag.compMain = -1;
//--- take a default component for the X-axis
diag.compX = -1;
//is there H+ among the components in the chemical system?
for(int i =0; i < cs.Na; i++) {
if(Util.isProton(cs.namn.identC[i])) {diag.compX = i; break;}
} //for i
if(diag.compX <0) {
//is there e- among the components in the chemical system?
for(int i =0; i < cs.Na; i++) {
if(Util.isElectron(cs.namn.identC[i])) {diag.compX = i; break;}
} //for i
}
if(diag.compX <0 && dgrC != null) { //no H+ or e- among the components
for(int i =0; i < cs.Na; i++) {
//is the concentration varied? (assuming concs. are given)
if(dgrC.hur[i] ==2 || dgrC.hur[i] ==3 || dgrC.hur[i] ==5) {
diag.compX = i; break;
} //conc. varied
} //for i
}
if(diag.compX < 0) {
for(int i =0; i < cs.Na; i++) {
// take the first non-cation
if(!Util.isCation(cs.namn.identC[i])) {
diag.compX = i; break;
} //conc. varied
} //for i
}
//nothing works: take the first component
if(diag.compX < 0) {diag.compX = 0;}
} //setDefaultPlot
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="checkConcsInAxesAndMain">
/** Checks that components in the axes have varied concentrations (if needed)
* and that the "main" component (in a Predom diagram) has a fixed concentration.
* It also sets non-varied concentrations for any component that is not in the axes.
*
* @param namn a reference to an instance of Chem.NamesEtc
* @param diag a reference to an instance of Chem.Diagr
* @param dgrC a reference to an instance of Chem.DiagrConcs
* @param dbg if true some "debug" output is printed
* @param kth if <code>true</code> deffault total concetration for cationic
* components is 0.01 instead of 1e-5. Special settings for students at
* the school of chemistry at the Royal Institute of Technology (KTH)
* in Stockholm, Sweden.
* @see DefaultPlotAndConcs#setDefaultConcs setDefaultConcs
* @see DefaultPlotAndConcs#setDefaultConc(int, java.lang.String, lib.kemi.chem.Chem.DiagrConcs) setDefaultConc */
public static void checkConcsInAxesAndMain(
Chem.ChemSystem.NamesEtc namn,
Chem.Diagr diag,
Chem.DiagrConcs dgrC,
boolean dbg, boolean kth) {
//
if(dbg) {System.out.println("checkConcsInAxesAndMain - plotType ="+diag.plotType
+", compMain ="+diag.compMain+", compX ="+diag.compX+", compY ="+diag.compY);}
for(int i =0; i < dgrC.hur.length; i++) {
if(i == diag.compX
|| (diag.plotType ==0 && (i == diag.compMain || i == diag.compY))) {
//if(dbg) {System.out.println(" i="+i+" ("+namn.identC[i]+"), ok");}
continue;
}
if(dgrC.hur[i] <= 0 || dgrC.hur[i] >5 || Double.isNaN(dgrC.cLow[i])
|| (dgrC.hur[i] !=1 && dgrC.hur[i] !=4 // concentration is varied
&& Double.isNaN(dgrC.cHigh[i]))) {
//if(dbg) {System.out.println(" i="+i+" ("+namn.identC[i]+"), setting defaults.");}
setDefaultConc(i, namn.identC[i], dgrC, kth);
}
} //for i
//--- is the concentration for the X-axis component not varied?
if(diag.compX >=0 &&
(dgrC.hur[diag.compX] !=2 && dgrC.hur[diag.compX] !=3 && dgrC.hur[diag.compX] !=5)) {
//make it varied
dgrC.hur[diag.compX] = 5; //"LAV" log(actiity) varied
dgrC.cLow[diag.compX] = -10; dgrC.cHigh[diag.compX] = -1;
if(Util.isProton(namn.identC[diag.compX])) {dgrC.cLow[diag.compX] = -12;}
if(Util.isElectron(namn.identC[diag.compX])) {dgrC.cLow[diag.compX] = -10; dgrC.cHigh[diag.compX] = 10;}
} //if conc. not varied
//--- is the concentration for the Y-axis (Predom) component not varied?
if(diag.compY >=0 && diag.plotType == 0 &&
(dgrC.hur[diag.compY] !=2 && dgrC.hur[diag.compY] !=3 && dgrC.hur[diag.compY] !=5)) {
//make it varied
dgrC.hur[diag.compY] = 5; //"LAV" log(actiity) varied
dgrC.cLow[diag.compY] = -10; dgrC.cHigh[diag.compY] = -1;
if(Util.isProton(namn.identC[diag.compY])) {dgrC.cLow[diag.compY] = -12;}
if(Util.isElectron(namn.identC[diag.compY])) {dgrC.cLow[diag.compY] = -10; dgrC.cHigh[diag.compY] = 10;}
} //if conc. not varied
//--- is the concentration for the Main component (Predom) not in an axis and not fixed?
if(diag.compMain >=0 && diag.compMain != diag.compY && diag.compMain != diag.compX &&
(dgrC.hur[diag.compMain] ==2 || dgrC.hur[diag.compMain] ==3 || dgrC.hur[diag.compMain] ==5)) {
//make it fixed
dgrC.hur[diag.compMain] = 1; //"T" total conc. fixed
dgrC.cLow[diag.compMain] = 1e-6; dgrC.cHigh[diag.compMain] = 0;
} //if conc. not varied
} //checkConcsInAxesAndMain
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="setDefaultConc(ChemSystem, DiagrConcs)">
/** Sets default concentrations (fixed, not varied) for all components in a
* chemcial system. After this procedure you should run
* <code>checkConcsInAxesAndMain</code> to make sure
* that components in the axes have varied concentrations.
* @param cs a reference to an instance of Chem.ChemSystem
* @param dgrC a reference to an instance of Chem.DiagrConcs
* @param kth if <code>true</code> deffault total concetration for cationic
* components is 0.01 instead of 1e-5. Special settings for students at
* the school of chemistry at the Royal Institute of Technology (KTH)
* in Stockholm, Sweden.
* @see DefaultPlotAndConcs#checkConcsInAxesAndMain checkConcsInAxesAndMain */
public static void setDefaultConcs (
Chem.ChemSystem cs,
Chem.DiagrConcs dgrC,
boolean kth) {
for(int i =0; i < cs.Na; i++) {
setDefaultConc(i, cs.namn.identC[i], dgrC, kth);
} //for i
} //setDefaultConcs (ChemSystem, DiagrConcs)
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="setDefaultConc(i, compName, DiagrConcs)">
/** Sets a default concentration (fixed, not varied) for a given
* component "i" in a chemcial system.
* @param i the component (0 to (cs.Na-1)) for which default values of
* <code>hur</code>, <code>cLow</code> and <code>cHigh</code> are needed
* @param compName the name of the component, for example "CO3 2-"
* @param dgrC a reference to an instance of Chem.DiagrConcs
* @param kth if <code>true</code> deffault total concetration for cationic
* components is 0.01 instead of 1e-5. Special settings for students at
* the school of chemistry at the Royal Institute of Technology (KTH)
* in Stockholm, Sweden.
* @see DefaultPlotAndConcs#checkConcsInAxesAndMain checkConcsInAxesAndMain
* @see DefaultPlotAndConcs#setDefaultConcs setDefaultConcs
* @see Chem.DiagrConcs#hur hur
* @see Chem.DiagrConcs#cLow cLow
* @see Chem.DiagrConcs#cHigh cHigh
*/
public static void setDefaultConc (int i, String compName, Chem.DiagrConcs dgrC, boolean kth) {
// defaults
dgrC.hur[i] = 1; //"T" fixed total concentration
dgrC.cHigh[i] = 0; //not used
if(kth) {dgrC.cLow[i] = 0.01;} else {dgrC.cLow[i] = 1e-5;}
//is this e-
if(Util.isElectron(compName)) {
dgrC.cLow[i] = -8.5;
dgrC.hur[i] = 4; //"LA" fixed log(activity)
} // e-
else if(Util.isProton(compName)) {
dgrC.cLow[i] = -7; //pH=7
dgrC.hur[i] = 4; //"LA" fixed log(activity)
} // H+
else {
if(!Util.isCation(compName)) {dgrC.cLow[i] = 0.01;}
if(Util.isGas(compName)) {
dgrC.cLow[i] = -3.5; dgrC.hur[i] = 4; //"LA" fixed log(activity)
} //if gas
else if(Util.isWater(compName)) {
dgrC.cLow[i] = 0; dgrC.hur[i] = 4; //"LA" fixed log(activity)
} //if H2O
} //not H_present and not e_present
} //setDefaultConcs(i, compName, DiagrConcs)
// </editor-fold>
} | 9,811 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
WriteChemSyst.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibChemDiagr/src/lib/kemi/readWriteDataFiles/WriteChemSyst.java | package lib.kemi.readWriteDataFiles;
import lib.common.Util;
import lib.kemi.chem.Chem;
/** Write a data file.
* The data to write must be stored in an instance of class Chem.
*
* Copyright (C) 2015-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class WriteChemSyst {
private static java.util.Locale engl = java.util.Locale.ENGLISH;
/** New-line character(s) to substitute "\n" */
private static String nl = System.getProperty("line.separator");
/** Write a data file.
* @param ch an instance of of the class Chem,
* containing the data to be written
* @param dataFile the file that will be written
* @throws java.io.IOException
* @throws lib.kemi.readWriteDataFiles.WriteChemSyst.DataLimitsException
* @throws lib.kemi.readWriteDataFiles.WriteChemSyst.WriteChemSystArgsException */
public static void writeChemSyst (Chem ch,
java.io.File dataFile)
throws DataLimitsException, WriteChemSystArgsException, java.io.IOException {
if(ch == null) {
throw new WriteChemSystArgsException(
nl+"Error in \"writeChemSyst\":"+nl+
" empty instance of class \"Chem\"");
}
if(dataFile == null || dataFile.getName().length()<=0) {
throw new WriteChemSystArgsException(
nl+"Error in \"writeChemSyst\":"+nl+
" no output data file given");
}
String dataFileName;
try{dataFileName = dataFile.getCanonicalPath();}
catch (java.io.IOException ex) {dataFileName = dataFile.getAbsolutePath();}
if(!dataFileName.toLowerCase().endsWith(".dat")) {
throw new WriteChemSystArgsException(
"File: \""+dataFileName+"\""+nl+
"Error: data file name must end with \".dat\"");
} // does not end with ".dat"
if(dataFile.exists() && (!dataFile.canWrite() || !dataFile.setWritable(true))) {
throw new WriteChemSystArgsException("Error: can not modify file:"+nl+
" \""+dataFile.getPath()+"\""+nl+
"Is this file write-protected?");
}
// Make a temporary file to write the information. If no error occurs,
// then the data file is overwritten with the temporary file
String tmpFileName;
tmpFileName = dataFileName.substring(0,dataFileName.length()-4).concat(".tmp");
java.io.File tmpFile = new java.io.File(tmpFileName);
java.io.FileOutputStream fos = null;
java.io.Writer w = null;
fos = new java.io.FileOutputStream(tmpFile);
w = new java.io.BufferedWriter(new java.io.OutputStreamWriter(fos,"UTF8"));
Chem.ChemSystem cs = ch.chemSystem;
Chem.ChemSystem.NamesEtc namn = cs.namn;
Chem.Diagr diag = ch.diag;
Chem.DiagrConcs dgrC = ch.diagrConcs;
// make some simple checks
if(cs.Na<1 || cs.Na>1000) {
throw new DataLimitsException(
nl+"Error: Number of components is: "+cs.Na+nl+
"Must be >0 and <1000.");
}
if(cs.nx < 0 || cs.nx > 1000000) {
throw new DataLimitsException(
nl+"Error: Number of soluble complexes is: "+cs.nx+nl+
"Must be >=0 and < 1 000 000.");}
int nrSol = cs.mSol - cs.solidC;
if(nrSol < 0 || nrSol > 100000) {
throw new DataLimitsException(
nl+"Error: Number of solid reaction products is: "+nrSol+nl+
"Must be >=0 and < 100 000.");}
if(cs.solidC < 0 || cs.solidC > cs.Na) {
throw new DataLimitsException(
nl+"Error: Number of solid components is: "+cs.solidC+nl+
"Must be >=0 and <= "+cs.Na+" (the nbr of components).");}
String m = ", /SPANA (MEDUSA)";
if(!Double.isNaN(diag.temperature)) {m = m + ", t="+Util.formatDbl3(diag.temperature);}
if(!Double.isNaN(diag.pressure)) {m = m + ", p="+Util.formatDbl3(diag.pressure);}
w.write(" "+String.valueOf(cs.Na)+", "+
String.valueOf(cs.nx)+", "+String.valueOf(nrSol)+", "+
String.valueOf(cs.solidC) + m.trim() +nl);
for(int i=0; i < cs.Na; i++) {
w.write(String.format("%s",namn.identC[i]));
if(namn.comment[i] != null && namn.comment[i].length() >0) {w.write(String.format(" /%s",namn.comment[i]));}
w.write(nl);
} //for i
w.flush();
int ix; StringBuilder logB = new StringBuilder(); int j;
for(int i=cs.Na; i < cs.Na+cs.nx+nrSol; i++) {
if(namn.ident[i].length()<=20) {
w.write(String.format(engl, "%-20s, ",namn.ident[i]));
} else {w.write(String.format(engl, "%s, ",namn.ident[i]));}
ix = i - cs.Na;
if(logB.length()>0) {logB.delete(0, logB.length());}
if(Double.isNaN(cs.lBeta[ix])) {
throw new WriteChemSystArgsException(nl+
"Error: species \""+namn.ident[i]+"\" has logK = Not-a-Number."+nl+
" in \"writeChemSyst\","+nl+
" while writing the data file"+nl+
" \""+tmpFileName+"\"");
}
logB.append(Util.formatDbl3(cs.lBeta[ix]));
//make logB occupy at least 10 chars: padding with space
j = 10 - logB.length();
if(j>0) {for(int k=0;k<j;k++) {logB.append(' ');}}
else {logB.append(' ');} //add at least one space
w.write(logB.toString());
for(j=0; j < cs.Na-1; j++) {
w.write(Util.formatDbl4(cs.a[ix][j])+" ");
}//for j
w.write(Util.formatDbl4(cs.a[ix][cs.Na-1]));
if(namn.comment[i] != null && namn.comment[i].length() >0) {w.write(String.format(" /%s",namn.comment[i]));}
w.write(nl);
}//for i
w.flush();
// ------------------------
// Write Plot information
// ------------------------
boolean ePresent =false;
for(int i=0; i < cs.Na; i++) {
if(Util.isElectron(namn.identC[i])) {ePresent = true; break;}
}
if(!ePresent) {
for(int i=cs.Na; i < cs.Na+cs.nx+nrSol; i++) {
if(Util.isElectron(namn.ident[i])) {ePresent = true; break;}
}
}
if(diag.plotType == 0) { // a Predom diagram:
if(ePresent && diag.Eh) {w.write("EH, ");}
w.write(namn.identC[diag.compY]+", "+
namn.identC[diag.compX]+", "+
namn.identC[diag.compMain]+","+nl);
} else { // a SED diagram
if(diag.plotType == 1) { // "Fraction"
w.write(namn.identC[diag.compY]+", ");
if(ePresent && diag.Eh) {w.write("EH, ");}
w.write(namn.identC[diag.compX]+","+nl);
} else
if(diag.plotType == 2) { // "log Solubilities"
w.write("LS,"+Util.formatDbl4(diag.yLow)+","+Util.formatDbl4(diag.yHigh)+", ");
if(ePresent && diag.Eh) {w.write("EH, ");}
w.write(namn.identC[diag.compX]+","+nl);
} else
if(diag.plotType == 3) { // "Logarithmic"
w.write("LC,"+Util.formatDbl4(diag.yLow)+","+Util.formatDbl4(diag.yHigh)+", ");
if(ePresent && diag.Eh) {w.write("EH, ");}
w.write(namn.identC[diag.compX]+","+nl);
} else
if(diag.plotType == 4) { // "Relative activities"
w.write("R, "+namn.identC[diag.compY]+", "
+Util.formatDbl4(diag.yLow)+","+Util.formatDbl4(diag.yHigh)+", ");
if(ePresent && diag.Eh) {w.write("EH, ");}
w.write(namn.identC[diag.compX]+","+nl);
} else
if(diag.plotType == 5) { // "calculated pe" "calculated Eh"
w.write("pe,"+Util.formatDbl4(diag.yLow)+","+Util.formatDbl4(diag.yHigh)+", ");
if(ePresent && diag.Eh) {w.write("EH, ");}
w.write(namn.identC[diag.compX]+","+nl);
} else
if(diag.plotType == 6) { // "calculated pH"
w.write("pH,"+Util.formatDbl4(diag.yLow)+","+Util.formatDbl4(diag.yHigh)+", ");
if(ePresent && diag.Eh) {w.write("EH, ");}
w.write(namn.identC[diag.compX]+","+nl);
} else
if(diag.plotType == 7) { // "log Activities"
w.write("LAC,"+Util.formatDbl4(diag.yLow)+","+Util.formatDbl4(diag.yHigh)+", ");
if(ePresent && diag.Eh) {w.write("EH, ");}
w.write(namn.identC[diag.compX]+","+nl);
} else
if(diag.plotType == 8) { // "H+ affinity spectrum"
w.write("PS, ");
if(ePresent && diag.Eh) {w.write("EH, ");}
w.write(namn.identC[diag.compX]+","+nl);
}
} // SED or Predom?
w.flush();
// ------------------------
// Write concentrations
// ------------------------
String[] ct = {" ","T","TV","LTV","LA","LAV"};
int h;
for(int i=0; i<cs.Na; i++) {
h = dgrC.hur[i];
if(h ==2 || h ==3 || h ==5) { //conc varied
w.write(ct[h]+", "+Util.formatDbl6(dgrC.cLow[i])+" "+
Util.formatDbl6(dgrC.cHigh[i])+nl);
} else
if(h ==1 || h ==4) { //conc constant
w.write(ct[h]+", "+Util.formatDbl6(dgrC.cLow[i])+nl);
}
} //for i
// title and any comment lines
if(diag.title != null && diag.title.length() >0) {
w.write(diag.title+nl);
}
if(diag.endLines != null && diag.endLines.length() >0) {
if(diag.title == null || diag.title.length() <=0) {w.write(nl);}
w.write(diag.endLines+nl);
}
w.flush(); w.close(); fos.close();
//the temporary file has been created without a problem
// delete the data file and rename the temporary file
dataFile.delete();
tmpFile.renameTo(dataFile);
//return;
} //writeChemSyst
public static class WriteChemSystArgsException extends Exception {
public WriteChemSystArgsException() {}
public WriteChemSystArgsException(String txt) {super(txt);}
} //WriteChemSystArgsException
public static class DataLimitsException extends Exception {
public DataLimitsException() {}
public DataLimitsException(String txt) {super(txt);}
} //DataLimitsException
} | 10,020 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
MsgExceptn.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibChemDiagr/src/lib/common/MsgExceptn.java | package lib.common;
/** A collection of static methods to display messages and exceptions.
*
* Copyright (C) 2014-2018 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class MsgExceptn {
private static final String nl = System.getProperty("line.separator");
//<editor-fold defaultstate="collapsed" desc="msg">
/** outputs <code>txt</code> on <b><code>System.out</code></b> preceeded by a line
* with the calling class and method, and surrounded by lines.
* @param txt the message
* @see lib.common.Util#stack2string(java.lang.Exception) stack2string
* @see #exception(java.lang.String) exceptn
* @see #showErrMsg(java.awt.Component, java.lang.String, int) showErrMsg
*/
public static void msg(String txt) {
exceptionPrivate(txt, ClassLocator.getCallerClassName(), getCallingMethod(), false);
} //error(msg)
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="exception">
/** outputs <code>txt</code> on <b><code>System.err</code></b> preceeded by a line
* with the calling class and method, and surrounded by lines.
* @param txt the message
* @see lib.common.Util#stack2string(java.lang.Exception) stack2string
* @see #msg(java.lang.String) msg
* @see #showErrMsg(java.awt.Component, java.lang.String, int) showErrMsg
*/
public static void exception(String txt) {
exceptionPrivate(txt, ClassLocator.getCallerClassName(), getCallingMethod(), true);
} //error(msg)
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="showErrMsg">
/** Prints "msg" on System.out and displays it on a message box.
* @param parent The owner of the modal dialog that shows the message.
* If null or not enabled: a special frame (window) will be created
* to show the message.
* @param msg message to be shown. If null or empty nothing is done
* @param type =1 exception error; =2 warning; =3 information */
public static void showErrMsg(java.awt.Component parent, String msg, int type) {
if(msg == null || msg.trim().length() <=0) {return;}
if(type == 1) {
System.err.println("----"+nl+msg+nl+"----");
} else {
System.out.println("----"+nl+msg+nl+"----");
}
if(parent == null || !parent.isEnabled()) {
System.out.println("--- showErrMsg: parent is \"null\" or not enabled");
ErrMsgBox mb = new ErrMsgBox(msg, null);
} else {
String title;
if(parent instanceof java.awt.Frame) {
title = ((java.awt.Frame)parent).getTitle();
} else if(parent instanceof java.awt.Dialog) {
title = ((java.awt.Dialog)parent).getTitle();
} else {title = " Error:";}
int j;
if(type==2) {j=javax.swing.JOptionPane.INFORMATION_MESSAGE;}
else if(type==3) {j=javax.swing.JOptionPane.WARNING_MESSAGE;}
else {j=javax.swing.JOptionPane.ERROR_MESSAGE;}
msg = wrapString(msg,50);
javax.swing.JOptionPane.showMessageDialog(parent, msg, title,j);
parent.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
}
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="private wrapString">
/** Returns an input string, with lines that are longer than <code>maxLength</code>
* word-wrapped and indented. *
* @param s input string
* @param maxLength if an input line is longer than this length,
* the line will be word-wrapped at the first white space after <code>maxLength</code>
* and indented with 4 spaces
* @return string with long-lines word-wrapped
*/
private static String wrapString(String s, int maxLength) {
String deliminator = "\n";
StringBuilder result = new StringBuilder();
StringBuffer wrapLine;
int lastdelimPos;
for (String line : s.split(deliminator, -1)) {
if(line.length()/(maxLength+1) < 1) {
result.append(line).append(deliminator);
}
else { //line too long, try to split it
wrapLine = new StringBuffer();
lastdelimPos = 0;
for (String token : line.trim().split("\\s+", -1)) {
if (wrapLine.length() - lastdelimPos + token.length() > maxLength) {
if(wrapLine.length()>0) {wrapLine.append(deliminator);}
wrapLine.append(" ").append(token);
lastdelimPos = wrapLine.length() + 1;
} else {
if(wrapLine.length() <=0) {wrapLine.append(token);}
else {wrapLine.append(" ").append(token);}
}
}
result.append(wrapLine).append(deliminator);
}
}
return result.toString();
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="private exceptionPrivate + getCallingMethod">
private static void exceptionPrivate(String msg, String callingClass, String callingMethod, boolean error) {
final String ERR_START = "============================";
final java.io.PrintStream ps;
if(error) {ps = System.err;} else {ps = System.out;}
ps.println(ERR_START);
boolean p = false;
if(callingClass != null && callingClass.length() >0) {
ps.print(callingClass);
p = true;
}
if(callingMethod != null && callingMethod.length() >0) {
if(p) {ps.print("$");}
ps.print(callingMethod);
p = true;
}
if(p) {ps.println();}
if(msg == null || msg.length() <=0) {msg = "Unknown error.";}
ps.println(msg+nl+ERR_START);
ps.flush();
} //error(msg)
private static String getCallingMethod() {
boolean doNext = false;
int n = 2;
for (StackTraceElement s : Thread.currentThread().getStackTrace()) {
if (doNext) {
if(n == 0) {
return s.getMethodName();
} else {n--;}
}
else {doNext = s.getMethodName().equals("getStackTrace");}
}
return "unknown";
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="private class ErrMsgBox">
/** Displays a "message box" modal dialog with an "OK" button and a title. */
private static class ErrMsgBox {
/** Displays a "message box" modal dialog with an "OK" button and a title.
* The message is displayed in a text area (non-editable),
* which can be copied and pasted elsewhere.
* @param msg will be displayed in a text area, and line breaks may be
* included, for example: <code>new MsgBox("Very\nbad!",""); </code>
* If null or empty nothing is done.
* @param title for the dialog. If null or empty, "Error:" is used
* @see MsgExceptn#showErrMsg(java.awt.Component, java.lang.String, int)
* @version 2015-July-14 */
public ErrMsgBox(String msg, String title) {
if(msg == null || msg.trim().length() <=0) {
System.out.println("--- MsgBox: null or empty \"message\".");
return;
}
//--- Title
if(title == null || title.length() <=0) {title = " Error:";}
java.awt.Frame frame = new java.awt.Frame(title);
//--- Icon
String iconName = "images/ErrMsgBx.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
if(imgURL != null) {frame.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());}
else {System.out.println("--- Error in MsgBox constructor: Could not load image = \""+iconName+"\"");}
frame.pack();
//--- centre Window frame on Screen
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int left; int top;
left = Math.max(55, (screenSize.width - frame.getWidth() ) / 2);
top = Math.max(10, (screenSize.height - frame.getHeight()) / 2);
frame.setLocation(Math.min(screenSize.width-100, left), Math.min(screenSize.height-100, top));
//---
final String msgText = wrapString(msg.trim(),80);
//System.out.println("--- MsgBox:"+nl+msgText+nl+"---");
frame.setVisible(true);
//javax.swing.JOptionPane.showMessageDialog(frame, msg, title, javax.swing.JOptionPane.ERROR_MESSAGE);
MsgBoxDialog msgBox = new MsgBoxDialog(frame, msgText, title, true);
msgBox.setVisible(true); // becase the dialog is modal, statements below will wait
msgBox.dispose();
frame.setVisible(false);
frame.dispose();
}
//<editor-fold defaultstate="collapsed" desc="private class MsgBoxDialog">
private static class MsgBoxDialog extends java.awt.Dialog {
private java.awt.Button ok;
private java.awt.Panel p;
private final java.awt.TextArea text;
/** Creates new form NewDialog */
public MsgBoxDialog(java.awt.Frame parent, String msg, String title, boolean modal) {
super(parent, (" "+title), modal);
addWindowListener(new java.awt.event.WindowAdapter() {
@Override public void windowClosing(java.awt.event.WindowEvent evt) {
MsgBoxDialog.this.setVisible(false);
}
});
setLayout(new java.awt.BorderLayout());
p = new java.awt.Panel();
p.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER));
ok = new java.awt.Button();
// find out the size of the message (width and height)
final int wMax = 85; final int hMax=20;
final int wMin = 5; final int hMin = 1;
int w = wMin;
int h=hMin; int i=0; int j=wMin;
final String eol = "\n"; char c;
final String nl = System.getProperty("line.separator");
while (true) {
c = msg.charAt(i);
String s = String.valueOf(c);
if(s.equals(eol) || s.equals(nl)) {
h++; j=wMin;
} else {
j++; w = Math.max(j,w);
}
i++;
if(i >= msg.length()-1) {break;}
}
// create a text area
int scroll = java.awt.TextArea.SCROLLBARS_NONE;
if(w > wMax && h <= hMax) {scroll = scroll & java.awt.TextArea.SCROLLBARS_HORIZONTAL_ONLY;}
if(h > hMax && w <= wMax) {scroll = scroll & java.awt.TextArea.SCROLLBARS_VERTICAL_ONLY;}
if(w > wMax && h > hMax) {scroll = java.awt.TextArea.SCROLLBARS_BOTH;}
w = Math.min(Math.max(w,10),wMax);
h = Math.min(h,hMax);
text = new java.awt.TextArea(msg, h, w, scroll);
text.setEditable(false);
//text.setBackground(java.awt.Color.white);
text.addKeyListener(new java.awt.event.KeyAdapter() {
@Override public void keyPressed(java.awt.event.KeyEvent evt) {
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER
|| evt.getKeyCode() == java.awt.event.KeyEvent.VK_ESCAPE) {closeDialog();}
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_TAB) {ok.requestFocusInWindow();}
}
});
text.setBackground(java.awt.Color.WHITE);
text.setFont(new java.awt.Font("monospaced", java.awt.Font.PLAIN, 12));
add(text, java.awt.BorderLayout.CENTER);
ok.setLabel("OK");
ok.addActionListener(new java.awt.event.ActionListener() {
@Override public void actionPerformed(java.awt.event.ActionEvent evt) {
closeDialog();
}
});
ok.addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER
|| evt.getKeyCode() == java.awt.event.KeyEvent.VK_ESCAPE) {closeDialog();}
}
});
p.add(ok);
add(p, java.awt.BorderLayout.SOUTH);
pack();
ok.requestFocusInWindow();
//--- centre Window frame on Screen
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int left; int top;
left = Math.max(55, (screenSize.width - getWidth() ) / 2);
top = Math.max(10, (screenSize.height - getHeight()) / 2);
setLocation(Math.min(screenSize.width-100, left), Math.min(screenSize.height-100, top));
}
private void closeDialog() {this.setVisible(false);}
} // private static class MsgBoxDialog
//</editor-fold>
}
// </editor-fold>
}
| 13,228 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
ClassLocator.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibChemDiagr/src/lib/common/ClassLocator.java | package lib.common;
/** Adapted from http://jroller.com/eu/entry/looking_who_is_calling<br>
*
* Copyright (C) 2014 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class ClassLocator extends SecurityManager {
/** Adapted by Ignasi Puigdomenech<br>
* from http://jroller.com/eu/entry/looking_who_is_calling<br>
* (by Eugene Kuleshov). To use:<pre>
* public class Demo {
* public static void main(String[] args) {
* A.aa();
* }
* }
* class A {
* static void aa() {
* System.err.println(ClassLocator.getCallerClass().getName());
* }
* }</pre>
* This method (getCallerClass()) is about six times faster than to do:<pre>
* Throwable stack = new Throwable();
* stack.fillInStackTrace();
* StackTraceElement[] stackTE = stack.getStackTrace();
* String msg = stackTE[1].getClassName();</pre>
* @return the class that called this method
*/
public static Class getCallerClass() {
Class[] classes = new ClassLocator().getClassContext();
if(classes.length >0) {return classes[classes.length-1];}
return null;
}
/** Obtains the name of the class that called the method where "getCallerClassName()" is used
* @return the name of the class */
public static String getCallerClassName() {
Class[] classes = new ClassLocator().getClassContext();
if(classes.length >0) {
int i = Math.min(classes.length-1, 2);
return classes[i].getName();
}
return null;
}
} | 2,089 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
Util.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibChemDiagr/src/lib/common/Util.java | package lib.common;
/** A collection of static methods used by the libraries and
* by the software "Chemical Equilibrium Diagrams".
*
* Copyright (C) 2015-2018 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class Util {
private static final String nl = System.getProperty("line.separator");
private static javax.swing.JFileChooser fc;
private static final java.text.NumberFormat nf;
private static final java.text.NumberFormat nfe;
private static final java.text.NumberFormat nfi;
private static final java.text.DecimalFormat myFormatter;
private static final java.text.DecimalFormat myFormatterExp;
private static final java.text.DecimalFormat myFormatterInt;
private static final String SLASH = java.io.File.separator;
static { // static initializer
nf = java.text.NumberFormat.getNumberInstance(java.util.Locale.ENGLISH);
nfe = java.text.NumberFormat.getNumberInstance(java.util.Locale.ENGLISH);
nfi = java.text.NumberFormat.getNumberInstance(java.util.Locale.ENGLISH);
myFormatter = (java.text.DecimalFormat)nf;
myFormatter.setGroupingUsed(false);
myFormatter.setDecimalSeparatorAlwaysShown(false);
myFormatter.applyPattern("###0.###");
myFormatterExp = (java.text.DecimalFormat)nfe;
myFormatterExp.setGroupingUsed(false);
myFormatterExp.setDecimalSeparatorAlwaysShown(false);
myFormatterExp.applyPattern("0.0##E0");
myFormatterInt = (java.text.DecimalFormat)nfi;
myFormatterInt.setGroupingUsed(false);
myFormatterInt.setDecimalSeparatorAlwaysShown(false);
// -2147483648
myFormatterInt.applyPattern("##########0");
} // static initializer
//--------------------------
// --- Chemical Names ---
//--------------------------
//<editor-fold defaultstate="collapsed" desc="chargeOf(species)">
/** Returns the charge of a species. For "H+" and "Na +" returns +1;
* for "CO3-2" and "SO4 2-" it returns -2; for "X+10" and "X 10+" returns +10.
* For "A+B " it returns zero. For "Al+++" and "CO3--" it +3 and -2.
* For "B+-", "B+-+", "B++--" and "B-+++" it returns -1,+1,-2, and +3, respectively
* @param speciesName
* @return the electric charge of the species
*/
public static int chargeOf(String speciesName) {
int len = speciesName.length();
if(len <= 1) {return 0;}
IntPointer signPos = new IntPointer(-1);
int lastCh = getLastCharExcludingChargeAndSignPosition(speciesName, signPos);
//System.out.println("name \""+speciesName+"\", len="+len+", signPos.i = "+signPos.i+", lastCh="+lastCh);
if(signPos.i <= 0) {return 0;}
int iz = 1;
// get the charge
char sign = speciesName.charAt(signPos.i);
int charge;
if(sign =='+') {charge = 1;} else {charge = -1;}
char ip1 =' ';
if(signPos.i < (len-1)) {ip1 = speciesName.charAt(signPos.i+1);}
//System.out.println("name \""+speciesName+"\", len="+len+", lastCh="+lastCh+", signPos.i="+signPos.i);
if(Character.isDigit(ip1)) { // The char.following the sign is a number
try{charge = charge * Integer.parseInt(speciesName.substring(signPos.i+1).trim());}
catch(NumberFormatException ex) {charge = 0;}
} else if(ip1 == ' ') { // The char.following the sign is not a number,
//then the (+/-) sign is the last character
if(lastCh < (signPos.i-1)) {
try{iz = Integer.parseInt(speciesName.substring(lastCh+1, signPos.i).trim());}
catch(NumberFormatException ex) {iz = 1;}
}
charge = charge * iz;
} else if(ip1 == sign) { // For cases like "Al+++" or "PO4---"
for(int i = signPos.i+1; i < len; i++) {
if(speciesName.charAt(i) == sign) {iz++;}
else {iz = 0; break;} // for cases such as "Al++-"
}
charge = charge * iz;
}
else {charge = 0;}
return charge;
} // chargeOf
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="nameCompare(species1, species2)">
/** Compare two chemical names and decide if they are equal.
* This takes into account electrical charges. Therefore, "Fe 3+" is equal
* to "Fe+3". Note that "I2-" has charge 1-, and "I 2-" has charge 2-.
* Also Ca(OH)2(aq) is equal to Ca(OH)2 which is different to Ca(OH)2(s).
* In addition CO2 and CO2(g) are different.
* @param spe1 one species
* @param spe2 another species
* @return true if they are equivalent */
public static boolean nameCompare(String spe1, String spe2) {
// make sure that strings are not null
if(spe1 == null) {return (spe2 == null);}
else {if(spe2 == null) {return false;}}
//
int z1 = chargeOf(spe1); int z2 = chargeOf(spe2);
if(z1 != z2) {return false;}
return nameOf(spe1).equalsIgnoreCase(nameOf(spe2));
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="nameOf(species)">
/** Get the name without the electric charge for a soluble species.
* Remove also "(aq)" at the end of a name (if it is there).
* @param speciesName
* @return the "bare" species name
* @see #bareNameOf bareNameOf
* @see #chargeOf chargeOf
*/
public static String nameOf(String speciesName) {
int len = speciesName.length();
if(len <= 1) {return speciesName;}
if(len > 4) {
if(speciesName.toUpperCase().endsWith("(AQ)")) {
return speciesName.substring(0, (len-4));
}
}
//-- if the last symbol is a letter: then there is no charge
if(Character.isLetter(speciesName.charAt(len-1))) {return speciesName;}
IntPointer signPos = new IntPointer();
int lastCh;
lastCh = getLastCharExcludingChargeAndSignPosition(speciesName, signPos);
//do not include white space at the end, but keep at least one char
while(lastCh>0 && Character.isWhitespace(speciesName.charAt(lastCh))) {lastCh--;}
return speciesName.substring(0, (lastCh+1));
} // nameOf(species)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="bareNameOf(species)">
/** Get the name without the electric charge for a soluble species.
* Remove also "(aq)" at the end of a name. For a solid, liquid or gas,
* remove phase specification such as "(s)", "(g)" etc
* @param speciesName
* @return the "bare" species name
* @see #nameOf nameOf
* @see #chargeOf chargeOf
*/
public static String bareNameOf(String speciesName) {
String sName = speciesName.trim();
int len = sName.trim().length();
if(len <= 1) {return sName;}
boolean solid = false;
if(len > 3 && sName.toUpperCase().endsWith("(S)")) {
solid = true;
sName = sName.substring(0, (len-3));
len = sName.trim().length();
}
String sNameU = sName.toUpperCase();
if(len > 3) {
if(sNameU.endsWith("(C)") || sNameU.endsWith("(A)")
|| (!solid && (sNameU.endsWith("(L)") || sNameU.endsWith("(G)")))) {
return sName.substring(0, (len-3));
}
}
if(len > 4) {
if(sNameU.endsWith("(CR)") || sNameU.endsWith("(AM)")
|| (!solid && sNameU.endsWith("(AQ)"))) {
return sName.substring(0, (len-4));
}
}
if(len > 5) {
if(sNameU.endsWith("(VIT)") || sNameU.endsWith("(PPT)")) {
return sName.substring(0, (len-5));
}
} //if len >5
if(solid) {return sName;}
//-- if the last symbol is a letter: then there is no charge
if(Character.isLetter(sName.charAt(len-1))) {return sName;}
IntPointer signPos = new IntPointer();
int lastCh;
lastCh = getLastCharExcludingChargeAndSignPosition(sName, signPos);
//do not include white space at the end, but keep at least one char
while(lastCh>0 && Character.isWhitespace(sName.charAt(lastCh))) {lastCh--;}
return sName.substring(0, (lastCh+1));
} // nameOf
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="isProton/isElectron/isSolid / etc">
/** Check if a species name is equivalent to the "proton"
* @param t0 a species name
* @return true if the species is "H+" or "H +" */
public static boolean isProton(String t0) {
if(t0 == null || t0.length() <=1) {return false;}
return (t0.equals("H+") || t0.equals("H +"));
}
/** Check if a species name is equivalent to the "electron". Standard minus (hyphen)
* or Unicode dash or minus sign are ok.
* @param t0 a species name
* @return true if the species is "e-", "e -", etc */
public static boolean isElectron(String t0) {
if(t0 == null || t0.length() <=1) {return false;}
String tu = t0.toUpperCase();
return (tu.equals("E-") || tu.equals("E -") ||
// unicode en dash or unicode minus
tu.equals("E\u2013") || tu.equals("E\u2212") ||
tu.equals("E \u2013") || tu.equals("E \u2212"));
}
/** Check if a species name corresponds to water
* @param t0 a species name
* @return true if the species is "H2O" or "H2O(l)" etc */
public static boolean isWater(String t0) {
if(t0 == null || t0.length() <=2) {return false;}
return (t0.equals("H2O") || t0.toUpperCase().equals("H2O(L)"));
}
/** Check if a species name corresponds to a gas
* @param t0 a species name
* @return true if the species ends with "(g)" */
public static boolean isGas(String t0) {
if(t0 == null || t0.length() <=3) {return false;}
return t0.toUpperCase().endsWith("(G)");
}
/** Check if a species name corresponds to a cation
* @param t0 a species name
* @return true if the electric charge of the species is positive */
public static boolean isCation(String t0) {
if(t0 == null || t0.length() <=1) {return false;}
return chargeOf(t0)>0;
}
/** Check if a species name corresponds to an anion
* @param t0 a species name
* @return true if the electric charge of the species is negative */
public static boolean isAnion(String t0) {
if(t0 == null || t0.length() <=1) {return false;}
return chargeOf(t0)<0;
}
/** Check if a species name corresponds to a solid.
* NOTE: it is dangerous to rely on this method. The user might rename a
* solid such as Ca(CO)3(s) to "calcite", thus, this method may return false
* for names that correspond to perfectly valid solids.
* @param t0 a species name
* @return true if the species ends with either:
* "(s)", "(c)", "(l)", "(cr)", "(am)", , "(a)", "(vit)" or "(ppt)" */
public static boolean isSolid(String t0) {
if(t0 == null || t0.length() <=3) {return false;}
String tU = t0.toUpperCase();
if(tU.endsWith("(S)")) {return true;} //solid
else if(tU.endsWith("(A)")) {return true;} //amorphous
else if(tU.endsWith("(C)")) {return true;} //crystalline
else if(tU.endsWith("(L)")) {return true;} //liquid
if(t0.length() > 4) {
if(tU.endsWith("(CR)")) {return true;} //crystal
else if(tU.endsWith("(AM)")) {return true;} //amorphous
}
if(t0.length() > 5) {
if(tU.endsWith("(VIT)")) {return true;}//vitreous
if(tU.endsWith("(PPT)")) {return true;}//precipitated
}
return false;
}
/** Check if a species name corresponds to a liquid
* @param t0 a species name
* @return true if the species ends with "(l)" */
public static boolean isLiquid(String t0) {
if(t0 == null || t0.length() <=3) {return false;}
return t0.toUpperCase().endsWith("(L)");
}
/** Find out if a species is a neutral aqueous species:
* <ul><li>the species is water,
* <li>the name ends with "(aq)",
* <li>it is neutral and it is not a solid nor a gas.</ul>
* @param t0 name of a species
* @return true if the species is a neutral aqueous species */
public static boolean isNeutralAqu(String t0) {
if(t0 == null || t0.length() <=0) {return false;}
if(t0.length() > 4) {
if(t0.toUpperCase().endsWith("(AQ)")) {return true;} //aqueous
}
if(isWater(t0)) {return true;}
if(t0.length() > 1) {
if(chargeOf(t0)!=0) {return false;}
}
return !isGas(t0) && !isSolid(t0);
}
/** Check if a species name corresponds to a "(cr)" or "(c)" solid.
* @param t0 a species name
* @return true if the species ends with either "(c)" or "(cr)" */
public static boolean is_cr_or_c_solid(String t0) {
if(t0 == null || t0.length() <=3) {return false;}
String tU = t0.toUpperCase();
if(tU.endsWith("(C)")) {return true;} //crystalline
if(t0.length() > 4) {
if(tU.endsWith("(CR)")) {return true;} //crystal
}
return false;
}
/** Check if a species name corresponds to a "(cr)" solid.
* @param t0 a species name
* @return true if the species ends with "(cr)" */
public static boolean is_cr_solid(String t0) {
if(t0 == null || t0.length() <=4) {return false;}
String tU = t0.toUpperCase();
return tU.endsWith("(CR)");
}
/** Check if a species name corresponds to a "(c)" solid.
* @param t0 a species name
* @return true if the species ends with "(c)" */
public static boolean is_c_solid(String t0) {
if(t0 == null || t0.length() <=3) {return false;}
String tU = t0.toUpperCase();
return tU.endsWith("(C)");
}
//</editor-fold>
//-------------------
// --- Compare ---
//-------------------
//<editor-fold defaultstate="collapsed" desc="areEqualDoubles(w1, w2)">
/** Compares two doubles using "Double.compare". If they are not equal
* then checks if they are equal within 1e-7*(min(w1,w2)).
*
* @param w1
* @param w2
* @return true if both doubles are equal
*/
public static boolean areEqualDoubles(double w1, double w2) {
if(Double.compare(w1, w2) == 0) {return true;}
// check if one is NaN or infinite and the other not
final double CLOSE_TO_ZERO = Double.MIN_VALUE * 1e6;
if((Double.isNaN(w1) && !Double.isNaN(w2)) ||
(!Double.isNaN(w1) && Double.isNaN(w2))) {return false;}
if((Double.isInfinite(w1) && !Double.isInfinite(w2)) ||
(!Double.isInfinite(w1) && Double.isInfinite(w2))) {return false;}
// check if one is zero and the other not:
if((Math.abs(w1) < CLOSE_TO_ZERO && Math.abs(w2) > CLOSE_TO_ZERO) ||
(Math.abs(w2) < CLOSE_TO_ZERO && Math.abs(w1) > CLOSE_TO_ZERO)) {return false;}
return Math.abs(w2-w1) < Math.min(Math.abs(w1), Math.abs(w2))*1e-7;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="stringsEqual(species1, species2)">
/** Decide if two stings are equal when "trimmed", even if they are both null.
* @param t1 one string
* @param t2 another string
* @return true if they are equal */
public static boolean stringsEqual(String t1, String t2) {
return ((t1 !=null && t2 !=null && t1.trim().equals(t2.trim())) ||
(t1 ==null && t2 ==null));
}
//</editor-fold>
//---------------------------
// --- Error reporting ---
//---------------------------
//<editor-fold defaultstate="collapsed" desc="stack2string(Exception e)">
/** returns a <code>printStackTrace</code> in a String, surrounded by two dash-lines.
* @param e Exception
* @return printStackTrace */
public static String stack2string(Exception e) {
try{
java.io.StringWriter sw = new java.io.StringWriter();
e.printStackTrace(new java.io.PrintWriter(sw));
String t = sw.toString();
if(t != null && t.length() >0) {
int i = t.indexOf("Unknown Source");
int j = t.indexOf("\n");
if(i>0 && i > j) {
t = t.substring(0,i);
j = t.lastIndexOf("\n");
if(j>0) {t = t.substring(0,j)+nl;}
}
}
return "- - - - - -"+nl+
t +
"- - - - - -";
}
catch(Exception e2) {
return "Internal error in \"stack2string(Exception e)\"";
}
} //stack2string(ex)
//</editor-fold>
//-----------------------------
// --- Number formatting ---
//-----------------------------
//<editor-fold defaultstate="collapsed" desc="formatNum(double)">
/** Returns a String containing a representation of a double floating
* point value, using a point as a decimal separator. Inserts a space
* at the beginning if the string does not start with "-". If the argument is
* NaN (not a number) the value of zero is used.
* @param num the variable (double) to format
* @return the text String representing "num".
* At least one digit is used to represent the fractional part,
* and beyond that as many, but only as many, more digits are used as are needed
* to uniquely distinguish the argument value from adjacent values */
public static String formatNum(double num) {
if(Double.isNaN(num)) {return "NaN";}
if(Double.isInfinite(num)) {return "infinite";}
float f = (float)Math.max((double)(-Float.MAX_VALUE), Math.min((double)Float.MAX_VALUE,num));
if(f == -0.) {f=0;}
java.io.StringWriter sw = new java.io.StringWriter();
java.io.PrintWriter pw = new java.io.PrintWriter(sw);
pw.print(f);
StringBuffer sb = sw.getBuffer();
if(sb.charAt(0) != '-') {sb.insert(0, " ");}
return sb.toString();
} // formatNum(num)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="formatNumAsInt(double)">
/** Returns a String containing a representation of a double floating
* point value, using a point as a decimal separator.
* The number is written as an integer if possible. For example,
* 1.0 will be "1" and -22.0 will be "-22", but 1.1 will be returned as "1.1".
* If the argument is NaN (not a number) the value of zero is used.
* @param num the variable (double) to format
* @return the text String representing "num".
* The number is written as an integer if possible. For example,
* 1.0 will be "1" and -22.0 will be "-22", but 1.1 will be returned as "1.1".
* If the fractional part is needed, at least one digit is used
* and beyond that as many, but only as many, more digits are used as are needed
* to uniquely distinguish the argument value from adjacent values
* @see #formatDbl formatDbl */
public static String formatNumAsInt(double num) {
String textNum = formatNum(num);
int p = textNum.indexOf(".");
if(p > -1 && textNum.endsWith("0")) { //ends with "0" and it contains a "."
int i = textNum.length()-1;
while (true) {
if(textNum.charAt(i) != '0') {break;}
i--;
} //while
textNum = textNum.substring(0, (i+1));
}
if(textNum.endsWith(".")) {return textNum.substring(0, textNum.length()-1);}
return textNum;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="formatDbl, formatInt">
/** Returns a String containing a representation of a double floating
* point value, using a point as a decimal separator. Inserts a space
* at the beginning if the string does not start with "-"
* If the argument is NaN (not a number) or infinite the value of zero is used.
* @param num the variable (double) to format
* @return the text String representing "num".
* The patterns "###0.###" or "0.0##E0", will be used resulting
* in a maximum of four (3) digits in the fractional part. */
public static String formatDbl3(double num) {
if(Double.isNaN(num)) {return "NaN";}
if(Double.isInfinite(num)) {return "infinite";}
String textNum;
if(num == -0) {num = 0;}
if((Math.abs(num) < 0.01 && num != 0) || Math.abs(num) > 9999) {
myFormatterExp.applyPattern("0.0###E0");
textNum = myFormatterExp.format(num);
} else {
myFormatter.applyPattern("####0.###");
textNum = myFormatter.format(num);
}
if(textNum.startsWith("-")) {return textNum.trim();}
else{return " "+textNum.trim();}
} // formatDbl(num)
/** Returns a String containing a representation of a double floating
* point value, using a point as a decimal separator. Inserts a space
* at the beginning if the string does not start with "-"
* If the argument is NaN (not a number) or infinite the value of zero is used.
* @param num the variable (double) to format
* @return the text String representing "num".
* The patterns "###0.####" or "0.0###E0", will be used resulting
* in a maximum of four (4) digits in the fractional part. */
public static String formatDbl4(double num) {
if(Double.isNaN(num)) {return "NaN";}
if(Double.isInfinite(num)) {return "infinite";}
String textNum;
if(num == -0) {num = 0;}
if((Math.abs(num) < 0.001 && num != 0) || Math.abs(num) > 1000) {
myFormatterExp.applyPattern("0.0###E0");
textNum = myFormatterExp.format(num);
} else {
myFormatter.applyPattern("###0.####");
textNum = myFormatter.format(num);
}
if(textNum.startsWith("-")) {return textNum.trim();}
else{return " "+textNum.trim();}
} // formatDbl(num)
/** Returns a String containing a representation of a double floating
* point value, using a point as a decimal separator. Inserts a space
* at the beginning if the string does not start with "-"
* If the argument is NaN (not a number) or infinite the value of zero is used.
* @param num the variable (double) to format
* @return the text String representing "num".
* The patterns "###0.######" or "0.0#####E0", will be used resulting
* in a maximum of six (6) digits in the fractional part. */
public static String formatDbl6(double num) {
if(Double.isNaN(num)) {return "NaN";}
if(Double.isInfinite(num)) {return "infinite";}
String textNum;
if(num == -0) {num = 0;}
if((Math.abs(num) < 0.001 && num != 0) || Math.abs(num) > 1000) {
myFormatterExp.applyPattern("0.0#####E0");
textNum = myFormatterExp.format(num);
} else {
myFormatter.applyPattern("###0.######");
textNum = myFormatter.format(num);
}
if(textNum.startsWith("-")) {return textNum.trim();}
else{return " "+textNum.trim();}
} // formatDbl(num)
/** Returns a String containing a representation of an integer.
* Inserts a space at the beginning if the string does not start with "-"
* @param num the variable (int) to format
* @return the text String representing "num" */
public static String formatInt(int num) {
if(num == -0) {num = 0;}
String textNum = myFormatterInt.format(num);
if(textNum.startsWith("-")) {return textNum.trim();}
else{ return " "+textNum.trim();}
} // formatInt(num)
//</editor-fold>
//-------------------
// --- Diverse ---
//-------------------
/** Throw a NullPointerException: <code>thowErr(null);</code>
* @param n must be "<code>null</code>" to throw a NullPointerException */
public static void throwErr(Integer n) {int a = n*2;}
//<editor-fold defaultstate="collapsed" desc="configureOptionPane()">
/** <b>Left/Right arrow keys support for JOptionpane:</b><p>
* Call this in the "main" method and <i>everytime after selecting a look-and-feel</i>
* to navigate JOptionPanes with the left and right arrow keys (in addtion to TAB and Shift-TAB).
* <p>
* Also use "UIManager.put("Button.defaultButtonFollowsFocus", Boolean.TRUE)" to make
* the ENTER key follow any JButton with the focus. */
public static void configureOptionPane() {
if(javax.swing.UIManager.getLookAndFeelDefaults().get("OptionPane.actionMap") == null) {
javax.swing.UIManager.put("OptionPane.windowBindings", new
Object[] {
"ESCAPE", "close",
"LEFT", "left",
"KP_LEFT", "left",
"RIGHT", "right",
"KP_RIGHT", "right"
});
javax.swing.ActionMap map = new javax.swing.plaf.ActionMapUIResource();
map.put("close", new OptionPaneCloseAction());
map.put("left", new OptionPaneArrowAction(false));
map.put("right", new OptionPaneArrowAction(true));
javax.swing.UIManager.getLookAndFeelDefaults().put("OptionPane.actionMap", map);
}
}
//<editor-fold defaultstate="collapsed" desc="private">
private static class OptionPaneCloseAction extends javax.swing.AbstractAction {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
javax.swing.JOptionPane optionPane = (javax.swing.JOptionPane) e.getSource();
optionPane.setValue(javax.swing.JOptionPane.CLOSED_OPTION);
}
}
private static class OptionPaneArrowAction extends javax.swing.AbstractAction {
private boolean myMoveRight;
OptionPaneArrowAction(boolean moveRight) {myMoveRight = moveRight;}
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
javax.swing.JOptionPane optionPane = (javax.swing.JOptionPane) e.getSource();
java.awt.EventQueue eq = java.awt.Toolkit.getDefaultToolkit().getSystemEventQueue();
eq.postEvent(new java.awt.event.KeyEvent(
optionPane,
java.awt.event.KeyEvent.KEY_PRESSED,
e.getWhen(),
(myMoveRight) ? 0 : java.awt.event.InputEvent.SHIFT_DOWN_MASK,
java.awt.event.KeyEvent.VK_TAB,
java.awt.event.KeyEvent.CHAR_UNDEFINED,
java.awt.event.KeyEvent.KEY_LOCATION_UNKNOWN
));
}
}
// </editor-fold>
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="getFileName()">
//<editor-fold defaultstate="collapsed" desc="getSaveFileName">
/** Get a file name from the user using an Save File dialog.
* @param parent used for error reporting (may be null)
* @param progr name of calling program; used for error reporting (may be null or "")
* @param title caption for the Open File dialog (may be null or "")
* @param type in the range 0 to 11:<pre>
* 0 all files
* 1 (*.exe, *.jar)
* 2 Data bases (*.db, *.txt, *.skv, *.csv)
* 3 Text databases (*.txt, *.skv, *.csv)
* 4 Binary databases (*.db)
* 5 Data files (*.dat)
* 6 Plot files (*.plt)
* 7 Text files (*.txt)
* 8 Acrobat files (*.pdf)
* 9 PostScript (*.ps)
* 10 encapsulated PostScript (*.eps)
* 11 ini-files (*.ini)</pre>
* @param defName a default file name for the Open File dialog. With or without a path. May be null.
* @param path a default path for the Open File dialog (may be null)).
* A path in <code>defName</code> takes preference.
* @return "null" if the user cancels the operation; " " if a programming error is found;
* a file name otherwise */
public static String getSaveFileName(java.awt.Component parent,
String progr,
String title,
int type,
String defName,
String path) {
// Ask the user for a file name using a Open File dialog
boolean mustExist = false;
boolean openF = false;
boolean filesOnly = true;
return getFileName(parent,progr,openF,mustExist,filesOnly,title,type,defName,path);
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="getOpenFileName">
/** Get a file name from the user using an Open File dialog.
* @param parent used for error reporting (may be null)
* @param progr name of calling program; used for error reporting (may be null or "")
* @param mustExist <code>true</code> if file must exist
* @param title caption for the Open File dialog (may be null or "")
* @param type in the range 0 to 11:<pre>
* 0 all files
* 1 (*.exe, *.jar)
* 2 Data bases (*.db, *.txt, *.skv, *.csv)
* 3 Text databases (*.txt, *.skv, *.csv)
* 4 Binary databases (*.db)
* 5 Data files (*.dat)
* 6 Plot files (*.plt)
* 7 Text files (*.txt)
* 8 Acrobat files (*.pdf)
* 9 PostScript (*.ps)
* 10 encapsulated PostScript (*.eps)
* 11 ini-files (*.ini)</pre>
* @param defName a default file name for the Open File dialog. With or without a path. May be null.
* @param path a default path for the Open File dialog (may be null)). A path in
* <code>defName</code> takes preference.
* @return "null" if the user cancels the operation; " " if a programming error is found;
* a file name otherwise */
public static String getOpenFileName(java.awt.Component parent,
String progr,
boolean mustExist,
String title,
int type,
String defName,
String path) {
// Ask the user for a file name using a Open File dialog
boolean openF = true;
boolean filesOnly = true;
return getFileName(parent,progr,openF,mustExist,filesOnly,title,type,defName,path);
}
// </editor-fold>
/** A general purpose procedure to get a file name from the user using
* an Open/Save File Dialog.
* @param parent the parent component of the dialog
* @param progr name of calling program; used for error reporting (may be null or "")
* @param openF show an open (true) or a save (false) dialog?
* @param mustExist <code>true</code> if file must exist
* @param filesOnly <code>true</code> if only files may be selected.
* <code>false</code> if both files and directories may be selected.
* @param title caption for the Open File dialog (may be null or "")
* @param type in the range 0 to 11:<pre>
* 0 all files
* 1 (*.exe, *.jar)
* 2 Data bases (*.db, *.txt, *.skv, *.csv)
* 3 Text databases (*.txt, *.skv, *.csv)
* 4 Binary databases (*.db)
* 5 Data files (*.dat)
* 6 Plot files (*.plt)
* 7 Text files (*.txt)
* 8 Acrobat files (*.pdf)
* 9 PostScript (*.ps)
* 10 encapsulated PostScript (*.eps)
* 11 ini-files (*.ini)</pre>
* @param defName a default file name for the Open File dialog. With or without a path. May be null.
* @param path a default path for the Open File dialog (may be null)).
* A path in <code>defName</code> takes preference.
* @return "null" if the user cancels the operation; " " if a programming error is found;
* a file name otherwise
* @see #getOpenFileName getOpenFileName
* @see #getSaveFileName getSaveFileName */
public static String getFileName(java.awt.Component parent,
String progr,
boolean openF,
boolean mustExist,
boolean filesOnly,
String title,
int type,
String defName,
String path) {
int returnVal;
// Ask the user for a file name using a Open File dialog
parent.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
if(path != null && path.length() >0) {fc = new javax.swing.JFileChooser(path);}
else {fc = new javax.swing.JFileChooser(".");}
fc.setMultiSelectionEnabled(false);
java.io.File currDir = null;
if(path != null && path.trim().length()>0) {currDir = new java.io.File(path);}
if(currDir == null || !currDir.exists()) {currDir = new java.io.File(".");}
fc.setCurrentDirectory(currDir);
if(title != null && title.trim().length()>0) {fc.setDialogTitle(title);}
else {fc.setDialogTitle("Enter a file name");}
if(filesOnly) {
fc.setFileSelectionMode(javax.swing.JFileChooser.FILES_ONLY);
} else {
fc.setFileSelectionMode(javax.swing.JFileChooser.FILES_AND_DIRECTORIES);
}
fc.setAcceptAllFileFilterUsed(true);
java.io.File defFile;
if(defName != null && defName.trim().length() >0) {
defFile = new java.io.File(defName);
//this may change the current directory of the dialog
fc.setSelectedFile(defFile);
}
javax.swing.filechooser.FileNameExtensionFilter filter1 = null;
javax.swing.filechooser.FileNameExtensionFilter filter2 = null;
javax.swing.filechooser.FileNameExtensionFilter filter3 = null;
//javax.swing.filechooser.FileFilter filter = null;
//javax.swing.filechooser.FileFilter filter2 = null;
//javax.swing.filechooser.FileFilter filter3 = null;
String osName = System.getProperty("os.name");
String[] ext = null;
if(type ==1) {
if(osName.startsWith("Mac OS")) {
ext = new String[] {"APP", "JAR"};
filter1 = new javax.swing.filechooser.FileNameExtensionFilter("Programs (*.app, *.jar)", ext);
//filter = new ExtensionFileFilter("Programs (*.app, *.jar)", ext);
} else if(osName.startsWith("Windows")) {
ext = new String[] {"EXE", "JAR"};
filter1 = new javax.swing.filechooser.FileNameExtensionFilter("Programs (*.exe, *.jar)", ext);
} else {
ext = new String[] {"JAR"};
filter1 = new javax.swing.filechooser.FileNameExtensionFilter("Programs (*.jar)", ext);
}
} else if(type ==2) {
ext = new String[] {"DB", "TXT", "SKV", "CSV"};
filter1 = new javax.swing.filechooser.FileNameExtensionFilter("Data bases (*.db, *.txt, *.skv, *.csv)", ext);
filter2 = new javax.swing.filechooser.FileNameExtensionFilter("Text files (*.txt, *.skv, *.csv)", new String[] {"TXT", "SKV", "CSV"});
filter3 = new javax.swing.filechooser.FileNameExtensionFilter("Binary files (*.db)", new String[] {"DB"});
} else if(type ==3) {
ext = new String[] {"TXT", "SKV", "CSV"};
filter1 = new javax.swing.filechooser.FileNameExtensionFilter("Text databases (*.txt, *.skv, *.csv)", ext);
} else if(type ==4) {
ext = new String[] {"DB"};
filter1 = new javax.swing.filechooser.FileNameExtensionFilter("Binary databases (*.db)", ext);
} else if(type ==5) {
ext = new String[] {"DAT"};
filter1 = new javax.swing.filechooser.FileNameExtensionFilter("*.dat", ext);
} else if(type ==6) {
ext = new String[] {"PLT"};
filter1 = new javax.swing.filechooser.FileNameExtensionFilter("*.plt", ext);
} else if(type ==7) {
ext = new String[] {"TXT"};
filter1 = new javax.swing.filechooser.FileNameExtensionFilter("*.txt", ext);
} else if(type ==8) {
ext = new String[] {"PDF"};
filter1 = new javax.swing.filechooser.FileNameExtensionFilter("*.pdf", ext);
} else if(type ==9) {
ext = new String[] {"PS"};
filter1 = new javax.swing.filechooser.FileNameExtensionFilter("*.ps", ext);
} else if(type ==10) {
ext = new String[] {"EPS"};
filter1 = new javax.swing.filechooser.FileNameExtensionFilter("*.eps", ext);
} else if(type ==11) {
ext = new String[] {"INI"};
filter1 = new javax.swing.filechooser.FileNameExtensionFilter("*.ini", ext);
}
// show the Open File dialog using the System look and feel
javax.swing.LookAndFeel oldLaF = javax.swing.UIManager.getLookAndFeel();
boolean resetLaF = false;
if(!oldLaF.getClass().getName().equals(javax.swing.UIManager.getSystemLookAndFeelClassName())) {
try {
javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
System.out.println("--- setLookAndFeel(System);");
fc.updateUI();
resetLaF = true;
}
catch (Exception ex) {System.out.println("--- setLookAndFeel: "+ex.getMessage());}
}
parent.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
if(filter3 != null) {fc.addChoosableFileFilter(filter3);}
if(filter2 != null) {fc.addChoosableFileFilter(filter2);}
if(filter1 != null) {fc.setFileFilter(filter1);}
if(openF) {
returnVal = fc.showOpenDialog(parent);
} else {
returnVal = fc.showSaveDialog(parent);
}
// reset the look and feel
if(resetLaF) {
try {
javax.swing.UIManager.setLookAndFeel(oldLaF);
System.out.println("--- setLookAndFeel(oldLookAndFeel);");
}
catch (javax.swing.UnsupportedLookAndFeelException ex) {System.out.println("--- setLookAndFeel: UnsupportedLookAndFeelException!");}
//javax.swing.UIManager.put("Button.defaultButtonFollowsFocus", Boolean.TRUE);
System.out.println("--- configureOptionPane();");
configureOptionPane();
}
if(returnVal != javax.swing.JFileChooser.APPROVE_OPTION) {return null;}
java.io.File userFile = fc.getSelectedFile();
if (userFile == null) {
System.err.println("--- Error: selected file is \"null\"?");
return null;
}
if(osName.startsWith("Mac OS") && userFile.getName().toLowerCase().endsWith(".app")) {
String n = userFile.getName();
n = n.substring(0, n.length()-4)+".jar";
java.io.File f = new java.io.File(userFile.getAbsolutePath()+SLASH+"Contents"+SLASH+"Resources"+SLASH+"Java"+SLASH+n);
if(f.exists()) {userFile = f;}
}
// -- make sure we got a correct extension
boolean issueWarning = false;
if(ext != null && ext.length >0) { // did the user give an extension?
String userFNU = userFile.getName().toUpperCase();
boolean extOk = false;
String xt = ext[0];
if(xt !=null && xt.length()>0 && userFNU.endsWith("."+xt)) {extOk=true;}
if(!extOk && ext.length > 1) {
for(int i=1; i < ext.length; i++) {
xt = ext[i];
if(xt !=null && xt.length()>0 && userFNU.endsWith("."+xt)) {extOk=true; break;}
} //for
}
boolean dot = userFNU.contains(".");
if(type ==1 && !osName.startsWith("Windows")) { // for Mac OS or Unix/Linux
if(!dot) {extOk=true;}
}
if(!extOk) { // the user gave none of the allowed extentions
if(userFile.getName().contains(".")) {issueWarning = true;}
// find out if a file with any of the allowed extensions exist
java.io.File f;
for(String x : ext) {
f = new java.io.File(userFile.getAbsolutePath()+"."+x.toLowerCase());
if(f.exists()) {userFile = f; extOk = true; issueWarning = false; break;}
} //for
if(!extOk) { // assume first extension
userFile = new java.io.File(userFile.getAbsolutePath()+"."+ext[0].toLowerCase());
if(openF && mustExist && userFile.exists()) {issueWarning = false;}
} //if !extOk
} //if !extOk
// at this point: if "save file" an extension if given
} //if ext[]
if(progr == null || progr.trim().length()<=0) {progr = "(Enter a file name)";}
if(issueWarning) {
Object[] opt = {"OK", "Cancel"};
int answer = javax.swing.JOptionPane.showOptionDialog(parent,
"Note: file name must end with \""+ext[0]+"\""+nl+nl+
"The file name is changed to:"+nl+"\""+userFile.getName()+"\"",
progr, javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.WARNING_MESSAGE,null, opt, opt[1]);
if(answer != javax.swing.JOptionPane.YES_OPTION) {return null;}
}
if(!openF) { //-- save file
if(userFile.exists()) { //save: overwrite?
if(!userFile.canWrite() || !userFile.setWritable(true)) {
javax.swing.JOptionPane.showMessageDialog(parent,
"Can not overwrite file \""+userFile.getName()+"\"."+nl+
"The file or the directory is perhpas write-protected."+nl+
"Try again with another name.",
progr, javax.swing.JOptionPane.ERROR_MESSAGE);
return null;
}
Object[] opt = {"Yes", "No"};
int answer = javax.swing.JOptionPane.showOptionDialog(parent,
"File \""+userFile.getName()+"\" already exists,"+nl+
"Overwrite?",
progr, javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.WARNING_MESSAGE,null, opt, opt[1]);
if(answer != javax.swing.JOptionPane.YES_OPTION) {return null;}
} //exists?
} else { //-- open file
if(mustExist && !userFile.exists()) {
javax.swing.JOptionPane.showMessageDialog(parent,
"File \""+userFile.getName()+"\""+nl+
"does Not exist.",
progr, javax.swing.JOptionPane.ERROR_MESSAGE);
return null;
}
if(userFile.exists() && !userFile.canRead()) {
javax.swing.JOptionPane.showMessageDialog(parent,
"Can not read file \""+userFile.getName()+"\"."+nl+
"The file or the directory is perhpas read-protected.",
progr, javax.swing.JOptionPane.ERROR_MESSAGE);
return null;
}
} //save/open?
// make sure the extension is lower case
String s = userFile.getAbsolutePath();
s = s.substring(0, s.length()-3)+s.substring(s.length()-3).toLowerCase();
return s;
} // getDataFileName()
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="isKeyPressedOK(evt)">
/** For a JTextArea (or a JTextField) that is used to display information,
* some KeyPressed key events,
* such as "delete" or "enter" must be consumed. Other events, such as "page up"
* are acceptable. This procedure returns <code>false</code> if the event is
* not acceptable in KeyPressed events, and it should be consumed.
* @param evt
* @return true if the key event is acceptable, false if it should be consumed */
public static boolean isKeyPressedOK(java.awt.event.KeyEvent evt) {
//int ctrl = java.awt.event.InputEvent.CTRL_DOWN_MASK;
if(evt.isControlDown() &&
//(evt.getModifiersEx() & ctrl) == ctrl) &&
(evt.getKeyCode() == java.awt.event.KeyEvent.VK_V
|| evt.getKeyCode() == java.awt.event.KeyEvent.VK_X
|| evt.getKeyCode() == java.awt.event.KeyEvent.VK_H)) {return false;}
else if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {return false;}
else if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_TAB) {return false;}
else if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_DELETE) {return false;}
else if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_BACK_SPACE) {return false;}
return true;
} //isKeyPressedOK(KeyEvent)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="rTrim">
/** Remove trailing white space. If the argument is null, the return value is null as well.
* @param text input String.
* @return text without trailing white space. */
public static String rTrim(String text) {
if(text == null) {return text;}
//another possibility: ("a" + text).trim().substring(1)
int idx = text.length()-1;
if (idx >= 0) {
//while (idx>=0 && text.charAt(idx) == ' ') {idx--;}
while (idx>=0 && Character.isWhitespace(text.charAt(idx))) {idx--;}
if (idx < 0) {return "";}
else {return text.substring(0,idx+1);}
}
else { //if length =0
return text;
}
} // rTrim
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="private">
//<editor-fold defaultstate="collapsed" desc="getLastCharExcludingChargeAndSignPosition(species)">
/** Finds the position of the last character excluding the electric charge
* (the first character is at position zero) and the position of the (+/-) sign.
* For "X+10", "Y+3" and "F- " it returns 0 and sets signPos.i=1; while for "X 10+",
* "Y 3+" and "F - " it returns 1 and sets signPos.i to 4, 3 and 2, respectively.
* For "A+B " it returns 2 and sets signPos.i = -1. For "Al+++" it returns 1 and
* sets signPos.i = 2 (position of first +/- sign). For "B+-", "B+-+", "B++--" and
* "B-+++" it returns 1,2,2,1, respectively, and sets signPos.i to 2,3,3,2, respectively
* (position of first +/- sign equal to the last sign).
* @param speciesName
* @param signPos a pointer, set by this method, to the position of the (+/-) sign;
* "-1" if there is no (+/-) sign that corresponds to an electric charge in
* speciesName.
* @return the position of the last character excluding the electric charge
* (the first character is at position zero).
*/
private static int getLastCharExcludingChargeAndSignPosition(
String speciesName, IntPointer signPos) {
int len = rTrim(speciesName).length();
//--- is the last character is not a +/- or a number: then finish
char c = speciesName.charAt(len-1);
// unicode en dash or unicode minus
if((c != '+' && c != '-' && c !='\u2013' && c !='\u2212') &&
(c < '0' | c >'9')) {
signPos.i = -1; return len-1;
}
//--- find out if there is a charge; get the last +/-
char sign = ' ';
signPos.i = -1;
for(int ik = len-1; ik >= 0; ik--) {
sign = speciesName.charAt(ik);
// unicode en dash or unicode minus
if(sign == '+' || sign == '-' || sign =='\u2013' || sign =='\u2212')
{signPos.i = ik; break;}
}
//--- if there is no (+/-) in the name, return
if(sign != '+' && sign != '-' && sign !='\u2013' && sign !='\u2212') {signPos.i = -1; return len-1;}
//--- if the (+/-) is not located near the end of the name it is not a sign
if(signPos.i < (len-3) || //for W14O41+10 the position is at (len-3)
signPos.i <= 0) { //if the name starts with + or -.
signPos.i = -1; return len-1;
}
//--- get lastCh = position of the name's last character (excluding last sign)
int lastCh = signPos.i - 1;
char ip1 =' '; // char at position signPos+1
if(signPos.i < (len-1)) {ip1 = speciesName.charAt(signPos.i+1);}
if(ip1 == ' ') {
//The (+/-) sign is the last character (i1 == ' ')
// then lastCh must be smaller...
// look at the character before the sign
// for cases like "Fe 3+" and "SO4 2-" or "Al+++":
c = speciesName.charAt(lastCh); //lastCh =signPos-1
if(Character.isDigit(c)) { // There is a number before the sign: as in "CO3 2-" or "Fe(OH)2+"
//is there a space before the charge?
char im2; //the char at signPos-2
if(signPos.i >=3) { //for example: "U 3+", but Not "I3-"
im2 =speciesName.charAt(signPos.i-2);
if(im2 == ' ') {//it is a space like "CO3 2-"
lastCh = signPos.i - 3;
} else {//im2 is not a space, such as "HS2-"
//for cases like "X 10+"
if(signPos.i >=4
&& Character.isDigit(im2)
&& speciesName.charAt(signPos.i-3) ==' ') {lastCh = signPos.i -4;}
}
} //if(signPos >=3)
} //if isDigit(signPos-1)
else if(c == sign) { // There is another sign before the sign: like Al+++ or CO3--
for(int ik = lastCh; ik >= 0; ik--) {
if(speciesName.charAt(ik) != sign) {signPos.i = ik+1; return ik;}
}
} // else: The character before the sign is not a digit, and it is not the same (+/-)
// do noting, lastCh = signPos.i - 1;
} //if signPos is the last char
//The (+/-) sign is not the last char:
// chech that the (+/-) sign is really an electric charge:
// look at the following chars
else if(Character.isDigit(ip1)) {//The character following the (+/-) sign is a digit
// such as "Ca+2" or for "X+10"
if(signPos.i != (len-2) // exclude "X+1b"
&& !(signPos.i == (len-3) && Character.isDigit(speciesName.charAt(len-1)))) {lastCh = len-1;}
} //if !isDigit(signPos+1)
else {lastCh = len-1;} //the (+/-) sign is not the last, and the following char is not a digit:
return lastCh;
} //getLastCharExcludingChargeAndSignPosition(speciesName,i)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="class IntPointer">
/** a class to point to an integer */
private static class IntPointer {
public int i;
public IntPointer() {}
public IntPointer(int j) {
i = j;
}
} // class IntPointer
//</editor-fold>
//</editor-fold>
}
| 49,126 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
TestHaltaFall.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibChemDiagr/other_stuff/Lib_tests/Test_HaltaFall/src/testHaltaFall/TestHaltaFall.java | package testHaltaFall;
import lib.kemi.chem.Chem;
import lib.kemi.haltaFall.HaltaFall;
import lib.kemi.haltaFall.Factor;
/**
* Test of HaltaFall routine
* 3 chemical components are: H+, e-, Fe(s)
* 15 aqueous species are: H+, e-,
* Fe 2+, FeOH+, Fe(OH)3 -, Fe(OH)4 2-
* Fe 3+, FeOH 2+, Fe(OH)2+, Fe(OH)3, Fe2(OH)2 4+, Fe3(OH)4 5+
* OH-, O2(g), H2(g)
* 3 solid complexes are: Fe(OH)2(s), Fe3O4(s), FeOOH(s)
* Because a component is a solid, an extra solid complex is added: Fe(s)
* ------------------------------------------------------------------
* @author Ignasi Puigdomenech
*/
public class TestHaltaFall {
private static final String nl = System.getProperty("line.separator");
/** @param args the command line arguments */
public static void main(String[] args) {
int na = 3; // chemical cmponents (both soluble and solids)
int ms = 19; // species = components (soluble+solid) + complexes (soluble+solid)
int solidC = 1; // how many components are solid phases
ms = ms + solidC; // add one extra species (solid complex)
// for each solid component
int msol = 4; // solids = 3 solid complexes +1 solid component
// create an instance of the enclosing class "Chem"
// this also creates ChemSystem and ChemConc objects
Chem chem = null;
try{chem = new Chem(na, ms, msol, solidC);}
catch (Chem.ChemicalParameterException ex) {ex.printStackTrace(); System.exit(1);}
if(chem == null) {System.out.println("Chem instance failed."); System.exit(1);}
// get the instance of the inner class "ChemSystem"
Chem.ChemSystem cs = chem.chemSystem;
cs.noll = new boolean[cs.Ms];
for(int i = 0; i < cs.noll.length; i++)
{cs.noll[i] = false;} // for i
cs.noll[1] = true; // do not consider the formation of "e-"
// Note: all soluble complexes must be given 1st, followed by all solids.
// Note: Here the solids are arranged in the following order:
// all solid complexes, followed by all solid components.
// Enter data for complexes
cs.a = new double[cs.Ms-cs.Na][cs.Na];
cs.lBeta = new double[cs.Ms-cs.Na];
cs.a[0][0] = 0.; cs.a[0][1] =-2.; cs.a[0][2] = 1.; cs.lBeta[0] =14.9; // Fe+2
cs.a[1][0] =-1.; cs.a[1][1] =-2.; cs.a[1][2] = 1.; cs.lBeta[1] = 5.1; // FeOH+
cs.a[2][0] =-3.; cs.a[2][1] =-2.; cs.a[2][2] = 1.; cs.lBeta[2] =-16.88;// Fe(OH)3-
cs.a[3][0] =-4.; cs.a[3][1] =-2.; cs.a[3][2] = 1.; cs.lBeta[3] =-30.8; // Fe(OH)4-2
cs.a[4][0] = 0.; cs.a[4][1] =-3.; cs.a[4][2] = 1.; cs.lBeta[4] = 2.43; // Fe+3
cs.a[5][0] =-1.; cs.a[5][1] =-3.; cs.a[5][2] = 1.; cs.lBeta[5] =-0.62; // FeOH+2
cs.a[6][0] =-2.; cs.a[6][1] =-3.; cs.a[6][2] = 1.; cs.lBeta[6] =-3.88; // Fe(OH)2+
cs.a[7][0] =-3.; cs.a[7][1] =-3.; cs.a[7][2] = 1.; cs.lBeta[7] =-10.49;// Fe(OH)3
cs.a[8][0] =-2.; cs.a[8][1] =-6.; cs.a[8][2] = 2.; cs.lBeta[8] = 1.9; // Fe2(OH)2+4
cs.a[9][0] =-4.; cs.a[9][1] =-9.; cs.a[9][2] = 3.; cs.lBeta[9] = 1.52; // Fe3(OH)4+5
cs.a[10][0]=-1.; cs.a[10][1]= 0.; cs.a[10][2]= 0.; cs.lBeta[10]=-14.2; // OH-
cs.a[11][0]=-4.; cs.a[11][1]=-4.; cs.a[11][2]= 0.; cs.lBeta[11]=-84.49;// O2(g)
cs.a[12][0]= 2.; cs.a[12][1]= 2.; cs.a[12][2]= 0.; cs.lBeta[12]=-1.39; // H2(g)
cs.a[13][0]=-2.; cs.a[13][1]=-2.; cs.a[13][2]= 1.; cs.lBeta[13]= 1.52; // Fe(OH)2(s)
cs.a[14][0]=-8.; cs.a[14][1]=-8.; cs.a[14][2]= 3.; cs.lBeta[14]= 8.6; // Fe3O4(s)
cs.a[15][0]=-3.; cs.a[15][1]=-3.; cs.a[15][2]= 1.; cs.lBeta[15]=-1.12; // FeOOH(s)
// Data for components
// create a reference data type variable pointing to the inner class
Chem.ChemSystem.ChemConcs c = cs.chemConcs;
for(int i = 0; i < cs.Na; i++) {
c.kh[i] = 1; // only total concentrations given (kh=1)
c.tol = 1.E-5; // tolerance when solving mass-balance equation
} // for li
// for solid components: the data for the extra solid complexex
for(int i =0; i < solidC; i++) {
int j = (cs.Ms-cs.Na-solidC) +i; // j= (Ms-Na)-solidC ...(Ms-Na)-1
int k = (cs.Na - solidC) +i; // k = (Na-solidC)...(Na-1)
cs.noll[k] = true; // solid components are not aqueous specie
cs.lBeta[j] = 0.; // equilibrium contstant of formation = 1.
for(int n = 0; n <cs.Na; n++) {
cs.a[j][n] = 0.;
if(n == k) {cs.a[j][n] = 1.;}
} // for n
} // for i
// total concentrations for the components
c.tot[0]= 1.E-5;
c.tot[1]= -0.15;
c.tot[2]= 0.1;
int nIon = cs.Ms - cs.mSol; // nIon= number of aqueous species (comps + complxs)
System.out.println("Test of HaltaFall"+nl+nl+
"Nr. Components = "+cs.Na+nl+
"Nr. Aqueous Species = "+nIon+nl+
"Nr. Solid Phases = "+cs.mSol+nl+nl+
"Find pH and pe of an almost neutral aqueous solution where 0.1 mol of"+nl+
"Fe(s) have been oxidized (0.15 mol e- substracted from the system).");
System.out.println("Components: Input Tot.Concs. = "+
java.util.Arrays.toString(c.tot));
// -------------------
//c.dbg = 0; // do not print errors nor debug information
c.dbg = 1; // print errors, but no debug information
//c.dbg = 2; // print errors and some debug information
//c.dbg = 3; // print errors and more debug information
c.cont = false;
// create an instance of Factor
Factor f = new Factor(); //ideal solution: all activity coeffs.=1
// create an instance of class HaltaFall.
HaltaFall h = null;
try{h = new HaltaFall(cs, f, System.out);}
catch (Chem.ChemicalParameterException ex) {ex.printStackTrace(); System.exit(1);}
if(h == null) {System.out.println("HaltaFall instance failed."); System.exit(1);}
// do the calculations
try{h.haltaCalc();}
catch (Chem.ChemicalParameterException ex) {ex.printStackTrace(); System.exit(1);}
// -------------------
System.out.println("RESULTS: err = "+c.errFlagsToString());
double pH = -c.logA[0];
double pe = -c.logA[1];
java.util.Locale e = java.util.Locale.ENGLISH;
System.out.format(e," pH=%6.3f (should be 6.565), pe=%7.3f (should be -6.521)%n",pH,pe);
System.out.println("Components:");
System.out.format(e," Tot.Conc. = %14.6G %14.6G %14.6G%n",
c.tot[0],c.tot[1],c.tot[2]);
System.out.format(e," Solubilities = %14.6G %14.6G %14.6G%n",
c.solub[0],c.solub[1],c.solub[2]);
System.out.format(e," log Act. = %14.6f %14.6f %14.6f%n",
c.logA[0],c.logA[1],c.logA[2]);
//for(int i=0; i<cs.Ms; i++) {c.C[i] = i;c.logA[i]=-i;}
System.out.println("Aqu.Species (all components + aqu.complexes):");
int n0 = 0; //start index to print
int nM = nIon-1; //end index to print
int iPl = 4; int nP= nM-n0; //items_Per_Line and number of items to print
if(nP>0) {
System.out.print(" Conc. =");
print_1:
for(int i=0; i<=nP/iPl; i++) { for(int j=0; j<iPl; j++) { int k = n0+(i*iPl+j);
System.out.format(e," %14.6g",c.C[k]);
if(k >(nM-1)) {System.out.println(); break print_1;}} //for j
System.out.println(); System.out.print(" ");
} //for i
}
System.out.println("Solid Phases:");
n0 = nIon; //start index to print
nM = cs.Ms-1; //end index to print
nP= nM-n0; if(nP>0) {
System.out.print(" Conc. =");
print_1:
for(int i=0; i<=nP/iPl; i++) { for(int j=0; j<iPl; j++) { int k = n0+(i*iPl+j);
System.out.format(e," %14.6g",c.C[k]);
if(k >(nM-1)) {System.out.println(); break print_1;}} //for i2
System.out.println(); System.out.print(" ");
} //for i
}
n0 = nIon; //start index to print
nM = cs.Ms-1; //end index to print
nP= nM-n0; if(nP>0) {
System.out.print(" log Act. =");
print_1:
for(int i=0; i<=nP/iPl; i++) { for(int j=0; j<iPl; j++) { int k = n0+(i*iPl+j);
System.out.format(e," %14.6f",c.logA[k]);
if(k >(nM-1)) {System.out.println(); break print_1;}} //for i2
System.out.println(); System.out.print(" ");
} //for i
}
} // main
}
| 8,194 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
TestGraphLib.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibChemDiagr/other_stuff/Lib_tests/Test_GraphLib/src/testGraphLib/TestGraphLib.java | package testGraphLib;
import lib.kemi.graph_lib.DiagrPaintUtility;
import lib.kemi.graph_lib.GraphLib;
public class TestGraphLib extends javax.swing.JFrame {
private javax.swing.JPanel jPanel1;
private static GraphLib.PltData dd;
private static DiagrPaintUtility glib = new DiagrPaintUtility();
private static final boolean TEXT_WITH_FONTS = true;
public static void main(String[] args) {
//---- write a test plot file "test_symbol.plt"
// - create a PltData instance
dd = new GraphLib.PltData();
// - create a GraphLib instance
GraphLib g = new GraphLib();
//---- make a diagram, store it in "dd" asnd save to a disk file
try {g.start(dd, new java.io.File("test_symbol.plt"), true);}
catch (Exception ex) {System.err.println(ex.getMessage()); g.end(); return;}
float size = 0.3f;
float x1=0.2f, y=0.2f, x2=14.2f;
g.setIsFormula(false); g.sym(x1, y, size, "H+ Na + OH- F - HCO3- H2PO4 -", 0, -1, false);
g.setIsFormula(true); g.sym(x2, y, size, "H+ Na + OH- F - HCO3- H2PO4 -", 0, -1, false);
y = y + 0.8f;
g.setIsFormula(false); g.sym(x1, y, size, "SO4-2 CO3 2- Fe 2+ (UO2)2(OH)2+2", 0, -1, false);
g.setIsFormula(true); g.sym(x2, y, size, "SO4-2 CO3 2- Fe 2+ (UO2)2(OH)2+2", 0, -1, false);
y = y + 0.8f;
g.setIsFormula(false); g.sym(x1, y, size, "(PO4-3) [Fe(CO3)2-2]`TOT' {SO4-2}", 0, -1, false);
g.setIsFormula(true); g.sym(x2, y, size, "(PO4-3) [Fe(CO3)2-2]`TOT' {SO4-2}", 0, -1, false);
y = y + 0.8f;
g.setIsFormula(false); g.sym(x1, y, size, "(PO4 3-) [Fe(CO3)2 2-]`TOT' {SO4 2-}", 0, -1, false);
g.setIsFormula(true); g.sym(x2, y, size, "(PO4 3-) [Fe(CO3)2 2-]`TOT' {SO4 2-}", 0, -1, false);
y = y + 0.8f;
g.setIsFormula(false); g.sym(x1, y, size, "Fe0.943O(c) NaCl·2H2O UO2.6667(c)", 0, -1, false);
g.setIsFormula(true); g.sym(x2, y, size, "Fe0.943O(c) NaCl·2H2O UO2.6667(c)", 0, -1, false);
y = y + 0.8f;
g.setIsFormula(false); g.sym(x1, y, size, "CaCO3:2.5H2O log P`CO2' E`SHE' 10'-3`", 0, -1, false);
g.setIsFormula(true); g.sym(x2, y, size, "CaCO3:2.5H2O log P`CO2' E`SHE' 10'-3`", 0, -1, false);
y = y + 0.8f;
g.setIsFormula(false); g.sym(x1, y, size, "((CH3)2Hg)-2 (S6) 2- (Al(OH)2)2 2+", 0, -1, false);
g.setIsFormula(true); g.sym(x2, y, size, "((CH3)2Hg)-2 (S6) 2- (Al(OH)2)2 2+", 0, -1, false);
y = y + 0.8f;
g.setIsFormula(false); g.sym(x1, y, size, "[(CH3)2Hg]-2 [S6] 2- [Al(OH)2]2 2+", 0, -1, false);
g.setIsFormula(true); g.sym(x2, y, size, "[(CH3)2Hg]-2 [S6] 2- [Al(OH)2]2 2+", 0, -1, false);
y = y + 0.8f;
g.setIsFormula(false); g.sym(x1, y, size, "{(CH3)2Hg}-2 {S6} 2- {Al(OH)2}2 2+", 0, -1, false);
g.setIsFormula(true); g.sym(x2, y, size, "{(CH3)2Hg}-2 {S6} 2- {Al(OH)2}2 2+", 0, -1, false);
y = y + 0.8f;
g.setIsFormula(false); g.sym(x1, y, size, "Pu38O56Cl54-14 W14O41 10+ B22H66-23 Fe8 23+", 0, -1, false);
g.setIsFormula(true); g.sym(x2, y, size, "Pu38O56Cl54-14 W14O41 10+ B22H66-23 Fe8 23+", 0, -1, false);
y = y + 0.8f;
g.setIsFormula(false); g.sym(x1, y, size, "(W14O41 10-) [W14O41 10+] {B22H66-23} [Fe8]+23", 0, -1, false);
g.setIsFormula(true); g.sym(x2, y, size, "(W14O41 10-) [W14O41 10+] {B22H66-23} [Fe8]+23", 0, -1, false);
y = y + 0.8f;
g.setIsFormula(false); g.sym(x1, y, size, "\"W14O41\"-11 \"W14O41\" 10+ \"N2O3\"- \"Cu2\"+", 0, -1, false);
g.setIsFormula(true); g.sym(x2, y, size, "\"W14O41\"-11 \"W14O41\" 10+ \"N2O3\"- \"Cu2\"+", 0, -1, false);
y = y + 0.8f;
g.setIsFormula(false); g.sym(x1, y, size, "Fe+2 -2H+=Fe(OH)2 Ca+2 +CO3-2 = CaCO3(s)", 0, -1, false);
g.setIsFormula(true); g.sym(x2, y, size, "Fe+2 -2H+=Fe(OH)2 Ca+2 +CO3-2 = CaCO3(s)", 0, -1, false);
y = y + 0.8f;
g.setIsFormula(false); g.sym(x1, y, size, "x'2` + v`i' - log`10'f = 2·10'-3`bar", 0, -1, false);
g.setIsFormula(true); g.sym(x2, y, size, "x'2` + v`i' - log`10'f = 2·10'-3`bar", 0, -1, false);
y = y + 0.8f;
g.setIsFormula(false); g.sym(x1, y, size, "^H`f''o` =5; f`Fe3O4'=3$M t=25~C", 0, -1, false);
g.setIsFormula(true); g.sym(x2, y, size, "^H`f''o` =5; f`Fe3O4'=3$M t=25~C", 0, -1, false);
y = y + 0.8f;
g.setIsFormula(false); g.sym(x1, y, size, "^G`f'~=3.9 kJ'.`mol'-1` P`CO2'", 0, -1, false);
g.setIsFormula(true); g.sym(x2, y, size, "^G`f'~=3.9 kJ'.`mol'-1` P`CO2'", 0, -1, false);
y = y + 0.8f;
g.setIsFormula(false); g.sym(x1, y, size, "·ÅÄÖåäöñ &%#~^$@→°º±•×µ‰%", 0, -1, false);
g.setIsFormula(true); g.sym(x2, y, size, "·ÅÄÖåäöñ &%#~^$@→°º±•×µ‰%", 0, -1, false);
y = y + 0.8f;
g.setIsFormula(false); g.sym(x1, y, size, "Non-symbol style:", 0, -1, false);
g.setIsFormula(true); g.sym(x2, y, size, "Symbol style:", 0, -1, false);
// finished
g.end();
System.out.println("Written: \"test_symbol.plt\"");
//---- write another test plot file "test_rotated_text.plt"
// - create a PltData instance
dd = new GraphLib.PltData();
// - create a GraphLib instance
g = new GraphLib();
//---- make a diagram, store it in "dd" and save to a disk file
try {g.start(dd, new java.io.File("test_rotated_text.plt"), true);}
catch (Exception ex) {System.err.println(ex.getMessage()); g.end(); return;}
g.setIsFormula(true);
float x0=5f, y0=5f, r=2f, angle =0f;
float f = 3.14159265f/180f;
size = 0.35f;
String t = "(PO4-3) [Fe(CO3)2-2]`TOT' {SO4-2} (UO2)2(OH)2+2";
x1 = x0 + r*(float)Math.cos(angle*f); y = y0 + r*(float)Math.sin(angle*f);
g.sym(x1, y, size, t, angle, -1, false);
angle = 22f;
x1 = x0 + r*(float)Math.cos(angle*f); y = y0 + r*(float)Math.sin(angle*f);
g.sym(x1, y, size, t, angle, -1, false);
angle = 45f;
x1 = x0 + r*(float)Math.cos(angle*f); y = y0 + r*(float)Math.sin(angle*f);
g.sym(x1, y, size, t, angle, -1, false);
angle = 67f;
x1 = x0 + r*(float)Math.cos(angle*f); y = y0 + r*(float)Math.sin(angle*f);
g.sym(x1, y, size, t, angle, -1, false);
angle = 90f;
x1 = x0 + r*(float)Math.cos(angle*f); y = y0 + r*(float)Math.sin(angle*f);
g.sym(x1, y, size, t, angle, -1, false);
angle = 180f;
x1 = x0 + r*(float)Math.cos(angle*f); y = y0 + r*(float)Math.sin(angle*f);
g.sym(x1, y, size, t, angle, -1, false);
angle = 180f + 30f;
x1 = x0 + r*(float)Math.cos(angle*f); y = y0 + r*(float)Math.sin(angle*f);
g.sym(x1, y, size, t, angle, -1, false);
angle = 180f + 60f;
x1 = x0 + r*(float)Math.cos(angle*f); y = y0 + r*(float)Math.sin(angle*f);
g.sym(x1, y, size, t, angle, -1, false);
angle = -30f;
x1 = x0 + r*(float)Math.cos(angle*f); y = y0 + r*(float)Math.sin(angle*f);
g.sym(x1, y, size, t, angle, -1, false);
angle = -60f;
x1 = x0 + r*(float)Math.cos(angle*f); y = y0 + r*(float)Math.sin(angle*f);
g.sym(x1, y, size, t, angle, -1, false);
angle = -90f;
x1 = x0 + r*(float)Math.cos(angle*f); y = y0 + r*(float)Math.sin(angle*f);
g.sym(x1, y, size, t, angle, -1, false);
angle = -180f - 45f;
x1 = x0 + r*(float)Math.cos(angle*f); y = y0 + r*(float)Math.sin(angle*f);
g.sym(x1, y, size, t, angle, -1, false);
// finished
g.end();
System.out.println("Written: \"test_rotated_text.plt\"");
//---- write another test plot file "test_all.plt"
// - create a PltData instance
dd = new GraphLib.PltData();
// - create a GraphLib instance
g = new GraphLib();
//---- make a diagram, store it in "dd" and save to a disk file
try {g.start(dd, new java.io.File("test_all.plt"), true);}
catch (Exception ex) {System.err.println(ex.getMessage()); g.end(); return;}
size = 0.25f;
String t1 = "^[CO3 2-]`TOT'", t2 = "123.456";
int n1 = t1.length(), n2 = t2.length();
float a0 =0, a45 = 45, a90 = 95; // angles
int align;
x0 = 0f;
y0 = 25f;
g.setPen(1); g.setPen(-1);
g.sym(x0, y0, size, "Not \"formula\"", 0f, -1, false);
g.sym(x0+((Math.max(n1,n2)+1)*size)*3, y0, size, "\"Formula\"", 0f, -1, false);
g.sym(x0+2*size, y0-1.7*size, size, "Align: Left", 0f, -1, false);
g.sym(x0+(2+(Math.max(n1,n2)+1))*size, y0-1.7*size, size, "Centre", 0f, -1, false);
g.sym(x0+(2+2*(Math.max(n1,n2)+1))*size, y0-1.7*size, size, "Right", 0f, -1, false);
g.sym(x0+(2+3*(Math.max(n1,n2)+1))*size, y0-1.7*size, size, "Align: Left", 0f, -1, false);
g.sym(x0+(2+4*(Math.max(n1,n2)+1))*size, y0-1.7*size, size, "Centre", 0f, -1, false);
g.sym(x0+(2+5*(Math.max(n1,n2)+1))*size, y0-1.7*size, size, "Right", 0f, -1, false);
// ---- pen thickness ----
int nPen =1;
while(nPen <=2) {
g.setPen(nPen); g.setPen(-nPen);
// ---- not formulas ----
g.setIsFormula(false);
// ---- align left
align = -1; //left
// first text
g.sym (x0, y0-(n1+3)*size, size, t1, a0, align, false);
textBox(x0, y0-(n1+3)*size, size, size*n1, a0, g);
g.sym (x0, y0-(n1+2)*size, size, t1, a45, align, false);
textBox(x0, y0-(n1+2)*size, size, size*n1, a45, g);
g.sym (x0, y0-(n1+1)*size, size, t1, a90, align, false);
textBox(x0, y0-(n1+1)*size, size, size*n1, a90, g);
// second text
g.sym (x0, y0-((n1+3)+(n2+3))*size, size, t2, a0, align, false);
textBox(x0, y0-((n1+3)+(n2+3))*size, size, size*n2, a0, g);
g.sym (x0, y0-((n1+3)+(n2+2))*size, size, t2, a45, align, false);
textBox(x0, y0-((n1+3)+(n2+2))*size, size, size*n2, a45, g);
g.sym (x0, y0-((n1+3)+(n2+1))*size, size, t2, a90, align, false);
textBox(x0, y0-((n1+3)+(n2+1))*size, size, size*n2, a90, g);
// ---- align centre
align = 0; //centre
x0 = x0 + (Math.max(n1,n2)+1)*size;
// first text
g.sym (x0, y0-(n1+3)*size, size, t1, a0, align, false);
textBox(x0, y0-(n1+3)*size, size, size*n1, a0, g);
g.sym (x0, y0-(n1+2)*size, size, t1, a45, align, false);
textBox(x0, y0-(n1+2)*size, size, size*n1, a45, g);
g.sym (x0, y0-(n1+1)*size, size, t1, a90, align, false);
textBox(x0, y0-(n1+1)*size, size, size*n1, a90, g);
// second text
g.sym (x0, y0-((n1+3)+(n2+3))*size, size, t2, a0, align, false);
textBox(x0, y0-((n1+3)+(n2+3))*size, size, size*n2, a0, g);
g.sym (x0, y0-((n1+3)+(n2+2))*size, size, t2, a45, align, false);
textBox(x0, y0-((n1+3)+(n2+2))*size, size, size*n2, a45, g);
g.sym (x0, y0-((n1+3)+(n2+1))*size, size, t2, a90, align, false);
textBox(x0, y0-((n1+3)+(n2+1))*size, size, size*n2, a90, g);
// ---- align right
align = 1; //right
x0 = x0 + (Math.max(n1,n2)+1)*size;
// first text
g.sym (x0, y0-(n1+3)*size, size, t1, a0, align, false);
textBox(x0, y0-(n1+3)*size, size, size*n1, a0, g);
g.sym (x0, y0-(n1+2)*size, size, t1, a45, align, false);
textBox(x0, y0-(n1+2)*size, size, size*n1, a45, g);
g.sym (x0, y0-(n1+1)*size, size, t1, a90, align, false);
textBox(x0, y0-(n1+1)*size, size, size*n1, a90, g);
// second text
g.sym (x0, y0-((n1+3)+(n2+3))*size, size, t2, a0, align, false);
textBox(x0, y0-((n1+3)+(n2+3))*size, size, size*n2, a0, g);
g.sym (x0, y0-((n1+3)+(n2+2))*size, size, t2, a45, align, false);
textBox(x0, y0-((n1+3)+(n2+2))*size, size, size*n2, a45, g);
g.sym (x0, y0-((n1+3)+(n2+1))*size, size, t2, a90, align, false);
textBox(x0, y0-((n1+3)+(n2+1))*size, size, size*n2, a90, g);
// ---- formulas ----
g.setIsFormula(true);
x0 = x0 + (Math.max(n1,n2)+1)*size;
// ---- align left
align = -1; //left
// first text
g.sym (x0, y0-(n1+3)*size, size, t1, a0, align, false);
textBox(x0, y0-(n1+3)*size, size, size*n1, a0, g);
g.sym (x0, y0-(n1+2)*size, size, t1, a45, align, false);
textBox(x0, y0-(n1+2)*size, size, size*n1, a45, g);
g.sym (x0, y0-(n1+1)*size, size, t1, a90, align, false);
textBox(x0, y0-(n1+1)*size, size, size*n1, a90, g);
// second text
float size0 = size*1.2f;
g.sym (x0, y0-((n1+3)+(n2+3))*size, size0, t2, a0, align, false);
textBox(x0, y0-((n1+3)+(n2+3))*size, size0, size*n2, a0, g);
g.sym (x0, y0-((n1+3)+(n2+2))*size, size0, t2, a45, align, false);
textBox(x0, y0-((n1+3)+(n2+2))*size, size0, size*n2, a45, g);
g.sym (x0, y0-((n1+3)+(n2+1))*size, size0, t2, a90, align, false);
textBox(x0, y0-((n1+3)+(n2+1))*size, size0, size*n2, a90, g);
// ---- align centre
align = 0; //centre
x0 = x0 + (Math.max(n1,n2)+1)*size;
// first text
g.sym (x0, y0-(n1+3)*size, size, t1, a0, align, false);
textBox(x0, y0-(n1+3)*size, size, size*n1, a0, g);
g.sym (x0, y0-(n1+2)*size, size, t1, a45, align, false);
textBox(x0, y0-(n1+2)*size, size, size*n1, a45, g);
g.sym (x0, y0-(n1+1)*size, size, t1, a90, align, false);
textBox(x0, y0-(n1+1)*size, size, size*n1, a90, g);
// second text
g.sym (x0, y0-((n1+3)+(n2+3))*size, size, t2, a0, align, false);
textBox(x0, y0-((n1+3)+(n2+3))*size, size, size*n2, a0, g);
g.sym (x0, y0-((n1+3)+(n2+2))*size, size, t2, a45, align, false);
textBox(x0, y0-((n1+3)+(n2+2))*size, size, size*n2, a45, g);
g.sym (x0, y0-((n1+3)+(n2+1))*size, size, t2, a90, align, false);
textBox(x0, y0-((n1+3)+(n2+1))*size, size, size*n2, a90, g);
// ---- align right
align = 1; //right
x0 = x0 + (Math.max(n1,n2)+1)*size;
// first text
g.sym (x0, y0-(n1+3)*size, size, t1, a0, align, false);
textBox(x0, y0-(n1+3)*size, size, size*n1, a0, g);
g.sym (x0, y0-(n1+2)*size, size, t1, a45, align, false);
textBox(x0, y0-(n1+2)*size, size, size*n1, a45, g);
g.sym (x0, y0-(n1+1)*size, size, t1, a90, align, false);
textBox(x0, y0-(n1+1)*size, size, size*n1, a90, g);
// second text
g.sym (x0, y0-((n1+3)+(n2+3))*size, size, t2, a0, align, false);
textBox(x0, y0-((n1+3)+(n2+3))*size, size, size*n2, a0, g);
g.sym (x0, y0-((n1+3)+(n2+2))*size, size, t2, a45, align, false);
textBox(x0, y0-((n1+3)+(n2+2))*size, size, size*n2, a45, g);
g.sym (x0, y0-((n1+3)+(n2+1))*size, size, t2, a90, align, false);
textBox(x0, y0-((n1+3)+(n2+1))*size, size, size*n2, a90, g);
// ---- thick pen ----
nPen++;
x0 = 0f;
y0 = y0 -((n1+3)+(n2+1))*size;
} // while pen <=2
// finished
g.end();
System.out.println("Written: \"test_all.plt\"");
//---- display a frame
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {new TestGraphLib().setVisible(true);}
});
} // main(args)
//<editor-fold defaultstate="collapsed" desc="textBox">
/** draw a box around an assumed text
* @param x0 the x-position of the text-box (lower left corner)
* @param y0 the y-position of the text-box (lower left corner)
* @param height the height of the box
* @param width the width of the box
* @param angle the angle at which the text is supposed to be printed
* @param g
* @return an instance of BoundingBox with the four corners of the box
*/
private static void textBox (float x0, float y0,
float height, float width, float angle,
GraphLib g) {
final double DEG_2_RAD = 0.017453292519943;
final double a0 = angle * DEG_2_RAD;
final double a1 = (angle + 90) * DEG_2_RAD;
Point p1 = new Point(), p2 = new Point(), p3 = new Point();
p1.x = x0 + width * (float)Math.cos(a0);
p1.y = y0 + width * (float)Math.sin(a0);
p2.x = p1.x + height * (float)Math.cos(a1);
p2.y = p1.y + height * (float)Math.sin(a1);
p3.x = x0 + height * (float)Math.cos(a1);
p3.y = y0 + height * (float)Math.sin(a1);
g.setLabel("TextBox w="+width+" h="+height);
g.moveToDrawTo(x0, y0, 0);
g.moveToDrawTo(p1.x, p1.y, 1);
g.moveToDrawTo(p2.x, p2.y, 1);
g.moveToDrawTo(p3.x, p3.y, 1);
g.setLabel("TextBox end");
g.moveToDrawTo(x0, y0, 1);
}
private static class Point {
public float x, y;
public Point(float x, float y) {this.x = x; this.y = y;}
public Point() {x = Float.NaN;y = Float.NaN;}
@Override
public String toString() {return "["+x+","+y+"]";}
}
//</editor-fold>
public TestGraphLib() { // constructor
jPanel1 = new javax.swing.JPanel() {
@Override public void paint(java.awt.Graphics g) {
super.paint(g);
java.awt.Graphics2D g2D = (java.awt.Graphics2D)g;
glib.paintDiagram(g2D, jPanel1.getSize(), dd, false);
} // paint
}; // JPanel
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jPanel1.setPreferredSize(new java.awt.Dimension(640,470));
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new java.awt.BorderLayout());
getContentPane().add(jPanel1);
this.setLocation(60, 30);
pack();
// - create a PltData instance
dd = new GraphLib.PltData();
// - create a GraphLib instance
GraphLib g = new GraphLib();
// - make a diagram, store it in "dd" but do not save to a disk file
try {g.start(dd, null, TEXT_WITH_FONTS);}
catch (Exception ex) {System.err.println(ex.getMessage()); g.end(); return;}
glib.textWithFonts = TEXT_WITH_FONTS;
dd.axisInfo = false;
float xAxl = 15, yAxl = 10, xOr = 4, yOr = 5;
float heightAx = (0.03f*Math.max(xAxl, yAxl));
// draw axes
try {g.axes(0f, 1f, 10f, 11f, xOr,yOr, xAxl,yAxl, heightAx,
false, true, true);}
catch (Exception ex) {System.err.println("Error: "+ex.getMessage()); g.end(); return;}
// draw a line
g.lineType(1);
double[] xd = {0.2,1.75}, yd = {10.5,10.8};
g.line(xd, yd);
// draw a text
g.setIsFormula(true);
g.sym(xOr+0.5*xAxl, yOr+1, heightAx, "P`CO`2'' = 10 bar", 45, 0, false);
// finished
g.end();
//---- now the "paint" method of jPanel1 will call method
// "graphLib.DiagrPaintUtility.paintDiagram"
// using the PltData instance "dd".
return;
} // Test() constructor
} | 19,231 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
TestReadDataLib.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibChemDiagr/other_stuff/Lib_tests/Test_ReadDataLib/src/testReadDataLib/TestReadDataLib.java | package testRreadDataLib;
import lib.kemi.readDataLib.ReadDataLib;
public class TestReadDataLib {
private static ReadDataLib rd;
private static final String nl = System.getProperty("line.separator");
public static void main(String[] args) {
String testFileName = "test.dat";
System.out.println("Test of \"ReadDataLib\":");
java.io.File inputFile = new java.io.File(testFileName);
if(!inputFile.exists()) {
// --- write a text file to read later
System.out.println("Writing file: \""+inputFile.getAbsolutePath()+"\"");
java.io.FileOutputStream fos = null;
java.io.Writer out = null;
try{
fos = new java.io.FileOutputStream(testFileName);
out = new java.io.BufferedWriter(new java.io.OutputStreamWriter(fos,"UTF8"));
} //try
catch (Exception e) {
System.err.print("Error: \""+e.toString()+"\""+nl+
"trying to write file: \""+testFileName+"\"");
try {if(out != null) {out.flush(); out.close();}}
catch (Exception e1) {}
return;
} //catch
try{
out.write(
"/ a test file:"+nl+
"/"+nl+
"\"text 1\",, text 3 ,"+nl+
" text 4 "+nl+nl+
" 1234567890 ,"+nl+nl+
" 3.1 ,4e-3"+nl+
"5.1E-5 6.0000000000001"+nl+
"Line with comment must have \"/\" after a comma or space / Comment 1"+nl+
"Line without a comment:/ not a comment"+nl+
",/ note that this line contains either an empty text string or a zero"+nl+
" /a line with only a comment: blank space and end-of-lines do not count"+nl+nl+
"/another line with only a comment"+nl+
"7.2,/ a comment after a comma"+nl+
"-1.e-3,4 5,3600,"+nl+
" a line with text /note: comments not considered for text lines"+nl+
"/this comment does not 'belong' to any data"+nl+
"-7 /almost the end"+nl+nl+
"one comment line"+nl+
" two comment /lines"+nl+
"three comment lines"+nl);
out.flush(); out.close(); fos.close();
}
catch (Exception ex) {
System.err.print("Error: \""+ex.toString()+"\""+nl+
"trying to write file: \""+testFileName+"\"");
try {if(out != null) {out.close();} if(fos != null) {fos.close();}}
catch (Exception e1) {}
return;
}
}
// --- read the test file created above
//testFileName = "test.dat";
System.out.println("Reading file: \""+(new java.io.File(testFileName).getAbsolutePath())+"\"");
try{rd = new ReadDataLib(new java.io.File(testFileName));}
catch (Exception ex) {System.err.println("Error: "+ex.toString()); return;}
try{System.out.println("Starting comment=\""+rd.readLine()+"\""+nl);}
catch (Exception ex) {System.err.println("Error: "+ex.toString()); return;}
System.out.flush();
try{System.out.println("Four texts: \""+rd.readA()+"\", \""+rd.readA()+"\", \""+rd.readA()+"\", \""+rd.readA()+"\"");}
catch (Exception ex) {System.err.println("Error: "+ex.toString()); return;}
System.out.println(" comment=\""+rd.dataLineComment.toString()+"\""+nl);
System.out.flush();
try{System.out.println("Next 5 data: "+rd.readI()+", "+
rd.readR()+", "+rd.readR()+", "+
rd.readR()+", "+rd.readR());}
catch (Exception ex) {System.err.println("Error: "+ex.toString()); return;}
System.out.flush();
try{System.out.println("Text before comment: \""+rd.readA()+"\"");}
catch (Exception ex) {System.err.println("Error: "+ex.toString()); return;}
System.out.println(" comment=\""+rd.dataLineComment.toString()+"\""+nl);
System.out.flush();
try{System.out.println("No comment: \""+rd.readA()+"\"");}
catch (Exception ex) {System.err.println("Error: "+ex.toString()); return;}
System.out.println(" comment=\""+rd.dataLineComment.toString()+"\""+nl);
System.out.flush();
try{System.out.println("Empty data: "+rd.readR());}
catch (Exception ex) {System.err.println("Error: "+ex.toString()); return;}
System.out.println(" comment=\""+rd.dataLineComment.toString()+"\""+nl);
System.out.flush();
try{System.out.println("Next value: "+rd.readR());}
catch (Exception ex) {System.err.println("Error: "+ex.toString()); return;}
System.out.println(" comment=\""+rd.dataLineComment.toString()+"\""+nl);
System.out.flush();
try{System.out.println("A double: "+rd.readR()+" (skipping the other values in this line)");}
catch (Exception ex) {System.err.println("Error: "+ex.toString()); return;}
System.out.println(" comment=\""+rd.dataLineComment.toString()+"\""+nl);
System.out.flush();
try{System.out.println("Read a line: \""+rd.readLine()+"\"");}
catch (Exception ex) {System.err.println("Error: "+ex.toString()); return;}
System.out.println(" comment=\""+rd.dataLineComment.toString()+"\""+nl);
System.out.flush();
try{System.out.println("Next value: "+rd.readR());}
catch (Exception ex) {System.err.println("Error: "+ex.toString()); return;}
System.out.println(" comment=\""+rd.dataLineComment.toString()+"\""+nl);
System.out.flush();
StringBuilder t = new StringBuilder();
while(true) {
try{t.append(rd.readLine());t.append(nl);}
catch (ReadDataLib.DataEofException ex) {break;}
catch (Exception ex) {ex.printStackTrace(); break;}
}
System.out.println("Last lines=\""+t.toString()+"\"");
System.out.println(" comment=\""+rd.dataLineComment.toString()+"\""+nl);
System.out.flush();
System.out.println("Finished.");
try{rd.close();}
catch (Exception ex) {ex.printStackTrace();}
} // main(args)
} | 6,372 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
TestAxes.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/LibChemDiagr/other_stuff/Lib_tests/Test_Axes/src/testAxes/TestAxes.java | package testAxes;
import lib.kemi.graph_lib.DiagrPaintUtility;
import lib.kemi.graph_lib.GraphLib;
/**
* @author Ignasi Puigdomenech
*/
public class TestAxes extends javax.swing.JFrame {
protected static final String progName = "Test Axes";
protected static TestAxes frame;
protected static java.awt.Dimension windowSize;
protected static java.awt.Dimension screenSize;
static java.util.Locale engl = java.util.Locale.ENGLISH;
java.io.PrintStream errPrintStream =
new java.io.PrintStream(
new errFilteredStream(
new java.io.ByteArrayOutputStream()));
java.io.PrintStream outPrintStream =
new java.io.PrintStream(
new outFilteredStream(
new java.io.ByteArrayOutputStream()));
GraphLib.PltData dd;
float tHeight;
float xMin; float xMax; float yMin; float yMax;
boolean logX = false; boolean logY = false; boolean frameAxes = false;
//<editor-fold defaultstate="collapsed" desc="Constructor">
/** Creates new form TestAxes */
public TestAxes() {
initComponents();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
frame = this;
//close window on ESC key
javax.swing.Action escapeAction = new javax.swing.AbstractAction() {
public void actionPerformed(java.awt.event.ActionEvent e) {
quitTestAxes(); //close the frame here
}};
javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE");
getRootPane().getActionMap().put("ESCAPE", escapeAction);
//Title
frame.setTitle("Test Axes");
windowSize = frame.getSize();
screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int left; int top;
left = Math.max(55, (screenSize.width - windowSize.width ) / 2);
top = Math.max(10, (screenSize.height - windowSize.height) / 2);
frame.setLocation(Math.min(screenSize.width-100, left),
Math.min(screenSize.height-100, top));
java.awt.Font f = new java.awt.Font("monospaced", java.awt.Font.PLAIN, 12);
jTextAreaA.setFont(f);
jTabbedPane.setEnabledAt(1, false);
jTabbedPane.setEnabledAt(2, false);
jMenuStartOver.setEnabled(false);
jScrollBarHeight.setFocusable(true);
tHeight = 1.f;
jScrollBarHeight.setValue(Math.round((float)(10d*tHeight)));
jLabelStatus.setText("wating...");
System.setOut(outPrintStream); // catches System.out messages
System.setErr(errPrintStream); // catches error messages
frame.setVisible(true);
} // TestAxes()
//</editor-fold>
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jTabbedPane = new javax.swing.JTabbedPane();
jPanelParameters = new javax.swing.JPanel();
jTextFieldYmin = new javax.swing.JTextField();
jLabelYmin = new javax.swing.JLabel();
jTextFieldXmin = new javax.swing.JTextField();
jLabelXmin = new javax.swing.JLabel();
jCheckLogX = new javax.swing.JCheckBox();
jLabelHeight = new javax.swing.JLabel();
jCheckLogY = new javax.swing.JCheckBox();
jCheckFrame = new javax.swing.JCheckBox();
jLabelHD = new javax.swing.JLabel();
jScrollBarHeight = new javax.swing.JScrollBar();
jLabelXmax = new javax.swing.JLabel();
jLabelYmax = new javax.swing.JLabel();
jTextFieldXmax = new javax.swing.JTextField();
jTextFieldYmax = new javax.swing.JTextField();
jButtonOK = new javax.swing.JButton();
jButtonTestLine = new javax.swing.JButton();
jScrollPaneMessg = new javax.swing.JScrollPane();
jTextAreaA = new javax.swing.JTextArea();
jPanelDiagram = new javax.swing.JPanel()
{
@Override
public void paint(java.awt.Graphics g)
{
super.paint(g);
paintDiagrPanel(g);
}
};
jPanelStatusBar = new javax.swing.JPanel();
jLabelStatus = new javax.swing.JLabel();
jMenuBar = new javax.swing.JMenuBar();
jMenuFile = new javax.swing.JMenu();
jMenuStartOver = new javax.swing.JMenuItem();
jMenuFileXit = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jTabbedPane.setTabLayoutPolicy(javax.swing.JTabbedPane.SCROLL_TAB_LAYOUT);
jTabbedPane.setPreferredSize(new java.awt.Dimension(268, 249));
jTextFieldYmin.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
jTextFieldYmin.setText("7");
jTextFieldYmin.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextFieldYminFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jTextFieldYminFocusLost(evt);
}
});
jTextFieldYmin.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTextFieldYminKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextFieldYminKeyTyped(evt);
}
});
jLabelYmin.setLabelFor(jTextFieldYmin);
jLabelYmin.setText("<html>Y-min</html>");
jLabelYmin.setEnabled(false);
jTextFieldXmin.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
jTextFieldXmin.setText("7");
jTextFieldXmin.setToolTipText("<html>\nThe temperature is needed either to calculate Debye-Hückel constants<br>\nin activity coefficient models, or to calculate Eh values<br>\nfrom pe: Eh = pe*(ln(10)*R*T)/F<br>\nValue must be between 0 and 300 (in Celsius)</html>");
jTextFieldXmin.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextFieldXminFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jTextFieldXminFocusLost(evt);
}
});
jTextFieldXmin.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTextFieldXminKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextFieldXminKeyTyped(evt);
}
});
jLabelXmin.setLabelFor(jTextFieldXmin);
jLabelXmin.setText("<html>X-min</html>");
jLabelXmin.setEnabled(false);
jCheckLogX.setMnemonic(java.awt.event.KeyEvent.VK_L);
jCheckLogX.setSelected(true);
jCheckLogX.setText("<html><u>L</u>og x-axis</html>");
jLabelHeight.setText("<html>Height of text in diagram:</html>");
jCheckLogY.setMnemonic(java.awt.event.KeyEvent.VK_I);
jCheckLogY.setSelected(true);
jCheckLogY.setText("<html>log y-ax<u>I</u>s</html>");
jCheckFrame.setMnemonic(java.awt.event.KeyEvent.VK_A);
jCheckFrame.setText("<html>fr<u>A</u>me</html>");
jLabelHD.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabelHD.setText("1.0");
jLabelHD.setMaximumSize(new java.awt.Dimension(15, 14));
jLabelHD.setMinimumSize(new java.awt.Dimension(15, 14));
jLabelHD.setPreferredSize(new java.awt.Dimension(15, 14));
jScrollBarHeight.setMaximum(101);
jScrollBarHeight.setMinimum(3);
jScrollBarHeight.setOrientation(javax.swing.JScrollBar.HORIZONTAL);
jScrollBarHeight.setValue(10);
jScrollBarHeight.setVisibleAmount(1);
jScrollBarHeight.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jScrollBarHeightFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jScrollBarHeightFocusLost(evt);
}
});
jScrollBarHeight.addAdjustmentListener(new java.awt.event.AdjustmentListener() {
public void adjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {
jScrollBarHeightAdjustmentValueChanged(evt);
}
});
jLabelXmax.setLabelFor(jTextFieldXmin);
jLabelXmax.setText("<html>x-Max</html>");
jLabelXmax.setEnabled(false);
jLabelYmax.setLabelFor(jTextFieldYmin);
jLabelYmax.setText("<html>y-Max</html>");
jLabelYmax.setEnabled(false);
jTextFieldXmax.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
jTextFieldXmax.setText("2");
jTextFieldXmax.setToolTipText("<html>\nThe temperature is needed either to calculate Debye-Hückel constants<br>\nin activity coefficient models, or to calculate Eh values<br>\nfrom pe: Eh = pe*(ln(10)*R*T)/F<br>\nValue must be between 0 and 300 (in Celsius)</html>");
jTextFieldXmax.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextFieldXmaxFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jTextFieldXmaxFocusLost(evt);
}
});
jTextFieldXmax.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTextFieldXmaxKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextFieldXmaxKeyTyped(evt);
}
});
jTextFieldYmax.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
jTextFieldYmax.setText("2");
jTextFieldYmax.setToolTipText("<html>\nThe temperature is needed either to calculate Debye-Hückel constants<br>\nin activity coefficient models, or to calculate Eh values<br>\nfrom pe: Eh = pe*(ln(10)*R*T)/F<br>\nValue must be between 0 and 300 (in Celsius)</html>");
jTextFieldYmax.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextFieldYmaxFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jTextFieldYmaxFocusLost(evt);
}
});
jTextFieldYmax.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTextFieldYmaxKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextFieldYmaxKeyTyped(evt);
}
});
jButtonOK.setMnemonic(java.awt.event.KeyEvent.VK_O);
jButtonOK.setText("OK");
jButtonOK.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonOKActionPerformed(evt);
}
});
jButtonTestLine.setMnemonic(java.awt.event.KeyEvent.VK_T);
jButtonTestLine.setText("Test dash line clipping");
jButtonTestLine.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonTestLineActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanelParametersLayout = new javax.swing.GroupLayout(jPanelParameters);
jPanelParameters.setLayout(jPanelParametersLayout);
jPanelParametersLayout.setHorizontalGroup(
jPanelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelParametersLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanelParametersLayout.createSequentialGroup()
.addComponent(jCheckLogX, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jCheckFrame, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(201, 201, 201))
.addGroup(jPanelParametersLayout.createSequentialGroup()
.addGroup(jPanelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelParametersLayout.createSequentialGroup()
.addComponent(jLabelHeight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(3, 3, 3)
.addComponent(jLabelHD, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollBarHeight, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanelParametersLayout.createSequentialGroup()
.addComponent(jCheckLogY, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButtonOK))
.addGroup(jPanelParametersLayout.createSequentialGroup()
.addGroup(jPanelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanelParametersLayout.createSequentialGroup()
.addComponent(jLabelYmin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextFieldYmin))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanelParametersLayout.createSequentialGroup()
.addComponent(jLabelXmin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextFieldXmin, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addGroup(jPanelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelParametersLayout.createSequentialGroup()
.addComponent(jLabelYmax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextFieldYmax, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanelParametersLayout.createSequentialGroup()
.addComponent(jLabelXmax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(4, 4, 4)
.addComponent(jTextFieldXmax, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGap(116, 116, 116)))
.addComponent(jButtonTestLine))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelParametersLayout.setVerticalGroup(
jPanelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelParametersLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelXmin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextFieldXmin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelXmax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextFieldXmax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelYmin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextFieldYmin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelYmax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextFieldYmax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(13, 13, 13)
.addGroup(jPanelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelHeight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelHD, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollBarHeight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(10, 10, 10)
.addGroup(jPanelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jCheckFrame, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButtonOK, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanelParametersLayout.createSequentialGroup()
.addComponent(jCheckLogX, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jCheckLogY, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(48, 48, 48)
.addComponent(jButtonTestLine)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jTabbedPane.addTab("Parameters", jPanelParameters);
jScrollPaneMessg.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
jScrollPaneMessg.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
jTextAreaA.setBackground(new java.awt.Color(255, 255, 204));
jTextAreaA.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTextAreaAKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextAreaAKeyTyped(evt);
}
});
jScrollPaneMessg.setViewportView(jTextAreaA);
jTabbedPane.addTab("Messages", jScrollPaneMessg);
jPanelDiagram.setBackground(new java.awt.Color(255, 255, 255));
javax.swing.GroupLayout jPanelDiagramLayout = new javax.swing.GroupLayout(jPanelDiagram);
jPanelDiagram.setLayout(jPanelDiagramLayout);
jPanelDiagramLayout.setHorizontalGroup(
jPanelDiagramLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 359, Short.MAX_VALUE)
);
jPanelDiagramLayout.setVerticalGroup(
jPanelDiagramLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 224, Short.MAX_VALUE)
);
jTabbedPane.addTab("Diagram", jPanelDiagram);
jPanelStatusBar.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jLabelStatus.setText("01234567890");
javax.swing.GroupLayout jPanelStatusBarLayout = new javax.swing.GroupLayout(jPanelStatusBar);
jPanelStatusBar.setLayout(jPanelStatusBarLayout);
jPanelStatusBarLayout.setHorizontalGroup(
jPanelStatusBarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelStatusBarLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabelStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 325, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(25, Short.MAX_VALUE))
);
jPanelStatusBarLayout.setVerticalGroup(
jPanelStatusBarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelStatus)
);
jMenuFile.setMnemonic(java.awt.event.KeyEvent.VK_F);
jMenuFile.setText("File");
jMenuStartOver.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.ALT_MASK));
jMenuStartOver.setText("Start over");
jMenuStartOver.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuStartOverActionPerformed(evt);
}
});
jMenuFile.add(jMenuStartOver);
jMenuFileXit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK));
jMenuFileXit.setText("Exit");
jMenuFileXit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuFileXitActionPerformed(evt);
}
});
jMenuFile.add(jMenuFileXit);
jMenuBar.add(jMenuFile);
setJMenuBar(jMenuBar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 364, Short.MAX_VALUE)
.addComponent(jPanelStatusBar, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jTabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanelStatusBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
//<editor-fold defaultstate="collapsed" desc="Events">
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
quitTestAxes();
}//GEN-LAST:event_formWindowClosing
private void jMenuFileXitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuFileXitActionPerformed
quitTestAxes();
}//GEN-LAST:event_jMenuFileXitActionPerformed
private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
int w = Math.round((float)windowSize.getWidth());
int h = Math.round((float)windowSize.getHeight());
if(this.getHeight()<h){this.setSize(this.getWidth(), h);}
if(this.getWidth()<w){this.setSize(w,this.getHeight());}
if(jTabbedPane.getWidth()>this.getWidth()) {jTabbedPane.setSize(this.getWidth(), jTabbedPane.getHeight());}
}//GEN-LAST:event_formComponentResized
private void jTextAreaAKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextAreaAKeyTyped
evt.consume();
}//GEN-LAST:event_jTextAreaAKeyTyped
private void jTextAreaAKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextAreaAKeyPressed
int ctrl = java.awt.event.InputEvent.CTRL_DOWN_MASK;
if (((evt.getModifiersEx() & ctrl) == ctrl) &&
(evt.getKeyCode() == java.awt.event.KeyEvent.VK_V)) {evt.consume();}
if(evt.getKeyChar() == java.awt.event.KeyEvent.VK_DELETE) {evt.consume();}
if(evt.getKeyChar() == java.awt.event.KeyEvent.VK_BACK_SPACE) {evt.consume();}
}//GEN-LAST:event_jTextAreaAKeyPressed
private void jScrollBarHeightAdjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {//GEN-FIRST:event_jScrollBarHeightAdjustmentValueChanged
jLabelHD.setText(String.valueOf((float)jScrollBarHeight.getValue()/10f));
}//GEN-LAST:event_jScrollBarHeightAdjustmentValueChanged
private void jScrollBarHeightFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jScrollBarHeightFocusGained
jScrollBarHeight.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0,0,0)));
}//GEN-LAST:event_jScrollBarHeightFocusGained
private void jScrollBarHeightFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jScrollBarHeightFocusLost
jScrollBarHeight.setBorder(null);
}//GEN-LAST:event_jScrollBarHeightFocusLost
private void jTextFieldYminKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldYminKeyTyped
if (!Character.isDigit(evt.getKeyChar()) &&
evt.getKeyChar() != 'e' && evt.getKeyChar() != 'E' &&
evt.getKeyChar() != '-' && evt.getKeyChar() != '.') {evt.consume();}
}//GEN-LAST:event_jTextFieldYminKeyTyped
private void jTextFieldYminFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldYminFocusLost
validateYmin();
}//GEN-LAST:event_jTextFieldYminFocusLost
private void jTextFieldYminKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldYminKeyPressed
if(evt.getKeyChar() == java.awt.event.KeyEvent.VK_ENTER) {
validateYmin();}
}//GEN-LAST:event_jTextFieldYminKeyPressed
private void jTextFieldXminKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldXminKeyPressed
if(evt.getKeyChar() == java.awt.event.KeyEvent.VK_ENTER) {
validateXmin();}
}//GEN-LAST:event_jTextFieldXminKeyPressed
private void jTextFieldXminFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldXminFocusLost
validateXmin();
}//GEN-LAST:event_jTextFieldXminFocusLost
private void jTextFieldXminKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldXminKeyTyped
if (!Character.isDigit(evt.getKeyChar()) &&
evt.getKeyChar() != '-' &&
evt.getKeyChar() != 'e' && evt.getKeyChar() != 'E' &&
evt.getKeyChar() != '.') {evt.consume();}
}//GEN-LAST:event_jTextFieldXminKeyTyped
private void jTextFieldXmaxFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldXmaxFocusLost
validateXmax();
}//GEN-LAST:event_jTextFieldXmaxFocusLost
private void jTextFieldXmaxKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldXmaxKeyPressed
if(evt.getKeyChar() == java.awt.event.KeyEvent.VK_ENTER) {
validateXmax();}
}//GEN-LAST:event_jTextFieldXmaxKeyPressed
private void jTextFieldXmaxKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldXmaxKeyTyped
if (!Character.isDigit(evt.getKeyChar()) &&
evt.getKeyChar() != 'e' && evt.getKeyChar() != 'E' &&
evt.getKeyChar() != '-' && evt.getKeyChar() != '.') {evt.consume();}
}//GEN-LAST:event_jTextFieldXmaxKeyTyped
private void jTextFieldYmaxFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldYmaxFocusLost
validateYmax();
}//GEN-LAST:event_jTextFieldYmaxFocusLost
private void jTextFieldYmaxKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldYmaxKeyPressed
if(evt.getKeyChar() == java.awt.event.KeyEvent.VK_ENTER) {
validateYmax();}
}//GEN-LAST:event_jTextFieldYmaxKeyPressed
private void jTextFieldYmaxKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldYmaxKeyTyped
if (!Character.isDigit(evt.getKeyChar()) &&
evt.getKeyChar() != 'e' && evt.getKeyChar() != 'E' &&
evt.getKeyChar() != '-' && evt.getKeyChar() != '.') {evt.consume();}
}//GEN-LAST:event_jTextFieldYmaxKeyTyped
private void jButtonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOKActionPerformed
xMin = Float.parseFloat(jTextFieldXmin.getText());
xMax = Float.parseFloat(jTextFieldXmax.getText());
yMin = Float.parseFloat(jTextFieldYmin.getText());
yMax = Float.parseFloat(jTextFieldYmax.getText());
tHeight = jScrollBarHeight.getValue()/10.f;
tHeight = Math.min(10.f,Math.max(tHeight, 0.3f));
if(jCheckFrame.isSelected()) {frameAxes = true;} else {frameAxes = false;}
if(jCheckLogX.isSelected()) {logX = true;} else {logX = false;}
if(jCheckLogY.isSelected()) {logY = true;} else {logY = false;}
jLabelStatus.setText("plotting...");
drawPlot();
jTabbedPane.setEnabledAt(2, true);
jTabbedPane.setSelectedComponent(jPanelDiagram);
jMenuStartOver.setEnabled(true);
jLabelStatus.setText("waiting...");
}//GEN-LAST:event_jButtonOKActionPerformed
private void jMenuStartOverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuStartOverActionPerformed
jMenuStartOver.setEnabled(false);
jTabbedPane.setEnabledAt(2, false);
jTabbedPane.setSelectedComponent(jPanelParameters);
frame.requestFocus();
}//GEN-LAST:event_jMenuStartOverActionPerformed
private void jTextFieldYminFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldYminFocusGained
jTextFieldYmin.setSelectionStart(0);
jTextFieldYmin.setSelectionEnd(jTextFieldYmin.getText().length());
}//GEN-LAST:event_jTextFieldYminFocusGained
private void jTextFieldYmaxFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldYmaxFocusGained
jTextFieldYmax.setSelectionStart(0);
jTextFieldYmax.setSelectionEnd(jTextFieldYmax.getText().length());
}//GEN-LAST:event_jTextFieldYmaxFocusGained
private void jTextFieldXminFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldXminFocusGained
jTextFieldXmin.setSelectionStart(0);
jTextFieldXmin.setSelectionEnd(jTextFieldXmin.getText().length());
}//GEN-LAST:event_jTextFieldXminFocusGained
private void jTextFieldXmaxFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldXmaxFocusGained
jTextFieldXmax.setSelectionStart(0);
jTextFieldXmax.setSelectionEnd(jTextFieldXmax.getText().length());
}//GEN-LAST:event_jTextFieldXmaxFocusGained
private void jButtonTestLineActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonTestLineActionPerformed
jLabelStatus.setText("plotting...");
drawTest();
jTabbedPane.setEnabledAt(2, true);
jTabbedPane.setSelectedComponent(jPanelDiagram);
jMenuStartOver.setEnabled(true);
jLabelStatus.setText("waiting...");
}//GEN-LAST:event_jButtonTestLineActionPerformed
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="diverse Methods">
private void quitTestAxes() {
this.dispose();
return;
} // quitTestAxes()
private void validateYmin() {
try{yMin = Float.parseFloat(jTextFieldYmin.getText());
jTextFieldYmin.setText(Float.toString(yMin));} //try
catch (NumberFormatException nfe) {
javax.swing.JOptionPane.showMessageDialog(this,"Wrong numeric format\n"+
"\nPlease enter a floating point number.",
progName, javax.swing.JOptionPane.WARNING_MESSAGE);
jTextFieldYmin.setText(Float.toString(yMin));
jTextFieldYmin.requestFocus();} //catch
} // validateYmin()
private void validateXmin() {
try{xMin = Float.parseFloat(jTextFieldXmin.getText());
jTextFieldXmin.setText(Float.toString(xMin));} //try
catch (NumberFormatException nfe) {
javax.swing.JOptionPane.showMessageDialog(this,"Wrong numeric format\n"+
"\nPlease enter a floating point number.",
progName, javax.swing.JOptionPane.WARNING_MESSAGE);
jTextFieldXmin.setText(Float.toString(xMin));
jTextFieldXmin.requestFocus();} //catch
} // validateXmin()
private void validateYmax() {
try{yMax = Float.parseFloat(jTextFieldYmax.getText());
jTextFieldYmax.setText(Float.toString(yMax));} //try
catch (NumberFormatException nfe) {
javax.swing.JOptionPane.showMessageDialog (this,"Wrong numeric format\n"+
"\nPlease enter a floating point number.",
progName, javax.swing.JOptionPane.WARNING_MESSAGE);
jTextFieldYmax.setText(Float.toString(yMax));
jTextFieldYmax.requestFocus();} //catch
} // validateYmax()
private void validateXmax() {
try{xMax = Float.parseFloat(jTextFieldXmax.getText());
jTextFieldXmax.setText(Float.toString(xMax));} //try
catch (NumberFormatException nfe) {
javax.swing.JOptionPane.showMessageDialog (this,"Wrong numeric format\n"+
"\nPlease enter a floating point number.",
progName, javax.swing.JOptionPane.WARNING_MESSAGE);
jTextFieldXmax.setText(Float.toString(xMax));
jTextFieldXmax.requestFocus();} //catch
} // validateXmax()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="drawTest()">
protected void drawTest() {
double[] xData = new double[201]; double[] yData = new double[xData.length];
for(int i=0; i < xData.length; i++) {
xData[i]= i*5; yData[i] = Math.sin(Math.toRadians(xData[i]));
}
// -------------------------------------------------------------------
// Draw Axes
//---- create a DiagrData instance
dd = new GraphLib.PltData();
//---- create a GraphLib instance
GraphLib g = new GraphLib();
try{g.start(dd, new java.io.File("test_lines.plt"), true);}
catch (GraphLib.OpenPlotFileException ex) {System.err.println("Error "+ex.toString());}
dd.axisInfo = false;
yMin = -1.1f; yMax = 0.6f;
xMin = 0; xMax = 1000; logX=false; logY=false; frameAxes = true;
float xAxl = 12; float yAxl = 5;
float xOr = 3; float yOr = 2;
float heightAx = (0.03f*Math.max(xAxl, yAxl));
g.setIsFormula(false);
g.sym(xOr+0.5*xAxl, yOr+1, heightAx, "°±µ·ºΔμ•∆", -45, 1, false);
g.setIsFormula(true);
// draw axes
try{g.axes(xMin, xMax, yMin, yMax,
xOr,yOr, xAxl,yAxl, heightAx,
logX, logY, frameAxes);}
catch (Exception ex) {
System.err.println("Error: "+ex.getMessage());
}
g.lineType(1);
//double[] xd = {-20d,200d};double[] yd = {0d,1d};
double[] xd = new double[500];
double[] yd = new double[xd.length];
for(int i=0; i<xd.length; i++) {xd[i]=i*1000/xd.length;}
for(int i=0; i<yd.length; i++) {yd[i]=Math.sin(Math.toRadians(xd[i]));}
g.line(xd, yd);
g.moveToDrawTo(xOr-heightAx*0.7071f, yOr+heightAx*0.7071f, 0);
g.moveToDrawTo(xOr, yOr, 1);
g.moveToDrawTo(xOr+heightAx*6f*0.7071f, yOr+heightAx*6f*0.7071f, 1);
g.moveToDrawTo(xOr+heightAx*5f*0.7071f, yOr+heightAx*7f*0.7071f, 1);
g.setIsFormula(true);
g.sym(xOr, yOr, heightAx, " M", 135, 1, false);
yMin = 0.7f; yMax = 1.1f;
yOr = yOr+yAxl+1;
yAxl = 2;
// draw axes
try{g.axes(xMin, xMax, yMin, yMax,
xOr,yOr, xAxl,yAxl, heightAx,
logX, logY, frameAxes);}
catch (Exception ex) {
System.err.println("Error: "+ex.getMessage());
}
g.lineType(4);
g.line(xd, yd);
// -------------------------------------------------------------------
// Finished
g.end();
} //drawTest()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="drawPlot()">
protected void drawPlot() {
// -------------------------------------------------------------------
// Draw Axes
//---- create a DiagrData instance
dd = new GraphLib.PltData();
//---- create a GraphLib instance
GraphLib g = new GraphLib();
try{g.start(dd, new java.io.File("test_axes.plt"), true);}
catch (GraphLib.OpenPlotFileException ex) {System.err.println("Error "+ex.toString());}
dd.axisInfo = false;
g.setIsFormula(true);
float xAxl = 15; float yAxl = 10;
float xOr = 4; float yOr = 3;
float heightAx = (0.03f*Math.max(xAxl, yAxl)) * tHeight;
/*g.moveToDrawTo(xOr-heightAx*0.7071f, yOr+heightAx*0.7071f, 0);
g.moveToDrawTo(xOr, yOr, 1);
g.moveToDrawTo(xOr+heightAx*8f*0.7071f, yOr+heightAx*8f*0.7071f, 1);
g.moveToDrawTo(xOr+heightAx*7f*0.7071f, yOr+heightAx*9f*0.7071f, 1);
g.sym(xOr, yOr, heightAx, " M", 45, 0, false);*/
g.sym(xOr+0.5*xAxl, yOr+1, heightAx, "P`CO`2'' CO3-2", 80, 0, false);
// draw axes
try{g.axes(xMin, xMax, yMin, yMax,
xOr,yOr, xAxl,yAxl, heightAx,
logX, logY, frameAxes);}
catch (Exception ex) {
System.err.println("Error: "+ex.getMessage());
}
// -------------------------------------------------------------------
// Finished
g.end();
} //drawPlot()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="paintDiagrPanel">
private void paintDiagrPanel(java.awt.Graphics g) {
java.awt.Graphics2D g2D = (java.awt.Graphics2D)g;
DiagrPaintUtility dpu = new DiagrPaintUtility();
dpu.paintDiagram(g2D, jPanelDiagram.getSize(), dd, false);
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="main">
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
// get SystemLookAndFeel
try { javax.swing.UIManager.setLookAndFeel(
javax.swing.UIManager.getSystemLookAndFeelClassName());}
catch (Exception ex) {}
// show the main window
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
TestAxes sed = new TestAxes();//.setVisible(true);
// in the main class the following is defined:
// private static TestAxes frame;
// in the constructor TestAxes() there is following statement:
// frame = this;
}
});
} // main(args[])
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="FilteredStreams">
class errFilteredStream extends java.io.FilterOutputStream {
public errFilteredStream(java.io.OutputStream aStream) {
super(aStream);
} // constructor
@Override
public void write(byte b[]) throws java.io.IOException {
String aString = new String(b);
jTabbedPane.setEnabledAt(1, true);
jTabbedPane.setSelectedComponent(jScrollPaneMessg);
jTextAreaA.append(aString);
jTextAreaA.setSelectionStart(Integer.MAX_VALUE);
}
@Override
public void write(byte b[], int off, int len) throws java.io.IOException {
String aString = new String(b , off , len);
jTabbedPane.setEnabledAt(1, true);
jTabbedPane.setSelectedComponent(jScrollPaneMessg);
jTextAreaA.append(aString);
jTextAreaA.setSelectionStart(Integer.MAX_VALUE);
} // write
} // class errFilteredStream
class outFilteredStream extends java.io.FilterOutputStream {
public outFilteredStream(java.io.OutputStream aStream) {
super(aStream);
} // constructor
@Override
public void write(byte b[]) throws java.io.IOException {
String aString = new String(b);
jTabbedPane.setEnabledAt(1, true);
jTextAreaA.append(aString);
jTextAreaA.setSelectionStart(Integer.MAX_VALUE);
}
@Override
public void write(byte b[], int off, int len) throws java.io.IOException {
String aString = new String(b , off , len);
jTabbedPane.setEnabledAt(1, true);
jTextAreaA.append(aString);
jTextAreaA.setSelectionStart(Integer.MAX_VALUE);
} // write
} // class outFilteredStream
//</editor-fold>
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButtonOK;
private javax.swing.JButton jButtonTestLine;
private javax.swing.JCheckBox jCheckFrame;
private javax.swing.JCheckBox jCheckLogX;
private javax.swing.JCheckBox jCheckLogY;
private javax.swing.JLabel jLabelHD;
private javax.swing.JLabel jLabelHeight;
private javax.swing.JLabel jLabelStatus;
private javax.swing.JLabel jLabelXmax;
private javax.swing.JLabel jLabelXmin;
private javax.swing.JLabel jLabelYmax;
private javax.swing.JLabel jLabelYmin;
private javax.swing.JMenuBar jMenuBar;
private javax.swing.JMenu jMenuFile;
private javax.swing.JMenuItem jMenuFileXit;
private javax.swing.JMenuItem jMenuStartOver;
private javax.swing.JPanel jPanelDiagram;
private javax.swing.JPanel jPanelParameters;
private javax.swing.JPanel jPanelStatusBar;
private javax.swing.JScrollBar jScrollBarHeight;
private javax.swing.JScrollPane jScrollPaneMessg;
private javax.swing.JTabbedPane jTabbedPane;
private javax.swing.JTextArea jTextAreaA;
private javax.swing.JTextField jTextFieldXmax;
private javax.swing.JTextField jTextFieldXmin;
private javax.swing.JTextField jTextFieldYmax;
private javax.swing.JTextField jTextFieldYmin;
// End of variables declaration//GEN-END:variables
} // class TestAxes
| 45,436 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
PlotPS.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/PlotPS/src/plotPS/PlotPS.java | package plotPS;
/** Convert a plt-file to PostScript-format.
* The input file is assumed to be in the system-dependent default
* character encoding. The PS file is written in "ISO-8859-1" character
* encoding (ISO Latin Alphabet No. 1).
*
* If an error occurs, a message is displayed to the console, and
* unless the command line argument -nostop is given, a message box
* displaying the error is also produced.
*
* Copyright (C) 2015-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class PlotPS {
private static final String progName = "PlotPS";
private static final String VERS = "2020-June-12";
private static boolean started = false;
/** print debug information? */
private boolean dbg = false;
/** if true the program does display dialogs with warnings or errors */
private boolean doNotStop = false;
/** the plot file to be converted */
private java.io.File pltFile;
/** the ps file name (the converted plt file) */
private String psFile_name;
/** the ps file (the converted plt file) */
private java.io.File psFile;
/** has the file conversion finished ? */
private boolean finished = false;
private java.io.BufferedReader bufReader;
private java.io.BufferedWriter outputFile;
/** has an error occurred? if so, delete the output file */
private boolean delete = false;
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
private static final String SLASH = java.io.File.separator;
private static final String DASH_LINE = "- - - - - -";
private static final java.util.Locale engl = java.util.Locale.ENGLISH;
private String[] colours = new String[11];
/** line widths: normal (0.282 mm), thick, very-thin, thin */
private final double[] WIDTHS = {2.82, 6.35, 0.07, 1.06}; // units: 100 = 1 cm
// -- PS things --
private boolean eps = false;
private BoundingBox boundingBox;
/** line widths: 0 = normal, 1 = thick, 2 = very-thin, 3 = thin */
private int penNow =0;
private int colorNow =0;
/** line widths: 0 = normal, 1 = thick, 2 = very-thin, 3 = thin */
private int penOld =-1;
private int colorOld =-1;
private int pathCounter = 0;
//TODO: change zx and zy to shiftX and shiftY
private double scaleX, scaleY, zx, zy;
private double xNow=-Double.MAX_VALUE, yNow=-Double.MAX_VALUE;
private double x1st=-Double.MAX_VALUE, y1st=-Double.MAX_VALUE;
/** -1 = start of program;<br>
* 0 = no drawing performed yet;<br>
* 1 = some move performed;<br>
* 2 = some move/line-draw performed. */
private int newPath = -1;
// -- for text strings --
private int fontSize = Integer.MIN_VALUE;
private int fontSizeOld = -1;
private boolean oldBold = false;
// -- data from the command-line arguments
private boolean psHeader = true;
/** Colours: 0=black/white; 1=Standard palette; 2="Spana" palette. */
private int psColors = 1;
private boolean psPortrait = true;
/** Font type: 0=draw; 1=Times; 2=Helvetica; 3=Courier. */
private int psFont = 2;
/** 0=Vector graphics; 1=Times-Roman; 2=Helvetica; 3=Courier. */
private final String[] FONTS = {"Vector graphics", "Times-Roman", "Helvetica", "Courier"};
private int psSizeX = 100;
private int psSizeY = 100;
private double psMarginB = 0;
private double psMarginL = 0;
//<editor-fold defaultstate="collapsed" desc="class BoundingBox">
private static class BoundingBox {
public double xMn,yMn, xMx,yMx;
public BoundingBox() {
xMn = Double.MAX_VALUE;
yMn = Double.MAX_VALUE;
xMx = -Double.MAX_VALUE;
yMx = -Double.MAX_VALUE;
}
@Override
public String toString() {
return "["+xMn+","+yMn+" ; "+xMx+","+yMx+"]";
}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="main: calls the Constructor">
/** @param args the command line arguments */
public static void main(String[] args) {
boolean h = false;
boolean doNotS = false, debg = false;
String msg = "GRAPHIC \"PostScript\" UTILITY "+VERS+nl+
"============================== (Unicode UTF-8 vers.)"+nl;
System.out.println(msg);
if(args.length > 0) {
for(String arg : args) {
if (arg.equalsIgnoreCase("-dbg") || arg.equalsIgnoreCase("/dbg")) {
debg =true;
} else if (arg.equalsIgnoreCase("-nostop") || arg.equalsIgnoreCase("/nostop")) {
doNotS = true;
} else if (arg.equals("-?") || arg.equals("/?") || arg.equals("?")) {
h = true;
printInstructions(System.out);
} //if args[] = "?"
} //for arg : args
if(h) {return;} // exit after help
} //if args.length >0
else {
String t = "This program will convert a plot file (*.plt) into a PS file."+nl+
"Usage: java -jar PlotPS.jar [plot-file-name] [-command=value]"+nl+
"For a list of possible commands type: java -jar PlotPS.jar -?";
System.out.println(t);
ErrMsgBx mb = new ErrMsgBx(msg + nl + "Note: This is a console application."+nl+t, progName);
System.exit(0);
}
PlotPS pp;
try{
pp = new PlotPS(debg, doNotS, args);
} catch (Exception ex) { // this should not happen
exception(ex, null, doNotS);
pp = null;
}
// ---- if needed: wait for the calculations to finish on a different thread
if(pp != null) {
final PlotPS p = pp;
Thread t = new Thread() {@Override public void run(){
p.synchWaitConversion();
p.end_program();
}};// Thread t
t.start(); // Note: t.start() returns inmediately;
// statements here are executed inmediately.
try{t.join();} catch (java.lang.InterruptedException ex) {} // wait for the thread to finish
}
System.out.println("All done."+nl+DASH_LINE);
System.exit(0);
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="end_program, etc">
private void end_program() {
finished = true;
this.notify_All();
}
private synchronized void notify_All() {this.notifyAll();}
private synchronized void synchWaitConversion() {
while(!finished) {
try {this.wait();} catch(InterruptedException ex) {}
}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Constructor: runs the program itself">
/** Constructor: runs the program itself
* @param debg
* @param doNotS
* @param args */
public PlotPS(boolean debg, boolean doNotS, final String[] args) {
if(debg) {dbg = true;}
doNotStop = doNotS;
//--- read the command line arguments
pltFile = null; psFile = null;
String msg = null;
boolean argErr = false;
if(args != null && args.length >0){
if(dbg) {System.out.println("Reading command-line arguments..."+nl);}
for(int i=0; i<args.length; i++) {
if(dbg){System.out.println("Command-line argument = \""+args[i]+"\"");}
if(i == 0 && !args[0].toLowerCase().startsWith("-p")) {
// Is it a plot file name?
boolean ok = true;
String name = args[0];
if(name.startsWith("\"") && name.endsWith("\"")) { //remove enclosing quotes
name = name.substring(1, name.length()-1);
}
if(!name.toLowerCase().endsWith(".plt")) {name = name.concat(".plt");}
java.io.File f = new java.io.File(name);
if(!f.exists()) {
if(dbg) {System.out.println("Not a plt-file: \""+f.getAbsolutePath()+"\"");}
ok = false;
} // it is not a file
if(ok && f.isDirectory()) {
msg = "Error: \""+f.getAbsolutePath()+"\" is a directory.";
ok = false;
}
if(ok && !f.canRead()) {
msg = "Error: can not open file for reading:"+nl+" \""+f.getAbsolutePath()+"\"";
ok = false;
}
// ok = true if it is an existing file that can be read
if(ok) {
if(dbg){System.out.println("Plot file: "+f.getPath());}
pltFile = f;
continue;
} else {
if(msg != null) {
if(doNotStop) {System.out.println(msg);} else {ErrMsgBx mb = new ErrMsgBx(msg,progName);}
}
}
} // if i=0
if(!parseArg(args[i].trim())) {argErr = true; break;}
} // for i
} // if args
if(dbg) {System.out.println(nl+"Command-line arguments ended."+nl);}
if(argErr) {end_program(); return;}
if(pltFile == null) {
msg = "No plot file name given in the command-line.";
if(doNotStop) {System.out.println(msg);} else {ErrMsgBx mb = new ErrMsgBx(msg,progName);}
end_program(); return;
}
if(psFile_name != null && psFile_name.trim().length() >0) {
if(psFile_name.contains(SLASH)) {
psFile = new java.io.File(psFile_name);
} else {
psFile = new java.io.File(pltFile.getParent(), psFile_name);
if(dbg) {
msg = "PostScript-file: \""+psFile.getAbsolutePath()+"\""+nl;
if(eps) {msg = "Encapsulated "+msg;}
System.out.println(msg);
}
}
}
if(psFile == null) {
String name = pltFile.getAbsolutePath();
int n = name.length();
name = name.substring(0, n-4)+".ps";
psFile = new java.io.File(name);
eps = false;
}
if(psFile.exists() && (!psFile.canWrite() || !psFile.setWritable(true))) {
msg = "Error: can not write to file"+nl+" \""+psFile.toString()+"\""+nl+
"is the file locked?";
if(doNotStop) {System.out.println(msg);} else {ErrMsgBx mb = new ErrMsgBx(msg,progName);}
end_program(); return;
}
if(eps) {
if(!psPortrait) {
System.out.println("Warning: for Encapsulated PostScript the orientation is Portrait!");
psPortrait = true;
}
if(Math.abs(psMarginB) > 0.001) {
System.out.println("Warning: for Encapsulated PostScript the bottom margin is zero!");
}
if(Math.abs(psMarginL) > 0.001) {
System.out.println("Warning: for Encapsulated PostScript the left margin is zero!");
}
psMarginB = 0;
psMarginL = 0;
}
String o = "Portrait"; if(!psPortrait) {o = "Landscape";}
String c = "black on white";
if(psColors == 1) {c = "colours";} else if(psColors == 2) {c = "colours selected in \"Spana\"";}
System.out.println("plot file: "+maybeInQuotes(pltFile.getName())+nl+
"output file: "+maybeInQuotes(psFile.getName())+nl+
"options:"+nl+
" size "+psSizeX+"/"+psSizeY+" %;"+
" left, bottom margins = "+psMarginL+", "+psMarginB+" cm"+nl+
" orientation = "+o+"; font = "+FONTS[psFont]+nl+
" "+c);
System.out.print("converting to "); if(eps) {System.out.print("encapsulated ");}
System.out.println("PostScript ...");
try{convert2PS();}
catch(Exception ex) {
exception(ex, null, doNotStop);
delete = true;
}
// --- close streams
try{if(bufReader != null) {bufReader.close();}}
catch (java.io.IOException ex) {
exception(ex, "while closing file:"+nl+" \""+pltFile+"\"", doNotStop);
}
if(outputFile != null) {
try{
outputFile.flush();
outputFile.close();
} catch (java.io.IOException ex) {
exception(ex, "while closing file:"+nl+" \""+psFile+"\"", doNotStop);
}
}
if(delete) {psFile.delete();}
end_program();
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="parseArg">
/** Interpret a command-line argument
* @param arg String containing a command-line argument
* @return false if there was an error associated with the command argument
*/
private boolean parseArg(String arg) {
if(arg == null) {return true;}
if(arg.length() <=0) {return true;}
if(arg.equals("-?") || arg.equals("/?") || arg.equals("?")) {
printInstructions(System.out);
return true;
} //if args[] = "?"
String msg = null;
while(true) {
if(arg.equalsIgnoreCase("-dbg") || arg.equalsIgnoreCase("/dbg")) {
dbg = true;
System.out.println("Debug printout = true");
return true;
} // -dbg
else if(arg.equalsIgnoreCase("-nostop") || arg.equalsIgnoreCase("/nostop")) {
doNotStop = true;
if(dbg) {System.out.println("Do not show message boxes");}
return true;
} // -nostop
else if(arg.equalsIgnoreCase("-bw") || arg.equalsIgnoreCase("/bw")) {
if(dbg){System.out.println("Black on white");}
psColors = 0;
return true;
} // -bw
else if(arg.equalsIgnoreCase("-noh") || arg.equalsIgnoreCase("/noh")) {
if(dbg){System.out.println("No header");}
psHeader = false;
return true;
} // -noh
else if(arg.equalsIgnoreCase("-clr") || arg.equalsIgnoreCase("/clr")) {
if(dbg){System.out.println("Colours (default palette)");}
psColors = 1;
return true;
} // -clr
else if(arg.equalsIgnoreCase("-clr2") || arg.equalsIgnoreCase("/clr2")) {
if(dbg){System.out.println("Colours (\"Spana\" palette)");}
psColors = 2;
return true;
} // -clr2
else {
if(arg.length() >3) {
String arg0 = arg.substring(0, 2).toLowerCase();
if(arg0.startsWith("-p") || arg0.startsWith("/p")) {
if(arg.charAt(2) == '=' || arg.charAt(2) == ':') {
String name = arg.substring(3);
if(name.startsWith("\"") && name.endsWith("\"")) { //remove enclosing quotes
name = name.substring(1, name.length()-1);
}
if(!name.toLowerCase().endsWith(".plt")) {name = name.concat(".plt");}
java.io.File f = new java.io.File(name);
name = f.getAbsolutePath();
f = new java.io.File(name);
if(!f.exists()) {
msg = "Error: the plot file does not exist:"+nl+" \""+f.getAbsolutePath()+"\"";
break;
} // it is not a file
if(f.isDirectory()) {
msg = "Error: \""+f.getAbsolutePath()+"\" is a directory.";
break;
}
if(!f.canRead()) {
msg = "Error: can not open file for reading:"+nl+" \""+f.getAbsolutePath()+"\"";
break;
}
if(dbg){System.out.println("Plot file: "+f.getPath());}
pltFile = f;
return true;
}// = or :
} // if starts with "-p"
else if(arg0.startsWith("-b") || arg0.startsWith("/b")) {
if(arg.charAt(2) == '=' || arg.charAt(2) == ':') {
String t = arg.substring(3);
try {psMarginB = Double.parseDouble(t);
psMarginB = Math.min(20,Math.max(psMarginB,-5));
if(dbg) {System.out.println("Bottom margin = "+psMarginB);}
return true;
} //try
catch (NumberFormatException nfe) {
msg = "Error: Wrong numeric format for bottom margin in text \""+t+"\"";
psMarginB = Double.NaN;
break;
} //catch
}// = or :
} // if starts with "-b"
else if(arg0.startsWith("-l") || arg0.startsWith("/l")) {
if(arg.charAt(2) == '=' || arg.charAt(2) == ':') {
String t = arg.substring(3);
try {psMarginL = Double.parseDouble(t);
psMarginL = Math.min(20,Math.max(psMarginL,-5));
if(dbg) {System.out.println("Left margin = "+psMarginL);}
return true;
} //try
catch (NumberFormatException nfe) {
msg = "Error: Wrong numeric format for left margin in text \""+t+"\"";
psMarginL = Double.NaN;
break;
} //catch
}// = or :
} // if starts with "-l"
else if(arg0.startsWith("-s") || arg0.startsWith("/s")) {
if(arg.charAt(2) == '=' || arg.charAt(2) == ':') {
String t = arg.substring(3);
int size;
try {size = Integer.parseInt(t);
size = Math.min(300,Math.max(size,20));
if(dbg) {System.out.println("Output size = "+size+" %");}
psSizeX = size;
psSizeY = size;
return true;
} //try
catch (NumberFormatException nfe) {
msg = "Error: Wrong numeric format for output size in text \""+t+"\"";
size = 100;
psSizeX = size;
psSizeY = size;
break;
} //catch
}// = or :
} // if starts with "-s"
else if(arg0.startsWith("-o") || arg0.startsWith("/o")) {
if(arg.charAt(2) == '=' || arg.charAt(2) == ':') {
String t = arg.substring(3).toLowerCase();
if(t.equals("p")) {psPortrait = true;} else
if(t.equals("l")) {psPortrait = false;}
if(t.equals("p") || t.equals("l")) {
if(dbg) {
t = "Orientation = ";
if(psPortrait) {t = t + "Portrait";}
else {t = t + "Landscape";}
System.out.println(t);
}
return true;
} else {
msg = "Error: Wrong format for orientation in text \""+t+"\"";
break;
}
}// = or :
} // if starts with "-o"
else if(arg0.startsWith("-f") || arg0.startsWith("/f")) {
if(arg.charAt(2) == '=' || arg.charAt(2) == ':') {
String t = arg.substring(3);
int f;
try {f = Integer.parseInt(t);
if(f >= 1 && f <= 4) {
psFont = f-1;
if(dbg) {System.out.println("Output font = "+FONTS[psFont]);}
return true;
} else {
msg = "Error: Wrong font type in text \""+t+"\"";
psFont = 2;
break;
}
} catch (NumberFormatException nfe) {
msg = "Error: Wrong numeric format for output size in text \""+t+"\"";
psFont = 2;
break;
} //catch
}// = or :
} // if starts with "-f"
} // if length >3
if(arg.length() >4) {
String arg0 = arg.substring(0, 3).toLowerCase();
if(arg0.startsWith("-sx") || arg0.startsWith("/sx")) {
if(arg.charAt(3) == '=' || arg.charAt(3) == ':') {
String t = arg.substring(4);
int size;
try {size = Integer.parseInt(t);
size = Math.min(300,Math.max(size,20));
if(dbg) {System.out.println("Output X-size = "+size+" %");}
psSizeX = size;
return true;
} //try
catch (NumberFormatException nfe) {
msg = "Error: Wrong numeric format for output X-size in text \""+t+"\"";
size = 100;
psSizeX = size;
break;
} //catch
}// = or :
} // if starts with "-sx"
else if(arg0.startsWith("-sy") || arg0.startsWith("/sy")) {
if(arg.charAt(3) == '=' || arg.charAt(3) == ':') {
String t = arg.substring(4);
int size;
try {size = Integer.parseInt(t);
size = Math.min(300,Math.max(size,20));
if(dbg) {System.out.println("Output Y-size = "+size+" %");}
psSizeY = size;
return true;
} //try
catch (NumberFormatException nfe) {
msg = "Error: Wrong numeric format for output Y-size in text \""+t+"\"";
size = 100;
psSizeY = size;
break;
} //catch
}// = or :
} // if starts with "-sy"
else if(arg0.startsWith("-ps") || arg0.startsWith("/ps")) {
if(arg.charAt(3) == '=' || arg.charAt(3) == ':') {
String name = arg.substring(4);
if(name.startsWith("\"") && name.endsWith("\"")) { //remove enclosing quotes
name = name.substring(1, name.length()-1);
}
if(!name.toLowerCase().endsWith(".ps")
&& !name.toLowerCase().endsWith(".eps")) {name = name.concat(".ps");}
if(name.toLowerCase().endsWith(".eps")) {eps = true;}
if(dbg){
String out = "PostScript file: "+name;
if(eps) {out = "encapsulated "+out;}
System.out.println(out);
}
psFile_name = name;
return true;
}// = or :
} // if starts with "-ps"
} // if length >4
}
// nothing matches
break;
} //while
if(msg == null) {msg = "Error: can not understand command-line argument:"+nl+
" \""+arg+"\"";}
else {msg = "Command-line argument \""+arg+"\":"+nl+msg;}
if(doNotStop) {System.out.println(msg);} else {ErrMsgBx mb = new ErrMsgBx(msg,progName);}
System.out.println();
printInstructions(System.out);
return false;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="convert2PS">
private void convert2PS() {
// initialize the contents of some variables
scaleX = (double)psSizeX/100d + 1e-10;
scaleY = (double)psSizeY/100d + 1e-10;
zx = psMarginL * 100;
zy = psMarginB * 100;
newPath = -1;
x1st = -Double.MAX_VALUE; y1st = -Double.MAX_VALUE;
//--- The PostScript file is written in ISO-LATIN-1 encoding
// Standard charsets: Every implementation of the Java platform is
// required to support the following standard charsets.
// Charset Description
// US-ASCII Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block
// of the Unicode character set
// ISO-8859-1 ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1
// UTF-8 Eight-bit UCS Transformation Format
// UTF-16BE Sixteen-bit UCS Transformation Format, big-endian byte order
// UTF-16LE Sixteen-bit UCS Transformation Format, little-endian byte order
// UTF-16 Sixteen-bit UCS Transformation Format, byte order identified by
// an optional byte-order mark
//--- make sure the output file can be written
String msg;
try{
outputFile = new java.io.BufferedWriter(
new java.io.OutputStreamWriter(
new java.io.FileOutputStream(psFile), "UTF8"));
} catch (java.io.FileNotFoundException ex) {
msg = "File not found:"+nl+
" \""+psFile.getAbsolutePath()+"\"";
exception(ex, msg, doNotStop);
return;
} catch (java.io.UnsupportedEncodingException ex) {
msg = "while writing the PostScript file:"+nl+
" \""+psFile.getAbsolutePath()+"\"";
exception(ex, msg, doNotStop);
return;
}
//--- files appear to be ok
setPalette();
// If `eps' the size of the BoundingBox is needed for MicroSoft's Word
// and Word for Windows (WordPerfect can understand `(atend)').
// The Boundingbox (in units of the default user cooordinate system) is
// determined first, the file is rewinded, and the real "plotting" is done.
if(eps) {
boundingBox = getBoundingBox();
if(boundingBox == null) {return;}
}
//--- open the input plt-file
bufReader = getBufferedReader(pltFile, doNotStop);
if(bufReader == null) {return;}
psInit(outputFile);
// ----------------------------------------------------
int i0, i1, i2;
String s0, s1, s2;
String line;
String comment;
boolean readingText = false;
/** -1=Left 0=center +1=right */
int align = 0, alignDef = 0;
// ----- read all lines
while(true) {
try {line = bufReader.readLine();}
catch (java.io.IOException ex) {
msg = "while reading the plot file:"+nl+
" \""+pltFile.getAbsolutePath()+"\"";
exception(ex, msg, doNotStop);
break;
}
if(line == null) {break;}
// --- get i0, i1, i2 and any comment
if(line.length() > 0) {s0= line.substring(0,1).trim();} else {s0 = "";}
if(line.length() > 4) {s1= line.substring(1,5).trim();} else {s1 = "";}
if(line.length() > 8) {s2= line.substring(5,9).trim();} else {s2 = "";}
if(s0.length() > 0) {i0 = readInt(s0);} else {i0 = -1;}
if(s1.length() > 0) {i1 = readInt(s1);} else {i1 = 0;}
if(s2.length() > 0) {i2 = readInt(s2);} else {i2 = 0;}
if(line.length() > 9) {
comment= line.substring(9).trim();
if(comment.equals("TextEnd")) {readingText = false; continue;}
} else {comment = "";}
if(readingText) {continue;}
if(comment.equals("-- HEADING --")) {alignDef = -1;}
// --- change pen or colour
if(i0!=0 && i0!=1) {
if(i0==5 || i0==8) {setPen(i0,i1,outputFile);}
continue;
}
// at this point either i0 = 0 or i0 = 1
// --- line drawing
if(psFont ==0
|| i0 == 1
|| !comment.startsWith("TextBegin")) {
moveOrDraw(i0,(double)i1,(double)i2, outputFile);
continue;
}
// --- is there a text to print?
// at this point: diagrConvertFont >0,
// i0 =0, and comment.startsWith("TextBegin")
boolean isFormula = false;
double txtSize, txtAngle;
if(i0 == 0 && comment.length()>41 && comment.startsWith("TextBegin")) {
if(comment.substring(9,10).equals("C")) {isFormula=true;}
txtSize = readDouble(comment.substring(17,24));
txtAngle = readDouble(comment.substring(35,42));
// get alignment
if(comment.length() > 42) {
String t = comment.substring(55,56);
if(t.equalsIgnoreCase("L")) {align = -1;}
else if(t.equalsIgnoreCase("R")) {align = 1;}
else if(t.equalsIgnoreCase("C")) {align = 0;}
} else {align = alignDef;}
// the text is in next line
try{line = bufReader.readLine();}
catch(java.io.IOException ex) {
msg = "while reading the plot file:"+nl+
" \""+pltFile.getAbsolutePath()+"\"";
exception(ex, msg, doNotStop);
break;
}
if(line != null) {
if(line.length() > 9) {
comment= rTrim(line.substring(9));
if(comment.startsWith(" ")) {comment = comment.substring(1);}
} else {comment = "";}
// print the text
printText(i1,i2,comment,isFormula,align,txtSize,txtAngle,outputFile);
} // if line != null
// ------ read all lines until "TextEnd"
readingText = true;
} // if "TextBegin"
} //while
psEnd(outputFile);
} //convert2PS
//<editor-fold defaultstate="collapsed" desc="getBufferedReader">
private static java.io.BufferedReader getBufferedReader(java.io.File f, boolean noStop) {
String msg;
java.io.BufferedReader bufReader;
java.io.InputStreamReader isr;
try{
isr = new java.io.InputStreamReader(new java.io.FileInputStream(f) , "UTF-8");
bufReader = new java.io.BufferedReader(isr);
}
catch (java.io.FileNotFoundException ex) {
msg = "File not found:"+nl+
" \""+f.getAbsolutePath()+"\"";
exception(ex, msg, noStop);
return null;
} catch (java.io.UnsupportedEncodingException ex) {
msg = "while reading the plot file:"+nl+
" \""+f.getAbsolutePath()+"\"";
exception(ex, msg, noStop);
return null;
}
return bufReader;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="readInt(String)">
private static int readInt(String t) {
int i;
try{i = Integer.parseInt(t);}
catch (java.lang.NumberFormatException ex) {
System.out.println(DASH_LINE+nl+"Error: "+ex.toString()+nl+
" while reading an integer from String: \""+t+"\""+nl+DASH_LINE);
i = 0;}
return i;
} //readInt(T)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="readDouble(String)">
private static double readDouble(String t) {
double d;
try{d = Double.parseDouble(t);}
catch (java.lang.NumberFormatException ex) {
System.out.println(DASH_LINE+nl+"Error: "+ex.toString()+nl+
" while reading an floating-point number from String: \""+t+"\""+nl+DASH_LINE);
d = 0;}
return d;
} //readDouble(T)
//</editor-fold>
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="getBoundingBox">
private BoundingBox getBoundingBox() {
System.out.println("calculating BoundingBox (for EPS) ...");
BoundingBox bb = new BoundingBox();
java.io.BufferedReader br = getBufferedReader(pltFile, doNotStop);
if(br == null) {return null;}
// ----- read all lines
String line, msg;
int i0,i1,i2;
String s0, s1, s2;
double x,y;
String comment;
while(true) {
try {line = br.readLine();}
catch (java.io.IOException ex) {
msg = "while reading the plot file:"+nl+
" \""+pltFile.getAbsolutePath()+"\"";
exception(ex, msg, doNotStop);
bb = null;
break;
}
if(line == null) {break;}
// --- get i0, i1, i2 and any comment
if(line.length() > 0) {s0= line.substring(0,1).trim();} else {s0 = "";}
if(line.length() > 4) {s1= line.substring(1,5).trim();} else {s1 = "";}
if(line.length() > 8) {s2= line.substring(5,9).trim();} else {s2 = "";}
if(s0.length() > 0) {i0 = readInt(s0);} else {i0 = -1;}
if(s1.length() > 0) {i1 = readInt(s1);} else {i1 = 0;}
if(s2.length() > 0) {i2 = readInt(s2);} else {i2 = 0;}
if(i0<0 || i0>1) {continue;}
x = (double)i1 * scaleX; y = (double)i2 * scaleY;
if(bb.xMx < x) bb.xMx = x;
if(bb.yMx < y) bb.yMx = y;
if(bb.xMn > x) bb.xMn = x;
if(bb.yMn > y) bb.yMn = y;
if (line.length() > 9) {comment= line.substring(9).trim();} else {comment = "";}
// read a TextBegin-TextEnd
float txtSize; float txtAngle;
if (i0 == 0 && comment.length()>41 && comment.startsWith("TextBegin")) {
txtSize = readFloat(comment.substring(17,24));
txtAngle = readFloat(comment.substring(35,42));
//get angles between +180 and -180
while (txtAngle>360) {txtAngle=txtAngle-360f;}
while (txtAngle<-360) {txtAngle=txtAngle+360f;}
if(txtAngle>180) {txtAngle=txtAngle-360f;}
if(txtAngle<-180) {txtAngle=txtAngle+360f;}
// the text is in next line
try {line = br.readLine();}
catch (java.io.IOException ex) {
msg = "while reading the plot file:"+nl+
" \""+pltFile.getAbsolutePath()+"\"";
exception(ex, msg, doNotStop);
bb = null;
break;
}
if(line == null) {break;}
if (line.length()>9) {
comment= rTrim(line.substring(9));
if(comment.startsWith(" ")) {comment = comment.substring(1);}
} else {comment = "";}
// addjust userSpaceMax and userSpaceMin
textBoxMinMax(i1, i2, (txtSize * 100f),
(txtSize*100f*comment.length()), txtAngle, bb);
}
}
try{br.close();} catch (java.io.IOException ex) {exception(ex, null, doNotStop);}
return bb;
}
//<editor-fold defaultstate="collapsed" desc="readFloat(String)">
private static float readFloat(String t) {
float f;
try{f = Float.parseFloat(t);}
catch (java.lang.NumberFormatException ex) {
System.out.println(DASH_LINE+nl+"Error: "+ex.toString()+nl+
" while reading a \"float\" from String: \""+t+"\""+nl+DASH_LINE);
f = 0f;}
return f;
} //readFloat(T)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="textBoxMinMax">
/** find out the bounding box around a text, (adding some margins on top and bottom
* to allow for super- and sub-scripts). Adjust bb using this bounding box.
* @param i1 the x-value for the bottom-left corner
* @param i2 the y-value for the bottom-left corner
* @param height the height of the letters of the text in the same coordinates
* as "i1" and "i2"
* @param width the width of the text in the same coordinates
* as "i1" and "i2"
* @param angle the angle in degrees
* @param bb */
private static void textBoxMinMax (int i1, int i2,
float height, float width, float angle,
BoundingBox bb) {
final double DEG_2_RAD = 0.017453292519943;
final double a0 = angle * DEG_2_RAD;
final double a1 = (angle + 90) * DEG_2_RAD;
final float h = height * 2f;
final float w = width;
java.awt.Point p0 = new java.awt.Point();
java.awt.Point p1 = new java.awt.Point();
p0.x = i1 - (int)((height) * (float)Math.cos(a1));
p0.y = i2 - (int)((height) * (float)Math.sin(a1));
if(p0.x<bb.xMn) {bb.xMn = p0.x;}
if(p0.x>bb.xMx) {bb.xMx = p0.x;}
if(p0.y<bb.yMn) {bb.yMn = p0.y;}
if(p0.y>bb.yMx) {bb.yMx = p0.y;}
p0.x = i1 + (int)(w * (float)Math.cos(a0));
p0.y = i2 + (int)(w * (float)Math.sin(a0));
if(p0.x<bb.xMn) {bb.xMn = p0.x;}
if(p0.x>bb.xMx) {bb.xMx = p0.x;}
if(p0.y<bb.yMn) {bb.yMn = p0.y;}
if(p0.y>bb.yMx) {bb.yMx = p0.y;}
p1.x = p0.x + (int)(h * (float)Math.cos(a1));
p1.y = p0.y + (int)(h * (float)Math.sin(a1));
if(p1.x<bb.xMn) {bb.xMn = p1.x;}
if(p1.x>bb.xMx) {bb.xMx = p1.x;}
if(p1.y<bb.yMn) {bb.yMn = p1.y;}
if(p1.y>bb.yMx) {bb.yMx = p1.y;}
p0.x = i1 + (int)(h * (float)Math.cos(a1));
p0.y = i2 + (int)(h * (float)Math.sin(a1));
if(p0.x<bb.xMn) {bb.xMn = p0.x;}
if(p0.x>bb.xMx) {bb.xMx = p0.x;}
if(p0.y<bb.yMn) {bb.yMn = p0.y;}
if(p0.y>bb.yMx) {bb.yMx = p0.y;}
}
//</editor-fold>
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="psInit">
private void psInit(java.io.BufferedWriter o) {
final String[] FONTN = {"Times-Roman","Helvetica","Courier"};
final String[] FONTBN = {"Times-Bold","Helvetica-Bold","Courier-Bold"};
final String[] FONTIN = {"Times-Italic","Helvetica-Oblique","Courier-Oblique"};
try{
String t = "%%Title: "+fixTextSimple(maybeInQuotes(pltFile.getName()),false)+"; ";
if(!eps) {
o.write("%!PS-Adobe-2.0"+nl);
o.write(t+nl);
} else { //for eps:
o.write("%!PS-Adobe-2.0 EPSF-2.0"+nl);
o.write(t+nl);
}
o.write("%%Creator: PlotPS [java], version: "+VERS+nl);
o.write("%%CreationDate: "+getDateTime()+nl);
o.write("%%For: "+fixTextSimple(System.getProperty("user.name", "anonymous"),false)+nl);
String or = "Portrait"; if(!psPortrait) {or = "Landscape";}
// o.write("%%Orientation: "+or+nl);
t = "%%DocumentNeededResources: font ";
int n = psFont-1;
if(!eps) {
// the Courier font is used to print the file-name, and
// date-time on top of each page
if(psFont <= 2) {t = t + "Courier ";}
if(psFont > 0) {o.write(t + FONTN[n]+" "+FONTBN[n]+" "+FONTIN[n]+nl);}
o.write("%%Pages: 1"+nl);
} else { //eps:
if(psFont >= 1 && psFont <= 3) {
o.write(t + FONTN[n]+" "+FONTBN[n]+" "+FONTIN[n]+nl);
}
//avoid a "zero" BoundingBox:
if(boundingBox.xMx <= -1e4) {boundingBox.xMx = 100;}
if(boundingBox.yMx <= -1e4) {boundingBox.yMx = 100;}
if(boundingBox.xMn >= (boundingBox.xMx -2)) {boundingBox.xMn = boundingBox.xMx -100;}
if(boundingBox.yMn >= (boundingBox.yMx -2)) {boundingBox.yMn = boundingBox.yMx -100;}
//size of the bounding-box with a margin:
long ixMx, ixMn, iyMx, iyMn;
ixMn = Math.round(boundingBox.xMn*0.283465);
iyMn = Math.round(boundingBox.yMn*0.283465);
ixMx = Math.round((boundingBox.xMx+90)*0.283465);
iyMx = Math.round((boundingBox.yMx+90)*0.283465);
t = "%%BoundingBox: "+String.format("%8d",ixMn).trim()+" "
+String.format("%8d",iyMn).trim()+" "
+String.format("%8d",ixMx).trim()+" "
+String.format("%8d",iyMx).trim();
o.write(t+nl);
}
o.write("%%EndComments"+nl);
if(eps) {o.write("% to change the \"BoundingBox\" given above: add margins in cm * 28.4"+nl);}
// initialize
o.write("%%BeginProlog"+nl+
"% ------- Prolog: defining procedures and variables -------"+nl);
o.write("/ChemEqDict 60 dict def % create a dictionary"+nl+
"ChemEqDict begin % push dictionary in dictionary stack"+nl+
"/Mv {moveto} def"+nl+"/Ln {lineto} def"+nl+"/_sn {stroke newpath} def"+nl+
"/_csn {closepath stroke newpath} def"+nl+
"/_setWidth {/linWidth exch def linWidth setlinewidth} def"+nl+
"% --- dash-line types:"+nl+
"/Lt0 {stroke linWidth setlinewidth [] 0 setdash} def"+nl+
"/Lt1 {stroke linWidth setlinewidth [30 10] 0 setdash} def"+nl+
"/Lt2 {stroke linWidth setlinewidth [15 15] 0 setdash} def"+nl+
"/Lt3 {stroke linWidth setlinewidth [5 10] 0 setdash} def"+nl+
"/Lt4 {stroke linWidth setlinewidth [30 10 5 10] 0 setdash } def"+nl+
"/Lt5 {stroke linWidth setlinewidth [15 10 5 10] 0 setdash} def"+nl);
if(psFont >0 && psFont <=3) {
o.write("%-------------------- Font related stuff: ---------------------------------"+nl+
"/rShow {dup stringwidth pop 0 exch % right-show"+nl+
" sub 0 rmoveto show} def"+nl+
"/lShow {show} def % left-show"+nl+
"/cShow {dup stringwidth pop -2 div -0.5 % center-show (both"+nl+
" getSize siz mul rmoveto show} def % vertically & horizontally)"+nl+
"/_angle 0 def % angle to rotate text"+nl+
"/TxtRotate % Procedure to rotate text. Usage:"+nl+
" {gsave % /_angle nn def TxtRotate"+nl+
" currentpoint translate % x y moveto (text1) show"+nl+
" _angle rotate} def % x y moveto (text2) show grestore"+nl+
"/fontScale 1.40 def"+nl+
"/_setSize % scale current font (parameter: font size in 0.01 cm units)"+nl+
" {fontScale mul /UserFont currentfont def"+nl+
" /UserFont findfont exch scalefont setfont} def"+nl+
"/getSize {gsave newpath 0 0 moveto (X) % find current font size"+nl+
" true charpath flattenpath pathbbox % and store result in \"siz\""+nl+
" /siz exch def pop pop pop grestore} def"+nl+
"%----------------------------------------------------------------------------"+nl+
"% ----- additions for PostScript output -----"+nl+
"% ----- which allow printing math and chemical formulas -----"+nl+
"%----------------------------------------------------------------------------"+nl+
"% ---- super/sub-scripts."+nl+
"% Both \"^\" and \"_^\" take two arguments: the string to output and"+nl+
"% the vertical shift (positive or negative as fraction of letter"+nl+
"% size). The difference: \"_^\" does not advance the cursor (allowing"+nl+
"% subs- and super-scripts on the same letter)."+nl+
"% For example, to output UO2(CO3)3-4:"+nl+
"% (UO) show (2) -0.5 ^ (\\(CO) show (3) -0.5 ^"+nl+
"% (\\)) show (3) -0.5 ^ (4-) 0.5 _^"+nl+
"% \"_f\" takes one argument (spacing as fraction of letter size)"+nl+
"% and moves the cursor forward or backward. Useful in math formulas."+nl+
"/^ {/regFont currentfont def /ssFont currentfont [.7 0 0 .7 0 0] makefont def"+nl+
" getSize dup 0 exch siz mul rmoveto ssFont setfont"+nl+
" exch show 0 exch siz neg mul rmoveto regFont setfont } def"+nl+
"/_^ {/regFont currentfont def /ssFont currentfont [.7 0 0 .7 0 0] makefont def"+nl+
" getSize dup 0 exch siz mul rmoveto ssFont setfont"+nl+
" exch dup stringwidth pop neg exch show "+nl+
" 0 rmoveto 0 exch siz neg mul rmoveto regFont setfont } def"+nl+
"/_f {getSize siz mul 0 rmoveto} def"+nl+
"%"+nl+
"% ----- printing symbols and/or change to Bold and Italic."+nl+
"% *1* bold, italics, etc: \"_norm\", \"_bold\", \"_em\" and \"_sym\" take"+nl+
"% no arguments and they are used before a \"(text) show\"."+nl+
"% Because the Roman fonts use here the ISOLatin1 encoding,"+nl+
"% one can plot some symbols with them. Examples:"+nl+
"% _norm (normal) show _bold (bold) show _em (italics) show _norm"+nl+
"% _norm (T=25 \\260C, [Cu]=1\\265M) show"+nl+
"% *2* the Symbol font may be used with octal codes (\\nnn)."+nl+
"% Example formula (- delta-r-Cp0m):"+nl+
"% _sym (-\\104) show _norm (r) -0.4 ^ 0.05 _f _em (C) show"+nl+
"% _sym (\\260) 0.3 _^ _norm (p,m) -0.4 ^"+nl+
"% another example (log_10 pCO2(g)):"+nl+
"% _norm (log) show (10) -0.4 ^ 0.1 _f _em (p) show"+nl+
"% _norm (CO) -0.4 ^ (2) -0.8 ^ (\\(g\\)) -0.4 ^"+nl+
"% Tables with the octal encoding vectors for the Roman and Symbol"+nl+
"% fonts are given in PostScript manuals."+nl+
"%"+nl+
"/_norm {/"+FONTN[n]+" findfont dup length dict begin"+nl+
" {1 index /FID ne {def} {pop pop} ifelse} forall"+nl+
" /Encoding ISOLatin1Encoding def currentdict end"+nl+
" /UserFont exch definefont pop"+nl+
" getSize /UserFont findfont 1.43 siz mul scalefont setfont} def"+nl+
"/_bold {/"+FONTBN[n]+" findfont dup length dict begin"+nl+
" {1 index /FID ne {def} {pop pop} ifelse} forall"+nl+
" /Encoding ISOLatin1Encoding def currentdict end"+nl+
" /UserFont exch definefont pop"+nl+
" getSize /UserFont findfont 1.43 siz mul scalefont setfont} def"+nl+
"/_em {/"+FONTIN[n]+" findfont dup length dict begin"+nl+
" {1 index /FID ne {def} {pop pop} ifelse} forall"+nl+
" /Encoding ISOLatin1Encoding def currentdict end"+nl+
" /UserFont exch definefont pop"+nl+
" getSize /UserFont findfont 1.43 siz mul scalefont setfont} def"+nl+
"/_normS {/"+FONTN[n]+" findfont dup length dict begin"+nl+
" {1 index /FID ne {def} {pop pop} ifelse} forall"+nl+
" /Encoding StandardEncoding def currentdict end"+nl+
" /UserFont exch definefont pop"+nl+
" getSize /UserFont findfont 1.43 siz mul scalefont setfont} def"+nl+
"/_boldS {/"+FONTBN[n]+" findfont dup length dict begin"+nl+
" {1 index /FID ne {def} {pop pop} ifelse} forall"+nl+
" /Encoding StandardEncoding def currentdict end"+nl+
" /UserFont exch definefont pop"+nl+
" getSize /UserFont findfont 1.43 siz mul scalefont setfont} def"+nl+
"/_emS {/"+FONTIN[n]+" findfont dup length dict begin"+nl+
" {1 index /FID ne {def} {pop pop} ifelse} forall"+nl+
" /Encoding StandardEncoding def currentdict end"+nl+
" /UserFont exch definefont pop"+nl+
" getSize /UserFont findfont 1.43 siz mul scalefont setfont} def"+nl+
"/_sym {getSize /Symbol findfont 1.43 siz mul scalefont setfont} def"+nl+"%"+nl);
}
o.write("end % pop ChemEqDict from dictionary stack"+nl+
"% ------------------------------- end Prolog --------------------------------"+nl+
"%%EndProlog"+nl);
if(!eps) {o.write("%%Page: 1 1"+nl);}
t = "% size: ";
if(psSizeX == psSizeY) {
t = t + String.valueOf(psSizeX);
} else {
t = t + String.valueOf(psSizeX)+"/"+String.valueOf(psSizeY);
}
String c = "black on white";
if(psColors == 1) {c = "colours";} else if(psColors == 2) {c = "colours selected in \"Spana\"";}
o.write("% ----------------------------- PlotPS options:"+nl+
t+"%; left- and bottom-margin: "+psMarginL+" "+psMarginB+nl+
"% "+c+"; "+or.toLowerCase()+"; font: "+FONTS[psFont]+nl);
o.write("% ---- Initialize the page ----"+nl+
"ChemEqDict begin % push dictionary in dictionary stack"+nl+
"gsave"+nl);
if(!eps && psHeader) {
o.write("% ---- print out file name, time and date"+nl+
"/Courier findfont dup length dict begin"+nl+
" {1 index /FID ne {def} {pop pop} ifelse} forall"+nl+
" /Encoding ISOLatin1Encoding def currentdict end"+nl+
" /UserFont exch definefont pop"+nl+
" /UserFont findfont 8 scalefont setfont"+nl+" ");
o.write("30 770 moveto"+nl);
t = "(file: "+fixTextSimple(maybeInQuotes(pltFile.getAbsolutePath()),false)+" PostScripted: "+getDateTime()+") show";
o.write(t+nl);
}
// set Landscape / Portrait orientation
int angle = 90, x =12, y =-579;
if(psPortrait) {angle=0; x =16; y =12;}
o.write("% ---- set landscape/portrait orientation"+nl+
angle+" rotate "+x+" "+y+" translate"+nl);
o.write("% ---- re-scale to 100 = 1 cm; (1 inch * 2.54) cm /72 points * 100"+nl+
"0.283465 0.283465 scale"+nl+
"1 setlinejoin 0 setgray 2.82 _setWidth % set defaults for line drawing"+nl);
if(psFont > 0) {
o.write("% ---- set initial font size (0.35 cm). Needed before \"_norm\", \"rShow\", etc"+nl+
"% (which call \"getSize\", and require a font size)"+nl+
"/"+FONTN[psFont-1]+" findfont 35 scalefont setfont"+nl+
"_norm"+nl);
}
o.write("%-------------------------- plot file starts here --------------------------"+nl);
} catch (java.io.IOException ex) {
exception(ex, null, doNotStop);
delete = true;
}
} // psInit
/** get the date and time in default format */
private String getDateTime() {
java.text.DateFormat df = java.text.DateFormat.getDateTimeInstance
(java.text.DateFormat.DEFAULT, java.text.DateFormat.DEFAULT,
java.util.Locale.getDefault());
java.util.Date now = new java.util.Date();
return df.format(now);
} //getDateTime()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="psEnd">
private void psEnd(java.io.BufferedWriter o) {
try{
o.write("stroke"+nl);
o.write("%-------------------------- plot file ends here --------------------------"+nl);
String t = "grestore"+nl+"end % pop ChemEqDict from dictionary stack"+nl+
"showpage"+nl+"%%Trailer"+nl+"%%EOF";
o.write(t+nl);
int eof = 4;
if(!eps) {o.write((char)eof);
}
} catch (java.io.IOException ex) {
exception(ex, null, doNotStop);
delete = true;
}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="setPalette">
/** Set the values in "colours[]" depending on diagrConvertColors.
* if diagrConvertColors = 2, then the palete selected in "Spana" is used,
* if found. */
private void setPalette() {
if(psColors == 2) { // "Spana" palette
java.io.FileInputStream fis = null;
java.io.File f = null;
boolean ok = false;
while (true) { // if "Spana" palette not found: break
java.util.Properties propertiesIni = new java.util.Properties();
f = getSpana_Ini();
if(f == null) {
System.out.println("Warning: could not find \"Spana.ini\""+nl+
"default colours will be used.");
break;
}
try {
fis = new java.io.FileInputStream(f);
propertiesIni.load(fis);
} //try
catch (java.io.FileNotFoundException e) {
System.out.println("Warning: file Not found: \""+f.getPath()+"\""+nl+
"default colours will be used.");
break;
} //catch FileNotFoundException
catch (java.io.IOException e) {
System.out.println("Error: \""+e.toString()+"\""+nl+
" while loading file:"+nl+
" \""+f.getPath()+"\""+nl+
"default colours will be used.");
break;
} // catch loading-exception
if(dbg) {System.out.println("Reading colours from \""+f.getPath()+"\".");}
int red, green, blue;
float r, g, b;
String rt, gt, bt;
try{
for(int ii=0; ii < colours.length; ii++) {
String[] c = propertiesIni.getProperty("Disp_Colour["+ii+"]").split(",");
if(c.length >0) {red =Integer.parseInt(c[0]);} else {red=0;}
if(c.length >1) {green =Integer.parseInt(c[1]);} else {green=0;}
if(c.length >2) {blue =Integer.parseInt(c[2]);} else {blue=0;}
r = Math.max(0f, Math.min(1f, (float)Math.max(0, Math.min(255, red))/255f));
g = Math.max(0f, Math.min(1f, (float)Math.max(0, Math.min(255, green))/255f));
b = Math.max(0f, Math.min(1f, (float)Math.max(0, Math.min(255, blue))/255f));
if(r < 0.000001) {rt ="0";} else if(r > 0.999999) {rt ="1";} else {rt = String.valueOf(r);}
if(g < 0.000001) {gt ="0";} else if(g > 0.999999) {gt ="1";} else {gt = String.valueOf(g);}
if(b < 0.000001) {bt ="0";} else if(b > 0.999999) {bt ="1";} else {bt = String.valueOf(b);}
colours[ii] = (rt+" "+gt+" "+bt).trim();
} //for ii
} catch (java.lang.NumberFormatException e) {
System.out.println("Error: \""+e.toString()+"\""+nl+
" while loading file:"+nl+
" \""+f.getPath()+"\""+nl+
"default colours will be used.");
break;
}
ok = true;
break;
} //while
if(!ok) {psColors = 1;} // use the standard colours instead
try{if(fis != null) {fis.close();}}
catch (java.io.IOException e) {
String msg = "Error: "+e.toString();
if(f != null) {msg = msg +nl+"while closing \""+f.getPath()+"\"";}
else {msg = msg +nl+"while closing \"null\"";}
System.out.println(msg);
}
}
if(psColors <=0 || psColors >2) {
for(int i =0; i < colours.length; i++) {
colours[i] = "0 0 0"; //Black
}
return;
}
if(psColors == 1) { // standard palette
colours[0] = "0 0 0"; //Black
colours[1] = "1 0 0"; //light Red
colours[2] = "0.5843 0.2627 0"; //Vermilion
colours[3] = "0 0 1"; //Blue
colours[4] = "0 0.502 0"; //Green
colours[5] = "0.7843 0.549 0"; //Orange
colours[6] = "1 0 1"; //Magenta
colours[7] = "0 0 0.502"; //dark Blue
colours[8] = "0.502 0.502 0.502";//Gray
colours[9] = "0 0.651 1"; //Sky Blue
colours[10]= "0.502 0 1"; //Violet
}
if(dbg) {
System.out.println("Colours in use;");
for(int ii=0; ii < colours.length; ii++) {
System.out.println(" colour["+ii+"] = \""+colours[ii]+"\"");
}
}
} // setPalette()
private java.io.File getSpana_Ini() {
java.io.File p;
boolean ok;
java.util.ArrayList<String> dirs = new java.util.ArrayList<String>(6);
String home = getPathApp();
if(home != null && home.trim().length() >0) {
p = new java.io.File(home);
if(p.exists()) {dirs.add(p.getAbsolutePath());}
}
String homeDrv = System.getenv("HOMEDRIVE");
String homePath = System.getenv("HOMEPATH");
if(homeDrv != null && homeDrv.trim().length() >0 && homeDrv.endsWith(SLASH)) {
homeDrv = homeDrv.substring(0, homeDrv.length()-1);
}
if(homePath != null && homePath.trim().length() >0 && !homePath.startsWith(SLASH)) {
homePath = SLASH + homePath;
}
if((homeDrv != null && homeDrv.trim().length() >0)
&& (homePath != null && homePath.trim().length() >0)) {
if(homePath.endsWith(SLASH)) {homePath = homePath.substring(0, homePath.length()-1);}
p = new java.io.File(homeDrv+homePath+SLASH+".config"+SLASH+"eq-diagr");
if(p.exists()) {dirs.add(p.getAbsolutePath());}
}
home = System.getenv("HOME");
if(home != null && home.trim().length() >0) {
if(home.endsWith(SLASH)) {home = home.substring(0, home.length()-1);}
p = new java.io.File(home+SLASH+".config"+SLASH+"eq-diagr");
if(p.exists()) {dirs.add(p.getAbsolutePath());}
}
home = System.getProperty("user.home");
if(home != null && home.trim().length() >0) {
if(home.endsWith(SLASH)) {home = home.substring(0, home.length()-1);}
p = new java.io.File(home+SLASH+".config"+SLASH+"eq-diagr");
if(p.exists()) {dirs.add(p.getAbsolutePath());}
}
java.io.File f = null;
for(String t : dirs) {
if(t.endsWith(SLASH)) {t = t.substring(0, t.length()-1);}
final String fileINIname = ".Spana.ini";
p = new java.io.File(t+SLASH+fileINIname);
if(p.exists() && p.canRead()) {
if(f != null && p.lastModified() > f.lastModified()) {f = p;}
}
} // for(dirs)
return f;
} // getSpana_Ini()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="setPen">
/** Emulates several pens with line width or colours.
* In black on white mode: if i=8 then the line thickness is changed,
* if i=5 nothing happens.
* In colour mode: if i=5 then the line colour is changed
* (gray scale in non-colour printers), if i=8 nothing happens
* @param i either 5 (change screen colour) or 8 (chenage plotter pen number)
* @param pen0 the colour/pen nbr
* @param o output file */
private void setPen(int i, int pen0, java.io.BufferedWriter o) {
if(i != 5 && i != 8) {return;}
int pen = Math.max(1, pen0);
pen--;
if(i == 5) { // Screen Colour
if(psColors <=0) { //black/white
colorNow = 0;
return;
}
while(pen >= colours.length) {
pen = pen - colours.length;
}
if(pen < 0) {pen = colours.length - pen;}
colorNow = pen;
}
if(i == 8) { // Pen Thickness
while(pen >= WIDTHS.length) {
pen = pen - WIDTHS.length;
}
if(pen < 0) {pen = WIDTHS.length - pen;}
penNow = pen;
}
StringBuilder line = new StringBuilder();
if(psColors >0 && colorNow != colorOld) {
line.append(colours[colorNow]);
line.append(" setrgbcolor");
colorOld = colorNow;
}
if(penNow != penOld) {
double w = Math.max(0.05, (double)WIDTHS[penNow]*(scaleX+scaleY)/2);
if(line.length() >0) {line.append(" ");}
line.append(toStr(w));
line.append(" _setWidth");
penOld = penNow;
}
if(line.length() > 0) {
try{
if(newPath == 2) { //some move/line-draw performed
o.write("_sn "+line.toString()+nl);
newPath =0;
} else {
if(newPath <0) { //start of program
o.write("newpath "+line.toString()+nl);
newPath =0;
} else {
o.write(line.toString()+nl);
}
}
} catch (java.io.IOException ex) {exception(ex, null, doNotStop); delete =true;}
}
} //setPen
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="moveOrDraw">
private void moveOrDraw (int i0, double x0, double y0, java.io.BufferedWriter o) {
// --- newPath: -1 = start of program;
// 0 = no drawing performed yet
// 1 = some move performed
// 2 = some move/line-draw performed
if(newPath < 0) {
try{
o.write("newpath"+nl);
} catch (java.io.IOException ex) {exception(ex, null, doNotStop); delete =true;}
pathCounter = 0;
newPath = 0;
}
double x, y, w;
x = x0*scaleX + zx;
y = y0*scaleY + zy;
//---- move-to: if a drawing has been done: stroke and newpath.
// if i0=0 do not output anything, only save position.
// if i0=-1 force a move-to (for example, before a text-output)
if(i0 <= 0) {
// drawing done?
if(newPath == 2) {
try{
if(Math.abs(x1st-xNow)<0.01 && Math.abs(y1st-yNow)<0.01) {
o.write("_csn"+nl);
} else {
o.write("_sn"+nl);
}
} catch (java.io.IOException ex) {exception(ex, null, doNotStop); delete =true;}
pathCounter = 0;
newPath = 0;
}
x1st = -Double.MAX_VALUE; y1st = -Double.MAX_VALUE;
} //move to
//---- force a move-to
if(i0 < 0) {
try{
o.write(toStr(x)+" "+toStr(y)+" Mv"+nl);
} catch (java.io.IOException ex) {exception(ex, null, doNotStop); delete =true;}
// set flag as nothing done, because after this, text output
// will take place, and after that a new move-to will be necessary.
newPath =0;
x1st = x; y1st = y;
}
//---- draw-to: if necessary do a move-to, then a line-to
if(i0 == 1) {
//line-draw after a 'move', 1st go to last point: xNow/yNow
if(newPath ==0) {
try{
o.write(toStr(xNow)+" "+toStr(yNow)+" Mv"+nl);
} catch (java.io.IOException ex) {exception(ex, null, doNotStop); delete =true;}
newPath = 1;
pathCounter++;
x1st = xNow; y1st = yNow;
} //if newPath =0
try{
o.write(toStr(x)+" "+toStr(y)+" Ln"+nl);
} catch (java.io.IOException ex) {exception(ex, null, doNotStop); delete =true;}
newPath = 2;
pathCounter++;
if(pathCounter >400) {
//currentpoint stroke moveto
try{
o.write("currentpoint stroke moveto"+nl);
} catch (java.io.IOException ex) {exception(ex, null, doNotStop); delete =true;}
x1st = -Double.MAX_VALUE; y1st = -Double.MAX_VALUE;
pathCounter = 0;
}
} //draw to
xNow = x; yNow = y;
} // moveOrDraw
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="toStr(double)">
/** Write a double into a string. If possible, write it
* without the decimal point: 3.1 returns "3.1", while 3.0
* returns "3"
* @param d
* @return */
private static String toStr(double d) {
if(Double.isNaN(d)) {d = 0;}
d = Math.min(999999999999999.9d,Math.max(-999999999999999.9d,d));
String dTxt;
if(Math.abs(d-Math.round(d)) >0.001) {
dTxt = String.format(engl,"%20.2f", d);
} else {dTxt = Long.toString(Math.round(d));}
return dTxt.trim();
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="fixTextSimple">
/** Escape parenthesis and back-slash (that is, change "(" to "\(", etc);
* and change hyphen, "-", to endash.
* @param txt
* @return */
private String fixTextSimple(String txt, boolean isFormula) {
if(txt == null || txt.trim().length() <=0) {return txt;}
/**
* €γερΣΔ‚ƒ„…†‡^‰Š‹ŒŽ‘’“”•–—~™š›œžŸ¤¦¨©ª¬®¯°±²³´μ·¹º¼½¾ÀÁÂÃÄÅÆÇÈÉÊË
* ÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ
*/
StringBuilder t = new StringBuilder(txt);
int i = 0;
while(i < t.length()) {
// "\" change to "\\"
if(t.charAt(i) == '\\') {t.replace(i, i+1, "\\\\"); i++;}
else if(t.charAt(i) == '(') {t.replace(i, i+1, "\\("); i++;}
else if(t.charAt(i) == ')') {t.replace(i, i+1, "\\)"); i++;}
// for hyphen and minus sign
else if(t.charAt(i) == '-' || t.charAt(i) == '−') {t.replace(i, i+1, "\\055"); i = i+3;} // minus in PostScript
// when it is a "formula" then tilde is 'degree sign' and circumflex is 'Delta'
else if(t.charAt(i) == '~' && !isFormula) {t.replace(i, i+1, "\\230"); i = i+3;} //tilde (152 dec)
else if(t.charAt(i) == '^' && !isFormula) {t.replace(i, i+1, "\\210"); i = i+3;} //circumflex (136 dec)
else if(t.charAt(i) == '×') {t.replace(i, i+1, "\\327"); i = i+3;} //multiply
// these are not written properly:
//else if(t.charAt(i) == '€') {t.replace(i, i+1, "\\200"); i = i+3;} //euro (Symbol font)
else if(t.charAt(i) == '‚') {t.replace(i, i+1, "\\140"); i = i+3;} //quotesinglbase (=quoteleft)
//else if(t.charAt(i) == 'ƒ') {t.replace(i, i+1, "\\203"); i = i+3;} //florin (Symbol font)
else if(t.charAt(i) == '„') {t.replace(i, i+1, "\\042"); i = i+3;} //quotedblbase (=quotedbl)
//else if(t.charAt(i) == '…') {t.replace(i, i+1, "\\205"); i = i+3;} //ellipsis (Symbol font)
//else if(t.charAt(i) == '†') {t.replace(i, i+1, "\\174"); i = i+3;} //dagger (StandardEncoding)
//else if(t.charAt(i) == '‡') {t.replace(i, i+1, "\\174"); i = i+3;} //daggerdbl (StandardEncoding)
//else if(t.charAt(i) == '‰') {t.replace(i, i+1, "\\077"); i = i+3;} //perthousand (StandardEncoding)
else if(t.charAt(i) == 'Š') {t.replace(i, i+1, "\\123"); i = i+3;} //Scaron (=S)
else if(t.charAt(i) == '‹') {t.replace(i, i+1, "\\074"); i = i+3;} //guilsinglleft (=< less)
//else if(t.charAt(i) == 'Œ') {t.replace(i, i+1, "\\326"); i = i+3;} //OE (=Ö)
else if(t.charAt(i) == 'Ž') {t.replace(i, i+1, "\\132"); i = i+3;} //Zcaron (=Z)
else if(t.charAt(i) == '‘') {t.replace(i, i+1, "\\140"); i = i+3;} //quoteleft
else if(t.charAt(i) == '’') {t.replace(i, i+1, "\\047"); i = i+3;} //quoteright
else if(t.charAt(i) == '“') {t.replace(i, i+1, "\\042"); i = i+3;} //quotedblleft (=quotedbl)
else if(t.charAt(i) == '”') {t.replace(i, i+1, "\\042"); i = i+3;} //quotedblright (=quotedbl)
//else if(t.charAt(i) == '•') {t.replace(i, i+1, "\\225"); i = i+3;} //bullet (Symbol font)
else if(t.charAt(i) == '–') {t.replace(i, i+1, "\\055"); i = i+3;} //endash (=minus)
else if(t.charAt(i) == '—') {t.replace(i, i+1, "\\055"); i = i+3;} //emdash (=minus)
//else if(t.charAt(i) == '™') {t.replace(i, i+1, "\\231"); i = i+3;} //trademark (Symbol font)
else if(t.charAt(i) == 'š') {t.replace(i, i+1, "\\163"); i = i+3;} //scaron (=s)
else if(t.charAt(i) == '›') {t.replace(i, i+1, "\\076"); i = i+3;} //guilsinglright (=> greater)
//else if(t.charAt(i) == 'œ') {t.replace(i, i+1, "\\366"); i = i+3;} //oe (=ö)
else if(t.charAt(i) == 'ž') {t.replace(i, i+1, "\\172"); i = i+3;} //zcaron (=z)
else if(t.charAt(i) == 'Ÿ') {t.replace(i, i+1, "\\131"); i = i+3;} //Ydieresis (=Y)
else if(t.charAt(i) == '¤') {t.replace(i, i+1, "\\244"); i = i+3;} //currency
else if(t.charAt(i) == '¦') {t.replace(i, i+1, "\\246"); i = i+3;} //brokenbar
else if(t.charAt(i) == '¨') {t.replace(i, i+1, "\\250"); i = i+3;} //dieresis
else if(t.charAt(i) == '©') {t.replace(i, i+1, "\\251"); i = i+3;} //copyright
else if(t.charAt(i) == 'ª') {t.replace(i, i+1, "\\252"); i = i+3;} //ordfeminine
else if(t.charAt(i) == '¬') {t.replace(i, i+1, "\\254"); i = i+3;} //logicalnot
else if(t.charAt(i) == '®') {t.replace(i, i+1, "\\256"); i = i+3;} //registered
else if(t.charAt(i) == '¯') {t.replace(i, i+1, "\\257"); i = i+3;} //macron
else if(t.charAt(i) == '°') {t.replace(i, i+1, "\\260"); i = i+3;} //degree
else if(t.charAt(i) == '±') {t.replace(i, i+1, "\\261"); i = i+3;} //plusminus
else if(t.charAt(i) == '²') {t.replace(i, i+1, "\\262"); i = i+3;} //twosuperior
else if(t.charAt(i) == '³') {t.replace(i, i+1, "\\263"); i = i+3;} //threesuperior
else if(t.charAt(i) == '´') {t.replace(i, i+1, "\\264"); i = i+3;} //acute
else if(t.charAt(i) == 'μ') {t.replace(i, i+1, "\\265"); i = i+3;} //mu
else if(t.charAt(i) == '·') {t.replace(i, i+1, "\\267"); i = i+3;} //periodcentered
else if(t.charAt(i) == '¹') {t.replace(i, i+1, "\\271"); i = i+3;} //onesuperior
else if(t.charAt(i) == 'º') {t.replace(i, i+1, "\\272"); i = i+3;} //ordmasculine
else if(t.charAt(i) == '¼') {t.replace(i, i+1, "\\274"); i = i+3;} //onequarter
else if(t.charAt(i) == '½') {t.replace(i, i+1, "\\275"); i = i+3;} //onehalf
else if(t.charAt(i) == '¾') {t.replace(i, i+1, "\\276"); i = i+3;} //threequarters
else if(t.charAt(i) == 'À') {t.replace(i, i+1, "\\300"); i = i+3;} //Agrave
else if(t.charAt(i) == 'Á') {t.replace(i, i+1, "\\301"); i = i+3;} //Aacute
else if(t.charAt(i) == 'Â') {t.replace(i, i+1, "\\302"); i = i+3;} //Acircumflex
else if(t.charAt(i) == 'Ã') {t.replace(i, i+1, "\\303"); i = i+3;} //Atilde
else if(t.charAt(i) == 'Ä') {t.replace(i, i+1, "\\304"); i = i+3;} //Adieresis
else if(t.charAt(i) == 'Å') {t.replace(i, i+1, "\\305"); i = i+3;} //Aring
else if(t.charAt(i) == 'Æ') {t.replace(i, i+1, "\\306"); i = i+3;} //AE
else if(t.charAt(i) == 'Ç') {t.replace(i, i+1, "\\307"); i = i+3;} //Ccedilla
else if(t.charAt(i) == 'È') {t.replace(i, i+1, "\\310"); i = i+3;} //Egrave
else if(t.charAt(i) == 'É') {t.replace(i, i+1, "\\311"); i = i+3;} //Eacute
else if(t.charAt(i) == 'Ê') {t.replace(i, i+1, "\\312"); i = i+3;} //Ecircumflex
else if(t.charAt(i) == 'Ë') {t.replace(i, i+1, "\\313"); i = i+3;} //Edieresis
else if(t.charAt(i) == 'Ì') {t.replace(i, i+1, "\\314"); i = i+3;} //Igrave
else if(t.charAt(i) == 'Í') {t.replace(i, i+1, "\\315"); i = i+3;} //Iacute
else if(t.charAt(i) == 'Î') {t.replace(i, i+1, "\\316"); i = i+3;} //Icircumflex
else if(t.charAt(i) == 'Ï') {t.replace(i, i+1, "\\317"); i = i+3;} //Idieresis
else if(t.charAt(i) == 'Ð') {t.replace(i, i+1, "\\320"); i = i+3;} //Eth
else if(t.charAt(i) == 'Ñ') {t.replace(i, i+1, "\\321"); i = i+3;} //Ntilde
else if(t.charAt(i) == 'Ò') {t.replace(i, i+1, "\\322"); i = i+3;} //Ograve
else if(t.charAt(i) == 'Ó') {t.replace(i, i+1, "\\323"); i = i+3;} //Oacute
else if(t.charAt(i) == 'Ô') {t.replace(i, i+1, "\\324"); i = i+3;} //Ocircumflex
else if(t.charAt(i) == 'Õ') {t.replace(i, i+1, "\\325"); i = i+3;} //Otilde
else if(t.charAt(i) == 'Ö') {t.replace(i, i+1, "\\326"); i = i+3;} //Odieresis
else if(t.charAt(i) == 'Ø') {t.replace(i, i+1, "\\330"); i = i+3;} //Oslash
else if(t.charAt(i) == 'Ù') {t.replace(i, i+1, "\\331"); i = i+3;} //Ugrave
else if(t.charAt(i) == 'Ú') {t.replace(i, i+1, "\\332"); i = i+3;} //Uacute
else if(t.charAt(i) == 'Û') {t.replace(i, i+1, "\\333"); i = i+3;} //Ucircumflex
else if(t.charAt(i) == 'Ü') {t.replace(i, i+1, "\\334"); i = i+3;} //Udieresis
else if(t.charAt(i) == 'Ý') {t.replace(i, i+1, "\\335"); i = i+3;} //Yacute
else if(t.charAt(i) == 'Þ') {t.replace(i, i+1, "\\336"); i = i+3;} //Thorn
else if(t.charAt(i) == 'ß') {t.replace(i, i+1, "\\337"); i = i+3;} //germandbls
else if(t.charAt(i) == 'à') {t.replace(i, i+1, "\\340"); i = i+3;} //agrave
else if(t.charAt(i) == 'á') {t.replace(i, i+1, "\\341"); i = i+3;} //aacute
else if(t.charAt(i) == 'â') {t.replace(i, i+1, "\\342"); i = i+3;} //acircumflex
else if(t.charAt(i) == 'ã') {t.replace(i, i+1, "\\343"); i = i+3;} //atilde
else if(t.charAt(i) == 'ä') {t.replace(i, i+1, "\\344"); i = i+3;} //adieresis
else if(t.charAt(i) == 'å') {t.replace(i, i+1, "\\345"); i = i+3;} //aring
else if(t.charAt(i) == 'æ') {t.replace(i, i+1, "\\346"); i = i+3;} //ae
else if(t.charAt(i) == 'ç') {t.replace(i, i+1, "\\347"); i = i+3;} //ccedilla
else if(t.charAt(i) == 'è') {t.replace(i, i+1, "\\350"); i = i+3;} //egrave
else if(t.charAt(i) == 'é') {t.replace(i, i+1, "\\351"); i = i+3;} //eacute
else if(t.charAt(i) == 'ê') {t.replace(i, i+1, "\\352"); i = i+3;} //ecircumflex
else if(t.charAt(i) == 'ë') {t.replace(i, i+1, "\\353"); i = i+3;} //edieresis
else if(t.charAt(i) == 'ì') {t.replace(i, i+1, "\\354"); i = i+3;} //igrave
else if(t.charAt(i) == 'í') {t.replace(i, i+1, "\\355"); i = i+3;} //iacute
else if(t.charAt(i) == 'î') {t.replace(i, i+1, "\\356"); i = i+3;} //icircumflex
else if(t.charAt(i) == 'ï') {t.replace(i, i+1, "\\357"); i = i+3;} //idieresis
else if(t.charAt(i) == 'ð') {t.replace(i, i+1, "\\360"); i = i+3;} //eth
else if(t.charAt(i) == 'ñ') {t.replace(i, i+1, "\\361"); i = i+3;} //ntilde
else if(t.charAt(i) == 'ò') {t.replace(i, i+1, "\\362"); i = i+3;} //ograve
else if(t.charAt(i) == 'ó') {t.replace(i, i+1, "\\363"); i = i+3;} //oacute
else if(t.charAt(i) == 'ô') {t.replace(i, i+1, "\\364"); i = i+3;} //ocircumflex
else if(t.charAt(i) == 'õ') {t.replace(i, i+1, "\\365"); i = i+3;} //otilde
else if(t.charAt(i) == 'ö') {t.replace(i, i+1, "\\366"); i = i+3;} //odieresis
else if(t.charAt(i) == '÷') {t.replace(i, i+1, "\\367"); i = i+3;} //divide
else if(t.charAt(i) == 'ø') {t.replace(i, i+1, "\\370"); i = i+3;} //oslash
else if(t.charAt(i) == 'ù') {t.replace(i, i+1, "\\371"); i = i+3;} //ugrave
else if(t.charAt(i) == 'ú') {t.replace(i, i+1, "\\372"); i = i+3;} //uacute
else if(t.charAt(i) == 'û') {t.replace(i, i+1, "\\373"); i = i+3;} //ucircumflex
else if(t.charAt(i) == 'ü') {t.replace(i, i+1, "\\374"); i = i+3;} //udieresis
else if(t.charAt(i) == 'ý') {t.replace(i, i+1, "\\375"); i = i+3;} //yacute
else if(t.charAt(i) == 'þ') {t.replace(i, i+1, "\\376"); i = i+3;} //thorn
else if(t.charAt(i) == 'ÿ') {t.replace(i, i+1, "\\377"); i = i+3;} //ydieresis
i++;
} //while
return t.toString();
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="maybeInQuotes">
private String maybeInQuotes(String t) {
if(t == null || t.length() <=0) {return t;}
boolean encloseInQuotes = false;
final String[] q = {"\"","\""};
for(int i =0; i < t.length(); i++) {
if(Character.isWhitespace(t.charAt(i))) {encloseInQuotes = true;}
}
if(encloseInQuotes) {return (q[0]+t+q[1]);} else {return t;}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="printInstructions()">
private static void printInstructions(java.io.PrintStream out) {
if(out == null) {out = System.out;}
out.flush();
out.println("This program will convert a plot file (*.plt) into a PS file."+nl+
"Usage: java -jar PlotPS.jar [plot-file-name] [-command=value]");
out.println("Possible commands are:"+nl+
" -b=bottom-margin (in cm)"+nl+
" -bw (black on white output)"+nl+
" -clr (colours - standard palette)"+nl+
" -clr2 (colours selected in \"Spana\")"+nl+
" -dbg (output debug information)"+nl+
" -f=font-nbr (1:Vector_Graphics, 2:Times-Roman, 3:Helvetica, 4:Courier)"+nl+
" -l=left-margin (in cm)"+nl+
" -noh (do not make a header with file name and date)"+nl+
" -nostop (do not stop for warnings)"+nl+
" -o=P/L (P: portrait; L: landscape)"+nl+
" -p=plot-file-name (input \"plt\"-file in UTF-8 Unicode ecoding)"+nl+
" -ps=output-file-name (for encapsulated PostScrit set the extention"+nl+
" to \".eps\"; which also sets: -o=P -l=0 -b=0)"+nl+
" -s=% (output size; integer %-value)"+nl+
" -sx=% and -sy=% (different vertical and horizontal scaling)"+nl+
"Enclose file-names with double quotes (\"\") it they contain blank space."+nl+
"Example: java -jar PlotPS.jar \"Fe 53\" -PS=\"ps\\Fe 53.ps\" -s:60 -clr -F:2");
} //printInstructions(out)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="methods to print text">
//<editor-fold defaultstate="collapsed" desc="printText">
/** Print a text string.
* @param i1 x-coordinate
* @param i2 y-coordinate
* @param txt the text to be printed
* @param isFormula if the text is to handled as a chemical formula,
* with super- and sub-scripts
* @param align -1=Left 0=center +1=right
* @param txtSize size in cm
* @param txtAngle angle in degrees
* @param o where the text will be printed */
private void printText(int i1, int i2, String txt,
boolean isFormula, int align, double txtSize, double txtAngle,
java.io.BufferedWriter o) {
//final double[] FontScaleHeight={1.45, 1.35, 1.6};
final double[] FontScaleWidth ={0.7, 0.71, 0.88};
final String[] ALIGNMENTS = {"left","centre","right"};
ChemFormula cf = null;
if(dbg) {
System.out.println("Print text \""+txt+"\""+nl+
" formula:"+isFormula+", align="+align+" size="+txtSize+" angle="+txtAngle);
}
if(txt == null || txt.trim().length() <=0) {return;}
txt = rTrim(txt);
// get angles between +180 and -180
while (txtAngle>360) {txtAngle=txtAngle-360;}
while (txtAngle<-360) {txtAngle=txtAngle+360;}
if(txtAngle>180) {txtAngle=txtAngle-360;}
if(txtAngle<-180) {txtAngle=txtAngle+360;}
// recalculate the angle according to distorsion by different x/y scaling
double newAngle = txtAngle;
double rads = Math.toRadians(txtAngle);
if(Math.abs(txtAngle) > 0.01) {
double w1 = Math.cos(rads)*(scaleX/scaleY), w2 = Math.sin(rads);
newAngle = Math.signum(txtAngle)*Math.toDegrees( Math.acos(w1 / (Math.sqrt(w1*w1 + w2*w2))) );
}
// font size
fontSize = (int)Math.round(100 * ((scaleX+scaleY)/2) * (txtSize + 0.001));
fontSize = Math.min(5000, fontSize);
align = Math.max(-1,Math.min(1,align));
try{
String str= "% text at X,Y= "+String.valueOf(i1)+" "+String.valueOf(i2)+
"; size = "+toStr(txtSize)+"; angle = "+toStr(txtAngle)+"; is formula: "+isFormula+"; alignment:"+ALIGNMENTS[align+1];
o.write(str+nl+"% text is: "+txt+nl);
if(fontSize <=0) {
o.write(str+nl+"% (size too small)"+nl);
return;
} else {
if(fontSize != fontSizeOld) {
fontSizeOld = fontSize;
//fontSizeTxt = String.format(engl, "%15.2f",fontSize).trim();
String fontSizeTxt = String.valueOf(fontSize);
o.write(fontSizeTxt+" _setSize"+nl);
}
}
} catch (java.io.IOException ex) {exception(ex, null, doNotStop); delete = true;}
boolean bold = (penNow == 1);
if(bold != oldBold) {
try{
if(bold) {o.write("_bold"+nl);} else {o.write("_norm"+nl);}
} catch (java.io.IOException ex) {exception(ex, null, doNotStop); delete =true;}
oldBold = bold;
}
boolean containsLetters = false;
char c;
for(int i =0; i < txt.length(); i++) {
c = txt.charAt(i);
if(Character.isDigit(c) || c == '-' || c == '+' || c == '.') {continue;}
containsLetters = true;
break;
}
// if it does not contain letters it can not be a chemical formula
if(!containsLetters || txt.length()<=1) {
isFormula = false;
//align = 0; // center-align?
}
// find out the length of the text, and sub- and super-scripts
int txtLength = txt.length();
if(isFormula && txtLength > 1) {
if(txt.equalsIgnoreCase("log (ai/ar")) {txt = "log (a`i'/a`ref'";}
cf = new ChemFormula(txt, new float[1]);
chemF(cf);
txtLength = cf.t.length();
}
// --- position ---
double xpl = (double)i1;
double ypl = (double)i2;
// --- recalculate position according to alignment etc ---
double w;
// for non-chemical formulas:
// - left aligned: the start position is given
// - right aligned: the start position is
// "exactly" calculated from the text length
// - centre alignment is aproximately calculated
// from the text length, as the width varies
// for different characters
// for chemical formulas:
// alignment is always aproximately calculated
// from the text length, as the width varies
// for different characters
if(!isFormula) { // not a chemical formula
// for plain text: if center-aligned or right-aligned, move the origin
if(align == 1 || align == 0) { //right aligned or centred
w = txtLength; // advance the whole requested text length
if(align == 0) { //centre
w = w /2; // centre means only half
}
w = w * txtSize * 100;
xpl = xpl + w * Math.cos(rads);
ypl = ypl + w * Math.sin(rads);
if(align == 0) { // centered means both in the x-direction and in the y-direction
w = (txtSize * 100) /2; // move 1/2 letter "up"
xpl = xpl + w * Math.cos(rads+Math.PI/2);
ypl = ypl + w * Math.sin(rads+Math.PI/2);
}
}
} else { // it is a chemical formula
if(Math.abs(txtAngle) < 0.01 && align == 0) {
// (only for text not in axis: no special texts like 'pH', etc)
// move the text up slightly (labels on curves look better if they
// do not touch the lines of the curve): increase y-value 0.2*txtSize.
// Also, move the text to the right a bit proportional to text
// length. (only for text not in axis (angle must be zero, or text
// only be numbers, and no special texts like 'pH', etc))
if(!(txt.equals("pH") ||txt.equals("pe") ||txt.startsWith("Log") ||txt.startsWith("E / V"))
&& !txt.contains("`TOT'")) {
// label on a curve or predominance area
ypl = ypl + 0.3*txtSize*100;
}
} //if angle =0
// advance the whole text length minus the "real" text length
w = txt.length() * (1-FontScaleWidth[psFont-1]);
// remove things not printed. For example, in [Fe 3+]`TOT' there are three
// characters not printed: the space before the electrical charge
// and the accents surrounding "TOT"
w = w - (txt.length()-txtLength);
if(align == 0) { w = w /2; }
if(align == 1 || align == 0) { //right aligned or centred
w = w * txtSize * 100;
xpl = xpl + w * Math.cos(rads);
ypl = ypl + w * Math.sin(rads);
}
} // if is formula
// calling moveOrDraw with "-1" forces a move-to
moveOrDraw(-1, xpl, ypl, o);
if(Math.abs(txtAngle) > 0.01) {
try{
o.write("/_angle "+toStr(newAngle) +" def TxtRotate"+nl);
} catch (java.io.IOException ex) {exception(ex, null, doNotStop); delete =true;}
}
// --- do the printing itself ---
if(isFormula && cf != null) { //a chemical formula
String move;
String l2;
int n1 = 0;
int j = 1;
try{
while (j < cf.t.length()) {
if(cf.d[j] != cf.d[j-1]) {
l2 = cf.t.substring(n1, j);
n1 = j;
if(Math.abs(cf.d[j-1]) <0.05) {
move = "lShow";
} else {
move = toStr(cf.d[j-1]) + " ^";
}
l2 = "("+fixText(l2,isFormula,move)+")"+move;
o.write(l2+nl);
}
j++;
} // while
if(n1 <= cf.t.length()) {
l2 = cf.t.substring(n1);
if(Math.abs(cf.d[n1]) <0.05) {
move = "lShow";
} else {
move = toStr(cf.d[n1]) + " ^";
}
l2 = "("+fixText(l2,isFormula,move)+")"+move;
o.write(l2+nl);
}
} catch (java.io.IOException ex) {exception(ex, null, doNotStop); delete =true;}
} // it is a formula
else {
try{
if(align == 1) {
o.write("("+fixTextSimple(txt,isFormula)+")rShow"+nl);
} else if(align == 0) {
o.write("("+fixTextSimple(txt,isFormula)+")cShow"+nl);
} else if(align == -1) {
o.write("("+fixTextSimple(txt,isFormula)+")lShow"+nl);
}
} catch (java.io.IOException ex) {exception(ex, null, doNotStop); delete =true;}
}
if(Math.abs(txtAngle) > 0.05) {
try{
o.write("grestore"+nl);
} catch (java.io.IOException ex) {exception(ex, null, doNotStop); delete = true;}
}
} // printText
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="fixText">
/** Escape parenthesis and back-slash (that is, change "(" to "\(", etc);
* and change hyphen, "-", to endash.
* @param txt
* @param isFormula
* @param move contains a PostScript command specifying how to show the string in "txt".
* It is either "lShow" or "nn.n ^" (for super/sub-scripts). It may be null or empty.
* @return */
private String fixText(String txt, boolean isFormula, String move) {
if(txt == null || txt.trim().length() <=0) {return txt;}
if(move == null) {move = "";}
// change "\", "(" and ")" to "\\", "\(" and "\)"
StringBuilder t = new StringBuilder(fixTextSimple(txt,isFormula));
String fontSizeTxt = String.valueOf(fontSize);
int i = 0;
while(i < t.length()) {
if(isFormula){
if(t.charAt(i) == '~') {t.replace(i, i+1, "\\260"); i = i+4; continue;} //degree
else if(t.charAt(i) == '$') {t.replace(i, i+1, "\\265"); i = i+4; continue;} //mu
}
// Delta:
if(t.charAt(i) == 'Δ' || t.charAt(i) == '∆' || (isFormula && t.charAt(i) == '^')) {
/** String str = ") "+move+" "+ fontSizeTxt + " _setSize _sym (\\104) "+move;
if(penNow == 1) {str = str + " _bold ";} else {str = str + " _norm ";}
fontSizeOld = fontSize;
str = str + fontSizeTxt + " _setSize (";
t.replace(i, i+1, str);
i = i+str.length(); */
i = symChar("104",t,i,move);
continue;
}
// versus:
if(i <= (t.length()-6) && t.substring(i).startsWith("versus")) {
String str = ") "+move+" _em "+ fontSizeTxt + " _setSize (versus) "+move;
if(penNow == 1) {str = str + " _bold ";} else {str = str + " _norm ";}
str = str + fontSizeTxt + " _setSize (";
t.replace(i, i+6, str);
i = i+str.length();
continue;
}
// log: change to lower case
if(i <= (t.length()-4)
&& (t.substring(i).startsWith("Log ") || t.substring(i).startsWith("Log[")
|| t.substring(i).startsWith("Log{"))) {
t.replace(i, i+3, "log");
i = i+3;
continue;
}
// log P: change to lower case "log" and italics "p"
if(i <= (t.length()-5)
&& t.substring(i).toLowerCase().startsWith("log p")) {
String str = "log ) "+move+" _em "+ fontSizeTxt + " _setSize (p) "+move;
if(penNow == 1) {str = str + " _bold ";} else {str = str + " _norm ";}
str = str + fontSizeTxt + " _setSize (";
t.replace(i, i+5, str);
i = i+str.length();
continue;
}
if(t.charAt(i) == '‰') { // perthousand:
i = standardEncodingChar("275",t,i,move); continue;
}
if(t.charAt(i) == '†') { // dagger:
i = standardEncodingChar("262",t,i,move); continue;
}
if(t.charAt(i) == '‡') { // daggerdbl:
i = standardEncodingChar("263",t,i,move); continue;
}
if(t.charAt(i) == 'Œ') { // OE:
i = standardEncodingChar("352",t,i,move); continue;
}
if(t.charAt(i) == 'œ') { // oe:
i = standardEncodingChar("372",t,i,move); continue;
}
if(t.charAt(i) == '€') { // Euro:
i = symChar("240",t,i,move); continue;
}
if(t.charAt(i) == '…') { // elipsis:
i = symChar("274",t,i,move); continue;
}
if(t.charAt(i) == '•') { // bullet:
i = symChar("267",t,i,move); continue;
}
if(t.charAt(i) == '™') { // trademark:
i = symChar("324",t,i,move); continue;
}
if(t.charAt(i) == 'ƒ') { // florin:
i = symChar("246",t,i,move); continue;
}
// Sum:
if(t.charAt(i) == 'Σ' || t.charAt(i) == '∑') {
i = symChar("123",t,i,move); continue;
}
// rho:
if(t.charAt(i) == 'ρ') {
i = symChar("162",t,i,move); continue;
}
// epsilon:γ
if(t.charAt(i) == 'ε') {
i = symChar("145",t,i,move); continue;
}
// gamma:
if(t.charAt(i) == 'γ') {
i = symChar("147",t,i,move); continue;
}
i++;
} //while
return t.toString();
}
private int standardEncodingChar(String code, StringBuilder t, int i, String move) {
String fontSizeTxt = String.valueOf(fontSize);
String f;
if(penNow == 1) {f = "_boldS";} else {f = "_normS";} // StandardEncoding fonts
String str = ") "+move+" "+ fontSizeTxt + " _setSize "+f+" (\\"+code+") "+move;
if(penNow == 1) {str = str + " _bold ";} else {str = str + " _norm ";}
fontSizeOld = fontSize;
str = str + fontSizeTxt + " _setSize (";
t.replace(i, i+1, str);
i = i+str.length();
return i;
}
private int symChar(String code, StringBuilder t, int i, String move) {
String fontSizeTxt = String.valueOf(fontSize);
String str = ") "+move+" "+ fontSizeTxt + " _setSize _sym (\\"+code+") "+move;
if(penNow == 1) {str = str + " _bold ";} else {str = str + " _norm ";}
fontSizeOld = fontSize;
str = str + fontSizeTxt + " _setSize (";
t.replace(i, i+1, str);
i = i+str.length();
return i;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="rTrim">
/** Remove trailing white space. If the argument is null, the return value is null as well.
* @param text input String.
* @return text without trailing white space. */
private static String rTrim(String text) {
if(text == null) {return text;}
//another possibility: ("a" + text).trim().substring(1)
int idx = text.length()-1;
if (idx >= 0) {
//while (idx>=0 && text.charAt(idx) == ' ') {idx--;}
while (idx>=0 && Character.isWhitespace(text.charAt(idx))) {idx--;}
if (idx < 0) {return "";}
else {return text.substring(0,idx+1);}
}
else { //if length =0
return text;
}
} // rTrim
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="class ChemFormula">
/** Class used for input and output from method "chemF" */
static class ChemFormula {
/** t is a StringBuffer with the initial chemical formula given
* to method "chemF", and it will be modified on return
* from chemF, for example "Fe+2" may be changed to "Fe2+". */
StringBuffer t;
/** d float[] returned by method "chemF" with
* super- subscript data for each character position
* in the StringBuffer t returned by chemF. */
float[] d;
/** @param txt String
* @param d_org float[] */
ChemFormula(String txt, float[] d_org) { // constructor
t = new StringBuffer();
//if (t.length()>0) {t.delete(0, t.length());}
t.append(txt);
int nChar = txt.length();
d = new float[nChar];
System.arraycopy(d_org, 0, d, 0, d_org.length); }
} // class ChemFormula
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="chemF">
/** Purpose: given a "chemical formula" in StringBuffer <b>t</b> it returns
* an array <b>d</b> indicating which characters are super- or
* sub-scripted and a new (possibly modified) <b>t</b>.
* Both <b>t</b> and <b>d</b> are stored for input
* and output in objects of class ChemFormula. Note that <b>t</b> may
* be changed, e.g. from "Fe+2" to "Fe2+".
* <p>
* Stores in array <b>d</b> the vertical displacement of each
* character (in units of character height). In the case of HCO3-, for example,
* d(1..3)=0, d(4)=-0.4, d(5)=+0.4
* <p>
* Not only chemical formulas, but this method also "understands" math
* formulas: x'2`, v`i', log`10', 1.35'.`10'-3`
* <p>
* For aqueous ions, the electric charge may be written as either a space and
* the charge (Fe 3+, CO3 2-, Al(OH)2 +), or as a sign followed by a number
* (Fe+3, CO3-2, Al(OH)2+). For charges of +-1: with or without a space
* sepparating the name from the charge (Na+, Cl-, HCO3- or Na +, Cl -, HCO3 -).
* <p>
* Within this method, <b>t</b> may be changed, so that on return:
* <ul><li>formulas Fe+3, CO3-2 are converted to Fe3+ and CO32-
* <li>math formulas: x'2`, v`i', log`10', 1.35'.`10'-3`
* are stripped of "`" and "'"
* <li>@ is used to force next character into base line, and
* the @ is removed (mostly used for names containing digits and
* some math formulas)</ul>
* <p>
* To test:<br>
* <pre>String txt = "Fe(CO3)2-";
* System.out.println("txt = \""+txt+"\","+
* " new txt = \""+chemF(new ChemFormula(txt, new float[1])).t.toString()+"\","+
* " d="+Arrays.toString(chemF(new ChemFormula(txt, new float[1])).d));</pre></p>
*
* <p>Version: 2013-Apr-03.
*
* @param cf ChemFormula
* @return new instance of ChemFormula with d[] of super- subscript
* positions for each character and a modified StingBuffer t. */
private static void chemF(ChemFormula cf) {
int act; // list of actions:
final int REMOVE_CHAR = 0;
final int DOWN = 1;
final int NONE = 2;
final int UP = 3;
final int CONT = 4;
final int END = 6;
int nchr; char t1; char t2; int i;
float dm; float df;
final char M1='\u2013'; // Unicode En Dash
final char M2='\u2212'; // Minus Sign = \u2212
// The characters in the StringBuffer are stored in "int" variables
// Last, Next-to-last, Next-to-Next-to-last
// ow (present character)
// Next, Next-Next, Next-Next-Next
int L; int nL; int nnL; int now; int n; int n2; int n3;
// ASCII Table:
// -----------------------------------------------------------------------------
// 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
// ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9
// -----------------------------------------------------------------------------
// 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
// : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S
// -----------------------------------------------------------------------------
// 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 00 01 02 03 04 05 06 07 08 09
// T U V W X Y Z [ \ ] ^ _ ` a b c d e f g h i j k n m
// -----------------------------------------------------------------------------
//110 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
// n o p q r s t u v w x y z { | } ~
// -----------------------------------------------------------------------------
// If the string is too short: do nothing
StringBuffer t = new StringBuffer();
t.append(cf.t);
L = t.toString().trim().length();
if(L <= 1) {return;}
// Remove trailing space from the StringBuffer
L = t.length(); // total length
nchr = rTrim(t.toString()).length(); // length without trailing space
if(L > nchr) {t.delete(nchr, L);}
// create d and initialize it
float[] d = new float[nchr];
for(i = 0; i < d.length; i++) {d[i] = 0f;}
// set the non-existing characters to "space"
// Last, Next-to-last, Next-to-Next-to-last
L = 32; nL = 32; nnL = 32;
// get the ASCII code
now = t.charAt(0);
// get the following characters
n = 32; if (nchr >=2) {n = t.charAt(1);} // Next
n2 = 32; if (nchr >=3) {n2 = t.charAt(2);} // Next-Next
// dm (Displacement-Math) for '` sequences: 1.5'.`10'-12`, log p`CO2'
dm = 0f;
// df (Displacement-Formulas) in chemical formulas: CO3 2-, Fe 3+, Cl-, Na+
df = 0f;
//
// -----------------------------
// Main Loop
//
i = 0;
main_do_loop:
do {
n3 = 32;
if(nchr >=(i + 4)) {n3 = t.charAt(i + 3);} //Next-Next-Next
// Because a chemical formula only contains supersripts at the end
// (the electric charge), a superscrip character marks the end of a formula.
// Set df=0 after superscript for characters that are not 0:9 + or -
if(df > 0.001f) { // (if last was supercript, i.e. df>0)
if (now <43 || now >57 || now ==44 || now ==46 || now ==47) //not +- 0:9
{df = 0f;}
} //df > 0.001
checks: { // named block of statements to be used with "break"
// ---------------
// for @
// ---------------
// if the character is @, do nothing; if last char. was @, treat "now" as a
// "normal" char. (and therefore, if last char. was @, and "now" is a space,
// leave a blank space);
if(now ==64 && L !=64) { act =REMOVE_CHAR; break checks;}
if(L ==64) { // @
if(now ==32) {act =CONT;} else {act =NONE;}
break checks;
} // Last=@
// ---------------
// for Ctrl-B (backspace)
// ---------------
if(now ==2) {
now = n; n = n2; n2 = n3;
act =END; break checks;
} // now = backspace
// ---------------
// for ' or `
// ---------------
if(now ==39 || now ==96) {
// for '`, `' sequences: change the value of variable dm.
// if it is a ' and we are writing a "normal"-line, and next is either
// blank or s (like it's or it's.): write it normal
if(now ==39 && dm ==0
&& ( (n ==32 && L ==115)
|| (n ==115 && (n2==32||n2==46||n2==44||n2==58||n2==59||n2==63
||n2==33||n2==41||n2==93)) ) )
{act =CONT; break checks;}
if(now ==39) {dm = dm + 0.5f;}
if(now ==96) {dm = dm - 0.5f;}
act =REMOVE_CHAR; break checks;
} // now = ' or `
// ---------------
// for BLANK (space)
// ---------------
// Decide if the blank must be printed or not.
// In front of an electric charge: do not print (like CO3 2-, etc)
if(now ==32) {
// if next char. is not a digit (1:9) and not (+-), make a normal blank
if((n <49 && (n !=43 && n !=45 &&n!=M1&&n!=M2)) || n >57) {act =NONE; break checks;}
// Space and next is a digit or +-:
// if next is (+-) and last (+-) make a normal blank
if((n ==43 || n ==45 || n==M1||n==M2)
&& (L ==43 || L ==45 ||L==M1||L==M2)) {act =NONE; break checks;}
// if the 2nd-next is letter (A-Z, a-z), make a normal blank
if((n2 >=65 && n2 <=90) || (n2 >=97 && n2 <=122)) {act =NONE; break checks;}
// if next is a digit (1-9)
if(n >=49 && n <=57) { // 1:9
// and 2nd-next is also a digit and 3rd-next is +- " 12+"
if(n2 >=48 && n2 <=57) { // 0:9
if (n3 !=43 && n3 !=45 &&n3!=M1&&n3!=M2) {act =NONE; break checks;} // n3=+:-
} // n2=0:9
// if next is (1-9) and 2nd-next is not either + or -, make a blank
else if (n2 !=43 && n2 !=45 &&n2!=M1&&n2!=M2) {act =NONE; break checks;}
} // n=1:9
// if last char. was blank, make a blank
if(L ==32) {act =NONE; break checks;} // 110 //
// if last char. was neither a letter (A-Z,a-z) nor a digit (0:9),
// and was not )]}"'>, make a blank
if((L <48 || L >122 || (L >=58 && L <=64) || (L >=91 && L<= 96))
&& (L !=41 && L !=93 && L !=125 && L !=62 && L !=34 && L !=39))
{act =NONE; break checks;}
// Blanks followed either by + or -, or by a digit (1-9) and a + or -
// and preceeded by either )]}"'> or a letter or a digit:
// do not make a blank space.
act =REMOVE_CHAR; break checks;
} //now = 32
// ---------------
// for Numbers (0:9)
// ---------------
// In general a digit is a subscript, except for electric charges...etc
if(now >=48 && now <=57) {
// if last char. is either ([{+- or an impossible chem.name,
// then write it "normal"
if(L !=40 && L !=91 && L !=123 && L !=45 &&L!=M1&&L!=M2&& L !=43) { // Last not ([{+-
if((L ==106 || L ==74) || (L ==113 || L ==81)) {act =NONE; break checks;} // jJ qQ
if((L ==120 || L ==88) || (L ==122 || L ==90)) {act =NONE; break checks;} // xX zZ
//if last char. is )]} or a letter (A-Z,a-z): write it 1/2 line down
if((L >=65 && L <=90) || (L >=97 && L <=122)) {act =DOWN; break checks;} // A-Z a-z
if(L ==41 || L ==93 || L ==125) {act =DOWN; break checks;} // )]}
//if last char. is (0:9 or .) 1/2 line (down or up), keep it
if(df >0.01f && ((L >=48 && L <=57) || L ==46)) {act =CONT; break checks;}
if(df <-0.01f && (L ==46 || (L >=48 && L <=57))) {act =CONT; break checks;}
} // Last not ([{+-
// it is a digit and last char. is not either of ([{+-)]} or A:Z a:z
// is it an electric charge?
df = 0f; //125//
// if last char is space, and next char. is a digit and 2nd-next is a +-
// (like: W14O41 10+) then write it "up"
if(L ==32 && (n >=48 && n <=57)
&& (n2 ==43 || n2 ==45 ||n2 ==M1||n2 ==M2) && now !=48) {
//if 3rd-next char. is not (space, )]}), write it "normal"
if(n3 !=32 && n3 !=41 && n3 !=93 && n3 !=125) {act =CONT; break checks;} // )]}
act =UP; break checks;
}
// if last is not space or next char. is not one of +-, then write it "normal"
if(L !=32 || (n !=43 && n !=45 &&n!=M1&&n!=M2)) {act =CONT; break checks;} // +-
// Next is +-:
// if 2nd-next char. is a digit or letter, write it "normal"
if((n2 >=48 && n2 <=57) || (n2 >=65 && n2 <=90)
|| (n2 >=97 && n2 <=122)) {act =CONT; break checks;} // 0:9 A:Z a:z
// if last char. was a digit or a blank, write it 1/2 line up
// if ((L >=48 && L <=57) || L ==32) {act =UP; break checks;}
// act =CONT; break checks;
act =UP; break checks;
} // now = (0:9)
// ---------------
// for Signs (+ or -)
// ---------------
// Decide if it is an electric charge...
// and convert things like: CO3-2 to: CO3 2-
if(now ==43 || now ==45 ||now ==M1||now ==M2) {
// First check for charges like: Fe 2+ and W16O24 11-
// If last char. was a digit (2:9) written 1/2 line up, write it
// also 1/2 line up (as an electrical charge in H+ or Fe 3+).
if(L >=50 && L <=57 && df >0.01f) {act =UP; break checks;} // 2:9
// charges like: W16O24 11-
if((L >=48 && L <=57) && (nL >=49 && nL <=57)
&& (df >0.01f)) {act =UP; break checks;} // 0:9 1:9
//is it a charge like: Fe+3 ? ------------------------
if(n >=49 && n <=57) { // 1:9
// it is a +- and last is not superscript and next is a number:
// check for impossible cases:
// if 2nd to last was a digit or a period and next a digit: 1.0E-1, 2E-3, etc
if(((nL >=48 && nL <=57) || nL ==46) && (L ==69 || L==101)) {act =NONE; break checks;} // 09.E
if(L ==32) {act =NONE; break checks;} // space
if((L ==106 || L ==74) || (L ==113 || L ==81)) {act =NONE; break checks;} // jJ qQ
if((L ==120 || L ==88) || (L ==122 || L ==90)) {act =NONE; break checks;} // xX zZ
// if last was 0 and 2nd to last 1 and dm>0 (for 10'-3` 10'-3.1` or 10'-36`)
if(dm >0.01f && (L ==39 && nL ==48 && nnL ==49)
&& (n >=49 && n <=57)
&& (n2 ==46 || n2 ==96 || (n2 >=48 && n2 <=57))) {act =NONE; break checks;}
// allowed in L: numbers, letters and )]}"'
// 1st Line: !#$%&(*+,-./ 2nd line: {|~:;<=?@ 3rd Line: [\^_`
if((L <48 && L !=41 && L !=34 && L !=39)
|| (L >122 && L !=125) || (L >=58 && L <=64 && L !=62)
|| (L >=91 && L <=96 && L !=93)) {act =NONE; break checks;}
if((L ==41 || L ==93 || L ==125 || L ==34 || L ==39)
&& (nL ==32 || nL <48 || nL >122 || (nL >=58 && nL <=64)
|| (nL >=91 && nL <=96))) {act =NONE; break checks;} // )]}"'
// allowed in n2: numbers and space )']`}
// 1st Line: !"#$%&(*+,-./ 2nd Line: except ]`}
if((n2 <48 && n2 !=41 && n2 !=32 && n2 !=39)
|| (n2 >57 && n2 !=93 && n2 !=96 && n2 !=125)) {act =NONE; break checks;}
//it is a +- and last is not superscript and next is a number:
// is it a charge like: W14O41-10 ?
if((n >=49 && n <=57) && (n2 >=48 && n2 <=57)) { // 1:9 0:9
// characters allowed after the electric charge: )]}`'@= space and backsp
if(n3 !=32 && n3 !=2 && n3 !=41 && n3 !=93 && n3 !=125
&& n3 !=96 && n3 !=39 && n3 !=64 && n3 !=61) {act =NONE; break checks;}
// it is a formula like "W12O41-10" convert to "W12O41 10-" and move "up"
t1 = t.charAt(i+1); t2 = t.charAt(i+2);
t.setCharAt(i+2, t.charAt(i));
t.setCharAt(i+1, t2);
t.setCharAt(i, t1);
int j1 = n; int j2 = n2;
n2 = now;
n = j2; now = j1;
act =UP; break checks;
} // 1:9 0:9
// is it a charge like Fe+3, CO3-2 ?
if(n >=50 && n <=57) { // 2:9
//it is a formula of type Fe+3 or CO3-2
// convert it to Fe3+ or CO32- and move "up"
t1 = t.charAt(i+1);
t.setCharAt(i+1, t.charAt(i));
t.setCharAt(i, t1);
int j = n; n = now; now = j;
act =UP; break checks;
} // 2:9
} // 1:9
// it is a +- and last is not superscript and: next is not a number:
// write it 1/2 line up (H+, Cl-, Na +, HCO3 -), except:
// 1) if last char. was either JQXZ, or not blank-letter-digit-or-)]}, or
// 2) if next char. is not blank or )}]
// 3) if last char. is blank or )]}"' and next-to-last is not letter or digit
if(L ==106 || L ==74 || L ==113 || L ==81) {act =NONE; break checks;} // jJ qQ
if(L ==120 || L ==88 || L ==122 || L ==90) {act =NONE; break checks;} // xX zZ
if(L ==32 || L ==41 || L ==93 || L ==125) { // space )]}
//1st Line: !"#$%&'(*+,-./{|}~ 2nd Line: :;<=>?@[\^_`
if(nL ==32 || (nL <48 && nL !=41) || (nL >122)
|| (nL >=58 && nL <=64)
|| (nL >=91 && nL <=96 && nL !=93)) {act =NONE; break checks;}
act =UP; break checks;
} // space )]}
// 1st Line: !#$%&(*+,-./{|~ 2nd Line: :;<=>?@[\^_`
if((L <48 && L !=41 && L !=34 && L !=39)
|| (L >122 && L !=125) || (L >=58 && L <=64)
|| (L >=91 && L <=96 && L !=93)) {act =NONE; break checks;}
if(n !=32 && n !=41 && n !=93 && n !=125 && n !=61
&& n !=39 && n !=96) {act =NONE; break checks;} // )]}=`'
act =UP; break checks;
} // (+ or -)
// ---------------
// for Period (.)
// ---------------
if (now ==46) {
// if last char was a digit (0:9) written 1/2 line (down or up)
// and next char is also a digit, continue 1/2 line (down or up)
if((L >=48 && L <=57) && (n >=48 && n <=57)) {act =CONT; break checks;} // 0:9
act =NONE; break checks;
} // (.)
act =NONE;
} // --------------- "checks" (end of block name)
switch_action:
switch (act) {
case REMOVE_CHAR:
// ---------------
// take OUT present character //150//
if(i <nchr) {t.deleteCharAt(i);}
nchr = nchr - 1;
nnL = nL; nL = L; L = now; now = n; n = n2; n2 = n3;
continue; // main_do_loop;
case DOWN:
df = -0.4f; // 170 //
break; // switch_action;
case NONE:
df = 0.0f; // 180 //
break; // switch_action;
case UP:
df = 0.4f; // 190 //
break; // switch_action;
case CONT:
case END:
default:
} // switch_action
if(act != END) {// - - - - - - - - - - - - - - - - - - - // 200 //
nnL = nL;
nL = L;
L = now;
now = n;
n = n2;
n2 = n3;
}
d[i] = dm + df; //201//
i = i + 1;
} while (i < nchr); // main do-loop
// finished
// store results in ChemFormula cf
if(cf.t.length()>0) {cf.t.delete(0, cf.t.length());}
cf.t.append(t);
cf.d = new float[nchr];
System.arraycopy(d, 0, cf.d, 0, nchr);
// return;
} // ChemFormula chemF
//</editor-fold>
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="exception(Exception ex)">
/** return the message "msg" surrounded by lines, including the calling method.
* @param ex
* @param msg
* @param doNotStop
*/
private static void exception(Exception ex, String msg, boolean doNotStop) {
final String ERR_START = "============================";
String errMsg = ERR_START;
String exMsg = ex.toString();
if(exMsg == null || exMsg.length() <=0) {exMsg = "Unknown error.";} else {exMsg = "Error: "+exMsg;}
errMsg = errMsg +nl+ exMsg;
if(msg != null && msg.trim().length() >0) {errMsg = errMsg + nl + msg;}
errMsg = errMsg + nl +stack2string(ex) + nl + ERR_START;
if(doNotStop) {System.out.println(errMsg);} else {ErrMsgBx mb = new ErrMsgBx(errMsg,progName);}
} //error(msg)
//<editor-fold defaultstate="collapsed" desc="stack2string(Exception e)">
/** returns a <code>printStackTrace</code> in a String, surrounded by two dash-lines.
* @param e Exception
* @return printStackTrace */
private static String stack2string(Exception e) {
try{
java.io.StringWriter sw = new java.io.StringWriter();
java.io.PrintWriter pw = new java.io.PrintWriter(sw);
e.printStackTrace(pw);
String t = sw.toString();
if(t != null && t.length() >0) {
int i = t.indexOf("Unknown Source");
int j = t.indexOf("\n");
if(i>0 && i > j) {
t = t.substring(0,i);
j = t.lastIndexOf("\n");
if(j>0) {t = t.substring(0,j)+nl;}
}
}
return "- - - - - -"+nl+
t +
"- - - - - -";
}
catch(Exception e2) {
return "Internal error in \"stack2string(Exception e)\"";
}
} //stack2string(ex)
//</editor-fold>
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="getPathApp">
/** Get the path where an application is located.
* @return the directory where the application is located,
* or "user.dir" if an error occurs
* @version 2014-Jan-17 */
private static class C {private static void C(){}}
public static String getPathApp() {
C c = new C();
String path;
java.net.URI dir;
try{
dir = c.getClass().
getProtectionDomain().
getCodeSource().
getLocation().
toURI();
if(dir != null) {
String d = dir.toString();
if(d.startsWith("jar:") && d.endsWith("!/")) {
d = d.substring(4, d.length()-2);
dir = new java.net.URI(d);
}
path = (new java.io.File(dir.getPath())).getParent();
} else {path = System.getProperty("user.dir");}
}
catch (java.net.URISyntaxException e) {
if(!started) {
ErrMsgBx emb = new ErrMsgBx("Error: "+e.toString()+nl+
" trying to get the application's directory.", progName);
}
path = System.getProperty("user.dir");
} // catch
started = true;
return path;
} //getPathApp()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="ErrMsgBx">
/** Displays a "message box" modal dialog with an "OK" button.<br>
* Why is this needed? For any java console application: if started using
* javaw.exe (on Windows) or through a ProcessBuilder, no console will appear.
* Error messages are then "lost" unless a log-file is generated and the user
* reads it. This class allows the program to stop running and wait for the user
* to confirm that the error message has been read.
* <br>
* A small frame (window) is first created and made visible. This frame is
* the parent to the modal "message box" dialog, and it has an icon on the
* task bar (Windows). Then the modal dialog is displayed on top of the
* small parent frame.
* <br>
* Copyright (C) 2015 I.Puigdomenech.
* @author Ignasi Puigdomenech
* @version 2015-July-14 */
static class ErrMsgBx {
/** Displays a "message box" modal dialog with an "OK" button and a title.
* The message is displayed in a text area (non-editable),
* which can be copied and pasted elsewhere.
* @param msg will be displayed in a text area, and line breaks may be
* included, for example: <code>new MsgBox("Very\nbad!",""); </code>
* If null or empty nothing is done.
* @param title for the dialog. If null or empty, "Error:" is used
* @version 2014-July-14 */
public ErrMsgBx(String msg, String title) {
if(msg == null || msg.trim().length() <=0) {
System.out.println("--- MsgBox: null or empty \"message\".");
return;
}
//--- Title
if(title == null || title.length() <=0) {title = " Error:";}
java.awt.Frame frame = new java.awt.Frame(title);
//--- Icon
String iconName = "images/ErrMsgBx.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
if(imgURL != null) {frame.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());}
else {System.out.println("--- Error in MsgBox constructor: Could not load image = \""+iconName+"\"");}
frame.pack();
//--- centre Window frame on Screen
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int left; int top;
left = Math.max(55, (screenSize.width - frame.getWidth() ) / 2);
top = Math.max(10, (screenSize.height - frame.getHeight()) / 2);
frame.setLocation(Math.min(screenSize.width-100, left), Math.min(screenSize.height-100, top));
//---
final String msgText = wrapString(msg.trim(),80);
//System.out.println("--- MsgBox:"+nl+msgText+nl+"---");
frame.setVisible(true);
//javax.swing.JOptionPane.showMessageDialog(frame, msg, title, javax.swing.JOptionPane.ERROR_MESSAGE);
MsgBoxDialog msgBox = new MsgBoxDialog(frame, msgText, title, true);
msgBox.setVisible(true); // becase the dialog is modal, statements below will wait
msgBox.dispose();
frame.setVisible(false);
frame.dispose();
}
/** Returns an input string, with lines that are longer than <code>maxLength</code>
* word-wrapped and indented. *
* @param s input string
* @param maxLength if an input line is longer than this length,
* the line will be word-wrapped at the first white space after <code>maxLength</code>
* and indented with 4 spaces
* @return string with long-lines word-wrapped
*/
public static String wrapString(String s, int maxLength) {
String deliminator = "\n";
StringBuilder result = new StringBuilder();
StringBuffer wrapLine;
int lastdelimPos;
for (String line : s.split(deliminator, -1)) {
if(line.length()/(maxLength+1) < 1) {
result.append(line).append(deliminator);
}
else { //line too long, try to split it
wrapLine = new StringBuffer();
lastdelimPos = 0;
for (String token : line.trim().split("\\s+", -1)) {
if (wrapLine.length() - lastdelimPos + token.length() > maxLength) {
if(wrapLine.length()>0) {wrapLine.append(deliminator);}
wrapLine.append(" ").append(token);
lastdelimPos = wrapLine.length() + 1;
} else {
if(wrapLine.length() <=0) {wrapLine.append(token);}
else {wrapLine.append(" ").append(token);}
}
}
result.append(wrapLine).append(deliminator);
}
}
return result.toString();
}
//<editor-fold defaultstate="collapsed" desc="MsgBoxDialog">
private static class MsgBoxDialog extends java.awt.Dialog {
private java.awt.Button ok;
private java.awt.Panel p;
private final java.awt.TextArea text;
/** Creates new form NewDialog */
public MsgBoxDialog(java.awt.Frame parent, String msg, String title, boolean modal) {
super(parent, (" "+title), modal);
addWindowListener(new java.awt.event.WindowAdapter() {
@Override public void windowClosing(java.awt.event.WindowEvent evt) {
MsgBoxDialog.this.setVisible(false);
}
});
setLayout(new java.awt.BorderLayout());
p = new java.awt.Panel();
p.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER));
ok = new java.awt.Button();
// find out the size of the message (width and height)
final int wMax = 85; final int hMax=20;
final int wMin = 5; final int hMin = 1;
int w = wMin;
int h=hMin; int i=0; int j=wMin;
final String eol = "\n"; char c;
final String nl = System.getProperty("line.separator");
while (true) {
c = msg.charAt(i);
String s = String.valueOf(c);
if(s.equals(eol) || s.equals(nl)) {
h++; j=wMin;
} else {
j++; w = Math.max(j,w);
}
i++;
if(i >= msg.length()-1) {break;}
}
// create a text area
int scroll = java.awt.TextArea.SCROLLBARS_NONE;
if(w > wMax && h <= hMax) {scroll = scroll & java.awt.TextArea.SCROLLBARS_HORIZONTAL_ONLY;}
if(h > hMax && w <= wMax) {scroll = scroll & java.awt.TextArea.SCROLLBARS_VERTICAL_ONLY;}
if(w > wMax && h > hMax) {scroll = java.awt.TextArea.SCROLLBARS_BOTH;}
w = Math.min(Math.max(w,10),wMax);
h = Math.min(h,hMax);
text = new java.awt.TextArea(msg, h, w, scroll);
text.setEditable(false);
//text.setBackground(java.awt.Color.white);
text.addKeyListener(new java.awt.event.KeyAdapter() {
@Override public void keyPressed(java.awt.event.KeyEvent evt) {
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER
|| evt.getKeyCode() == java.awt.event.KeyEvent.VK_ESCAPE) {closeDialog();}
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_TAB) {ok.requestFocusInWindow();}
}
});
text.setBackground(java.awt.Color.WHITE);
text.setFont(new java.awt.Font("monospaced", java.awt.Font.PLAIN, 12));
add(text, java.awt.BorderLayout.CENTER);
ok.setLabel("OK");
ok.addActionListener(new java.awt.event.ActionListener() {
@Override public void actionPerformed(java.awt.event.ActionEvent evt) {
closeDialog();
}
});
ok.addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER
|| evt.getKeyCode() == java.awt.event.KeyEvent.VK_ESCAPE) {closeDialog();}
}
});
p.add(ok);
add(p, java.awt.BorderLayout.SOUTH);
pack();
ok.requestFocusInWindow();
//--- centre Window frame on Screen
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int left; int top;
left = Math.max(55, (screenSize.width - getWidth() ) / 2);
top = Math.max(10, (screenSize.height - getHeight()) / 2);
setLocation(Math.min(screenSize.width-100, left), Math.min(screenSize.height-100, top));
}
private void closeDialog() {this.setVisible(false);}
} // private static class MsgBoxDialog
//</editor-fold>
} // static class ErrMsgBx
//</editor-fold>
}
| 122,691 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
AddShowRefs.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/AddShowReferences/src/addShowRefs/AddShowRefs.java | package addShowRefs;
import java.util.Arrays;
import lib.huvud.ProgramConf;
import lib.common.Util;
import lib.database.References;
/**
* Copyright (C) 2015-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class AddShowRefs extends javax.swing.JFrame {
// Note: for java 1.6 jComboBox must not have type,
// for java 1.7 jComboBox must be <String>
private final String pathApp;
private static final String progName = "AddRefs";
private References r = null;
/** true if it is possible to write to the references-file;
* false if the file is read-only */
private boolean canWriteRefs = true;
private java.awt.Dimension windowSize = new java.awt.Dimension(400,280);
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
private static final String SLASH = java.io.File.separator;
/** Creates new form AddShowRefs */
public AddShowRefs() {
initComponents();
pathApp = Main.getPathApp();
this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
//--- F1 for help
javax.swing.KeyStroke f1KeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_F1,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(f1KeyStroke,"F1");
javax.swing.Action f1Action = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
AddShowRefs.this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
Thread hlp = new Thread() {@Override public void run(){
String[] a = {"DB_Supplied_htm"};
lib.huvud.RunProgr.runProgramInProcess(null,ProgramConf.HELP_JAR,a,false,false,Main.getPathApp());
try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec
catch (InterruptedException e) {}
AddShowRefs.this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
}};//new Thread
hlp.start();
}};
getRootPane().getActionMap().put("F1", f1Action);
//---- Position the window on the screen
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
java.awt.Point frameLocation = new java.awt.Point(-1000,-1000);
frameLocation.x = Math.max(0, (screenSize.width - this.getWidth() ) / 2);
frameLocation.y = Math.max(0, (screenSize.height - this.getHeight() ) / 2);
this.setLocation(frameLocation);
//---- Icon
String iconName = "images/Refs.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
java.awt.Image icon;
if (imgURL != null) {
icon = new javax.swing.ImageIcon(imgURL).getImage();
this.setIconImage(icon);
//com.apple.eawt.Application.getApplication().setDockIconImage(new javax.swing.ImageIcon("Football.png").getImage());
if(System.getProperty("os.name").startsWith("Mac OS")) {
try {
Class<?> c = Class.forName("com.apple.eawt.Application");
//Class params[] = new Class[] {java.awt.Image.class};
java.lang.reflect.Method m =
c.getDeclaredMethod("setDockIconImage",new Class[] { java.awt.Image.class });
Object i = c.newInstance();
Object paramsObj[] = new Object[]{icon};
m.invoke(i, paramsObj);
} catch (Exception e) {System.out.println("Error: "+e.getMessage());}
}
} else {
System.out.println("Error: Could not load image = \""+iconName+"\"");
}
jComboBoxKeys.removeAllItems();
jComboBoxKeys.setEnabled(false);
jButtonShow.setEnabled(false);
jButtonEdit.setEnabled(false);
jButtonAdd.setEnabled(false);
jLabelFileName.setText("(not selected yet...)");
this.setTitle("Show references");
}
private void start() {
AddShowRefs.this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
jButtonShow.setEnabled(false);
jButtonEdit.setEnabled(false);
jButtonAdd.setEnabled(false);
String t = getFileName(this);
if(t == null) {
this.dispose();
return;
} else {
AddShowRefs.this.setVisible(true);
jLabelFileName.setText(t);
}
AddShowRefs.this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
r = new References();
if(!r.readRefsFile(t, false)) {
String msg = "File:"+nl+" "+t+nl+"does not exist."+nl+nl+
"Create?"+nl+" ";
Object[] opt = {"Yes", "Exit"};
int m = javax.swing.JOptionPane.showOptionDialog(this, msg,
"Save/Show References", javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[1]);
if(m != javax.swing.JOptionPane.YES_OPTION) {
this.dispose();
return;
}
r.saveRefsFile(this, true);
}
fillComboBox();
jButtonShow.setEnabled(true);
windowSize = AddShowRefs.this.getSize();
jButtonEdit.setEnabled(canWriteRefs);
jButtonAdd.setEnabled(canWriteRefs);
AddShowRefs.this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel0 = new javax.swing.JLabel();
jLabelFileName = new javax.swing.JLabel();
jButtonAdd = new javax.swing.JButton();
jButtonQuit = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jComboBoxKeys = new javax.swing.JComboBox<>();
jButtonShow = new javax.swing.JButton();
jButtonEdit = new javax.swing.JButton();
jLabelUnicode = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jLabel0.setText("Reference file:");
jLabelFileName.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabelFileName.setText("jLabelFileName");
jButtonAdd.setMnemonic('a');
jButtonAdd.setText(" Add new reference ");
jButtonAdd.setAlignmentX(0.5F);
jButtonAdd.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonAddActionPerformed(evt);
}
});
jButtonQuit.setMnemonic('x');
jButtonQuit.setText(" Exit ");
jButtonQuit.setAlignmentX(0.5F);
jButtonQuit.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonQuit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonQuitActionPerformed(evt);
}
});
jLabel1.setText("Keys:");
jComboBoxKeys.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jButtonShow.setMnemonic('s');
jButtonShow.setText(" Show ");
jButtonShow.setAlignmentX(0.5F);
jButtonShow.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonShow.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonShowActionPerformed(evt);
}
});
jButtonEdit.setMnemonic('e');
jButtonEdit.setText(" Edit ");
jButtonEdit.setAlignmentX(0.5F);
jButtonEdit.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonEdit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonEditActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jButtonShow)
.addGap(18, 18, 18)
.addComponent(jButtonEdit))
.addComponent(jComboBoxKeys, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 10, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBoxKeys, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonShow)
.addComponent(jButtonEdit)))
);
jLabelUnicode.setText("(Unicode UTF-8)");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jLabel0, javax.swing.GroupLayout.DEFAULT_SIZE, 313, Short.MAX_VALUE)
.addGap(33, 33, 33))
.addGroup(layout.createSequentialGroup()
.addComponent(jButtonQuit)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabelUnicode))
.addComponent(jLabelFileName, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButtonAdd))
.addGap(0, 0, Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel0)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabelFileName)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButtonAdd)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButtonQuit)
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jLabelUnicode))))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
if(windowSize != null) {
int w = windowSize.width;
int h = windowSize.height;
if(this.getHeight()<h){this.setSize(this.getWidth(), h);}
if(this.getWidth()<w){this.setSize(w,this.getHeight());}
}
}//GEN-LAST:event_formComponentResized
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
this.dispose();
}//GEN-LAST:event_formWindowClosing
private void jButtonQuitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonQuitActionPerformed
this.dispose();
}//GEN-LAST:event_jButtonQuitActionPerformed
private void jButtonAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAddActionPerformed
if(!canWriteRefs) {return;}
this.setVisible(false);
Thread t = new Thread() {@Override public void run(){
EditAddRefs sr = new EditAddRefs(r);
sr.setVisible(true);
sr.start();
final String k = sr.waitFor();
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override
public void run() {
AddShowRefs.this.setVisible(true);
AddShowRefs.this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
fillComboBox();
setComboBoxKey(k);
AddShowRefs.this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
}}); //invokeLater(Runnable)
}};//new Thread
t.start();
}//GEN-LAST:event_jButtonAddActionPerformed
private void jButtonShowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonShowActionPerformed
if(jComboBoxKeys.getSelectedIndex()<0) {
javax.swing.JOptionPane.showMessageDialog(this, "No key is selected?", "Show refs", javax.swing.JOptionPane.QUESTION_MESSAGE);
return;
}
java.util.ArrayList<String> a = new java.util.ArrayList<String>();
a.add(jComboBoxKeys.getSelectedItem().toString());
r.displayRefs(this, true, null, a);
}//GEN-LAST:event_jButtonShowActionPerformed
private void jButtonEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEditActionPerformed
if(!canWriteRefs) {return;}
if(jComboBoxKeys.getSelectedIndex()<0) {
javax.swing.JOptionPane.showMessageDialog(this, "No key is selected?", "Show refs", javax.swing.JOptionPane.QUESTION_MESSAGE);
return;
}
this.setVisible(false);
Thread t = new Thread() {@Override public void run(){
EditAddRefs sr = new EditAddRefs(r);
sr.setVisible(true);
String key = jComboBoxKeys.getSelectedItem().toString();
String reftxt = r.isRefThere(key);
sr.start(key,reftxt);
final String k = sr.waitFor();
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override
public void run() {
AddShowRefs.this.setVisible(true);
fillComboBox();
setComboBoxKey(k);
}}); //invokeLater(Runnable)
}};//new Thread
t.start();
}//GEN-LAST:event_jButtonEditActionPerformed
private void fillComboBox() {
String[] k = r.referenceKeys();
if(k == null || k.length <=0) {
jComboBoxKeys.removeAllItems();
jComboBoxKeys.setEnabled(false);
jButtonShow.setEnabled(false);
jButtonEdit.setEnabled(false);
jButtonAdd.setEnabled(false);
return;
}
jComboBoxKeys.setEnabled(true);
jButtonShow.setEnabled(true);
jButtonEdit.setEnabled(true);
jButtonAdd.setEnabled(true);
javax.swing.DefaultComboBoxModel<String> dcbm = new javax.swing.DefaultComboBoxModel<>();
//javax.swing.DefaultComboBoxModel dcbm = new javax.swing.DefaultComboBoxModel(); // java 1.6
java.util.ArrayList<String> keyList2 = new java.util.ArrayList<String>();
keyList2.addAll(Arrays.asList(k));
java.util.Collections.sort(keyList2);
k = keyList2.toArray(new String[0]);
for(String ex : k) {
if(ex.length() >0) {dcbm.addElement(ex);}
}
jComboBoxKeys.setModel(dcbm);
}
private void setComboBoxKey(String key) {
// -- makes the "key" the selected item in the combo box
if(key == null || key.trim().length() <=0 || jComboBoxKeys.getItemCount() <=0) {return;}
int fnd = -1;
for(int j=0; j < jComboBoxKeys.getItemCount(); j++) {
if(jComboBoxKeys.getItemAt(j).toString().equalsIgnoreCase(key)) {fnd = j; break;}
}
if(fnd >-1) {jComboBoxKeys.setSelectedIndex(fnd);}
}
//<editor-fold defaultstate="collapsed" desc="getFileName()">
/** Get a file name from the user using an Open File dialog.
* If the file exists and it is not empty, read it and save it to sort the entries.
* @param frame the parent component of the dialog
* @return "null" if the user cancels the opertion; a file name otherwise. */
private String getFileName(java.awt.Component frame) {
frame.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
// Ask the user for a file name using a Open File dialog
boolean mustExist = false;
final String refFileName = Util.getOpenFileName(this, progName,mustExist,
"Select a text file with references:", 7,
pathApp + SLASH + "References.txt", null);
if(refFileName == null || refFileName.trim().length() <=0) {return null;}
int answer;
java.io.File refFile = new java.io.File(refFileName);
if(!refFile.getName().toLowerCase().endsWith(".txt")) {
refFile = new java.io.File(refFile.getAbsolutePath()+".txt");
if(refFile.getName().contains(".")) {
Object[] opt = {"OK", "Cancel"};
answer = javax.swing.JOptionPane.showOptionDialog(frame,
"Note: file name must end with \".txt\""+nl+nl+
"The file name will be:"+nl+"\""+refFile.getName()+".txt\"",
progName, javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[1]);
if(answer != javax.swing.JOptionPane.YES_OPTION) {return null;}
}
}
/* if(refFile.exists()) {
Object[] opt = {"Ok","Cancel"};
answer = javax.swing.JOptionPane.showOptionDialog(frame,
"File \""+refFile.getName()+"\" already exists!"+nl+nl+
"If you add or delete references"+nl+"the file will be overwritten",
progName, javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.QUESTION_MESSAGE,null,opt,opt[0]);
if(answer != javax.swing.JOptionPane.YES_OPTION) {return null;}
} */
if(refFile.exists() && (!refFile.canWrite() || !refFile.setWritable(true))) {
javax.swing.JOptionPane.showMessageDialog(frame,
"Can not overwrite file \""+refFile.getName()+"\"."+nl+
"The file or the directory is perhpas write-protected."+nl+nl+
"You will only be able to display existing references.",
progName, javax.swing.JOptionPane.ERROR_MESSAGE);
canWriteRefs = false;
}
return refFile.getAbsolutePath();
} // getFileName()
// </editor-fold>
/** @param args the command line arguments */
public static void main(String args[]) {
boolean windows = System.getProperty("os.name").startsWith("Windows");
//---- set Look-And-Feel
try{
if(windows) {
javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
System.out.println("--- setLookAndFeel(System);");
} else {
javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getCrossPlatformLookAndFeelClassName());
System.out.println("--- setLookAndFeel(CrossPlatform);");
}
}
catch (Exception ex) {System.out.println("Error: "+ex.getMessage());}
//---- for JOptionPanes set the default button to the one with the focus
// so that pressing "enter" behaves as expected:
javax.swing.UIManager.put("Button.defaultButtonFollowsFocus", Boolean.TRUE);
// and make the arrow keys work:
Util.configureOptionPane();
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
AddShowRefs sr = new AddShowRefs();
// sr.setVisible(true);
sr.start();
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButtonAdd;
private javax.swing.JButton jButtonEdit;
private javax.swing.JButton jButtonQuit;
private javax.swing.JButton jButtonShow;
private javax.swing.JComboBox<String> jComboBoxKeys;
private javax.swing.JLabel jLabel0;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabelFileName;
private javax.swing.JLabel jLabelUnicode;
private javax.swing.JPanel jPanel1;
// End of variables declaration//GEN-END:variables
}
| 23,542 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
EditAddRefs.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/AddShowReferences/src/addShowRefs/EditAddRefs.java | package addShowRefs;
import lib.database.References;
/** Save references to a reference file.
*
* Copyright (C) 2015-2020 I.Puigdomenech.
*
* 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
* 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/
* @author Ignasi Puigdomenech */
public class EditAddRefs extends javax.swing.JFrame {
private References r = null;
private boolean finished;
private String theKey;
private java.awt.Dimension windowSize = new java.awt.Dimension(400,280);
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
/** Creates new form EditAddRefs
* @param r0 */
public EditAddRefs(References r0) {
initComponents();
this.r = r0;
finished = false;
jTextArea.setWrapStyleWord(true);
//--- Ctrl-S save
javax.swing.KeyStroke ctrlSKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(ctrlSKeyStroke,"CTRL_S");
javax.swing.Action ctrlSAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jButtonSave.doClick();
}};
getRootPane().getActionMap().put("CTRL_S", ctrlSAction);
//---- Position the window on the screen
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
java.awt.Point frameLocation = new java.awt.Point(-1000,-1000);
frameLocation.x = Math.max(0, (screenSize.width - this.getWidth() ) / 2);
frameLocation.y = Math.max(0, (screenSize.height - this.getHeight() ) / 2);
this.setLocation(frameLocation);
this.setTitle("Save a reference");
//---- Icon
String iconName = "images/Refs.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
if (imgURL != null) {this.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());}
else {System.out.println("Error: Could not load image = \""+iconName+"\"");}
theKey = "";
}
public void start() {
//---- Title
this.setTitle("Show references");
jTextFieldKey.setText("");
String t = r.referencesFileName();
if(t == null) {
javax.swing.JOptionPane.showMessageDialog(
this, "No reference file!?", "Add References",
javax.swing.JOptionPane.ERROR_MESSAGE);
jButtonQuit.doClick();
return;
} else {jLabelFileName.setText(t);}
windowSize = this.getSize();
}
public void start(String key, String ref) {
//---- Title
this.setTitle("Edit reference");
if(key == null || key.trim().length() <=0) {
javax.swing.JOptionPane.showMessageDialog(
this, "No key!?", "Edit Reference",
javax.swing.JOptionPane.ERROR_MESSAGE);
jButtonQuit.doClick();
return;
}
if(ref == null || ref.trim().length() <=0) {ref="";}
jTextFieldKey.setText(key);
jTextFieldKey.setEditable(false);
jTextFieldKey.setBackground(java.awt.Color.LIGHT_GRAY);
jTextArea.setText(ref);
jTextArea.setCaretPosition(0);
String t = r.referencesFileName();
if(t == null) {
javax.swing.JOptionPane.showMessageDialog(
this, "No reference file!?", "Edit Reference",
javax.swing.JOptionPane.ERROR_MESSAGE);
jButtonQuit.doClick();
return;
} else {jLabelFileName.setText(t);}
windowSize = this.getSize();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
jPanel1 = new javax.swing.JPanel();
jLabel0 = new javax.swing.JLabel();
jLabelFileName = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jTextFieldKey = new javax.swing.JTextField();
jPanel3 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jScrollPane = new javax.swing.JScrollPane();
jTextArea = new javax.swing.JTextArea();
jPanel4 = new javax.swing.JPanel();
jButtonSave = new javax.swing.JButton();
jButtonQuit = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
getContentPane().setLayout(new java.awt.GridBagLayout());
jPanel1.setLayout(new java.awt.BorderLayout());
jLabel0.setText("Reference file:");
jPanel1.add(jLabel0, java.awt.BorderLayout.NORTH);
jLabelFileName.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabelFileName.setText("jLabel4");
jPanel1.add(jLabelFileName, java.awt.BorderLayout.SOUTH);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.ipady = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(2, 5, 12, 0);
getContentPane().add(jPanel1, gridBagConstraints);
jPanel2.setLayout(new java.awt.BorderLayout());
jLabel1.setLabelFor(jTextFieldKey);
jLabel1.setText("Reference Key:");
jPanel2.add(jLabel1, java.awt.BorderLayout.NORTH);
jPanel2.add(jTextFieldKey, java.awt.BorderLayout.SOUTH);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 13, 5);
getContentPane().add(jPanel2, gridBagConstraints);
jPanel3.setLayout(new java.awt.GridBagLayout());
jLabel2.setLabelFor(jTextArea);
jLabel2.setText("Reference contents:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
jPanel3.add(jLabel2, gridBagConstraints);
jScrollPane.setFont(new java.awt.Font("Monospaced", 0, 13)); // NOI18N
jTextArea.setColumns(20);
jTextArea.setLineWrap(true);
jTextArea.setRows(5);
jScrollPane.setViewportView(jTextArea);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
jPanel3.add(jScrollPane, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 10, 5);
getContentPane().add(jPanel3, gridBagConstraints);
jPanel4.setLayout(new java.awt.BorderLayout());
jButtonSave.setMnemonic('s');
jButtonSave.setText(" Save ");
jButtonSave.setAlignmentX(0.5F);
jButtonSave.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonSave.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonSaveActionPerformed(evt);
}
});
jPanel4.add(jButtonSave, java.awt.BorderLayout.WEST);
jButtonQuit.setMnemonic('q');
jButtonQuit.setText(" Quit ");
jButtonQuit.setAlignmentX(0.5F);
jButtonQuit.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonQuit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonQuitActionPerformed(evt);
}
});
jPanel4.add(jButtonQuit, java.awt.BorderLayout.EAST);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.PAGE_END;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 5, 5);
getContentPane().add(jPanel4, gridBagConstraints);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButtonQuitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonQuitActionPerformed
quitFrame();
}//GEN-LAST:event_jButtonQuitActionPerformed
private void jButtonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSaveActionPerformed
if(jTextFieldKey.getText() == null || jTextFieldKey.getText().trim().length()<=0) {
javax.swing.JOptionPane.showMessageDialog(this,"Error:"+nl+"Reference Key may not be empty!",
"Save References",javax.swing.JOptionPane.ERROR_MESSAGE);
return;
}
String key = jTextFieldKey.getText().trim();
String newRef = jTextArea.getText();
if(!r.readRefsFile(jLabelFileName.getText(), false)) {
System.out.println("Properties not loaded from file \""+jLabelFileName.getText()+"\""+nl+"quitting ...");
return;
}
if(newRef == null || newRef.trim().length()<=0) {
String oldRef = r.isRefThere(key);
if(oldRef != null) {
String msg = "Delete existing reference?"+nl+nl+
key+" = "+oldRef+nl+" ";
Object[] opt = {"Yes", "Cancel"};
int m = javax.swing.JOptionPane.showOptionDialog(this,
msg,
"Save References", javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[1]);
if(m != javax.swing.JOptionPane.YES_OPTION) {return;}
} else {
javax.swing.JOptionPane.showMessageDialog(this, "No reference text to save", "Save References", javax.swing.JOptionPane.QUESTION_MESSAGE);
return;
}
newRef = null;
} else { // newRef not empty
newRef = newRef.trim();
String found = r.isRefThere(key);
if(found != null && found.trim().length() >=0) {
String msg = "Replace reference?"+nl+nl;
Object[] opt = {"Yes", "Cancel"};
int m = javax.swing.JOptionPane.showOptionDialog(this, msg,
"Save References", javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[1]);
if(m != javax.swing.JOptionPane.YES_OPTION) {return;}
}
} // newRef empty?
r.setRef(key, newRef);
r.saveRefsFile(this, false);
theKey = key;
jTextFieldKey.setText("");
jTextArea.setText("");
jButtonQuit.doClick();
}//GEN-LAST:event_jButtonSaveActionPerformed
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
quitFrame();
}//GEN-LAST:event_formWindowClosing
private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
if(windowSize != null) {
int w = windowSize.width;
int h = windowSize.height;
if(this.getHeight()<h){this.setSize(this.getWidth(), h);}
if(this.getWidth()<w){this.setSize(w,this.getHeight());}
}
}//GEN-LAST:event_formComponentResized
private void quitFrame() {
finished = true;
this.notify_All();
this.dispose();
}
private synchronized void notify_All() {notifyAll();}
/** this method will wait for this dialog frame to be closed
* @return the key to the reference saved if the user presses the "OK" button,
* or an empty string if the edit is cancelled.
*/
public synchronized String waitFor() {
while(!finished) {
try {wait();} catch (InterruptedException ex) {}
} // while
return theKey;
} // waitFor()
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButtonQuit;
private javax.swing.JButton jButtonSave;
private javax.swing.JLabel jLabel0;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabelFileName;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JScrollPane jScrollPane;
private javax.swing.JTextArea jTextArea;
private javax.swing.JTextField jTextFieldKey;
// End of variables declaration//GEN-END:variables
}
| 14,928 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
ErrMsgBox.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/AddShowReferences/src/addShowRefs/ErrMsgBox.java | package addShowRefs;
/** Displays a "message box" modal dialog with an "OK" button and a title.
* The message is displayed in a text area (non-editable),
* which can be copied and pasted elsewhere.
*
* Copyright (C) 2014-2017 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class ErrMsgBox {
private static final String nl = System.getProperty("line.separator");
//<editor-fold defaultstate="collapsed" desc="ErrMsgBox(msg, title)">
/** Displays a "message box" modal dialog with an "OK" button and a title.
* The message is displayed in a text area (non-editable),
* which can be copied and pasted elsewhere.
* @param msg will be displayed in a text area, and line breaks may be
* included, for example: <code>new MsgBox("Very\nbad!",""); </code>
* If null or empty nothing is done.
* @param title for the dialog. If null or empty, "Error:" is used
* @version 2015-July-14 */
public ErrMsgBox(String msg, String title) {
if(msg == null || msg.trim().length() <=0) {
System.out.println("--- MsgBox: null or empty \"message\".");
return;
}
//--- Title
if(title == null || title.length() <=0) {title = " Error:";}
java.awt.Frame frame = new java.awt.Frame(title);
//--- Icon
String iconName = "images/ErrMsgBx.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
if(imgURL != null) {frame.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());}
else {System.out.println("--- Error in MsgBox constructor: Could not load image = \""+iconName+"\"");}
frame.pack();
//--- centre Window frame on Screen
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int left; int top;
left = Math.max(55, (screenSize.width - frame.getWidth() ) / 2);
top = Math.max(10, (screenSize.height - frame.getHeight()) / 2);
frame.setLocation(Math.min(screenSize.width-100, left), Math.min(screenSize.height-100, top));
//---
final String msgText = wrapString(msg.trim(),80);
//System.out.println("--- MsgBox:"+nl+msgText+nl+"---");
frame.setVisible(true);
//javax.swing.JOptionPane.showMessageDialog(frame, msg, title, javax.swing.JOptionPane.ERROR_MESSAGE);
MsgBoxDialog msgBox = new MsgBoxDialog(frame, msgText, title, true);
msgBox.setVisible(true); // becase the dialog is modal, statements below will wait
msgBox.dispose();
frame.setVisible(false);
frame.dispose();
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="private class MsgBoxDialog">
private static class MsgBoxDialog extends java.awt.Dialog {
private java.awt.Button ok;
private java.awt.Panel p;
private final java.awt.TextArea text;
/** Creates new form NewDialog */
public MsgBoxDialog(java.awt.Frame parent, String msg, String title, boolean modal) {
super(parent, (" "+title), modal);
addWindowListener(new java.awt.event.WindowAdapter() {
@Override public void windowClosing(java.awt.event.WindowEvent evt) {
MsgBoxDialog.this.setVisible(false);
}
});
setLayout(new java.awt.BorderLayout());
p = new java.awt.Panel();
p.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER));
ok = new java.awt.Button();
// find out the size of the message (width and height)
final int wMax = 85; final int hMax=20;
final int wMin = 5; final int hMin = 1;
int w = wMin;
int h=hMin; int i=0; int j=wMin;
final String eol = "\n"; char c;
final String nl = System.getProperty("line.separator");
while (true) {
c = msg.charAt(i);
String s = String.valueOf(c);
if(s.equals(eol) || s.equals(nl)) {
h++; j=wMin;
} else {
j++; w = Math.max(j,w);
}
i++;
if(i >= msg.length()-1) {break;}
}
// create a text area
int scroll = java.awt.TextArea.SCROLLBARS_NONE;
if(w > wMax && h <= hMax) {scroll = scroll & java.awt.TextArea.SCROLLBARS_HORIZONTAL_ONLY;}
if(h > hMax && w <= wMax) {scroll = scroll & java.awt.TextArea.SCROLLBARS_VERTICAL_ONLY;}
if(w > wMax && h > hMax) {scroll = java.awt.TextArea.SCROLLBARS_BOTH;}
w = Math.min(Math.max(w,10),wMax);
h = Math.min(h,hMax);
text = new java.awt.TextArea(msg, h, w, scroll);
text.setEditable(false);
//text.setBackground(java.awt.Color.white);
text.addKeyListener(new java.awt.event.KeyAdapter() {
@Override public void keyPressed(java.awt.event.KeyEvent evt) {
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER
|| evt.getKeyCode() == java.awt.event.KeyEvent.VK_ESCAPE) {closeDialog();}
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_TAB) {ok.requestFocusInWindow();}
}
});
text.setBackground(java.awt.Color.WHITE);
text.setFont(new java.awt.Font("monospaced", java.awt.Font.PLAIN, 12));
add(text, java.awt.BorderLayout.CENTER);
ok.setLabel("OK");
ok.addActionListener(new java.awt.event.ActionListener() {
@Override public void actionPerformed(java.awt.event.ActionEvent evt) {
closeDialog();
}
});
ok.addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER
|| evt.getKeyCode() == java.awt.event.KeyEvent.VK_ESCAPE) {closeDialog();}
}
});
p.add(ok);
add(p, java.awt.BorderLayout.SOUTH);
pack();
ok.requestFocusInWindow();
//--- centre Window frame on Screen
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int left; int top;
left = Math.max(55, (screenSize.width - getWidth() ) / 2);
top = Math.max(10, (screenSize.height - getHeight()) / 2);
setLocation(Math.min(screenSize.width-100, left), Math.min(screenSize.height-100, top));
}
private void closeDialog() {this.setVisible(false);}
} // private static class MsgBoxDialog
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="private wrapString">
/** Returns an input string, with lines that are longer than <code>maxLength</code>
* word-wrapped and indented. *
* @param s input string
* @param maxLength if an input line is longer than this length,
* the line will be word-wrapped at the first white space after <code>maxLength</code>
* and indented with 4 spaces
* @return string with long-lines word-wrapped
*/
private static String wrapString(String s, int maxLength) {
String deliminator = "\n";
StringBuilder result = new StringBuilder();
StringBuffer wrapLine;
int lastdelimPos;
for (String line : s.split(deliminator, -1)) {
if(line.length()/(maxLength+1) < 1) {
result.append(line).append(deliminator);
}
else { //line too long, try to split it
wrapLine = new StringBuffer();
lastdelimPos = 0;
for (String token : line.trim().split("\\s+", -1)) {
if (wrapLine.length() - lastdelimPos + token.length() > maxLength) {
if(wrapLine.length()>0) {wrapLine.append(deliminator);}
wrapLine.append(" ").append(token);
lastdelimPos = wrapLine.length() + 1;
} else {
if(wrapLine.length() <=0) {wrapLine.append(token);}
else {wrapLine.append(" ").append(token);}
}
}
result.append(wrapLine).append(deliminator);
}
}
return result.toString();
}
// </editor-fold>
}
| 8,904 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
Main.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/AddShowReferences/src/addShowRefs/Main.java | package addShowRefs;
/** Checks that all the jar-libraries needed exist.
* <br>
* Copyright (C) 2014-2016 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class Main {
private static final String progName = "Program \"AddShowReferences\""; //Leta? Lagra? Samla?
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
private static boolean started = false;
private static final String SLASH = java.io.File.separator;
/** Check that all the jar-libraries needed do exist.
* @param args the command line arguments */
public static void main(String[] args) {
// ---- are all jar files needed there?
if(!doJarFilesExist()) {return;}
// ---- ok!
AddShowRefs.main(args);
} //main
//<editor-fold defaultstate="collapsed" desc="doJarFilesExist">
/** Look in the running jar file's classPath Manifest for any other "library"
* jar-files listed under "Class-path".
* If any of these jar files does not exist display an error message
* (and an error Frame) and continue.
* @return true if all needed jar files exist; false otherwise.
* @version 2016-Aug-03 */
private static boolean doJarFilesExist() {
java.io.File libJarFile, libPathJarFile;
java.util.jar.JarFile runningJar = getRunningJarFile();
// runningJar.getName() = C:\Eq-Calc_Java\dist\Prog.jar
if(runningJar != null) { // if running within Netbeans there will be no jar-file
java.util.jar.Manifest manifest;
try {manifest = runningJar.getManifest();}
catch (java.io.IOException ex) {
manifest = null;
String msg = "Warning: no manifest found in the application's jar file:"+nl+
"\""+runningJar.getName()+"\"";
ErrMsgBox emb = new ErrMsgBox(msg, progName);
//this will return true;
}
if(manifest != null) {
String classPath = manifest.getMainAttributes().getValue("Class-Path");
if(classPath != null && classPath.length() > 0) {
// this will be a list of space-separated names
String[] jars = classPath.split("\\s+"); //regular expression to match one or more spaces
if(jars.length >0) {
java.io.File[] rootNames = java.io.File.listRoots();
boolean isPathAbsolute;
String pathJar;
String p = getPathApp(); // get the application's path
for(String jar : jars) { // loop through all jars needed
libJarFile = new java.io.File(jar);
if(libJarFile.exists()) {continue;}
isPathAbsolute = false;
for(java.io.File f : rootNames) {
if(jar.toLowerCase().startsWith(f.getAbsolutePath().toLowerCase())) {
isPathAbsolute = true;
break;}
}
if(!isPathAbsolute) { // add the application's path
if(!p.endsWith(SLASH) && !jar.startsWith(SLASH)) {p = p+SLASH;}
pathJar = p + jar;
} else {pathJar = jar;}
libPathJarFile = new java.io.File(pathJar);
if(libPathJarFile.exists()) {continue;}
libPathJarFile = new java.io.File(libPathJarFile.getAbsolutePath());
ErrMsgBox emb = new ErrMsgBox(progName+" - Error:"+nl+
" File: \""+jar+"\" NOT found."+nl+
" And file: \""+libPathJarFile.getName()+"\" is NOT in folder:"+nl+
" \""+libPathJarFile.getParent()+"\""+nl+
" either!"+nl+nl+
" This file is needed by the program."+nl, progName);
return false;
}
}
}//if classPath != null
} //if Manifest != null
} //if runningJar != null
return true;
} //doJarFilesExist()
//<editor-fold defaultstate="collapsed" desc="getRunningJarFile()">
/** Find out the jar file that contains this class
* @return a File object of the jar file containing the enclosing class "Main",
* or null if the main class is not inside a jar file.
* @version 2014-Jan-17 */
public static java.util.jar.JarFile getRunningJarFile() {
//from http://www.rgagnon.com/javadetails/
//and the JarClassLoader class
C c = new C();
String className = c.getClass().getName().replace('.', '/');
// class = "progPackage.Main"; className = "progPackage/Main"
java.net.URL url = c.getClass().getResource("/" + className + ".class");
// url = "jar:file:/C:/Eq-Calc_Java/dist/Prog.jar!/progPackage/Main.class"
if(url.toString().startsWith("jar:")) {
java.net.JarURLConnection jUrlC;
try{
jUrlC = (java.net.JarURLConnection)url.openConnection();
return jUrlC.getJarFile();
} catch(java.io.IOException ex) {
ErrMsgBox emb = new ErrMsgBox("Error "+ex.toString(), progName);
return null;
}
} else {
// it might not be a jar file if running within NetBeans
return null;
}
} //getRunningJarFile()
//</editor-fold>
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="getPathApp">
/** Get the path where an application is located.
* @return the directory where the application is located,
* or "user.dir" if an error occurs
* @version 2014-Jan-17 */
private static class C {private static void C(){}}
public static String getPathApp() {
C c = new C();
String path;
java.net.URI dir;
try{
dir = c.getClass().
getProtectionDomain().
getCodeSource().
getLocation().
toURI();
if(dir != null) {
String d = dir.toString();
if(d.startsWith("jar:") && d.endsWith("!/")) {
d = d.substring(4, d.length()-2);
dir = new java.net.URI(d);
}
path = (new java.io.File(dir.getPath())).getParent();
} else {path = System.getProperty("user.dir");}
}
catch (java.net.URISyntaxException e) {
if(!started) {
ErrMsgBox emb = new ErrMsgBox("Error: "+e.toString()+nl+
" trying to get the application's directory.", progName);
}
path = System.getProperty("user.dir");
} // catch
started = true;
return path;
} //getPathApp()
//</editor-fold>
}
| 7,312 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
ExitDialog.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/DataBase/src/database/ExitDialog.java | package database;
import lib.common.MsgExceptn;
import lib.common.Util;
import lib.database.Complex;
import lib.database.LibDB;
import lib.database.ProgramDataDB;
import lib.huvud.ProgramConf;
/** Exit dialog.
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class ExitDialog extends javax.swing.JDialog {
private ProgramConf pc;
private final ProgramDataDB pd;
private final FrameDBmain dbF;
private final DBSearch hs;
private final java.awt.Dimension windowSize = new java.awt.Dimension(185,185);
/** New-line character(s) to substitute "\n". */
private static final String nl = System.getProperty("line.separator");
private static final java.util.Locale engl = java.util.Locale.ENGLISH;
//<editor-fold defaultstate="collapsed" desc="Constructor">
/** Creates new form ExitDialog
* @param parent
* @param modal
* @param pc0
* @param pd0
* @param hs0 */
public ExitDialog(java.awt.Frame parent, boolean modal,
ProgramConf pc0,
ProgramDataDB pd0,
DBSearch hs0) {
super(parent, modal);
initComponents();
pc = pc0;
pd = pd0;
dbF = (FrameDBmain)parent;
hs = hs0;
// ----
dbF.setCursorDef();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
//--- Close window on ESC key
javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE");
javax.swing.Action escAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
closeWindow();
}};
getRootPane().getActionMap().put("ESCAPE", escAction);
//--- Alt-Q quit
javax.swing.KeyStroke altQKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altQKeyStroke,"ALT_Q");
getRootPane().getActionMap().put("ALT_Q", escAction);
//--- Alt-X eXit
javax.swing.KeyStroke altXKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altXKeyStroke,"ALT_X");
getRootPane().getActionMap().put("ALT_X", escAction);
//--- F1 for help
javax.swing.KeyStroke f1KeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_F1,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(f1KeyStroke,"F1");
javax.swing.Action f1Action = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
ExitDialog.this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
Thread hlp = new Thread() {@Override public void run(){
String[] a = {"DB_0_Main_htm"};
lib.huvud.RunProgr.runProgramInProcess(null,ProgramConf.HELP_JAR,a,false,pc.dbg,pc.pathAPP);
try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec
catch (InterruptedException e) {}
ExitDialog.this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
}};//new Thread
hlp.start();
}};
getRootPane().getActionMap().put("F1", f1Action);
//--- Alt-H help
javax.swing.KeyStroke altHKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_H, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altHKeyStroke,"ALT_H");
getRootPane().getActionMap().put("ALT_H", f1Action);
//---- forward/backwards arrow keys
java.util.Set<java.awt.AWTKeyStroke> keys = getFocusTraversalKeys(java.awt.KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS);
java.util.Set<java.awt.AWTKeyStroke> newKeys = new java.util.HashSet<java.awt.AWTKeyStroke>(keys);
newKeys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_RIGHT, 0));
newKeys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_DOWN, 0));
setFocusTraversalKeys(java.awt.KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,newKeys);
keys = getFocusTraversalKeys(java.awt.KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS);
newKeys = new java.util.HashSet<java.awt.AWTKeyStroke>(keys);
newKeys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_LEFT, 0));
newKeys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_UP, 0));
setFocusTraversalKeys(java.awt.KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,newKeys);
//---- Title, etc
getContentPane().setBackground(java.awt.Color.BLUE);
this.setTitle(pc.progName+" - Exit and...");
//---- Centre window on parent/screen
int left,top;
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
if(parent != null) {
left = Math.max(0,(parent.getX() + 20));
top = Math.max(0,(parent.getY()+20));
} else {
left = Math.max(0,(screenSize.width-this.getWidth())/2);
top = Math.max(0,(screenSize.height-this.getHeight())/2);
}
this.setLocation(Math.min(screenSize.width-this.getWidth()-20,left),
Math.min(screenSize.height-this.getHeight()-20, top));
//---- is "Diagram" there?
String diagramProg = LibDB.getDiagramProgr(pd.diagramProgr);
if(diagramProg == null) {
jButtonDiagram.setEnabled(false);
jLabelDiagram.setForeground(java.awt.Color.GRAY);
jLabelDiagram.setText("<html>save file and<br>make a Diagram</html>");
jLabelSave.setText("<html><u>S</u>ave<br>to disk file</html>");
}
jButtonDiagram.setMnemonic(java.awt.event.KeyEvent.VK_D);
dbF.exitCancel = true;
dbF.send2Diagram = false;
this.setVisible(true);
//windowSize = ExitDialog.this.getSize();
} //constructor
//</editor-fold>
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jButtonDiagram = new javax.swing.JButton();
jLabelDiagram = new javax.swing.JLabel();
jButtonSave = new javax.swing.JButton();
jLabelSave = new javax.swing.JLabel();
jButtonCancel = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jButtonDiagram.setIcon(new javax.swing.ImageIcon(getClass().getResource("/database/images/Diagram_button.gif"))); // NOI18N
jButtonDiagram.setMnemonic('d');
jButtonDiagram.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonDiagram.setMargin(new java.awt.Insets(2, 2, 2, 2));
jButtonDiagram.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonDiagramActionPerformed(evt);
}
});
jLabelDiagram.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabelDiagram.setForeground(java.awt.Color.white);
jLabelDiagram.setLabelFor(jButtonDiagram);
jLabelDiagram.setText("<html>save file and<br>make a <u>D</u>iagram</html>");
jButtonSave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/database/images/Save_32x32.gif"))); // NOI18N
jButtonSave.setMnemonic('s');
jButtonSave.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonSave.setMargin(new java.awt.Insets(2, 2, 2, 2));
jButtonSave.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonSaveActionPerformed(evt);
}
});
jLabelSave.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabelSave.setForeground(java.awt.Color.white);
jLabelSave.setLabelFor(jButtonSave);
jLabelSave.setText("<html>only <u>S</u>ave<br>file</html>");
jButtonCancel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButtonCancel.setMnemonic('c');
jButtonCancel.setText("Cancel");
jButtonCancel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonCancel.setMargin(new java.awt.Insets(2, 5, 2, 5));
jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonCancelActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButtonCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jButtonSave, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButtonDiagram, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelDiagram, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelSave, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(16, 16, 16)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButtonDiagram)
.addComponent(jLabelDiagram, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButtonSave)
.addComponent(jLabelSave, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jButtonCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
//<editor-fold defaultstate="collapsed" desc="Events">
private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelActionPerformed
closeWindow();
}//GEN-LAST:event_jButtonCancelActionPerformed
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
closeWindow();
}//GEN-LAST:event_formWindowClosing
private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
if(windowSize != null) {
int w = windowSize.width;
int h = windowSize.height;
if(this.getHeight()<h){this.setSize(this.getWidth(), h);}
if(this.getWidth()<w){this.setSize(w,this.getHeight());}
}
}//GEN-LAST:event_formComponentResized
private void jButtonDiagramActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDiagramActionPerformed
if(saveDataFile(hs)) {
dbF.send2Diagram = true;
dbF.exitCancel = false;
} else {dbF.exitCancel = true;}
closeWindow();
}//GEN-LAST:event_jButtonDiagramActionPerformed
private void jButtonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSaveActionPerformed
dbF.exitCancel = !saveDataFile(hs);
closeWindow();
}//GEN-LAST:event_jButtonSaveActionPerformed
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Methods">
private void closeWindow() {
this.dispose();
dbF.bringToFront();
} // closeWindow()
private boolean saveDataFile(DBSearch srch) {
if(srch == null) {
MsgExceptn.exception("Error in \"saveDataFile\": null argument");
return false;
}
// Is there enthalpy data?
if(!DBSearch.checkTemperature(srch, this, false)) {return false;}
String defaultName;
if(dbF.outputDataFile != null) {defaultName = dbF.outputDataFile;} else {defaultName = "";}
String fn = Util.getSaveFileName(this, pc.progName,
"Save file: Enter data-file name", 5, defaultName, pc.pathDef.toString());
if(fn == null) {return false;}
pc.setPathDef(fn);
// Make a temporary file to write the information. If no error occurs,
// then the data file is overwritten with the temporary file
String tmpFileName;
tmpFileName = fn.substring(0,fn.length()-4).concat(".tmp");
java.io.File tmpFile = new java.io.File(tmpFileName);
java.io.FileOutputStream fos;
java.io.Writer w;
try{
fos = new java.io.FileOutputStream(tmpFile);
w = new java.io.BufferedWriter(new java.io.OutputStreamWriter(fos,"UTF8"));
}
catch (java.io.IOException ex) {
String msg = "Error in \"saveDataFile\","+nl+
" \""+ex.toString()+"\","+nl+
" while preparing file:"+nl+" \""+tmpFileName+"\"";
MsgExceptn.exception(msg);
javax.swing.JOptionPane.showMessageDialog(this, msg, pc.progName,javax.swing.JOptionPane.ERROR_MESSAGE);
return false;
}
// make some simple checks
if(srch.na<1 || srch.na>1000) {
MsgExceptn.exception("Error: Number of components is: "+srch.na+nl+
"Must be >0 and <1000.");
}
if(srch.nx < 0 || srch.nx > 1000000) {
MsgExceptn.exception("Error: Number of soluble complexes is: "+srch.nx+nl+
"Must be >=0 and < 1 000 000.");}
int nrSol = srch.nf;
if(srch.nf < 0 || srch.nf > 100000) {
MsgExceptn.exception("Error: Number of solid reaction products is: "+srch.nf+nl+
"Must be >=0 and < 100 000.");}
if(srch.solidC < 0 || srch.solidC > srch.na) {
MsgExceptn.exception("Error: Number of solid components is: "+srch.solidC+nl+
"Must be >=0 and <= "+srch.na+" (the nbr of components).");}
if(pc.dbg) {System.out.println("---- Saving file \""+fn+"\".");}
String m = ", /DATABASE (HYDRA)";
if(!Double.isNaN(srch.temperature_C)) {m = m + ", t="+Util.formatDbl3(srch.temperature_C);}
if(!Double.isNaN(srch.pressure_bar)) {m = m + ", p="+Util.formatDbl3(srch.pressure_bar);}
//if requested: add water
if(pd.includeH2O) {
dbF.modelSelectedComps.add((srch.na - srch.solidC), "H2O");
srch.na++;
}
try{
w.write(" "+String.valueOf(srch.na)+", "+
String.valueOf(srch.nx)+", "+String.valueOf(nrSol)+", "+
String.valueOf(srch.solidC) + m.trim()+nl);
for(int i=0; i < srch.na; i++) {
w.write(String.format("%s",dbF.modelSelectedComps.get(i))+nl);
} //for i
w.flush();
int j, jc, nTot;
Complex cmplx;
StringBuilder logB = new StringBuilder();
for(int ix=0; ix < srch.nx+srch.nf; ix++) {
cmplx = srch.dat.get(ix);
if(cmplx.name.length()<=19) {
w.write(String.format(engl, "%-19s, ",cmplx.name));
} else {w.write(String.format(engl, "%s, ",cmplx.name));}
if(logB.length()>0) {logB.delete(0, logB.length());}
double lgK = cmplx.logKatTandP(srch.temperature_C, srch.pressure_bar);
if(Double.isNaN(lgK)) {
String msg = "Error in \"saveDataFile\","+nl+
" species \""+cmplx.name+"\" has logK = Not-a-Number."+nl+
" while writing data file:"+nl+
" \""+fn+"\"";
MsgExceptn.exception(msg);
javax.swing.JOptionPane.showMessageDialog(this, msg, pc.progName,javax.swing.JOptionPane.ERROR_MESSAGE);
return false;
}
logB.append(Util.formatDbl3(lgK));
//make logB occupy at least 9 chars: padding with space
j = 9 - logB.length();
if(j>0) {for(int k=0;k<j;k++) {logB.append(' ');}}
else {logB.append(' ');} //add at least one space
w.write(logB.toString());
boolean fnd;
for(jc = 0; jc < srch.na; jc++) {
fnd = false;
nTot = Math.min(cmplx.reactionComp.size(), cmplx.reactionCoef.size());
for(int jdat=0; jdat < nTot; jdat++) {
if(cmplx.reactionComp.get(jdat).equals(dbF.modelSelectedComps.get(jc))) {
w.write(Util.formatDbl4(cmplx.reactionCoef.get(jdat)));
if(jc < srch.na-1) {w.write(" ");}
fnd = true; break;
}
} //for jdat
if(!fnd) {
w.write(" 0");
if(jc < srch.na-1) {w.write(" ");}
}
}//for jc
if(cmplx.comment != null && cmplx.comment.length() >0) {
w.write(" /"+cmplx.comment);
}
w.write(nl);
}//for ix
w.flush(); w.close(); fos.close();
}
catch (Exception ex) {
String msg = "Error in \"saveDataFile\","+nl+
" \""+ex.getMessage()+"\","+nl+
" while writing to file:"+nl+
" \""+tmpFileName+"\"";
MsgExceptn.exception(msg);
javax.swing.JOptionPane.showMessageDialog(this, msg, pc.progName,javax.swing.JOptionPane.ERROR_MESSAGE);
return false;
}
//the temporary file has been created without a problem
// delete the data file and rename the temporary file
java.io.File dataFile = new java.io.File(fn);
dataFile.delete();
if(!tmpFile.renameTo(dataFile)) {
MsgExceptn.exception("Error in \"saveDataFile\":"+nl+
" can not rename file \""+tmpFile.getAbsolutePath()+"\""+nl+
" to \""+dataFile.getAbsolutePath()+"\"");
return false;
}
dbF.outputDataFile = dataFile.getAbsolutePath();
return true;
} //saveDataFile
//</editor-fold>
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButtonCancel;
private javax.swing.JButton jButtonDiagram;
private javax.swing.JButton jButtonSave;
private javax.swing.JLabel jLabelDiagram;
private javax.swing.JLabel jLabelSave;
// End of variables declaration//GEN-END:variables
}
| 21,205 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
AskRedox.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/DataBase/src/database/AskRedox.java | package database;
import lib.database.ProgramDataDB;
import lib.huvud.ProgramConf;
/** Ask the user about what redox equilibria to be included
* in the database searchs.
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class AskRedox extends javax.swing.JDialog {
boolean askSomething = false;
private ProgramConf pc;
private ProgramDataDB pd;
private FrameDBmain dbF;
private boolean ok = false;
private boolean askingBeforeSearch;
private java.awt.Dimension windowSize = new java.awt.Dimension(227,122);
/** Creates new form AskRedox
* @param parent
* @param modal
* @param pc0 program configuration
* @param pd0 program data
* @param aBS true if "askingBeforeSearch";
* false if asking the user for program options
* @param model the selected components, or null */
public AskRedox(java.awt.Frame parent, boolean modal,
ProgramConf pc0,
ProgramDataDB pd0,
boolean aBS,
javax.swing.DefaultListModel model) {
super(parent, modal);
initComponents();
pc = pc0;
pd = pd0;
dbF = (FrameDBmain)parent;
askingBeforeSearch = aBS;
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
// ---- Close window on ESC key
javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE");
javax.swing.Action escAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
closeWindow();
}};
getRootPane().getActionMap().put("ESCAPE", escAction);
//--- Alt-Q quit
javax.swing.KeyStroke altQKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altQKeyStroke,"ALT_Q");
getRootPane().getActionMap().put("ALT_Q", escAction);
//--- Alt-X eXit
javax.swing.KeyStroke altXKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altXKeyStroke,"ALT_X");
javax.swing.Action altXAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jButtonOK.doClick();
}};
getRootPane().getActionMap().put("ALT_X", altXAction);
// ---- F1 for help
javax.swing.KeyStroke f1KeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_F1,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(f1KeyStroke,"F1");
javax.swing.Action f1Action = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jButtonHelp.doClick();
}};
getRootPane().getActionMap().put("F1", f1Action);
//---- forward/backwards arrow keys
java.util.Set<java.awt.AWTKeyStroke> keys = getFocusTraversalKeys(java.awt.KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS);
java.util.Set<java.awt.AWTKeyStroke> newKeys = new java.util.HashSet<java.awt.AWTKeyStroke>(keys);
newKeys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_RIGHT, 0));
newKeys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_DOWN, 0));
setFocusTraversalKeys(java.awt.KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,newKeys);
keys = getFocusTraversalKeys(java.awt.KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS);
newKeys = new java.util.HashSet<java.awt.AWTKeyStroke>(keys);
newKeys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_LEFT, 0));
newKeys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_UP, 0));
setFocusTraversalKeys(java.awt.KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,newKeys);
//---- Title, etc
this.setTitle(pc.progName+" - Redox options");
//---- Centre window on parent/screen
int left,top;
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
if(parent != null) {
left = Math.max(0,(parent.getX() + (parent.getWidth()/2) - this.getWidth()/2));
top = Math.max(0,(parent.getY()+(parent.getHeight()/2)-this.getHeight()/2));
} else {
left = Math.max(0,(screenSize.width-this.getWidth())/2);
top = Math.max(0,(screenSize.height-this.getHeight())/2);
}
this.setLocation(Math.min(screenSize.width-this.getWidth()-20,left),
Math.min(screenSize.height-this.getHeight()-20, top));
if(pd.redoxN) {jCheckBoxN.setSelected(true);}
if(pd.redoxP) {jCheckBoxP.setSelected(true);}
if(pd.redoxS) {jCheckBoxS.setSelected(true);}
if(pd.redoxAsk) {
jRadioButtonAsk.setSelected(true);
jCheckBoxN.setEnabled(false);
jCheckBoxP.setEnabled(false);
jCheckBoxS.setEnabled(false);
} else {
jRadioButtonDoNotAsk.setSelected(true);
jCheckBoxN.setEnabled(true);
jCheckBoxP.setEnabled(true);
jCheckBoxS.setEnabled(true);
}
jLabelMessage.setVisible(false);
// if asking before a database search: askSomething =false
askSomething = !askingBeforeSearch;
if(askingBeforeSearch) {
// find out which elements "N", "P", or "S" the user selected
String[] elemComp; String selCompName; String el;
for(int i =0; i< model.size(); i++) {
selCompName = model.get(i).toString();
if(selCompName.equals("SCN-")) {continue;}
for (String[] elemComp1 : pd.elemComp) {
//loop through all components in the database (CO3-2,SO4-2,HS-,etc)
//Note: array elemComp[0] contains: the name-of-the-element (e.g. "C"),
// the formula-of-the-component ("CN-"), and
// the name-of-the-component ("cyanide")
elemComp = elemComp1;
if(!elemComp[1].equals(selCompName)) {continue;}
//Got the component selected by the user
el = elemComp[0]; //get the element corresponding to the component: e.g. "S" for SO4-2
if(el.equals("N")) {askSomething = true; jCheckBoxN.setEnabled(true);}
if(el.equals("S")) {askSomething = true; jCheckBoxS.setEnabled(true);}
if(el.equals("P")) {askSomething = true; jCheckBoxP.setEnabled(true);}
} //for list of all available components
} //for i; all selected components
if(!askSomething) {closeWindow(); return;}
jLabelTop.setText("<html>\"e-\" has been selected:<br>"+
"include redox equilibria among ligands?<br> </html>");
jLabelMessage.setVisible(true);
jRadioButtonAsk.setVisible(false);
jRadioButtonDoNotAsk.setVisible(false);
} //if askingBeforeSearch
} //constructor
public void start() {
this.setVisible(true);
windowSize = AskRedox.this.getSize();
jButtonCancel.requestFocusInWindow();
dbF.setCursorDef();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
jLabelTop = new javax.swing.JLabel();
jButtonHelp = new javax.swing.JButton();
jButtonCancel = new javax.swing.JButton();
jButtonOK = new javax.swing.JButton();
jPanel4 = new javax.swing.JPanel();
jRadioButtonAsk = new javax.swing.JRadioButton();
jRadioButtonDoNotAsk = new javax.swing.JRadioButton();
jPanel3 = new javax.swing.JPanel();
jCheckBoxN = new javax.swing.JCheckBox();
jCheckBoxS = new javax.swing.JCheckBox();
jCheckBoxP = new javax.swing.JCheckBox();
jLabelMessage = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jLabelTop.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabelTop.setText("<html>If \"e-\" is selected:<br>include redox equilibria among ligands?</html>");
jButtonHelp.setMnemonic('h');
jButtonHelp.setText(" Help ");
jButtonHelp.setToolTipText("Alt-H or F1");
jButtonHelp.setAlignmentX(0.5F);
jButtonHelp.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonHelp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonHelpActionPerformed(evt);
}
});
jButtonCancel.setMnemonic('c');
jButtonCancel.setText(" Cancel ");
jButtonCancel.setToolTipText("Alt-C or Esc");
jButtonCancel.setAlignmentX(0.5F);
jButtonCancel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonCancelActionPerformed(evt);
}
});
jButtonOK.setMnemonic('o');
jButtonOK.setText("OK");
jButtonOK.setToolTipText("Alt-O");
jButtonOK.setAlignmentX(0.5F);
jButtonOK.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonOK.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonOKActionPerformed(evt);
}
});
buttonGroup1.add(jRadioButtonAsk);
jRadioButtonAsk.setMnemonic('A');
jRadioButtonAsk.setText("Ask every time \"e-\" is selected");
jRadioButtonAsk.setToolTipText("Alt-A");
jRadioButtonAsk.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
jRadioButtonAsk.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonAskActionPerformed(evt);
}
});
buttonGroup1.add(jRadioButtonDoNotAsk);
jRadioButtonDoNotAsk.setMnemonic('d');
jRadioButtonDoNotAsk.setText("Do not ask. Include the following equilibria:");
jRadioButtonDoNotAsk.setToolTipText("Alt-D");
jRadioButtonDoNotAsk.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
jRadioButtonDoNotAsk.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonDoNotAskActionPerformed(evt);
}
});
jCheckBoxN.setMnemonic('n');
jCheckBoxN.setText("N (NO3-, NO2-, NH3, etc)");
jCheckBoxN.setToolTipText("Alt-N");
jCheckBoxS.setMnemonic('s');
jCheckBoxS.setText("S (SO4-2, SO3-2, HS-, etc)");
jCheckBoxS.setToolTipText("Alt-S");
jCheckBoxP.setMnemonic('p');
jCheckBoxP.setText("P (PO4-3, HPO3-2, H2PO2-, etc)");
jCheckBoxP.setToolTipText("Alt-P");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jCheckBoxN)
.addComponent(jCheckBoxS)
.addComponent(jCheckBoxP))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jCheckBoxN)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jCheckBoxP)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jCheckBoxS))
);
jLabelMessage.setText("<html>Note: some of the selected components might not participate in redox reactions</html>");
jLabelMessage.setVerticalAlignment(javax.swing.SwingConstants.TOP);
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jRadioButtonAsk)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jRadioButtonDoNotAsk))
.addContainerGap(10, Short.MAX_VALUE))
.addComponent(jLabelMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(jRadioButtonAsk)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jRadioButtonDoNotAsk)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelTop, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButtonCancel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButtonHelp)
.addComponent(jButtonOK, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabelTop, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(59, 59, 59)
.addComponent(jButtonHelp)
.addGap(18, 18, 18)
.addComponent(jButtonCancel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButtonOK)
.addContainerGap(44, Short.MAX_VALUE))
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
if(windowSize != null) {
int w = windowSize.width;
int h = windowSize.height;
if(this.getHeight()<h){this.setSize(this.getWidth(), h);}
if(this.getWidth()<w){this.setSize(w,this.getHeight());}
}
}//GEN-LAST:event_formComponentResized
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
closeWindow();
}//GEN-LAST:event_formWindowClosing
private void jButtonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOKActionPerformed
pd.redoxAsk = jRadioButtonAsk.isSelected();
pd.redoxN = jCheckBoxN.isSelected();
pd.redoxP = jCheckBoxP.isSelected();
pd.redoxS = jCheckBoxS.isSelected();
ok = true;
closeWindow();
}//GEN-LAST:event_jButtonOKActionPerformed
private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelActionPerformed
closeWindow();
}//GEN-LAST:event_jButtonCancelActionPerformed
private void jButtonHelpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonHelpActionPerformed
setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
Thread hlp = new Thread() {@Override public void run(){
String[] a = {"DB_0_Main_htm"};
lib.huvud.RunProgr.runProgramInProcess(null,ProgramConf.HELP_JAR,a,false,pc.dbg,pc.pathAPP);
try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec
catch (InterruptedException e) {}
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
}};//new Thread
hlp.start();
}//GEN-LAST:event_jButtonHelpActionPerformed
private void jRadioButtonAskActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonAskActionPerformed
jCheckBoxN.setEnabled(false);
jCheckBoxP.setEnabled(false);
jCheckBoxS.setEnabled(false);
}//GEN-LAST:event_jRadioButtonAskActionPerformed
private void jRadioButtonDoNotAskActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonDoNotAskActionPerformed
jCheckBoxN.setEnabled(true);
jCheckBoxP.setEnabled(true);
jCheckBoxS.setEnabled(true);
}//GEN-LAST:event_jRadioButtonDoNotAskActionPerformed
private void closeWindow() {
dbF.exitCancel = !ok;
this.dispose();
dbF.bringToFront();
} // closeWindow()
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JButton jButtonCancel;
private javax.swing.JButton jButtonHelp;
private javax.swing.JButton jButtonOK;
private javax.swing.JCheckBox jCheckBoxN;
private javax.swing.JCheckBox jCheckBoxP;
private javax.swing.JCheckBox jCheckBoxS;
private javax.swing.JLabel jLabelMessage;
private javax.swing.JLabel jLabelTop;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JRadioButton jRadioButtonAsk;
private javax.swing.JRadioButton jRadioButtonDoNotAsk;
// End of variables declaration//GEN-END:variables
}
| 21,795 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
OneInstance.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/DataBase/src/database/OneInstance.java | package database;
/** The method <b>findOtherInstance</b> returns true if another instance
* of the application is already running in another JVM.
* <p>
* A server socket is used. The application tries to connect to the socket.
* If a server is not found, the socket is free and the server socket is
* constructed. If a server is found and a connection is made, it means that
* the application is already running. In that case the command line arguments
* are sent to other instance.
* <p>
* Modify the code after lines containing <code>"==="</code>.
* <p>
* Use "getInstance()" instead of creating a new OneInstance()!
* <p>
* Copyright (C) 2014 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class OneInstance {
private static OneInstance one = null;
private static final String knockKnock = "Ett skepp kommer lastad";
private boolean dbg;
private String progName;
private int port;
private java.net.ServerSocket serverSocket = null;
private java.net.Socket socket;
private java.io.BufferedReader socketIn;
private java.io.PrintWriter socketOut;
private String whosThere;
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
/** Find out if another instance of the application is already running in another JVM.
* <p>
* A server socket is used. The application tries to connect to the socket.
* If a server is not found, the socket is free and the server socket is
* constructed. If a server is found and a connection is made, it means that
* the application is already running. In that case the command line arguments
* are sent to other instance.
* <p>
* Modify the code after lines containing <code>"==="</code>.
* <p>
* Use "getInstance()" instead of creating a new OneInstance()!
* @param args the command line arguments to the main method of the application.
* The arguments are sent to the other instance through the server socket.
* Not used if no other instance of the application is found.
* @param portDef a port to search for a server socket.
* If no other application is found, at least five additional sockets are tried.
* @param prgName the application's name, used for message and error reporting.
* @param debg true if performance messages are wished.
* @return true if another instance is found, false otherwise. */
public boolean findOtherInstance(
final String[] args,
final int portDef,
final String prgName,
final boolean debg) {
if(one != null) {
String msg;
if(prgName != null && prgName.trim().length() >0) {msg = prgName;} else {msg = "OneInstance";}
if(debg) {System.out.println(msg+"- findOtherInstance already running.");}
return false;
} else {
one = this;
}
dbg = debg;
if(prgName != null && prgName.trim().length() >0) {progName = prgName;} else {progName = "OneInstance";}
whosThere = progName;
// loop though sockets numbers, if a socket is busy check if it is
// another instance of this application
//<editor-fold defaultstate="collapsed" desc="first loop">
port = portDef;
int portNbrMax = portDef + 5;
java.net.InetAddress address = null;
do{
// note: testing a client socket (creating a stream socket and connecting it)
// would be much more time consuming
try{
serverSocket = new java.net.ServerSocket(port);
if(dbg){System.out.println(progName+"- socket "+port+" is not used.");}
serverSocket.close();
serverSocket = null;
port++;
} catch (java.net.BindException ex) {
if(dbg){System.out.println(progName+"- socket "+port+" busy. Another instance already running?");}
if(address == null) {
try {
address = java.net.InetAddress.getLocalHost();
if(dbg){System.out.println(progName+"- Local machine address: "+address.toString());}
}
catch (java.net.UnknownHostException e) {
System.out.println(progName+"- "+e.toString()+" using getLocalHost().");
address = null;
} //catch
}
if (!isOtherInstance(address, port)) {
//Not another instance. It means some software is using
// this socket port number; continue looking...
if(socketOut != null) {socketOut.close(); socketOut = null;}
if(socketIn != null) {
try{socketIn.close();} catch (java.io.IOException ioe) {}
socketIn = null;
}
socket = null;
port++;
} else {
//Another instance of this software is already running:
// send args[] and end the program (exit from "main")
sendArgsToOtherInstance(args);
return true;
}
} catch (java.io.IOException ex) { // there should be no error...
System.err.println(progName+"- "+
ex.toString()+nl+" while creating a stream Socket.");
break;
} // catch
} while (port < portNbrMax); // do-while
if(socketOut != null) {socketOut.close(); socketOut = null;}
if(socketIn != null) {
try{socketIn.close();} catch (java.io.IOException ioe) {}
socketIn = null;
}
socket = null;
// address = null; // garbage collect
//</editor-fold>
// Another instance not found: create a server socket on the first free port
//<editor-fold defaultstate="collapsed" desc="create server socket">
port = portDef;
do{
try{
serverSocket = new java.net.ServerSocket(port);
if(dbg){System.out.println(progName+"- Created server socket on port "+port);}
break;
} catch (java.net.BindException ex) {
if(dbg){System.out.println(progName+"- socket "+port+" is busy.");}
port++;
} //Socket busy
catch (java.io.IOException ex) { // there should be no error...
System.err.println(progName+"- "+
ex.toString()+nl+" while creating a Server Socket.");
break;
}
} while (port < portNbrMax); // do-while
//</editor-fold>
if(port == portNbrMax) {
System.out.println(progName+"- Error: could not create a server socket.");
return false;
}
// A Server Socket has been created.
// Wait for new connections on the serverSocket on a separate thread.
// The program will continue execution simultaenously...
//<editor-fold defaultstate="collapsed" desc="accept clients thread">
Thread t = new Thread(){@Override public void run(){
while(true){
final java.net.Socket client;
try{ // Wait until we get a client in serverSocket
if(dbg){System.out.println(progName+"- waiting for a connection to serverSocket("+port+").");}
// this will block until a connection is made:
client = serverSocket.accept();
}
catch (java.net.SocketException ex) {break;}
catch (java.io.IOException ex) {
System.err.println(progName+"- "+ex.toString()+nl+" Accept failed on server port: "+port);
break; //while
}
//Got a connection, wait for lines of text from the new connection (client)
//<editor-fold defaultstate="collapsed" desc="deal with a client thread">
if(dbg){System.out.println(progName+"- connection made to serverSocket in port "+port);}
Thread t = new Thread(){@Override public void run(){
String line;
boolean clientNewInstance = false;
boolean connected = true;
java.io.BufferedReader in = null;
java.io.PrintWriter out = null;
try{
client.setSoTimeout(3000); // avoid socket.readLine() lock
in = new java.io.BufferedReader(new java.io.InputStreamReader(client.getInputStream()));
out = new java.io.PrintWriter(client.getOutputStream(), true);
if(dbg){System.out.println(progName+"- while (connected)");}
while(connected){
if(dbg){System.out.println(progName+"- (waiting for line from client)");}
// wait for a line of text from the client
// note: client.setSoTimeout(3000) means
// SocketTimeoutException after 3 sec
line = in.readLine();
if(line == null) {break;}
if(dbg){System.out.println(progName+"- got line from client (in port "+port+"): "+line);}
// is this another instance asking who am I?
if(line.toLowerCase().equals(knockKnock.toLowerCase())) {
// yes: another instance calling!
// === add code here to bring this instance to front ===
// --- for HelpWindow.java:
//if(HelpWindow.getInstance() != null) {
// HelpWindow.getInstance().bringToFront();
// if(dbg) {System.out.println(progName+"- bringToFront()");}
//}
// --- for Spana:
//if(SpanaFrame.getInstance() != null) {SpanaFrame.getInstance().bringToFront();}
// --- for DataBase:
if(FrameDBmain.getInstance() != null) {FrameDBmain.getInstance().bringToFront();}
// ---
//answer to client with program identity
if(dbg){System.out.println(progName+"- sending line to client (at port "+port+"): "+whosThere);}
out.println(whosThere);
clientNewInstance=true;
} else {// line != knockKnock
if(clientNewInstance) {
// === add code here to deal with the command-line arguments ===
// from the new instance sendt to this instance
// --- for HelpWindow.java:
//if(HelpWindow.getInstance() != null) {
// HelpWindow.getInstance().bringToFront();
// HelpWindow.getInstance().setHelpID(line);
//}
// --- for Spana:
//if(SpanaFrame.getInstance() != null) {SpanaFrame.getInstance().dispatchArg(line);}
// --- for Database:
if(FrameDBmain.getInstance() != null) {FrameDBmain.getInstance().dispatchArg(line);}
// ---
} else { //not clientNewInstance
if(dbg){System.err.println(progName+"- Warning: got garbage in port "+port+" from another application; line = \""+line+"\"");}
connected = false; // close the connection
}
} //line = knockKnock ?
} // while(connected)
out.close(); out = null;
in.close(); in = null;
client.close();
} catch (java.io.IOException ioe) {
System.err.println(progName+"- Note: "+ioe.toString()+nl+" Closing socket connection in port "+port);
} finally {
if(dbg){System.out.println(progName+"- Connection to serverSocket("+port+") closed ");}
if(out != null) {out.close();}
try{ if(in != null) {in.close();} client.close(); }
catch (java.io.IOException ioe) {}
}
}};
t.start(); // "start" returns inmediately without waiting.
//</editor-fold>
// wait for next connection....
} // while(true)
}};
t.start(); // "start" returns inmediately without waiting.
//</editor-fold>
//-------------------------------------------------------------
// Finished checking for another instance
//-------------------------------------------------------------
return false; // found no other instance
}
//<editor-fold defaultstate="collapsed" desc="isOtherInstanceInSocket">
// -------------------------------
/** Checking for another instance:<br>
* The first instance of this program opens a server socket connection and
* listens for other instances of this program to send messages. The
* first instance also creates a "lock" file containing the socket number.
* This method tries to send a message to a socket, and checks if the
* response corresponds to that expected from the first instance of this
* application. If the response is correct, it returns true.
* @param port the socket number to try
* @return <code>true</code> if another instance of this program is
* listening at this socket number; <code>false</code> if either
* an error occurs, no response is obtained from this socket within one sec,
* or if the answer received is not the one expected from the first instance.
*/
private boolean isOtherInstance(final java.net.InetAddress address, final int port) {
if (port <= 0) {return false;}
if(dbg){System.out.println(progName+"- isOtherInstance("+port+") ?");}
// Create socket connection
String line;
boolean ok;
try{
socket = new java.net.Socket(address, port);
socket.setSoTimeout(1000); // avoid socket.readLine() lock
socketOut = new java.io.PrintWriter(socket.getOutputStream(), true);
socketIn = new java.io.BufferedReader(
new java.io.InputStreamReader(socket.getInputStream()));
//Send data over socket
if(dbg){System.out.println(progName+"- Sending text:\""+knockKnock+"\" to port "+port);}
socketOut.println(knockKnock);
//Receive text from server.
if(dbg){System.out.println(progName+"- Reading answer from socket "+port);}
// note: socket.setSoTimeout(1000) means
// SocketTimeoutException after 1 sec
try{
line = socketIn.readLine();
if(dbg){System.out.println(progName+"- Text received: \"" + line + "\" from port "+port);}
} catch (java.io.IOException ex){
line = null;
System.err.println(progName+"- Note: "+ex.toString()+nl+" in socket("+port+").readLine()");
} //catch
// did we get the correct answer?
if(line != null && line.toLowerCase().startsWith(whosThere.toLowerCase())) {
if(dbg){System.out.println(progName+"- isOtherInstance("+port+") = true");}
ok = true;
} else {
if(dbg){System.out.println(progName+"- isOtherInstance("+port+") = false");}
ok = false;
}
} catch (java.io.IOException ex) {
System.out.println(progName+"- "+ex.toString()+", isOtherInstance("+port+") = false");
ok = false;
}
return ok;
// -------------------------------------
} // isOtherInstance(port)
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="sendArgsToOtherInstance">
// -------------------------------
/** Checking for another instance:<br>
* The first instance of this program opens a server socket connection and
* listens for other instances of this program to send messages. The
* first instance also creates a "lock" file containing the socket number.
* This method assumes that this is a "2nd" instance of this program
* and it sends the command-line arguments from this instance to the
* first instance, through the socket connetion.
*
* <p>The connection is closed and the program ends after sending the
* arguments.</p>
*
* @param args <code>String[]</code> contains the command-line
* arguments given to this instance of the program.
*/
private void sendArgsToOtherInstance(String args[]) {
if(socketOut == null) {return;}
if(args != null && args.length >0) {
for(String arg : args) {
if(dbg) {System.out.println(progName+"- sending command-line arg to other instance: \"" + arg + "\"");}
socketOut.println(arg);
} // for arg
} // if args.length >0
try {
if(socketIn != null) {socketIn.close(); socketIn = null;}
if(socketOut != null) {socketOut.close(); socketOut = null;}
socket = null;
} catch (java.io.IOException ex) {
System.out.println(progName+"- "+ex.toString()+", while closing streams.");
}
// --------------------------------
} //sendArgsToOtherInstance(args[])
// </editor-fold>
/** Use this method to get the instance of this class to start
* a the server socket thread, instead of constructing a new object.
* @return an instance of this class
* @see OneInstance#endCheckOtherInstances() endCheckOtherInstances */
public static OneInstance getInstance() {return one;}
/** Stops the server socket thread. */
public static void endCheckOtherInstances() {
if(one != null) {
try{one.serverSocket.close(); one.serverSocket = null; one = null;} catch (java.io.IOException ex) {}
}
}
}
| 18,942 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
ErrMsgBox.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/DataBase/src/database/ErrMsgBox.java | package database;
/** Displays a "message box" modal dialog with an "OK" button and a title.
* The message is displayed in a text area (non-editable),
* which can be copied and pasted elsewhere.
*
* Copyright (C) 2014-2016 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class ErrMsgBox {
private static final String nl = System.getProperty("line.separator");
//<editor-fold defaultstate="collapsed" desc="ErrMsgBox(msg, title)">
/** Displays a "message box" modal dialog with an "OK" button and a title.
* The message is displayed in a text area (non-editable),
* which can be copied and pasted elsewhere.
* @param msg will be displayed in a text area, and line breaks may be
* included, for example: <code>new MsgBox("Very\nbad!",""); </code>
* If null or empty nothing is done.
* @param title for the dialog. If null or empty, "Error:" is used
* @see #showErrMsg(java.awt.Component, java.lang.String, int) showErrMsg
* @version 2015-July-14 */
public ErrMsgBox(String msg, String title) {
if(msg == null || msg.trim().length() <=0) {
System.out.println("--- MsgBox: null or empty \"message\".");
return;
}
//--- Title
if(title == null || title.length() <=0) {title = " Error:";}
java.awt.Frame frame = new java.awt.Frame(title);
//--- Icon
String iconName = "images/ErrMsgBx.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
if(imgURL != null) {frame.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());}
else {System.out.println("--- Error in MsgBox constructor: Could not load image = \""+iconName+"\"");}
frame.pack();
//--- centre Window frame on Screen
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int left; int top;
left = Math.max(55, (screenSize.width - frame.getWidth() ) / 2);
top = Math.max(10, (screenSize.height - frame.getHeight()) / 2);
frame.setLocation(Math.min(screenSize.width-100, left), Math.min(screenSize.height-100, top));
//---
final String msgText = wrapString(msg.trim(),80);
//System.out.println("--- MsgBox:"+nl+msgText+nl+"---");
frame.setVisible(true);
//javax.swing.JOptionPane.showMessageDialog(frame, msg, title, javax.swing.JOptionPane.ERROR_MESSAGE);
MsgBoxDialog msgBox = new MsgBoxDialog(frame, msgText, title, true);
msgBox.setVisible(true); // becase the dialog is modal, statements below will wait
msgBox.dispose();
frame.setVisible(false);
frame.dispose();
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="private class MsgBoxDialog">
private static class MsgBoxDialog extends java.awt.Dialog {
private java.awt.Button ok;
private java.awt.Panel p;
private final java.awt.TextArea text;
/** Creates new form NewDialog */
public MsgBoxDialog(java.awt.Frame parent, String msg, String title, boolean modal) {
super(parent, (" "+title), modal);
addWindowListener(new java.awt.event.WindowAdapter() {
@Override public void windowClosing(java.awt.event.WindowEvent evt) {
MsgBoxDialog.this.setVisible(false);
}
});
setLayout(new java.awt.BorderLayout());
p = new java.awt.Panel();
p.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER));
ok = new java.awt.Button();
// find out the size of the message (width and height)
final int wMax = 85; final int hMax=20;
final int wMin = 5; final int hMin = 1;
int w = wMin;
int h=hMin; int i=0; int j=wMin;
final String eol = "\n"; char c;
final String nl = System.getProperty("line.separator");
while (true) {
c = msg.charAt(i);
String s = String.valueOf(c);
if(s.equals(eol) || s.equals(nl)) {
h++; j=wMin;
} else {
j++; w = Math.max(j,w);
}
i++;
if(i >= msg.length()-1) {break;}
}
// create a text area
int scroll = java.awt.TextArea.SCROLLBARS_NONE;
if(w > wMax && h <= hMax) {scroll = scroll & java.awt.TextArea.SCROLLBARS_HORIZONTAL_ONLY;}
if(h > hMax && w <= wMax) {scroll = scroll & java.awt.TextArea.SCROLLBARS_VERTICAL_ONLY;}
if(w > wMax && h > hMax) {scroll = java.awt.TextArea.SCROLLBARS_BOTH;}
w = Math.min(Math.max(w,10),wMax);
h = Math.min(h,hMax);
text = new java.awt.TextArea(msg, h, w, scroll);
text.setEditable(false);
//text.setBackground(java.awt.Color.white);
text.addKeyListener(new java.awt.event.KeyAdapter() {
@Override public void keyPressed(java.awt.event.KeyEvent evt) {
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER
|| evt.getKeyCode() == java.awt.event.KeyEvent.VK_ESCAPE) {closeDialog();}
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_TAB) {ok.requestFocusInWindow();}
}
});
text.setBackground(java.awt.Color.WHITE);
text.setFont(new java.awt.Font("monospaced", java.awt.Font.PLAIN, 12));
add(text, java.awt.BorderLayout.CENTER);
ok.setLabel("OK");
ok.addActionListener(new java.awt.event.ActionListener() {
@Override public void actionPerformed(java.awt.event.ActionEvent evt) {
closeDialog();
}
});
ok.addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER
|| evt.getKeyCode() == java.awt.event.KeyEvent.VK_ESCAPE) {closeDialog();}
}
});
p.add(ok);
add(p, java.awt.BorderLayout.SOUTH);
pack();
ok.requestFocusInWindow();
//--- centre Window frame on Screen
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int left; int top;
left = Math.max(55, (screenSize.width - getWidth() ) / 2);
top = Math.max(10, (screenSize.height - getHeight()) / 2);
setLocation(Math.min(screenSize.width-100, left), Math.min(screenSize.height-100, top));
}
private void closeDialog() {this.setVisible(false);}
} // private static class MsgBoxDialog
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="private wrapString">
/** Returns an input string, with lines that are longer than <code>maxLength</code>
* word-wrapped and indented. *
* @param s input string
* @param maxLength if an input line is longer than this length,
* the line will be word-wrapped at the first white space after <code>maxLength</code>
* and indented with 4 spaces
* @return string with long-lines word-wrapped
*/
private static String wrapString(String s, int maxLength) {
String deliminator = "\n";
StringBuilder result = new StringBuilder();
StringBuffer wrapLine;
int lastdelimPos;
for (String line : s.split(deliminator, -1)) {
if(line.length()/(maxLength+1) < 1) {
result.append(line).append(deliminator);
}
else { //line too long, try to split it
wrapLine = new StringBuffer();
lastdelimPos = 0;
for (String token : line.trim().split("\\s+", -1)) {
if (wrapLine.length() - lastdelimPos + token.length() > maxLength) {
if(wrapLine.length()>0) {wrapLine.append(deliminator);}
wrapLine.append(" ").append(token);
lastdelimPos = wrapLine.length() + 1;
} else {
if(wrapLine.length() <=0) {wrapLine.append(token);}
else {wrapLine.append(" ").append(token);}
}
}
result.append(wrapLine).append(deliminator);
}
}
return result.toString();
}
// </editor-fold>
}
| 8,978 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
Main.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/DataBase/src/database/Main.java | package database;
/** Checks that all the jar-libraries needed exist.
* <br>
* Copyright (C) 2014-2016 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class Main {
private static final String progName = "Program \"DataBase\""; //Leta? Lagra? Samla?
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
private static boolean started = false;
private static final String SLASH = java.io.File.separator;
/** Check that all the jar-libraries needed do exist.
* @param args the command line arguments */
public static void main(String[] args) {
// ---- are all jar files needed there?
if(!doJarFilesExist()) {return;}
// ---- ok!
FrameDBmain.main(args);
} //main
//<editor-fold defaultstate="collapsed" desc="doJarFilesExist">
/** Look in the running jar file's classPath Manifest for any other "library"
* jar-files listed under "Class-path".
* If any of these jar files does not exist display an error message
* (and an error Frame) and continue.
* @return true if all needed jar files exist; false otherwise.
* @version 2016-Aug-03 */
private static boolean doJarFilesExist() {
java.io.File libJarFile, libPathJarFile;
java.util.jar.JarFile runningJar = getRunningJarFile();
// runningJar.getName() = C:\Eq-Calc_Java\dist\Prog.jar
if(runningJar != null) { // if running within Netbeans there will be no jar-file
java.util.jar.Manifest manifest;
try {manifest = runningJar.getManifest();}
catch (java.io.IOException ex) {
manifest = null;
String msg = "Warning: no manifest found in the application's jar file:"+nl+
"\""+runningJar.getName()+"\"";
ErrMsgBox emb = new ErrMsgBox(msg, progName);
//this will return true;
}
if(manifest != null) {
String classPath = manifest.getMainAttributes().getValue("Class-Path");
if(classPath != null && classPath.length() > 0) {
// this will be a list of space-separated names
String[] jars = classPath.split("\\s+"); //regular expression to match one or more spaces
if(jars.length >0) {
java.io.File[] rootNames = java.io.File.listRoots();
boolean isPathAbsolute;
String pathJar;
String p = getPathApp(); // get the application's path
for(String jar : jars) { // loop through all jars needed
libJarFile = new java.io.File(jar);
if(libJarFile.exists()) {continue;}
isPathAbsolute = false;
for(java.io.File f : rootNames) {
if(jar.toLowerCase().startsWith(f.getAbsolutePath().toLowerCase())) {
isPathAbsolute = true;
break;}
}
if(!isPathAbsolute) { // add the application's path
if(!p.endsWith(SLASH) && !jar.startsWith(SLASH)) {p = p+SLASH;}
pathJar = p + jar;
} else {pathJar = jar;}
libPathJarFile = new java.io.File(pathJar);
if(libPathJarFile.exists()) {continue;}
libPathJarFile = new java.io.File(libPathJarFile.getAbsolutePath());
ErrMsgBox emb = new ErrMsgBox(progName+" - Error:"+nl+
" File: \""+jar+"\" NOT found."+nl+
" And file: \""+libPathJarFile.getName()+"\" is NOT in folder:"+nl+
" \""+libPathJarFile.getParent()+"\""+nl+
" either!"+nl+nl+
" This file is needed by the program."+nl, progName);
return false;
}
}
}//if classPath != null
} //if Manifest != null
} //if runningJar != null
return true;
} //doJarFilesExist()
//<editor-fold defaultstate="collapsed" desc="getRunningJarFile()">
/** Find out the jar file that contains this class
* @return a File object of the jar file containing the enclosing class "Main",
* or null if the main class is not inside a jar file.
* @version 2014-Jan-17 */
public static java.util.jar.JarFile getRunningJarFile() {
//from http://www.rgagnon.com/javadetails/
//and the JarClassLoader class
C c = new C();
String className = c.getClass().getName().replace('.', '/');
// class = "progPackage.Main"; className = "progPackage/Main"
java.net.URL url = c.getClass().getResource("/" + className + ".class");
// url = "jar:file:/C:/Eq-Calc_Java/dist/Prog.jar!/progPackage/Main.class"
if(url.toString().startsWith("jar:")) {
java.net.JarURLConnection jUrlC;
try{
jUrlC = (java.net.JarURLConnection)url.openConnection();
return jUrlC.getJarFile();
} catch(java.io.IOException ex) {
ErrMsgBox emb = new ErrMsgBox("Error "+ex.toString(), progName);
return null;
}
} else {
// it might not be a jar file if running within NetBeans
return null;
}
} //getRunningJarFile()
//</editor-fold>
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="getPathApp">
/** Get the path where an application is located.
* @return the directory where the application is located,
* or "user.dir" if an error occurs
* @version 2014-Jan-17 */
private static class C {private static void C(){}}
public static String getPathApp() {
C c = new C();
String path;
java.net.URI dir;
try{
dir = c.getClass().
getProtectionDomain().
getCodeSource().
getLocation().
toURI();
if(dir != null) {
String d = dir.toString();
if(d.startsWith("jar:") && d.endsWith("!/")) {
d = d.substring(4, d.length()-2);
dir = new java.net.URI(d);
}
path = (new java.io.File(dir.getPath())).getParent();
} else {path = System.getProperty("user.dir");}
}
catch (java.net.URISyntaxException e) {
if(!started) {
ErrMsgBox emb = new ErrMsgBox("Error: "+e.toString()+nl+
" trying to get the application's directory.", progName);
}
path = System.getProperty("user.dir");
} // catch
started = true;
return path;
} //getPathApp()
//</editor-fold>
}
| 7,301 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
HelpAboutDB.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/DataBase/src/database/HelpAboutDB.java | package database;
import lib.database.ProgramDataDB;
import lib.huvud.LicenseFrame;
import lib.common.MsgExceptn;
/** Show a window frame with "help-about" information, versions, etc.
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class HelpAboutDB extends javax.swing.JFrame {
private boolean finished = false;
private HelpAboutDB frame = null;
private LicenseFrame lf = null;
private java.awt.Dimension windowSize; //new java.awt.Dimension(300,200);
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
/** Creates new form HelpAboutL
* @param pathAPP
* @param pd */
public HelpAboutDB(final String pathAPP, final ProgramDataDB pd,
final boolean saveIniFileToApplicationPathOnly) {
initComponents();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
//--- Close window on ESC key
javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE");
javax.swing.Action escAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
closeWindow();
}};
getRootPane().getActionMap().put("ESCAPE", escAction);
//--- Alt-X eXit
javax.swing.KeyStroke altXKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altXKeyStroke,"ALT_X");
getRootPane().getActionMap().put("ALT_X", escAction);
//--- alt-Q exit
javax.swing.KeyStroke altQKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altQKeyStroke,"ALT_Q");
getRootPane().getActionMap().put("ALT_Q", escAction);
//--- Title, etc
//getContentPane().setBackground(new java.awt.Color(255, 255, 153));
getContentPane().setBackground(java.awt.Color.white);
this.setTitle("DataBase: About");
//---- Icon
String iconName = "images/Question_16x16.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
if(imgURL != null) {this.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());}
else {System.out.println("Error: Could not load image = \""+iconName+"\"");}
//
jLabelVers.setText("Program version: "+FrameDBmain.VERS);
//
jLabelLib.setText("LibChemDiagr: "+lib.Version.version());
//
jLabelLib2.setText("LibDataBase: "+lib.database.Version.version());
//
java.io.File f;
java.text.DateFormat dateFormatter = java.text.DateFormat.getDateTimeInstance
(java.text.DateFormat.DEFAULT, java.text.DateFormat.SHORT, java.util.Locale.getDefault());
long lm = -1;
for(String t : pd.dataBasesList) {
if(t == null || t.length() <=0) {continue;}
f = new java.io.File(t);
lm = Math.max(lm, f.lastModified());
}
if(lm <=0) {jLabelLastUpdate.setText(" ");}
else {
jLabelLastUpdate.setText("last database-file updated: "+
dateFormatter.format(new java.util.Date(lm)));
}
//
if(pathAPP != null) {
if(pathAPP.trim().length()>0) {jLabelPathApp.setText(pathAPP);}
else {jLabelPathApp.setText(" \"\"");}
}
jLabelPathUser.setText(System.getProperty("user.home"));
this.validate();
int w = jLabelPathApp.getWidth()+40;
if(w > this.getWidth()) {this.setSize(w, this.getHeight());}
//
if(FrameDBmain.fileIni != null
&& (!FrameDBmain.fileIni.canWrite() || !FrameDBmain.fileIni.setWritable(true))) {
jLabelIniF.setText("INI-file (read-only):");
}
if(FrameDBmain.fileIni != null) {jLabelIniFile.setText(FrameDBmain.fileIni.getPath());}
if(FrameDBmain.fileIniUser != null) {
jLabelIniFileUser.setText(FrameDBmain.fileIniUser.getPath());
} else {
if(saveIniFileToApplicationPathOnly) {
jLabelIniFU.setText("(saveIniFileToApplicationPathOnly = true)");
} else {
jLabelIniFU.setVisible(false);
}
jLabelIniFileUser.setVisible(false);
}
jLabelJavaVers.setText("Java Runtime Environment "+System.getProperty("java.version"));
jLabelOS.setText("<html>Operating system: \""+
System.getProperty("os.name")+" "+System.getProperty("os.version")+"\"<br>"+
"architecture: \""+System.getProperty("os.arch")+"\"</html>");
/*
// remove "bold" from CrossPlatform look and feel
java.awt.Font fN = jLabelName.getFont();
fN = new java.awt.Font(fN.getName(), java.awt.Font.PLAIN, fN.getSize());
jLabelName.setFont(fN);
jLabelLibs.setFont(fN);
jLabelChemDiagLib.setFont(fN);
jLabelLibLS.setFont(fN);
jLabelJVectClipb.setFont(fN); jLabelJVectClipb_www.setFont(fN);
jLabelFreeHEP.setFont(fN); jLabelFreeHEP_www.setFont(fN);
jLabelAppP.setFont(fN); jLabelPathApp.setFont(fN);
jLabelIniF.setFont(fN); jLabelIniFile.setFont(fN);
jLabelJava.setFont(fN);
jLabelNetBeans.setFont(fN); jLabelNetBeans_www.setFont(fN);
jLabelJavaVers.setFont(fN);
jLabelOS.setFont(fN);
fN = jButtonLicense.getFont();
fN = new java.awt.Font(fN.getName(), java.awt.Font.PLAIN, fN.getSize());
jButtonLicense.setFont(fN);
*/
this.validate();
w = jLabelIniFile.getWidth()+40;
if(w > this.getWidth()) {this.setSize(w, this.getHeight());}
//---- Centre window on parent/screen
int left,top;
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
left = Math.max(0,(screenSize.width-this.getWidth())/2);
top = Math.max(0,(screenSize.height-this.getHeight())/2);
this.setLocation(Math.min(screenSize.width-this.getWidth()-20,left),
Math.min(screenSize.height-this.getHeight()-20, top));
}
public void start() {
setVisible(true);
windowSize = getSize();
frame = this;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabelName = new javax.swing.JLabel();
jLabelVers = new javax.swing.JLabel();
jLabelLib = new javax.swing.JLabel();
jLabelLib2 = new javax.swing.JLabel();
jLabelLastUpdate = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jButtonLicense = new javax.swing.JButton();
jLabel_wwwKTH = new javax.swing.JLabel();
jLabel_www = new javax.swing.JLabel();
jSeparator2 = new javax.swing.JSeparator();
jLabelJavaIcon = new javax.swing.JLabel();
jLabelJava = new javax.swing.JLabel();
jPanelNetBeans = new javax.swing.JPanel();
jLabelNetbeansIcon = new javax.swing.JLabel();
jLabelNetBeans = new javax.swing.JLabel();
jLabelNetBeans_www = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jLabelJavaVers = new javax.swing.JLabel();
jLabelOS = new javax.swing.JLabel();
jSeparator3 = new javax.swing.JSeparator();
jLabelPathA = new javax.swing.JLabel();
jLabelPathApp = new javax.swing.JLabel();
jLabelPathU = new javax.swing.JLabel();
jLabelPathUser = new javax.swing.JLabel();
jLabelIniF = new javax.swing.JLabel();
jLabelIniFile = new javax.swing.JLabel();
jLabelIniFU = new javax.swing.JLabel();
jLabelIniFileUser = new javax.swing.JLabel();
jLabelUnicode = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jLabelName.setText("<html><font size=+1><b>DataBase</b></font> © 2012-2020 I.Puigdomenech<br>\nThis program comes with<br>\nABSOLUTELY NO WARRANTY.<br>\nThis is free software, and you may<br>\nredistribute it under the GNU GPL license.</html>"); // NOI18N
jLabelName.setVerticalAlignment(javax.swing.SwingConstants.TOP);
jLabelVers.setText("Program version: 201#-March-30");
jLabelLib.setText("LibChemDiagr: 201#-March-30");
jLabelLib2.setText("LibDataBase: 201#-March-30");
jLabelLastUpdate.setText("latest database-file update: 2010-06-06");
jPanel2.setOpaque(false);
jButtonLicense.setMnemonic('l');
jButtonLicense.setText(" License Details ");
jButtonLicense.setAlignmentX(0.5F);
jButtonLicense.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonLicense.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonLicenseActionPerformed(evt);
}
});
jLabel_wwwKTH.setForeground(new java.awt.Color(0, 0, 221));
jLabel_wwwKTH.setText("<html><u>www.kth.se/che/medusa</u></html>"); // NOI18N
jLabel_wwwKTH.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jLabel_wwwKTH.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel_wwwKTHMouseClicked(evt);
}
});
jLabel_www.setForeground(new java.awt.Color(0, 0, 221));
jLabel_www.setText("<html><u>sites.google.com/site/chemdiagr/</u></html>"); // NOI18N
jLabel_www.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jLabel_www.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel_wwwMouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel_wwwKTH, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel_www, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButtonLicense))
.addGap(0, 62, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(28, 28, 28)
.addComponent(jButtonLicense)
.addGap(18, 18, 18)
.addComponent(jLabel_wwwKTH, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(3, 3, 3)
.addComponent(jLabel_www, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 18, Short.MAX_VALUE))
);
jLabelJavaIcon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/database/images/Java_24x24.gif"))); // NOI18N
jLabelJava.setText("<html>Java Standard Edition<br> Development Kit 7 (JDK 1.7)</html>"); // NOI18N
jPanelNetBeans.setOpaque(false);
jLabelNetbeansIcon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/database/images/Netbeans11_24x24.gif"))); // NOI18N
jLabelNetbeansIcon.setIconTextGap(0);
jLabelNetBeans.setText("NetBeans IDE 11"); // NOI18N
jLabelNetBeans_www.setForeground(new java.awt.Color(0, 0, 221));
jLabelNetBeans_www.setText("<html><u>netbeans.org</u></html>"); // NOI18N
jLabelNetBeans_www.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jLabelNetBeans_www.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabelNetBeans_wwwMouseClicked(evt);
}
});
javax.swing.GroupLayout jPanelNetBeansLayout = new javax.swing.GroupLayout(jPanelNetBeans);
jPanelNetBeans.setLayout(jPanelNetBeansLayout);
jPanelNetBeansLayout.setHorizontalGroup(
jPanelNetBeansLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelNetBeansLayout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jLabelNetbeansIcon)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabelNetBeans)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelNetBeans_www, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelNetBeansLayout.setVerticalGroup(
jPanelNetBeansLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelNetBeansLayout.createSequentialGroup()
.addGap(0, 0, 0)
.addGroup(jPanelNetBeansLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelNetbeansIcon)
.addGroup(jPanelNetBeansLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelNetBeans_www, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelNetBeans, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))))
);
jPanel1.setOpaque(false);
jLabelJavaVers.setText("jLabelJavaVers");
jLabelOS.setText("<html>Operating system:<br>\"os.name os.version\" \narchitecture: \"os.arch\"</html>");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabelJavaVers)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jLabelOS))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabelJavaVers)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelOS, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(12, Short.MAX_VALUE))
);
jLabelPathA.setLabelFor(jLabelPathA);
jLabelPathA.setText("Application path:"); // NOI18N
jLabelPathApp.setText("\"null\""); // NOI18N
jLabelPathU.setText("User \"home\" directory:");
jLabelPathUser.setText("\"null\"");
jLabelIniF.setLabelFor(jLabelIniFile);
jLabelIniF.setText("INI-file:"); // NOI18N
jLabelIniFile.setText("\"null\""); // NOI18N
jLabelIniFU.setText("User INI-file:");
jLabelIniFileUser.setText("\"null\"");
jLabelUnicode.setText("(Unicode UTF-8)");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jSeparator3, javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelJavaIcon)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelJava, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanelNetBeans, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelLastUpdate)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelVers)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelUnicode))
.addComponent(jLabelLib)
.addComponent(jLabelLib2)
.addComponent(jLabelName, javax.swing.GroupLayout.PREFERRED_SIZE, 307, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelPathA)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelPathApp))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelIniFU)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelIniFileUser))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelIniF)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelIniFile))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelPathU)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelPathUser)))
.addGap(0, 0, Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(2, 2, 2)
.addComponent(jLabelName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelVers)
.addComponent(jLabelUnicode))
.addGap(2, 2, 2)
.addComponent(jLabelLib)
.addGap(2, 2, 2)
.addComponent(jLabelLib2))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelLastUpdate)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(6, 6, 6)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelJava, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelJavaIcon))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanelNetBeans, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelPathA)
.addComponent(jLabelPathApp))
.addGap(2, 2, 2)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelPathU)
.addComponent(jLabelPathUser))
.addGap(2, 2, 2)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelIniF)
.addComponent(jLabelIniFile))
.addGap(2, 2, 2)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelIniFU)
.addComponent(jLabelIniFileUser))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jLabel_wwwKTHMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel_wwwKTHMouseClicked
this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
jLabel_wwwKTH.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
BareBonesBrowserLaunch.openURL("https://www.kth.se/che/medusa/", this);
this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jLabel_wwwKTH.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
}//GEN-LAST:event_jLabel_wwwKTHMouseClicked
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
closeWindow();
}//GEN-LAST:event_formWindowClosing
private void jLabelNetBeans_wwwMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelNetBeans_wwwMouseClicked
this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
jLabelNetBeans_www.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
BareBonesBrowserLaunch.openURL("https://netbeans.org/", this);
this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jLabelNetBeans_www.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
}//GEN-LAST:event_jLabelNetBeans_wwwMouseClicked
private void jLabel_wwwMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel_wwwMouseClicked
this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
jLabel_www.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
BareBonesBrowserLaunch.openURL("https://sites.google.com/site/chemdiagr/", this);
this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jLabel_www.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
}//GEN-LAST:event_jLabel_wwwMouseClicked
private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
if(windowSize != null) {
int w = windowSize.width;
int h = windowSize.height;
if(this.getHeight()<h){this.setSize(this.getWidth(), h);}
if(this.getWidth()<w){this.setSize(w,this.getHeight());}
}
}//GEN-LAST:event_formComponentResized
private void jButtonLicenseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLicenseActionPerformed
if(lf != null) {return;} //this should not happen
this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
Thread licShow = new Thread() {@Override public void run(){
jButtonLicense.setEnabled(false);
lf = new LicenseFrame(HelpAboutDB.this);
lf.setVisible(true);
HelpAboutDB.this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
lf.waitFor();
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
jButtonLicense.setEnabled(true);
lf = null;
}}); //invokeLater(Runnable)
}};//new Thread
licShow.start();
}//GEN-LAST:event_jButtonLicenseActionPerformed
public void closeWindow() {
if(lf != null) {lf.closeWindow();}
finished = true; //return from "waitFor()"
this.notify_All();
this.dispose();
} // closeWindow()
private synchronized void notify_All() {
//needed by "waitFor()"
notifyAll();
}
/** this method will wait for this dialog frame to be closed */
public synchronized void waitFor() {
while(!finished) {
try {wait();} catch (InterruptedException ex) {}
} // while
} // waitFor()
public void bringToFront() {
if(frame != null) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override public void run() {
frame.setVisible(true);
if((frame.getExtendedState() & javax.swing.JFrame.ICONIFIED) // minimised?
== javax.swing.JFrame.ICONIFIED) {
frame.setExtendedState(javax.swing.JFrame.NORMAL);
} // if minimized
frame.setAlwaysOnTop(true);
frame.toFront();
frame.requestFocus();
frame.setAlwaysOnTop(false);
}
});
}
} // bringToFront()
//<editor-fold defaultstate="collapsed" desc="class BareBonesBrowserLaunch">
/**
* <b>Bare Bones Browser Launch for Java</b><br>
* Utility class to open a web page from a Swing application
* in the user's default browser.<br>
* Supports: Mac OS X, GNU/Linux, Unix, Windows XP/Vista/7<br>
* Example Usage:<code><br>
* String url = "http://www.google.com/";<br>
* BareBonesBrowserLaunch.openURL(url);<br></code>
* Latest Version: <a href=http://centerkey.com/java/browser>centerkey.com/java/browser</a><br>
* Author: Dem Pilafian<br>
* WTFPL -- Free to use as you like
* @version 3.2, October 24, 2010
*/
private static class BareBonesBrowserLaunch {
static final String[] browsers = { "x-www-browser", "google-chrome",
"firefox", "opera", "epiphany", "konqueror", "conkeror", "midori",
"kazehakase", "mozilla", "chromium" }; // modified by Ignasi (added "chromium")
static final String errMsg = "Error attempting to launch web browser";
/**
* Opens the specified web page in the user's default browser
* @param url A web address (URL) of a web page (ex: "http://www.google.com/")
*/
public static void openURL(String url, javax.swing.JFrame parent) { // modified by Ignasi (added "parent")
try { //attempt to use Desktop library from JDK 1.6+
Class<?> d = Class.forName("java.awt.Desktop");
d.getDeclaredMethod("browse", new Class[] {java.net.URI.class}).invoke(
d.getDeclaredMethod("getDesktop").invoke(null),
new Object[] {java.net.URI.create(url)});
//above code mimicks: java.awt.Desktop.getDesktop().browse()
}
catch (Exception ignore) { //library not available or failed
String osName = System.getProperty("os.name");
try {
if (osName.startsWith("Mac OS")) {
Class.forName("com.apple.eio.FileManager").getDeclaredMethod(
"openURL", new Class[] {String.class}).invoke(null,new Object[] {url});
}
else if (osName.startsWith("Windows"))
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
else { //assume Unix or Linux
String browser = null;
for (String b : browsers)
if (browser == null && Runtime.getRuntime().exec(new String[]
{"which", b}).getInputStream().read() != -1)
Runtime.getRuntime().exec(new String[] {browser = b, url});
if (browser == null)
throw new Exception(java.util.Arrays.toString(browsers));
}
}
catch (Exception e) {
MsgExceptn.exception(errMsg + "\n" + e.getMessage()); // added by Ignasi
javax.swing.JOptionPane.showMessageDialog(parent, errMsg + "\n" + e.getMessage(), // modified by Ignasi (added "parent")
"Chemical Equilibrium Diagrams", javax.swing.JOptionPane.ERROR_MESSAGE); // added by Ignasi
}
}
}
}
//</editor-fold>
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButtonLicense;
private javax.swing.JLabel jLabelIniF;
private javax.swing.JLabel jLabelIniFU;
private javax.swing.JLabel jLabelIniFile;
private javax.swing.JLabel jLabelIniFileUser;
private javax.swing.JLabel jLabelJava;
private javax.swing.JLabel jLabelJavaIcon;
private javax.swing.JLabel jLabelJavaVers;
private javax.swing.JLabel jLabelLastUpdate;
private javax.swing.JLabel jLabelLib;
private javax.swing.JLabel jLabelLib2;
private javax.swing.JLabel jLabelName;
private javax.swing.JLabel jLabelNetBeans;
private javax.swing.JLabel jLabelNetBeans_www;
private javax.swing.JLabel jLabelNetbeansIcon;
private javax.swing.JLabel jLabelOS;
private javax.swing.JLabel jLabelPathA;
private javax.swing.JLabel jLabelPathApp;
private javax.swing.JLabel jLabelPathU;
private javax.swing.JLabel jLabelPathUser;
private javax.swing.JLabel jLabelUnicode;
private javax.swing.JLabel jLabelVers;
private javax.swing.JLabel jLabel_www;
private javax.swing.JLabel jLabel_wwwKTH;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanelNetBeans;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JSeparator jSeparator3;
// End of variables declaration//GEN-END:variables
}
| 34,740 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
AskSolids.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/DataBase/src/database/AskSolids.java | package database;
import lib.database.ProgramDataDB;
import lib.huvud.ProgramConf;
/** Ask the user about what redox equilibria to be included
* in the database searchs.
* <br>
* Copyright (C) 2018-2020 I.Puigdomenech
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class AskSolids extends javax.swing.JDialog {
private final ProgramConf pc;
private final ProgramDataDB pd;
private final FrameDBmain dbF;
private boolean ok = false;
private final boolean askingBeforeSearch;
private java.awt.Dimension windowSize = new java.awt.Dimension(227,122);
/** Creates new form AskRedox
* @param parent
* @param modal
* @param pc0 program configuration
* @param pd0 program data
* @param aBS true if "askingBeforeSearch";
* false if asking the user for program options */
public AskSolids(java.awt.Frame parent, boolean modal,
ProgramConf pc0,
ProgramDataDB pd0,
boolean aBS) {
super(parent, modal);
initComponents();
pc = pc0;
pd = pd0;
dbF = (FrameDBmain)parent;
askingBeforeSearch = aBS;
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
// ---- Close window on ESC key
javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE");
javax.swing.Action escAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
closeWindow();
}};
getRootPane().getActionMap().put("ESCAPE", escAction);
//--- Alt-Q quit
javax.swing.KeyStroke altQKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altQKeyStroke,"ALT_Q");
getRootPane().getActionMap().put("ALT_Q", escAction);
//--- Alt-X eXit
javax.swing.KeyStroke altXKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altXKeyStroke,"ALT_X");
javax.swing.Action altXAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jButtonOK.doClick();
}};
getRootPane().getActionMap().put("ALT_X", altXAction);
// ---- F1 for help
javax.swing.KeyStroke f1KeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_F1,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(f1KeyStroke,"F1");
javax.swing.Action f1Action = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jButtonHelp.doClick();
}};
getRootPane().getActionMap().put("F1", f1Action);
//---- forward/backwards arrow keys
java.util.Set<java.awt.AWTKeyStroke> keys = getFocusTraversalKeys(java.awt.KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS);
java.util.Set<java.awt.AWTKeyStroke> newKeys = new java.util.HashSet<java.awt.AWTKeyStroke>(keys);
newKeys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_RIGHT, 0));
newKeys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_DOWN, 0));
setFocusTraversalKeys(java.awt.KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,newKeys);
keys = getFocusTraversalKeys(java.awt.KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS);
newKeys = new java.util.HashSet<java.awt.AWTKeyStroke>(keys);
newKeys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_LEFT, 0));
newKeys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_UP, 0));
setFocusTraversalKeys(java.awt.KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,newKeys);
//---- Title, etc
this.setTitle(pc.progName+" - Solid options");
//---- Centre window on parent/screen
int left,top;
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
if(parent != null) {
left = Math.max(0,(parent.getX() + (parent.getWidth()/2) - this.getWidth()/2));
top = Math.max(0,(parent.getY()+(parent.getHeight()/2)-this.getHeight()/2));
} else {
left = Math.max(0,(screenSize.width-this.getWidth())/2);
top = Math.max(0,(screenSize.height-this.getHeight())/2);
}
this.setLocation(Math.min(screenSize.width-this.getWidth()-20,left),
Math.min(screenSize.height-this.getHeight()-20, top));
// 0=include all solids; 1=exclude (cr); 2=exclude (c); 3=exclude (cr)&(c)
if(pd.allSolids == 1) {jRadioButton1.setSelected(true);}
else if(pd.allSolids == 2) {jRadioButton2.setSelected(true);}
else if(pd.allSolids == 3) {jRadioButton3.setSelected(true);}
else {jRadioButtonAll.setSelected(true);}
if(pd.allSolidsAsk) {
jRadioButtonAsk.setSelected(true);
jRadioButtonAll.setEnabled(false);
jRadioButton1.setEnabled(false);
jRadioButton2.setEnabled(false);
jRadioButton3.setEnabled(false);
} else {
jRadioButtonDoNotAsk.setSelected(true);
jRadioButtonAll.setEnabled(true);
jRadioButton1.setEnabled(true);
jRadioButton2.setEnabled(true);
jRadioButton3.setEnabled(true);
}
if(askingBeforeSearch) {
jRadioButtonAll.setEnabled(true);
jRadioButton1.setEnabled(true);
jRadioButton2.setEnabled(true);
jRadioButton3.setEnabled(true);
jRadioButtonAsk.setVisible(false);
jRadioButtonDoNotAsk.setVisible(false);
} //if askingBeforeSearch
} //constructor
public void start() {
this.setVisible(true);
windowSize = AskSolids.this.getSize();
jButtonCancel.requestFocusInWindow();
dbF.setCursorDef();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
buttonGroup2 = new javax.swing.ButtonGroup();
jLabelTop = new javax.swing.JLabel();
jButtonHelp = new javax.swing.JButton();
jButtonCancel = new javax.swing.JButton();
jButtonOK = new javax.swing.JButton();
jPanel4 = new javax.swing.JPanel();
jRadioButtonAsk = new javax.swing.JRadioButton();
jRadioButtonDoNotAsk = new javax.swing.JRadioButton();
jPanel3 = new javax.swing.JPanel();
jRadioButtonAll = new javax.swing.JRadioButton();
jRadioButton3 = new javax.swing.JRadioButton();
jRadioButton1 = new javax.swing.JRadioButton();
jRadioButton2 = new javax.swing.JRadioButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jLabelTop.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabelTop.setText("<html>If solids are found when searching the database:<br>include all types of solids?</html>");
jButtonHelp.setMnemonic('h');
jButtonHelp.setText(" Help ");
jButtonHelp.setToolTipText("Alt-H or F1");
jButtonHelp.setAlignmentX(0.5F);
jButtonHelp.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonHelp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonHelpActionPerformed(evt);
}
});
jButtonCancel.setMnemonic('c');
jButtonCancel.setText(" Cancel ");
jButtonCancel.setToolTipText("Alt-C or Esc");
jButtonCancel.setAlignmentX(0.5F);
jButtonCancel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonCancelActionPerformed(evt);
}
});
jButtonOK.setMnemonic('o');
jButtonOK.setText(" OK ");
jButtonOK.setToolTipText("Alt-O");
jButtonOK.setAlignmentX(0.5F);
jButtonOK.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonOK.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonOKActionPerformed(evt);
}
});
buttonGroup1.add(jRadioButtonAsk);
jRadioButtonAsk.setMnemonic('A');
jRadioButtonAsk.setText("Ask before every database search");
jRadioButtonAsk.setToolTipText("Alt-A");
jRadioButtonAsk.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
jRadioButtonAsk.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonAskActionPerformed(evt);
}
});
buttonGroup1.add(jRadioButtonDoNotAsk);
jRadioButtonDoNotAsk.setMnemonic('d');
jRadioButtonDoNotAsk.setText("Do not ask. Include the following type of solids:");
jRadioButtonDoNotAsk.setToolTipText("Alt-D");
jRadioButtonDoNotAsk.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
jRadioButtonDoNotAsk.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonDoNotAskActionPerformed(evt);
}
});
buttonGroup2.add(jRadioButtonAll);
jRadioButtonAll.setMnemonic('0');
jRadioButtonAll.setText("All solids included");
jRadioButtonAll.setToolTipText("Alt-0");
buttonGroup2.add(jRadioButton3);
jRadioButton3.setMnemonic('3');
jRadioButton3.setText("Exclude solids endng with either \"(cr)\" or \"(c)\"");
jRadioButton3.setToolTipText("Alt-3");
buttonGroup2.add(jRadioButton1);
jRadioButton1.setMnemonic('1');
jRadioButton1.setText("Exclude solids endng with \"(cr)\"");
jRadioButton1.setToolTipText("Alt-1");
buttonGroup2.add(jRadioButton2);
jRadioButton2.setMnemonic('2');
jRadioButton2.setText("Exclude solids endng with \"(c)\"");
jRadioButton2.setToolTipText("Alt-2");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jRadioButtonAll)
.addComponent(jRadioButton3)
.addComponent(jRadioButton1)
.addComponent(jRadioButton2))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jRadioButtonAll)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jRadioButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jRadioButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jRadioButton3)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jRadioButtonAsk)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jRadioButtonDoNotAsk))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(jRadioButtonAsk)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jRadioButtonDoNotAsk)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelTop, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButtonCancel)
.addComponent(jButtonHelp)
.addComponent(jButtonOK, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabelTop, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(58, 58, 58)
.addComponent(jButtonHelp)
.addGap(18, 18, 18)
.addComponent(jButtonCancel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButtonOK)
.addContainerGap(36, Short.MAX_VALUE))
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
if(windowSize != null) {
int w = windowSize.width;
int h = windowSize.height;
if(this.getHeight()<h){this.setSize(this.getWidth(), h);}
if(this.getWidth()<w){this.setSize(w,this.getHeight());}
}
}//GEN-LAST:event_formComponentResized
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
closeWindow();
}//GEN-LAST:event_formWindowClosing
private void jButtonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOKActionPerformed
if(jRadioButton1.isSelected()) {pd.allSolids = 1;}
else if(jRadioButton2.isSelected()) {pd.allSolids = 2;}
else if(jRadioButton3.isSelected()) {pd.allSolids = 3;}
else {pd.allSolids = 0;}
pd.allSolidsAsk = jRadioButtonAsk.isSelected();
ok = true;
closeWindow();
}//GEN-LAST:event_jButtonOKActionPerformed
private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelActionPerformed
closeWindow();
}//GEN-LAST:event_jButtonCancelActionPerformed
private void jButtonHelpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonHelpActionPerformed
setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
Thread hlp = new Thread() {@Override public void run(){
String[] a = {"DB_Solid_solub_htm"};
lib.huvud.RunProgr.runProgramInProcess(null,ProgramConf.HELP_JAR,a,false,pc.dbg,pc.pathAPP);
try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec
catch (InterruptedException e) {}
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
}};//new Thread
hlp.start();
}//GEN-LAST:event_jButtonHelpActionPerformed
private void jRadioButtonAskActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonAskActionPerformed
jRadioButtonAll.setEnabled(false);
jRadioButton1.setEnabled(false);
jRadioButton2.setEnabled(false);
jRadioButton3.setEnabled(false);
}//GEN-LAST:event_jRadioButtonAskActionPerformed
private void jRadioButtonDoNotAskActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonDoNotAskActionPerformed
jRadioButtonAll.setEnabled(true);
jRadioButton1.setEnabled(true);
jRadioButton2.setEnabled(true);
jRadioButton3.setEnabled(true);
}//GEN-LAST:event_jRadioButtonDoNotAskActionPerformed
private void closeWindow() {
dbF.exitCancel = !ok;
this.dispose();
dbF.bringToFront();
} // closeWindow()
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.ButtonGroup buttonGroup2;
private javax.swing.JButton jButtonCancel;
private javax.swing.JButton jButtonHelp;
private javax.swing.JButton jButtonOK;
private javax.swing.JLabel jLabelTop;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
private javax.swing.JRadioButton jRadioButton3;
private javax.swing.JRadioButton jRadioButtonAll;
private javax.swing.JRadioButton jRadioButtonAsk;
private javax.swing.JRadioButton jRadioButtonDoNotAsk;
// End of variables declaration//GEN-END:variables
}
| 21,067 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
SetTempPressDialog.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/DataBase/src/database/SetTempPressDialog.java | package database;
import lib.common.Util;
import lib.database.ProgramDataDB;
import lib.huvud.ProgramConf;
/** Temperature dialog.
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class SetTempPressDialog extends javax.swing.JDialog {
// Note: for java 1.6 jComboBox must not have type,
// for java 1.7 jComboBox must be <String>
private boolean loading = true;
private ProgramConf pc;
private final ProgramDataDB pd;
private final FrameDBmain dbF;
private final java.awt.Dimension windowSize; // = new java.awt.Dimension(185,185);
private double temperature_C;
private double pressure_bar;
private final String[] pSat = new String[] {"pSat","250","500","750","1000","2000","3000","4000","5000"};
private final String[] noPsat = new String[] {"250","500","750","1000","2000","3000","4000","5000"};
private final String[] tAll = new String[] {"0","10","20","25","30","40","50","75","100","125","150","175","200","225","250","275","300","325","350","400","450","500","550","600"};
private final String[] t100 = new String[] {"0","5","10","15","20","25","30","35","40","50","60","70","75","80","90","100"};
private final double[] tLimit = new double[]{373.946,400,410,430,440,460,470,490,510,520,540,550,570,580,600};
private final double[] pLimit = new double[]{220.64, 300,350,400,450,500,550,600,650,700,750,800,850,900,950};
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
//<editor-fold defaultstate="collapsed" desc="Constructor">
/** Creates new form SetTempDialog
* @param parent
* @param modal
* @param pc0
* @param pd0 */
public SetTempPressDialog(java.awt.Frame parent, boolean modal,
ProgramConf pc0,
ProgramDataDB pd0
) {
super(parent, modal);
initComponents();
pc = pc0;
pd = pd0;
dbF = (FrameDBmain)parent;
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
//--- Close window on ESC key
javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE");
javax.swing.Action escAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
closeWindow();
}};
getRootPane().getActionMap().put("ESCAPE", escAction);
//--- Alt-Q quit
javax.swing.KeyStroke altQKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altQKeyStroke,"ALT_Q");
javax.swing.Action altQAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
closeWindow();
}};
getRootPane().getActionMap().put("ALT_Q", altQAction);
//--- Alt-X eXit
javax.swing.KeyStroke altXKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altXKeyStroke,"ALT_X");
javax.swing.Action altXAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jButtonOK.doClick();
}};
getRootPane().getActionMap().put("ALT_X", altXAction);
//--- F1 for help
javax.swing.KeyStroke f1KeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_F1,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(f1KeyStroke,"F1");
javax.swing.Action f1Action = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
SetTempPressDialog.this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
Thread hlp = new Thread() {@Override public void run(){
String[] a = {"DB_0_Main_htm"};
lib.huvud.RunProgr.runProgramInProcess(null,ProgramConf.HELP_JAR,a,false,pc.dbg,pc.pathAPP);
try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec
catch (InterruptedException e) {}
SetTempPressDialog.this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
} };//new Thread
hlp.start();
}};
getRootPane().getActionMap().put("F1", f1Action);
//--- Alt-H ghelp
javax.swing.KeyStroke altHKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_H, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altHKeyStroke,"ALT_H");
getRootPane().getActionMap().put("ALT_H", f1Action);
//---- forward/backwards arrow keys
java.util.Set<java.awt.AWTKeyStroke> keys = getFocusTraversalKeys(java.awt.KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS);
java.util.Set<java.awt.AWTKeyStroke> newKeys = new java.util.HashSet<java.awt.AWTKeyStroke>(keys);
newKeys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_RIGHT, 0));
//newKeys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_DOWN, 0));
setFocusTraversalKeys(java.awt.KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,newKeys);
keys = getFocusTraversalKeys(java.awt.KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS);
newKeys = new java.util.HashSet<java.awt.AWTKeyStroke>(keys);
newKeys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_LEFT, 0));
//newKeys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_UP, 0));
setFocusTraversalKeys(java.awt.KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,newKeys);
//---- Title, etc
this.setTitle(" Temperature:");
//---- Centre window on parent/screen
int left,top;
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
if(parent != null) {
left = Math.max(0,(parent.getX() + (parent.getWidth()/2) - this.getWidth()/2));
top = Math.max(0,(parent.getY()+(parent.getHeight()/2)-this.getHeight()/2));
} else {
left = Math.max(0,(screenSize.width-this.getWidth())/2);
top = Math.max(0,(screenSize.height-this.getHeight())/2);
}
this.setLocation(Math.min(screenSize.width-this.getWidth()-20,left),
Math.min(screenSize.height-this.getHeight()-20, top));
windowSize = new java.awt.Dimension(this.getWidth(),this.getHeight());
temperature_C = pd.temperature_C;
pressure_bar = pd.pressure_bar;
if(pd.temperatureAllowHigher) { // above 100 C
//jComboBoxT.setModel(new javax.swing.DefaultComboBoxModel( // java 1.6
jComboBoxT.setModel(new javax.swing.DefaultComboBoxModel<String>(tAll));
jComboBoxP.setEnabled(true);
} else { // only 0 to 100 C
// jComboBoxT.setModel(new javax.swing.DefaultComboBoxModel( // java 1.6
jComboBoxT.setModel(new javax.swing.DefaultComboBoxModel<String>(t100));
jComboBoxP.setEnabled(false);
}
if(temperature_C > 350) {
jComboBoxP.setModel(new javax.swing.DefaultComboBoxModel<String>(noPsat));
} else {
jComboBoxP.setModel(new javax.swing.DefaultComboBoxModel<String>(pSat));
}
set_temp_inComboBox();
set_press_inComboBox();
if(pc.dbg) {
System.out.println("---- SetTempPressDialog"+nl+
" temperature = "+temperature_C+nl+
" pressure = "+pressure_bar);
}
pack();
loading = false;
setVisible(true);
}
//</editor-fold>
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jButtonOK = new javax.swing.JButton();
jButtonCancel = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
jComboBoxT = new javax.swing.JComboBox<>();
jLabelDegrees = new javax.swing.JLabel();
jLabelT = new javax.swing.JLabel();
jComboBoxP = new javax.swing.JComboBox<>();
jLabelP = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jButtonOK.setMnemonic('O');
jButtonOK.setText(" OK ");
jButtonOK.setAlignmentX(0.5F);
jButtonOK.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonOK.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonOKActionPerformed(evt);
}
});
jButtonCancel.setMnemonic('C');
jButtonCancel.setText(" Cancel ");
jButtonCancel.setAlignmentX(0.5F);
jButtonCancel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonCancelActionPerformed(evt);
}
});
jComboBoxT.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "0", "5", "10", "15", "20", "25", "30", "35", "40", "50", "60", "70", "75", "80", "90", "100" }));
jComboBoxT.setSelectedIndex(5);
jComboBoxT.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBoxTActionPerformed(evt);
}
});
jLabelDegrees.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabelDegrees.setLabelFor(jComboBoxT);
jLabelDegrees.setText("°C");
jLabelDegrees.setToolTipText("double-click to set T=25'C");
jLabelDegrees.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabelDegreesMouseClicked(evt);
}
});
jLabelT.setIcon(new javax.swing.ImageIcon(getClass().getResource("/database/images/Termometer.gif"))); // NOI18N
jComboBoxP.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Psat", "500", "1000", "2000", "3000", "4000", "5000" }));
jComboBoxP.setToolTipText("Psat = vapor-liquid equilibrium (saturation) pressure");
jComboBoxP.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBoxPActionPerformed(evt);
}
});
jLabelP.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabelP.setText("bar");
jLabelP.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabelPMouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabelT)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBoxT, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBoxP, 0, 65, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelDegrees)
.addComponent(jLabelP))
.addContainerGap(40, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jComboBoxT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelDegrees))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jComboBoxP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelP))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabelT)
.addGap(0, 0, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(36, 36, 36)
.addComponent(jButtonOK, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButtonCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonOK)
.addComponent(jButtonCancel))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
//<editor-fold defaultstate="collapsed" desc="Events">
private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelActionPerformed
closeWindow();
}//GEN-LAST:event_jButtonCancelActionPerformed
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
closeWindow();
}//GEN-LAST:event_formWindowClosing
private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
if(windowSize != null) {
int w = windowSize.width;
int h = windowSize.height;
if(this.getHeight()<h){this.setSize(this.getWidth(), h);}
if(this.getWidth()<w){this.setSize(w,this.getHeight());}
}
}//GEN-LAST:event_formComponentResized
private void jComboBoxTActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxTActionPerformed
if(loading) {return;}
temperature_C = Double.parseDouble(jComboBoxT.getSelectedItem().toString());
if(temperature_C > 372.946) { // critical point of H2O
jComboBoxP.setModel(new javax.swing.DefaultComboBoxModel<String>(noPsat));
for(int i = 0; i < (tLimit.length-1); i++) {
// tLimit = {373.946,400,410,430,440,460,470,490,510,520,540,550,570,580,600};
// pLimit = {220.64, 300,350,400,450,500,550,600,650,700,750,800,850,900,950};
if(temperature_C > tLimit[i] && temperature_C <= tLimit[i+1]
&& pressure_bar < pLimit[i+1]) {
pressure_bar = pLimit[i+1];
}
}
} else { // temperature <= 373
jComboBoxP.setModel(new javax.swing.DefaultComboBoxModel<String>(pSat));
if(pressure_bar < 221) { // critical point of H2O
pressure_bar = Math.max(1.,lib.kemi.H2O.IAPWSF95.pSat(temperature_C));
}
}
set_press_inComboBox();
}//GEN-LAST:event_jComboBoxTActionPerformed
private void jButtonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOKActionPerformed
int answer;
if(temperature_C > 372.946) { // critical point of H2O
jComboBoxP.setModel(new javax.swing.DefaultComboBoxModel<String>(noPsat));
for(int i = 0; i < (tLimit.length-1); i++) {
// tLimit = {373.946,400,410,430,440,460,470,490,510,520,540,550,570,580,600};
// pLimit = {220.64, 300,350,400,450,500,550,600,650,700,750,800,850,900,950};
if(temperature_C > tLimit[i] && temperature_C <= tLimit[i+1]
&& pressure_bar < pLimit[i+1]) {
System.out.println("ButtonOK: Pbar = "+pressure_bar+", tC = "+temperature_C);
answer = javax.swing.JOptionPane.showConfirmDialog(this,
"<html><b>Note:</b> at "+Util.formatNumAsInt(temperature_C)+"°C the pressure<br>"
+"must be >= "+Util.formatNumAsInt(pLimit[i+1])+" bar.<br><br>"
+"Change the pressure to "+Util.formatNumAsInt(pLimit[i+1])+" bar?</html>",
pc.progName, javax.swing.JOptionPane.OK_CANCEL_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE);
if(answer != javax.swing.JOptionPane.OK_OPTION) {
System.out.println("Answer: Cancel");
return;
}
pressure_bar = pLimit[i+1];
}
}
}
pd.temperature_C = temperature_C;
pd.pressure_bar = pressure_bar;
closeWindow();
}//GEN-LAST:event_jButtonOKActionPerformed
private void jLabelDegreesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelDegreesMouseClicked
if(evt.getClickCount() >1) { // double-click
temperature_C = 25;
for(int i = 0; i < jComboBoxT.getItemCount();i++) {
if(jComboBoxT.getItemAt(i).equals("25")) {jComboBoxT.setSelectedIndex(i); break;}
}
}
}//GEN-LAST:event_jLabelDegreesMouseClicked
private void jComboBoxPActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxPActionPerformed
if(loading) {return;}
double pOld = pressure_bar;
String s = jComboBoxP.getSelectedItem().toString();
if(s.equalsIgnoreCase("psat")) {
temperature_C = Math.min(350, temperature_C);
pressure_bar = Math.max(1.,lib.kemi.H2O.IAPWSF95.pSat(temperature_C));
set_temp_inComboBox();
}
else {pressure_bar = Double.parseDouble(s);}
if(pressure_bar != 250 && pOld == 250) {
jComboBoxT.setModel(new javax.swing.DefaultComboBoxModel<String>(tAll));
set_temp_inComboBox();
}
}//GEN-LAST:event_jComboBoxPActionPerformed
private void jLabelPMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelPMouseClicked
if(temperature_C > 350) {return;}
if(evt.getClickCount() >1) { // double-click
jComboBoxP.setSelectedIndex(0);
pressure_bar = Math.max(1.,lib.kemi.H2O.IAPWSF95.pSat(temperature_C));
}
}//GEN-LAST:event_jLabelPMouseClicked
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Methods">
private void closeWindow() {
this.dispose();
dbF.bringToFront();
} // closeWindow()
//<editor-fold defaultstate="collapsed" desc="set_temp_inComboBox">
/** find the closest item in the temperature combo box and select it */
private void set_temp_inComboBox() {
double w0, w1;
int listItem =0;
int listCount = jComboBoxT.getItemCount();
for(int i =1; i < listCount; i++) {
w0 = Double.parseDouble(jComboBoxT.getItemAt(i-1).toString());
w1 = Double.parseDouble(jComboBoxT.getItemAt(i).toString());
if(temperature_C <= w0 && i==1) {listItem = 0; break;}
if(temperature_C >= w1 && i==(listCount-1)) {listItem = (listCount-1); break;}
if(temperature_C > w0 && temperature_C <=w1) {
if(Math.abs(temperature_C-w0) < Math.abs(temperature_C-w1)) {
listItem = i-1;
} else {
listItem = i;
}
break;
}
} //for i
jComboBoxT.setSelectedIndex(listItem);
} //set_tol_inComboBox()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="set_press_inComboBox">
/** find the closest item in the pressure combo box and select it */
private void set_press_inComboBox() {
int min = 1;
if(jComboBoxP.getItemAt(0).toString().equalsIgnoreCase("pSat")) {
if(pressure_bar < lib.kemi.H2O.IAPWSF95.CRITICAL_pBar) {jComboBoxP.setSelectedIndex(0); return;}
min = 2;
}
double w0=-1, w1=-1;
int listItem =0;
int listCount = jComboBoxP.getItemCount();
for(int i = min; i < listCount; i++) {
w0 = Double.parseDouble(jComboBoxP.getItemAt(i-1).toString());
w1 = Double.parseDouble(jComboBoxP.getItemAt(i).toString());
if(pressure_bar <= w0 && i == min) {listItem = min-1; break;}
if(pressure_bar >= w1 && i == (listCount-1)) {listItem = (listCount-1); break;}
if(pressure_bar > w0 && pressure_bar <=w1) {
listItem = i;
break;
}
} //for i
jComboBoxP.setSelectedIndex(listItem);
} //set_tol_inComboBox()
//</editor-fold>
//</editor-fold>
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButtonCancel;
private javax.swing.JButton jButtonOK;
private javax.swing.JComboBox<String> jComboBoxP;
private javax.swing.JComboBox<String> jComboBoxT;
private javax.swing.JLabel jLabelDegrees;
private javax.swing.JLabel jLabelP;
private javax.swing.JLabel jLabelT;
private javax.swing.JPanel jPanel1;
// End of variables declaration//GEN-END:variables
}
| 24,532 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
FrameDBmain.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/DataBase/src/database/FrameDBmain.java | package database;
import lib.common.MsgExceptn;
import lib.common.Util;
import lib.database.*;
import lib.huvud.ProgramConf;
import lib.huvud.RedirectedFrame;
import lib.huvud.SortedProperties;
import lib.huvud.Splash;
/** Main window frame of the Database program.
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
* @author Ignasi Puigdomenech */
public class FrameDBmain extends javax.swing.JFrame {
static final String VERS = "2020-June-10";
/** all instances will use the same redirected frame */
static RedirectedFrame msgFrame = null;
/** Because the program checks for other instances and exits if there is
* another instance, "dbf" is a reference to the only instance of
* this class */
private static FrameDBmain dbf = null;
private final ProgramDataDB pd = new ProgramDataDB();
private final ProgramConf pc;
private HelpAboutDB helpAboutFrame = null;
/** <code>true</code> if the operating system is "Windows",
* <code>false</code> otherwise */
static boolean windows = false;
private static java.awt.Dimension msgFrameSize = new java.awt.Dimension(500,400);
private static java.awt.Point locationMsgFrame = new java.awt.Point(80,28);
private static final java.awt.Point locationFrame = new java.awt.Point(-1000,-1000);
private java.awt.Dimension windowSize;
/** true if the user has done "some work": a dialog will ask to confirm quit without saving */
private boolean doneSomeWork = false;
/** do we need to ask the user to confirm quitting? */
private boolean queryToQuit;
/** is the search going on? */
private boolean searchingComplexes = false;
static java.io.File fileIni;
static java.io.File fileIniUser;
private static final String FileINI_NAME = ".DataBase.ini";
private boolean disclaimerSkip = false;
private Disclaimer disclaimerFrame;
/** This parameter is read from the ini-file: if <code>true</code> then the
* advanced menu with "AddShowReferences" and "DatabaseMaintenace" will be
* shown (for any operating system); in WIndows the menu will be
* invisible if <code>false</code>; in other operating systems the menu
* might become visible anyway. */
private boolean advancedMenu = false;
/** <tt>laf</tt> = LookAndFeel: the look-and-feel to be used (read from the ini-file).
* If <tt>laf</tt> = 2 then the <i>C<rossPlatform</i> look-and-feel will be used;
* else if <tt>laf</tt> = 1 the <i>System</i> look-and-feel will be used.
* Else (<tt>laf</tt> = 0, default) then the look-and-feel will be <i>System</i>
* for Windows and <i>CrossPlatform</i> on Linux and Mac OS.
* Default at program start = 0 **/
private int laf = 0;
/** used to set any selected solid components at the end of jListSelectedComps */
int solidSelectedComps;
private static final String DEF_DataBase = "Reactions.db";
private boolean noDataBasesFound = false;
private final javax.swing.JButton[] buttons = new javax.swing.JButton[LibDB.ELEMENTS];
private final ButtonActionListener buttonAListener = new ButtonActionListener();
private final ButtonMouseListener buttonMListener = new ButtonMouseListener();
private final ButtonFocusListener buttonFListener = new ButtonFocusListener();
private final ButtonKeyListener buttonKListener = new ButtonKeyListener();
private int lastButtonInFocus = -1;
private int lastReactionInFocus = -1;
/** default border for elements with data in the database(s) */
private final javax.swing.border.Border buttonBorder = javax.swing.BorderFactory.createRaisedBevelBorder();
/** border for elements without data in the database(s) */
private final javax.swing.border.Border buttonBorderN = javax.swing.BorderFactory.createEmptyBorder();
private final javax.swing.border.Border bevelBorder = javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED);
private final javax.swing.border.Border lineBorder = javax.swing.BorderFactory.createLineBorder(java.awt.Color.black,1);
private final javax.swing.border.Border buttonBorderSelected = javax.swing.BorderFactory.createCompoundBorder(lineBorder, bevelBorder);
//private javax.swing.border.Border buttonBorderSelected = javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED,java.awt.Color.gray,java.awt.Color.white);
//private javax.swing.border.Border buttonBorderSelected = javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED);
//private javax.swing.border.Border buttonBorderSelected = javax.swing.BorderFactory.createLineBorder(java.awt.Color.black,2);
//private javax.swing.border.Border buttonBorderSelected = javax.swing.BorderFactory.createLineBorder(java.awt.Color.black,1);
/** background for elements with data in the database(s) */
private final java.awt.Color buttonBackgroundB = new java.awt.Color(204, 204, 204);
/** background for elements without data in the database(s) */
private final java.awt.Color buttonBackgroundN = new java.awt.Color(231, 231, 231);
private final java.awt.Font buttonFont = new java.awt.Font("Tahoma",java.awt.Font.BOLD,11);
private final StringBuilder originalJLabelLeft = new StringBuilder(" ");
/** the names of the components (if any) corresponding to the formulas
* listed in jListAvailableComps, for example "cyanide" for component "CN-" */
private final java.util.ArrayList<String> availableComponentsNames = new java.util.ArrayList<String>();
/** the names of the components listed in jListComponents */
private final java.util.ArrayList<String> componentsNames = new java.util.ArrayList<String>();
/** java 1.6
private final javax.swing.DefaultListModel modelAvailableComps = new javax.swing.DefaultListModel();
javax.swing.DefaultListModel modelSelectedComps = new javax.swing.DefaultListModel();
javax.swing.DefaultListModel modelComplexes = new javax.swing.DefaultListModel();
*/
private final javax.swing.DefaultListModel<String> modelAvailableComps = new javax.swing.DefaultListModel<>();
javax.swing.DefaultListModel<String> modelSelectedComps = new javax.swing.DefaultListModel<>();
javax.swing.DefaultListModel<String> modelComplexes = new javax.swing.DefaultListModel<>();
/** An object that performs searches reactions in the databases */
private DBSearch srch;
/** when ending the program (through window "ExitDialog"):
* does the user want to send the data file to "Diagram"? */
boolean send2Diagram;
/** Changed by dialogs to indicate if the user closed the dialog without
* clicking the "ok" button. For exameple, when ending the program (through
* dialog "ExitDialog"): does the user want to cancel and continue instead? */
boolean exitCancel;
/** name of output data file; either selected by the user on exit
* (through window "ExitDialog") or given as command-line argument */
String outputDataFile = null;
private final int panelLowerLabelsW0;
private final int labelRightX0;
/** indicates if a mouse click on the reaction list should show the popup menu */
private boolean isPopup = false;
/** if it is not null, it means addData is showing and "this" is not showing */
private FrameAddData addData = null;
/** if it is not null, it means singleComp is showing and "this" is not showing */
private FrameSingleComponent singleComp = null;
/** if it is not null, it means dbND is showing */
private DBnamesDialog dbND = null;
private static String[] commandArgs;
/** New-line character(s) to substitute "\n".<br>
* It is needed when a String is created first, including new-lines,
* and the String is then printed. For example
* <pre>String t = "1st line\n2nd line";
*System.out.println(t);</pre>will add a carriage return character
* between the two lines, which on Windows system might be
* unsatisfactory. Use instead:
* <pre>String t = "1st line" + nl + "2nd line";
*System.out.println(t);</pre> */
private static final String nl = System.getProperty("line.separator");
private static final String SLASH = java.io.File.separator;
static final String LINE = "- - - - - - - - - - - - - - - - - - - - - - - - - - -";
//<editor-fold defaultstate="collapsed" desc="Constructor">
/** Creates new form FrameDBmain
* @param pc0
* @param msgFrame0 */
public FrameDBmain(ProgramConf pc0, RedirectedFrame msgFrame0) {
initComponents();
this.pc = pc0;
pd.msgFrame = msgFrame0;
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
labelRightX0 = jLabelRight.getX();
panelLowerLabelsW0 = jPanelLowerLabels.getWidth();
solidSelectedComps = 0;
//---- initial location: centered on screen
locationFrame.x = Math.max(0, (LibDB.screenSize.width - this.getWidth() ) / 2);
locationFrame.y = Math.max(0, (LibDB.screenSize.height - this.getHeight() ) / 2);
setLocation(locationFrame);
} // constructor
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="setTitle()">
private void setTitle() {
String title = "Hydrochemical logK Database";
String t;
if(pd.temperature_C <=22.5 || pd.temperature_C >=27.5) {
t = "Temperature = " + String.format("%.0f 'C",pd.temperature_C);
//title = title + " - " + t;
jLabelTemperature.setText(t);
} else {jLabelTemperature.setText(" ");}
if(pd.pressure_bar >1.1) {
if(pd.pressure_bar < lib.kemi.H2O.IAPWSF95.CRITICAL_pBar) {
t = "Pressure = " + String.format(java.util.Locale.ENGLISH,"%.2f bar",pd.pressure_bar);
} else {
t = "Pressure = " + String.format("%.0f bar",pd.pressure_bar);
}
jLabelPressure.setText(t);
} else {jLabelPressure.setText(" ");}
this.setTitle(title);
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="prepareButtons()">
private void prepareButtons() {
if(pc.dbg) {System.out.println(pc.progName+" - prepareButtons()");}
setCursorWait();
//buttonBorder = jButton0.getBorder(); // get the default button border
//---- an array of JButton is made with the chemical element buttons in the frame;
// to each element button it is assigned an action name ("0", "1", "2", ...),
// corresponding to the button's index in the array.
// When the user clicks on an element, the button's action name
// is used as the array index
makeButtonsArray();
// add the mouse and action listeners
for(int i=0; i < buttons.length; i++) {
buttons[i].setActionCommand(String.valueOf(i));
buttons[i].addMouseListener(buttonMListener);
buttons[i].addActionListener(buttonAListener);
buttons[i].addFocusListener(buttonFListener);
buttons[i].addKeyListener(buttonKListener);
buttons[i].setMargin(new java.awt.Insets(2, 0, 2, 0));
buttons[i].setPreferredSize(new java.awt.Dimension(27, 27));
buttons[i].setBackground(buttonBackgroundB);
buttons[i].setBorder(buttonBorder);
}
setCursorDef();
} // prepareButtons()
//<editor-fold defaultstate="collapsed" desc="makeButtonsArray()">
private void makeButtonsArray(){
buttons[ 0]= jButton0; buttons[ 1]= jButton1; buttons[ 2]= jButton2; buttons[ 3]= jButton3;
buttons[ 4]= jButton4; buttons[ 5]= jButton5; buttons[ 6]= jButton6; buttons[ 7]= jButton7;
buttons[ 8]= jButton8; buttons[ 9]= jButton9; buttons[10]=jButton10; buttons[11]=jButton11;
buttons[12]=jButton12; buttons[13]=jButton13; buttons[14]=jButton14; buttons[15]=jButton15;
buttons[16]=jButton16; buttons[17]=jButton17; buttons[18]=jButton18; buttons[19]=jButton19;
buttons[20]=jButton20; buttons[21]=jButton21; buttons[22]=jButton22; buttons[23]=jButton23;
buttons[24]=jButton24; buttons[25]=jButton25; buttons[26]=jButton26; buttons[27]=jButton27;
buttons[28]=jButton28; buttons[29]=jButton29; buttons[30]=jButton30; buttons[31]=jButton31;
buttons[32]=jButton32; buttons[33]=jButton33; buttons[34]=jButton34; buttons[35]=jButton35;
buttons[36]=jButton36; buttons[37]=jButton37; buttons[38]=jButton38; buttons[39]=jButton39;
buttons[40]=jButton40; buttons[41]=jButton41; buttons[42]=jButton42; buttons[43]=jButton43;
buttons[44]=jButton44; buttons[45]=jButton45; buttons[46]=jButton46; buttons[47]=jButton47;
buttons[48]=jButton48; buttons[49]=jButton49; buttons[50]=jButton50; buttons[51]=jButton51;
buttons[52]=jButton52; buttons[53]=jButton53; buttons[54]=jButton54; buttons[55]=jButton55;
buttons[56]=jButton56; buttons[57]=jButton57; buttons[58]=jButton58; buttons[59]=jButton59;
buttons[60]=jButton60; buttons[61]=jButton61; buttons[62]=jButton62; buttons[63]=jButton63;
buttons[64]=jButton64; buttons[65]=jButton65; buttons[66]=jButton66; buttons[67]=jButton67;
buttons[68]=jButton68; buttons[69]=jButton69; buttons[70]=jButton70; buttons[71]=jButton71;
buttons[72]=jButton72; buttons[73]=jButton73; buttons[74]=jButton74; buttons[75]=jButton75;
buttons[76]=jButton76; buttons[77]=jButton77; buttons[78]=jButton78; buttons[79]=jButton79;
buttons[80]=jButton80; buttons[81]=jButton81; buttons[82]=jButton82; buttons[83]=jButton83;
buttons[84]=jButton84; buttons[85]=jButton85; buttons[86]=jButton86; buttons[87]=jButton87;
buttons[88]=jButton88; buttons[89]=jButton89; buttons[90]=jButton90; buttons[91]=jButton91;
buttons[92]=jButton92; buttons[93]=jButton93; buttons[94]=jButton94; buttons[95]=jButton95;
buttons[96]=jButton96; buttons[97]=jButton97; buttons[98]=jButton98; buttons[99]=jButton99;
buttons[100]=jButton100; buttons[101]=jButton101; buttons[102]=jButton102; buttons[103]=jButton103;
} //makeButtonsArray
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="buttonsArray Listeners">
private class ButtonActionListener implements java.awt.event.ActionListener {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(e.getSource() instanceof javax.swing.JButton) {
int i = Integer.parseInt(e.getActionCommand());
lastButtonInFocus = i;
getAvailableComponents(i);
if(LibDB.elementName[i] != null) {
jLabelLeft.setText("Element: "+LibDB.elementName[i]);
}
originalJLabelLeft.replace(0, originalJLabelLeft.length(), jLabelLeft.getText());
buttons[i].requestFocusInWindow();
if(i==0) {availableComponentClick(0);}
}
} //actionPerformed
} //class ButtonActionListener
private class ButtonFocusListener implements java.awt.event.FocusListener {
@Override public void focusGained(java.awt.event.FocusEvent evt) {
javax.swing.JButton b = (javax.swing.JButton)evt.getSource();
int i = Integer.parseInt(b.getActionCommand());
lastButtonInFocus = i;
if(LibDB.elementName[i] != null) {
jLabelLeft.setText("Element: "+LibDB.elementName[i]);
originalJLabelLeft.replace(0, originalJLabelLeft.length(), jLabelLeft.getText());
}
buttons[i].setPreferredSize(new java.awt.Dimension(27, 27));
buttons[i].setMargin(new java.awt.Insets(2, 0, 2, 0));
buttons[i].setBorder(buttonBorderSelected);
getAvailableComponents(i);
}
@Override public void focusLost(java.awt.event.FocusEvent evt) {
javax.swing.JButton b = (javax.swing.JButton)evt.getSource();
int i = Integer.parseInt(b.getActionCommand());
buttons[i].setPreferredSize(new java.awt.Dimension(27, 27));
buttons[i].setMargin(new java.awt.Insets(2, 0, 2, 0));
buttons[i].setBackground(buttonBackgroundB);
buttons[i].setBorder(buttonBorder);
jLabelLeft.setText(originalJLabelLeft.toString());
}
} //class ButtonFocusListener
private class ButtonKeyListener extends java.awt.event.KeyAdapter {
@Override public void keyPressed(java.awt.event.KeyEvent evt) {
javax.swing.JButton b = (javax.swing.JButton)evt.getSource();
int i = Integer.parseInt(b.getActionCommand());
int j;
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_UP) {
if(i == 0) {
for(j=(buttons.length-1); j > i; j--) {
if(buttons[j].isEnabled()) {buttons[j].requestFocusInWindow(); return;}
}
}
if(i == 1 || i == 2) {j=0;}
else if(i == 3) {j=1;}
else if(i ==10 || (i >=11 && i <=20)) {j=i-8;}
else if(i >=31 && i <= 57) {j=i-18;}
else if(i >=72 && i <= 103) {j=i-32;} else {j=-1;}
if(j > -1) {buttons[j].requestFocusInWindow();}
} else if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_DOWN) {
if(i == 0) {j=1;}
else if(i == 1) {j=3;}
else if(i >= 2 && i <=12) {j=i+8;}
else if(i >= 13 && i <=39) {j=i+18;}
else if(i >= 40 && i <=71) {j=i+32;}
else if(i >=72 && i <= 103) {j=0;} else {j=-1;}
if(j > -1) {buttons[j].requestFocusInWindow();}
} else if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_RIGHT) {
if(i < (buttons.length-1)) {
for(j=i+1; j<buttons.length; j++) {
if(buttons[j].isEnabled()) {buttons[j].requestFocusInWindow(); return;}
}
}
buttons[0].requestFocusInWindow(); // buttons[0] is always enabled
} else if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_LEFT) {
if(i > 0) {
for(j=i-1; j >= 0; j--) {
if(buttons[j].isEnabled()) {buttons[j].requestFocusInWindow(); return;}
}
}
for(j=(buttons.length-1); j > i; j--) {
if(buttons[j].isEnabled()) {buttons[j].requestFocusInWindow(); return;}
}
buttons[i].requestFocusInWindow();
}
}
} //class ButtonKeyListener
private class ButtonMouseListener extends java.awt.event.MouseAdapter {
@Override
public void mouseEntered(java.awt.event.MouseEvent evt) {
javax.swing.JButton b = (javax.swing.JButton)evt.getSource();
int i = Integer.parseInt(b.getActionCommand());
if(LibDB.elementName[i] != null) {
jLabelLeft.setText("Element: "+LibDB.elementName[i]);
}
}
@Override
public void mouseExited(java.awt.event.MouseEvent evt) {
jLabelLeft.setText(originalJLabelLeft.toString());
}
} //class ButtonMouseListener
// </editor-fold>
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="start()">
/** Performs start-up actions that require an "object" of this class to be present */
private void start() {
if(pc.dbg) {System.out.println(pc.progName+" - start()");}
//---- read the INI-file
// because this might result in message boxes, that nee a parent,
// this must be done after the constructor is finished.
// Note, however, that the parent (this) frame is not visible yet.
readIni();
//---- Position the window on the screen
locationFrame.x = Math.min(LibDB.screenSize.width - this.getWidth() - 4,
Math.max(4, locationFrame.x));
locationFrame.y = Math.min(LibDB.screenSize.height - this.getHeight()- 25,
Math.max(4, locationFrame.y));
setLocation(locationFrame);
//----
jLabel_cr_solids.setText(" ");
jLabelLeft.setText(" ");
jLabelMid.setText(" ");
jLabelRight.setText(" ");
jMenuSearch.setEnabled(false);
jMenuExit.setEnabled(false);
//<editor-fold defaultstate="collapsed" desc="---- Icon">
//---- Icon
String iconName = "images/DataBase.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
java.awt.Image icon;
if (imgURL != null) {
icon = new javax.swing.ImageIcon(imgURL).getImage();
this.setIconImage(icon);
//com.apple.eawt.Application.getApplication().setDockIconImage(new javax.swing.ImageIcon("Football.png").getImage());
if(System.getProperty("os.name").startsWith("Mac OS")) {
try {
Class<?> c = Class.forName("com.apple.eawt.Application");
//Class params[] = new Class[] {java.awt.Image.class};
java.lang.reflect.Method m =
c.getDeclaredMethod("setDockIconImage",new Class[] { java.awt.Image.class });
Object i = c.newInstance();
Object paramsObj[] = new Object[]{icon};
m.invoke(i, paramsObj);
} catch (Exception e) {System.out.println("Error: "+e.getMessage());}
}
} else {
System.out.println("Error: Could not load image = \""+iconName+"\"");
}
// </editor-fold>
//getContentPane().setBackground(java.awt.Color.white);
jMenuBar.add(javax.swing.Box.createHorizontalGlue(),2); //move "Help" menu to the right
//<editor-fold defaultstate="collapsed" desc="---- key actions ----">
//----- key actions -----
//--- ESC key: with a menu bar, the behaviour of ESC is too complex
//--- Alt-Q quit
javax.swing.KeyStroke altQKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altQKeyStroke,"ALT_Q");
javax.swing.Action altQAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
queryToQuit = true; end_program();
}};
getRootPane().getActionMap().put("ALT_Q", altQAction);
//--- Alt-X eXit
javax.swing.KeyStroke altXKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altXKeyStroke,"ALT_X");
javax.swing.Action altXAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jMenuExit.doClick();
}};
getRootPane().getActionMap().put("ALT_X", altXAction);
//--- Alt-S show debug frame
javax.swing.KeyStroke altSKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altSKeyStroke,"ALT_S");
javax.swing.Action altSAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jCheckBoxMenuDebug.doClick();
}};
getRootPane().getActionMap().put("ALT_S", altSAction);
//--- Alt-A available components or "Accept"
javax.swing.KeyStroke altAKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altAKeyStroke,"ALT_A");
javax.swing.Action altAAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jListAvailableComps.requestFocusInWindow();
int i = jListAvailableComps.getSelectedIndex();
if(i>=0) {
jLabelLeft.setText(availableComponentsNames.get(i));
} else {
jListAvailableComps.setSelectedIndex(0);
jLabelLeft.setText(availableComponentsNames.get(0));
}
}};
getRootPane().getActionMap().put("ALT_A", altAAction);
//--- F1 for help
javax.swing.KeyStroke f1KeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_F1,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(f1KeyStroke,"F1");
javax.swing.Action f1Action = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jMenuHelp.doClick();
}};
getRootPane().getActionMap().put("F1", f1Action);
//--- Alt-C components
javax.swing.KeyStroke altCKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altCKeyStroke,"ALT_C");
javax.swing.Action altCAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jListSelectedComps.requestFocusInWindow();
int i = jListSelectedComps.getSelectedIndex();
if(i>=0) {
jLabelMid.setText(componentsNames.get(i));
} else {
jListSelectedComps.setSelectedIndex(0);
jLabelMid.setText(componentsNames.get(0));
}
}};
getRootPane().getActionMap().put("ALT_C", altCAction);
//--- Alt-D complexes
javax.swing.KeyStroke altDKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_D, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altDKeyStroke,"ALT_D");
javax.swing.Action altDAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jListComplexes.isShowing()) {jListComplexes.requestFocusInWindow();}
int i = jListComplexes.getSelectedIndex();
if(i<0) {
jListComplexes.setSelectedIndex(0);
lastReactionInFocus = 0;
} else {
lastReactionInFocus = i;
}
}};
getRootPane().getActionMap().put("ALT_D", altDAction);
//----- key actions end -----
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="---- print debug info">
if (pc.dbg) {
System.out.println(LINE);
StringBuffer msg = new StringBuffer();
msg.append("After reading cfg- and INI-files");msg.append(nl);
msg.append(" and after checking for another instance:");msg.append(nl);
msg.append("App_Path = ");
if(pc.pathAPP == null) {
msg.append("\"null\"");
} else {
if(pc.pathAPP.trim().length()<=0) {msg.append("\"\"");}
else {msg.append(pc.pathAPP);}
}
msg.append(nl);
msg.append("Def_path = ");msg.append(pc.pathDef.toString());msg.append(nl);
try {
msg.append("User.dir = ");msg.append(System.getProperty("user.dir"));msg.append(nl);
msg.append("User.home = ");msg.append(System.getProperty("user.home"));msg.append(nl);
}
catch (Exception e) {}
msg.append("CLASSPATH = ");msg.append(System.getProperty("java.class.path"));msg.append(nl);
msg.append("Program to make diagrams = ");msg.append(pd.diagramProgr);msg.append(nl);
int ndb = pd.dataBasesList.size();
msg.append(ndb); msg.append(" database"); if(ndb != 1) {msg.append("s");}
if(ndb > 0) {
msg.append(":"); msg.append(nl);
for(int i = 0; i < ndb; i++) {
msg.append(" "); msg.append(pd.dataBasesList.get(i));
msg.append(nl);
}
}
System.out.println(msg);
System.out.println(LINE);
} // if dbg
// </editor-fold>
// ----
if(pd.msgFrame != null) {
pd.msgFrame.setLocation(locationMsgFrame);
pd.msgFrame.setSize(msgFrameSize);
jCheckBoxMenuDebug.setSelected(pd.msgFrame.isVisible());
} else {jCheckBoxMenuDebug.setVisible(false);}
if(pc.pathAPP != null && pc.pathAPP.trim().length()>0) {
pd.pathDatabaseFiles.replace(0,pd.pathDatabaseFiles.length(),pc.pathAPP);
} else {pd.pathDatabaseFiles.replace(0,pd.pathDatabaseFiles.length(),".");}
java.io.File f = new java.io.File(pc.pathAPP+SLASH+ProgramConf.HELP_JAR);
if(!f.exists()) {jMenuHelp.setEnabled(false);}
//---- set Look-And-Feel
boolean changeLookAndFeel = ((laf == 2 && windows) || (laf == 1 && !windows));
if(pc.dbg) {System.out.println("--- Change look-and-feel: windows = "+windows+", look-and-feel in ini-file = "+laf);}
if (changeLookAndFeel) {
try{
if(laf == 2) {
javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getCrossPlatformLookAndFeelClassName());
System.out.println("--- setLookAndFeel(CrossPlatform);");
} else if(laf == 1) {
javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
System.out.println("--- setLookAndFeel(System);");
}
} catch (Exception ex) {System.out.println("Error: "+ex.getMessage());}
javax.swing.SwingUtilities.updateComponentTreeUI(dbf);
dbf.invalidate(); dbf.validate(); dbf.repaint();
javax.swing.SwingUtilities.updateComponentTreeUI(msgFrame);
msgFrame.invalidate(); msgFrame.validate(); msgFrame.repaint();
if(pc.dbg) {System.out.println("--- configureOptionPane();");}
Util.configureOptionPane();
} // changeLookAndFeel
if(pd.temperatureAllowHigher) {
jMenuItemTemperature.setText("set Temperature & pressure");
} else {
jMenuItemTemperature.setText("set Temperature");
}
prepareButtons();
setTitle();
pack();
if(pc.dbg) {System.out.println(pc.progName+" - start() exit.");}
if(disclaimerFrame != null) {
if(disclaimerSkip) {
System.out.println("Skipping disclaimer.");
//--- remove the "disclaimer" window
disclaimerFrame.closeWindow(true);
disclaimerFrame = null;
// set this window visible, set the minimum size and the location
bringToFront();
disclaimerAccepted();
} else {
System.out.println("... waiting for disclaimer acceptance ...");
disclaimerFrame.requestFocus();
// ---- Start a thread to wait for the disclaimer
new javax.swing.SwingWorker<Void,Void>() {
@Override protected Void doInBackground() throws Exception {
disclaimerFrame.waitForDisclaimer();
return null;
}
@Override protected void done(){
disclaimerFrame = null;
// set this window visible, set the minimum size and the location
System.out.println(" disclaimer accepted.");
disclaimerAccepted();
bringToFront();
} // done()
}.execute(); // this returns inmediately,
// but the SwingWorker continues running...
}
} else { // if disclaimerFrame == null
// there was no disclaimer,
// set this window visible, set the minimum size and the location
bringToFront();
disclaimerAccepted();
}
} //start
// </editor-fold>
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPopupMenu = new javax.swing.JPopupMenu();
jMenuItemDel = new javax.swing.JMenuItem();
jMenuItemData = new javax.swing.JMenuItem();
jSeparator = new javax.swing.JPopupMenu.Separator();
jMenuItemCancel = new javax.swing.JMenuItem();
buttonGroup1 = new javax.swing.ButtonGroup();
jPanelTable = new javax.swing.JPanel();
jPanelPeriodicT = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton();
jButton7 = new javax.swing.JButton();
jButton8 = new javax.swing.JButton();
jButton9 = new javax.swing.JButton();
jButton10 = new javax.swing.JButton();
jButton11 = new javax.swing.JButton();
jButton12 = new javax.swing.JButton();
jButton13 = new javax.swing.JButton();
jButton14 = new javax.swing.JButton();
jButton15 = new javax.swing.JButton();
jButton16 = new javax.swing.JButton();
jButton17 = new javax.swing.JButton();
jButton18 = new javax.swing.JButton();
jButton19 = new javax.swing.JButton();
jButton20 = new javax.swing.JButton();
jButton21 = new javax.swing.JButton();
jButton22 = new javax.swing.JButton();
jButton23 = new javax.swing.JButton();
jButton24 = new javax.swing.JButton();
jButton25 = new javax.swing.JButton();
jButton26 = new javax.swing.JButton();
jButton27 = new javax.swing.JButton();
jButton28 = new javax.swing.JButton();
jButton29 = new javax.swing.JButton();
jButton30 = new javax.swing.JButton();
jButton31 = new javax.swing.JButton();
jButton32 = new javax.swing.JButton();
jButton33 = new javax.swing.JButton();
jButton34 = new javax.swing.JButton();
jButton35 = new javax.swing.JButton();
jButton36 = new javax.swing.JButton();
jButton37 = new javax.swing.JButton();
jButton38 = new javax.swing.JButton();
jButton39 = new javax.swing.JButton();
jButton40 = new javax.swing.JButton();
jButton41 = new javax.swing.JButton();
jButton42 = new javax.swing.JButton();
jButton43 = new javax.swing.JButton();
jButton44 = new javax.swing.JButton();
jButton45 = new javax.swing.JButton();
jButton46 = new javax.swing.JButton();
jButton47 = new javax.swing.JButton();
jButton48 = new javax.swing.JButton();
jButton49 = new javax.swing.JButton();
jButton50 = new javax.swing.JButton();
jButton51 = new javax.swing.JButton();
jButton52 = new javax.swing.JButton();
jButton53 = new javax.swing.JButton();
jButton54 = new javax.swing.JButton();
jButton55 = new javax.swing.JButton();
jButton56 = new javax.swing.JButton();
jButton57 = new javax.swing.JButton();
jButton72 = new javax.swing.JButton();
jButton73 = new javax.swing.JButton();
jButton74 = new javax.swing.JButton();
jButton75 = new javax.swing.JButton();
jButton76 = new javax.swing.JButton();
jButton77 = new javax.swing.JButton();
jButton78 = new javax.swing.JButton();
jButton79 = new javax.swing.JButton();
jButton80 = new javax.swing.JButton();
jButton81 = new javax.swing.JButton();
jButton82 = new javax.swing.JButton();
jButton83 = new javax.swing.JButton();
jButton84 = new javax.swing.JButton();
jButton85 = new javax.swing.JButton();
jButton86 = new javax.swing.JButton();
jButton87 = new javax.swing.JButton();
jButton88 = new javax.swing.JButton();
jButton89 = new javax.swing.JButton();
jButton0 = new javax.swing.JButton();
jPanelREEactinides = new javax.swing.JPanel();
jButton58 = new javax.swing.JButton();
jButton59 = new javax.swing.JButton();
jButton60 = new javax.swing.JButton();
jButton61 = new javax.swing.JButton();
jButton62 = new javax.swing.JButton();
jButton63 = new javax.swing.JButton();
jButton64 = new javax.swing.JButton();
jButton65 = new javax.swing.JButton();
jButton66 = new javax.swing.JButton();
jButton67 = new javax.swing.JButton();
jButton68 = new javax.swing.JButton();
jButton69 = new javax.swing.JButton();
jButton70 = new javax.swing.JButton();
jButton71 = new javax.swing.JButton();
jButton90 = new javax.swing.JButton();
jButton91 = new javax.swing.JButton();
jButton92 = new javax.swing.JButton();
jButton93 = new javax.swing.JButton();
jButton94 = new javax.swing.JButton();
jButton95 = new javax.swing.JButton();
jButton96 = new javax.swing.JButton();
jButton97 = new javax.swing.JButton();
jButton98 = new javax.swing.JButton();
jButton99 = new javax.swing.JButton();
jButton100 = new javax.swing.JButton();
jButton101 = new javax.swing.JButton();
jButton102 = new javax.swing.JButton();
jButton103 = new javax.swing.JButton();
jLabelTemperature = new javax.swing.JLabel();
jLabelPressure = new javax.swing.JLabel();
jPanelBottom = new javax.swing.JPanel();
jPanelLower = new javax.swing.JPanel();
jLabelAvailableComp = new javax.swing.JLabel();
jScrollPaneAvailableComps = new javax.swing.JScrollPane();
jListAvailableComps = new javax.swing.JList();
jLabelComps = new javax.swing.JLabel();
jScrollPaneSelectedComps = new javax.swing.JScrollPane();
jListSelectedComps = new javax.swing.JList();
jLabelComplexes = new javax.swing.JLabel();
jScrollPaneComplexes = new javax.swing.JScrollPane();
jListComplexes = new javax.swing.JList();
jLabel_cr_solids = new javax.swing.JLabel();
jPanelLowerLabels = new javax.swing.JPanel();
jLabelLeft = new javax.swing.JLabel();
jLabelMid = new javax.swing.JLabel();
jLabelRight = new javax.swing.JLabel();
jPanelProgressBar = new javax.swing.JPanel();
jLabelNow = new javax.swing.JLabel();
jLabelNowLoop = new javax.swing.JLabel();
jProgressBar = new javax.swing.JProgressBar();
jMenuBar = new javax.swing.JMenuBar();
jMenuFile = new javax.swing.JMenu();
jMenuSearch = new javax.swing.JMenuItem();
jMenuExit = new javax.swing.JMenuItem();
jMenuQuit = new javax.swing.JMenuItem();
jMenuOptions = new javax.swing.JMenu();
jMenuItemTemperature = new javax.swing.JMenuItem();
jMenuPref = new javax.swing.JMenu();
jMenuAdvH2O = new javax.swing.JMenuItem();
jMenuAdvRedox = new javax.swing.JMenuItem();
jMenuAdvSolids = new javax.swing.JMenuItem();
jMenuLocate = new javax.swing.JMenuItem();
jCheckBoxMenuVerbose = new javax.swing.JCheckBoxMenuItem();
jCheckBoxMenuDebug = new javax.swing.JCheckBoxMenuItem();
jMenuData = new javax.swing.JMenu();
jMenuDBFiles = new javax.swing.JMenuItem();
jMenuAddData = new javax.swing.JMenuItem();
jMenuSingleC = new javax.swing.JMenuItem();
jMenuAdvanced = new javax.swing.JMenu();
jMenuRefs = new javax.swing.JMenuItem();
jMenuMaintenance = new javax.swing.JMenuItem();
jMenuH = new javax.swing.JMenu();
jMenuHelp = new javax.swing.JMenuItem();
jMenuHelpAbout = new javax.swing.JMenuItem();
jMenuItemDel.setMnemonic('r');
jMenuItemDel.setText("Remove");
jMenuItemDel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItemDelActionPerformed(evt);
}
});
jPopupMenu.add(jMenuItemDel);
jMenuItemData.setMnemonic('d');
jMenuItemData.setText("show Details");
jMenuItemData.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItemDataActionPerformed(evt);
}
});
jPopupMenu.add(jMenuItemData);
jPopupMenu.add(jSeparator);
jMenuItemCancel.setMnemonic('c');
jMenuItemCancel.setText("cancel");
jMenuItemCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItemCancelActionPerformed(evt);
}
});
jPopupMenu.add(jMenuItemCancel);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
addWindowFocusListener(new java.awt.event.WindowFocusListener() {
public void windowGainedFocus(java.awt.event.WindowEvent evt) {
formWindowGainedFocus(evt);
}
public void windowLostFocus(java.awt.event.WindowEvent evt) {
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowActivated(java.awt.event.WindowEvent evt) {
formWindowActivated(evt);
}
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jPanelTable.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jPanelPeriodicT.setBackground(new java.awt.Color(255, 255, 153));
jPanelPeriodicT.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
jPanelPeriodicT.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jButton1.setText("H");
jButton1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButton1.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton1.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 13, -1, -1));
jButton2.setText("He");
jButton2.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton2.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(471, 13, -1, -1));
jButton3.setText("Li");
jButton3.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jButton3.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton3.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 40, -1, -1));
jButton4.setText("Be");
jButton4.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton4.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton4, new org.netbeans.lib.awtextra.AbsoluteConstraints(39, 40, -1, -1));
jButton5.setText("B");
jButton5.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton5.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton5, new org.netbeans.lib.awtextra.AbsoluteConstraints(336, 40, -1, -1));
jButton6.setText("C");
jButton6.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton6.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton6, new org.netbeans.lib.awtextra.AbsoluteConstraints(363, 40, -1, -1));
jButton7.setText("N");
jButton7.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton7.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton7, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 40, -1, -1));
jButton8.setText("O");
jButton8.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton8.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton8, new org.netbeans.lib.awtextra.AbsoluteConstraints(417, 40, -1, -1));
jButton9.setText("F");
jButton9.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton9.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton9, new org.netbeans.lib.awtextra.AbsoluteConstraints(444, 40, -1, -1));
jButton10.setText("Ne");
jButton10.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton10.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton10, new org.netbeans.lib.awtextra.AbsoluteConstraints(471, 40, -1, -1));
jButton11.setText("Na");
jButton11.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton11.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton11, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 67, -1, -1));
jButton12.setText("Mg");
jButton12.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton12.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton12, new org.netbeans.lib.awtextra.AbsoluteConstraints(39, 67, -1, -1));
jButton13.setText("Al");
jButton13.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton13.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton13, new org.netbeans.lib.awtextra.AbsoluteConstraints(336, 67, -1, -1));
jButton14.setText("Si");
jButton14.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton14.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton14, new org.netbeans.lib.awtextra.AbsoluteConstraints(363, 67, -1, -1));
jButton15.setText("P");
jButton15.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton15.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton15, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 67, -1, -1));
jButton16.setText("S");
jButton16.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton16.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton16, new org.netbeans.lib.awtextra.AbsoluteConstraints(417, 67, -1, -1));
jButton17.setText("Cl");
jButton17.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton17.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton17, new org.netbeans.lib.awtextra.AbsoluteConstraints(444, 67, -1, -1));
jButton18.setText("Ar");
jButton18.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton18.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton18, new org.netbeans.lib.awtextra.AbsoluteConstraints(471, 67, -1, -1));
jButton19.setText("K");
jButton19.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton19.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton19, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 94, -1, -1));
jButton20.setText("Ca");
jButton20.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton20.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton20, new org.netbeans.lib.awtextra.AbsoluteConstraints(39, 94, -1, -1));
jButton21.setText("Sc");
jButton21.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton21.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton21, new org.netbeans.lib.awtextra.AbsoluteConstraints(66, 94, -1, -1));
jButton22.setText("Ti");
jButton22.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton22.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton22, new org.netbeans.lib.awtextra.AbsoluteConstraints(93, 94, -1, -1));
jButton23.setText("V");
jButton23.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton23.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton23, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 94, -1, -1));
jButton24.setText("Cr");
jButton24.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton24.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton24, new org.netbeans.lib.awtextra.AbsoluteConstraints(147, 94, -1, -1));
jButton25.setText("Mn");
jButton25.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton25.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton25, new org.netbeans.lib.awtextra.AbsoluteConstraints(174, 94, -1, -1));
jButton26.setText("Fe");
jButton26.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton26.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton26, new org.netbeans.lib.awtextra.AbsoluteConstraints(201, 94, -1, -1));
jButton27.setText("Co");
jButton27.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton27.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton27, new org.netbeans.lib.awtextra.AbsoluteConstraints(228, 94, -1, -1));
jButton28.setText("Ni");
jButton28.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton28.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton28, new org.netbeans.lib.awtextra.AbsoluteConstraints(255, 94, -1, -1));
jButton29.setText("Cu");
jButton29.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton29.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton29, new org.netbeans.lib.awtextra.AbsoluteConstraints(282, 94, -1, -1));
jButton30.setText("Zn");
jButton30.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton30.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton30, new org.netbeans.lib.awtextra.AbsoluteConstraints(309, 94, -1, -1));
jButton31.setText("Ga");
jButton31.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton31.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton31, new org.netbeans.lib.awtextra.AbsoluteConstraints(336, 94, -1, -1));
jButton32.setText("Ge");
jButton32.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton32.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton32, new org.netbeans.lib.awtextra.AbsoluteConstraints(363, 94, -1, -1));
jButton33.setText("As");
jButton33.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton33.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton33, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 94, -1, -1));
jButton34.setText("Se");
jButton34.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton34.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton34, new org.netbeans.lib.awtextra.AbsoluteConstraints(417, 94, -1, -1));
jButton35.setText("Br");
jButton35.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton35.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton35, new org.netbeans.lib.awtextra.AbsoluteConstraints(444, 94, -1, -1));
jButton36.setText("Kr");
jButton36.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton36.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton36, new org.netbeans.lib.awtextra.AbsoluteConstraints(471, 94, -1, -1));
jButton37.setText("Rb");
jButton37.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton37.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton37, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 121, -1, -1));
jButton38.setText("Sr");
jButton38.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton38.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton38, new org.netbeans.lib.awtextra.AbsoluteConstraints(39, 121, -1, -1));
jButton39.setText("Y");
jButton39.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton39.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton39, new org.netbeans.lib.awtextra.AbsoluteConstraints(66, 121, -1, -1));
jButton40.setText("Zr");
jButton40.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton40.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton40, new org.netbeans.lib.awtextra.AbsoluteConstraints(93, 121, -1, -1));
jButton41.setText("Nb");
jButton41.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton41.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton41, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 121, -1, -1));
jButton42.setText("Mo");
jButton42.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton42.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton42, new org.netbeans.lib.awtextra.AbsoluteConstraints(147, 121, -1, -1));
jButton43.setText("Tc");
jButton43.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton43.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton43, new org.netbeans.lib.awtextra.AbsoluteConstraints(174, 121, -1, -1));
jButton44.setText("Ru");
jButton44.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton44.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton44, new org.netbeans.lib.awtextra.AbsoluteConstraints(201, 121, -1, -1));
jButton45.setText("Rh");
jButton45.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton45.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton45, new org.netbeans.lib.awtextra.AbsoluteConstraints(228, 121, -1, -1));
jButton46.setText("Pd");
jButton46.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton46.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton46, new org.netbeans.lib.awtextra.AbsoluteConstraints(255, 121, -1, -1));
jButton47.setText("Ag");
jButton47.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton47.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton47, new org.netbeans.lib.awtextra.AbsoluteConstraints(282, 121, -1, -1));
jButton48.setText("Cd");
jButton48.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton48.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton48, new org.netbeans.lib.awtextra.AbsoluteConstraints(309, 121, -1, -1));
jButton49.setText("In");
jButton49.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton49.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton49, new org.netbeans.lib.awtextra.AbsoluteConstraints(336, 121, -1, -1));
jButton50.setText("Sn");
jButton50.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton50.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton50, new org.netbeans.lib.awtextra.AbsoluteConstraints(363, 121, -1, -1));
jButton51.setText("Sb");
jButton51.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton51.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton51, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 121, -1, -1));
jButton52.setText("Te");
jButton52.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton52.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton52, new org.netbeans.lib.awtextra.AbsoluteConstraints(417, 121, -1, -1));
jButton53.setText("I");
jButton53.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton53.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton53, new org.netbeans.lib.awtextra.AbsoluteConstraints(444, 121, -1, -1));
jButton54.setText("Xe");
jButton54.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton54.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton54, new org.netbeans.lib.awtextra.AbsoluteConstraints(471, 121, -1, -1));
jButton55.setText("Cs");
jButton55.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton55.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton55, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 148, -1, -1));
jButton56.setText("Ba");
jButton56.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton56.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton56, new org.netbeans.lib.awtextra.AbsoluteConstraints(39, 148, -1, -1));
jButton57.setText("La");
jButton57.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton57.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton57, new org.netbeans.lib.awtextra.AbsoluteConstraints(66, 148, -1, -1));
jButton72.setText("Hf");
jButton72.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton72.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton72, new org.netbeans.lib.awtextra.AbsoluteConstraints(93, 148, -1, -1));
jButton73.setText("Ta");
jButton73.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton73.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton73, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 148, -1, -1));
jButton74.setText("W");
jButton74.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton74.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton74, new org.netbeans.lib.awtextra.AbsoluteConstraints(147, 148, -1, -1));
jButton75.setText("Re");
jButton75.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton75.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton75, new org.netbeans.lib.awtextra.AbsoluteConstraints(174, 148, -1, -1));
jButton76.setText("Os");
jButton76.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton76.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton76, new org.netbeans.lib.awtextra.AbsoluteConstraints(201, 148, -1, -1));
jButton77.setText("Ir");
jButton77.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton77.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton77, new org.netbeans.lib.awtextra.AbsoluteConstraints(228, 148, -1, -1));
jButton78.setText("Pt");
jButton78.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton78.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton78, new org.netbeans.lib.awtextra.AbsoluteConstraints(255, 148, -1, -1));
jButton79.setText("Au");
jButton79.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton79.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton79, new org.netbeans.lib.awtextra.AbsoluteConstraints(282, 148, -1, -1));
jButton80.setText("Hg");
jButton80.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton80.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton80, new org.netbeans.lib.awtextra.AbsoluteConstraints(309, 148, -1, -1));
jButton81.setText("Tl");
jButton81.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton81.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton81, new org.netbeans.lib.awtextra.AbsoluteConstraints(336, 148, -1, -1));
jButton82.setText("Pb");
jButton82.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton82.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton82, new org.netbeans.lib.awtextra.AbsoluteConstraints(363, 148, -1, -1));
jButton83.setText("Bi");
jButton83.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton83.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton83, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 148, -1, -1));
jButton84.setText("Po");
jButton84.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton84.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton84, new org.netbeans.lib.awtextra.AbsoluteConstraints(417, 148, -1, -1));
jButton85.setText("At");
jButton85.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton85.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton85, new org.netbeans.lib.awtextra.AbsoluteConstraints(444, 148, -1, -1));
jButton86.setText("Rn");
jButton86.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton86.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton86, new org.netbeans.lib.awtextra.AbsoluteConstraints(471, 148, -1, -1));
jButton87.setText("Fr");
jButton87.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton87.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton87, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 175, -1, -1));
jButton88.setText("Ra");
jButton88.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton88.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton88, new org.netbeans.lib.awtextra.AbsoluteConstraints(39, 175, -1, -1));
jButton89.setText("Ac");
jButton89.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton89.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton89, new org.netbeans.lib.awtextra.AbsoluteConstraints(66, 175, -1, -1));
jButton0.setText("e-");
jButton0.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButton0.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton0.setPreferredSize(new java.awt.Dimension(27, 27));
jPanelPeriodicT.add(jButton0, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 10, -1, -1));
jPanelREEactinides.setOpaque(false);
jButton58.setText("Ce");
jButton58.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton58.setPreferredSize(new java.awt.Dimension(27, 27));
jButton59.setText("Pr");
jButton59.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton59.setPreferredSize(new java.awt.Dimension(27, 27));
jButton60.setText("Nd");
jButton60.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton60.setPreferredSize(new java.awt.Dimension(27, 27));
jButton61.setText("Pm");
jButton61.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton61.setPreferredSize(new java.awt.Dimension(27, 27));
jButton62.setText("Sm");
jButton62.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton62.setPreferredSize(new java.awt.Dimension(27, 27));
jButton63.setText("Eu");
jButton63.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton63.setPreferredSize(new java.awt.Dimension(27, 27));
jButton64.setText("Gd");
jButton64.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton64.setPreferredSize(new java.awt.Dimension(27, 27));
jButton65.setText("Tb");
jButton65.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton65.setPreferredSize(new java.awt.Dimension(27, 27));
jButton66.setText("Dy");
jButton66.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton66.setPreferredSize(new java.awt.Dimension(27, 27));
jButton67.setText("Ho");
jButton67.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton67.setPreferredSize(new java.awt.Dimension(27, 27));
jButton68.setText("Er");
jButton68.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton68.setPreferredSize(new java.awt.Dimension(27, 27));
jButton69.setText("Tm");
jButton69.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton69.setPreferredSize(new java.awt.Dimension(27, 27));
jButton70.setText("Yb");
jButton70.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton70.setPreferredSize(new java.awt.Dimension(27, 27));
jButton71.setText("Lu");
jButton71.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton71.setPreferredSize(new java.awt.Dimension(27, 27));
jButton90.setText("Th");
jButton90.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton90.setPreferredSize(new java.awt.Dimension(27, 27));
jButton91.setText("Pa");
jButton91.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton91.setPreferredSize(new java.awt.Dimension(27, 27));
jButton92.setText("U");
jButton92.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton92.setPreferredSize(new java.awt.Dimension(27, 27));
jButton93.setText("Np");
jButton93.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton93.setPreferredSize(new java.awt.Dimension(27, 27));
jButton94.setText("Pu");
jButton94.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton94.setPreferredSize(new java.awt.Dimension(27, 27));
jButton95.setText("Am");
jButton95.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton95.setPreferredSize(new java.awt.Dimension(27, 27));
jButton96.setText("Cm");
jButton96.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton96.setPreferredSize(new java.awt.Dimension(27, 27));
jButton97.setText("Bk");
jButton97.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton97.setPreferredSize(new java.awt.Dimension(27, 27));
jButton98.setText("Cf");
jButton98.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton98.setPreferredSize(new java.awt.Dimension(27, 27));
jButton99.setText("Es");
jButton99.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton99.setPreferredSize(new java.awt.Dimension(27, 27));
jButton100.setText("Fm");
jButton100.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton100.setPreferredSize(new java.awt.Dimension(27, 27));
jButton101.setText("Md");
jButton101.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton101.setPreferredSize(new java.awt.Dimension(27, 27));
jButton102.setText("No");
jButton102.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton102.setPreferredSize(new java.awt.Dimension(27, 27));
jButton103.setText("Lr");
jButton103.setMargin(new java.awt.Insets(2, 0, 2, 0));
jButton103.setPreferredSize(new java.awt.Dimension(27, 27));
javax.swing.GroupLayout jPanelREEactinidesLayout = new javax.swing.GroupLayout(jPanelREEactinides);
jPanelREEactinides.setLayout(jPanelREEactinidesLayout);
jPanelREEactinidesLayout.setHorizontalGroup(
jPanelREEactinidesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelREEactinidesLayout.createSequentialGroup()
.addComponent(jButton90, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jButton91, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jButton92, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jButton93, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jButton94, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jButton95, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jButton96, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jButton97, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jButton98, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jButton99, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jButton100, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jButton101, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jButton102, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jButton103, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanelREEactinidesLayout.createSequentialGroup()
.addComponent(jButton58, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jButton59, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jButton60, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jButton61, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jButton62, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jButton63, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jButton64, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jButton65, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jButton66, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jButton67, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jButton68, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jButton69, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jButton70, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jButton71, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jPanelREEactinidesLayout.setVerticalGroup(
jPanelREEactinidesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelREEactinidesLayout.createSequentialGroup()
.addGroup(jPanelREEactinidesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton58, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton59, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton60, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton61, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton62, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton63, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton64, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton65, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton66, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton67, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton68, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton69, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton70, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton71, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0)
.addGroup(jPanelREEactinidesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton90, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton91, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton92, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton93, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton94, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton95, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton96, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton97, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton98, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton99, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton100, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton101, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton102, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton103, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelPeriodicT.add(jPanelREEactinides, new org.netbeans.lib.awtextra.AbsoluteConstraints(101, 184, -1, 60));
jLabelTemperature.setText("Temperature = 80°C");
jLabelTemperature.setToolTipText("double-click to set T=25´C");
jLabelTemperature.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabelTemperatureMouseClicked(evt);
}
});
jPanelPeriodicT.add(jLabelTemperature, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 10, -1, -1));
jLabelPressure.setText("Pressure = 1.014 bar");
jLabelPressure.setToolTipText("");
jLabelPressure.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabelPressureMouseClicked(evt);
}
});
jPanelPeriodicT.add(jLabelPressure, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 30, -1, -1));
jPanelTable.add(jPanelPeriodicT, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 510, -1));
jPanelBottom.setLayout(new java.awt.CardLayout());
jPanelLower.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
jPanelLower.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabelAvailableComp.setText("<html><u>A</u>vailable:</html>");
jPanelLower.add(jLabelAvailableComp, new org.netbeans.lib.awtextra.AbsoluteConstraints(16, 7, -1, -1));
jListAvailableComps.setModel(modelAvailableComps);
jListAvailableComps.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jListAvailableComps.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jListAvailableCompsMouseClicked(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
jListAvailableCompsMouseExited(evt);
}
});
jListAvailableComps.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
jListAvailableCompsMouseMoved(evt);
}
});
jListAvailableComps.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
jListAvailableCompsValueChanged(evt);
}
});
jListAvailableComps.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jListAvailableCompsFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jListAvailableCompsFocusLost(evt);
}
});
jListAvailableComps.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
jListAvailableCompsKeyTyped(evt);
}
});
jScrollPaneAvailableComps.setViewportView(jListAvailableComps);
jPanelLower.add(jScrollPaneAvailableComps, new org.netbeans.lib.awtextra.AbsoluteConstraints(15, 27, 150, 100));
jLabelComps.setText("<html><u>C</u>omponents selected:</html>");
jPanelLower.add(jLabelComps, new org.netbeans.lib.awtextra.AbsoluteConstraints(181, 7, -1, -1));
jListSelectedComps.setModel(modelSelectedComps);
jListSelectedComps.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jListSelectedComps.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
jListSelectedCompsMouseMoved(evt);
}
});
jListSelectedComps.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jListSelectedCompsFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jListSelectedCompsFocusLost(evt);
}
});
jListSelectedComps.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jListSelectedCompsMouseClicked(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
jListSelectedCompsMouseExited(evt);
}
});
jListSelectedComps.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
jListSelectedCompsKeyTyped(evt);
}
});
jListSelectedComps.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
jListSelectedCompsValueChanged(evt);
}
});
jScrollPaneSelectedComps.setViewportView(jListSelectedComps);
jPanelLower.add(jScrollPaneSelectedComps, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 27, 150, 100));
jLabelComplexes.setText("<html>Reactions foun<u>d</u>:</html>");
jPanelLower.add(jLabelComplexes, new org.netbeans.lib.awtextra.AbsoluteConstraints(346, 7, -1, -1));
jListComplexes.setModel(modelComplexes);
jListComplexes.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jListComplexes.setToolTipText("Right-click for a pop-up menu");
jListComplexes.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jListComplexesMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
jListComplexesMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
jListComplexesMouseExited(evt);
}
public void mousePressed(java.awt.event.MouseEvent evt) {
jListComplexesMousePressed(evt);
}
public void mouseReleased(java.awt.event.MouseEvent evt) {
jListComplexesMouseReleased(evt);
}
});
jListComplexes.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
jListComplexesMouseMoved(evt);
}
});
jListComplexes.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jListComplexesFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jListComplexesFocusLost(evt);
}
});
jListComplexes.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
jListComplexesKeyTyped(evt);
}
});
jScrollPaneComplexes.setViewportView(jListComplexes);
jPanelLower.add(jScrollPaneComplexes, new org.netbeans.lib.awtextra.AbsoluteConstraints(345, 27, 150, 100));
jLabel_cr_solids.setFont(new java.awt.Font("Tahoma", 0, 9)); // NOI18N
jLabel_cr_solids.setText("(cr) solids excluded!");
jPanelLower.add(jLabel_cr_solids, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 127, -1, -1));
jPanelLowerLabels.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jPanelLowerLabels.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabelLeft.setText("left");
jPanelLowerLabels.add(jLabelLeft, new org.netbeans.lib.awtextra.AbsoluteConstraints(1, 1, -1, -1));
jLabelMid.setText("mid");
jPanelLowerLabels.add(jLabelMid, new org.netbeans.lib.awtextra.AbsoluteConstraints(167, 1, -1, -1));
jLabelRight.setText("right");
jPanelLowerLabels.add(jLabelRight, new org.netbeans.lib.awtextra.AbsoluteConstraints(328, 1, -1, -1));
jPanelLower.add(jPanelLowerLabels, new org.netbeans.lib.awtextra.AbsoluteConstraints(16, 138, 480, -1));
jPanelBottom.add(jPanelLower, "cardLower");
jLabelNow.setText("jLabelNow");
jLabelNowLoop.setText("jLabelNowLoop");
jProgressBar.setForeground(java.awt.Color.blue);
javax.swing.GroupLayout jPanelProgressBarLayout = new javax.swing.GroupLayout(jPanelProgressBar);
jPanelProgressBar.setLayout(jPanelProgressBarLayout);
jPanelProgressBarLayout.setHorizontalGroup(
jPanelProgressBarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelProgressBarLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelProgressBarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jProgressBar, javax.swing.GroupLayout.DEFAULT_SIZE, 490, Short.MAX_VALUE)
.addComponent(jLabelNowLoop)
.addComponent(jLabelNow))
.addContainerGap())
);
jPanelProgressBarLayout.setVerticalGroup(
jPanelProgressBarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelProgressBarLayout.createSequentialGroup()
.addGap(47, 47, 47)
.addComponent(jLabelNow)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelNowLoop)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jProgressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(57, Short.MAX_VALUE))
);
jPanelBottom.add(jPanelProgressBar, "cardProgress");
jPanelTable.add(jPanelBottom, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 250, -1, 160));
jMenuFile.setMnemonic('f');
jMenuFile.setText("File");
jMenuSearch.setMnemonic('s');
jMenuSearch.setText("Search reactions in database");
jMenuSearch.setEnabled(false);
jMenuSearch.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuSearchActionPerformed(evt);
}
});
jMenuFile.add(jMenuSearch);
jMenuExit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK));
jMenuExit.setMnemonic('x');
jMenuExit.setText("Search and Exit");
jMenuExit.setEnabled(false);
jMenuExit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuExitActionPerformed(evt);
}
});
jMenuFile.add(jMenuExit);
jMenuQuit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK));
jMenuQuit.setMnemonic('q');
jMenuQuit.setText("Quit");
jMenuQuit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuQuitActionPerformed(evt);
}
});
jMenuFile.add(jMenuQuit);
jMenuBar.add(jMenuFile);
jMenuOptions.setMnemonic('o');
jMenuOptions.setText("Options");
jMenuOptions.setEnabled(false);
jMenuItemTemperature.setMnemonic('T');
jMenuItemTemperature.setText("set Temperature & pressure");
jMenuItemTemperature.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItemTemperatureActionPerformed(evt);
}
});
jMenuOptions.add(jMenuItemTemperature);
jMenuPref.setMnemonic('P');
jMenuPref.setText("Preferences");
jMenuAdvH2O.setMnemonic('w');
jMenuAdvH2O.setText("Water (H2O)");
jMenuAdvH2O.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuAdvH2OActionPerformed(evt);
}
});
jMenuPref.add(jMenuAdvH2O);
jMenuAdvRedox.setMnemonic('R');
jMenuAdvRedox.setText("Redox reactions");
jMenuAdvRedox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuAdvRedoxActionPerformed(evt);
}
});
jMenuPref.add(jMenuAdvRedox);
jMenuAdvSolids.setMnemonic('S');
jMenuAdvSolids.setText("Solids");
jMenuAdvSolids.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuAdvSolidsActionPerformed(evt);
}
});
jMenuPref.add(jMenuAdvSolids);
jMenuLocate.setMnemonic('L');
jMenuLocate.setText("Locate diagram-making program");
jMenuLocate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuLocateActionPerformed(evt);
}
});
jMenuPref.add(jMenuLocate);
jCheckBoxMenuVerbose.setMnemonic('V');
jCheckBoxMenuVerbose.setText("debug (Verbose output of messages)");
jCheckBoxMenuVerbose.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxMenuVerboseActionPerformed(evt);
}
});
jMenuPref.add(jCheckBoxMenuVerbose);
jCheckBoxMenuDebug.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.ALT_MASK));
jCheckBoxMenuDebug.setMnemonic('S');
jCheckBoxMenuDebug.setText("Show errors and messages");
jCheckBoxMenuDebug.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxMenuDebugActionPerformed(evt);
}
});
jMenuPref.add(jCheckBoxMenuDebug);
jMenuOptions.add(jMenuPref);
jMenuData.setMnemonic('d');
jMenuData.setText("Data");
jMenuDBFiles.setMnemonic('D');
jMenuDBFiles.setText("Database files");
jMenuDBFiles.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuDBFilesActionPerformed(evt);
}
});
jMenuData.add(jMenuDBFiles);
jMenuAddData.setMnemonic('A');
jMenuAddData.setText("Add data !");
jMenuAddData.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuAddDataActionPerformed(evt);
}
});
jMenuData.add(jMenuAddData);
jMenuSingleC.setMnemonic('C');
jMenuSingleC.setText("display single Component");
jMenuSingleC.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuSingleCActionPerformed(evt);
}
});
jMenuData.add(jMenuSingleC);
jMenuAdvanced.setMnemonic('v');
jMenuAdvanced.setText("advanced");
jMenuRefs.setMnemonic('R');
jMenuRefs.setText("add-show References");
jMenuRefs.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuRefsActionPerformed(evt);
}
});
jMenuAdvanced.add(jMenuRefs);
jMenuMaintenance.setMnemonic('M');
jMenuMaintenance.setText("database Maintenance");
jMenuMaintenance.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuMaintenanceActionPerformed(evt);
}
});
jMenuAdvanced.add(jMenuMaintenance);
jMenuData.add(jMenuAdvanced);
jMenuOptions.add(jMenuData);
jMenuBar.add(jMenuOptions);
jMenuH.setMnemonic('h');
jMenuH.setText("Help");
jMenuH.setEnabled(false);
jMenuHelp.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0));
jMenuHelp.setMnemonic('c');
jMenuHelp.setText("help Contents");
jMenuHelp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuHelpActionPerformed(evt);
}
});
jMenuH.add(jMenuHelp);
jMenuHelpAbout.setMnemonic('a');
jMenuHelpAbout.setText("About");
jMenuHelpAbout.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuHelpAboutActionPerformed(evt);
}
});
jMenuH.add(jMenuHelpAbout);
jMenuBar.add(jMenuH);
setJMenuBar(jMenuBar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanelTable, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanelTable, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
//<editor-fold defaultstate="collapsed" desc="Events">
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
queryToQuit = true;
end_program();
}//GEN-LAST:event_formWindowClosing
private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
if(pd.msgFrame != null) {
pd.msgFrame.setParentFrame(this);
jCheckBoxMenuDebug.setSelected(pd.msgFrame.isVisible());
}
}//GEN-LAST:event_formWindowActivated
private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus
if(helpAboutFrame != null) {helpAboutFrame.bringToFront();}
if(pd.msgFrame != null) {jCheckBoxMenuDebug.setSelected(pd.msgFrame.isVisible());}
else {jCheckBoxMenuDebug.setEnabled(false);}
if(lastReactionInFocus >-1) {
jListComplexes.requestFocusInWindow();
jListComplexes.ensureIndexIsVisible(lastReactionInFocus);
jListComplexes.setSelectedIndex(lastReactionInFocus);
} else if(lastButtonInFocus >-1) {
buttons[lastButtonInFocus].requestFocusInWindow();
} else {
jListSelectedComps.requestFocusInWindow();
}
}//GEN-LAST:event_formWindowGainedFocus
private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
if(windowSize != null) {
int w = windowSize.width;
int h = windowSize.height;
if(this.getHeight()<h){this.setSize(this.getWidth(), h);}
if(this.getWidth()<w){this.setSize(w,this.getHeight());}
}
}//GEN-LAST:event_formComponentResized
private void jMenuSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuSearchActionPerformed
searchReactions(false); // exit = false
}//GEN-LAST:event_jMenuSearchActionPerformed
private void jMenuExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuExitActionPerformed
searchReactions(true); // exit = true
}//GEN-LAST:event_jMenuExitActionPerformed
private void jMenuQuitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuQuitActionPerformed
queryToQuit = false;
end_program();
}//GEN-LAST:event_jMenuQuitActionPerformed
private void jCheckBoxMenuDebugActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxMenuDebugActionPerformed
if(pd.msgFrame != null) {
pd.msgFrame.setVisible(jCheckBoxMenuDebug.isSelected());
}
}//GEN-LAST:event_jCheckBoxMenuDebugActionPerformed
private void jMenuDBFilesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuDBFilesActionPerformed
setCursorWait();
if(pc.dbg) {System.out.println("--- jMenuDBFiles(event)");}
dbND = new DBnamesDialog(this, true, pc, pd.dataBasesList, pd.pathDatabaseFiles, pd.elemComp);
dbND.setVisible(true); //this will wait for the modal dialog to close
if(!dbND.cancel) {
//---- read the elements/components for the databases
LibDB.getElements(this, pc.dbg, pd.dataBasesList, pd.elemComp);
pd.foundH2O = false;
for (String[] elemComp : pd.elemComp) {
if (Util.isWater(elemComp[1])) {pd.foundH2O = true; break;}
}
//---- show which elements have data
setupFrame();
int i = modelSelectedComps.size()-1;
while(i>0) {
componentClick(i);
i = modelSelectedComps.size()-1;
}
}
dbND.dispose();
dbND = null;
//this.setVisible(true);
setCursorDef();
bringToFront();
}//GEN-LAST:event_jMenuDBFilesActionPerformed
private void jMenuLocateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuLocateActionPerformed
setCursorWait();
String fn = Util.getOpenFileName(this, pc.progName, true, "Select a program:",
1, pd.diagramProgr, null);
if(fn == null || fn.length() <=0) {setCursorDef(); return;}
java.io.File f = new java.io.File(fn);
fn = f.getName();
if(!fn.toLowerCase().startsWith("spana") && !fn.toLowerCase().startsWith("medusa")) {
String msg = "Warning: \""+fn+"\""+nl+"is NOT the \"Spana\" program."+nl+
"(the program to make diagrams)";
javax.swing.JOptionPane.showMessageDialog(this, msg, pc.progName, javax.swing.JOptionPane.WARNING_MESSAGE);
MsgExceptn.msg(msg);
} //is the file name "spana"?
try {fn = f.getCanonicalPath();} catch (java.io.IOException ex) {fn = null;}
if(fn == null) {
try {fn = f.getAbsolutePath();} catch (Exception ex) {fn = f.getPath();}
}
pd.diagramProgr = fn;
if(pc.dbg) {System.out.println("--- Path to diagram-making program: "+pd.diagramProgr);}
setCursorDef();
}//GEN-LAST:event_jMenuLocateActionPerformed
private void jMenuAddDataActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuAddDataActionPerformed
setCursorWait();
if(pc.dbg) {System.out.println("--- jMenuAddData(event)");}
if(addData != null) {
String msg = "Programming error: addData != null in Add Data Menu";
MsgExceptn.showErrMsg(this,msg,1);
setCursorDef();
return;
}
jMenuAddData.setEnabled(false);
Thread adShow = new Thread() {@Override public void run(){
addData = new FrameAddData(pc, pd, dbf);
dbf.setVisible(false);
addData.start();
addData.waitFor();
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
jMenuAddData.setEnabled(true);
addData = null;
//---- read the elements/components for the databases
LibDB.getElements(dbf, pc.dbg, pd.dataBasesList, pd.elemComp);
pd.foundH2O = false;
for(int i=0; i < pd.elemComp.size(); i++) {
if(Util.isWater(pd.elemComp.get(i)[1])) {pd.foundH2O = true; break;}
}
//---- show which elements have data
setupFrame();
bringToFront();
setCursorDef();
}}); //invokeLater(Runnable)
}};//new Thread
adShow.start();
}//GEN-LAST:event_jMenuAddDataActionPerformed
private void jMenuSingleCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuSingleCActionPerformed
if(singleComp != null) {MsgExceptn.exception("Programming error: singleComp != null in Single Component Menu"); return;}
setCursorWait();
jMenuSingleC.setEnabled(false);
Thread scShow = new Thread() {@Override public void run(){
singleComp = new FrameSingleComponent(dbf, pc, pd);
singleComp.start();
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
setCursorDef();
dbf.setVisible(false);
}});
singleComp.waitFor();
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
jMenuSingleC.setEnabled(true);
singleComp = null;
bringToFront();
}}); //invokeLater(Runnable)
}};//new Thread
scShow.start();
}//GEN-LAST:event_jMenuSingleCActionPerformed
private void jMenuHelpAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuHelpAboutActionPerformed
this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
jMenuHelpAbout.setEnabled(false);
// -- although HelpAboutDB is a frame, it behaves almost as a modal dialog
// because it is brought to focus when "this" gains focus
Thread hlp = new Thread() {@Override public void run(){
dbf.helpAboutFrame = new HelpAboutDB(pc.pathAPP, pd, pc.saveIniFileToApplicationPathOnly);
dbf.helpAboutFrame.start();
dbf.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
dbf.helpAboutFrame.waitFor();
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
dbf.helpAboutFrame = null;
jMenuHelpAbout.setEnabled(true);
bringToFront();
}}); //invokeLater(Runnable)
}};//new Thread
hlp.start();
}//GEN-LAST:event_jMenuHelpAboutActionPerformed
private void jMenuHelpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuHelpActionPerformed
setCursorWait();
Thread hlp = new Thread() {@Override public void run(){
String[] a = {"DB_0_Main_htm"};
lib.huvud.RunProgr.runProgramInProcess(null,ProgramConf.HELP_JAR,a,false,pc.dbg,pc.pathAPP);
try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec
catch (InterruptedException e) {}
setCursorDef();
}};//new Thread
hlp.start();
}//GEN-LAST:event_jMenuHelpActionPerformed
private void jListAvailableCompsFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListAvailableCompsFocusGained
if(modelAvailableComps.getSize()>0) {
int i = jListAvailableComps.getSelectedIndex();
if(i<0) {jListAvailableComps.setSelectedIndex(0);}
}
jListSelectedComps.clearSelection();
if(jListComplexes.isVisible()) {jListComplexes.clearSelection();} else {lastReactionInFocus = -1;}
}//GEN-LAST:event_jListAvailableCompsFocusGained
private void jListAvailableCompsFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListAvailableCompsFocusLost
jListAvailableComps.clearSelection();
}//GEN-LAST:event_jListAvailableCompsFocusLost
private void jListAvailableCompsKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jListAvailableCompsKeyTyped
if(evt.getKeyChar() == java.awt.event.KeyEvent.VK_SPACE) {
evt.consume();
availableComponentClick();
}
}//GEN-LAST:event_jListAvailableCompsKeyTyped
private void jListAvailableCompsMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListAvailableCompsMouseMoved
java.awt.Point p = evt.getPoint();
int i = jListAvailableComps.locationToIndex(p);
if(i>=0) {
java.awt.Rectangle r = jListAvailableComps.getCellBounds(i, i);
if(p.y < r.y || p.y > r.y+r.height) {i=-1;}
if(i>=0) {
jLabelLeft.setText(availableComponentsNames.get(i));
} else {jLabelLeft.setText(" ");}
}
}//GEN-LAST:event_jListAvailableCompsMouseMoved
private void jListAvailableCompsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListAvailableCompsMouseClicked
java.awt.Point p = evt.getPoint();
int i = jListAvailableComps.locationToIndex(p);
if(i>=0) {
java.awt.Rectangle r = jListAvailableComps.getCellBounds(i, i);
if(p.y < r.y || p.y > r.y+r.height) {return;}
availableComponentClick(i);
}
}//GEN-LAST:event_jListAvailableCompsMouseClicked
private void jListAvailableCompsMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListAvailableCompsMouseExited
jLabelLeft.setText(originalJLabelLeft.toString());
}//GEN-LAST:event_jListAvailableCompsMouseExited
private void jListAvailableCompsValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jListAvailableCompsValueChanged
int i = jListAvailableComps.getSelectedIndex();
if(i>=0) {
jLabelLeft.setText(availableComponentsNames.get(i));
} else {
jLabelLeft.setText(originalJLabelLeft.toString());
}
}//GEN-LAST:event_jListAvailableCompsValueChanged
private void jListSelectedCompsFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListSelectedCompsFocusGained
jListAvailableComps.clearSelection();
if(jListComplexes.isVisible()) {jListComplexes.clearSelection();}
if(modelSelectedComps.getSize()>0) {
int i = jListSelectedComps.getSelectedIndex();
if(i>=0) {
//jListSelectedComps.ensureIndexIsVisible(i);
lastReactionInFocus = i;
} else {
jListSelectedComps.setSelectedIndex(0);
lastReactionInFocus = 0;
}
}
}//GEN-LAST:event_jListSelectedCompsFocusGained
private void jListSelectedCompsFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListSelectedCompsFocusLost
jListSelectedComps.clearSelection();
if(modelSelectedComps.size() <=0) {
jMenuExit.setText("Search and Exit");
jMenuExit.setEnabled(false);
jMenuSearch.setEnabled(false);
}
jLabelMid.setText(" ");
}//GEN-LAST:event_jListSelectedCompsFocusLost
private void jListSelectedCompsKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jListSelectedCompsKeyTyped
if(evt.getKeyChar() == java.awt.event.KeyEvent.VK_BACK_SPACE ||
evt.getKeyChar() == java.awt.event.KeyEvent.VK_DELETE) {
evt.consume();
componentClick();
}
}//GEN-LAST:event_jListSelectedCompsKeyTyped
private void jListSelectedCompsMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListSelectedCompsMouseMoved
java.awt.Point p = evt.getPoint();
int i = jListSelectedComps.locationToIndex(p);
if(i>=0) {
java.awt.Rectangle r = jListSelectedComps.getCellBounds(i, i);
if(p.y < r.y || p.y > r.y+r.height) {i=-1;}
if(i>=0) {jLabelMid.setText(componentsNames.get(i));} else {jLabelMid.setText(" ");}
}
}//GEN-LAST:event_jListSelectedCompsMouseMoved
private void jListSelectedCompsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListSelectedCompsMouseClicked
java.awt.Point p = evt.getPoint();
int i = jListSelectedComps.locationToIndex(p);
if(i>=0) {
java.awt.Rectangle r = jListSelectedComps.getCellBounds(i, i);
if(p.y < r.y || p.y > r.y+r.height) {i=-1;}
componentClick(i);
}
}//GEN-LAST:event_jListSelectedCompsMouseClicked
private void jListSelectedCompsMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListSelectedCompsMouseExited
jLabelMid.setText(" ");
}//GEN-LAST:event_jListSelectedCompsMouseExited
private void jListSelectedCompsValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jListSelectedCompsValueChanged
int i = jListSelectedComps.getSelectedIndex();
if(i>=0) {jLabelMid.setText(componentsNames.get(i));} else {jLabelMid.setText(" ");}
}//GEN-LAST:event_jListSelectedCompsValueChanged
private void jListComplexesFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListComplexesFocusGained
jListAvailableComps.clearSelection();
jListSelectedComps.clearSelection();
if(!jPopupMenu.isVisible() && modelComplexes.getSize()>0) {
int i = lastReactionInFocus;
if(i < 0) {i = jListComplexes.getSelectedIndex();}
if(i>=0) {
jListComplexes.ensureIndexIsVisible(i);
//jListComplexes.setSelectedIndex(i);
lastReactionInFocus = i;
} else {
jListComplexes.setSelectedIndex(0);
lastReactionInFocus = 0;
}
}
}//GEN-LAST:event_jListComplexesFocusGained
private void jListComplexesFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jListComplexesFocusLost
if(!jPopupMenu.isVisible()) {jListComplexes.clearSelection();}
}//GEN-LAST:event_jListComplexesFocusLost
private void jListComplexesKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jListComplexesKeyTyped
if(evt.getKeyChar() == java.awt.event.KeyEvent.VK_SPACE) {
int i = jListComplexes.getSelectedIndex();
if(i>=0) {
lastReactionInFocus = i;
jListComplexes.ensureIndexIsVisible(i);
jListComplexes.setSelectedIndex(i);
setTextLabelRight(" ");
java.awt.Rectangle r = jListComplexes.getCellBounds(i, i);
jPopupMenu.show(jListComplexes, (r.x+r.width/2), (r.y+r.height/2));
}//if i>=0
isPopup = false;
} // if "space"
else if(evt.getKeyChar() == java.awt.event.KeyEvent.VK_BACK_SPACE ||
evt.getKeyChar() == java.awt.event.KeyEvent.VK_DELETE) {
evt.consume();
complexClick();
}
}//GEN-LAST:event_jListComplexesKeyTyped
private void jListComplexesMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListComplexesMouseEntered
if(jLabelLeft.getText().trim().length()>0) {
originalJLabelLeft.replace(0, originalJLabelLeft.length(), jLabelLeft.getText());
jLabelLeft.setText(" ");
}
jLabelMid.setText(" ");
}//GEN-LAST:event_jListComplexesMouseEntered
private void jListComplexesMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListComplexesMouseMoved
if(jPopupMenu.isVisible()) {return;}
java.awt.Point p = evt.getPoint();
int i = jListComplexes.locationToIndex(p);
if(i>=0) {
java.awt.Rectangle r = jListComplexes.getCellBounds(i, i);
if(p.y < r.y || p.y > r.y+r.height) {i=-1;}
String rt;
if(i>=0) {
rt = srch.dat.get(i).reactionTextWithLogK(pd.temperature_C, pd.pressure_bar);
} else {
rt = " ";
}
setTextLabelRight(rt);
}
}//GEN-LAST:event_jListComplexesMouseMoved
private void jListComplexesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListComplexesMouseClicked
int i = -1;
if(isPopup || evt.getClickCount() >1) {
java.awt.Point p = evt.getPoint();
i = jListComplexes.locationToIndex(p);
if(i>=0) {
java.awt.Rectangle r = jListComplexes.getCellBounds(i, i);
if(p.y < r.y || p.y > r.y+r.height) {i=-1;}
}
}
//if(pc.dbg) {System.out.println("jListComplexesMouseClicked("+i+")");}
if(i>=0 && i < modelComplexes.size()) {
lastReactionInFocus = i;
if(isPopup) {
jListComplexes.ensureIndexIsVisible(i);
jListComplexes.setSelectedIndex(i);
setTextLabelRight(" ");
jPopupMenu.show(jListComplexes, evt.getX(), evt.getY());
}
else if(evt.getClickCount() >1) {
ShowDetailsDialog dd = new ShowDetailsDialog(this, true, srch.dat.get(i),
pd.temperature_C, pd.pressure_bar, pd.references);
dd.setVisible(true);
}
}//if i>=0
isPopup = false;
}//GEN-LAST:event_jListComplexesMouseClicked
private void jListComplexesMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListComplexesMouseExited
setTextLabelRight(" ");
jLabelLeft.setText(originalJLabelLeft.toString());
}//GEN-LAST:event_jListComplexesMouseExited
private void jMenuItemDelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemDelActionPerformed
complexClick();
}//GEN-LAST:event_jMenuItemDelActionPerformed
private void jMenuItemCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemCancelActionPerformed
jPopupMenu.setVisible(false);
}//GEN-LAST:event_jMenuItemCancelActionPerformed
private void jListComplexesMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListComplexesMousePressed
if(evt.isPopupTrigger()) {isPopup = true;}
}//GEN-LAST:event_jListComplexesMousePressed
private void jListComplexesMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListComplexesMouseReleased
if(evt.isPopupTrigger()) {isPopup = true;}
}//GEN-LAST:event_jListComplexesMouseReleased
private void jMenuAdvH2OActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuAdvH2OActionPerformed
setCursorWait();
pd.includeH2O = askH2O(this, pc.progName, pd.includeH2O);
bringToFront();
setCursorDef();
}//GEN-LAST:event_jMenuAdvH2OActionPerformed
private void jMenuItemTemperatureActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemTemperatureActionPerformed
SetTempPressDialog tDialog = new SetTempPressDialog(dbf, true, pc, pd);
setTitle();
if(pc.dbg) {
System.out.println("--- temperature changed to = "+pd.temperature_C+nl+
" pressure to = "+(float)pd.pressure_bar);
}
if(srch != null) {
srch.temperature_C = pd.temperature_C;
srch.pressure_bar = pd.pressure_bar;
if(pc.dbg) {
System.out.println("setting temperature of search results = "+srch.temperature_C+
", pressure = "+srch.pressure_bar);
}
}
}//GEN-LAST:event_jMenuItemTemperatureActionPerformed
private void jMenuItemDataActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemDataActionPerformed
int index = jListComplexes.getSelectedIndex();
lastReactionInFocus = index;
if(pc.dbg) {System.out.println("jMenuItemData("+index+")");}
if(index <0 || index >= modelComplexes.size()) {return;}
if(pc.dbg) {System.out.println("Show data(s) for: \""+srch.dat.get(index).name.trim()+"\"");}
ShowDetailsDialog dd = new ShowDetailsDialog(this, true, srch.dat.get(index),
pd.temperature_C, pd.pressure_bar, pd.references);
dd.setVisible(true);
}//GEN-LAST:event_jMenuItemDataActionPerformed
private void jLabelTemperatureMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelTemperatureMouseClicked
if(evt.getClickCount() >1 // double-click
&& (pd.temperature_C <24.99 || pd.temperature_C >25.01
|| pd.pressure_bar >1.02)) {
pd.temperature_C = 25;
pd.pressure_bar = 1.;
setTitle();
if(pc.dbg) {
System.out.println("--- temperature changed to = "+pd.temperature_C+", p = "+(float)pd.pressure_bar+" bar");
}
if(srch != null) {
srch.temperature_C = pd.temperature_C;
srch.pressure_bar = pd.pressure_bar;
if(pc.dbg) {
System.out.println(" setting temperature of search results = "+srch.temperature_C+", p = "+srch.pressure_bar+" bar");
}
}
}
}//GEN-LAST:event_jLabelTemperatureMouseClicked
private void jMenuRefsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuRefsActionPerformed
setCursorWait();
Thread asr = new Thread() {@Override public void run(){
//---- start the program on a separate process
lib.huvud.RunProgr.runProgramInProcess(null,"AddShowReferences.jar",null,false,pc.dbg,pc.pathAPP);
try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec
catch (InterruptedException e) {}
setCursorDef();
}};//new Thread
asr.start();
}//GEN-LAST:event_jMenuRefsActionPerformed
private void jMenuMaintenanceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuMaintenanceActionPerformed
setCursorWait();
Thread dm = new Thread() {@Override public void run(){
//---- start the program on a separate process
lib.huvud.RunProgr.runProgramInProcess(null,"DataMaintenance.jar",null,false,pc.dbg,pc.pathAPP);
try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec
catch (InterruptedException e) {}
setCursorDef();
}};//new Thread
dm.start();
}//GEN-LAST:event_jMenuMaintenanceActionPerformed
private void jCheckBoxMenuVerboseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxMenuVerboseActionPerformed
pc.dbg = jCheckBoxMenuVerbose.isSelected();
}//GEN-LAST:event_jCheckBoxMenuVerboseActionPerformed
private void jMenuAdvRedoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuAdvRedoxActionPerformed
boolean askingBeforeSearch = false;
AskRedox ask = new AskRedox(this, true, pc, pd, askingBeforeSearch, modelSelectedComps);
ask.start();
}//GEN-LAST:event_jMenuAdvRedoxActionPerformed
private void jMenuAdvSolidsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuAdvSolidsActionPerformed
boolean askingBeforeSearch = false;
AskSolids askSolids = new AskSolids(this, true, pc, pd, askingBeforeSearch);
askSolids.start();
}//GEN-LAST:event_jMenuAdvSolidsActionPerformed
private void jLabelPressureMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelPressureMouseClicked
if(evt.getClickCount() >1 // double-click
&& (pd.temperature_C <24.99 || pd.temperature_C >25.01
|| pd.pressure_bar >1.02)) {
pd.temperature_C = 25;
pd.pressure_bar = 1.;
setTitle();
if(pc.dbg) {
System.out.println("--- temperature changed to = "+pd.temperature_C+", p = "+(float)pd.pressure_bar+" bar");
}
if(srch != null) {
srch.temperature_C = pd.temperature_C;
srch.pressure_bar = pd.pressure_bar;
if(pc.dbg) {
System.out.println(" setting temperature of search results = "+srch.temperature_C+", p = "+srch.pressure_bar+" bar");
}
}
}
}//GEN-LAST:event_jLabelPressureMouseClicked
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Methods">
//<editor-fold defaultstate="collapsed" desc="end_program()">
void end_program() {
if(pc.dbg){System.out.println(pc.progName+"-- end_program()");}
if(addData != null) {
addData.bringToFront();
if(!addData.queryClose()) {return;}
}
if((doneSomeWork && queryToQuit) || searchingComplexes) {
bringToFront();
Object[] opt = {"Yes", "Cancel"};
int m = javax.swing.JOptionPane.showOptionDialog(this,
"Quit?",
pc.progName, javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[1]);
if(m != javax.swing.JOptionPane.YES_OPTION) {return;}
} //if query
if(helpAboutFrame != null) {helpAboutFrame.closeWindow();}
if(fileIniUser != null) {saveIni(fileIniUser);} else if(fileIni != null) {saveIni(fileIni);}
this.dispose();
dbf = null;
OneInstance.endCheckOtherInstances();
if(pc.dbg) {MsgExceptn.showErrMsg(this, "DataBase - Debug mode"+nl+"System.exit(0);", 3);}
System.exit(0);
} // end_program()
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="bringToFront()">
public void bringToFront() {
if(this != null) {
if(addData != null) {
addData.bringToFront();
return;
} else if(singleComp != null) {
singleComp.bringToFront();
return;
} else if(dbND != null) {
dbND.bringToFront();
return;
}
java.awt.EventQueue.invokeLater(new Runnable() {
@Override public void run() {
setVisible(true);
if((getExtendedState() & javax.swing.JFrame.ICONIFIED) // minimised?
== javax.swing.JFrame.ICONIFIED) {
setExtendedState(javax.swing.JFrame.NORMAL);
} // if minimized
setAlwaysOnTop(true);
toFront();
requestFocus();
setAlwaysOnTop(false);
pd.msgFrame.setParentFrame(FrameDBmain.this);
if(windowSize == null) {
// get the size after the window is made visible
windowSize = getSize();
}
}
});
} // if this != null
} // bringToFront()
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="askH2O">
/** Show a JOptionPane asking the user if H2O should be included
* <p>The JOptionPane responds to both the TAB key and to
* the arrow keys in the keyboard
* @return true if the user clicks the OK button and the "include" radio button is selected;
* false if either a) the user chooses "Cancel" or b) the dialog is closed, or
* c) if OK is clicked and the "do not include" radio button is selected */
private static boolean askH2O(java.awt.Frame parent, final String title, final boolean includeH2O) {
//-- crate a group of radio buttons
javax.swing.JLabel label = new javax.swing.JLabel("Water (H2O):");
final javax.swing.JRadioButton radio1 = new javax.swing.JRadioButton("Include H2O as a component in output files");
//javax.swing.SwingUtilities.invokeLater(new Runnable() {public void run() { radio1.requestFocusInWindow(); }});
javax.swing.JRadioButton radio2 = new javax.swing.JRadioButton("do Not include H2O");
radio1.setMnemonic('i');
radio2.setMnemonic('n');
javax.swing.ButtonGroup group = new javax.swing.ButtonGroup();
group.add(radio1); group.add(radio2);
radio1.setSelected(includeH2O);
radio2.setSelected(!includeH2O);
//-- create the object to display in the JOptionPane
Object[] array = {label,radio1,radio2};
//-- the option pane
final Object[] options = {"Ok","Cancel"};
final javax.swing.JOptionPane pane = new javax.swing.JOptionPane(array,
javax.swing.JOptionPane.PLAIN_MESSAGE, javax.swing.JOptionPane.OK_CANCEL_OPTION, null, options, options[0]);
//-- bind to the arrow keys
java.util.Set<java.awt.AWTKeyStroke> keys = new java.util.HashSet<java.awt.AWTKeyStroke>(
pane.getFocusTraversalKeys(java.awt.KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS));
keys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_RIGHT, 0));
keys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_DOWN, 0));
pane.setFocusTraversalKeys(java.awt.KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, keys);
keys = new java.util.HashSet<java.awt.AWTKeyStroke>(
pane.getFocusTraversalKeys(java.awt.KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS));
keys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_LEFT, 0));
keys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_UP, 0));
pane.setFocusTraversalKeys(java.awt.KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, keys);
//-- create a dialog
final javax.swing.JDialog dialog = pane.createDialog(parent, title);
//--- Alt-Q
javax.swing.KeyStroke altQKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK, false);
dialog.getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altQKeyStroke,"ALT_Q");
javax.swing.Action altQAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
pane.setValue(options[1]);
dialog.setVisible(false);
dialog.dispose();
}};
dialog.getRootPane().getActionMap().put("ALT_Q", altQAction);
//--- Alt-X
javax.swing.KeyStroke altXKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK, false);
dialog.getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altXKeyStroke,"ALT_X");
javax.swing.Action altXAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
pane.setValue(options[0]);
dialog.setVisible(false);
dialog.dispose();
}};
dialog.getRootPane().getActionMap().put("ALT_X", altXAction);
//--- F1 for help
javax.swing.KeyStroke f1KeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1,0, false);
dialog.getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(f1KeyStroke,"F1");
javax.swing.Action f1Action = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
FrameDBmain.getInstance().setCursorWait();
dialog.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
Thread hlp = new Thread() {@Override public void run(){
String[] a = {"DB_H2O_htm"};
lib.huvud.RunProgr.runProgramInProcess(null,ProgramConf.HELP_JAR,a,false,dbf.pc.dbg,dbf.pc.pathAPP);
try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec
catch (InterruptedException e) {}
dialog.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
FrameDBmain.getInstance().setCursorDef();
}};//new Thread
hlp.start();
}};
dialog.getRootPane().getActionMap().put("F1", f1Action);
//--- Alt-H help
javax.swing.KeyStroke altHKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_H, java.awt.event.InputEvent.ALT_MASK, false);
dialog.getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altHKeyStroke,"ALT_H");
dialog.getRootPane().getActionMap().put("ALT_H", f1Action);
//-- show the dialog
dialog.setVisible(true);
//-- The return value
int res = javax.swing.JOptionPane.CLOSED_OPTION; //default return value, signals nothing selected
// Get the selected Value
Object selectedValue = pane.getValue();
// If none, then nothing selected
if (selectedValue != null) {
for (int i = 0, n = options.length; i < n; i++) {
if (options[i].equals(selectedValue)) {res = i; break;}
}
}
// the user pressed the OK button?
if(res != javax.swing.JOptionPane.OK_OPTION) {return includeH2O;}
return radio1.isSelected();
} //askH2O
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="availableComponentClick">
private void availableComponentClick() {
int index = jListAvailableComps.getSelectedIndex();
availableComponentClick(index);
}
private void availableComponentClick(int index) {
if(index < 0 || index >= modelAvailableComps.size()) {return;}
//if(pc.dbg) {System.out.println("availableComponentClick("+index+")");}
boolean alreadyThere = false;
if(modelSelectedComps.size() >0) {
for(int i = 0; i < modelSelectedComps.size(); i++) {
if(modelAvailableComps.get(index).equals(modelSelectedComps.get(i))) {alreadyThere = true; break;}
}
}
if(!alreadyThere) {
jLabelComplexes.setVisible(false);
jScrollPaneComplexes.setVisible(false);
jLabel_cr_solids.setText(" ");
setTextLabelRight(" ");
int position;
if(modelAvailableComps.get(index).equals("H+")) {
position = 0;
} else if(modelAvailableComps.get(index).equals("e-")) {
position = 0;
if(modelSelectedComps.size() >0 && modelSelectedComps.get(0).equals("H+")) {position = 1;}
} else {
if(Util.isSolid(modelAvailableComps.get(index).toString())) {
solidSelectedComps++;
position = -1;
} else { //not a solid
if(solidSelectedComps >0) {
position = modelSelectedComps.size() - solidSelectedComps;
} else { //no selected solid components yet
position = -1;
}
} //solid?
} //not H+ or e-
if(position == -1) {position = modelSelectedComps.size();}
modelSelectedComps.add(position, modelAvailableComps.get(index));
componentsNames.add(position, availableComponentsNames.get(index));
doneSomeWork = true;
} //if not alreadyThere
jListAvailableComps.clearSelection();
jMenuExit.setText("Search and Exit");
if(modelSelectedComps.size() >0) {
jMenuExit.setEnabled(true);
jMenuSearch.setEnabled(true);
} else {
jMenuExit.setEnabled(false);
jMenuSearch.setEnabled(false);
}
} //availableComponentClick
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="askRemoveSpecies(species)">
private boolean askRemoveSpecies(String species) {
if(species == null || species.length() <= 0) {return true;}
if(pc.dbg) {System.out.println("askRemoveSpecies \""+species+"\"");}
Object[] opt = {"Yes", "Cancel"};
int m = javax.swing.JOptionPane.showOptionDialog(this,
"Remove \""+species+"\" ?",
pc.progName, javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[1]);
if(m == javax.swing.JOptionPane.YES_OPTION) {
String msg = "Please note:"+nl;
if(Util.isProton(species)) {
msg = msg +
"Hydrogen ions are always present in aqueous solutions ..."+nl+
"Removing \"H+\" will probably result in wrong diagrams !";
} else if(species.equals("OH-")) {
msg = msg +
"Hydroxide ions are always present in aqueous solutions ..."+nl+
"Removing \"OH-\" will probably result in wrong diagrams !";
} else {
msg = msg + "Removing a species may result in wrong diagrams !";
}
msg = msg +nl+nl+ "Remove \""+species+"\" anyway?";
m = javax.swing.JOptionPane.showOptionDialog(this, msg,
pc.progName, javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.ERROR_MESSAGE, null, opt, opt[1]);
return m == javax.swing.JOptionPane.YES_OPTION;
} else {return false;}
} //askRemoveSpecies(species)
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="complexClick">
private void complexClick() {
int index = jListComplexes.getSelectedIndex();
complexClick(index);
}
private void complexClick(int index) {
if(index <0 || index >= modelComplexes.size()) {return;}
if(pc.dbg) {System.out.println("complexClick index="+index);}
String species = modelComplexes.get(index).toString();
if(!askRemoveSpecies(species)) {return;}
if(Util.isSolid(species)) {srch.nf--;} else {srch.nx--;}
modelComplexes.remove(index);
srch.dat.remove(index);
//jListComplexes.clearSelection();
//jMenuExit.setText("Search and Exit");
jMenuExit.setEnabled(true);
jMenuSearch.setEnabled(true);
if(modelComplexes.size() <=0) {
jScrollPaneComplexes.setVisible(false);
jLabel_cr_solids.setText(" ");
jLabelComplexes.setVisible(false);
setTextLabelRight(" ");
}
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="componentClick">
private void componentClick() {
int index = jListSelectedComps.getSelectedIndex();
componentClick(index);
}
private void componentClick(int index) {
if(index <0 || index >= modelSelectedComps.size()) {return;}
String species = modelSelectedComps.get(index).toString();
if(pc.dbg) {System.out.println("componentClick index="+index+" species = \""+species+"\"");}
if(Util.isProton(species)) {
if(!askRemoveSpecies(species)) {return;}
} // H+?
if(jListComplexes.isShowing()) { //clear any search
doneSomeWork = true;
modelComplexes.clear();
jScrollPaneComplexes.setVisible(false);
lastReactionInFocus = -1;
jLabel_cr_solids.setText(" ");
jLabelComplexes.setVisible(false);
setTextLabelRight(" ");
}
if(Util.isSolid(species)) {solidSelectedComps--;}
modelSelectedComps.remove(index);
componentsNames.remove(index);
jListSelectedComps.clearSelection();
jMenuExit.setText("Search and Exit");
if(modelSelectedComps.size() >0) {
jMenuExit.setEnabled(true);
jMenuSearch.setEnabled(true);
} else {
jMenuExit.setEnabled(false);
jMenuSearch.setEnabled(false);
}
} //componentClick()
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="disclaimerAccepted()">
void disclaimerAccepted() {
if(pc.dbg) {System.out.println("--- disclaimerAccepted()");}
if(noDataBasesFound) {jMenuDBFiles.doClick();}
LibDB.getElements(dbf, pc.dbg, pd.dataBasesList, pd.elemComp);
pd.foundH2O = false;
for(String[] elemComp : pd.elemComp) {
if (Util.isWater(elemComp[1])) {
pd.foundH2O = true; break;
}
}
setupFrame();
jMenuH.setEnabled(true);
jMenuOptions.setEnabled(true);
pd.references = new References();
String r;
String dir = pc.pathAPP;
if(dir != null) {
if(dir.endsWith(SLASH)) {dir = dir.substring(0, dir.length()-1);}
r = dir + SLASH + "References.txt";
} else {r = "References.txt";}
if(!pd.references.readRefsFile(r, pc.dbg)) {pd.references = null;}
jCheckBoxMenuVerbose.setSelected(pc.dbg);
jMenuAdvanced.setEnabled(advancedMenu);
jMenuAdvanced.setVisible(advancedMenu);
if(advancedMenu) {
java.io.File f = new java.io.File(dir+SLASH+"DataMaintenance.jar");
jMenuMaintenance.setEnabled(f.exists());
f = new java.io.File(dir+SLASH+"AddShowReferences.jar");
jMenuRefs.setEnabled(f.exists());
}
jMenuAdvSolids.setEnabled(advancedMenu || pd.allSolidsAsk || pd.allSolids != 0);
jMenuAdvSolids.setVisible(advancedMenu || pd.allSolidsAsk || pd.allSolids != 0);
jMenuAdvRedox.setEnabled(advancedMenu || pd.redoxAsk || !pd.redoxN || !pd.redoxP || !pd.redoxS);
jMenuAdvRedox.setVisible(advancedMenu || pd.redoxAsk || !pd.redoxN || !pd.redoxP || !pd.redoxS);
if(pc.dbg) {System.out.println("--- disclaimerAccepted() end.");}
//---- deal with command-line arguments
if(commandArgs != null && commandArgs.length > 0){
if(pc.dbg) {System.out.println("--- Dealing with command line arguments");}
Thread dArg = new Thread() {@Override public void run(){
for(String commandArg : commandArgs) {dispatchArg(commandArg);}
// add path to output file name if needed
if(outputDataFile != null && !outputDataFile.contains(SLASH)) {
String dir = pc.pathDef.toString();
if(dir.endsWith(SLASH)) {dir = dir.substring(0, dir.length()-1);}
java.io.File f = new java.io.File(dir + SLASH + outputDataFile);
outputDataFile = f.getAbsolutePath();
}
}}; //new Thread
dArg.start();
} // if args != null
setCursorDef();
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="dispatchArg(String)">
/** Execute the command-line arguments (one by one)
* @param arg String containing a command-line argument */
public void dispatchArg(String arg) {
if(arg == null || arg.trim().length() <=0) {return;}
//these are handled in "main"
System.out.println("Command-line argument = "+arg);
if(arg.equals("-dbg") || arg.equals("/dbg")) {return;}
if(arg.equals("-?") || arg.equals("/?") || arg.equals("?")
|| arg.equals("-help") || arg.equals("--help")) {
printInstructions();
msgFrame.setVisible(true);
return;
}
if(arg.length() > 2 && arg.startsWith("\"") && arg.endsWith("\"")) {
arg = arg.substring(1, arg.length());
}
if(arg.length() > 4 && arg.toLowerCase().endsWith(".dat")) {
java.io.File datFile = new java.io.File(arg);
if(datFile.getName().length() <= 4) {
MsgExceptn.exception("Error: file name must have at least one character");
return;
}
if(!arg.contains(SLASH)) {
outputDataFile = arg;
System.out.println("Default output file: \""+arg+"\"");
return;
}
if(datFile.getParentFile() != null && !datFile.getParentFile().exists()) {
String msg = "Error: \""+datFile.getAbsolutePath()+"\""+nl+
" file directory does not exist.";
MsgExceptn.exception(msg);
return;
}
if(datFile.exists() && (!datFile.canWrite() || !datFile.setWritable(true))) {
String msg = "Error - file is read-only:"+nl+" \""+datFile.getAbsolutePath()+"\"";
MsgExceptn.exception(msg);
if(!this.isVisible()) {
MsgExceptn.showErrMsg(dbf, msg, 1);
} else {
javax.swing.JOptionPane.showMessageDialog(this, msg, pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE);
}
return;
}
try{outputDataFile = datFile.getCanonicalPath();}
catch(java.io.IOException ex) {
try{outputDataFile = datFile.getAbsolutePath();}
catch(Exception e) {outputDataFile = datFile.getPath();}
}
System.out.println("Default output file: \""+outputDataFile+"\"");
return;
} else { // does not end with ".dat"
arg = arg.trim();
java.io.File d = new java.io.File(arg);
if(d.exists()) {
pc.setPathDef(d);
System.out.println("Default path: \""+pc.pathDef.toString()+"\"");
return;
} else if(arg.contains(SLASH)) {
String msg = "Error: \""+d.getAbsolutePath()+"\""+nl+
" directory does not exist.";
MsgExceptn.exception(msg);
return;
}
}
String msg = "Error: bad format for"+nl+
" command-line argument: \""+arg+"\"";
System.out.println(msg);
printInstructions();
msgFrame.setVisible(true);
javax.swing.JOptionPane.showMessageDialog(this,msg,
pc.progName,javax.swing.JOptionPane.ERROR_MESSAGE);
setCursorWait();
Thread hlp = new Thread() {@Override public void run(){
String[] a = {"S_Batch_htm"};
lib.huvud.RunProgr.runProgramInProcess(null,ProgramConf.HELP_JAR,a,false,dbf.pc.dbg,dbf.pc.pathAPP);
try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec
catch (InterruptedException e) {}
setCursorDef();
}};//new Thread
hlp.start();
} // dispatchArg(arg)
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="getAvailableComponents(i)">
private void getAvailableComponents(int index) {
if(index < 0 || index >= buttons.length) {return;}
modelAvailableComps.clear();
availableComponentsNames.clear();
String element = LibDB.elementSymb[index];
String[] elemComp;
for(int i = 0; i < pd.elemComp.size(); i++) {
elemComp = pd.elemComp.get(i);
if(elemComp[0].equals(element)) {
modelAvailableComps.addElement(elemComp[1]);
availableComponentsNames.add(elemComp[2]);
}
}
jLabelAvailableComp.setText("<html><u>A</u>vailable for "+element+":</html>");
} //getAvailableComponents(i)
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="menuOptionsEnable">
private void menuOptionsEnable(boolean b) {
//jMenuSolids.setEnabled(b);
jMenuLocate.setEnabled(b);
jMenuData.setEnabled(b);
if(pd.foundH2O) {jMenuAdvH2O.setEnabled(b);}
} //menuOptionsEnable
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="printInstructions">
public static void printInstructions() {
System.out.flush();
String msg = LINE+nl+"Possible commands are:"+nl+
" -dbg (output debugging information to the messages window)"+nl+
" data-file-name (create a data file, name must end with \".dat\","+nl+
" it may contain a directory part)"+nl+
" directory-name (create a data file in the given directory. A file name"+nl+
" will be requested from the user. If a file name"+nl+
" with a directory is also given, it takes precedence)"+nl+
"Enclose file or path names with double quotes (\"\") it they contain blank space."+nl+
"Example: java -jar DataBase.jar \"projects\\Fe\\test 25.dat\""+nl+LINE;
System.out.println(msg);
System.out.flush();
} //printInstructions()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="read-write INI file">
//<editor-fold defaultstate="collapsed" desc="readIni()">
/** Reads program settings saved when the program was previously closed.
* Exceptions are reported both to the console (if there is one) and to a dialog.<br>
* Reads the ini-file in:<ul>
* <li> the Application Path if found there.</ul>
* If not found in the application path, or if the file is write-protected, then:<ul>
* <li> in %HomeDrive%%HomePath% if found there; if write-protected also
* <li> in %Home% if found there; if write-protected also
* <li> in the user's home directory (system dependent) if it is found there
* otherwise: give a warning and create a new file. Note: except for the
* installation directory, the ini-file will be writen in a sub-folder
* named "<code>.config\eq-diag</code>".
* <p>
* This method also saves the ini-file after reading it and after
* checking its contents. The file is written in the application path if
* "saveIniFileToApplicationPathOnly" is <code>true</code>. Otherwise,
* if an ini-file was read and if it was not write-protected, then program
* options are saved in that file on exit. If no ini-file was found,
* an ini file is created on the first non-write protected directory of
* those listed above. */
private void readIni() {
// start by getting the defaults (this is needed because the arrays must be initialised)
iniDefaults(); // needed to initialise arrays etc.
if(pc.dbg) {System.out.println("--- readIni() --- reading ini-file(s)");}
fileIni = null;
java.io.File p = null, fileRead = null, fileINInotRO = null;
boolean ok, readOk = false;
//--- check the application path ---//
if(pc.pathAPP == null || pc.pathAPP.trim().length() <=0) {
if(pc.saveIniFileToApplicationPathOnly) {
String name = "\"null\"" + SLASH + FileINI_NAME;
MsgExceptn.exception("Error: can not read ini file"+nl+
" "+name+nl+
" (application path is \"null\")");
return;
}
} else { //pathApp is defined
String dir = pc.pathAPP;
if(dir.endsWith(SLASH)) {dir = dir.substring(0, dir.length()-1);}
fileIni = new java.io.File(dir + SLASH + FileINI_NAME);
p = new java.io.File(dir);
if(!p.exists()) {
p = null; fileIni = null;
if(pc.saveIniFileToApplicationPathOnly) {
MsgExceptn.exception("Error: can not read ini file:"+nl+
" "+fileIni.getPath()+nl+
" (application path does not exist)");
return;
}
}
}
success: {
// --- first read the ini-file from the application path, if possible
if(pc.saveIniFileToApplicationPathOnly && fileIni != null) {
// If the ini-file must be written to the application path,
// then try to read this file, even if the file is write-protected
fileINInotRO = fileIni;
if(fileIni.exists()) {
readOk = readIni2(fileIni, false);
if(readOk) {fileRead = fileIni;}
}
break success;
} else { // not saveIniFileToApplicationPathOnly or fileINI does not exist
if(fileIni != null && fileIni.exists()) {
readOk = readIni2(fileIni, false);
if(readOk) {fileRead = fileIni;}
if(fileIni.canWrite() && fileIni.setWritable(true)) {
fileINInotRO = fileIni;
if(readOk) {break success;}
}
} else { //ini-file null or does not exist
if(fileIni != null && p != null) {
try{ // can we can write to this directory?
java.io.File tmp = java.io.File.createTempFile("datab",".tmp", p);
ok = tmp.exists();
if(ok) {tmp.delete();}
} catch (java.io.IOException ex) {ok = false;}
if(pc.dbg) {
String s; if(ok) {s="";} else {s="NOT ";}
System.out.println(" can "+s+"write files to path: "+p.getAbsolutePath());
}
// file does not exist, but the path is not write-protected
if(ok && fileINInotRO == null) {fileINInotRO = fileIni;}
}
}
}
// --- an ini-file has not been read in the application path
// and saveIniFileToApplicationPathOnly = false. Read the ini-file from
// the user's path, if possible
java.util.ArrayList<String> dirs = new java.util.ArrayList<String>(5);
String homeDrv = System.getenv("HOMEDRIVE");
String homePath = System.getenv("HOMEPATH");
if(homePath != null && homePath.trim().length() >0 && !homePath.startsWith(SLASH)) {
homePath = SLASH + homePath;
}
if(homeDrv != null && homeDrv.trim().length() >0 && homeDrv.endsWith(SLASH)) {
homeDrv = homeDrv.substring(0, homeDrv.length()-1);
}
if((homeDrv != null && homeDrv.trim().length() >0)
&& (homePath != null && homePath.trim().length() >0)) {
p = new java.io.File(homeDrv+homePath);
if(p.exists()) {dirs.add(p.getAbsolutePath());}
}
String home = System.getenv("HOME");
if(home != null && home.trim().length() >0) {
p = new java.io.File(home);
if(p.exists()) {dirs.add(p.getAbsolutePath());}
}
home = System.getProperty("user.home");
if(home != null && home.trim().length() >0) {
p = new java.io.File(home);
if(p.exists()) {dirs.add(p.getAbsolutePath());}
}
for(String t : dirs) {
if(t.endsWith(SLASH)) {t = t.substring(0, t.length()-1);}
fileIniUser = new java.io.File(t+SLASH+".config"+SLASH+"eq-diagr"+SLASH+FileINI_NAME);
if(fileIniUser.exists()) {
readOk = readIni2(fileIniUser, true);
if(readOk) {fileRead = fileIniUser;}
if(fileIniUser.canWrite() && fileIniUser.setWritable(true)) {
if(fileINInotRO == null) {fileINInotRO = fileIniUser;}
if(readOk) {break success;}
}
} else { //ini-file does not exist
try{ // can we can write to this directory?
p = new java.io.File(t);
java.io.File tmp = java.io.File.createTempFile("datab",".tmp", p);
ok = tmp.exists();
if(ok) {tmp.delete();}
} catch (java.io.IOException ex) {ok = false;}
if(pc.dbg) {
String s; if(ok) {s="";} else {s="NOT ";}
System.out.println(" can "+s+"write files to path: "+t);
}
// file does not exist, but the path is not write-protected
if(ok && fileINInotRO == null) {fileINInotRO = fileIniUser;}
}
} // for(dirs)
} //--- success?
if(pc.dbg) {
String s;
if(fileINInotRO != null) {s=fileINInotRO.getAbsolutePath();} else {s="\"null\"";}
System.out.println(" ini-file not read-only = "+s);
if(fileRead != null) {s=fileRead.getAbsolutePath();} else {s="\"null\"";}
System.out.println(" ini-file read = "+s);
}
if(!readOk) {
String msg = "Failed to read any INI-file."+nl+
"Default program settings will be used.";
MsgExceptn.showErrMsg(dbf, msg, 1);
int nbr = pd.dataBasesList.size();
if(nbr <=0) {
msg = "Error: no databases found";
msg = msg + nl+nl+
"Please select a database using"+nl+
"menu \"Options / Data / Database files\""+nl+" ";
MsgExceptn.showErrMsg(dbf, msg, 1);
noDataBasesFound = true;
}
}
if(fileINInotRO != null && fileINInotRO != fileRead) {
ok = saveIni(fileINInotRO);
if(ok) {
if(fileIni != fileINInotRO) {fileIniUser = fileINInotRO;} else {fileIniUser = null;}
} else {fileIniUser = null;}
}
} // readIni()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="readIni2">
/**
* @param f the INI-file
* @param userFile if true databases are added to the list (the list is not
* cleared first) and some options, such as "all solids" are not read
* @return true if ok */
private boolean readIni2(java.io.File f, boolean userFile) {
System.out.flush();
String msg = "Reading ";
if(userFile) {msg = msg + "user ";}
msg = msg + "ini-file: \""+f.getPath()+"\"";
System.out.println(msg);
java.util.Properties propertiesIni = new java.util.Properties();
java.io.FileInputStream fis = null;
java.io.BufferedReader r = null;
boolean ok = true;
try {
fis = new java.io.FileInputStream(f);
r = new java.io.BufferedReader(new java.io.InputStreamReader(fis,"UTF8"));
propertiesIni.load(r);
//throw new Exception("Test error");
} //try
catch (java.io.FileNotFoundException e) {
System.out.println("Warning: file not found: \""+f.getPath()+"\""+nl+
"using default parameter values.");
checkIniValues();
ok = false;
} //catch FileNotFoundException
catch (java.io.IOException e) {
MsgExceptn.exception(Util.stack2string(e));
msg = "Error: \""+e.toString()+"\""+nl+
" while loading INI-file:"+nl+
" \""+f.getPath()+"\"";
MsgExceptn.showErrMsg(dbf, msg, 1);
ok = false;
} // catch loading-exception
finally {
try {if(r != null) {r.close();} if(fis != null) {fis.close();}}
catch (java.io.IOException e) {
msg = "Error: \""+e.toString()+"\""+nl+
" while closing INI-file:"+nl+
" \""+f.getPath()+"\"";
MsgExceptn.showErrMsg(dbf, msg, 1);
javax.swing.JOptionPane.showMessageDialog(this, msg, pc.progName, javax.swing.JOptionPane.ERROR_MESSAGE);
}
}
if(!ok) {return ok;}
try{
disclaimerSkip = Boolean.parseBoolean(propertiesIni.getProperty("skipDisclaimer","false"));
} catch (NullPointerException e) {disclaimerSkip = false;}
//--- hide the "disclaimer" window
if(disclaimerSkip && disclaimerFrame != null) {disclaimerFrame.setVisible(false);}
try {
locationFrame.x = Integer.parseInt(propertiesIni.getProperty("location_left"));
locationFrame.y = Integer.parseInt(propertiesIni.getProperty("location_top"));
msgFrameSize.width = Integer.parseInt(propertiesIni.getProperty("msgFrame_width"));
msgFrameSize.height = Integer.parseInt(propertiesIni.getProperty("msgFrame_height"));
locationMsgFrame.x = Integer.parseInt(propertiesIni.getProperty("msgFrame_left"));
locationMsgFrame.y = Integer.parseInt(propertiesIni.getProperty("msgFrame_top"));
pd.addDataLocation.x = Integer.parseInt(propertiesIni.getProperty("addData_left"));
pd.addDataLocation.y = Integer.parseInt(propertiesIni.getProperty("addData_top"));
pd.allSolidsAsk = Boolean.parseBoolean(propertiesIni.getProperty("All_Solids_Ask","false"));
pd.redoxAsk = Boolean.parseBoolean(propertiesIni.getProperty("Redox_Ask","false"));
pd.temperatureAllowHigher = Boolean.parseBoolean(propertiesIni.getProperty("Temperature_Allow_Higher","true"));
//if(!userFile) {
// // These settings are NOT read from the "user" ini-file.
// // If running from a CD or on a network server, the user may save these
// // but they will have to be re-setted on every run
pd.allSolids = Integer.parseInt(propertiesIni.getProperty("All_Solids"));
pd.redoxN = Boolean.parseBoolean(propertiesIni.getProperty("Redox_N"));
pd.redoxS = Boolean.parseBoolean(propertiesIni.getProperty("Redox_S"));
pd.redoxP = Boolean.parseBoolean(propertiesIni.getProperty("Redox_P"));
pd.includeH2O = Boolean.parseBoolean(propertiesIni.getProperty("H2O"));
pd.diagramProgr = propertiesIni.getProperty("diagramProgram");
try{pd.temperature_C = Double.parseDouble(propertiesIni.getProperty("Temperature","25"));}
catch (NumberFormatException e) {pd.temperature_C = 25;
System.out.println("Error reading temperature in \"ini\"-file; setting temperature = 25 C.");
}
try{pd.pressure_bar = Double.parseDouble(propertiesIni.getProperty("Pressure","1"));}
catch (NumberFormatException e) {pd.pressure_bar = 1;
System.out.println("Error reading pressure in \"ini\"-file; setting pressure = 1 bar.");
}
advancedMenu = Boolean.parseBoolean(propertiesIni.getProperty("advancedMenu","false"));
//} // if !userFile
if(pc.pathDef.length() >0) {pc.pathDef.delete(0, pc.pathDef.length());}
pc.pathDef.append(propertiesIni.getProperty("pathDefault"));
if(pd.pathAddData.length() >0) {pd.pathAddData.delete(0, pd.pathAddData.length());}
pd.pathAddData.append(propertiesIni.getProperty("pathAddData"));
if(!userFile) {
// If running from a CD or on a network server, a default database
// is supplied to all users. The user's ini-file will not clear
// the default database.
pd.dataBasesList.clear();
}
int nbr = Integer.parseInt(propertiesIni.getProperty("DataBases_Nbr"));
if(nbr > 0) {
String dbName;
for(int i=0; i < nbr; i++) {
dbName = propertiesIni.getProperty("DataBase["+String.valueOf(i+1).trim()+"]");
if(dbName != null && dbName.trim().length() >0) {pd.dataBasesList.add(dbName);}
}
}
} catch (Exception e) {
MsgExceptn.exception(Util.stack2string(e));
msg = "Error: \""+e.toString()+"\""+nl+
" while reading INI-file:"+nl+
" \""+f.getPath()+"\""+nl+nl+
"Setting default program parameters.";
MsgExceptn.showErrMsg(dbf, msg, 1);
ok = false;
}
try{
String s = propertiesIni.getProperty("lookAndFeel").trim().toLowerCase();
if(s.startsWith("system")) {laf = 1;}
else if(s.startsWith("cross")) {laf = 2;}
else {laf = 0;}
} catch (NullPointerException e) {laf = 0;}
if(ok && pc.dbg) {System.out.println("Finished reading ini-file");}
System.out.flush();
checkIniValues();
return ok;
} // readIni2()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="checkIniValues">
private void checkIniValues() {
System.out.flush();
System.out.println(LINE+nl+"Checking ini-values.");
if(locationFrame.x < -1 || locationFrame.y < -1) {
locationFrame.x = Math.max(0, (LibDB.screenSize.width - this.getWidth() ) / 2);
locationFrame.y = Math.max(0, (LibDB.screenSize.height - this.getHeight() ) / 2);
}
// check Default Path
java.io.File f = new java.io.File(pc.pathDef.toString());
if(!f.exists()) {
pc.setPathDef(); // set Default Path = User Directory
}
if(pd.pathAddData.length() >0) {
f = new java.io.File(pd.pathAddData.toString());
if(!f.exists()) {
if(pd.pathAddData.length() >0) {pd.pathAddData.delete(0, pd.pathAddData.length());}
pd.pathAddData.append(pc.pathDef.toString());
}
} else {
pd.pathAddData.append(pc.pathDef.toString());
}
if(pd.diagramProgr != null && pd.diagramProgr.trim().length()>0) {
f = new java.io.File(pd.diagramProgr);
} else {f = null;}
if(f==null || !f.exists()) {
String s = pd.diagramProgr;
if(s==null) {s="null";}
System.out.println("Warning: the diagram-making program:"+nl+
" \""+s+"\""+nl+
" in the INI-file does not exist.");
getDiagramProgr(true);
}
if(System.getProperty("os.name").startsWith("Mac OS")) {
String dir = pc.pathAPP;
if(dir != null && dir.endsWith(SLASH)) {dir = dir.substring(0, dir.length()-1);}
String s = dir +SLASH+".."+SLASH+".."+SLASH+".."+SLASH+".."+SLASH+"DataBase.app";
f = new java.io.File(s);
if(f.exists()) {
System.out.println("Enabling menu \"Data / advanced\".");
advancedMenu = true;
}
}
String dir = pc.pathAPP;
if(dir != null && dir.endsWith(SLASH)) {dir = dir.substring(0, dir.length()-1);}
String dbName;
int nbr = pd.dataBasesList.size();
String msg = null;
if(nbr <=0) {
msg = "Warning: no databases are given in the INI-file";
System.out.println(msg);
if(dir != null && dir.trim().length()>0) {dbName = dir + SLASH + DEF_DataBase;} else {dbName = DEF_DataBase;}
if(LibDB.isDBnameOK(dbf, dbName, false)) {
pd.dataBasesList.add(dbName);
System.out.println(" Setting databse to "+dbName);
msg = null;
}
} else {
LibDB.checkListOfDataBases(dbf, pd.dataBasesList, pc.pathAPP, true);
nbr = pd.dataBasesList.size();
if(nbr <=0) {
msg = "Error: no database in the INI-file exist";
if(dir != null && dir.trim().length()>0) {dbName = dir + SLASH + DEF_DataBase;} else {dbName = DEF_DataBase;}
if(LibDB.isDBnameOK(dbf, dbName, false)) {
pd.dataBasesList.add(dbName);
System.out.println(" Setting databse to "+dbName);
msg = null;
}
} // none of the databases exist.
} // no databases in INI-file
if(msg != null) {
msg = msg + nl+nl+"Please select a database using"+nl+
"menu \"Options / Data / Database files\""+nl+" ";
MsgExceptn.showErrMsg(dbf, msg, 1);
noDataBasesFound = true;
}
// diagramLocation, dispLocation and dispSize are checked
// each time these windows are loaded
pd.allSolids = Math.min(3, Math.max(0, pd.allSolids));
double maxT, maxP;
if(pd.temperatureAllowHigher) {maxT = 1000; maxP = 5000;} else {maxT = 100; maxP = 1.0142;}
pd.temperature_C = Math.min(maxT, Math.max(-0.00001, pd.temperature_C));
pd.pressure_bar = Math.min(maxP, Math.max(1, pd.pressure_bar));
laf = Math.min(2,Math.max(0,laf));
System.out.println(LINE);
System.out.flush();
} // checkIniValues()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="getDiagramProgr">
private void getDiagramProgr(final boolean print) {
String dir = pc.pathAPP;
if(dir != null && dir.endsWith(SLASH)) {dir = dir.substring(0, dir.length()-1);}
java.io.File f;
if(dir == null || dir.trim().length()<=0) {
pd.diagramProgr = "Spana.jar";
} else {
pd.diagramProgr = dir + SLASH + "Spana.jar";
f = new java.io.File(pd.diagramProgr);
if(!f.exists() && System.getProperty("os.name").startsWith("Mac OS")) {
pd.diagramProgr = dir +SLASH+".."+SLASH+".."+SLASH+".."+SLASH+".."+SLASH+"Spana.app"
+SLASH+"Contents"+SLASH+"Resources"+SLASH+"Java"+SLASH+"Spana.jar";
f = new java.io.File(pd.diagramProgr);
try{pd.diagramProgr = f.getCanonicalPath();}
catch (java.io.IOException ex) {pd.diagramProgr = f.getAbsolutePath();}
}
}
f = new java.io.File(pd.diagramProgr);
if(!f.exists()) {
if(print) {System.out.println("Warning: could NOT find the diagram-making program: "+nl+
" "+pd.diagramProgr);}
pd.diagramProgr = null;
} else if(print) {System.out.println("Setting diagram-making program = "+nl+
" "+pd.diagramProgr);}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="iniDefaults">
private void iniDefaults() {
// Set default values for program variables
if (pc.dbg) {
System.out.flush();
System.out.println("Setting default parameter values (\"ini\"-values).");
}
advancedMenu = false;
pd.addDataLocation.x = -1000; pd.addDataLocation.y = -1000;
locationFrame.x = Math.max(0, (LibDB.screenSize.width - this.getWidth() ) / 2);
locationFrame.y = Math.max(0, (LibDB.screenSize.height - this.getHeight() ) / 2);
msgFrameSize.width = 500; msgFrameSize.height = 400;
locationMsgFrame.x = 80; locationMsgFrame.y = 28;
// set the default path to the "current directory" (from where the program is started)
pc.setPathDef(); // set Default Path = User Directory
pd.temperatureAllowHigher = true;
pd.temperature_C = 25;
pd.pressure_bar = 1;
pd.allSolidsAsk = false;
// 0=include all solids; 1=exclude (cr); 2=exclude (c); 3=exclude (cr)&(c)
pd.allSolids = 0;
pd.redoxAsk = false;
pd.redoxN = true;
pd.redoxS = true;
pd.redoxP = true;
pd.includeH2O = false;
if(pd.pathAddData.length() >0) {pd.pathAddData.delete(0, pd.pathAddData.length());}
pd.pathAddData.append(System.getProperty("user.home"));
getDiagramProgr(false);
String dir = pc.pathAPP;
if(dir != null && dir.endsWith(SLASH)) {dir = dir.substring(0, dir.length()-1);}
pd.dataBasesList.clear();
String dbName;
if(dir != null && dir.trim().length()>0) {dbName = dir + SLASH + DEF_DataBase;} else {dbName = DEF_DataBase;}
java.io.File db = new java.io.File(dbName);
String msg = null;
if(db.exists()) {
if(db.canRead()) {pd.dataBasesList.add(dbName);}
else {msg ="Error -- file \""+dbName+"\":"+nl+" can not be read.";}
}
if(msg != null) {MsgExceptn.showErrMsg(dbf, msg, 1);}
} // iniDefaults()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="saveIni(file)">
/** Save program settings.
* Exceptions are reported both to the console (if there is one) and to a dialog */
private boolean saveIni(java.io.File f) {
if(f == null) {return false;}
if(pc.dbg) {System.out.println("--- saveIni("+f.getAbsolutePath()+")");}
boolean ok = true;
String msg = null;
if(f.exists() && (!f.canWrite() || !f.setWritable(true))) {
msg = "Error - can not write ini-file:"+nl+
" \""+f.getAbsolutePath()+"\""+nl+
"The file is read-only.";
}
if(!f.exists() && !f.getParentFile().exists()) {
ok = f.getParentFile().mkdirs();
if(!ok) {
msg = "Error - can not create directory:"+nl+
" \""+f.getParent()+"\""+nl+
"Can not write ini-file.";
}
}
if(msg != null) {
MsgExceptn.showErrMsg(dbf, msg, 2);
return false;
}
java.util.Properties propertiesIni= new SortedProperties();
if(this != null && this.isVisible()
&& locationFrame.x > -1 && locationFrame.y > -1) {
if(getExtendedState()==javax.swing.JFrame.ICONIFIED
|| getExtendedState()==javax.swing.JFrame.MAXIMIZED_BOTH)
{setExtendedState(javax.swing.JFrame.NORMAL);}
locationFrame.x = getX();
locationFrame.y = getY();
}
propertiesIni.setProperty("<program_version>", VERS);
if(pd.msgFrame != null) {msgFrameSize = pd.msgFrame.getSize(); locationMsgFrame = pd.msgFrame.getLocation();}
propertiesIni.setProperty("msgFrame_width", String.valueOf(msgFrameSize.width));
propertiesIni.setProperty("msgFrame_height", String.valueOf(msgFrameSize.height));
propertiesIni.setProperty("msgFrame_left", String.valueOf(locationMsgFrame.x));
propertiesIni.setProperty("msgFrame_top", String.valueOf(locationMsgFrame.y));
propertiesIni.setProperty("location_left", String.valueOf(locationFrame.x));
propertiesIni.setProperty("location_top", String.valueOf(locationFrame.y));
propertiesIni.setProperty("addData_left", String.valueOf(pd.addDataLocation.x));
propertiesIni.setProperty("addData_top", String.valueOf(pd.addDataLocation.y));
propertiesIni.setProperty("All_Solids_Ask", String.valueOf(pd.allSolidsAsk));
propertiesIni.setProperty("All_Solids", String.valueOf(pd.allSolids));
propertiesIni.setProperty("Temperature_Allow_Higher", String.valueOf(pd.temperatureAllowHigher));
propertiesIni.setProperty("Temperature", Util.formatNumAsInt(pd.temperature_C).trim());
propertiesIni.setProperty("Pressure", Util.formatNumAsInt(pd.pressure_bar).trim());
propertiesIni.setProperty("Redox_Ask", String.valueOf(pd.redoxAsk));
propertiesIni.setProperty("Redox_N", String.valueOf(pd.redoxN));
propertiesIni.setProperty("Redox_S", String.valueOf(pd.redoxS));
propertiesIni.setProperty("Redox_P", String.valueOf(pd.redoxP));
propertiesIni.setProperty("H2O", String.valueOf(pd.includeH2O));
propertiesIni.setProperty("pathDefault", pc.pathDef.toString());
propertiesIni.setProperty("pathAddData", pd.pathAddData.toString());
propertiesIni.setProperty("skipDisclaimer", String.valueOf(disclaimerSkip));
propertiesIni.setProperty("advancedMenu", String.valueOf(advancedMenu));
if(laf==2) {propertiesIni.setProperty("lookAndFeel", "CrossPlatform (may be 'CrossPlatform', 'System' or 'Default')");}
else if(laf==1) {propertiesIni.setProperty("lookAndFeel", "System (may be 'CrossPlatform', 'System' or 'Default')");}
else {propertiesIni.setProperty("lookAndFeel", "Default (may be 'CrossPlatform', 'System' or 'Default')");}
if(pd.diagramProgr != null) {
propertiesIni.setProperty("diagramProgram", pd.diagramProgr);
} else {propertiesIni.setProperty("diagramProgram", "");}
int nbr = pd.dataBasesList.size();
propertiesIni.setProperty("DataBases_Nbr", String.valueOf(nbr));
for (int i = 0; i < nbr; i++) {
propertiesIni.setProperty("DataBase["+String.valueOf(i+1).trim()+"]", pd.dataBasesList.get(i));
}
System.out.println("Saving ini-file: \""+f.getPath()+"\"");
java.io.FileOutputStream fos = null;
java.io.Writer w = null;
try{
fos = new java.io.FileOutputStream(f);
w = new java.io.BufferedWriter(new java.io.OutputStreamWriter(fos,"UTF8"));
// INI-section "[DataBase]" needed by PortableApps java launcher
char[] b = new char[10 + nl.length()];
b[0]='['; b[1]='D'; b[2]='a'; b[3]='t'; b[4]='a';
b[5]='B'; b[6]='a'; b[7]='s'; b[8]='e'; b[9]=']';
for(int j =0; j < nl.length(); j++) {b[10+j] = nl.charAt(j);}
w.write(b);
//
propertiesIni.store(w,null);
if (pc.dbg) {System.out.println("Written: \""+f.getPath()+"\"");}
} catch (java.io.IOException e) {
msg = "Error: \""+e.getMessage()+"\""+nl+
"while writing INI-file:"+nl+
"\""+f.getPath()+"\"";
if(!this.isVisible()) {this.setVisible(true);}
MsgExceptn.showErrMsg(dbf, msg, 1);
ok = false;
} // catch store-exception
finally {
try {if(w != null) {w.close();} if(fos != null) {fos.close();}}
catch (java.io.IOException e) {
msg = e.getMessage()+nl+
" trying to write ini-file: \""+f.getPath()+"\"";
if(!this.isVisible()) {this.setVisible(true);}
MsgExceptn.showErrMsg(dbf, msg, 1);
}
} //finally
return ok;
} // saveIni()
//</editor-fold>
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="searchReactions(exit)">
private void searchReactions(final boolean exit) {
if(modelSelectedComps.size() <=0) {
System.out.println("Error in \"searchReactions\": modelSelectedComps.size() <=0");
return;
}
setCursorWait();
final boolean needToSearch = (!exit || !jScrollPaneComplexes.isVisible() || modelComplexes.isEmpty());
if(pc.dbg) {System.out.println("--- search reactions: needToSearch = "+needToSearch);}
if(needToSearch) {
boolean electronsSelected = false;
for(int i=0; i < modelSelectedComps.size(); i++) {
if(Util.isElectron(modelSelectedComps.get(i).toString())) {electronsSelected = true; break;}
} //for i
if(pd.redoxAsk && electronsSelected) {
exitCancel = true;
boolean askingBeforeSearch = true;
AskRedox ask = new AskRedox(this, true, pc, pd, askingBeforeSearch, modelSelectedComps);
if(ask.askSomething) {
ask.start();
// because ask is a modal dialog, next statement is executed when "ask" is closed by the user
if(exitCancel) {setCursorDef(); return;}
}
ask.dispose();
}
if(pd.allSolidsAsk) {
exitCancel = true;
boolean askingBeforeSearch = true;
AskSolids ask = new AskSolids(this, true, pc, pd, askingBeforeSearch);
ask.start();
// because ask is a modal dialog, next statement is executed when "ask" is closed by the user
if(exitCancel) {setCursorDef(); return;}
ask.dispose();
}
searchingComplexes = true;
menuOptionsEnable(false);
jMenuExit.setEnabled(false);
jMenuSearch.setEnabled(false);
jScrollPaneComplexes.setVisible(true);
jLabel_cr_solids.setText(" ");
jLabelComplexes.setVisible(true);
java.awt.CardLayout cl = (java.awt.CardLayout)this.jPanelBottom.getLayout();
cl.show(this.jPanelBottom,"cardProgress");
updateProgressBar(0);
updateProgressBarLabel(" ", 0);
modelComplexes.clear();
}
javax.swing.SwingWorker srchWorker;
srchWorker = new javax.swing.SwingWorker<Boolean, Void>() {
private boolean searchError;
private boolean temperatureCorrectionsPossible;
@Override
public Boolean doInBackground() {
//do we need to search the databases?
if(!needToSearch) {
setCursorDef();
return true;
} else {
searchError = false;
if(pc.dbg) {System.out.println("---- new search");}
try{
srch = new DBSearch(pc,pd);
setCursorDef();
// the results of the search are stored in "srch.dat"
srch.searchComplexes(dbf);
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
jMenuExit.setText("Exit");
jMenuExit.setEnabled(true);
jMenuSearch.setEnabled(true);
}}); //invokeLater(Runnable)
}
catch (DBSearch.SearchException ex) {
MsgExceptn.showErrMsg(dbf, ex.getMessage(), 1);
searchError = true;
srch = null;
return false; //this will go to finally
}
finally {
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
menuOptionsEnable(true);
jMenuExit.setEnabled(true);
java.awt.CardLayout cl = (java.awt.CardLayout)dbf.jPanelBottom.getLayout();
cl.show(dbf.jPanelBottom,"cardLower");
//jListComplexes.requestFocusInWindow();
}}); //invokeLater(Runnable)
searchingComplexes = false;
}
temperatureCorrectionsPossible = true;
if(!searchError) {
for (Complex dat : srch.dat) {modelComplexes.addElement(dat.name);}
// ---
// --- Temperature corrections?
// ---
temperatureCorrectionsPossible = DBSearch.checkTemperature(srch, dbf, true);
} // searchError?
if(searchError || !temperatureCorrectionsPossible) {
final boolean se = searchError;
//javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
jMenuExit.setEnabled(true);
jMenuSearch.setEnabled(true);
if(se) {
jMenuExit.setText("Search and Exit");
jScrollPaneComplexes.setVisible(false);
jLabel_cr_solids.setText(" ");
jLabelComplexes.setVisible(false);
} else {
jMenuExit.setText("Exit");
}
//}});
if(searchError) {
srch = null;
if(pc.dbg) {System.out.println("---- new search end with error.");}
}
setCursorDef();
return false;
}
if(pc.dbg) {System.out.println("---- new search end.");}
doneSomeWork = true;
} //needToSearch
return true;
} // doInBackground()
@Override protected void done() {
if(needToSearch) {
if(isCancelled()) {
if(pc.dbg) {System.out.println("--- SwingWorker cancelled.");}
return;
}
if(searchError) {
if(pc.dbg) {System.out.println("--- Search error.");}
return;
}
if(!temperatureCorrectionsPossible) {
if(pc.dbg) {System.out.println("--- Temperature Corrections NOT Possible.");}
return;
}
}
if(!exit) {return;}
if(pc.dbg) {System.out.println("--- exit ...");}
exitCancel = true;
send2Diagram = false;
ExitDialog exitDialog = new ExitDialog(dbf, true, pc, pd, srch);
if(exitCancel) {
if(pc.dbg) {System.out.println("--- Exit cancelled");}
return;
}
if(send2Diagram) {
if(pd.diagramProgr == null) {
MsgExceptn.exception("Error \"pd.diagramProgr\" is null."); return;
}
if(outputDataFile == null || outputDataFile.length() <=0) {
System.out.println(" outputDataFile name is empty!?");
return;
}
if(pc.dbg) {System.out.println("Sending file to the diagram-making program");}
final String diagramProg = LibDB.getDiagramProgr(pd.diagramProgr);
if(diagramProg == null || diagramProg.trim().length()<=0) {
String t = "Error: could not find the diagram-making program:"+nl;
if(pd.diagramProgr != null) {t = t+" \""+pd.diagramProgr+"\"";}
else {t = t +" \"null\"";}
MsgExceptn.exception(t);
javax.swing.JOptionPane.showMessageDialog(dbf, t, pc.progName,javax.swing.JOptionPane.ERROR_MESSAGE);
return;
}
setCursorWait();
Thread hlp = new Thread() {@Override public void run(){
String[] argsDiagram = new String[]{"\""+outputDataFile+"\""};
boolean waitForCompletion = false;
lib.huvud.RunProgr.runProgramInProcess(null,diagramProg,argsDiagram,waitForCompletion,pc.dbg,pc.pathAPP);
try{Thread.sleep(2000);} //show the "wait" cursor for 2 sec
catch (InterruptedException e) {}
setCursorDef();
}};//new Thread
hlp.start();
} //if send2Diagram
doneSomeWork = false;
if(pc.dbg) {System.out.println("--- SwingWorker done.");}
end_program();
} // done()
};
srchWorker.execute();
} //searchReactions(exit)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="setCursorWait and setCursorDef">
private void setCursorWait() {
if(this != null) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
}});
}
if(pd.msgFrame != null && pd.msgFrame.isShowing()) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
pd.msgFrame.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
}});
}
}
protected void setCursorDef() {
if(this != null) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
}});
}
if(pd.msgFrame != null && pd.msgFrame.isShowing()) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
pd.msgFrame.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
}});
}
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="setTextLabelRight(msg)">
/** Sets and resizes jLabelRight with a text string
* @param msg
*/
private void setTextLabelRight(String msg) {
if(msg == null || msg.trim().length() <=0) {msg = " ";}
jLabelRight.setText(msg);
int w = jLabelRight.getWidth()+1;
if((labelRightX0 + w) > panelLowerLabelsW0) {
jLabelRight.setLocation(Math.max(0,(panelLowerLabelsW0 - w)), 1);
} else {
jLabelRight.setLocation(labelRightX0, 1);
}
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="setupFrame">
/** restore the main frame after executing "getElements" */
private void setupFrame() {
java.awt.Font fN = buttonFont.deriveFont(java.awt.Font.PLAIN);
java.awt.Font fB = buttonFont.deriveFont(java.awt.Font.BOLD);
String[] elemComp;
int jN = pd.elemComp.size();
boolean found;
for(javax.swing.JButton button : this.buttons) {
found = false;
for(int j = 0; j<jN; j++) {
elemComp = pd.elemComp.get(j);
if(button.getText().equals(elemComp[0])) {
found = true;
break;
}
} //for j
if(found) {
button.setEnabled(true);
button.setFocusable(true);
button.setFont(fB);
button.setBackground(buttonBackgroundB);
} else {
button.setEnabled(false);
button.setFocusable(false);
button.setFont(fN);
button.setBackground(buttonBackgroundN);
button.setBorder(buttonBorderN);
}
} //for button
if(pd.foundH2O) {jMenuAdvH2O.setEnabled(true);} else {jMenuAdvH2O.setEnabled(false);}
buttons[1].doClick(); //click on "H+" to select it as a component
availableComponentClick(0);
jLabelComplexes.setVisible(false);
jScrollPaneComplexes.setVisible(false);
jLabel_cr_solids.setText(" ");
setTextLabelRight(" ");
originalJLabelLeft.replace(0, originalJLabelLeft.length(), " ");
jLabelLeft.setText(" ");
jLabelMid.setText(" ");
doneSomeWork = false;
} //setupFrame()
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="updateProgressBar">
void updateProgressBar(final int newValue) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
jProgressBar.setValue(newValue);
}}); //invokeLater(Runnable)
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="updateProgressBarLabel">
void updateProgressBarLabel(final String newTxt, final int nLoop) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
if(nLoop <= 1) {
jLabelNowLoop.setText(" ");
jLabelNowLoop.setVisible(false);
} else {
jLabelNowLoop.setText("Redox loop number "+nLoop);
jLabelNowLoop.setVisible(true);
}
if(newTxt == null || newTxt.length() <=0) {jLabelNow.setText(" ");} else {jLabelNow.setText(newTxt);}
}}); //invokeLater(Runnable)
}
// </editor-fold>
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="main">
/** Starts DataBase. If another instance is running, send the command
* arguments to the other instance and quit, otherwise, start a DataBase-frame.
* @param args the command line arguments
*/
public static void main(final String[] args) {
System.out.println("DataBase - version "+VERS);
final Splash spl = new Splash(0);
//---- deal with some command-line arguments
boolean dbg = false;
if(args.length > 0) {
for(String arg : args) {
if (arg.equalsIgnoreCase("-dbg") || arg.equalsIgnoreCase("/dbg")) {
System.out.println("Command-line argument = \"" + arg + "\"");
dbg = true;
}
if (arg.equals("-?") || arg.equals("/?") || arg.equals("?")
|| arg.equals("-help") || arg.equals("--help")) {
System.out.println("Command-line argument = \"" + arg + "\"");
printInstructions();
} //if args[] = "?"
}
}
//---- is there another instance already running?
if((new OneInstance()).findOtherInstance(args, 56050, "DataBase", dbg)) {
System.out.println("---- Already running.");
spl.setVisible(false);
spl.dispose();
return;
}
//---- create a local instance of ProgramConf.
// Contains information read from the configuration file.
final ProgramConf pc = new ProgramConf("DataBase");
pc.dbg = dbg;
//---- all output to System.err and System.out will be shown in a frame.
if(msgFrame == null) {
msgFrame = new RedirectedFrame(550, 400, pc);
msgFrame.setVisible(dbg);
System.out.println("DataBase - version "+VERS);
}
if(System.getProperty("os.name").toLowerCase().startsWith("windows")) {windows = true;}
//---- set Look-And-Feel
// laf = 0
try{
if(windows) {
javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
System.out.println("--- setLookAndFeel(System);");
} else {
javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getCrossPlatformLookAndFeelClassName());
System.out.println("--- setLookAndFeel(CrossPlatform);");
}
}
catch (Exception ex) {System.out.println("Error: "+ex.getMessage());}
//---- for JOptionPanes set the default button to the one with the focus
// so that pressing "enter" behaves as expected:
javax.swing.UIManager.put("Button.defaultButtonFollowsFocus", Boolean.TRUE);
// and make the arrow keys work:
Util.configureOptionPane();
//---- get the Application Path
pc.pathAPP = Main.getPathApp();
//---- read the CFG-file
java.io.File fileNameCfg;
String dir = pc.pathAPP;
if(dir != null && dir.trim().length()>0) {
if(dir.endsWith(SLASH)) {dir = dir.substring(0, dir.length()-1);}
fileNameCfg = new java.io.File(dir + SLASH + pc.progName+".cfg");
} else {fileNameCfg = new java.io.File(pc.progName+".cfg");}
ProgramConf.read_cfgFile(fileNameCfg, pc);
java.text.DateFormat dateFormatter =
java.text.DateFormat.getDateTimeInstance
(java.text.DateFormat.DEFAULT, java.text.DateFormat.DEFAULT,
java.util.Locale.getDefault());
java.util.Date today = new java.util.Date();
String dateOut = dateFormatter.format(today);
System.out.println(pc.progName+" started: \""+dateOut+"\"");
System.out.println(LINE);
//---- set Default Path = Start Directory
pc.setPathDef();
commandArgs = args;
//---- show the main window
java.awt.EventQueue.invokeLater(new Runnable() {
@Override public void run() {
dbf = new FrameDBmain(pc, msgFrame); //send configuration data
if(!dbf.disclaimerSkip) {
dbf.disclaimerFrame = new Disclaimer(dbf, pc, msgFrame);
}
//--- remove the "splash" window
spl.setVisible(false);
spl.dispose();
dbf.start();
} // run
}); // invokeLater
} //main(args)
// </editor-fold>
public static FrameDBmain getInstance() {return dbf;}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JButton jButton0;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton10;
private javax.swing.JButton jButton100;
private javax.swing.JButton jButton101;
private javax.swing.JButton jButton102;
private javax.swing.JButton jButton103;
private javax.swing.JButton jButton11;
private javax.swing.JButton jButton12;
private javax.swing.JButton jButton13;
private javax.swing.JButton jButton14;
private javax.swing.JButton jButton15;
private javax.swing.JButton jButton16;
private javax.swing.JButton jButton17;
private javax.swing.JButton jButton18;
private javax.swing.JButton jButton19;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton20;
private javax.swing.JButton jButton21;
private javax.swing.JButton jButton22;
private javax.swing.JButton jButton23;
private javax.swing.JButton jButton24;
private javax.swing.JButton jButton25;
private javax.swing.JButton jButton26;
private javax.swing.JButton jButton27;
private javax.swing.JButton jButton28;
private javax.swing.JButton jButton29;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton30;
private javax.swing.JButton jButton31;
private javax.swing.JButton jButton32;
private javax.swing.JButton jButton33;
private javax.swing.JButton jButton34;
private javax.swing.JButton jButton35;
private javax.swing.JButton jButton36;
private javax.swing.JButton jButton37;
private javax.swing.JButton jButton38;
private javax.swing.JButton jButton39;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton40;
private javax.swing.JButton jButton41;
private javax.swing.JButton jButton42;
private javax.swing.JButton jButton43;
private javax.swing.JButton jButton44;
private javax.swing.JButton jButton45;
private javax.swing.JButton jButton46;
private javax.swing.JButton jButton47;
private javax.swing.JButton jButton48;
private javax.swing.JButton jButton49;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton50;
private javax.swing.JButton jButton51;
private javax.swing.JButton jButton52;
private javax.swing.JButton jButton53;
private javax.swing.JButton jButton54;
private javax.swing.JButton jButton55;
private javax.swing.JButton jButton56;
private javax.swing.JButton jButton57;
private javax.swing.JButton jButton58;
private javax.swing.JButton jButton59;
private javax.swing.JButton jButton6;
private javax.swing.JButton jButton60;
private javax.swing.JButton jButton61;
private javax.swing.JButton jButton62;
private javax.swing.JButton jButton63;
private javax.swing.JButton jButton64;
private javax.swing.JButton jButton65;
private javax.swing.JButton jButton66;
private javax.swing.JButton jButton67;
private javax.swing.JButton jButton68;
private javax.swing.JButton jButton69;
private javax.swing.JButton jButton7;
private javax.swing.JButton jButton70;
private javax.swing.JButton jButton71;
private javax.swing.JButton jButton72;
private javax.swing.JButton jButton73;
private javax.swing.JButton jButton74;
private javax.swing.JButton jButton75;
private javax.swing.JButton jButton76;
private javax.swing.JButton jButton77;
private javax.swing.JButton jButton78;
private javax.swing.JButton jButton79;
private javax.swing.JButton jButton8;
private javax.swing.JButton jButton80;
private javax.swing.JButton jButton81;
private javax.swing.JButton jButton82;
private javax.swing.JButton jButton83;
private javax.swing.JButton jButton84;
private javax.swing.JButton jButton85;
private javax.swing.JButton jButton86;
private javax.swing.JButton jButton87;
private javax.swing.JButton jButton88;
private javax.swing.JButton jButton89;
private javax.swing.JButton jButton9;
private javax.swing.JButton jButton90;
private javax.swing.JButton jButton91;
private javax.swing.JButton jButton92;
private javax.swing.JButton jButton93;
private javax.swing.JButton jButton94;
private javax.swing.JButton jButton95;
private javax.swing.JButton jButton96;
private javax.swing.JButton jButton97;
private javax.swing.JButton jButton98;
private javax.swing.JButton jButton99;
private javax.swing.JCheckBoxMenuItem jCheckBoxMenuDebug;
private javax.swing.JCheckBoxMenuItem jCheckBoxMenuVerbose;
private javax.swing.JLabel jLabelAvailableComp;
private javax.swing.JLabel jLabelComplexes;
private javax.swing.JLabel jLabelComps;
private javax.swing.JLabel jLabelLeft;
private javax.swing.JLabel jLabelMid;
private javax.swing.JLabel jLabelNow;
private javax.swing.JLabel jLabelNowLoop;
private javax.swing.JLabel jLabelPressure;
private javax.swing.JLabel jLabelRight;
private javax.swing.JLabel jLabelTemperature;
protected javax.swing.JLabel jLabel_cr_solids;
private javax.swing.JList jListAvailableComps;
private javax.swing.JList jListComplexes;
private javax.swing.JList jListSelectedComps;
private javax.swing.JMenuItem jMenuAddData;
private javax.swing.JMenuItem jMenuAdvH2O;
private javax.swing.JMenuItem jMenuAdvRedox;
private javax.swing.JMenuItem jMenuAdvSolids;
private javax.swing.JMenu jMenuAdvanced;
private javax.swing.JMenuBar jMenuBar;
private javax.swing.JMenuItem jMenuDBFiles;
private javax.swing.JMenu jMenuData;
private javax.swing.JMenuItem jMenuExit;
private javax.swing.JMenu jMenuFile;
private javax.swing.JMenu jMenuH;
private javax.swing.JMenuItem jMenuHelp;
private javax.swing.JMenuItem jMenuHelpAbout;
private javax.swing.JMenuItem jMenuItemCancel;
private javax.swing.JMenuItem jMenuItemData;
private javax.swing.JMenuItem jMenuItemDel;
private javax.swing.JMenuItem jMenuItemTemperature;
private javax.swing.JMenuItem jMenuLocate;
private javax.swing.JMenuItem jMenuMaintenance;
private javax.swing.JMenu jMenuOptions;
private javax.swing.JMenu jMenuPref;
private javax.swing.JMenuItem jMenuQuit;
private javax.swing.JMenuItem jMenuRefs;
private javax.swing.JMenuItem jMenuSearch;
private javax.swing.JMenuItem jMenuSingleC;
private javax.swing.JPanel jPanelBottom;
private javax.swing.JPanel jPanelLower;
private javax.swing.JPanel jPanelLowerLabels;
private javax.swing.JPanel jPanelPeriodicT;
private javax.swing.JPanel jPanelProgressBar;
private javax.swing.JPanel jPanelREEactinides;
private javax.swing.JPanel jPanelTable;
private javax.swing.JPopupMenu jPopupMenu;
private javax.swing.JProgressBar jProgressBar;
private javax.swing.JScrollPane jScrollPaneAvailableComps;
private javax.swing.JScrollPane jScrollPaneComplexes;
private javax.swing.JScrollPane jScrollPaneSelectedComps;
private javax.swing.JPopupMenu.Separator jSeparator;
// End of variables declaration//GEN-END:variables
}
| 198,828 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
Disclaimer.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/DataBase/src/database/Disclaimer.java | package database;
import lib.huvud.ProgramConf;
import lib.huvud.RedirectedFrame;
/** Disclaimer for the Database program.
* <br>
* Copyright (C) 2015-2020 I.Puigdomenech.
*
* 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
* 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/
* @author Ignasi Puigdomenech */
public class Disclaimer extends javax.swing.JFrame {
private final FrameDBmain dbF;
private final ProgramConf pc;
private boolean accepted = false;
private boolean finished = false;
private final RedirectedFrame msgFrame;
//<editor-fold defaultstate="collapsed" desc="Constructor">
/**
* Creates new form Disclaimer
* @param parent
* @param pc0 program configuration
* @param msgFrame0
*/
public Disclaimer(java.awt.Frame parent, ProgramConf pc0, RedirectedFrame msgFrame0) {
pc = pc0;
dbF = (FrameDBmain)parent;
initComponents();
msgFrame = msgFrame0;
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setResizable(false);
//--- close window on ESC key
javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_ESCAPE,0, false);
javax.swing.Action escAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
Object[] opt = {"Yes", "No"};
int answer = javax.swing.JOptionPane.showOptionDialog(Disclaimer.this,
"Quit?",
pc.progName, javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.QUESTION_MESSAGE,null, opt, opt[1]);
accepted = false;
if(answer == javax.swing.JOptionPane.YES_OPTION) {closeWindow(accepted);}
}};
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE");
getRootPane().getActionMap().put("ESCAPE", escAction);
//--- Return = exit
javax.swing.KeyStroke enterKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_ENTER, 0, false);
javax.swing.Action enterAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jButtonOK.doClick();
}};
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(enterKeyStroke,"_Enter");
getRootPane().getActionMap().put("_Enter", enterAction);
//---- Title, etc
this.setTitle(pc.progName+" - Disclaimer");
// ---- Icon
String iconName = "images/DataBase.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
if (imgURL != null) {this.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());}
else {System.out.println("Error: Could not load image = \""+iconName+"\"");}
//---- Centre window on parent/screen
int left,top;
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
left = Math.max(0,(screenSize.width-this.getWidth())/2);
top = Math.max(0,(screenSize.height-this.getHeight())/2);
this.setLocation(Math.min(screenSize.width-this.getWidth()-20,left),
Math.min(screenSize.height-this.getHeight()-20, top));
setVisible(true);
setAlwaysOnTop(true);
toFront();
jButtonOK.requestFocus();
setAlwaysOnTop(false);
start();
} // constructor
private void start(){msgFrame.setParentFrame(this);}
// </editor-fold>
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabelDisclTitle = new javax.swing.JLabel();
jScrollPanelDiscl = new javax.swing.JScrollPane();
jLabelDiscl = new javax.swing.JLabel();
jButtonOK = new javax.swing.JButton();
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
addWindowStateListener(new java.awt.event.WindowStateListener() {
public void windowStateChanged(java.awt.event.WindowEvent evt) {
formWindowStateChanged(evt);
}
});
jLabelDisclTitle.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabelDisclTitle.setText("<html>Only for <u>students</u>!</html>");
jScrollPanelDiscl.setBackground(new java.awt.Color(255, 255, 255));
jLabelDiscl.setBackground(new java.awt.Color(255, 255, 255));
jLabelDiscl.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabelDiscl.setText("<html>\n<p><font size=+1><b>Please note:</b> </font>\nThis software (including its database) is only<br>\nintended for educational activities. The database may contain:\n<ul><li><b>errors</b> and <b>inconsistencies</b> in the data,</li>\n<li><b>non-existing compounds</b> may be included, and</li>\n<li><b>well known species may be missing.</b></li>\n</ul></p>\n\n<p>You alone are solely responsible for any consequences from<br>\nusing this software in professional and/or research activites.<br> </p>\n\n<p><strong>Disclaimer of Warranty.</strong></p>\n\n<p><font size=-1>THERE IS NO WARRANTY FOR THIS SOFTWARE, TO THE EXTENT PERMITTED<br>\nBY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING<br>\nTHE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE<br>\nPROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED<br>\nOR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES<br>\nOF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.<br>\nTHE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THIS<br>\nSOFTWARE IS WITH YOU. SHOULD THIS SOFTWARE (OR ITS DATABASE)<br>\nPROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,<br>\nREPAIR OR CORRECTION.</font></p>\n\n<br><p><strong>Limitation of Liability.</strong></p>\n<p><font size=-1>IN NO EVENT UNLESS RE QUIRED BY APPLICABLE LAW OR AGREED TO<br>\nIN WRITING WILL ANY COPYRIGH HOLDER, OR ANY OTHER PARTY WHO<br>\nMODIFIES AND/OR CONVEYS THE PROGRAM, BE LIABLE TO YOU FOR<br>\nDAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR<br>\nCONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO<br>\nUSE THIS SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA<br>\nOR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU<br>\nOR THIRD PARTIES OR A FAILURE OF THIS SOFTWARE TO OPERATE<br>\nWITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER<br>\nPARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.</font></p>\n</html>");
jLabelDiscl.setVerticalAlignment(javax.swing.SwingConstants.TOP);
jLabelDiscl.setOpaque(true);
jScrollPanelDiscl.setViewportView(jLabelDiscl);
jButtonOK.setMnemonic('A');
jButtonOK.setText(" Accept ");
jButtonOK.setAlignmentX(0.5F);
jButtonOK.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonOK.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonOKActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelDisclTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jScrollPanelDiscl, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 493, Short.MAX_VALUE))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButtonOK, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(48, 48, 48))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabelDisclTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPanelDiscl, javax.swing.GroupLayout.PREFERRED_SIZE, 337, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButtonOK)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
//<editor-fold defaultstate="collapsed" desc="Events">
private void jButtonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOKActionPerformed
accepted = true;
closeWindow(accepted);
}//GEN-LAST:event_jButtonOKActionPerformed
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
closeWindow(accepted);
}//GEN-LAST:event_formWindowClosing
private void formWindowStateChanged(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowStateChanged
if((getExtendedState() & javax.swing.JFrame.ICONIFIED) // minimised?
== javax.swing.JFrame.ICONIFIED) {
setExtendedState(javax.swing.JFrame.NORMAL);
}
setAlwaysOnTop(true);
toFront();
jButtonOK.requestFocus();
setAlwaysOnTop(false);
}//GEN-LAST:event_formWindowStateChanged
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="closeWindow(accepted)">
/** Closes the Disclaimer window, displays the main window.
* If the user has not "accepted" the disclaimer, the program is ended.
* @param disclaimerAccepted */
public void closeWindow(boolean disclaimerAccepted) {
if(!disclaimerAccepted) {dbF.end_program();}
finished = true;
notify_All();
this.dispose();
} // closeWindow()
private synchronized void notify_All() {notifyAll();}
/** this method will wait for this dialog frame to be closed */
public synchronized void waitForDisclaimer() {
while(!finished) {
try {wait();} catch (InterruptedException ex) {}
} // while
} // waitForDisclaimer()
// </editor-fold>
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButtonOK;
private javax.swing.JLabel jLabelDiscl;
private javax.swing.JLabel jLabelDisclTitle;
private javax.swing.JScrollPane jScrollPanelDiscl;
// End of variables declaration//GEN-END:variables
}
| 12,237 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
DBSearch.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/DataBase/src/database/DBSearch.java | package database;
import lib.common.MsgExceptn;
import lib.common.Util;
import lib.database.Complex;
import lib.kemi.H2O.IAPWSF95;
import lib.database.LibDB;
import lib.database.ProgramDataDB;
import lib.huvud.ProgramConf;
/** Search reactions in the databases.
* <br>
* Copyright (C) 2016-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class DBSearch {
/** the search results: complexes and solids found in the database search */
java.util.ArrayList<Complex> dat = new java.util.ArrayList<Complex>();
/** temperature in degrees Celsius */
double temperature_C = 25;
/** pressure in bar */
double pressure_bar = 25;
/** number of components (soluble and solid) */
int na;
/** number of soluble complexes */
int nx;
/** number of solid reaction products */
int nf;
/** number of solid components */
int solidC;
//<editor-fold defaultstate="collapsed" desc="private fields">
private ProgramConf pc;
private ProgramDataDB pd;
private FrameDBmain dbF;
/** counter: the database being read */
private int db;
/** name of the database being read */
private String complxFileName;
/** the size in bytes of the file being read */
private long complxFileNameSize;
/** a counter indicating how many reactions have been read so far */
private long cmplxNbr = 0;
private final double SIZE_FACTOR_TXT = 54.675;
private final double SIZE_FACTOR_BIN = 124.929;
/** the binary database being read */
private java.io.DataInputStream dis;
/** the text database being read */
private java.io.BufferedReader br;
/** is "e-" among the components selected by the user? */
private boolean redox;
/** the data bases are searched again when new redoc components are found */
private int nLoops;
/** if <code>binaryOrText</code> = 2 reading a binary database<br>
* if <code>binaryOrText</code> = 1 reading text database<br>
* if <code>binaryOrText</code> = 0 then all files are closed (because they have been read) */
private int binaryOrText;
/** Contains the selected components, both the original,
* selected by the user, and new redox components
* (if the user selects Fe+2 and e-, then selectedComps[] contains Fe+2 and Fe+3) */
private java.util.ArrayList<String> selectedComps = new java.util.ArrayList<String>();
/** In advanced mode the user may select to exclude some redox couples,
* for example HS-/SO4-2, or NH3/NO3-. In such a case the complex SO4-2
* has to be excluded if HS- and e- are selected.
* The list with these components/complexes is kept in comps_X[] */
private java.util.ArrayList<String> comps_X = new java.util.ArrayList<String>();
/** List of all other possible components for elements of selected-components.
* For example: if CN- is selected, and it is listed under the elements C and N,
* then <code>comps[]</code> will contain CO3-2, EDTA-4, NO3-, NH3, etc. */
private java.util.ArrayList<String> comps = new java.util.ArrayList<String>();
/** The new redox components. For example, if the user selects H+, e- and Fe+2,
* then <code>selectedComps[]</code> contains H+, e-, Fe+2 and Fe+3 and
* <code>rRedox[]</code> will contain the new redox components (Fe+3).
* @see SearchData#selectedComps selectedComps */
private java.util.ArrayList<Complex> rRedox = new java.util.ArrayList<Complex>();
/** true if the current database has been searched to the end and therefore the next
* database must be opened (if there are any databases left to be searched) */
private boolean openNextFile;
/** true if no databases could be openend and searched */
private boolean noFilesFound;
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
//</editor-fold>
/** Constructor of a DBSearch instance
* @param programConf configuration data about the "calling" program
* @param programData data about the "calling" program, including the list of databases
* @throws DBSearch.SearchException */
public DBSearch(ProgramConf programConf, ProgramDataDB programData)
throws DBSearch.SearchException {
binaryOrText = 0;
noFilesFound = true;
openNextFile = true;
if(programConf == null) {throw new SearchException("Error: programConf = null in \"DBSearch\" constructor");}
this.pc = programConf;
if(programData == null) {throw new SearchException("Error: programDataDB = null in \"DBSearch\" constructor");}
this.pd = programData;
this.temperature_C = pd.temperature_C;
this.pressure_bar = pd.pressure_bar;
}
//<editor-fold defaultstate="collapsed" desc="searchComplexes">
/** Searches the databases for reactions fitting the components selected by the user
* and specified in the selectedComps[] list. If the electron "e-" is selected,
* the databases may have to be scanned repeated times if new redox components
* are found. For example, if {Fe+2, e-} are selected, after the first database
* scan Fe+3 is found, and the databases must be scanned again for {Fe+2, Fe+3, e-}.
*
* The reactions found in the search are stored in ArrayList "dat".
* The progress bars in the lower half of the FrameDBmain show the search progress.
* @param mainFrame
* @throws DBSearch.SearchException */
void searchComplexes (FrameDBmain mainFrame) throws DBSearch.SearchException {
if(mainFrame == null) {MsgExceptn.exception("Error: mainFrame = null in \"searchComplexes\""); throw new SearchException();}
this.dbF = mainFrame;
if(dbF.modelSelectedComps.size() <=0) {
MsgExceptn.exception("Error: modelSelectedComps.size() <=0 in \"searchComplexes\"");
throw new SearchException();
}
if(pd.dataBasesList.size() <=0) {
MsgExceptn.exception("Error: dataBasesList.size() <=0 in \"searchComplexes\"");
throw new SearchException();
}
boolean found;
try{
if(pc.dbg) {System.out.println(FrameDBmain.LINE+nl+"--- Searching reactions");}
nx =0;
nf =0;
binaryOrText = 0;
nLoops = 1;
// --- What components has the user selected?
// For redox systems (the user selected "e-" as a component)
// selectedComps[] contains the selected components, both the original,
// selected by the user, and new redox components. For example, if the user
// selects e- and Fe+2, then selectedComps[] contains Fe+2 and Fe+3)
for(int i = 0; i < dbF.modelSelectedComps.size(); i++) {
selectedComps.add(dbF.modelSelectedComps.get(i).toString());
}
redox = isComponentSelected("e-");
na = selectedComps.size();
solidC = 0;
for(int i =0; i < na; i++) {
if(Util.isSolid(selectedComps.get(i))) {solidC++;}
}
if(dbF.solidSelectedComps != solidC) {
MsgExceptn.exception("Error in \"searchComplexes\":"+nl+
"the number of solid components does not match!");
}
} catch (Exception ex) {throw new SearchException(Util.stack2string(ex));}
// todo ?
/* advanced option: exclude some redox reactions?
If redox And RedoxAsk Then */
if(!redoxChecks()) {
System.out.println("--- Search cancelled.");
return;
}
// -------- For redox systems (the user selected "e-" as a component) ----------
// Make a list of all other possible components for elements of selected-components
// for example: if CN- is selected, and it is listed under the elements C and N,
// the list will contain CO3-2, EDTA-4, NO3-, NH3, etc
// The list is stored in: comps[]
// selectedComps[nSelectedComps] contains the selected components, both the original,
// selected by the user, and new redox components
// (if the user selects Fe+2, then selectedComps[] contains Fe+2 and Fe+3)
// rRedox[] will contain the new redox components (Fe+3)
// The user may select to exclude some redox couples,
// for example HS-/SO4-2, or NH3/NO3-
// In such a case the complex SO4-2 might have to be excluded
// if HS- and e- are selected
// The list with these components/complexes is kept in comps_X[]
// --------------- Redox loop: new components ----------------------------------
try{
if(redox) {
boolean excluded;
String[] elemComp; String selCompName; String el;
for(String selComp : selectedComps) {
selCompName = selComp.toString();
for(int k0 =0; k0< pd.elemComp.size(); k0++) { //loop through all components in the database (CO3-2,SO4-2,HS-,etc)
elemComp = pd.elemComp.get(k0);
if(Util.nameCompare(elemComp[1],selCompName)) { //got the component selected by the user
//Note: array elemComp[0] contains: the name-of-the-element (e.g. "C"),
// the formula-of-the-component ("CN-"), and
// the name-of-the-component ("cyanide")
el = elemComp[0]; //get the element corresponding to the component: e.g. "S" for SO4-2
for(int k1 =0; k1< pd.elemComp.size(); k1++) { //loop through all components in the database (CO3-2,SO4-2,HS-,etc)
elemComp = pd.elemComp.get(k1);
if(elemComp[0].equals(el)) { //got the right element
if(k1 != k0) {
excluded = false;
if((el.equals("N") && !pd.redoxN) || (el.equals("S") && !pd.redoxS)
|| (el.equals("P") && !pd.redoxP)) {
excluded = true;
}
if(!excluded) {
// check if this component is already in the list,
// if it is not, it must be considered as a possible redox component
found = false;
if(comps.size()>0) {
for(String t : comps) {
if(Util.nameCompare(elemComp[1],t)) {found = true; break;}
} //for j
}
if(!found) {comps.add(elemComp[1]);}
} else { //excluded:
//check if this component is already in the list,
//if it is not, it must be considered as a possible redox component
found = false;
if(comps_X.size() >0) {
for(String t : comps_X) {
if(Util.nameCompare(elemComp[1],t)) {found = true; break;}
} //for j
}
if(!found) {comps_X.add(elemComp[1]);}
} //excluded?
} //if k1 != k0
} //elemComp[0] = el
} //for k1; list of all available components
} //if elemComp[1] = selCompName
} //for k0; list of all available components
} // for all selected components
if(pc.dbg) {
int n = comps.size();
System.out.println("--- Possible new redox components:"+nl+" comps[] size:"+n);
for(int j=0; j<n; j++) {System.out.println(" "+comps.get(j));}
n = comps_X.size();
System.out.println(" comps_X[] size:"+n);
for(int j=0; j<n; j++) {System.out.println(" "+comps_X.get(j));}
if(comps.size() > 0 || n > 0) {System.out.println("---");}
}
} //if redox
} catch (Exception ex) {throw new SearchException(Util.stack2string(ex));}
//-------- end of make lists for redox systems ----------
// --------------------------------------------------
// -------- Redox loop: new species -----------------
// loop searching database for redox systems
// (for non-redox systems the loop is run only once)
// --------------------------------------------------
try{
while(true) {
// ---------------------------------------------
// Search databases for all reactions
// ---------------------------------------------
try {scanDataBases();}
catch (SearchInternalException ex) {
if(!(ex instanceof SearchInternalException)) {
String msg = "Error in \"searchComplexes\":"+nl+Util.stack2string(ex);
throw new SearchException(msg);
} else {throw new SearchException(ex.getMessage());}
}
// ---------------------------------------------
if(!redox) {
if(pc.dbg) {System.out.println("--- Search reactions ended.");}
return;
}
//--------- For redox systems:
// If components appear as reaction products it will be needed to search again.
// For example, if the components selected by the user are Fe+2 and e-,
// the database search will find Fe+3 as a complex,
// which must be regarded as a new component
//
// Update: rRedox[] - contains a list with the new components.
// selectedComps[] - contains a list with all components:
// those selected originally by the user and
// the new ones found in the database search.
int n_selectedComps_0 = selectedComps.size();
for(Complex cplx : dat) {
if(cplx.isRedox()) {
found = false;
String t1 = cplx.name;
for(String t2 : comps) {
if(Util.nameCompare(t1,t2)) {
//found a complex (e g Fe+3) which is a component
// check that it is not already selected
found = true;
for(String t3 : selectedComps) {
if(Util.nameCompare(t1,t3)) {found = false; break;}
} //for k
break;
}
} //for j
if(found) {
selectedComps.add(t1);
rRedox.add(cplx);
} //if found
} //if ePresent
} //for cplx
// --------------------------------
// If new redox components have been found,
// one must search the database again.
// For example, if the components selected
// are Fe+2 and e-, the database search will
// find Fe+3 as a new component and another
// database search is needed including Fe+3
// --------------------------------
if(n_selectedComps_0 != selectedComps.size()) {
nLoops++;
continue; //while
}
break;
} //while
} catch (Exception ex) {throw new SearchException(Util.stack2string(ex));}
// --------------------------------
// end loops searching database
// for redox systems
// --------------------------------
// --------------------------------------------------
// -------- Redox loop: correct reactions -----------
// If rRedox() is not empty:
// Perform corrections for the new redox components.
//
// Example: if H+, e- and Fe+2 are choosen,
// a new redox component Fe+3 is found, and
// to the reaction: Fe+3 - H+ = FeOH+2
// one must add: Fe+2 - e- = Fe+3 etc
try{
if(rRedox.size() > 0) {
double n1, n2, np;
int rdxC, fnd, nTot;
String lComp, lComp2;
boolean needsMore;
Complex rcomp;
for(Complex cplx: dat) { // loop through all Complexes
// because cplx is a reference to an object of type Complex in the ArrayList,
// any change to cplx changes the object in the ArrayList (dat)
while (true) {
needsMore = false;
np = 0;
nTot = Math.min(cplx.reactionComp.size(),cplx.reactionCoef.size());
for(int ic=0; ic < nTot; ic++) {
lComp = cplx.reactionComp.get(ic);
if(lComp != null && lComp.length() >0) {
n1 = cplx.reactionCoef.get(ic);
if(Util.isProton(lComp)) {np = n1;}
rdxC = -1; //is this component a new redox component ?
for(int ir=0; ir < rRedox.size(); ir++) {
if(Util.nameCompare(rRedox.get(ir).name, lComp)) {rdxC = ir; break;}
}//for ir
if(rdxC > -1) { //it has a redox component: Make corrections
needsMore = true;
rcomp = rRedox.get(rdxC);
//add the equilibrium constant of rRedox(rdxC)
cplx.constant = cplx.constant + n1 * rcomp.constant;
for(int i = 0; i < cplx.a.length; i++) {
if(cplx.a[i] != Complex.EMPTY && rcomp.a[i] != Complex.EMPTY) {cplx.a[i] = cplx.a[i] + n1 * rcomp.a[i];}
}
if(cplx.lookUp || rcomp.lookUp) {
if(!cplx.lookUp) {cplx.toLookUp();}
if(!rcomp.lookUp) {rcomp.toLookUp();}
for(int i = 0; i < cplx.logKarray.length; i++) {
for(int j = 0; j < cplx.logKarray[i].length; j++) {
if(!Float.isNaN(cplx.logKarray[i][j]) && !Float.isNaN(rcomp.logKarray[i][j])) {
cplx.logKarray[i][j] = cplx.logKarray[i][j] + (float)n1 * rcomp.logKarray[i][j];
} else {cplx.logKarray[i][j] = Float.NaN;}
}
}
}
cplx.tMax = Math.min(cplx.tMax,rcomp.tMax);
cplx.pMax = Math.min(cplx.pMax,rcomp.pMax);
//add all stoichiometric coefficients of rRedox(rDxC)
cplx.reactionComp.set(ic,"");
cplx.reactionCoef.set(ic,0.);
for(int irr=0;
irr < Math.min(rcomp.reactionComp.size(),rcomp.reactionCoef.size());
irr++) {
lComp2 = rcomp.reactionComp.get(irr);
if(lComp2 == null || lComp2.length() <= 0) {continue;}
n2 = rcomp.reactionCoef.get(irr);
fnd = -1;
for(int ic2=0;
ic2<Math.min(cplx.reactionComp.size(), cplx.reactionCoef.size());
ic2++) {
if(Util.nameCompare(cplx.reactionComp.get(ic2), lComp2)) {
fnd = ic2;
cplx.reactionCoef.set(ic2, cplx.reactionCoef.get(ic2) + n1 * n2);
break;
}
}//for ic2
if(fnd < 0) {
cplx.reactionComp.add(lComp2);
if(Util.isProton(lComp2)) {
cplx.reactionCoef.add(np + n1 * n2);
} else {
cplx.reactionCoef.add(n1 * n2);
}//if "H+"
}//if fnd <0
}//for irr
}//if rDxC>-1
}//if lComp
} //for ic
if(!needsMore) {break;}
} //while true
System.out.println(cplx.toString());
System.out.println(cplx.sortReactants().toString());
}//for i (loop through all Complexes)
} //iv sd.rRedox.size() > 0
} catch (Exception ex) {throw new SearchException(Util.stack2string(ex));}
// ------- End of: Perform corretions for
// new redox components.
// ------------------------------------------
// ---------------------------------------------
// end of database search
// ---------------------------------------------
if(pc.dbg) {System.out.println("--- Search reactions ended.");}
} //searchComplexes
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="checkTemperature">
/** Checks that for a given search (srch), where the temperature and
* pressure are specified, each reaction has data that allows the calculation
* of logK at the given temperature and pressure. If any of the reactions does
* not have data, a message is displayed to the user, "false" is returned (not OK).
* If all the reactions have adequate temperature-pressure data, "true" is returned (OK).
*
* @param srch a search engine object, where the temperature and pressure are specified
* @param parent a window to anchor messages
* @param warning if true a "note" message will be displayed telling the user
* that temperature extrapolations will be made
* @return true if there are no problems with the temperature-pressure extrpolations,
* false if some of the reactions do not have data at the required temperature
*/
public static boolean checkTemperature(DBSearch srch, java.awt.Container parent, boolean warning) {
boolean fnd = false, temperatureCorrectionsPossible = true;
if(srch.temperature_C > 24.9 && srch.temperature_C < 25.1) {return temperatureCorrectionsPossible;}
if(srch.nx+srch.nf < 1) {
MsgExceptn.exception("Programming error: checking temperature before \"searchComplexes\".");
return temperatureCorrectionsPossible;
}
java.util.ArrayList<String> items = new java.util.ArrayList<String>();
// Is there T-P data for all reactions?
double maxT = Double.MAX_VALUE, maxP = Double.MAX_VALUE;
String txt;
long cnt = 0;
for(int ix=0; ix < srch.nx+srch.nf; ix++) {
if(srch.temperature_C > srch.dat.get(ix).tMax || srch.pressure_bar > srch.dat.get(ix).pMax
|| Double.isNaN(srch.dat.get(ix).logKatTandP(srch.temperature_C, srch.pressure_bar))) {
if(!fnd) {
System.out.println("--------- Temperature-pressure extrapolations to "
+String.format("%.0f",srch.temperature_C)+" C, pressure = "+
String.format(java.util.Locale.ENGLISH,"%.2f",srch.pressure_bar)+" bar");
fnd = true;
}
if(srch.dat.get(ix).pMax < 221) { // below critical point
txt = String.format("%.3f",srch.dat.get(ix).pMax);
} else {
txt = String.format("%.0f",srch.dat.get(ix).pMax);
}
System.out.println("species \""+srch.dat.get(ix).name+
"\": missing T-P data, max temperature = "+
String.format("%.0f",srch.dat.get(ix).tMax)+", max pressure = "+txt);
items.add(srch.dat.get(ix).name);
maxT = Math.min(maxT, srch.dat.get(ix).tMax);
maxP = Math.min(maxP, srch.dat.get(ix).pMax);
cnt++;
}
}
if(cnt >0) {
System.out.println("---------");
//javax.swing.DefaultListModel aModel = new javax.swing.DefaultListModel(); // java 1.6
java.util.Iterator<String> iter = items.iterator();
txt = "";
while(iter.hasNext()) {txt = txt+iter.next()+"\n";}
String msg = "<html><font size=\"+1\"><b>Error:</b></font><br>"+
"Temperature and pressure extrapolations are<br>"+
"requested to "+
String.format("%.0f",srch.temperature_C)+"°C and pressure = ";
if(srch.pressure_bar > IAPWSF95.CRITICAL_pBar) {msg = msg + Util.formatNumAsInt(srch.pressure_bar);}
else {msg = msg + String.format(java.util.Locale.ENGLISH,"%.2f",srch.pressure_bar);}
msg = msg + " bar,<br>but the necessary temperature-pressure<br>"+
"data are missing for the following species:</html>";
javax.swing.JLabel aLabel = new javax.swing.JLabel(msg);
// javax.swing.JList aList = new javax.swing.JList(aModel); // java 1.6
javax.swing.JTextArea aTextArea = new javax.swing.JTextArea(6,20);
javax.swing.JScrollPane scrollPane = new javax.swing.JScrollPane(aTextArea);
scrollPane.setVerticalScrollBarPolicy(javax.swing.JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
aTextArea.append(txt);
aTextArea.setEditable(true);
aTextArea.addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {evt.consume();}
@Override
public void keyTyped(java.awt.event.KeyEvent evt) {evt.consume();}
});
aTextArea.setFocusable(true);
String p = "\"pSat\" (vapor-liquid equilibrium)";
if(maxP > IAPWSF95.CRITICAL_pBar) {p = Util.formatNumAsInt(maxP)+" bar";}
javax.swing.JLabel endLabel = new javax.swing.JLabel(
"<html>For these reactions the maximum extrapolation<br>"+
"temperature is "+Util.formatNumAsInt(maxT)+"°C, and maximum<br>"+
"pressure is "+p+".<br> <br>"+
"Please change the temperature in the menu \"Options\".</html>");
Object[] o = {aLabel, scrollPane, endLabel};
javax.swing.JOptionPane.showMessageDialog(parent, o, "Temperature extrapolations",
javax.swing.JOptionPane.ERROR_MESSAGE);
temperatureCorrectionsPossible = false;
} else { // cnt <= 0
temperatureCorrectionsPossible = true;
if(warning) {
String msg = "Note:"+nl+"Equilibrium constants will be"+nl+
"extrapolated from 25 to "+Util.formatNumAsInt(srch.temperature_C)+"°C"+nl+"(pressure ";
if(srch.pressure_bar > IAPWSF95.CRITICAL_pBar) {msg = msg + Util.formatNumAsInt(srch.pressure_bar);}
else {msg = msg + String.format(java.util.Locale.ENGLISH,"%.2f",srch.pressure_bar);}
msg = msg + " bar)"+nl+"when you save the data file.";
javax.swing.JOptionPane.showMessageDialog(parent,msg,
"Selected Temperature = "+Util.formatNumAsInt(srch.temperature_C),
javax.swing.JOptionPane.WARNING_MESSAGE);
} // if warning
} // cnt >0?
return temperatureCorrectionsPossible;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="private methods">
//<editor-fold defaultstate="collapsed" desc="scanDataBases">
/** Reads all databases looking for all reaction products formed by the components
* in the selectedComps[] list. The reactions found are stored in ArrayList "dat".
* @throws DBSearch.SearchInternalException */
private void scanDataBases() throws DBSearch.SearchInternalException {
if(pc.dbg) {
System.out.println("--- \"scanDataBases\", nLoops = "+nLoops+", Selected components:");
for (String selectedComp : selectedComps) {System.out.println(" " + selectedComp);}
System.out.println("---");
}
int answer; String msg, t; boolean found; int i,j;
boolean firstComplex = true;
Complex rr;
complxFileName = "";
// the number of "components" will vary for redox systems,
// for example, if Fe+2 is selected by the user, we have to search Fe+3 as well
int nSelectedComps = selectedComps.size();
// ---------------------------------------------
// Search all databases for reactions
// ---------------------------------------------
while(true) {
rr = getOneComplex(firstComplex); //throws SearchInternalException()
if(rr == null) {break;} //no more reactions
if(rr.name.length() >0) {
//---- make some primitive consistency checks, in case of a text file
if(binaryOrText == 1 && nLoops ==1) {
msg = rr.check();
for(String s : rr.reactionComp) {
//check if the component is in the list of possible components
if(s != null && s.length() >0) {
found = false;
String[] elemComp;
for(j=0; j < pd.elemComp.size(); j++) {
elemComp = pd.elemComp.get(j);
if(Util.nameCompare(s,elemComp[1])) {found = true; break;}
} //for j
if(!found) {
t = "Component \""+s+"\" in complex \""+rr.name+"\""+nl+"not found in the element-files.";
if(msg.length() > 0) {msg = msg +nl+ t;} else {msg = t;}
}//not found
}
}//for i
if(msg != null) {
int nTot = Math.min(rr.reactionComp.size(),rr.reactionCoef.size());
System.out.println("---- Error \""+msg+"\""+nl+" for complex \""+rr.name+"\", logK="+rr.constant+", ref.=\""+rr.reference+"\"");
for(i=0; i< nTot; i++) {System.out.print(" "+rr.reactionComp.get(i)+" "+rr.reactionCoef.get(i)+";");}
System.out.println();
Object[] opt = {"OK", "Cancel"};
answer = javax.swing.JOptionPane.showOptionDialog(dbF,
"Error in file \""+complxFileName+"\""+nl+"\""+msg+"\"",
pc.progName, javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[1]);
if(answer != javax.swing.JOptionPane.YES_OPTION) {
try{
if(binaryOrText ==2 && dis != null) {dis.close();}
else if(binaryOrText ==1 && br != null) {br.close();}
} catch (java.io.IOException e) {}
throw new SearchInternalException();
}
} //if msg !=null
} //if text file and nLoops =1
//---- end of consistency checks
if(!rr.name.startsWith("@")) {
// ----- Name does not begin with "@" (the normal case)
// Add the complex
//check if we have already this complex. If found: replace it
boolean include = true;
if(redox) { //does this complex involve "e-" ?
boolean ePresent = false;
for(String s : rr.reactionComp) {
if (Util.isElectron(s)) {ePresent = true; break;}
}
if(ePresent) {
//does the user want to exclude this complex/component from redox equilibria?
for(j=0; j < comps_X.size(); j++) {
if(Util.nameCompare(rr.name,comps_X.get(j))) { //the complex (e g Fe+3) is a component to be excluded
include = false; break;
}
} //for j
if(include) {
//It could be a new redox component (like Fe+2 - e- = Fe+3)
//if so: replace RRedox if already found, otherwise add it
found = false; //check if it is already selected
for(int k=0; k < selectedComps.size(); k++) {
if(Util.nameCompare(rr.name,selectedComps.get(k))) {found = true; break;}
} //for k
if(found) { //already selected: replace?
if(pc.dbg) {System.out.println("Complex already there (it was one of the components): "+rr.name);}
include = false; //the complex was already there
//-- Replace rRedox if same name + same stoichiometry
for(i=0; i < rRedox.size(); i++) {
if(Complex.sameNameAndStoichiometry(rr, rRedox.get(i))) {
if(pc.dbg) {System.out.println("Complex already there and same stoichiometry: "+rr.name);}
rRedox.set(i, rr); break;
}
}//for i
} //if found
////The complex was not in the RRedox-list:
////Should it be excluded because the user does not want
//// redox equilibria for this element?
////This is done with the function "isRedoxComp" (= true if the component
//// only contains one element and H/O.
//// For example: SO4-2 contains only "S" isRedoxComp=true;
//// but for Fe(SO4)2- isRedoxComp=false)
//boolean exclude = false;
//if(isRedoxComp("C", rr.name) && !pd.redoxC) {exclude = true;}
//if(isRedoxComp("N", rr.name) && !pd.redoxN) {exclude = true;}
//if(isRedoxComp("S", rr.name) && !pd.redoxS) {exclude = true;}
//if(isRedoxComp("P", rr.name) && !pd.redoxP) {exclude = true;}
//if(exclude) {include = false;}
} //if include
} //if ePresent
} //if redox
//If "include": add the complex (replace otherwise)
if(include) {
found = false;
for(i = 0; i < dat.size(); i++) {
if(Util.nameCompare(rr.name,dat.get(i).name)) { //replace!
dat.set(i, rr); found = true; break;
}
}//for i
if(!found) { //add!
//allSolids: 0=include all solids; 1=exclude (cr); 2=exclude (c); 3=exclude (cr)&(c)
boolean excludeSolid = true;
if(!Util.is_cr_or_c_solid(rr.name) ||
pd.allSolids == 0 ||
(Util.is_cr_solid(rr.name) && pd.allSolids !=1 && pd.allSolids !=3) ||
(Util.is_c_solid(rr.name) && pd.allSolids <2)) {excludeSolid = false;}
if(excludeSolid) {
final String s; if(pd.allSolids == 1) {s="(cr) solids excluded!";}
else if(pd.allSolids == 2) {s="(c) solids excluded!";}
else if(pd.allSolids == 3) {s="(cr) & (c) solids excluded!";} else {s = " ";}
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
dbF.jLabel_cr_solids.setText(s);
}});
} else { //include solid or not a solid
if(Util.isSolid(rr.name)) {
dat.add(rr);
nf++;
} //if solid
else { //soluble
dat.add(nx, rr);
nx++;
} //solid/soluble?
} //excludeSolid?
}//if !found
}//if include
// ----- end of: name does Not begin with a "@"
} else {
// ----- Complex name begins with "@"
// Withdraw the complex if it already has been read from the database
rr.name = rr.name.substring(1);
// first see if it is a "normal" complex
if(nx+nf >0) {
i = 0;
do{ //while (i < (nx+nf)) --- loop through all reactions
if(Util.nameCompare(dat.get(i).name,rr.name)) {
dat.remove(i);
if(i < nx) {nx--;} else {nf--;}
}
else {i++;}
} while (i < (nx+nf));
} //if nx+nf >0
// if redox: remove any components that are equivalent to the @-complex
if(redox) {
int fnd = -1;
for(j = dbF.modelSelectedComps.size(); //search only new redox comps.
j < nSelectedComps; j++) {
if(Util.nameCompare(rr.name,selectedComps.get(j))) {fnd = j; break;}
}
if(fnd > -1) {
//First remove from components list
selectedComps.remove(fnd);
nSelectedComps--;
//2nd remove from "rRedox"
for(j =0; j<rRedox.size(); j++) {
if(Util.nameCompare(rr.name,rRedox.get(j).toString())) {rRedox.remove(j); break;}
}//for j
//remove from "dat" all reaction products formed by this redox component:
if(nx+nf >0) {
i = 0;
do{ //while (i < (nx+nf)) --- loop through all reactions
found = false;
for(String s : dat.get(i).reactionComp) {
if(Util.nameCompare(s,rr.name)) {found = true; break;}
}
if(found) {
dat.remove(i);
if(i < nx) {nx--;} else {nf--;}
} //if found
else {i++;}
} while (i < (nx+nf));
} //if nx+nf >0
} //if fnd >-1
} //if redox
} //----- end of: the name begins with a "@"
} //if rr.name.length() >0
if(binaryOrText == 0) {break;}
firstComplex = false;
} //while
// -----------------------------------------------
// end of database search
// -----------------------------------------------
try{
if(binaryOrText ==2 && dis != null) {dis.close();}
else if(binaryOrText ==1 && br != null) {br.close();}
} catch (java.io.IOException e) {}
dbF.updateProgressBarLabel(" ", 0);
dbF.updateProgressBar(0);
} //scanDataBases()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="getOneComplex">
/** This routine will get the next "complex" with the condition that
* all its components must be in the "selected-components" list.
* Both binary and text files will be read.
* This routine is NOT called to convert database files (Text <=> Binary).
* <p> On output:<br>
* if <code>binaryOrText</code> = 2 reading binary database<br>
* if <code>binaryOrText</code> = 1 reading text database<br>
* if <code>binaryOrText</code> = 0 then all files are closed
* (because they have been read)
*
* @param firstComplex if true the first file is opened and the first complex
* is searched for; if false then find the next complex from the list of
* database files
* @return
* @see lib.database.LibSearch#getComplex(boolean) getComplex
* @throws DBSearch.SearchInternalException */
private Complex getOneComplex(boolean firstComplex) throws DBSearch.SearchInternalException {
boolean protonPresent;
String msg;
if(firstComplex) {
//open the first file
openNextFile = true;
db = 0;
}
while (db < pd.dataBasesList.size()) {
if(openNextFile) {
try{
if(dis != null) {dis.close();} else if(br != null) {br.close();}
} catch (java.io.IOException ioe) {MsgExceptn.msg(ioe.getMessage());}
complxFileName = pd.dataBasesList.get(db);
if(complxFileName == null || complxFileName.length() <=0) {continue;}
java.io.File dbf = new java.io.File(complxFileName);
if(!dbf.exists() || !dbf.canRead()) {
msg = "Error: can not open file"+nl+
" \""+complxFileName+"\".";
if(!dbf.exists()) {msg = msg +nl+ "(the file does not exist)."+nl+
"Search terminated";}
throw new SearchInternalException(msg);
}
complxFileNameSize = dbf.length();
cmplxNbr = 0;
this.dbF.updateProgressBarLabel("Searching \""+complxFileName+"\"", nLoops);
this.dbF.updateProgressBar(0);
//--- text or binary?
try{
if(binaryOrText ==2 && dis != null) {dis.close();}
else if(binaryOrText ==1 && br != null) {br.close();}
} catch (java.io.IOException e) {}
try{
if(complxFileName.toLowerCase().endsWith("db")) { //--- binary file
binaryOrText = 2;
dis = new java.io.DataInputStream(new java.io.FileInputStream(dbf));
} else { //--- text file
binaryOrText = 1;
br = new java.io.BufferedReader(
new java.io.InputStreamReader(
new java.io.FileInputStream(dbf),"UTF8"));
// -- comments at the top of the file
// topComments = rd.dataLineComment.toString();
} //--- text or binary?
}
catch (Exception ex) {
try{
if(dis != null) {dis.close();} else if(br != null) {br.close();}
} catch (Exception ioe) {MsgExceptn.msg(ioe.getMessage());}
msg = "Error: "+ex.toString()+nl+
"while trying to open file: \""+complxFileName+"\"."+nl+"search terminated";
throw new SearchInternalException(msg);
}
noFilesFound = false;
openNextFile = false;
if(pc.dbg) {System.out.println("Scanning database \""+complxFileName+"\"");}
} //if sd.openNextFile
Complex complex = null;
loopComplex:
while (true) {
cmplxNbr++;
if(binaryOrText ==2) { //Binary complex database
try {
complex = LibDB.getBinComplex(dis);
dbF.updateProgressBar((int)(100*(double)cmplxNbr*SIZE_FACTOR_BIN
/(double)complxFileNameSize));
}
catch (LibDB.ReadBinCmplxException ex) {
msg = "Error: in \"getOneComplex\", cmplxNbr = "+cmplxNbr+nl+
"ReadBinCmplxException: "+ex.getMessage()+nl+
"in file: \""+complxFileName+"\"";
throw new SearchInternalException(msg);
}
} //binaryOrText =2 (Binary file)
else if(binaryOrText ==1) { // Text complex database
try {
try{
complex = LibDB.getTxtComplex(br);
dbF.updateProgressBar((int)(100*(double)cmplxNbr*SIZE_FACTOR_TXT
/(double)complxFileNameSize));
}
catch (LibDB.EndOfFileException ex) {complex = null;}
}
catch (LibDB.ReadTxtCmplxException ex) {
msg = "Error: in \"getOneComplex\", cmplxNbr = "+cmplxNbr+nl+
ex.getMessage()+nl+
"in file: \""+complxFileName+"\"";
throw new SearchInternalException(msg);
}
} //binaryOrText =1 (Text file)
if(complex == null || complex.name == null) {break;} // loopComplex // end-of-file, open next database
if(complex.name.startsWith("@")) {return complex;}
// --- is this a species formed from the selected components?
protonPresent = false;
int nTot = Math.min(complex.reactionComp.size(),complex.reactionCoef.size());
for(int i=0; i < nTot; i++) {
if(complex.reactionComp.get(i) == null || complex.reactionComp.get(i).length() <=0 ||
Util.isWater(complex.reactionComp.get(i))) {continue;} //H2O
if(!isComponentSelected(complex.reactionComp.get(i)) &&
Math.abs(complex.reactionCoef.get(i)) >0.0001) {continue loopComplex;}
if(Util.isProton(complex.reactionComp.get(i))) {protonPresent = true;}
} //for i
// all components are selected: select complex
return complex;
} //while (true) --- loopComplex:
// ----- no complex found: end-of-file, or error. Get next file
db++;
openNextFile = true;
} //while sd.db < pd.dataBasesList.size()
if(noFilesFound) { // this should not happen...
MsgExceptn.exception("Error: none of the databases could be found.");
throw new SearchInternalException();
}
try{
if(dis != null) {dis.close();} else if(br != null) {br.close();}
} catch (java.io.IOException ioe) {MsgExceptn.msg(ioe.getMessage());}
binaryOrText = 0;
return null; //return null if no more reactions
} //getOneComplex
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="isComponentSelected">
/** find out if "component" is in the list of selected components
* (in ArrayList selectedComps) */
private boolean isComponentSelected(String component) {
for(int i=0; i< selectedComps.size(); i++) {
if(Util.nameCompare(component,selectedComps.get(i))) {return true;}
}
return false;
} //isComponentSelected
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="isRedoxComp(element, component)">
/** For a given component, and one of its elements:
* is this a component which might be involved in redox equilibria?
* This is used to warn the user of a possible problem in the choice of components.
* For example, if the user selects both V+2 and VO2+, it might be better to choose
* instead V+2 and e-.<br>
* Rule: if the component is formed by only the element, oxygen and hydrogen,
* then return <code>true</code>. Examples: Fe+2, CrO4-2, H2PO4-
* (return <code>true</code> for the elements Fe, Cr and P),
* while for CN- return <code>false</code>. */
private static boolean isRedoxComp(String element, String component) {
StringBuilder comp = new StringBuilder(component);
//---If it does not contain the element in the name, it is not a redox couple
int i = component.indexOf(element);
if(i<0) {return false;}
//---Take away *, @, at the beginning of the name
if(comp.length() >=2) {
if(comp.charAt(0) == '*' || comp.charAt(0) == '@') {
comp.delete(0, 1);
}
}
//--- Take away diverse endings:
// --- Take away (c), (s), (l), (g)
if(comp.length() >=4) {
String end = comp.substring(comp.length()-3, comp.length());
if(end.equalsIgnoreCase("(c)") || end.equalsIgnoreCase("(s)") ||
end.equalsIgnoreCase("(l)") || end.equalsIgnoreCase("(g)")) {
comp.delete(comp.length()-3, comp.length());
}
}
// --- Take away (cr), (am), (aq)
if(comp.length() >=5) {
String end = comp.substring(comp.length()-4, comp.length());
if(end.equalsIgnoreCase("(cr)") || end.equalsIgnoreCase("(am)") ||
end.equalsIgnoreCase("(aq)")) {comp.delete(comp.length()-3, comp.length());}
}
// --- Take away (vit)
if(comp.length() >=6) {
String end = comp.substring(comp.length()-5, comp.length());
if(end.equalsIgnoreCase("(vit)")) {comp.delete(comp.length()-3, comp.length());}
}
//--- Take away numbers charge (+/-) and space
i = 0;
while(i<comp.length()) {
if((comp.charAt(i)>='0' && comp.charAt(i)<='9') || comp.charAt(i) == '+' ||
comp.charAt(i) == '-' ||
comp.charAt(i) == '\u2013' || comp.charAt(i) == '\u2212' || // unicode en dash or minus
comp.charAt(i) == '.' || comp.charAt(i) == ';' || comp.charAt(i) == ',' ||
comp.charAt(i) == '(' || comp.charAt(i) == ')' ||
comp.charAt(i) == '[' || comp.charAt(i) == ']' ||
comp.charAt(i) == '{' || comp.charAt(i) == '}') {
comp.delete(i, i+1);
} else {i++;}
} //while
//--- Take away the element name
while(true) {
i = comp.indexOf(element);
if(i<0) {break;}
comp.delete(i, i+element.length());
} //while
//--- Take away oxygen
while(true) {
i = comp.indexOf("O");
if(i<0) {break;}
comp.delete(i, i+1);
} //while
//--- Take away hydrogen
while(true) {
i = comp.indexOf("H");
if(i<0) {break;}
comp.delete(i, i+1);
} //while
//--- Take away white space
i = 0;
while(i<comp.length()) {
if(Character.isWhitespace(comp.charAt(i))) {comp.delete(i, i+1);}
else {i++;}
} //while
return comp.length() <= 0;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="redoxChecks">
/** Checks that the user does not select both Fe+2 and Fe+3 as components...
* @return true (go on with the search) if there was no problem (two similar components were not selected)
* or if the user clicks to go ahead anyway. Returns false (cancel the search) if there was a
* problem and the user selected to cancel the search
*/
private boolean redoxChecks() {
if(pc.dbg) {System.out.println("--- \"redoxChecks\". redox = "+redox);}
//----------
// Check that the user does not select both Fe+2 and Fe+3 as components...
//----------
// This is done with the function "is_redox" that =True if the component
// only contains one element and H/O. For example: SO4-2 contains only "S" is_redox%=True; but for CN- is_redox%=False
String[] elemComp; String selCompName, el; boolean problem = false;
for(int i =0; i< selectedComps.size(); i++) { //loop through all components selected by the user (e.g.: H+,CO3-,Fe+3)
selCompName = selectedComps.get(i).toString();
for(int k0 =0; k0< pd.elemComp.size(); k0++) { //loop through all components in the database (CO3-2,SO4-2,HS-,etc)
elemComp = pd.elemComp.get(k0);
if(Util.nameCompare(elemComp[1],selCompName)) { //this component has been selected by the user
//Note: array ElemComp[0] contains: the name-of-the-element (e.g. "C"),
// the formula-of-the-component ("CN-"), and
// the name-of-the-component ("cyanide")
el = elemComp[0]; //get the element corresponding to the component: e.g. "S" for SO4-2
if(!isRedoxComp(el, selCompName)) {break;} // k0
if(!pd.redoxAsk || redox) {
if(el.equals("N") && !pd.redoxN) {break;} // k0
else if(el.equals("P") && !pd.redoxP) {break;} // k0
else if(el.equals("S") && !pd.redoxS) {break;} // k0
}
//the component selected by the user "is redox": it only contains one element in addition to H/O
// such as H+, SO4-2 or Fe+3.
//Look and see if there are other components for the same element
for(int k1 =0; k1< pd.elemComp.size(); k1++) { //loop through all components in the database (CO3-2,SO4-2,HS-,etc)
elemComp = pd.elemComp.get(k1);
if(elemComp[0].equals(el)) { //got the right element
if(!Util.nameCompare(elemComp[1],selCompName)) { //look at all other components with the same element
if(isRedoxComp(el, elemComp[1])) {
// this component also "is redox".
// For example, the user selected SO4-2 and this component is HS-
// check if this redox component has also been selected by the user
for(int k2 =i; k2< selectedComps.size(); k2++) { //search the rest of the selected components
if(Util.nameCompare(elemComp[1],selectedComps.get(k2).toString())) {
problem = true;
String msg = "Warning!"+nl+"You selected two components for the same element:"+
" \""+selCompName+"\" and \""+elemComp[1]+"\""+nl+
"They are probably related by redox reactions."+nl;
if(redox) {msg = msg + "You should remove one of these components.";}
else {
msg = msg + "You should instead select \"e-\" as a component, and remove either "+
"\""+selCompName+"\" or \""+elemComp[1]+"\".";
} //if redox
msg = msg + nl + "The calculations will then determine their respective concentrations."+nl+nl+
"Are you sure that you want to continue ?";
System.out.println("- - - - - -"+nl+msg+nl+"- - - - - -");
Object[] opt = {"Continue", "Cancel"};
int answer = javax.swing.JOptionPane.showOptionDialog(
dbF, msg, pc.progName, javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE, null, opt, opt[1]);
if(answer != javax.swing.JOptionPane.YES_OPTION) {
System.out.println("Answer: Cancel");
return false;
}
System.out.println("Answer: Continue anyway");
} //if elemComp[1] = dbF.modelSelectedComps[k2]
} //for k2
}//isRedoxComp(el, elemComp[1])
}//elemComp[1] != selCompName
}//elemComp[0] = el
} //for k1
} //if elemComp[1] = selCompName
} //for k0
} //for i
//---------- check ends
if(pc.dbg && !problem) {System.out.println("Checks ok.");}
return true;
} //redoxChecks
//</editor-fold>
//</editor-fold>
class SearchException extends Exception {
public SearchException() {super();}
public SearchException(String txt) {super(txt);}
} // SearchException
private class SearchInternalException extends Exception {
public SearchInternalException() {super();}
public SearchInternalException(String txt) {super(txt);}
} //SearchInternalException
}
| 55,429 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
!go_java-launchers.cmd | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/NSIS/src/!go_java-launchers.cmd | @echo off
rem --- Windows script to make java launchers
rem (exe-files) for the jar-file
prompt -$g
echo =========================================================================
echo Updating java-launchers (exe-files)
echo ========== current working directory:
cd
set _sc_=..\..\..\trunk
set _wf_=..\..\..\Windows-files
if NOT exist "\PortableApps\NSISPortable\App\NSIS\makensisw.exe" (
echo.**** ERROR: file "\PortableApps\NSISPortable\App\NSIS\makensisw.exe"
echo. does not exist!?
goto xit
)
if NOT exist "\bin\nmake.exe" (
echo.**** ERROR - file not found: "\bin\nmake.exe" ****
goto xit
)
if NOT exist ".\makefile_java-launchers" (
echo **** ERROR: file ".\makefile_java-launchers" does not exist!?
goto xit
)
REM check the source for the PortableApps launchers
if NOT exist ".\PortableApps\Other\Source" (
echo.**** ERROR: folder ".\PortableApps\Other\Source"
echo. does not exist!?
goto xit
)
REM check the destination folders:
if NOT exist "%_wf_%" (
echo.creating folder "%_wf_%"
mkdir "%_wf_%"
if ERRORLEVEL 1 (echo can NOT create folder. Terminating... & goto xit:)
)
if NOT exist "%_wf_%\PortableApps_exe" (
echo creating folder "%_wf_%\PortableApps_exe"
mkdir "%_wf_%\PortableApps_exe"
if ERRORLEVEL 1 (echo can NOT create folder. Terminating... & goto xit:)
)
echo ======== running: nMake -f makefile_java-launchers
\bin\nmake -f makefile_java-launchers /noLogo
echo ======== nMake finished.
echo. "exe"-files (java-launchers) are in folder: "Windows-files"
if "%1"=="" echo.All done.
:xit
prompt $p$g
if "%1"=="" pause
| 1,663 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
makefile_java-launchers | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/NSIS/src/makefile_java-launchers |
.SUFFIXES: .nsi .exe
win=..\..\..\Windows-files
pa=..\..\..\Windows-files\PortableApps_exe
s=.\PortableApps\Other\Source
NSIS=\PortableApps\NSISPortable\App\NSIS\makensisw
{}.nsi{$(win)}.exe:
if exist $@ del $@ > nul
call $(NSIS) $(*B).nsi
all : $(pa)\DatabasePortable.exe $(pa)\SpanaPortable.exe \
$(win)\AddShowReferences.exe \
$(win)\Chem_Diagr_Help.exe \
$(win)\DataBase.exe \
$(win)\DataMaintenance.exe \
$(win)\ShellChangeNotify.exe \
$(win)\Spana.exe \
$(win)\SED.exe \
$(win)\Predom.exe
$(pa)\DatabasePortable.exe : $(s)\DatabasePortable.nsi \
$(s)\DatabasePortable.gif \
$(s)\DatabasePortable.ico
@if exist $@ del $@ > nul
call $(NSIS) $(s)\$(*B).nsi
@if exist $(s)\$(*B).exe move /y $(s)\$(*B).exe $@ >nul
$(pa)\SpanaPortable.exe : $(s)\SpanaPortable.nsi \
$(s)\SpanaPortable.gif \
$(s)\SpanaPortable.ico
@if exist $@ del $@ > nul
call $(NSIS) $(s)\$(*B).nsi
@if exist $(s)\$(*B).exe move /y $(s)\$(*B).exe $@ >nul
$(win)\AddShowReferences.exe : AddShowReferences.nsi images\Refs.ico
@if exist $@ del $@ > nul
call $(NSIS) $(*B).nsi
@if exist $(*B).exe move /y $(*B).exe $@ >nul
$(win)\Chem_Diagr_Help.exe : Chem_Diagr_Help.nsi images\Help.ico
@if exist $@ del $@ > nul
call $(NSIS) $(*B).nsi
@if exist $(*B).exe move /y $(*B).exe $@ >nul
$(win)\DataMaintenance.exe : DataMaintenance.nsi images\Data.ico
@if exist $@ del $@ > nul
call $(NSIS) $(*B).nsi
@if exist $(*B).exe move /y $(*B).exe $@ >nul
$(win)\DataBase.exe : DataBase.nsi images\DataBase.ico
@if exist $@ del $@ > nul
call $(NSIS) $(*B).nsi
@if exist $(*B).exe move /y $(*B).exe $@ >nul
$(win)\SED.exe : SED.nsi images\SED.ico
@if exist $@ del $@ > nul
call $(NSIS) $(*B).nsi
@if exist $(*B).exe move /y $(*B).exe $@ >nul
$(win)\Predom.exe : Predom.nsi images\Predom.ico
@if exist $@ del $@ > nul
call $(NSIS) $(*B).nsi
@if exist $(*B).exe move /y $(*B).exe $@ >nul
$(win)\Spana.exe : Spana.nsi images\Spana_diagram.ico
@if exist $@ del $@ > nul
call $(NSIS) $(*B).nsi
@if exist $(*B).exe move /y $(*B).exe $@ >nul
$(win)\ShellChangeNotify.exe : ShellChangeNotify.nsi images\Folder.ico
@if exist $@ del $@ > nul
call $(NSIS) $(*B).nsi
@if exist $(*B).exe move /y $(*B).exe $@ >nul
| 2,483 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
ErrMsgBox.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/SED/src/simpleEquilibriumDiagrams/ErrMsgBox.java | package simpleEquilibriumDiagrams;
/** Displays a "message box" modal dialog with an "OK" button and a title.
* The message is displayed in a text area (non-editable),
* which can be copied and pasted elsewhere.
*
* Copyright (C) 2014-2016 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class ErrMsgBox {
private static final String nl = System.getProperty("line.separator");
//<editor-fold defaultstate="collapsed" desc="ErrMsgBox(msg, title)">
/** Displays a "message box" modal dialog with an "OK" button and a title.
* The message is displayed in a text area (non-editable),
* which can be copied and pasted elsewhere.
* @param msg will be displayed in a text area, and line breaks may be
* included, for example: <code>new MsgBox("Very\nbad!",""); </code>
* If null or empty nothing is done.
* @param title for the dialog. If null or empty, "Error:" is used
* @see #showErrMsg(java.awt.Component, java.lang.String, int) showErrMsg
* @version 2015-July-14 */
public ErrMsgBox(String msg, String title) {
if(msg == null || msg.trim().length() <=0) {
System.out.println("--- MsgBox: null or empty \"message\".");
return;
}
//--- Title
if(title == null || title.length() <=0) {title = " Error:";}
java.awt.Frame frame = new java.awt.Frame(title);
//--- Icon
String iconName = "images/ErrMsgBx.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
if(imgURL != null) {frame.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());}
else {System.out.println("--- Error in MsgBox constructor: Could not load image = \""+iconName+"\"");}
frame.pack();
//--- centre Window frame on Screen
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int left; int top;
left = Math.max(55, (screenSize.width - frame.getWidth() ) / 2);
top = Math.max(10, (screenSize.height - frame.getHeight()) / 2);
frame.setLocation(Math.min(screenSize.width-100, left), Math.min(screenSize.height-100, top));
//---
final String msgText = wrapString(msg.trim(),80);
//System.out.println("--- MsgBox:"+nl+msgText+nl+"---");
frame.setVisible(true);
//javax.swing.JOptionPane.showMessageDialog(frame, msg, title, javax.swing.JOptionPane.ERROR_MESSAGE);
MsgBoxDialog msgBox = new MsgBoxDialog(frame, msgText, title, true);
msgBox.setVisible(true); // becase the dialog is modal, statements below will wait
msgBox.dispose();
frame.setVisible(false);
frame.dispose();
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="private class MsgBoxDialog">
private static class MsgBoxDialog extends java.awt.Dialog {
private java.awt.Button ok;
private java.awt.Panel p;
private final java.awt.TextArea text;
/** Creates new form NewDialog */
public MsgBoxDialog(java.awt.Frame parent, String msg, String title, boolean modal) {
super(parent, (" "+title), modal);
addWindowListener(new java.awt.event.WindowAdapter() {
@Override public void windowClosing(java.awt.event.WindowEvent evt) {
MsgBoxDialog.this.setVisible(false);
}
});
setLayout(new java.awt.BorderLayout());
p = new java.awt.Panel();
p.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER));
ok = new java.awt.Button();
// find out the size of the message (width and height)
final int wMax = 85; final int hMax=20;
final int wMin = 5; final int hMin = 1;
int w = wMin;
int h=hMin; int i=0; int j=wMin;
final String eol = "\n"; char c;
final String nl = System.getProperty("line.separator");
while (true) {
c = msg.charAt(i);
String s = String.valueOf(c);
if(s.equals(eol) || s.equals(nl)) {
h++; j=wMin;
} else {
j++; w = Math.max(j,w);
}
i++;
if(i >= msg.length()-1) {break;}
}
// create a text area
int scroll = java.awt.TextArea.SCROLLBARS_NONE;
if(w > wMax && h <= hMax) {scroll = scroll & java.awt.TextArea.SCROLLBARS_HORIZONTAL_ONLY;}
if(h > hMax && w <= wMax) {scroll = scroll & java.awt.TextArea.SCROLLBARS_VERTICAL_ONLY;}
if(w > wMax && h > hMax) {scroll = java.awt.TextArea.SCROLLBARS_BOTH;}
w = Math.min(Math.max(w,10),wMax);
h = Math.min(h,hMax);
text = new java.awt.TextArea(msg, h, w, scroll);
text.setEditable(false);
//text.setBackground(java.awt.Color.white);
text.addKeyListener(new java.awt.event.KeyAdapter() {
@Override public void keyPressed(java.awt.event.KeyEvent evt) {
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER
|| evt.getKeyCode() == java.awt.event.KeyEvent.VK_ESCAPE) {closeDialog();}
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_TAB) {ok.requestFocusInWindow();}
}
});
text.setBackground(java.awt.Color.WHITE);
text.setFont(new java.awt.Font("monospaced", java.awt.Font.PLAIN, 12));
add(text, java.awt.BorderLayout.CENTER);
ok.setLabel("OK");
ok.addActionListener(new java.awt.event.ActionListener() {
@Override public void actionPerformed(java.awt.event.ActionEvent evt) {
closeDialog();
}
});
ok.addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER
|| evt.getKeyCode() == java.awt.event.KeyEvent.VK_ESCAPE) {closeDialog();}
}
});
p.add(ok);
add(p, java.awt.BorderLayout.SOUTH);
pack();
ok.requestFocusInWindow();
//--- centre Window frame on Screen
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int left; int top;
left = Math.max(55, (screenSize.width - getWidth() ) / 2);
top = Math.max(10, (screenSize.height - getHeight()) / 2);
setLocation(Math.min(screenSize.width-100, left), Math.min(screenSize.height-100, top));
}
private void closeDialog() {this.setVisible(false);}
} // private static class MsgBoxDialog
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="private wrapString">
/** Returns an input string, with lines that are longer than <code>maxLength</code>
* word-wrapped and indented. *
* @param s input string
* @param maxLength if an input line is longer than this length,
* the line will be word-wrapped at the first white space after <code>maxLength</code>
* and indented with 4 spaces
* @return string with long-lines word-wrapped
*/
private static String wrapString(String s, int maxLength) {
String deliminator = "\n";
StringBuilder result = new StringBuilder();
StringBuffer wrapLine;
int lastdelimPos;
for (String line : s.split(deliminator, -1)) {
if(line.length()/(maxLength+1) < 1) {
result.append(line).append(deliminator);
}
else { //line too long, try to split it
wrapLine = new StringBuffer();
lastdelimPos = 0;
for (String token : line.trim().split("\\s+", -1)) {
if (wrapLine.length() - lastdelimPos + token.length() > maxLength) {
if(wrapLine.length()>0) {wrapLine.append(deliminator);}
wrapLine.append(" ").append(token);
lastdelimPos = wrapLine.length() + 1;
} else {
if(wrapLine.length() <=0) {wrapLine.append(token);}
else {wrapLine.append(" ").append(token);}
}
}
result.append(wrapLine).append(deliminator);
}
}
return result.toString();
}
// </editor-fold>
}
| 8,995 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
Main.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/SED/src/simpleEquilibriumDiagrams/Main.java | package simpleEquilibriumDiagrams;
/** Checks for all the jar-libraries needed.
* <br>
* Copyright (C) 2014-2016 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class Main {
private static final String progName = "Program SED";
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
private static boolean started = false;
private static final String SLASH = java.io.File.separator;
/** Check that all the jar-libraries needed do exist.
* @param args the command line arguments */
public static void main(String[] args) {
// ---- are all jar files needed there?
if(!doJarFilesExist()) {return;}
// ---- ok!
SED.main(args);
} //main
//<editor-fold defaultstate="collapsed" desc="doJarFilesExist">
/** Look in the running jar file's classPath Manifest for any other "library"
* jar-files listed under "Class-path".
* If any of these jar files does not exist display an error message
* (and an error Frame) and continue.
* @return true if all needed jar files exist; false otherwise.
* @version 2016-Aug-03 */
private static boolean doJarFilesExist() {
java.io.File libJarFile, libPathJarFile;
java.util.jar.JarFile runningJar = getRunningJarFile();
// runningJar.getName() = C:\Eq-Calc_Java\dist\Prog.jar
if(runningJar != null) { // if running within Netbeans there will be no jar-file
java.util.jar.Manifest manifest;
try {manifest = runningJar.getManifest();}
catch (java.io.IOException ex) {
manifest = null;
String msg = "Warning: no manifest found in the application's jar file:"+nl+
"\""+runningJar.getName()+"\"";
ErrMsgBox emb = new ErrMsgBox(msg, progName);
//this will return true;
}
if(manifest != null) {
String classPath = manifest.getMainAttributes().getValue("Class-Path");
if(classPath != null && classPath.length() > 0) {
// this will be a list of space-separated names
String[] jars = classPath.split("\\s+"); //regular expression to match one or more spaces
if(jars.length >0) {
java.io.File[] rootNames = java.io.File.listRoots();
boolean isPathAbsolute;
String pathJar;
String p = getPathApp(); // get the application's path
for(String jar : jars) { // loop through all jars needed
libJarFile = new java.io.File(jar);
if(libJarFile.exists()) {continue;}
isPathAbsolute = false;
for(java.io.File f : rootNames) {
if(jar.toLowerCase().startsWith(f.getAbsolutePath().toLowerCase())) {
isPathAbsolute = true;
break;}
}
if(!isPathAbsolute) { // add the application's path
if(!p.endsWith(SLASH) && !jar.startsWith(SLASH)) {p = p+SLASH;}
pathJar = p + jar;
} else {pathJar = jar;}
libPathJarFile = new java.io.File(pathJar);
if(libPathJarFile.exists()) {continue;}
libPathJarFile = new java.io.File(libPathJarFile.getAbsolutePath());
ErrMsgBox emb = new ErrMsgBox(progName+" - Error:"+nl+
" File: \""+jar+"\" NOT found."+nl+
" And file: \""+libPathJarFile.getName()+"\" is NOT in folder:"+nl+
" \""+libPathJarFile.getParent()+"\""+nl+
" either!"+nl+nl+
" This file is needed by the program."+nl, progName);
return false;
}
}
}//if classPath != null
} //if Manifest != null
} //if runningJar != null
return true;
} //doJarFilesExist()
//<editor-fold defaultstate="collapsed" desc="getRunningJarFile()">
/** Find out the jar file that contains this class
* @return a File object of the jar file containing the enclosing class "Main",
* or null if the main class is not inside a jar file.
* @version 2014-Jan-17 */
public static java.util.jar.JarFile getRunningJarFile() {
//from http://www.rgagnon.com/javadetails/
//and the JarClassLoader class
C c = new C();
String className = c.getClass().getName().replace('.', '/');
// class = "progPackage.Main"; className = "progPackage/Main"
java.net.URL url = c.getClass().getResource("/" + className + ".class");
// url = "jar:file:/C:/Eq-Calc_Java/dist/Prog.jar!/progPackage/Main.class"
if(url.toString().startsWith("jar:")) {
java.net.JarURLConnection jUrlC;
try{
jUrlC = (java.net.JarURLConnection)url.openConnection();
return jUrlC.getJarFile();
} catch(java.io.IOException ex) {
ErrMsgBox emb = new ErrMsgBox("Error "+ex.toString(), progName);
return null;
}
} else {
// it might not be a jar file if running within NetBeans
return null;
}
} //getRunningJarFile()
//</editor-fold>
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="getPathApp">
/** Get the path where an application is located.
* @return the directory where the application is located,
* or "user.dir" if an error occurs
* @version 2014-Jan-17 */
private static class C {private static void C(){}}
public static String getPathApp() {
C c = new C();
String path;
java.net.URI dir;
try{
dir = c.getClass().
getProtectionDomain().
getCodeSource().
getLocation().
toURI();
if(dir != null) {
String d = dir.toString();
if(d.startsWith("jar:") && d.endsWith("!/")) {
d = d.substring(4, d.length()-2);
dir = new java.net.URI(d);
}
path = (new java.io.File(dir.getPath())).getParent();
} else {path = System.getProperty("user.dir");}
}
catch (java.net.URISyntaxException e) {
if(!started) {
ErrMsgBox emb = new ErrMsgBox("Error: "+e.toString()+nl+
" trying to get the application's directory.", progName);
}
path = System.getProperty("user.dir");
} // catch
started = true;
return path;
} //getPathApp()
//</editor-fold>
}
| 7,270 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
HelpAboutF.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/SED/src/simpleEquilibriumDiagrams/HelpAboutF.java | package simpleEquilibriumDiagrams;
import lib.common.MsgExceptn;
/** Show a frame with the program version, acknowledgements, etc
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class HelpAboutF extends javax.swing.JFrame {
private boolean finished = false;
private HelpAboutF frame = null;
/** Where errors will be printed. It may be <code>System.err</code>.
* If null, <code>System.err</code> is used. */
private final java.io.PrintStream out;
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
/** Creates new form HelpAboutF
* @param vers A text providing the program version
* @param pathApp path where the application is located
* @param out0 Where errors will be printed. For example <code>System.out</code>.
* If null, <code>System.err</code> is used */
public HelpAboutF(final String vers, final String pathApp, java.io.PrintStream out0) {
if(out0 != null) {this.out = out0;} else {this.out = System.out;}
finished = false;
initComponents();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
//--- Close window on ESC key
javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE");
javax.swing.Action escAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
closeWindow();
}};
getRootPane().getActionMap().put("ESCAPE", escAction);
//--- Alt-X eXit
javax.swing.KeyStroke altXKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altXKeyStroke,"ALT_X");
getRootPane().getActionMap().put("ALT_X", escAction);
//--- alt-Q exit
javax.swing.KeyStroke altQKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altQKeyStroke,"ALT_Q");
getRootPane().getActionMap().put("ALT_Q", escAction);
//--- Title, etc
//getContentPane().setBackground(java.awt.Color.white);
this.setTitle(SED.progName+": About");
//---- Icon
String iconName = "images/Question_16x16.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
if (imgURL != null) {this.setIconImage(new javax.swing.ImageIcon(imgURL).getImage());}
else {out.println("Error: Could not load image = \""+iconName+"\"");}
jLabelVers.setText("Program version: "+vers);
jLabelPathApp.setText(pathApp);
jLabelPathUser.setText(System.getProperty("user.home"));
this.validate();
int w = jLabelPathApp.getWidth()+40;
if(w > this.getWidth()) {this.setSize(w, this.getHeight());}
// Centre the window on the screen
int left = Math.max(0,(SED.screenSize.width-this.getWidth())/2);
int top = Math.max(0,(SED.screenSize.height-this.getHeight())/2);
this.setLocation(Math.min(SED.screenSize.width-100, left),
Math.min(SED.screenSize.height-100, top));
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
frame = HelpAboutF.this;
}}); //invokeLater(Runnable)
} //constructor
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel_Name = new javax.swing.JLabel();
jLabelVers = new javax.swing.JLabel();
jLabelLicense = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jLabelJava = new javax.swing.JLabel();
jLabelPathA = new javax.swing.JLabel();
jLabelPathApp = new javax.swing.JLabel();
jLabelPathU = new javax.swing.JLabel();
jLabelPathUser = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jLabel_wwwKTH = new javax.swing.JLabel();
jLabel_www = new javax.swing.JLabel();
jLabelUnicode = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jLabel_Name.setText("<html><b><font size=+1>SED</font></b> <b>S</b>imple <b>E</b>quilibrium <b>D</b>iagrams<br>\n© 2020 I.Puigdomenech,<br>\nHaltafall algorithm by Ingri <i>et al</i> (1967).</html>");
jLabelVers.setText("LabelVers");
jLabelLicense.setText("<html>This program comes with ABSOLUTELY NO WARRANTY.<br>This is free software, and you are welcome to redistribute it<br>under the GNU GPL license. See file \"GPL.txt\".</html>");
jLabelJava.setText("<html>Java Standard Edition<br>Development Kit 7 (JDK 1.7)<br>NetBeans IDE</html>");
jLabelPathA.setLabelFor(jLabelPathApp);
jLabelPathA.setText("Application path:");
jLabelPathApp.setText("\"null\"");
jLabelPathU.setText("User \"home\" directory:");
jLabelPathUser.setText("\"null\"");
jLabel_wwwKTH.setForeground(new java.awt.Color(0, 0, 221));
jLabel_wwwKTH.setText("<html><u>www.kth.se/che/medusa</u></html>");
jLabel_wwwKTH.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jLabel_wwwKTH.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel_wwwKTHMouseClicked(evt);
}
});
jLabel_www.setForeground(new java.awt.Color(0, 0, 221));
jLabel_www.setText("<html><u>sites.google.com/site/chemdiagr/</u></html>");
jLabel_www.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jLabel_www.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel_wwwMouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel_wwwKTH, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel_www, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(26, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel_wwwKTH, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel_www, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jLabelUnicode.setText("(Unicode UTF-8)");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator1)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel_Name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabelJava, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelPathA)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelPathApp)))
.addGap(0, 11, Short.MAX_VALUE)))
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelLicense, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelVers)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelUnicode))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelPathU)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelPathUser)))
.addGap(0, 0, Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(5, 5, 5)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel_Name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelVers)
.addComponent(jLabelUnicode))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelLicense, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 4, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelJava, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelPathA)
.addComponent(jLabelPathApp))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelPathU)
.addComponent(jLabelPathUser))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jLabel_wwwMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel_wwwMouseClicked
BareBonesBrowserLaunch.openURL("https://sites.google.com/site/chemdiagr/",this);
}//GEN-LAST:event_jLabel_wwwMouseClicked
private void jLabel_wwwKTHMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel_wwwKTHMouseClicked
BareBonesBrowserLaunch.openURL("https://www.kth.se/che/medusa/",this);
}//GEN-LAST:event_jLabel_wwwKTHMouseClicked
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
closeWindow();
}//GEN-LAST:event_formWindowClosing
public void closeWindow() {
finished = true;
this.notify_All();
this.dispose();
} // closeWindow()
private synchronized void notify_All() {notifyAll();}
/** this method will wait for this dialog frame to be closed */
public synchronized void waitFor() {
while(!finished) {
try {wait();} catch (InterruptedException ex) {}
} // while
} // waitFor()
public void bringToFront() {
if(frame != null) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override public void run() {
frame.setVisible(true);
if((frame.getExtendedState() & javax.swing.JFrame.ICONIFIED) // minimised?
== javax.swing.JFrame.ICONIFIED) {
frame.setExtendedState(javax.swing.JFrame.NORMAL);
} // if minimized
frame.setAlwaysOnTop(true);
frame.toFront();
frame.requestFocus();
frame.setAlwaysOnTop(false);
}
});
}
} // bringToFront()
//<editor-fold defaultstate="collapsed" desc="class BareBonesBrowserLaunch">
/**
* <b>Bare Bones Browser Launch for Java</b><br>
* Utility class to open a web page from a Swing application
* in the user's default browser.<br>
* Supports: Mac OS X, GNU/Linux, Unix, Windows XP/Vista/7<br>
* Example Usage:<code><br>
* String url = "http://www.google.com/";<br>
* BareBonesBrowserLaunch.openURL(url);<br></code>
* Latest Version: <a href=http://centerkey.com/java/browser>centerkey.com/java/browser</a><br>
* Author: Dem Pilafian<br>
* WTFPL -- Free to use as you like
* @version 3.2, October 24, 2010
*/
private static class BareBonesBrowserLaunch {
static final String[] browsers = { "x-www-browser", "google-chrome",
"firefox", "opera", "epiphany", "konqueror", "conkeror", "midori",
"kazehakase", "mozilla", "chromium" }; // modified by Ignasi (added "chromium")
static final String errMsg = "Error attempting to launch web browser";
/**
* Opens the specified web page in the user's default browser
* @param url A web address (URL) of a web page (ex: "http://www.google.com/")
*/
public static void openURL(String url, javax.swing.JFrame parent) { // modified by Ignasi (added "parent")
try { //attempt to use Desktop library from JDK 1.6+
Class<?> d = Class.forName("java.awt.Desktop");
d.getDeclaredMethod("browse", new Class[] {java.net.URI.class}).invoke(
d.getDeclaredMethod("getDesktop").invoke(null),
new Object[] {java.net.URI.create(url)});
//above code mimicks: java.awt.Desktop.getDesktop().browse()
}
catch (Exception ignore) { //library not available or failed
String osName = System.getProperty("os.name");
try {
if (osName.startsWith("Mac OS")) {
Class.forName("com.apple.eio.FileManager").getDeclaredMethod(
"openURL", new Class[] {String.class}).invoke(null,new Object[] {url});
}
else if (osName.startsWith("Windows"))
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
else { //assume Unix or Linux
String browser = null;
for (String b : browsers)
if (browser == null && Runtime.getRuntime().exec(new String[]
{"which", b}).getInputStream().read() != -1)
Runtime.getRuntime().exec(new String[] {browser = b, url});
if (browser == null)
throw new Exception(java.util.Arrays.toString(browsers));
}
}
catch (Exception e) {
MsgExceptn.exception(errMsg + "\n" + e.getMessage()); // added by Ignasi
javax.swing.JOptionPane.showMessageDialog(parent, errMsg + "\n" + e.getMessage(), // modified by Ignasi (added "parent")
"Chemical Equilibrium Diagrams", javax.swing.JOptionPane.ERROR_MESSAGE); // added by Ignasi
}
}
}
}
//</editor-fold>
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabelJava;
private javax.swing.JLabel jLabelLicense;
private javax.swing.JLabel jLabelPathA;
private javax.swing.JLabel jLabelPathApp;
private javax.swing.JLabel jLabelPathU;
private javax.swing.JLabel jLabelPathUser;
private javax.swing.JLabel jLabelUnicode;
private javax.swing.JLabel jLabelVers;
private javax.swing.JLabel jLabel_Name;
private javax.swing.JLabel jLabel_www;
private javax.swing.JLabel jLabel_wwwKTH;
private javax.swing.JPanel jPanel1;
private javax.swing.JSeparator jSeparator1;
// End of variables declaration//GEN-END:variables
}
| 19,578 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
Table.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/SED/src/simpleEquilibriumDiagrams/Table.java | package simpleEquilibriumDiagrams;
import lib.kemi.chem.Chem;
/** Methods to save numerical results into output text file(s).
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class Table {
private java.io.File tf = null;
private java.io.Writer tW = null;
private final static java.util.Locale engl = java.util.Locale.ENGLISH;
private SED sed = null;
/** Where messages will be printed. It may be <code>System.out</code>.
* If null, <code>System.out</code> is used. */
private final java.io.PrintStream out;
/** New-line character(s) to substitute "\n". */
private static final String nl = System.getProperty("line.separator");
/** Text at the start of a text line to indicate that the line is a comment */
private String commentLineStart = "\"";
/** Text appended to the end of comment lines*/
private String commentLineEnd = "\"";
private static final String SLASH = java.io.File.separator;
/** field separator (for example a semicolon, ";", a comma ",", etc). */
private String fs;
/** Constructs an object of this class
* @param sed0 the program SED frame
* @param err0 Where errors will be printed. It may be <code>System.err</code>.
* If null, <code>System.err</code> is used.
* @param out0 Where messages will be printed. It may be <code>System.out</code>.
* If null, <code>System.out</code> is used. */
public Table(SED sed0, java.io.PrintStream err0, java.io.PrintStream out0) {
this.sed = sed0;
if(out0 != null) {this.out = out0;} else {this.out = System.out;}
commentLineStart = sed.tblCommentStart;
commentLineEnd = sed.tblCommentEnd;
} //constructor
//<editor-fold defaultstate="collapsed" desc="tableHeader()">
/** Prepare a new output text file to receive the table data.
* @param ch where data on the chemical system are stored
* @param tblExtension
* @return false if an error occurs */
boolean tableHeader(Chem ch, java.io.File tableFile) {
if(sed.dbg) {out.println("--- tableHeader");}
this.tf = tableFile;
String msg;
try {
tW = new java.io.BufferedWriter(
new java.io.OutputStreamWriter(
new java.io.FileOutputStream(tf),"UTF8"));
} catch (java.io.IOException ex) {
msg = "Error: \""+ex.getMessage()+"\""+nl+
"while opening file \""+tf.getAbsolutePath()+"\"";
sed.showErrMsgBx(msg, 1);
tableClose();
return false;
}
msg = "Writing table file:"+nl+" \""+tf.getAbsolutePath()+"\"";
out.println(msg);
if(sed.consoleOutput) {System.out.println(msg);}
try{
tW.write(commentLineStart+"TABLE output from program SED (I.Puigdomenech http://github.com/ignasi-p/eq-diagr/releases)"+commentLineEnd+nl);
java.text.DateFormat dateFormatter =
java.text.DateFormat.getDateTimeInstance
(java.text.DateFormat.DEFAULT, java.text.DateFormat.DEFAULT, java.util.Locale.getDefault());
java.util.Date today = new java.util.Date();
String dateOut = dateFormatter.format(today);
tW.write(commentLineStart+"file written: "+dateOut+commentLineEnd+nl);
tW.write(nl);
Chem.ChemSystem cs = ch.chemSystem;
Chem.ChemSystem.NamesEtc namn = cs.namn;
Chem.Diagr diag = ch.diag;
Chem.DiagrConcs dgrC = ch.diagrConcs;
tW.write(String.format(engl, "%sNbr chemical components = %d%s%n%s Concentrations:%s%n", commentLineStart, cs.Na, commentLineEnd, commentLineStart, commentLineEnd));
// Concentration types:
// hur =1 for "T" (fixed Total conc.)
// hur =2 for "TV" (Tot. conc. Varied)
// hur =3 for "LTV" (Log(Tot.conc.) Varied)
// hur =4 for "LA" (fixed Log(Activity) value)
// hur =5 for "LAV" (Log(Activity) Varied)
for(int i=0; i < cs.Na; i++) {
if(dgrC.hur[i] == 1) {
tW.write(String.format(engl,"%s Tot. Conc. constant = %10.3g for %s%s%n", commentLineStart, dgrC.cLow[i],namn.identC[i],commentLineEnd));}
if(dgrC.hur[i] == 2) {
tW.write(String.format(engl,"%s Tot. Conc. varied between %10.3g and %10.3g for %s%s%n", commentLineStart, dgrC.cLow[i],dgrC.cHigh[i],namn.identC[i],commentLineEnd));}
if(dgrC.hur[i] == 3) {
tW.write(String.format(engl,"%s log10(Tot.Conc.) varied between %10.3g and %10.3g for %s%s%n", commentLineStart, dgrC.cLow[i],dgrC.cHigh[i],namn.identC[i],commentLineEnd));}
if(dgrC.hur[i] == 4) {
tW.write(String.format(engl,"%s log10(Activity) constant = %10.3g for %s%s%n", commentLineStart, dgrC.cLow[i],namn.identC[i],commentLineEnd));}
if(dgrC.hur[i] == 5) {
tW.write(String.format(engl,"%s log10(Activity) varied between %10.3g and %10.3g for %s%s%n", commentLineStart, dgrC.cLow[i],dgrC.cHigh[i],namn.identC[i],commentLineEnd));}
}//for i
String ionStr;
if(diag.ionicStrength < 0) {ionStr = "calculated at each point";}
else {ionStr = String.format(engl,"%6.2f molal",diag.ionicStrength).trim();}
String t = String.format(engl,"t=%3d C",Math.round((float)diag.temperature));
if(!Double.isNaN(diag.pressure) && diag.pressure > 1.02) {
if(diag.pressure < 220.64) {
t = t + String.format(java.util.Locale.ENGLISH,", p=%.2f bar",diag.pressure);
} else {
if(diag.pressure <= 500) {t = t + String.format(", p=%.0f bar",diag.pressure);}
else {t = t + String.format(java.util.Locale.ENGLISH,", p=%.1f kbar",(diag.pressure/1000.));}
}
}
if(sed.calcActCoeffs && !Double.isNaN(diag.ionicStrength) && Math.abs(diag.ionicStrength) > 1.e-10) {
tW.write(nl);
tW.write(commentLineStart+"Activity coefficients calculated at "+t+" and I = "+ionStr+commentLineEnd+nl);
String At = At = String.format(engl, "%9.5f", sed.factor.Agamma).trim();
String Bt = String.format(engl, "%6.3f", sed.factor.rB).trim();
if(diag.activityCoeffsModel == 0) { //Davies
tW.write(commentLineStart+"using Davies eqn.:"+commentLineEnd+nl);
tW.write(commentLineStart+" log f(i) = -"+At+" Zi^2 ( I^0.5 / (1 + I^0.5) - 0.3 I)"+commentLineEnd+nl);
}
else if(diag.activityCoeffsModel == 1) { //SIT
tW.write(commentLineStart+"using the SIT model:"+commentLineEnd+nl);
tW.write(commentLineStart+" log f(i) = -("+At+" Zi^2 I^0.5 / (1 + "+Bt+" I^0.5))"+
" + Sum[ eps(i,j) m(j) ]"+commentLineEnd+nl);
tW.write(commentLineStart+"for all 'j' with Zj*Zi<=0; where eps(i,j) is a specific ion interaction parameter (in general independent of I)"+commentLineEnd+nl);
}
else if(diag.activityCoeffsModel == 2) { //HKF
tW.write(commentLineStart+"using simplified Helgeson, Kirkham & Flowers model:"+commentLineEnd+nl);
String bgit = String.format(engl, "%7.4f", sed.factor.bgi).trim();
tW.write(commentLineStart+" log f(i) = -("+At+" Zi^2 I^0.5) / (1 + "+Bt+" I^0.5) + Gamma + ("+bgit+" I)"+commentLineEnd+nl);
tW.write(commentLineStart+"where: Gamma = -log(1+0.0180153 I)"+commentLineEnd+nl);
}
}
tW.write(nl);
t = "(program error)";
if(diag.plotType ==1) {t="fractions";}
else if(diag.plotType ==2) {t="solubilities";}
else if(diag.plotType ==3) {t="log10(concs.)";}
else if(diag.plotType ==4) {t="log10(ai/ar)";}
else if(diag.plotType ==5) {t="pe (calc.)";}
else if(diag.plotType ==6) {t="pH (calc.)";}
else if(diag.plotType ==7) {t="log10(activities)";}
else if(diag.plotType ==8) {t="d(H-bound)/d(pH)";}
tW.write(String.format("%sComponent in X-axis is: %s; the Y-axis data are %s.%s%n", commentLineStart, namn.identC[diag.compX],t,commentLineEnd));
tW.flush();
tW.write(String.format("%sOutput data (there are %d lines and (1+%d) columns)%s%n", commentLineStart, (sed.nSteps+1),Plot.nbrSpeciesInPlot,commentLineEnd));
tW.write(commentLineStart+"(the first column contains the X-axis values)"+commentLineEnd+nl);
//--- column captions:
if(sed.tblFieldSeparator != null && sed.tblFieldSeparator.length() >0) {
fs = sed.tblFieldSeparator;
} else {fs = " ";}
//---
// Values for the Y-axis
// plotType=1 fraction diagram compY= main component
// plotType=2 log solubility diagram
// plotType=3 log (conc) diagram
// plotType=4 log (ai/ar) diagram compY= reference species
// plotType=5 pe in Y-axis
// plotType=6 pH in Y-axis
// plotType=7 log (activity) diagram
// plotType=8 H-affinity diagram
if(diag.plotType !=2) { //not solubilities
if(diag.plotType ==8) {
tW.write("\""+namn.identC[diag.compX]+"\""+fs+"\"d(H-h)/d(pH)\""+fs);
} else {
tW.write("\""+namn.identC[diag.compX]+"\""+fs);
for(int i =0; i < Plot.nbrSpeciesInPlot; i++) {
tW.write("\""+namn.ident[Plot.speciesInPlot[i]]+"\""+fs);
}
}
} else { // solubilities
tW.write("\""+namn.identC[diag.compX]+"\""+fs);
for(int i =0; i < Plot.nbrSpeciesInPlot; i++) {
tW.write("\""+namn.identC[Plot.speciesInPlot[i]]+"\""+fs);
}
}
// print ionic strength, concentrations and activity coefficients
if(!Double.isNaN(diag.ionicStrength) &&
Math.abs(diag.ionicStrength) > 1.e-10 && (diag.plotType !=4 && diag.plotType !=8)) {
tW.write(fs);
tW.write(String.format(engl,"I (molal)%sSum of m%s",fs,fs));
int nIon = cs.Na + cs.nx;
for(int j = 0; j < nIon; j++) {
if(j != cs.jWater) {
tW.write(String.format(engl,"C(%s)%slogf()%s",namn.ident[j],fs,fs));
} else {
tW.write(String.format(engl,"a(H2O)%sphi%s",fs,fs));
}
}
}
tW.write(nl);
} catch (Exception ex) {
msg = "Error: \""+ex.getMessage()+"\""+nl+
"while writing file \""+tf.getAbsolutePath()+"\"";
sed.showErrMsgBx(msg, 1);
tableClose();
return false;
}
return true;
} //tableHeader()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="tableBody()">
/** Print diagram data for this point (the equilibrium composition).
* @param nP the point number (along the x-axis)
* @param ch where the data for the chemical system are stored */
void tableBody(int nP, Chem ch) {
if(sed.dbg) {out.println("--- tableBody("+nP+", ch)");}
Chem.ChemSystem cs = ch.chemSystem;
Chem.ChemSystem.ChemConcs csC = cs.chemConcs;
Chem.ChemSystem.NamesEtc namn = cs.namn;
Chem.Diagr diag = ch.diag;
Chem.DiagrConcs dgrC = ch.diagrConcs;
//---
// Values for the Y-axis
// plotType=1 fraction diagram compY= main component
// plotType=2 log solubility diagram
// plotType=3 log (conc) diagram
// plotType=4 log (ai/ar) diagram compY= reference species
// plotType=5 pe in Y-axis
// plotType=6 pH in Y-axis
// plotType=7 log (activity) diagram
// plotType=8 H-affinity diagram
double xValue;
double w1; double w2; double y1; double y2;
double y[] = new double[cs.Ms];
int i;
xValue = sed.bt[diag.compX][nP];
if(dgrC.hur[diag.compX] ==3) { //"LTV"
xValue = Math.log10(xValue);
} else if(diag.pInX !=0) {
xValue = -xValue;
}
if(diag.plotType ==1) { //fractions
for(int k=0; k < Plot.nbrSpeciesInPlot; k++) {
i = Plot.speciesInPlot[k];
if(i >= cs.Ms) {continue;}
if(Math.abs(Plot.tot0[diag.compY][nP])>1.e-30) {
double o;
if(i < cs.Na) {
if(i==diag.compY) {o=1;} else {o=0;}
} else {o =cs.a[i-cs.Na][diag.compY];}
y[i]=o*Plot.c0[i][nP]/Plot.tot0[diag.compY][nP];
} else {
y[i] = 0;
}
if(y[i] >1d && y[i] < 1.01d) {y[i] = 1;}
} //for i
} else if(diag.plotType ==2) { //solubilities
for(int k=0; k < Plot.nbrSpeciesInPlot; k++) {
i = Plot.speciesInPlot[k];
if(i >= cs.Ms) {continue;}
if(Plot.tot0[i][nP]>1.e-50) {y[i] = Math.log10(Plot.tot0[i][nP]);}
else {y[i] = -50;}
}
} else if(diag.plotType ==3) { //log(concs.)
for(int k=0; k < Plot.nbrSpeciesInPlot; k++) {
i = Plot.speciesInPlot[k];
if(i >= cs.Ms) {continue;}
if(Plot.c0[i][nP]>1.e-35) {y[i] = Math.log10(Plot.c0[i][nP]);}
else {y[i] = -99;}
}
} else if(diag.plotType ==4) { //log(ai/ar)
for(int k=0; k < Plot.nbrSpeciesInPlot; k++) {
i = Plot.speciesInPlot[k];
if(i >= cs.Ms) {continue;}
y[i] = Plot.c0[i][nP] - Plot.c0[diag.compY][nP];
}
} else if(diag.plotType ==5 || diag.plotType ==6) { //pe or pH
for(int k=0; k < Plot.nbrSpeciesInPlot; k++) {
i = Plot.speciesInPlot[k];
if(i >= cs.Ms) {continue;}
y[i] = -Plot.c0[i][nP];
}
} else if(diag.plotType ==7) { //log(act.)
for(int k=0; k < Plot.nbrSpeciesInPlot; k++) {
i = Plot.speciesInPlot[k];
if(i >= cs.Ms) {continue;}
y[i] = Plot.c0[i][nP];
}
} else if(diag.plotType ==8) { //Proton affinity
//Note: c0[0][nSp] =c[Hplus] c0[1][nSp] =logA[Hplus] c0[2][nSp] =c[OHmin]
if(nP ==0) { //first point
y[0] =0;
} else if(nP <= sed.nSteps) {
// w1 = delta (-pH)
// w2 = delta (H_bound) = delta ([H]_tot - [H+] + [OH-]
w1 = Plot.c0[1][nP]-Plot.c0[1][nP-1];
w2 = (Plot.tot0[diag.Hplus][nP]-Plot.c0[0][nP]+Plot.c0[2][nP])
- (Plot.tot0[diag.Hplus][nP-1]-Plot.c0[0][nP-1]+Plot.c0[2][nP-1]);
if(Math.abs(w1) >= 1.E-35) y[0] = ( w2 / w1);
}
} else { //error
for(int k=0; k < y.length; k++) {y[k] = -9999.9999;}
}
try{
tW.write(String.format(engl,"%13.5g",xValue));
for(int k=0; k < Plot.nbrSpeciesInPlot; k++) {
i = Plot.speciesInPlot[k];
if(i >= cs.Ms) {continue;}
tW.write(String.format(engl,fs+"%13.5g",y[i]));
}
tW.write(fs);
// print ionic strength, concentrations and activity coefficients
if(!Double.isNaN(diag.ionicStrength) &&
Math.abs(diag.ionicStrength) > 1.e-10 && (diag.plotType !=4 && diag.plotType !=8)) {
tW.write(String.format(engl,"%s% 9.4f%s %9.4f", fs,diag.ionicStrCalc,fs,diag.sumM));
int nIon = cs.Na + cs.nx;
for(int j = 0; j < nIon; j++) {
if(j != cs.jWater) {
tW.write(String.format(engl,"%s% 12.4g%s %9.4f", fs,cs.chemConcs.C[j],fs,cs.chemConcs.logf[j]));
} else {
tW.write(String.format(engl,"%s% 9.4f%s %9.4f", fs,Math.pow(10,cs.chemConcs.logA[j]),fs,diag.phi));
}
}
}
tW.write(nl);
} catch (Exception ex) {
sed.showErrMsgBx("Error: \""+ex.getMessage()+"\""+nl+
"while writing file \""+tf.getAbsolutePath()+"\"", 1);
tableClose();
}
} //tableBody()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="tableClose()">
void tableClose() {
if(sed.dbg) {out.println("--- tableClose");}
out.println("Table output written to file:"+nl+" \""+tf.getName()+"\"");
try{if(tW != null) {tW.flush(); tW.close();}}
catch (Exception ex) {
sed.showErrMsgBx("Error: \""+ex.getMessage()+"\""+nl+
"while closing file \""+tf.getAbsolutePath()+"\"", 1);
}
}
//</editor-fold>
} // class Table
| 16,286 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
SED.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/SED/src/simpleEquilibriumDiagrams/SED.java | package simpleEquilibriumDiagrams;
import lib.common.Util;
import lib.kemi.chem.Chem;
import lib.kemi.graph_lib.DiagrPaintUtility;
import lib.kemi.graph_lib.GraphLib;
import lib.kemi.haltaFall.Factor;
import lib.kemi.haltaFall.HaltaFall;
import lib.kemi.readDataLib.ReadDataLib;
import lib.kemi.readWriteDataFiles.ReadChemSyst;
/** Creates a chemical equilibrium diagram.<br>
* This program will read a data file, make some calculations, and
* create a diagram. The diagram is displayed and stored in a plot file.<br>
* The data file contains the description of a chemical system (usually
* an aqueous system) and a description on how the diagram should be drawn:
* what should be in the axes, concentrations for each chemical
* component, etc.<br>
* If the command-line option "-nostop" is given, then no option dialogs will
* be shown.<br>
* Output messages and errors are written to <code>System.out</code> and
* <code>.err</code> (the console) and output is directed to a JTextArea as well.
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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 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/
*
* @author Ignasi Puigdomenech */
public class SED extends javax.swing.JFrame {
static final String VERS = "2020-June-18";
static final String progName = "SED";
/** variable needed in "main" method */
private static SED sedFrame;
/** print debug information? */
private static final boolean DBG_DEFAULT = false;
/** print debug information? */
boolean dbg = false;
/** if true the program does not exit after the diagram is drawn (and saved
* as a plot file), that is, the diagram remains visible for the user.
* If false, and if the data file is given as a command-line argument,
* then the program saves the diagram and exits without displaying it */
private boolean doNotExit = false;
/** if true the program does display dialogs with warnings or errors */
private boolean doNotStop = false;
/** if true the concentration range in the x-axis may have a reversed "order",
* that is, minimum value to the right and maximum value to the left, if so
* it is given in the input data file. */
private boolean reversedConcs = false;
/** the directory where the program files are located */
private static String pathApp;
/** the directory where the last input data file is located */
StringBuffer pathDef = new StringBuffer();
private java.io.File inputDataFile = null;
private java.io.File outputPltFile = null;
/** true if an input data file is given in the command line.
* If so, then the calculations are performed without waiting for user actions,
* a diagram is generated and saved, and the program exits unless doNotExit is true. */
private boolean inputDataFileInCommandLine;
/** true if the calculations have finished, or if the user wishes to finish
* them (and to end the program) */
private boolean finishedCalculations = true;
/** true if the graphic user interface (GUI) has been displayed and then closed by the user */
private boolean programEnded = false;
/** An instance of SwingWorker to perform the HaltaFall calculations */
private HaltaTask tsk = null;
/** used to calculate execution time */
private long calculationStart = 0;
/** the execution time */
private long calculationTime = 0;
/** size of the user's computer screen */
static java.awt.Dimension screenSize;
/** original size of the program window */
private final java.awt.Dimension originalSize;
/** a class used to store and retrieve data, used by HaltaFall */
private Chem ch = null;
/** a class to store data about a chemical system */
private Chem.ChemSystem cs = null;
/** a class to store data about a the concentrations to calculate an
* equilibrium composition, used by HaltaFall */
private Chem.ChemSystem.ChemConcs csC = null;
/** a class to store diverse information on a chemical system: names of species, etc */
private Chem.ChemSystem.NamesEtc namn = null;
/** a class to store array data about a diagram */
private Chem.DiagrConcs dgrC = null;
/** a class to store non-array data about a diagram */
private Chem.Diagr diag = null;
/** a class to calculate activity coefficients */
Factor factor;
/** the calculations class */
private HaltaFall h;
/** a class to read text files where data is separated by commas */
private ReadDataLib rd;
private Plot plot = null;
/** data from a plot-file needed by the paint methods */
GraphLib.PltData dd; // instantiated in "Plot.drawPlot"
// it containts the info in the plot file
private HelpAboutF helpAboutFrame = null;
private final javax.swing.JFileChooser fc;
private final javax.swing.filechooser.FileNameExtensionFilter filterDat;
/** true if the message text area should be erased before a new datafile is
* read (after the user has selected a new data file) */
private boolean eraseTextArea = false;
/** Where errors will be printed. It may be <code>System.err</code>.
* If null, <code>System.err</code> is used. */
private java.io.PrintStream err;
/** Where messages will be printed. It may be <code>System.out</code>.
* If null, <code>System.out</code> is used. */
private java.io.PrintStream out;
/** The maximum number of calculation steps along the X-axis */
private final static int NSTP_MAX = 300;
/** The minimum number of calculation steps along the X-axis */
private final static int NSTP_MIN = 4;
private final static int NSTP_DEF = 50;
/** The number of calculation steps along the X-axis.
* The number of points calculated is: <code>nSteps+1</code>.
* Note that to the outside world, the number of calculation points are reported. */
int nSteps = NSTP_DEF;
/** The calculation step being (along the x-axis) performed out of nSteps
* The first point corresponds to no step, <code>nStepX = 0</code> */
private int nStepX;
/** The given input concentrations recalculated for each calculation step.
* Dimensions: bt[Na][nSteps+1] */
double[][] bt;
private final double ln10 = Math.log(10d);
/** true if activity coeficients have to be calculated */
boolean calcActCoeffs = false;
private final int actCoeffsModelDefault =2;
/** the ionic strength, or -1 if it has to be calculated at each calculation step */
private double ionicStrength = Double.NaN;
/** the temperature value given given in the command line */
double temperature_InCommandLine = Double.NaN;
/** the pressure value given given in the command line */
double pressure_InCommandLine = Double.NaN;
private int actCoeffsModel_InCommandLine = -1;
private double tolHalta = Chem.TOL_HALTA_DEF;
double peEh = Double.NaN;
double tHeight;
/** used to direct SED and Predom to draw concentration units
* as either:<ul><li>0="molal"</li><li>1="mol/kg_w"</li><li>2="M"</li><li>-1=""</li></ul> */
int conc_units = 0;
String[] cUnits = new String[]{"","molal","mol/kg`w'","M"};
/** used to direct SED and Predom to draw concentrations
* as either scientific notation or engineering notation:<ul><li>0 = no choice
* (default, means scientific for "molal" and engineering for "M")</li>
* <li>1 = scientific notation</li><li>2 = engineering notation</li></ul> */
int conc_nottn = 0;
float threshold = 0.03f;
private boolean tableOutput = false;
private Table table = null;
String tblExtension = "csv";
String tblFieldSeparator = ";";
String tblCommentStart = "\"";
String tblCommentEnd = "\"";
/** output debug reporting in HaltaFall. Default = Chem.DBGHALTA_DEF = 1 (report errors only)
* @see Chem.ChemSystem.ChemConcs#dbg Chem.ChemSystem.ChemConcs.dbg */
int dbgHalta = Chem.DBGHALTA_DEF;
/** true if the component has either <code>noll</code> = false or it has positive
* values for the stoichiometric coefficients (a[ix][ia]-values)
* @see chem.Chem.ChemSystem#a a
* @see chem.Chem.ChemSystem#noll noll */
private boolean[] pos;
/** true if the component has some negative
* values for the stoichiometric coefficients (a[ix][ia]-values)
* @see chem.Chem.ChemSystem#a a */
private boolean[] neg;
//
private final DiagrPaintUtility diagrPaintUtil;
//
private final java.io.PrintStream errPrintStream =
new java.io.PrintStream(
new errFilteredStreamSED(
new java.io.ByteArrayOutputStream()),true);
private final java.io.PrintStream outPrintStream =
new java.io.PrintStream(
new outFilteredStreamSED(
new java.io.ByteArrayOutputStream()),true);
/** true if a minumum of information is sent to the console (System.out)
* when inputDataFileInCommandLine and not doNotExit.
* False if all output is sent only to the JTextArea panel. */
boolean consoleOutput = true;
/** New-line character(s) to substitute "\n".<br>
* It is needed when a String is created first, including new-lines,
* and the String is then printed. For example
* <pre>String t = "1st line\n2nd line";
*System.out.println(t);</pre>will add a carriage return character
* between the two lines, which on Windows system might be
* unsatisfactory. Use instead:
* <pre>String t = "1st line" + nl + "2nd line";
*System.out.println(t);</pre> */
private static final String nl = System.getProperty("line.separator");
private static final java.util.Locale engl = java.util.Locale.ENGLISH;
static final String LINE = "-------------------------------------";
private static final String SLASH = java.io.File.separator;
//
//todo: no names can start with "*" after reading the chemical system
//<editor-fold defaultstate="collapsed" desc="Constructor">
/** Creates new form SED
* @param doNotExit0
* @param doNotStop0
* @param dbg0 */
public SED(
final boolean doNotExit0,
final boolean doNotStop0,
final boolean dbg0) {
initComponents();
dbg = dbg0;
doNotStop = doNotStop0;
doNotExit = doNotExit0;
// ---- redirect all output to the tabbed pane
out = outPrintStream;
err = errPrintStream;
// ---- get the current working directory
setPathDef();
if(DBG_DEFAULT) {out.println("default path: \""+pathDef.toString()+"\"");}
// ---- Define open/save file filters
fc = new javax.swing.JFileChooser("."); //the "user" path
filterDat =new javax.swing.filechooser.FileNameExtensionFilter("*.dat", new String[] { "DAT"});
// ----
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
//--- F1 for help
javax.swing.KeyStroke f1KeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(f1KeyStroke,"F1");
javax.swing.Action f1Action = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jMenuHelpAbout.isEnabled()) {jMenuHelpAbout.doClick();}
}};
getRootPane().getActionMap().put("F1", f1Action);
//--- ctrl-C: stop calculations
javax.swing.KeyStroke ctrlCKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_DOWN_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(ctrlCKeyStroke,"CTRL_C");
javax.swing.Action ctrlCAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jTabbedPane.getSelectedIndex() == 1) {
if(h != null) {h.haltaCancel();}
if(tsk != null) {tsk.cancel(true);}
finishedCalculations = true;
SED.this.notify_All();
}
}};
getRootPane().getActionMap().put("CTRL_C", ctrlCAction);
//--- define Alt-key actions
//--- alt-X: eXit
javax.swing.KeyStroke altXKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altXKeyStroke,"ALT_X");
javax.swing.Action altXAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jMenuFileXit.isEnabled()) {jMenuFileXit.doClick();}
}};
getRootPane().getActionMap().put("ALT_X", altXAction);
//--- alt-Q: quit
javax.swing.KeyStroke altQKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altQKeyStroke,"ALT_Q");
getRootPane().getActionMap().put("ALT_Q", altXAction);
//--- alt-Enter: make diagram
javax.swing.KeyStroke altEnterKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_ENTER, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altEnterKeyStroke,"ALT_Enter");
javax.swing.Action altEnterAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jMenuFileMakeD.isEnabled()) {jMenuFileMakeD.doClick();}
}};
getRootPane().getActionMap().put("ALT_Enter", altEnterAction);
//--- alt-C: method for activity coefficients
javax.swing.KeyStroke altCKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altCKeyStroke,"ALT_C");
javax.swing.Action altCAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jTabbedPane.getSelectedIndex() == 0 &&
jComboBoxModel.isEnabled()) {jComboBoxModel.requestFocusInWindow();}
}};
getRootPane().getActionMap().put("ALT_C", altCAction);
//--- alt-D: diagram
javax.swing.KeyStroke altDKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_D, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altDKeyStroke,"ALT_D");
javax.swing.Action altDAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jTabbedPane.getSelectedIndex() == 0 &&
jMenuFileMakeD.isEnabled() &&
jButtonDoIt.isEnabled()) {jButtonDoIt.doClick();
} else if(jTabbedPane.getSelectedIndex() != 2 &&
jTabbedPane.isEnabledAt(2)) {jTabbedPane.setSelectedIndex(2);
}
}};
getRootPane().getActionMap().put("ALT_D", altDAction);
//--- alt-E: hEight
javax.swing.KeyStroke altEKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.ALT_MASK, false);
javax.swing.Action altEAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jTabbedPane.getSelectedIndex() == 0){jScrollBarHeight.requestFocusInWindow();}
}};
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altEKeyStroke,"ALT_E");
getRootPane().getActionMap().put("ALT_E", altEAction);
//--- alt-L: pLot file name
javax.swing.KeyStroke altLKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_L, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altLKeyStroke,"ALT_L");
javax.swing.Action altLAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jTabbedPane.getSelectedIndex() == 0){jTextFieldPltFile.requestFocusInWindow();}
}};
getRootPane().getActionMap().put("ALT_L", altLAction);
//--- alt-M: messages pane
javax.swing.KeyStroke altMKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_M, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altMKeyStroke,"ALT_M");
javax.swing.Action altMAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jTabbedPane.getSelectedIndex() != 1 &&
jTabbedPane.isEnabledAt(1)) {jTabbedPane.setSelectedComponent(jScrollPaneMessg);}
}};
getRootPane().getActionMap().put("ALT_M", altMAction);
//--- alt-N: nbr of points
javax.swing.KeyStroke altNKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altNKeyStroke,"ALT_N");
javax.swing.Action altNAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jTabbedPane.getSelectedIndex() == 0){jScrollBarNbrPoints.requestFocusInWindow();}
}};
getRootPane().getActionMap().put("ALT_N", altNAction);
//--- alt-P: parameters
javax.swing.KeyStroke altPKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altPKeyStroke,"ALT_P");
javax.swing.Action altPAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jTabbedPane.getSelectedIndex() != 0) {jTabbedPane.setSelectedIndex(0);}
}};
getRootPane().getActionMap().put("ALT_P", altPAction);
//--- alt-S: ionic strength / stop calculations
javax.swing.KeyStroke altSKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altSKeyStroke,"ALT_S");
javax.swing.Action altSAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jTabbedPane.getSelectedIndex() == 0 &&
jTextFieldIonicStgr.isEnabled()) {
jTextFieldIonicStgr.requestFocusInWindow();
} else if(jTabbedPane.getSelectedIndex() == 1) {
if(h != null) {h.haltaCancel();}
if(tsk != null) {tsk.cancel(true);}
finishedCalculations = true;
SED.this.notify_All();
}
}};
getRootPane().getActionMap().put("ALT_S", altSAction);
//--- alt-T: tolerance in Haltafall
javax.swing.KeyStroke altTKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altTKeyStroke,"ALT_T");
javax.swing.Action altTAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
if(jTabbedPane.getSelectedIndex() == 0 &&
jComboBoxTol.isEnabled()) {jComboBoxTol.requestFocusInWindow();}
}};
getRootPane().getActionMap().put("ALT_T", altTAction);
// -------
//--- Title
this.setTitle("Simple Equilibrium Diagrams");
jMenuBar.add(javax.swing.Box.createHorizontalGlue(),2); //move "Help" menu to the right
//--- center Window on Screen
originalSize = this.getSize();
screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int left; int top;
left = Math.max(55, (screenSize.width - originalSize.width ) / 2);
top = Math.max(10, (screenSize.height - originalSize.height) / 2);
this.setLocation(Math.min(screenSize.width-100, left),
Math.min(screenSize.height-100, top));
//---- Icon
String iconName = "images/PlotLog256_32x32_blackBckgr.gif";
java.net.URL imgURL = this.getClass().getResource(iconName);
java.awt.Image icon;
if (imgURL != null) {
icon = new javax.swing.ImageIcon(imgURL).getImage();
this.setIconImage(icon);
//com.apple.eawt.Application.getApplication().setDockIconImage(new javax.swing.ImageIcon("Football.png").getImage());
if(System.getProperty("os.name").startsWith("Mac OS")) {
try {
Class<?> c = Class.forName("com.apple.eawt.Application");
//Class params[] = new Class[] {java.awt.Image.class};
java.lang.reflect.Method m =
c.getDeclaredMethod("setDockIconImage",new Class[] { java.awt.Image.class });
Object i = c.newInstance();
Object paramsObj[] = new Object[]{icon};
m.invoke(i, paramsObj);
} catch (Exception e) {System.out.println("Error: "+e.getMessage());}
}
} else {
System.out.println("Error: Could not load image = \""+iconName+"\"");
}
//--- set up the Form
jMenuFileMakeD.setEnabled(false);
jButtonDoIt.setText("make the Diagram");
jButtonDoIt.setEnabled(false);
java.awt.Font f = new java.awt.Font("Monospaced", java.awt.Font.PLAIN, 12);
jTextAreaA.setFont(f);
jTextAreaA.setText(null);
jTabbedPane.setEnabledAt(1, false);
jTabbedPane.setEnabledAt(2, false);
jScrollBarNbrPoints.setFocusable(true);
jScrollBarNbrPoints.setValue(nSteps);
jScrollBarHeight.setFocusable(true);
tHeight = 1;
jScrollBarHeight.setValue(Math.round((float)(10*tHeight)));
jLabelPltFile.setText("plot file name");
jLabelPltFile.setEnabled(false);
jTextFieldPltFile.setText(null);
jTextFieldPltFile.setEnabled(false);
jLabelStatus.setText("waiting...");
jLabelProgress.setText(" ");
jLabelTemperature.setText("NaN"); // no temperature given
jLabelPressure.setText("NaN"); // no pressure given
jComboBoxModel.setSelectedIndex(actCoeffsModelDefault);
//--- the methods in DiagrPaintUtility are used to paint the diagram
diagrPaintUtil = new DiagrPaintUtility();
} // SED constructor
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="start">
/** Sets this window frame visible, and deals with the command-line arguments
* @param reversedConcs0 needed when reading the input data file.
* The command-line argument may be given <i>after</i> the data file name...
* @param help0 if help is displayed, request focus for the text pane,
* where the help is shown
* @param args the command-line arguments */
private void start(
final boolean reversedConcs0,
final boolean help0,
final String[] args) {
this.setVisible(true);
//--- deal with any command line arguments
inputDataFileInCommandLine = false;
reversedConcs = reversedConcs0; //this is needed when reading the data file
boolean argErr = false;
if(args != null && args.length >0){
for (String arg : args) {
if (!dispatchArg(arg)) {argErr = true;}
} // for arg
} // if argsList != null
if(argErr && !doNotExit) {end_program(); return;}
out.println("Finished reading command-line arguments.");
if(dbg) {
out.println("--------"+nl+
"Application path: \""+pathApp+"\""+nl+
"Default path: \""+pathDef.toString()+"\""+nl+
"--------");
}
consoleOutput = inputDataFileInCommandLine & !doNotExit;
// is the temperture missing even if a ionic strength is given?
if((!Double.isNaN(ionicStrength) && Math.abs(ionicStrength) >1e-10)
&& Double.isNaN(temperature_InCommandLine)) {
String msg = "Warning: ionic strength given as command line argument, I="
+(float)ionicStrength+nl+
" but no temperature is given on the command line.";
out.println(msg);
}
// if the command-line "-i" is not given, set the ionic strength to zero
if(!calcActCoeffs) {ionicStrength = 0;}
//set_dbgHalta_inRadioMenus();
jCheckReverse.setSelected(reversedConcs);
jCheckTable.setSelected(tableOutput);
jCheckActCoeff.setSelected(calcActCoeffs);
jTextFieldIonicStgr.setText(String.valueOf(ionicStrength));
showActivityCoefficientControls(calcActCoeffs);
set_tol_inComboBox();
//--- if help is requested on the command line and the
// program's window stays on screen: show the message pane
if(help0) {
jTextAreaA.setCaretPosition(0);
jTabbedPane.setSelectedComponent(jScrollPaneMessg);
}
// Make a diagram if an input file is given in the command-line
if(inputDataFileInCommandLine) {
if(outputPltFile == null) {
String txt = inputDataFile.getAbsolutePath();
String plotFileN = txt.substring(0,txt.length()-3).concat("plt");
outputPltFile = new java.io.File(plotFileN);
}
// note: as the calculations are done on a worker thread, this returns pretty quickly
try {doCalculations();}
catch (Exception ex) {showErrMsgBx(ex);}
}
programEnded = false;
} //start
//</editor-fold>
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroupDebug = new javax.swing.ButtonGroup();
jTabbedPane = new javax.swing.JTabbedPane();
jPanelParameters = new javax.swing.JPanel();
jPanelFiles = new javax.swing.JPanel();
jLabelData = new javax.swing.JLabel();
jTextFieldDataFile = new javax.swing.JTextField();
jLabelPltFile = new javax.swing.JLabel();
jTextFieldPltFile = new javax.swing.JTextField();
jPanel3 = new javax.swing.JPanel();
jCheckReverse = new javax.swing.JCheckBox();
jCheckTable = new javax.swing.JCheckBox();
jPanelActC = new javax.swing.JPanel();
jCheckActCoeff = new javax.swing.JCheckBox();
jPanel1 = new javax.swing.JPanel();
jLabelIonicStr = new javax.swing.JLabel();
jTextFieldIonicStgr = new javax.swing.JTextField();
jLabelIonicStrM = new javax.swing.JLabel();
jPanelT = new javax.swing.JPanel();
jLabelT = new javax.swing.JLabel();
jLabelTC = new javax.swing.JLabel();
jLabelP = new javax.swing.JLabel();
jLabelPressure = new javax.swing.JLabel();
jLabelBar = new javax.swing.JLabel();
jLabelTemperature = new javax.swing.JLabel();
jPanel5 = new javax.swing.JPanel();
jLabelModel = new javax.swing.JLabel();
jComboBoxModel = new javax.swing.JComboBox();
jPanel4 = new javax.swing.JPanel();
jLabelTol = new javax.swing.JLabel();
jComboBoxTol = new javax.swing.JComboBox();
jPanel6 = new javax.swing.JPanel();
jButtonDoIt = new javax.swing.JButton();
jPanel2 = new javax.swing.JPanel();
jLabelNbrPText = new javax.swing.JLabel();
jLabelPointsNbr = new javax.swing.JLabel();
jScrollBarNbrPoints = new javax.swing.JScrollBar();
jLabelHeight = new javax.swing.JLabel();
jLabelHD = new javax.swing.JLabel();
jScrollBarHeight = new javax.swing.JScrollBar();
jScrollPaneMessg = new javax.swing.JScrollPane();
jTextAreaA = new javax.swing.JTextArea();
jPanelDiagram = new javax.swing.JPanel()
{
@Override
public void paint(java.awt.Graphics g)
{
super.paint(g);
paintDiagrPanel(g);
}
};
jPanelStatusBar = new javax.swing.JPanel();
jLabelStatus = new javax.swing.JLabel();
jLabelProgress = new javax.swing.JLabel();
jMenuBar = new javax.swing.JMenuBar();
jMenuFile = new javax.swing.JMenu();
jMenuFileOpen = new javax.swing.JMenuItem();
jMenuFileMakeD = new javax.swing.JMenuItem();
jMenuFileXit = new javax.swing.JMenuItem();
jMenuDebug = new javax.swing.JMenu();
jCheckBoxMenuSEDdebug = new javax.swing.JCheckBoxMenuItem();
jMenuSave = new javax.swing.JMenuItem();
jMenuHF_dbg = new javax.swing.JMenuItem();
jMenuCancel = new javax.swing.JMenuItem();
jMenuHelp = new javax.swing.JMenu();
jMenuHelpAbout = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
addWindowFocusListener(new java.awt.event.WindowFocusListener() {
public void windowGainedFocus(java.awt.event.WindowEvent evt) {
formWindowGainedFocus(evt);
}
public void windowLostFocus(java.awt.event.WindowEvent evt) {
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jTabbedPane.setTabLayoutPolicy(javax.swing.JTabbedPane.SCROLL_TAB_LAYOUT);
jTabbedPane.setAlignmentX(0.0F);
jLabelData.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabelData.setLabelFor(jTextFieldDataFile);
jLabelData.setText("input data file:");
jTextFieldDataFile.setBackground(new java.awt.Color(204, 204, 204));
jTextFieldDataFile.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTextFieldDataFileMouseClicked(evt);
}
});
jTextFieldDataFile.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTextFieldDataFileKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextFieldDataFileKeyTyped(evt);
}
});
jLabelPltFile.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabelPltFile.setLabelFor(jTextFieldPltFile);
jLabelPltFile.setText("<html>p<u>l</u>ot file name:</html>");
javax.swing.GroupLayout jPanelFilesLayout = new javax.swing.GroupLayout(jPanelFiles);
jPanelFiles.setLayout(jPanelFilesLayout);
jPanelFilesLayout.setHorizontalGroup(
jPanelFilesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelFilesLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelFilesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelData, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelPltFile, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelFilesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextFieldDataFile)
.addComponent(jTextFieldPltFile))
.addContainerGap())
);
jPanelFilesLayout.setVerticalGroup(
jPanelFilesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelFilesLayout.createSequentialGroup()
.addGroup(jPanelFilesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelData)
.addComponent(jTextFieldDataFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelFilesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextFieldPltFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelPltFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(120, 120, 120))
);
jCheckReverse.setMnemonic(java.awt.event.KeyEvent.VK_R);
jCheckReverse.setText("<html>allow <u>R</u>eversed min. and max. axes limits</html>");
jCheckReverse.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckReverseActionPerformed(evt);
}
});
jCheckTable.setMnemonic(java.awt.event.KeyEvent.VK_O);
jCheckTable.setText("<html>table <u>O</u>utput</html>");
jCheckTable.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckTableActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jCheckReverse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(53, 53, 53)
.addComponent(jCheckTable, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(189, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(0, 0, 0)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jCheckTable, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jCheckReverse, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
jCheckActCoeff.setMnemonic(java.awt.event.KeyEvent.VK_A);
jCheckActCoeff.setText("<html><u>A</u>ctivity coefficient calculations</html>");
jCheckActCoeff.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckActCoeffActionPerformed(evt);
}
});
jLabelIonicStr.setLabelFor(jTextFieldIonicStgr);
jLabelIonicStr.setText("<html>ionic <u>S</u>trength</html>");
jLabelIonicStr.setEnabled(false);
jTextFieldIonicStgr.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
jTextFieldIonicStgr.setEnabled(false);
jTextFieldIonicStgr.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextFieldIonicStgrActionPerformed(evt);
}
});
jTextFieldIonicStgr.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextFieldIonicStgrFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jTextFieldIonicStgrFocusLost(evt);
}
});
jTextFieldIonicStgr.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTextFieldIonicStgrKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextFieldIonicStgrKeyTyped(evt);
}
});
jLabelIonicStrM.setText("<html>mol/(kg H<sub>2</sub>O)</html>");
jLabelIonicStrM.setEnabled(false);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabelIonicStr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextFieldIonicStgr, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelIonicStrM, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(7, 7, 7))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelIonicStr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextFieldIonicStgr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelIonicStrM, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jLabelT.setText("<html>temperature =</html>");
jLabelT.setEnabled(false);
jLabelTC.setText("<html>°C</html>");
jLabelTC.setEnabled(false);
jLabelP.setText("<html>pressure =</html>");
jLabelP.setEnabled(false);
jLabelPressure.setText("88.36");
jLabelPressure.setEnabled(false);
jLabelBar.setText("<html>bar</html>");
jLabelBar.setEnabled(false);
jLabelTemperature.setText("300");
jLabelTemperature.setEnabled(false);
javax.swing.GroupLayout jPanelTLayout = new javax.swing.GroupLayout(jPanelT);
jPanelT.setLayout(jPanelTLayout);
jPanelTLayout.setHorizontalGroup(
jPanelTLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelTLayout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jLabelT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelTemperature)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelTC, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(71, 71, 71)
.addComponent(jLabelP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelPressure)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(146, Short.MAX_VALUE))
);
jPanelTLayout.setVerticalGroup(
jPanelTLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelTLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelTC, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelPressure)
.addComponent(jLabelBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelTemperature))
);
jLabelModel.setLabelFor(jComboBoxModel);
jLabelModel.setText("<html>activity <u>C</u>officient model:<html>");
jComboBoxModel.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Davies eqn.", "SIT (Specific Ion interaction 'Theory')", "simplified HKF (Helgeson, Kirkham & Flowers)" }));
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jComboBoxModel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelModel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(28, Short.MAX_VALUE))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addComponent(jLabelModel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBoxModel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanelActCLayout = new javax.swing.GroupLayout(jPanelActC);
jPanelActC.setLayout(jPanelActCLayout);
jPanelActCLayout.setHorizontalGroup(
jPanelActCLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelActCLayout.createSequentialGroup()
.addGroup(jPanelActCLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelActCLayout.createSequentialGroup()
.addGroup(jPanelActCLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelActCLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jCheckActCoeff, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanelT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(20, Short.MAX_VALUE))
);
jPanelActCLayout.setVerticalGroup(
jPanelActCLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelActCLayout.createSequentialGroup()
.addGroup(jPanelActCLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelActCLayout.createSequentialGroup()
.addComponent(jCheckActCoeff, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
.addComponent(jPanelT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jLabelTol.setLabelFor(jComboBoxTol);
jLabelTol.setText("<html><u>T</u>olerance (for calculations in HaltaFall):</html>");
jComboBoxTol.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1E-2", "1E-3", "1E-4", "1E-5", "1E-6", "1E-7", "1E-8", "1E-9", " " }));
jComboBoxTol.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBoxTolActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jLabelTol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBoxTol, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(265, Short.MAX_VALUE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelTol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBoxTol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jButtonDoIt.setMnemonic('D');
jButtonDoIt.setText("make the Diagram");
jButtonDoIt.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonDoIt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonDoItActionPerformed(evt);
}
});
jLabelNbrPText.setLabelFor(jLabelPointsNbr);
jLabelNbrPText.setText("<html><u>N</u>br of calc. steps:</html>");
jLabelPointsNbr.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabelPointsNbr.setText("50");
jLabelPointsNbr.setToolTipText("double-click to reset to default");
jLabelPointsNbr.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabelPointsNbrMouseClicked(evt);
}
});
jScrollBarNbrPoints.setMaximum(NSTP_MAX+1);
jScrollBarNbrPoints.setMinimum(NSTP_MIN);
jScrollBarNbrPoints.setOrientation(javax.swing.JScrollBar.HORIZONTAL);
jScrollBarNbrPoints.setVisibleAmount(1);
jScrollBarNbrPoints.addAdjustmentListener(new java.awt.event.AdjustmentListener() {
public void adjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {
jScrollBarNbrPointsAdjustmentValueChanged(evt);
}
});
jScrollBarNbrPoints.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jScrollBarNbrPointsFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jScrollBarNbrPointsFocusLost(evt);
}
});
jLabelHeight.setText("<html>h<u>e</u>ight of text in diagram:</html>");
jLabelHD.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabelHD.setText("1.0");
jLabelHD.setToolTipText("double-click to reset to default");
jLabelHD.setMaximumSize(new java.awt.Dimension(15, 14));
jLabelHD.setMinimumSize(new java.awt.Dimension(15, 14));
jLabelHD.setPreferredSize(new java.awt.Dimension(15, 14));
jLabelHD.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabelHDMouseClicked(evt);
}
});
jScrollBarHeight.setMaximum(101);
jScrollBarHeight.setMinimum(3);
jScrollBarHeight.setOrientation(javax.swing.JScrollBar.HORIZONTAL);
jScrollBarHeight.setValue(10);
jScrollBarHeight.setVisibleAmount(1);
jScrollBarHeight.addAdjustmentListener(new java.awt.event.AdjustmentListener() {
public void adjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {
jScrollBarHeightAdjustmentValueChanged(evt);
}
});
jScrollBarHeight.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jScrollBarHeightFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jScrollBarHeightFocusLost(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabelNbrPText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelHeight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelPointsNbr, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelHD, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollBarHeight, javax.swing.GroupLayout.DEFAULT_SIZE, 75, Short.MAX_VALUE)
.addComponent(jScrollBarNbrPoints, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelNbrPText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelPointsNbr))
.addComponent(jScrollBarNbrPoints, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelHeight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelHD, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollBarHeight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButtonDoIt, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(121, Short.MAX_VALUE))
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButtonDoIt)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
javax.swing.GroupLayout jPanelParametersLayout = new javax.swing.GroupLayout(jPanelParameters);
jPanelParameters.setLayout(jPanelParametersLayout);
jPanelParametersLayout.setHorizontalGroup(
jPanelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelParametersLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jPanelFiles, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanelParametersLayout.createSequentialGroup()
.addGroup(jPanelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jPanel6, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanelActC, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 21, Short.MAX_VALUE)))
.addContainerGap())
);
jPanelParametersLayout.setVerticalGroup(
jPanelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelParametersLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanelFiles, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanelActC, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(41, 41, 41)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(49, Short.MAX_VALUE))
);
jTabbedPane.addTab("<html><u>P</u>arameters</html>", jPanelParameters);
jScrollPaneMessg.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
jScrollPaneMessg.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
jScrollPaneMessg.setFont(new java.awt.Font("Monospaced", 0, 13)); // NOI18N
jTextAreaA.setBackground(new java.awt.Color(255, 255, 204));
jTextAreaA.setText("Use the PrintStreams \"err\" and \"out\" to\nsend messages to this pane, for example;\n out.println(\"message\");\n err.println(\"Error\");\netc.\nSystem.out and System.err will send\noutput to the console, which might\nnot be available to the user.");
jTextAreaA.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTextAreaAKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextAreaAKeyTyped(evt);
}
});
jScrollPaneMessg.setViewportView(jTextAreaA);
jTabbedPane.addTab("Messages", jScrollPaneMessg);
jPanelDiagram.setBackground(new java.awt.Color(255, 255, 255));
javax.swing.GroupLayout jPanelDiagramLayout = new javax.swing.GroupLayout(jPanelDiagram);
jPanelDiagram.setLayout(jPanelDiagramLayout);
jPanelDiagramLayout.setHorizontalGroup(
jPanelDiagramLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 594, Short.MAX_VALUE)
);
jPanelDiagramLayout.setVerticalGroup(
jPanelDiagramLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 370, Short.MAX_VALUE)
);
jTabbedPane.addTab("Diagram", jPanelDiagram);
jPanelStatusBar.setBackground(new java.awt.Color(204, 255, 255));
jPanelStatusBar.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jLabelStatus.setText("# # # #");
jLabelProgress.setText("text");
javax.swing.GroupLayout jPanelStatusBarLayout = new javax.swing.GroupLayout(jPanelStatusBar);
jPanelStatusBar.setLayout(jPanelStatusBarLayout);
jPanelStatusBarLayout.setHorizontalGroup(
jPanelStatusBarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelStatusBarLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabelStatus)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabelProgress, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jPanelStatusBarLayout.setVerticalGroup(
jPanelStatusBarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelStatusBarLayout.createSequentialGroup()
.addGroup(jPanelStatusBarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelProgress)
.addComponent(jLabelStatus))
.addContainerGap())
);
jMenuFile.setMnemonic('F');
jMenuFile.setText("File");
jMenuFileOpen.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.ALT_MASK));
jMenuFileOpen.setMnemonic('O');
jMenuFileOpen.setText("Open input file");
jMenuFileOpen.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuFileOpenActionPerformed(evt);
}
});
jMenuFile.add(jMenuFileOpen);
jMenuFileMakeD.setMnemonic('D');
jMenuFileMakeD.setText("make the Diagram");
jMenuFileMakeD.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuFileMakeDActionPerformed(evt);
}
});
jMenuFile.add(jMenuFileMakeD);
jMenuFileXit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK));
jMenuFileXit.setMnemonic('x');
jMenuFileXit.setText("Exit");
jMenuFileXit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuFileXitActionPerformed(evt);
}
});
jMenuFile.add(jMenuFileXit);
jMenuBar.add(jMenuFile);
jMenuDebug.setMnemonic('b');
jMenuDebug.setText("debug");
jCheckBoxMenuSEDdebug.setMnemonic('V');
jCheckBoxMenuSEDdebug.setText("Verbose");
jCheckBoxMenuSEDdebug.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxMenuSEDdebugActionPerformed(evt);
}
});
jMenuDebug.add(jCheckBoxMenuSEDdebug);
jMenuSave.setMnemonic('v');
jMenuSave.setText("save messages to file");
jMenuSave.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuSaveActionPerformed(evt);
}
});
jMenuDebug.add(jMenuSave);
jMenuHF_dbg.setMnemonic('H');
jMenuHF_dbg.setText("debugging in HaltaFall...");
jMenuHF_dbg.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuHF_dbgActionPerformed(evt);
}
});
jMenuDebug.add(jMenuHF_dbg);
jMenuCancel.setMnemonic('S');
jMenuCancel.setText("STOP the Calculations (Alt-S)");
jMenuCancel.setEnabled(false);
jMenuCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuCancelActionPerformed(evt);
}
});
jMenuDebug.add(jMenuCancel);
jMenuBar.add(jMenuDebug);
jMenuHelp.setMnemonic('H');
jMenuHelp.setText("Help");
jMenuHelpAbout.setMnemonic('a');
jMenuHelpAbout.setText("About");
jMenuHelpAbout.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuHelpAboutActionPerformed(evt);
}
});
jMenuHelp.add(jMenuHelpAbout);
jMenuBar.add(jMenuHelp);
setJMenuBar(jMenuBar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanelStatusBar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTabbedPane)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jTabbedPane)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanelStatusBar, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
//<editor-fold defaultstate="collapsed" desc="Events">
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
end_program();
}//GEN-LAST:event_formWindowClosing
private void jMenuHelpAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuHelpAboutActionPerformed
jMenuHelpAbout.setEnabled(false);
Thread hlp = new Thread() {@Override public void run(){
helpAboutFrame = new HelpAboutF(VERS, pathApp, out);
helpAboutFrame.setVisible(true);
helpAboutFrame.waitFor();
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
helpAboutFrame = null;
jMenuHelpAbout.setEnabled(true);
}}); //invokeLater(Runnable)
}};//new Thread
hlp.start();
}//GEN-LAST:event_jMenuHelpAboutActionPerformed
private void jMenuFileXitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuFileXitActionPerformed
end_program();
}//GEN-LAST:event_jMenuFileXitActionPerformed
private void jMenuFileOpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuFileOpenActionPerformed
eraseTextArea = true;
getTheInputFileName();
jTabbedPane.requestFocusInWindow();
}//GEN-LAST:event_jMenuFileOpenActionPerformed
private void jMenuFileMakeDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuFileMakeDActionPerformed
jButtonDoIt.doClick();
}//GEN-LAST:event_jMenuFileMakeDActionPerformed
private void jCheckActCoeffActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckActCoeffActionPerformed
if(jCheckActCoeff.isSelected()) {
calcActCoeffs = true;
showActivityCoefficientControls(true);
ionicStrength = readIonStrength();
}
else {
calcActCoeffs = false;
showActivityCoefficientControls(false);
}
}//GEN-LAST:event_jCheckActCoeffActionPerformed
private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
int width = originalSize.width;
int height = originalSize.height;
if(this.getHeight()<height){this.setSize(this.getWidth(), height);}
if(this.getWidth()<width){this.setSize(width,this.getHeight());}
if(jTabbedPane.getWidth()>this.getWidth()) {
jTabbedPane.setSize(this.getWidth(), jTabbedPane.getWidth());
}
}//GEN-LAST:event_formComponentResized
private void jTextAreaAKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextAreaAKeyTyped
evt.consume();
}//GEN-LAST:event_jTextAreaAKeyTyped
private void jTextAreaAKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextAreaAKeyPressed
if(!Util.isKeyPressedOK(evt)) {evt.consume();}
}//GEN-LAST:event_jTextAreaAKeyPressed
private void jScrollBarNbrPointsAdjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {//GEN-FIRST:event_jScrollBarNbrPointsAdjustmentValueChanged
jLabelPointsNbr.setText(String.valueOf(jScrollBarNbrPoints.getValue()).trim());
}//GEN-LAST:event_jScrollBarNbrPointsAdjustmentValueChanged
private void jScrollBarNbrPointsFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jScrollBarNbrPointsFocusGained
jScrollBarNbrPoints.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0,0,0)));
}//GEN-LAST:event_jScrollBarNbrPointsFocusGained
private void jScrollBarNbrPointsFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jScrollBarNbrPointsFocusLost
jScrollBarNbrPoints.setBorder(null);
}//GEN-LAST:event_jScrollBarNbrPointsFocusLost
private void jScrollBarHeightAdjustmentValueChanged(java.awt.event.AdjustmentEvent evt) {//GEN-FIRST:event_jScrollBarHeightAdjustmentValueChanged
jLabelHD.setText(String.valueOf((float)jScrollBarHeight.getValue()/10f).trim());
}//GEN-LAST:event_jScrollBarHeightAdjustmentValueChanged
private void jScrollBarHeightFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jScrollBarHeightFocusGained
jScrollBarHeight.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0,0,0)));
}//GEN-LAST:event_jScrollBarHeightFocusGained
private void jScrollBarHeightFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jScrollBarHeightFocusLost
jScrollBarHeight.setBorder(null);
}//GEN-LAST:event_jScrollBarHeightFocusLost
private void jTextFieldIonicStgrKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldIonicStgrKeyTyped
char key = evt.getKeyChar();
if(!isCharOKforNumberInput(key)) {evt.consume();}
}//GEN-LAST:event_jTextFieldIonicStgrKeyTyped
private void jTextFieldIonicStgrFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldIonicStgrFocusLost
validateIonicStrength();
}//GEN-LAST:event_jTextFieldIonicStgrFocusLost
private void jTextFieldIonicStgrKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldIonicStgrKeyPressed
if(evt.getKeyChar() == java.awt.event.KeyEvent.VK_ENTER) {
validateIonicStrength();
}
}//GEN-LAST:event_jTextFieldIonicStgrKeyPressed
private void jTextFieldDataFileKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldDataFileKeyTyped
char c = Character.toUpperCase(evt.getKeyChar());
if(evt.getKeyChar() != java.awt.event.KeyEvent.VK_ESCAPE &&
!(evt.isAltDown() &&
((c == 'F') ||
(c == 'I') || (c == 'X') ||
(c == 'H') || (c == 'A') ||
(c == 'N') || (c == 'D') ||
(c == 'R') || (c == 'O') ||
(c == 'T') ||
(c == 'A') || (c == 'S'))
) //isAltDown
)
{
evt.consume(); // remove the typed key
getTheInputFileName();
}
}//GEN-LAST:event_jTextFieldDataFileKeyTyped
private void jTextFieldDataFileKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldDataFileKeyPressed
if(!Util.isKeyPressedOK(evt)) {evt.consume();}
}//GEN-LAST:event_jTextFieldDataFileKeyPressed
private void jCheckReverseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckReverseActionPerformed
reversedConcs = jCheckReverse.isSelected();
}//GEN-LAST:event_jCheckReverseActionPerformed
private void jCheckTableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckTableActionPerformed
tableOutput = jCheckTable.isSelected();
}//GEN-LAST:event_jCheckTableActionPerformed
private void jButtonDoItActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDoItActionPerformed
// If no plot-file name is given in the command line but
// a data-file name is given: set a default plot-file name
if(outputPltFile == null) {
String dir = pathDef.toString();
if(dir.endsWith(SLASH)) {dir = dir.substring(0,dir.length()-1);}
outputPltFile = new java.io.File(dir + SLASH + jTextFieldPltFile.getText());
}
// note: as the calculations are done on a worker thread, this returns pretty quickly
doCalculations();
// statements here are performed almost inmediately
}//GEN-LAST:event_jButtonDoItActionPerformed
private void jTextFieldDataFileMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFieldDataFileMouseClicked
eraseTextArea = true;
getTheInputFileName();
}//GEN-LAST:event_jTextFieldDataFileMouseClicked
private void jTextFieldIonicStgrActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldIonicStgrActionPerformed
validateIonicStrength();
}//GEN-LAST:event_jTextFieldIonicStgrActionPerformed
private void jTextFieldIonicStgrFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldIonicStgrFocusGained
jTextFieldIonicStgr.selectAll();
}//GEN-LAST:event_jTextFieldIonicStgrFocusGained
private void jCheckBoxMenuSEDdebugActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxMenuSEDdebugActionPerformed
dbg = jCheckBoxMenuSEDdebug.isSelected();
}//GEN-LAST:event_jCheckBoxMenuSEDdebugActionPerformed
private void jComboBoxTolActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxTolActionPerformed
int i = jComboBoxTol.getSelectedIndex();
tolHalta = 0.01/Math.pow(10,i);
}//GEN-LAST:event_jComboBoxTolActionPerformed
private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus
if(helpAboutFrame != null) {helpAboutFrame.bringToFront();}
}//GEN-LAST:event_formWindowGainedFocus
private void jLabelPointsNbrMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelPointsNbrMouseClicked
if(evt.getClickCount() >1) { // double-click
jScrollBarNbrPoints.setValue(NSTP_DEF);
}
}//GEN-LAST:event_jLabelPointsNbrMouseClicked
private void jLabelHDMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelHDMouseClicked
if(evt.getClickCount() >1) { // double-click
jScrollBarHeight.setValue(10);
}
}//GEN-LAST:event_jLabelHDMouseClicked
private void jMenuHF_dbgActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuHF_dbgActionPerformed
Debugging debugging = new Debugging(this,true, this, err);
debugging.setVisible(true);
}//GEN-LAST:event_jMenuHF_dbgActionPerformed
private void jMenuSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuSaveActionPerformed
jTextFieldDataFile.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
setCursorWait();
if(pathDef == null) {setPathDef();}
String txtfn = Util.getSaveFileName(this, progName, "Choose an output file name:", 7, "messages.txt", pathDef.toString());
jTextFieldDataFile.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
setCursorDef();
if(txtfn == null || txtfn.trim().equals("")) {return;}
java.io.File outputTxtFile = new java.io.File(txtfn);
java.io.Writer w = null;
try {
w = new java.io.BufferedWriter(
new java.io.OutputStreamWriter(
new java.io.FileOutputStream(outputTxtFile),"UTF8"));
w.write(jTextAreaA.getText());
w.flush();
w.close();
javax.swing.JOptionPane.showMessageDialog(this, "File:"+nl+" "+outputTxtFile.toString()+nl+"has been written.",
progName,javax.swing.JOptionPane.INFORMATION_MESSAGE);
}
catch (Exception ex) {showErrMsgBx(ex.toString(),1);}
finally {
try{if(w != null) {w.flush(); w.close();}}
catch (Exception ex) {showErrMsgBx(ex.toString(),1);}
}
jTabbedPane.setSelectedComponent(jScrollPaneMessg);
jTabbedPane.requestFocusInWindow();
}//GEN-LAST:event_jMenuSaveActionPerformed
private void jMenuCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuCancelActionPerformed
quitConfirm(this);
}//GEN-LAST:event_jMenuCancelActionPerformed
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="checkInput">
/** Make checks and make changes to the data stored in the Chem classes.
* @return true if checks are OK */
private boolean checkInput() {
if(cs == null) {err.println("? Programming error in \"SED.checkInput\": cs=null."); return false;}
if(dbg) {out.println("--- checkInput()");}
// -------------------
// CHEMICAL SYSTEM
// -------------------
// mg = total number of soluble species in the aqueous solution:
// all components + soluble complexes
// Note that in HaltaFall the solid components are fictitious soluble
// components with "zero" concentration (with noll = true)
int mg = cs.Ms - cs.mSol; // = na + nx;
int i;
// ---- Remove asterisk "*" from the name of components
for(i=0; i<cs.Na; i++) {
if(namn.identC[i].startsWith("*")) {
namn.identC[i] = namn.identC[i].substring(1);
namn.ident[i] = namn.identC[i];
cs.noll[i] = true;
}
//if(chem_syst.Chem.isWater(csNamn.identC[i]))
// {water = i;}
} // for i=0...Na-1
// ---- Remove reaction products (soluble or solid) with
// name starting with "*".
// Note that the solids corresponding to the components will
// not have a name starting with "*". This is already removed when
// reading the input file.
double w; int j; int js;
i = cs.Na;
while (i < cs.Ms) {
if(namn.ident[i].startsWith("*")) {
if(i < mg) {mg--; cs.nx = cs.nx-1;} else {cs.mSol = cs.mSol -1;}
cs.Ms = cs.Ms -1;
if(i >= cs.Ms) {break;}
for(j=i; j<cs.Ms; j++) {
js = j - cs.Na;
cs.lBeta[js] = cs.lBeta[js+1];
//for(int ia=0; ia<cs.Na; ia++) {cs.a[js][ia] = cs.a[js+1][ia];}
System.arraycopy(cs.a[js+1], 0, cs.a[js], 0, cs.Na);
namn.ident[j] = namn.ident[j+1];
cs.noll[j] = cs.noll[j+1];
}
} else {i++;}
} //while (true)
// ---- get electric charge, length of name, etc
diag.aquSystem = false;
for(i=0; i<cs.Ms; i++) {
namn.nameLength[i] = getNameLength(namn.ident[i]);
// Species for which the concentration is not to be
// included in the Mass-Balance (for ex. the concentration
// of "free" electrons is excluded)
if(Util.isElectron(namn.ident[i]) || Util.isWater(namn.ident[i])) {
cs.noll[i] = true;
diag.aquSystem = true;
}
if(i < mg) { //aqueous species
namn.z[i]=0;
csC.logf[i] = 0;
if(namn.ident[i].length() >4 &&
namn.ident[i].toUpperCase().endsWith("(AQ)")) {
diag.aquSystem = true;}
else { //does not end with "(aq)"
namn.z[i] = Util.chargeOf(namn.ident[i]);
if(namn.z[i] != 0) {diag.aquSystem = true;}
} // ends with "(aq)"?
}
} // for i=0...Ms-1
// The electric charge of two fictive species (Na+ and Cl-)
// that are used to ensure electrically neutral aqueous solutions
// when calculating the ionic strength and activity coefficients
namn.z[mg] = 1; //electroneutrality "Na+"
namn.z[mg+1] =-1; //electroneutrality "Na+"
// ---- set Gaseous species to have zero conc
// if it is an aqueous system
if(diag.aquSystem) {
for(i =0; i < mg; i++) {
if(Util.isGas(namn.ident[i])
|| Util.isLiquid(namn.ident[i])
|| Util.isWater(namn.ident[i])) {cs.noll[i] = true;}
} //for i
}
// ---- Remove any reaction product (complex) named "H2O", if found
if(diag.aquSystem) {
for(i=cs.Na; i<cs.Ms; i++) {
if(Util.isWater(namn.ident[i])) {
if(i < mg) {mg--; cs.nx = cs.nx-1;} else {cs.mSol = cs.mSol -1;}
cs.Ms = cs.Ms -1;
if(i >= cs.Ms) {break;}
for(j=i; j<cs.Ms; j++) {
js = j - cs.Na;
cs.lBeta[js] = cs.lBeta[js+1];
//for(int ia=0; ia<cs.Na; ia++) {cs.a[js][ia] = cs.a[js+1][ia];}
System.arraycopy(cs.a[js+1], 0, cs.a[js], 0, cs.Na);
namn.ident[j] = namn.ident[j+1];
cs.noll[j] = cs.noll[j+1];
}
} //ident[i]="H2O"
} //for i
} //if aquSystem
if(dbg) {cs.printChemSystem(out);}
// ---- Check that all reactions are charge balanced
if(calcActCoeffs) {
double zSum;
boolean ok = true;
for(i=cs.Na; i < mg; i++) {
int ix = i - cs.Na;
zSum = (double)(-namn.z[i]);
for(j=0; j < cs.Na; j++) {
zSum = zSum + cs.a[ix][j]*(double)namn.z[j];
} //for j
if(Math.abs(zSum) > 0.0005) {
ok = false;
err.format(engl,"--- Warning: %s, z=%3d, charge imbalance:%9.4f",
namn.ident[i],namn.z[i],zSum);
}
} //for i
if(!ok) {
if(!showErrMsgBxCancel("There are charge imbalanced reactions in the input file.",1)) {
return false;
}
}
} // if calcActCoeffs
// ---- Check that at least there is one fuid species active
boolean foundOne = false;
for(i =0; i < mg; i++) {
if(!cs.noll[i]) {foundOne = true; break;}
} //for i
if(!foundOne) {
String t = "Error: There are no fluid species active ";
if(cs.mSol > 0) {t = t.concat("(Only solids)");}
t = t+nl+"This program can not handle such chemical systems.";
showErrMsgBx(t, 1);
return false;
}
// --------------------
// PLOT INFORMATION
// --------------------
diag.pInX =0; diag.pInY = 0;
// pInX=0 "normal" X-axis
// pInX=1 pH in X-axis
// pInX=2 pe in X-axis
// pInX=3 Eh in X-axis
if(Util.isElectron(namn.identC[diag.compX])) {
if(diag.Eh) {diag.pInX = 3;} else {diag.pInX = 2;}
} else if(Util.isProton(namn.identC[diag.compX])) {diag.pInX = 1;}
// ----------------------------------------------
// CHECK THE CONCENTRATION FOR EACH COMPONENT
// ----------------------------------------------
for(int ia =0; ia < cs.Na; ia++) {
if(dgrC.hur[ia]==1 && // T
ia==diag.compX) {
showErrMsgBx("Error: the concentration for component \""+namn.identC[ia]+"\" "+
"must vary, as it belongs to the X-axis!",1);
return false;
}
if(dgrC.hur[ia] >0 && dgrC.hur[ia]<=3) { //T, TV or LTV
if(Util.isWater(namn.identC[ia])) {
showErrMsgBx("Error: The calculations are made for 1kg H2O"+nl+
"Give log(H2O-activity) instead of a total conc. for water.",1);
return false;
} // if water
} //if T, TV or LTV
if(dgrC.hur[ia] ==2 || dgrC.hur[ia] ==3 || dgrC.hur[ia] ==5) { //TV, LTV or LAV
if(ia != diag.compX) {
String t;
if(dgrC.hur[ia] ==5) {t="log(activity)";} else {t="total conc.";}
String msg = "Warning: The "+t+" is varied for \""+namn.identC[ia]+"\""+nl+
" but the component in the X-axis is \""+namn.identC[diag.compX]+"\"";
if(!showErrMsgBxCancel(msg,2)) {return false;}
}
} //if TV, LTV or LAV
if((dgrC.hur[ia] ==1 || dgrC.hur[ia] ==4) && //T or LA
ia == diag.compX) {
String t;
if(dgrC.hur[ia] ==4) {t="log(activity)";} else {t="total conc.";}
showErrMsgBx("Error: The "+t+" of \""+namn.identC[ia]+"\""+nl+
"can NOT be a fixed value because this component belongs to the X-axis !",1);
return false;
}
if(dgrC.hur[ia] ==1 && // T
Math.abs(dgrC.cLow[ia]) >100) {
String t = String.format(engl,"Error: For component: "+namn.identC[ia]+nl+
" Tot.Conc.=%12.4g mol/kg. This is not a reasonable value!",dgrC.cLow[ia]);
showErrMsgBx(t,1);
return false;
}
if(dgrC.hur[ia] ==4 && // LA
Util.isProton(namn.identC[ia]) &&
(dgrC.cLow[ia] <-14 || dgrC.cLow[ia] >2)) {
String msg = String.format(engl,"Warning: In the input, you give pH =%8.2f%n"+
"This value could be due to an input error.",(-dgrC.cLow[ia]));
if(!showErrMsgBxCancel(msg,2)) {return false;}
}
if(dgrC.hur[ia] !=1 && dgrC.hur[ia] !=4) {//if TV, LTV or LAV
if(dgrC.cLow[ia] == dgrC.cHigh[ia] ||
Math.max(Math.abs(dgrC.cLow[ia]), Math.abs(dgrC.cHigh[ia])) < 1e-15) {
showErrMsgBx("Error: Min-value = Max-value for component \""+namn.identC[ia]+"\"",1);
return false;
}
if(dgrC.cLow[ia] > dgrC.cHigh[ia] && !reversedConcs) {
w = dgrC.cLow[ia];
dgrC.cLow[ia] = dgrC.cHigh[ia];
dgrC.cHigh[ia] = w;
}
if(!reversedConcs && dgrC.hur[ia] ==5 && // pH/pe/EH varied - LAV
(Util.isProton(namn.identC[ia]) ||
Util.isElectron(namn.identC[ia]))) {
w = dgrC.cLow[ia];
dgrC.cLow[ia] = dgrC.cHigh[ia];
dgrC.cHigh[ia] = w;
}
if(dgrC.hur[ia] ==5 && // LAV
(Util.isProton(namn.identC[ia])) &&
(dgrC.cLow[ia] <-14.00001 || dgrC.cLow[ia] >2.00001 ||
dgrC.cHigh[ia] <-14.00001 || dgrC.cHigh[ia] >2.00001)) {
String msg = String.format(engl,"Warning: In the input, you give pH =%8.2f to %7.2f%n"+
"These values could be due to an input error.",(-dgrC.cLow[ia]),(-dgrC.cHigh[ia]));
if(!showErrMsgBxCancel(msg,2)) {return false;}
}
if(dgrC.hur[ia] ==2 && // TV
(Math.max(Math.abs(dgrC.cHigh[ia]),Math.abs(dgrC.cLow[ia]))>100)) {
showErrMsgBx("Error: You give ABS(TOT.CONC.) > 100 for component: "+namn.identC[ia]+nl+
"This value is too high and perhaps an input error."+nl+
"Set the maximum ABS(TOT.CONC.) value to 100.",1);
return false;
}
if(dgrC.hur[ia] ==3) { // LTV
if((Math.min(dgrC.cLow[ia], dgrC.cHigh[ia]) < -7.0001) &&
(Util.isProton(namn.identC[ia]))) {
String msg = "Warning: You give a LOG (TOT.CONC.) < -7 for component: "+namn.identC[ia]+nl+
"This value is rather low and could be due to an input error."+nl+
"Maybe you meant to set LOG (ACTIVITY) < -7 ??";
if(!showErrMsgBxCancel(msg,2)) {return false;}
}
if(Math.max(dgrC.cLow[ia], dgrC.cHigh[ia]) > 2.0001) {
showErrMsgBx("Error: You give a LOG (TOT.CONC.) > 2 for component: "+namn.identC[ia]+nl+
"This value is too high and it could be due to an input error."+nl+
"Please set the LOG (TOT.CONC.) value to <=2.",1);
return false;
}
} //if LTV
} //if TV, LTV or LAV
} // for ia = 0... Na-1
// ----------------
// OTHER CHECKS
// ----------------
// ---- See which components have positive or negative (or both)
// values for the stoichiometric coefficients (a[ix][ia]-values)
pos = new boolean[cs.Na];
neg = new boolean[cs.Na];
for(i =0; i < cs.Na; i++) {
pos[i] = false; neg[i] = false;
if(!cs.noll[i]) { // if not "e-" and not solid component
pos[i] = true;}
for(j = cs.Na; j < cs.Ms; j++) {
if(!cs.noll[j]) {
if(cs.a[j-cs.Na][i] >0) {pos[i] = true;}
if(cs.a[j-cs.Na][i] <0) {neg[i] = true;}
} // !noll
} //for j
} //for i
// check POS and NEG with the Tot.Conc. given in the input
for(i =0; i < cs.Na; i++) {
if(csC.kh[i] == 2) {continue;} //only it Tot.conc. is given
if((!pos[i] && !neg[i]) ) { // || cs.nx ==0
String msg = "Error: for component \""+namn.identC[i]+"\" give Log(Activity)";
if(dgrC.hur[i] !=1) { // not "T", that is: "TV" or "LTV"
msg = msg+" to vary";}
showErrMsgBx(msg,1);
return false;
} //if Nx =0 or (!pos[] & !neg[])
if((pos[i] && neg[i]) ||
(pos[i] && (dgrC.hur[i] ==3 || //LTV
(dgrC.cLow[i]>0 && (Double.isNaN(dgrC.cHigh[i]) || dgrC.cHigh[i]>0)))) ||
(neg[i] && (dgrC.hur[i] !=3 && //not LTV
(dgrC.cLow[i]<0 && (Double.isNaN(dgrC.cHigh[i]) || dgrC.cHigh[i]<0))))) {
continue;
}
if(pos[i] || neg[i]) {
String msg = "Error: Component \"%s\" may not have %s Tot.Conc. values.%s"+
"Give either Tot.Conc. %s=0.0 or Log(Activity)%s";
if(neg[i] && (dgrC.hur[i] ==3 || // LTV
dgrC.cLow[i]>0 || (!Double.isNaN(dgrC.cHigh[i]) && dgrC.cHigh[i]>0))) {
showErrMsgBx(String.format(msg, namn.identC[i], "positive", nl,"<",nl),1);
return false;}
if(pos[i] && (dgrC.hur[i] !=3 && //not LTV
(dgrC.cLow[i]<0 || (!Double.isNaN(dgrC.cHigh[i]) && dgrC.cHigh[i]<0)))) {
showErrMsgBx(String.format(msg, namn.identC[i], "negative", nl,">",nl),1);
return false;
}
} //if pos or neg
} //for i
// OK so far. Update "nx" (=nbr of soluble complexes)
cs.nx = mg - cs.Na;
return true;
} // checkInput()
//<editor-fold defaultstate="collapsed" desc="getNameLength(species)">
private static int getNameLength(String species) {
int nameL = Math.max(1, Util.rTrim(species).length());
if(nameL < 3) {return nameL;}
// Correct name length if there is a space between name and charge
// "H +", "S 2-", "Q 23+"
int sign; int ik;
sign =-1;
for(ik =nameL-1; ik >= 2; ik--) {
char c = species.charAt(ik);
if(c == '+' || c == '-' ||
// unicode en dash or unicode minus
c =='\u2013' || c =='\u2212') {sign = ik; break;}
} //for ik
if(sign <2) {return nameL;}
if(sign < nameL-1 &&
(Character.isLetterOrDigit(species.charAt(sign+1)))) {return nameL;}
if(species.charAt(sign-1) == ' ')
{nameL = nameL-1; return nameL;}
if(nameL >=4) {
if(species.charAt(sign-1) >= '2' && species.charAt(sign-1) <= '9' &&
species.charAt(sign-2) == ' ')
{nameL = nameL-1; return nameL;}
} //if nameL >=4
if(nameL >=5) {
if((species.charAt(sign-1) >= '0' && species.charAt(sign-1) <= '9') &&
(species.charAt(sign-2) >= '1' && species.charAt(sign-2) <= '9') &&
species.charAt(sign-3) == ' ')
{nameL = nameL-1;}
} //if nameL >=5
return nameL;
} // getNameLength(species)
//</editor-fold>
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="dispatchArg">
/**
* @param arg String containing a command-line argument
* @return false if there was an error associated with the command argument
*/
private boolean dispatchArg(String arg) {
if(arg == null) {return true;}
out.println("Command-line argument = \""+arg+"\"");
if(arg.equals("-?") || arg.equals("/?") || arg.equals("?")) {
out.println("Usage: SED [data-file-name] [-command=value]");
printInstructions(out);
if(this.isVisible()) {jTabbedPane.setSelectedComponent(jScrollPaneMessg);}
return true;} //if args[] = "?"
String msg = null;
while(true) {
if(arg.length() >3) {
String arg0 = arg.substring(0, 2).toLowerCase();
if(arg0.startsWith("-d") || arg0.startsWith("/d")) {
if(arg.charAt(2) == '=' || arg.charAt(2) == ':') {
String f = arg.substring(3);
if(f.startsWith("\"") && f.endsWith("\"")) { //remove enclosing quotes
f = f.substring(1, f.length()-1);
}
if(!f.toLowerCase().endsWith(".dat")) {f = f.concat(".dat");}
inputDataFile = new java.io.File(f);
setPathDef(inputDataFile);
//get the complete file name
String fil;
try{fil = inputDataFile.getCanonicalPath();}
catch (java.io.IOException e) {
try{fil = inputDataFile.getAbsolutePath();}
catch (Exception e1) {fil = inputDataFile.getPath();}
}
inputDataFile = new java.io.File(fil);
if(dbg){out.println("Data file: "+inputDataFile.getAbsolutePath());}
if(!doNotExit) {consoleOutput = true;}
if(!readDataFile(inputDataFile)) {
//-- error reading data file
if(this.isVisible()) {jTabbedPane.setSelectedComponent(jScrollPaneMessg);}
inputDataFileInCommandLine = false;
return false;
}
else {showTheInputFileName(inputDataFile);}
inputDataFileInCommandLine = true;
return true; // no error
}// = or :
} else if(arg0.startsWith("-p") || arg0.startsWith("/p")) {
if(arg.charAt(2) == '=' || arg.charAt(2) == ':') {
String f = arg.substring(3);
if(f.startsWith("\"") && f.endsWith("\"")) { //remove enclosing quotes
f = f.substring(1, f.length()-1);
}
if(!f.toLowerCase().endsWith(".plt")) {f = f.concat(".plt");}
outputPltFile = new java.io.File(f);
if(dbg){out.println("Plot file: "+outputPltFile.getAbsolutePath());}
jTextFieldPltFile.setText(outputPltFile.getName());
return true;
}// = or :
} else if(arg0.startsWith("-i") || arg0.startsWith("/i")) {
if(arg.charAt(2) == '=' || arg.charAt(2) == ':') {
String t = arg.substring(3);
try {ionicStrength = Double.parseDouble(t);
ionicStrength = Math.max(-1,Math.min(1000,ionicStrength));
if(ionicStrength < 0) {ionicStrength = -1;}
jTextFieldIonicStgr.setText(String.valueOf(ionicStrength));
if(Math.abs(ionicStrength) > 1e-10) {calcActCoeffs = true;}
if(dbg) {out.println("Ionic strength = "+ionicStrength);}
return true;
} //try
catch (NumberFormatException nfe) {
msg = "Wrong numeric format for ionic strength in text \""+t+"\"";
ionicStrength = 0;
jTextFieldIonicStgr.setText(String.valueOf(ionicStrength));
break;
} //catch
}// = or :
} else if(arg0.startsWith("-t") || arg0.startsWith("/t")) {
if(arg.charAt(2) == '=' || arg.charAt(2) == ':') {
String t = arg.substring(3);
try {temperature_InCommandLine = Double.parseDouble(t);
temperature_InCommandLine = Math.min(1000,Math.max(temperature_InCommandLine,-10));
jLabelTemperature.setText(String.valueOf(temperature_InCommandLine));
if(dbg) {out.println("Temperature = "+temperature_InCommandLine);}
return true;
} //try
catch (NumberFormatException nfe) {
msg = "Error: Wrong numeric format for temperature in text \""+t+"\"";
temperature_InCommandLine = Double.NaN;
break;
} //catch
}// = or :
} else if(arg0.startsWith("-h") || arg0.startsWith("/h")) {
if(arg.charAt(2) == '=' || arg.charAt(2) == ':') {
String t = arg.substring(3);
try {tHeight = Double.parseDouble(t);
tHeight = Math.min(10,Math.max(tHeight, 0.3));
jScrollBarHeight.setValue(Math.round((float)(10*tHeight)));
if(dbg) {out.println("Height factor for texts in diagrams = "+tHeight);}
return true;
} //try
catch (NumberFormatException nfe) {
msg = "Wrong numeric format for text height in \""+t+"\"";
tHeight =1;
jScrollBarHeight.setValue(Math.round((float)(10*tHeight)));
break;
} //catch
}// = or :
} // if starts with "-h"
if(arg0.startsWith("-m") || arg0.startsWith("/m")) {
if(arg.charAt(2) == '=' || arg.charAt(2) == ':') {
String t = arg.substring(3);
try {actCoeffsModel_InCommandLine = Integer.parseInt(t);
actCoeffsModel_InCommandLine = Math.min(jComboBoxModel.getItemCount()-1,
Math.max(0,actCoeffsModel_InCommandLine));
jComboBoxModel.setSelectedIndex(actCoeffsModel_InCommandLine);
if(dbg) {out.println("Activity coeffs. method = "+actCoeffsModel_InCommandLine);}
return true;
} //try
catch (NumberFormatException nfe) {
msg = "Wrong numeric format for activity coeff. model in \""+t+"\"";
actCoeffsModel_InCommandLine = actCoeffsModelDefault;
jComboBoxModel.setSelectedIndex(actCoeffsModelDefault);
break;
} //catch
}// = or :
} else if(arg0.startsWith("-n") || arg0.startsWith("/n")) {
if(arg.charAt(2) == '=' || arg.charAt(2) == ':') {
String t = arg.substring(3);
try{nSteps = Integer.parseInt(t);
nSteps = Math.min(NSTP_MAX, nSteps);
if(!dbg) {nSteps = Math.max(nSteps, NSTP_MIN);}
jScrollBarNbrPoints.setValue(nSteps);
if(dbg) {out.println("Nbr calc. steps in diagram = "+(nSteps)+" (nbr. points = "+(nSteps+1)+")");}
return true;
} catch (NumberFormatException nfe) {
msg = "Wrong numeric format for number of calculation steps in \""+t+"\"";
nSteps = NSTP_DEF;
jScrollBarNbrPoints.setValue(nSteps);
break;
}
}// = or :
} // if starts with "-n"
} // if length >3
if(arg.length() >4) {
String arg0 = arg.substring(0, 4).toLowerCase();
if(arg0.startsWith("-pr") || arg0.startsWith("/pr")) {
if(arg.charAt(4) == '=' || arg.charAt(4) == ':') {
String t = arg.substring(4);
try {pressure_InCommandLine = Double.parseDouble(t);
pressure_InCommandLine = Math.min(10000,Math.max(pressure_InCommandLine,1));
jLabelPressure.setText(String.valueOf(pressure_InCommandLine));
if(dbg) {out.println("Pressure = "+pressure_InCommandLine);}
return true;
} //try
catch (NumberFormatException nfe) {
msg = "Error: Wrong numeric format for pressure in text \""+t+"\"";
pressure_InCommandLine = Double.NaN;
break;
} //catch
}// = or :
} // if starts with "-tol"
} // if length >4
if(arg.length() >5) {
String arg0 = arg.substring(0, 5).toLowerCase();
if(arg0.startsWith("-tol") || arg0.startsWith("/tol")) {
if(arg.charAt(4) == '=' || arg.charAt(4) == ':') {
String t = arg.substring(5);
double w;
try {w = Double.parseDouble(t);
tolHalta = Math.min(1e-2,Math.max(w, 1e-9));
set_tol_inComboBox();
if(dbg) {out.println("Max tolerance in HaltaFall = "+tolHalta);}
return true;
} //try
catch (NumberFormatException nfe) {
msg = "Wrong numeric format for tolerance in \""+t+"\"";
tolHalta = Chem.TOL_HALTA_DEF;
set_tol_inComboBox();
break;
} //catch
}// = or :
} // if starts with "-tol"
if(arg0.startsWith("-thr") || arg0.startsWith("/thr")) {
if(arg.charAt(4) == '=' || arg.charAt(4) == ':') {
String t = arg.substring(5);
try {threshold = Float.parseFloat(t);
threshold = Math.min(0.1f,Math.max(threshold, 0.001f));
if(dbg) {out.println("Threshold for fraction diagrams = "+threshold);}
return true;
} //try
catch (NumberFormatException nfe) {
msg = "Wrong numeric format for fraction threshold in \""+t+"\"";
threshold =0.03f;
break;
} //catch
}// = or :
} // if starts with "-thr"
}
if(arg.length() >=6) {
String arg0 = arg.substring(0, 5).toLowerCase();
if(arg0.startsWith("-tble") || arg0.startsWith("/tble")) {
if(arg.charAt(5) == '=' || arg.charAt(5) == ':') {
String t = arg.substring(6);
if(t.length() <=0) {t = "";}
tblExtension = t;
tableOutput = true;
if(dbg) {out.println("Table output: file name extension = \""+t+"\"");}
return true;
}// = or :
} else if(arg0.startsWith("-tbls") || arg0.startsWith("/tbls")) {
if(arg.charAt(5) == '=' || arg.charAt(5) == ':') {
String t = arg.substring(6);
if(t.length() <=0) {t = " ";}
tblFieldSeparator = t;
if(tblFieldSeparator.equalsIgnoreCase("\\t"))
{tblFieldSeparator = "\u0009";}
tableOutput = true;
if(dbg) {out.println("Table output: field separator = \""+t+"\"");}
return true;
}// = or :
} // if starts with "-tbls"
}
if(arg.length() >=7) {
String arg0 = arg.substring(0, 6).toLowerCase();
if(arg0.startsWith("-tblcs") || arg0.startsWith("/tblcs")) {
if(arg.charAt(6) == '=' || arg.charAt(6) == ':') {
String t = arg.substring(7);
if(t.length() <=0) {t = "";}
tblCommentStart = t;
tableOutput = true;
if(dbg) {out.println("Table output: comment-line start = \""+t+"\"");}
return true;
}// = or :
} else if(arg0.startsWith("-tblce") || arg0.startsWith("/tblce")) {
if(arg.charAt(6) == '=' || arg.charAt(6) == ':') {
String t = arg.substring(7);
if(t.length() <=0) {t = "";}
tblCommentEnd = t;
tableOutput = true;
if(dbg) {out.println("Table output: comment-line end = \""+t+"\"");}
return true;
}// = or :
} // if starts with "-tbls"
}
if(arg.length() >6) {
String arg0 = arg.substring(0, 5).toLowerCase();
if(arg0.startsWith("-dbgh") || arg0.startsWith("/dbgh")) {
if(arg.charAt(5) == '=' || arg.charAt(5) == ':') {
String t = arg.substring(6);
try {dbgHalta = Integer.parseInt(t);
dbgHalta = Math.min(6, Math.max(dbgHalta, 0));
//set_dbgHalta_inRadioMenus();
if(dbg) {out.println("Debug printout level in HaltaFall = "+dbgHalta);}
return true;
} //try
catch (NumberFormatException nfe) {
msg = "Wrong numeric format for HaltaFall debug level \""+t+"\" (setting default:"+Chem.DBGHALTA_DEF+")";
dbgHalta = Chem.DBGHALTA_DEF;
//set_dbgHalta_inRadioMenus();
break;
} //catch
}// = or :
} // if starts with "-dbgh"
} //if length >6
if(arg.length() >7) {
String arg0 = arg.substring(0, 6).toLowerCase();
if(arg0.startsWith("-units") || arg0.startsWith("/units")) {
if(arg.charAt(6) == '=' || arg.charAt(6) == ':') {
String t = arg.substring(7);
try {conc_units = Integer.parseInt(t);
conc_units = Math.min(2, Math.max(conc_units, -1));
if(dbg) {out.println("Concentration units = "+conc_units+"(\""+cUnits[(conc_units+1)]+"\")");}
return true;
} //try
catch (NumberFormatException nfe) {
msg = "Wrong numeric format for concentration units \""+t+"\" (setting default: 0=\"molal\")";
conc_units = 0;
break;
} //catch
}// = or :
} // if starts with "-dbgh"
} //if length >7
if(arg.equalsIgnoreCase("-tbl") || arg.equalsIgnoreCase("/tbl")) {
tableOutput = true;
if(dbg) {out.println("Table output = true");}
return true;
} else if(arg.equalsIgnoreCase("-dbg") || arg.equalsIgnoreCase("/dbg")) {
dbg = true;
jCheckBoxMenuSEDdebug.setSelected(dbg);
out.println("Debug printout = true");
return true;
} else if(arg.equalsIgnoreCase("-rev") || arg.equalsIgnoreCase("/rev")) {
reversedConcs = true;
if(dbg) {out.println("Allow reversed ranges in axes");}
return true;
} else if(arg.equalsIgnoreCase("-keep") || arg.equalsIgnoreCase("/keep")) {
out = outPrintStream; // direct messages to tabbed pane
err = errPrintStream; // direct error messages to tabbed pane
doNotExit = true;
if(dbg) {out.println("Do not close window after calculations");}
return true;
} else if(arg.equalsIgnoreCase("-nostop") || arg.equalsIgnoreCase("/nostop")) {
doNotStop = true;
if(dbg) {out.println("Do not show message boxes");}
return true;
} else if(arg.equalsIgnoreCase("-sci") || arg.equalsIgnoreCase("/sci")) {
conc_nottn = 1;
if(dbg) {out.println("Display concentrations in scientific notation.");}
return true;
} else if(arg.equalsIgnoreCase("-eng") || arg.equalsIgnoreCase("/eng")) {
conc_nottn = 2;
if(dbg) {out.println("Display concentrations in engineerng notation.");}
return true;
}
break;
} //while
if(msg == null) {msg = "Error: can not understand command-line argument:"+nl+
" \""+arg+"\""+nl+"For a list of possible commands type: SED -?";}
else {msg = "Command-line argument \""+arg+"\":"+nl+msg;}
out.flush();
err.println(msg);
err.flush();
printInstructions(out);
if(!doNotStop) {
if(!this.isVisible()) {this.setVisible(true);}
javax.swing.JOptionPane.showMessageDialog(this,msg,progName,
javax.swing.JOptionPane.ERROR_MESSAGE);
}
if(this.isVisible()) {jTabbedPane.setSelectedComponent(jScrollPaneMessg);}
return false;
} // dispatchArg(arg)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="diverse Methods">
//<editor-fold defaultstate="collapsed" desc="showActivityCoefficientControls">
/** show/hide the activity coefficient controls in the window */
private void showActivityCoefficientControls(boolean show) {
if(show) {
jTextFieldIonicStgr.setEnabled(true);
jLabelIonicStr.setEnabled(true);
jLabelIonicStr.setText("<html>ionic <u>S</u>trength</html>");
jLabelIonicStrM.setEnabled(true);
jLabelModel.setEnabled(true);
jLabelModel.setText("<html>activity <u>C</u>officient model:<html>");
jComboBoxModel.setEnabled(true);
} else {
jLabelIonicStr.setEnabled(false);
jLabelIonicStr.setText("ionic Strength");
jLabelIonicStrM.setEnabled(false);
jTextFieldIonicStgr.setEnabled(false);
jLabelModel.setText("activity cofficient model:");
jLabelModel.setEnabled(false);
jComboBoxModel.setEnabled(false);
}
} //showActivityCoefficientControls(show)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="disable/restore Menus">
/** disable menus and buttons during calculations */
private void disableMenus() {
//if(this.isVisible()) {
jMenuFileOpen.setEnabled(false);
jMenuFileMakeD.setEnabled(false);
jMenuDebug.setEnabled(true);
jCheckBoxMenuSEDdebug.setEnabled(false);
jMenuSave.setEnabled(false);
jMenuHF_dbg.setEnabled(false);
jMenuCancel.setEnabled(true);
jTabbedPane.setSelectedComponent(jScrollPaneMessg);
jLabelData.setText("input data file:");
jLabelData.setEnabled(false);
jTextFieldDataFile.setEnabled(false);
jLabelPltFile.setText("plot file name:");
jLabelPltFile.setEnabled(false);
jTextFieldPltFile.setEnabled(false);
jLabelNbrPText.setText("Nbr of calc. steps:");
jLabelNbrPText.setEnabled(false);
jLabelPointsNbr.setEnabled(false);
jScrollBarNbrPoints.setEnabled(false);
jLabelHeight.setText("height of text in diagram:");
jLabelHeight.setEnabled(false);
jLabelHD.setEnabled(false);
jScrollBarHeight.setEnabled(false);
jCheckTable.setText("table Output");
jCheckTable.setEnabled(false);
jCheckActCoeff.setText("Activity coefficient calculations");
jCheckActCoeff.setEnabled(false);
showActivityCoefficientControls(false);
jLabelTol.setEnabled(false);
jComboBoxTol.setEnabled(false);
jCheckReverse.setText("allow Reversed min. and max. axes limits");
jCheckReverse.setEnabled(false);
jButtonDoIt.setText("make the Diagram");
jButtonDoIt.setEnabled(false);
//} //if visible
} //disableMenus()
/** enable menus and buttons after the calculations are finished
* and the diagram is displayed
* @param allowMakeDiagram if true then the button and menu to make diagrams are enabled,
* they are disabled otherwise */
private void restoreMenus(boolean allowMakeDiagram) {
//if(this.isVisible()) {
jMenuFileOpen.setEnabled(true);
if(allowMakeDiagram) {
jButtonDoIt.setText("<html>make the <u>D</u>iagram</html>");
} else {
jButtonDoIt.setText("make the Diagram");
}
jButtonDoIt.setEnabled(allowMakeDiagram);
jMenuFileMakeD.setEnabled(allowMakeDiagram);
jMenuDebug.setEnabled(true);
jCheckBoxMenuSEDdebug.setEnabled(true);
jMenuSave.setEnabled(true);
jMenuHF_dbg.setEnabled(true);
jMenuCancel.setEnabled(false);
jLabelData.setEnabled(true);
jTextFieldDataFile.setEnabled(true);
jLabelPltFile.setText("<html>p<u>l</u>ot file name:</html>");
jLabelPltFile.setEnabled(true);
jTextFieldPltFile.setEnabled(true);
jLabelNbrPText.setText("<html><u>N</u>br of calc. steps:</html>");
jLabelNbrPText.setEnabled(true);
jLabelPointsNbr.setEnabled(true);
jScrollBarNbrPoints.setEnabled(true);
jLabelHeight.setText("<html>h<u>e</u>ight of text in diagram:</html>");
jLabelHeight.setEnabled(true);
jLabelHD.setEnabled(true);
jScrollBarHeight.setEnabled(true);
jCheckTable.setText("<html>table <u>O</u>utput</html>");
jCheckTable.setEnabled(true);
jCheckActCoeff.setText("<html><u>A</u>ctivity coefficient calculations</html>");
jCheckActCoeff.setEnabled(true);
showActivityCoefficientControls(jCheckActCoeff.isSelected());
jLabelPltFile.setText("plot file name");
jLabelPltFile.setEnabled(false);
jTextFieldPltFile.setText(null);
jTextFieldPltFile.setEnabled(false);
//jTextFieldDataFile.setText("");
jLabelTol.setEnabled(true);
jComboBoxTol.setEnabled(true);
jCheckReverse.setText("<html>allow <u>R</u>eversed min. and max. axes limits</html>");
jCheckReverse.setEnabled(true);
jLabelStatus.setText("waiting...");
jLabelProgress.setText(" ");
//} //if visible
} //restoreMenus()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="readDataFile_hadError">
/** enable controls and disable diagram if an error is found when
* reading the input file */
private void readDataFile_hadError() {
out.println("--- Error(s) reading the input file ---");
if(this.isVisible()) {
jTabbedPane.setTitleAt(2, "Diagram");
jTabbedPane.setEnabledAt(2, false); //disable the diagram
restoreMenus(false);
jTabbedPane.setSelectedComponent(jScrollPaneMessg);
}
} // readDataFile_hadError()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="set_tol_inComboBox">
/** find the closest item in the tolerances combo box and select it */
private void set_tol_inComboBox() {
double w0, w1;
int listItem =0;
int listCount = jComboBoxTol.getItemCount();
for(int i =1; i < listCount; i++) {
w0 = Double.parseDouble(jComboBoxTol.getItemAt(i-1).toString());
w1 = Double.parseDouble(jComboBoxTol.getItemAt(i).toString());
if(tolHalta >= w0 && i==1) {listItem = 0; break;}
if(tolHalta <= w1 && i==(listCount-1)) {listItem = (listCount-1); break;}
if(tolHalta < w0 && tolHalta >=w1) {
if(Math.abs(tolHalta-w0) < Math.abs(tolHalta-w1)) {
listItem = i-1;
} else {
listItem = i;
}
break;
}
} //for i
jComboBoxTol.setSelectedIndex(listItem);
} //set_tol_inComboBox()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="end_program">
private void end_program() {
if(dbg) {out.println("--- end_program()");}
if(!finishedCalculations && !quitConfirm(this)) {return;}
programEnded = true;
this.notify_All();
this.dispose();
if(helpAboutFrame != null) {
helpAboutFrame.closeWindow();
helpAboutFrame = null;
}
} // end_program()
//</editor-fold>
private synchronized void notify_All() {this.notifyAll();}
private synchronized void synchWaitCalcs() {
while(!finishedCalculations) {
try {wait();} catch(InterruptedException ex) {}
}
}
private synchronized void synchWaitProgramEnded() {
while(!programEnded) {
try {wait();} catch(InterruptedException ex) {}
}
}
//<editor-fold defaultstate="collapsed" desc="isCharOKforNumberInput">
/** @param key a character
* @return true if the character is ok, that is, it is either a number,
* or a dot, or a minus sign, or an "E" (such as in "2.5e-6") */
private boolean isCharOKforNumberInput(char key) {
return Character.isDigit(key)
|| key == '-' || key == '+' || key == '.' || key == 'E' || key == 'e';
} // isCharOKforNumberInput(char)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="quitConfirm">
private boolean quitConfirm(javax.swing.JFrame c) {
boolean q = true;
if(!doNotStop) {
Object[] options = {"Cancel", "STOP"};
int n = javax.swing.JOptionPane.showOptionDialog (c,
"Do you really want to stop the calculations?",
progName, javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.ERROR_MESSAGE, null, options, null);
q = n == javax.swing.JOptionPane.NO_OPTION;
} //not "do not stop":
if(q) {
if(h != null) {h.haltaCancel();}
if(tsk != null) {tsk.cancel(true);}
finishedCalculations = true;
this.notify_All();
}
return q;
} // quitConfirm(JFrame)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="showTheInputFileName">
/** Show the input data file name in the JFrame (window) */
private void showTheInputFileName(java.io.File dataFile) {
jTextFieldDataFile.setText(dataFile.getAbsolutePath());
jLabelPltFile.setEnabled(true);
jLabelPltFile.setText("<html>p<u>l</u>ot file name:</html>");
jTextFieldPltFile.setEnabled(true);
jMenuFileMakeD.setEnabled(true);
jButtonDoIt.setEnabled(true);
jButtonDoIt.setText("<html>make the <u>D</u>iagram</html>");
jButtonDoIt.requestFocusInWindow();
} // showTheInputFileName()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="setPathDef">
/** Sets the variable "pathDef" to the path of a file.
* Note that "pathDef" may end with the file separator character, e.g. "D:\"
* @param f File */
private void setPathDef(java.io.File f) {
if(pathDef == null) {pathDef = new StringBuffer();}
java.net.URI uri;
if(f != null) {
if(!f.getAbsolutePath().contains(SLASH)) {
// it is a bare file name, without a path
if(pathDef.length()>0) {return;}
}
try{uri = f.toURI();}
catch (Exception ex) {uri = null;}
} else {uri = null;}
if(pathDef.length()>0) {pathDef.delete(0, pathDef.length());}
if(uri != null) {
if(f != null && f.isDirectory()) {
pathDef.append((new java.io.File(uri.getPath())).toString());
} else {
pathDef.append((new java.io.File(uri.getPath())).getParent().toString());
} //directory?
} else { //uri = null: set Default Path = Start Directory
java.io.File currDir = new java.io.File("");
try {pathDef.append(currDir.getCanonicalPath());}
catch (java.io.IOException e) {
try{pathDef.append(System.getProperty("user.dir"));}
catch (Exception e1) {pathDef.append(".");}
}
} //uri = null
} // setPathDef(File)
/** Set the variable "pathDef" to the path of a file name.
* Note that "pathDef" may end with the file separator character, e.g. "D:\"
* @param fName String with the file name */
private void setPathDef(String fName) {
java.io.File f = new java.io.File(fName);
setPathDef(f);
}
/** Set the variable "pathDef" to the user directory ("user.home", system dependent) */
private void setPathDef() {
String t = System.getProperty("user.home");
setPathDef(t);
}
// </editor-fold>
/*
static void pause() {
// Defines the standard input stream
java.io.BufferedReader stdin =
new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
System.out.print ("Press Enter");
System.out.flush();
try{String txt = stdin.readLine();}
catch (java.io.IOException ex) {System.err.println(ex.toString());}
}
*/
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="millisToShortDHMS">
/** converts time (in milliseconds) to human-readable format "<dd>hh:mm:ss"
* @param duration (in milliseconds)
* @return */
public static String millisToShortDHMS(long duration) {
//adapted from http://www.rgagnon.com
String res;
int millis = (int)(duration % 1000);
duration /= 1000;
int seconds = (int) (duration % 60);
duration /= 60;
int minutes = (int) (duration % 60);
duration /= 60;
int hours = (int) (duration % 24);
int days = (int) (duration / 24);
if (days == 0) {
res = String.format("%02d:%02d:%02d.%03d", hours, minutes, seconds,millis);
} else {
res = String.format("%dd%02d:%02d:%02d", days, hours, minutes, seconds);
}
return res;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="setCursor">
private void setCursorWait() {
this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
jTextAreaA.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
}
private void setCursorDef() {
this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jTextAreaA.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="FilteredStreams">
private class errFilteredStreamSED extends java.io.FilterOutputStream {
public errFilteredStreamSED(java.io.OutputStream aStream) {
super(aStream);
} // constructor
@Override
public void write(byte b[]) throws java.io.IOException {
String aString = new String(b);
jTabbedPane.setTitleAt(1, "<html><u>M</u>essages</html>");
jTabbedPane.setEnabledAt(1, true);
jTabbedPane.setSelectedComponent(jScrollPaneMessg);
jTextAreaA.append(aString);
jTextAreaA.setSelectionStart(Integer.MAX_VALUE);
}
@Override
public void write(byte b[], int off, int len) throws java.io.IOException {
String aString = new String(b , off , len);
jTabbedPane.setTitleAt(1, "<html><u>M</u>essages</html>");
jTabbedPane.setEnabledAt(1, true);
jTabbedPane.setSelectedComponent(jScrollPaneMessg);
jTextAreaA.append(aString);
jTextAreaA.setSelectionStart(Integer.MAX_VALUE);
} // write
} // class errFilteredStreamSED
/** redirect output */
private class outFilteredStreamSED extends java.io.FilterOutputStream {
public outFilteredStreamSED(java.io.OutputStream aStream) {
super(aStream);
} // constructor
@Override
public void write(byte b[]) throws java.io.IOException {
String aString = new String(b);
jTabbedPane.setTitleAt(1, "<html><u>M</u>essages</html>");
jTabbedPane.setEnabledAt(1, true);
jTextAreaA.append(aString);
jTextAreaA.setSelectionStart(Integer.MAX_VALUE);
}
@Override
public void write(byte b[], int off, int len) throws java.io.IOException {
String aString = new String(b , off , len);
jTabbedPane.setTitleAt(1, "<html><u>M</u>essages</html>");
jTabbedPane.setEnabledAt(1, true);
jTextAreaA.append(aString);
jTextAreaA.setSelectionStart(Integer.MAX_VALUE);
} // write
} // class outFilteredStreamSED
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="getTheInputFileName">
/** Get an input data file name from the user
* using an Open File dialog */
private void getTheInputFileName() {
jTextFieldDataFile.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
setCursorWait();
if(pathDef == null) {setPathDef();}
fc.setMultiSelectionEnabled(false);
fc.setCurrentDirectory(new java.io.File(pathDef.toString()));
fc.setDialogTitle("Select a data file:");
fc.setFileSelectionMode(javax.swing.JFileChooser.FILES_ONLY);
fc.setAcceptAllFileFilterUsed(true);
javax.swing.LookAndFeel defLaF = javax.swing.UIManager.getLookAndFeel();
try {javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());}
catch (Exception ex) {}
fc.updateUI();
jTextFieldDataFile.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
setCursorDef();
fc.setFileFilter(filterDat);
int returnVal = fc.showOpenDialog(this);
// reset the look and feel
try {javax.swing.UIManager.setLookAndFeel(defLaF);}
catch (javax.swing.UnsupportedLookAndFeelException ex) {}
Util.configureOptionPane();
if(returnVal == javax.swing.JFileChooser.APPROVE_OPTION) {
if(eraseTextArea) {
jTextAreaA.selectAll();
jTextAreaA.replaceRange("", 0, jTextAreaA.getSelectionEnd());
}
inputDataFile = fc.getSelectedFile();
setPathDef(fc.getCurrentDirectory());
if(readDataFile(inputDataFile)) {
showTheInputFileName(inputDataFile);
outputPltFile = null;
String txt = inputDataFile.getName();
String plotFileN = txt.substring(0,txt.length()-3).concat("plt");
jTextFieldPltFile.setText(plotFileN);
jTabbedPane.setSelectedComponent(jPanelParameters);
jTabbedPane.setTitleAt(2, "Diagram");
jTabbedPane.setEnabledAt(2, false);
jMenuFileOpen.setEnabled(true);
jMenuFileMakeD.setEnabled(true);
jButtonDoIt.setEnabled(true);
jButtonDoIt.setText("<html>make the <u>D</u>iagram</html>");
jButtonDoIt.requestFocusInWindow();
} // if readDataFile
else {return;}
} // if returnVal = JFileChooser.APPROVE_OPTION
jTabbedPane.setSelectedComponent(jPanelParameters);
jTabbedPane.requestFocusInWindow();
jButtonDoIt.requestFocusInWindow();
jCheckReverse.setText("allow Reversed min. and max. axes limits");
jCheckReverse.setEnabled(false);
} // getTheInputFileName()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="paintDiagrPanel">
/** used when constructing the jPanelDiagram:
* <pre>jPanelDiagram = new javax.swing.JPanel() {@Override
* public void paint(java.awt.Graphics g)
* {
* super.paint(g);
* paintDiagrPanel(g);
* }
* };</pre>
*/
private void paintDiagrPanel(java.awt.Graphics g) {
java.awt.Graphics2D g2D = (java.awt.Graphics2D)g;
if(dd != null) {
diagrPaintUtil.paintDiagram(g2D, jPanelDiagram.getSize(), dd, false);
}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="printInstructions">
private static void printInstructions(java.io.PrintStream out) {
if(out == null) {out = System.out;}
out.flush();
out.println("Possible commands are:"+nl+
" -d=data-file-name (input file name)"+nl+
" -dbg (output debug information)"+nl+
" -dbgH=n (level for debug output from HaltaFall"+nl+
" in the first calculation point; default ="+Chem.DBGHALTA_DEF+")"+nl+
" -eng (display concentrations in engineering notation)"+nl+
" -h=nbr (height factor for labels in the plot)"+nl+
" -i=nbr (ionic strength (the equil. constants are"+nl+
" assumed for I=0). Requires a temperature."+nl+
" Enter \"-i=-1\" to calculate I at each point)"+nl+
" -keep (window open to see the diagram after the calculations)"+nl+
" -m=nbr (model to calculate activity coefficients:"+nl+
" 0 = Davies eqn; 1 = SIT; 2 = simplified HKF; default =2)"+nl+
" -n=nbr (calculation steps along the X-axis; "+(NSTP_MIN)+" to "+(NSTP_MAX)+")"+nl+
" -nostop (do not stop for warnings)"+nl+
" -p=output-plot-file-name"+nl+
" -pr=nbr (pressure in bar; displayed in the diagram)"+nl+
" -rev (do not reverse the input min. and max. limits in x-axis)"+nl+
" -sci (display concentrations in scientific notation)"+nl+
" -t=nbr (temperature in degrees C, ignored if not needed)"+nl+
" -tbl (output both a diagram and a table file with comma-"+nl+
" separated values and extension \"csv\")"+nl+
" -tbls=; (character(s) to separate fields in the output table file;"+nl+
" for example comma(,) semicolon(;) or tab (\\t))"+nl+
" -tble=csv (name extension for output table file)"+nl+
" -tblcs=\" (character(s) to insert at the start of comment lines)"+nl+
" -tblce=\" (character(s) to append to the end of comment lines)"+nl+
" -tol=nbr (tolerance when solving mass-balance equations in Haltafall,"+nl+
" 0.01 >= nbr >= 1e-9; default ="+Chem.TOL_HALTA_DEF+")"+nl+
" -thr=nbr (threshold to display curves in a fraction diagram,"+nl+
" 0.001 to 0.1 (equivalent to 0.1 ro 10%); ignored if not needed)"+nl+
" -units=nbr (concentration units displayed in the diagram: 0=\"molal\","+nl+
" 1=\"mol/kg_w\", 2=\"M\", -1=\"\")"+nl+
"Enclose file names with double quotes (\"\") it they contain blank space."+nl+
"Example: java -jar SED.jar \"/d=Fe 25\" -t:25 -i=-1 \"-p:plt\\Fe 25\" -n=200");
} //printInstructions(out)
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="readDataFile">
private boolean readDataFile(java.io.File dataFile) {
if(dbg) {out.println("--- readDataFile("+dataFile.getAbsolutePath()+")");}
String msg;
//--- check the name
if(!dataFile.getName().toLowerCase().endsWith(".dat")) {
msg = "File: \""+dataFile.getName()+"\""+nl+
"Error: data file name must end with \".dat\"";
showErrMsgBx(msg,1);
return false;
}
if(dataFile.getName().length() <= 4) {
msg = "File: \""+dataFile.getName()+"\""+nl+
"Error: file name must have at least one character";
showErrMsgBx(msg,1);
return false;
}
String dataFileN = null;
try {dataFileN = dataFile.getCanonicalPath();} catch (java.io.IOException ex) {}
if(dataFileN == null) {
try {dataFileN = dataFile.getAbsolutePath();}
catch (Exception ex) {dataFileN = dataFile.getPath();}
}
dataFile = new java.io.File(dataFileN);
//
//--- create a ReadDataLib instance
try {rd = new ReadDataLib(dataFile);}
catch (ReadDataLib.DataFileException ex) {
showErrMsgBx(ex.getMessage(),1);
if(rd != null) {
try{rd.close();}
catch (ReadDataLib.ReadDataLibException ex2) {showErrMsgBx(ex2);}
}
return false;
}
msg = LINE+nl+"Reading input data file \""+dataFile+"\"";
out.println(msg);
if(consoleOutput) {System.out.println(msg);}
//--- read the chemical system (names, equilibrium constants, stoichiometry)
boolean warn = false; // throw an exception for missing plot data
try {ch = null;
ch = ReadChemSyst.readChemSystAndPlotInfo(rd, dbg, warn, out);
} catch (ReadChemSyst.ConcDataException ex) {
ch = null; showErrMsgBx(ex.getMessage(), 1);
}
catch (ReadChemSyst.DataLimitsException ex) {
ch = null; showErrMsgBx(ex.getMessage(), 1);
}
catch (ReadChemSyst.PlotDataException ex) {
ch = null; showErrMsgBx(ex.getMessage(), 1);
}
catch (ReadChemSyst.ReadDataFileException ex) {
ch = null; showErrMsgBx(ex.getMessage(), 1);
}
if(ch == null) {
msg = "Error while reading data file \""+dataFile.getName()+"\"";
showMsg(msg,1);
try {rd.close();}
catch (ReadDataLib.ReadDataLibException ex) {showMsg(ex);}
readDataFile_hadError();
return false;
}
if(ch.diag.plotType <= 0 || ch.diag.plotType > 8) {
msg = "Error: data file \""+dataFile.getName()+"\""+nl;
if(ch.diag.plotType == 0) {msg = msg +
"contains information for a Predominance Area Diagram."+nl+
"Run program PREDOM instead.";}
else {msg = msg + "contains erroneous plot information.";}
showErrMsgBx(msg,1);
try {rd.close();}
catch (ReadDataLib.ReadDataLibException ex) {showMsg(ex);}
readDataFile_hadError();
return false;}
//
//--- get a temperature:
double t_d, w;
try {w = rd.getTemperature();} // temperature written as a comment in the data file?
catch (ReadDataLib.DataReadException ex) {showErrMsgBx(ex); w = Double.NaN;}
if(!Double.isNaN(w)) {
t_d = w;
if(!Double.isNaN(temperature_InCommandLine)) {
// temperature also given in command line
if(Math.abs(t_d - temperature_InCommandLine)>0.001) { // difference?
msg = String.format(engl,"Warning: temperature in data file =%6.2f,%s",t_d,nl);
msg = msg + String.format(engl,
" but in the command line t=%6.2f!%s",
temperature_InCommandLine,nl);
msg = msg + String.format(engl,"t=%6.2f will be used.",temperature_InCommandLine);
showErrMsgBx(msg,2);
t_d = temperature_InCommandLine;
} // temperatures differ
} // temperature also given in command line
} // temperature written in data file
else {t_d = 25.;}
jLabelTemperature.setText(String.valueOf(t_d));
//--- get a pressure:
double p_d;
try {w = rd.getPressure();} // pressure written as a comment in the data file?
catch (ReadDataLib.DataReadException ex) {showErrMsgBx(ex); w = Double.NaN;}
if(!Double.isNaN(w)) {
p_d = w;
if(!Double.isNaN(pressure_InCommandLine)) {
// pressure also given in command line
if(Math.abs(p_d - pressure_InCommandLine)>0.001) { // difference?
msg = String.format(engl,"Warning: pressure in data file =%.3f bar,%s",p_d,nl);
msg = msg + String.format(engl,
" but in the command line p=%.3f bar!%s",
pressure_InCommandLine,nl);
msg = msg + String.format(engl,"p=%.3f will be used.",pressure_InCommandLine);
showErrMsgBx(msg,2);
p_d = pressure_InCommandLine;
} // pressures differ
} // pressure also given in command line
} // pressure written in data file
else {p_d = 1.;}
jLabelPressure.setText(String.valueOf(p_d));
try {rd.close();}
catch (ReadDataLib.ReadDataLibException ex) {showMsg(ex);}
msg = "Finished reading the input data file.";
out.println(msg);
if(consoleOutput) {System.out.println(msg);}
//--- set the references pointing to the instances of the storage classes
cs = ch.chemSystem;
csC = cs.chemConcs;
namn = cs.namn;
dgrC = ch.diagrConcs;
diag = ch.diag;
//---- Set the calculation instructions for HaltaFall
// Concentration types for each component:
// hur =1 for "T" (fixed Total conc.)
// hur =2 for "TV" (Tot. conc. Varied)
// hur =3 for "LTV" (Log(Tot.conc.) Varied)
// hur =4 for "LA" (fixed Log(Activity) value)
// hur =5 for "LAV" (Log(Activity) Varied)</pre>
for(int j =0; j < cs.Na; j++) {
if(dgrC.hur[j] >3)
{csC.kh[j]=2;} //kh=2 log(activity) is given
//The Mass Balance eqn. has to be solved
else {csC.kh[j]=1;} //kh=1 Tot.Conc. is given
//The Tot.Conc. will be calculated
}
// --------------------------
// --- Check concs. etc ---
// --------------------------
if(!checkInput()) {
ch = null; cs = null; csC = null; namn = null; dgrC = null; diag = null;
readDataFile_hadError();
return false;}
if(cs.jWater >=0 && dbg) {
out.println("Water (H2O) is included. All concentrations are in \"mol/(kg H2O)\".");
}
return true;
} //readDataFile()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Temperature & Ionic Strength">
private void validateIonicStrength() {
if(jTextFieldIonicStgr.getText().length() <=0) {return;}
try{
ionicStrength = readIonStrength();
ionicStrength = Math.min(1000,Math.max(ionicStrength, -1000));
if(ionicStrength < 0) {ionicStrength = -1;}
jTextFieldIonicStgr.setText(String.valueOf(ionicStrength));
} //try
catch (NumberFormatException nfe) {
String msg = "Wrong numeric format"+nl+nl+"Please enter a floating point number.";
showErrMsgBx(msg,1);
jTextFieldIonicStgr.setText(String.valueOf(ionicStrength));
jTextFieldIonicStgr.requestFocusInWindow();
} //catch
} // validateIonicStrength()
/** Reads the value in <code>jTextFieldIonicStgr</code>.
* Check that it is within -1 to 1000
* @return the ionic strength */
private double readIonStrength() {
if(jTextFieldIonicStgr.getText().length() <=0) {return 0;}
double w;
try{w = Double.parseDouble(jTextFieldIonicStgr.getText());
w = Math.min(1000,Math.max(w, -1));
if(w < 0) {w = -1;}
} //try
catch (NumberFormatException nfe) {
out.println("Error reading Ionic Strength:"+nl+" "+nfe.toString());
w = 0;
} //catch
return w;
} //readIonStrength()
/** Reads the value in <code>jLabelTemperature</code>.
* Checks that it is within -50 to 1000 Celsius. It returns 25
* if there is no temperature to read.
* @return the temperature in Celsius */
private double readTemperature() {
if(jLabelTemperature.getText().length() <=0) {return 25.;}
double w;
try{w = Double.parseDouble(jLabelTemperature.getText());
w = Math.min(1000,Math.max(w, -50));
} //try
catch (NumberFormatException nfe) {
if(!jLabelTemperature.getText().equals("NaN")) {
out.println("Error reading Temperature:"+nl+" "+nfe.toString());
}
w = 25.;
} //catch
return w;
} //readTemperature()
/** Reads the value in <code>jLabelPressure</code>.
* Checks that it is within 1 to 10000 bar. It returns 1 (one bar)
* if there is no pressure to read.
* @return the pressure in bar */
private double readPressure() {
if(jLabelPressure.getText().length() <=0) {return 1.;}
double w;
try{w = Double.parseDouble(jLabelPressure.getText());
w = Math.min(10000.,Math.max(w, 1.));
} //try
catch (NumberFormatException nfe) {
if(!jLabelPressure.getText().equals("NaN")) {
out.println("Error reading Pressure:"+nl+" "+nfe.toString());
}
w = 1.;
} //catch
return w;
} //readPressure()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="showErrMsgBx">
/** Outputs a message (through a call to <code>showMsg(msg,type)</code>
* and shows it in a [OK, Cancel] message box (if doNotStop = false)
* @param msg the message
* @param type =1 exception error; =2 warning; =3 information
* @return it return <code>true</code> if the user chooses "OK", returns <code>false</code> otherwise
* @see #showMsg(java.lang.String, int) showMsg */
boolean showErrMsgBxCancel(String msg, int type) {
if(msg == null || msg.trim().length() <=0) {return true;}
//if(type == 1) {type = 0;}
showMsg(msg,type);
if(!doNotStop && sedFrame != null) {
int j;
if(type<=1) {j=javax.swing.JOptionPane.ERROR_MESSAGE;}
else if(type==2) {j=javax.swing.JOptionPane.INFORMATION_MESSAGE;}
else {j=javax.swing.JOptionPane.WARNING_MESSAGE;}
if(!sedFrame.isVisible()) {sedFrame.setVisible(true);}
Object[] opt = {"OK", "Cancel"};
int n= javax.swing.JOptionPane.showOptionDialog(sedFrame,msg,
progName,javax.swing.JOptionPane.OK_CANCEL_OPTION,j, null, opt, opt[0]);
if(n != javax.swing.JOptionPane.OK_OPTION) {return false;}
}
return true;
}
/** Outputs a message (through a call to <code>showMsg(msg,0)</code> if type=1,
* or to <code>showMsg(msg,type)</code> if type is =2 or 3),
* and shows it in a message box (if doNotStop = false)
* @param msg the message
* @param type =1 exception error; =2 warning; =3 information
* @see #showMsg(java.lang.String, int) showMsg
*/
void showErrMsgBx(String msg, int type) {
if(msg == null || msg.trim().length() <=0) {return;}
//if(type == 1) {type = 0;}
showMsg(msg,type);
if(!doNotStop) {
if(sedFrame == null) {
ErrMsgBox mb = new ErrMsgBox(msg, progName);
} else {
int j;
if(type<=1) {j=javax.swing.JOptionPane.ERROR_MESSAGE;}
else if(type==2) {j=javax.swing.JOptionPane.INFORMATION_MESSAGE;}
else {j=javax.swing.JOptionPane.WARNING_MESSAGE;}
if(!this.isVisible()) {this.setVisible(true);}
javax.swing.JOptionPane.showMessageDialog(this, msg, progName,j);
}
}
}
/** Outputs the exception message and the stack trace,
* through a call to <code>showMsg(ex)</code>,
* and shows a message box (if doNotStop = false)
* @param ex the exception
* @see #showMsg(java.lang.Exception) showMsg */
void showErrMsgBx(Exception ex) {
if(ex == null) {return;}
showMsg(ex);
String msg = ex.getMessage();
if(!doNotStop) {
if(sedFrame == null) {
ErrMsgBox mb = new ErrMsgBox(msg, progName);
} else {
int j = javax.swing.JOptionPane.ERROR_MESSAGE;
if(!this.isVisible()) {this.setVisible(true);}
javax.swing.JOptionPane.showMessageDialog(this, msg, progName,j);
}
}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="showMsg">
/** Outputs a message either to System.out (if type is 1, 2 or 3) or
* to System.err otherwise (type=0).
* @param msg the message
* @param type =0 error (outputs message to System.err); =1 error; =2 warning; =3 information
* @see #showErrMsgBx(java.lang.String, int) showErrMsgBx */
void showMsg(String msg, int type) {
if(msg == null || msg.trim().length() <=0) {return;}
final String flag;
if(type == 2) {flag = "Warning";} else if(type == 3) {flag = "Message";} else {flag = "Error";}
if(type == 1 || type == 2 || type == 3) {
out.println("- - - - "+flag+":"+nl+msg+nl+"- - - -");
System.out.println("- - - - "+flag+":"+nl+msg+nl+"- - - -");
out.flush(); System.out.flush();
} else {
err.println("- - - - "+flag+":"+nl+msg+nl+"- - - -");
System.err.println("- - - - "+flag+":"+nl+msg+nl+"- - - -");
err.flush(); System.err.flush();
}
}
/** Outputs the exception message and the stack trace to System.err and to err
* @param ex the exception
* @see #showErrMsgBx(java.lang.Exception) showErrMsgBx */
void showMsg(Exception ex) {
if(ex == null) {return;}
String msg = "- - - - Error:"+nl+ex.getMessage()+nl+nl+Util.stack2string(ex)+nl+"- - - -";
err.println(msg);
System.err.println(msg);
err.flush();
System.err.flush();
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="doCalculations">
private void doCalculations() {
setCursorWait();
if(dbg) {out.println("--- doCalculations()");}
jLabelStatus.setText("Starting the calculations");
jLabelProgress.setText(" ");
disableMenus();
diag.fractionThreshold = threshold;
//---- Check if "EH" is needed -----------
if(diag.Eh &&
diag.pInX != 3 && diag.plotType != 5) { //plotType=5: pe in Y-axis
boolean peGiven = false;
for(int i =0; i < cs.Na; i++) {
if(Util.isElectron(namn.identC[i]) &&
csC.kh[i] ==2) { // kh=2 logA given
peGiven = true; break;}
} //for i
if(!peGiven) {diag.Eh = false;}
}
//--- temperature & pressure ------------------------
diag.temperature = readTemperature();
diag.pressure = readPressure();
if(Double.isNaN(diag.temperature)){
String msg = "";
if(diag.Eh) {msg = "\"Error: Need to plot Eh values but no temperature is given.";}
else if(calcActCoeffs) {msg = "\"Error: activity coefficient calculations required but no temperature is given.";}
if(!msg.isEmpty()) {
showErrMsgBx(msg,1);
setCursorDef();
restoreMenus(true);
return;
}
}
// decide if the temperature should be displayed in the diagram
if(!diag.Eh && !calcActCoeffs) {
if(dbg) {out.println(" (Note: temperature not needed in the diagram)");}
} else {
double pSat;
try {pSat= lib.kemi.H2O.IAPWSF95.pSat(diag.temperature);}
catch (Exception ex) {
out.println("\"IAPWSF95.pSat\": "+ex.getMessage());
out.println("Calculations cancelled.");
restoreMenus(false);
setCursorDef();
return;
}
if(Double.isNaN(diag.pressure)){diag.pressure = 1.;}
if(diag.temperature <= 99.61) {
if(diag.pressure < 1.) {
out.println("tC = "+diag.temperature+", pBar = "+diag.pressure+", setting pBar = 1.");
}
diag.pressure = Math.max(1.,diag.pressure);
}
// if pressure = 1 bar and temperature = 0, set temperature to 0.01 C (tripple point of water)
if(diag.pressure >0.99999 && diag.pressure < 1.00001 && Math.abs(diag.temperature) < 0.001) {diag.temperature = 0.01;}
if(diag.temperature <= 373.95) { // below critical point
if(diag.pressure < (pSat*0.999)) {
out.println("tC = "+diag.temperature+", pBar = "+diag.pressure+", setting pBar = "+(float)pSat);
diag.pressure = pSat;
}
}
}
if(diag.Eh) {peEh = (ln10*8.3144126d*(diag.temperature+273.15d)/96484.56d);} else {peEh = Double.NaN;}
// nbr of calculation steps
if(!dbg) {
nSteps = Math.max(NSTP_MIN,nSteps);
nSteps = jScrollBarNbrPoints.getValue();
}
final int nSteps1 = nSteps + 1;
jLabelNbrPText.setText("Nbr of calc. steps:");
jScrollBarNbrPoints.setEnabled(false);
jLabelNbrPText.setEnabled(false);
if(dbg) {out.println(" "+nSteps1+" caculation points"+nl+
"ionic strength = "+ionicStrength+nl+
"temperature = "+(float)diag.temperature+", pressure = "+(float)diag.pressure+nl+
"max relative mass-balance tolerance = "+(float)tolHalta);}
// ---------------------------------------
// get an instance of Plot
plot = new Plot(this, err, out);
//---- set up some arrays
plot.preparePlot(ch);
// ---------------------------------------
String msg;
// ionic strength
diag.ionicStrength = ionicStrength;
if(!diag.aquSystem && diag.ionicStrength != 0) {
msg = "Warning: This does not appear to be an aqueous system,"+nl+
"and yet you give a value for the ionic strength?";
showErrMsgBx(msg,2);
}
// model to calculate ion activity coefficients
if(calcActCoeffs) {
diag.activityCoeffsModel = jComboBoxModel.getSelectedIndex();
diag.activityCoeffsModel = Math.min(jComboBoxModel.getItemCount()-1,
Math.max(0,diag.activityCoeffsModel));
csC.actCoefCalc = true;
} else {
diag.activityCoeffsModel = -1;
csC.actCoefCalc = false;
}
// height scale for texts in the diagram
tHeight = jScrollBarHeight.getValue()/10;
tHeight = Math.min(10.d,Math.max(tHeight, 0.3));
int j;
// ---- Store given conc. ranges in array bt[Na][nSteps+1]
bt = new double[cs.Na][nSteps1];
for(j =0; j < cs.Na; j++) {
if(dgrC.hur[j] ==1 || dgrC.hur[j] ==4) { //T or LA
for(int n =0; n < bt[0].length; n++) {bt[j][n] = dgrC.cLow[j];}
} //if T or LA
else { //if TV, LTV or LAV
double stepX =(dgrC.cHigh[j] - dgrC.cLow[j]) / nSteps;
bt[j][0] = dgrC.cLow[j];
for(int n =1; n < (bt[0].length-1); n++) {bt[j][n] = bt[j][n-1] + stepX;}
bt[j][nSteps] = dgrC.cHigh[j]; // to avoid rounding errors
if(dgrC.hur[j] ==3) { // LTV
for(int n =0; n < bt[0].length; n++)
{bt[j][n] = Math.exp(ln10*bt[j][n]);}
} //if LTV
} //if TV, LTV or LAV
} //for j
// check POS and NEG with the Tot.Conc. given in the input
for(j =0; j < cs.Na; j++) {
if(csC.kh[j] == 2) {continue;} //only it Tot.conc. is given
if(!(pos[j] && neg[j]) && (pos[j] || neg[j])) {
if(dgrC.hur[j] !=3 && //not LTV
dgrC.cLow[j]==0 && (Double.isNaN(dgrC.cHigh[j]) || dgrC.cHigh[j]==0)) {
//it is only POS or NEG and Tot.Conc =0
for(int n =0; n < bt[0].length; n++) {bt[j][n] = -9999.;}
csC.kh[j] =2; //kh=2 means logA given
if(dbg) {out.println("Can not calculate mass-balance for for component \""+namn.identC[j]+"\""+nl+
" its log(activity) will be set to -9999.");}
}
}
} //for j
calculationStart = System.nanoTime();
msg = "Starting the calculations...";
out.println(msg);
if(consoleOutput) {System.out.println(msg);}
// ---- Make an instance of Factor
String userHome = System.getProperty("user.home");
try{factor = new Factor(ch, pathApp, userHome, pathDef.toString(), out);}
catch (Exception ex) {showErrMsgBx(ex.getMessage(),1); calcActCoeffs = false; diag.ionicStrength = Double.NaN;}
out.flush();
// ---- print information on the model used for activity coefficients
if(factor != null) {
try {factor.factorPrint(dbg);}
catch (Exception ex) {showErrMsgBx(ex.getMessage(),1); calcActCoeffs = false; diag.ionicStrength = Double.NaN;}
}
if(factor == null) {
out.println("Calculations cancelled.");
restoreMenus(false);
setCursorDef();
return;
}
// ---- table output?
if(inputDataFile == null) {tableOutput = false;}
if(tableOutput) {
table = new Table(this, err, out);
String txt = inputDataFile.getAbsolutePath();
if(tblExtension == null) {tblExtension = "";}
if(tblExtension.startsWith(".")) {tblExtension = tblExtension.substring(1);}
String tableFileN = txt.substring(0,txt.length()-4).concat(".").concat(tblExtension);
java.io.File outputTableFile = new java.io.File(tableFileN);
if(!table.tableHeader(ch, outputTableFile)) {
table = null;
tableOutput = false;
}
}
// ---- Initialize variables
csC.dbg = dbgHalta;
csC.cont = false;
csC.tol = tolHalta;
for(j =0; j < cs.Na; j++) {
if(csC.kh[j] == 1) {
csC.tot[j]=bt[j][0];
csC.logA[j]=-10;
if(csC.tot[j]>0) {csC.logA[j] = Math.log10(csC.tot[j]) -3;}
}
else {csC.logA[j]=bt[j][0];}
} // for j
// ---- Run the calculations on another Thread ----
jLabelStatus.setText("Please wait --");
finishedCalculations = false;
tsk = new HaltaTask();
tsk.execute();
} //doCalculations()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="private class HaltaTask">
/** A SwingWorker to perform tasks in the background.
* @see HaltaTask#doInBackground() doInBackground() */
public class HaltaTask extends javax.swing.SwingWorker<Boolean, Integer> {
private boolean getHaltaInstanceOK = true;
private boolean haltaError = false;
private int nbrTooLargeConcs = 0;
private int nbrHaltaErrors = 0;
private int nbrHaltaUncertain = 0;
private final StringBuilder failuresMsg = new StringBuilder();
/** The instructions to be executed are defined here
* @return true if no error occurs, false otherwise
* @throws Exception */
@Override protected Boolean doInBackground() throws Exception {
//--- do the HaltaFall calculations
// create an instance of class HaltaFall
h = null;
try {h = new HaltaFall(cs,factor, out);}
catch (Chem.ChemicalParameterException ex) { // this should not occur, but you never know
showErrMsgBx(ex);
getHaltaInstanceOK = false; // skip the rest of the thread
}
if(!getHaltaInstanceOK) {this.cancel(true); return false;}
int nStepX1, j;
double tolHalta0 = csC.tol;
final String f = "--- Calculation problem in \"HaltaFall.haltaCalc\" at point=%d, x=%7.5f"+nl+"%s";
nStepX = -1;
do_loopX:
do { // -------------------------------------- Loop for X-axis
nStepX++;
nStepX1 = nStepX+1;
publish(nStepX1);
//if needed for debugging: sleep some milliseconds (wait) at each calculation point
//try {Thread.sleep(500);} catch(Exception ex) {}
// --- input data for this calculation point
for(j =0; j < cs.Na; j++) {
if(dgrC.hur[j] >1 && dgrC.hur[j] !=4) { //TV, LTV or LAV
if(csC.kh[j] == 1) {csC.tot[j]=bt[j][nStepX];}
else {csC.logA[j]=bt[j][nStepX];}
} //if TV, LTV or LAV
} // for j
// ------ print debug output from HaltaFall only for the first point (first point = zero) ------
if(nStepX == 0) {
if(dbg || csC.dbg > Chem.DBGHALTA_DEF) {
out.println("Starting calculation point: "+nStepX1+" (of "+(nSteps+1)+"), x="+(float)bt[diag.compX][nStepX]);
}
/** // ########## ---------- ########## ---------- ########## ##?##
csC.dbg = 6;
out.println("---- Note: nStepX="+nStepX+" (debug) ----");
// ########## ---------- ########## ---------- ########## ##?## */
} else {
csC.dbg = Chem.DBGHALTA_DEF;
/** // ########## ---------- ########## ---------- ########## ##?##
j = diag.compX;
if(Math.abs(bt[j][nStepX]+0.35)<0.005) {
csC.dbg = 6;
out.println("---- Note: x="+(float)bt[j][nStepX]+", (debug) ---- nStepX="+nStepX);
} // ########## ---------- ########## ---------- ########## ##?## */
}
// --- HaltaFall: do the calculations
// calculate the equilibrium composition of the system
try {
csC.tol = tolHalta0;
h.haltaCalc();
if(csC.isErrFlagsSet(2)) { // too many iterations when solving the mass balance equations
do {
csC.tol = csC.tol * 0.1; // decrease tolerance and try again
if(dbg || csC.dbg > Chem.DBGHALTA_DEF) {
out.println("Too many iterations when solving the mass balance equations"+nl+
" decreasing tolerance to: "+(float)csC.tol+" and trying again.");
}
h.haltaCalc();
} while (csC.isErrFlagsSet(2) && csC.tol >= 1e-9);
csC.tol = tolHalta0;
if(dbg || csC.dbg > Chem.DBGHALTA_DEF) {
out.println("Restoring tolerance to: "+(float)tolHalta0+" for next calculations.");
}
}
if(csC.isErrFlagsSet(3)) { // failed to find a satisfactory combination of solids
if(dbg || csC.dbg > Chem.DBGHALTA_DEF) {
out.println("Failed to find a satisfactory combination of solids. Trying again...");
}
csC.cont = false; // try again
h.haltaCalc();
}
}
catch (Chem.ChemicalParameterException ex) {
String ms = "Error in \"HaltaFall.haltaCalc\", "+ex.getMessage()+nl+
" at point: "+nStepX1+" x="+bt[diag.compX][nStepX]+nl+
Util.stack2string(ex);
showErrMsgBx(ms, 1);
haltaError = true;
break; // do_loopX;
}
// ---
if(finishedCalculations) {break;} // do_loopX // user request exit?
out.flush();
if(csC.isErrFlagsSet(1)) {nbrHaltaUncertain++;}
if(csC.isErrFlagsSet(5)) {nbrTooLargeConcs++;}
if(csC.isErrFlagsSet(2) || csC.isErrFlagsSet(3) || csC.isErrFlagsSet(4)
|| csC.isErrFlagsSet(6)) {
nbrHaltaErrors++;
if(failuresMsg.length() >0) {failuresMsg.append(nl);}
failuresMsg.append(String.format(engl,f,nStepX1,(float)bt[diag.compX][nStepX],csC.errFlagsGetMessages()));
}
if(dbg) {
h.printConcs();
factor.printActivityCoeffs(out);
}
if(finishedCalculations) {break;} // do_loopX // user request exit?
// store the results for later plotting (and table output)
plot.storePlotData(nStepX, ch);
if(table != null) {table.tableBody(nStepX, ch);}
} while (nStepX < nSteps); // -------------------------- Loop for X-axis
return true;
}
/** Performs some tasks after the calculations have been finished */
@Override protected void done() {
if(isCancelled()) {
if(dbg) {System.out.println("SwingWorker cancelled.");}
} else {
String msg;
if(!haltaError) {
calculationTime = (System.nanoTime() - calculationStart)
/1000000; //convert nano seconds to milli seconds
msg = "--- Calculated "+(nSteps+1)+" points, time="+millisToShortDHMS(calculationTime);
out.println(msg);
System.out.println(msg);
msg = "";
if(nbrTooLargeConcs > 0) {
int percent = nbrTooLargeConcs*100 / (nSteps+1);
if(percent > 0) {
msg = percent+" % of the calculated points had some"+nl+
"concentrations > "+(int)Factor.MAX_CONC+" (molal); impossible in reality."+nl+nl;
if(calcActCoeffs) {msg = msg + "The activity coefficients are then WRONG"+nl+
"and the results unrealistic."+nl;}
else {msg = msg + "These results are unrealistic."+nl;}
}
}
if(nbrHaltaErrors <= 0 && nbrHaltaUncertain >0 && dbg) {
if(msg.length() >0) msg = msg+nl;
msg = msg+String.format("%d",nbrHaltaUncertain).trim()+" point(s) with round-off errors (not within tolerance).";
}
if(nbrHaltaErrors >0) {
if(msg.length() >0) msg = msg+nl;
msg = msg+String.format("Calculations failed for %d",nbrHaltaErrors).trim()+" point(s).";
}
if(msg.length() >0) {showErrMsgBx(msg, 1);}
if(nbrHaltaErrors >0 && failuresMsg != null && failuresMsg.length() >0) {// failuresMsg should not be empty...
out.println(LINE);
out.println(failuresMsg);
out.println(LINE);
}
out.println("Saving plot file \""+outputPltFile.getAbsolutePath()+"\"...");
try{plot.drawPlot(outputPltFile, ch);}
catch (Exception ex) {
showErrMsgBx("Error: "+ex.getMessage()+nl+
"while saving plot file \""+outputPltFile.getAbsolutePath()+"\"", 1);
}
if(outputPltFile != null && outputPltFile.getName().length()>0) {
String msg3 = "Saved plot file: \""+outputPltFile.getAbsolutePath()+"\"";
out.println(msg3);
System.out.println(msg3);
}
if(table != null) {table.tableClose();}
} // if !haltaError
// execute the following actions on the event-dispatching Thread
// after the "calculations" and the plotting are finished
if(getHaltaInstanceOK && !haltaError) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
jTabbedPane.setTitleAt(2, "<html><u>D</u>iagram</html>");
jTabbedPane.setEnabledAt(2, true);
jTabbedPane.setSelectedComponent(jPanelDiagram);
jTabbedPane.requestFocusInWindow();
restoreMenus(true);
}}); // invokeLater
}//if getHaltaInstanceOK
else {
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
jTabbedPane.setSelectedComponent(jScrollPaneMessg);
jTabbedPane.requestFocusInWindow();
restoreMenus(true);
}}); // invokeLater
}//if !getHaltaInstanceOK
if(dbg) {System.out.println("SwingWorker done.");}
}
out.println(LINE);
System.out.println(LINE);
finishedCalculations = true;
sedFrame.notify_All();
setCursorDef();
}
@Override protected void process(java.util.List<Integer> chunks) {
// Here we receive the values that we publish(). They may come grouped in chunks.
final int i = chunks.get(chunks.size()-1);
int nn = (int)Math.floor(Math.log10(nSteps+1))+1;
final String f = "now calculating loop: %"+String.format("%3d",nn).trim()
+"d (out of %"+String.format("%3d",nn).trim()+"d)";
javax.swing.SwingUtilities.invokeLater(new Runnable() {@Override public void run() {
jLabelProgress.setText(String.format(f,i,(nSteps+1)));
}}); // invokeLater
}
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="main">
/** The "main" method. Creates a new frame if needed.
* Errors and messages are sent to System.out and System.err.
* @param args the command line arguments */
public static void main(final String args[]) {
// ----
System.out.println(LINE+nl+progName+" (Simple Equilibrium Diagrams), version: "+VERS);
// set LookAndFeel
//try {javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getCrossPlatformLookAndFeelClassName());}
//try {javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");}
try {javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());}
catch (Exception ex) {}
//---- for JOptionPanes set the default button to the one with the focus
// so that pressing "enter" behaves as expected:
javax.swing.UIManager.put("Button.defaultButtonFollowsFocus", Boolean.TRUE);
// and make the arrow keys work:
Util.configureOptionPane();
if(args.length <=0) {System.out.println("Usage: SED [-command=value]"+nl+
"For a list of possible commands type: SED -?");}
else {
if(DBG_DEFAULT) {System.out.println("SED "+java.util.Arrays.toString(args));}
}
//---- get Application Path
pathApp = Main.getPathApp();
if(DBG_DEFAULT) {System.out.println("Application path: \""+pathApp+"\"");}
//---- "invokeAndWait": Wait for either:
// - the main window is shown, or
// - perform the calculations and save the diagram
boolean ok = true;
String errMsg = "SED construction did not complete successfully"+nl;
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {@Override public void run() {
// deal with some special command-line arguments
boolean doNotExit0 = false;
boolean doNotStop0 = false;
boolean dbg0 = DBG_DEFAULT;
boolean rev0 = false;
boolean h = false;
if(args.length > 0) {
for(String arg : args) {
if (arg.equalsIgnoreCase("-dbg") || arg.equalsIgnoreCase("/dbg")) {
dbg0 =true;
} else if (arg.equalsIgnoreCase("-keep") || arg.equalsIgnoreCase("/keep")) {
doNotExit0 =true;
} else if (arg.equalsIgnoreCase("-nostop") || arg.equalsIgnoreCase("/nostop")) {
doNotStop0 = true;
} else if (arg.equalsIgnoreCase("-rev") || arg.equalsIgnoreCase("/rev")) {
rev0 =true;
} else if (arg.equals("-?") || arg.equals("/?") || arg.equals("?")) {
h = true;
printInstructions(System.out);
} //if args[] = "?"
} //for arg
if(h && !doNotExit0) {return;} // exit after help if OK to exit
} //if args.length >0
sedFrame = new SED(doNotExit0, doNotStop0, dbg0);//.setVisible(true);
sedFrame.start(rev0, h, args);
}}); //invokeAndWait
} catch (InterruptedException ex) {
ok = false; errMsg = errMsg + Util.stack2string(ex);
}
catch (java.lang.reflect.InvocationTargetException ex) {
ok = false; errMsg = errMsg + Util.stack2string(ex)+nl+ex.getCause().toString();
}
if(!ok) {
System.err.println(errMsg);
ErrMsgBox mb = new ErrMsgBox(errMsg, progName);
}
//-- wait, either for the calculations to finish, or
// for the window to be closed by the user
if(sedFrame != null) {
Thread t = new Thread() {@Override public void run(){
if(sedFrame.inputDataFileInCommandLine) {
sedFrame.synchWaitCalcs();
if(!sedFrame.doNotExit) {sedFrame.end_program();}
else{sedFrame.synchWaitProgramEnded();}
} else {
sedFrame.synchWaitProgramEnded();
}
}};// Thread t
t.start(); // Note: t.start() returns inmediately;
// statements here are executed inmediately.
try {t.join();} catch (InterruptedException ex) {} // wait for the thread to finish
if(sedFrame.dbg) {System.out.println(progName+" - finished.");}
}
//javax.swing.JOptionPane.showMessageDialog(null, "ready", progName, javax.swing.JOptionPane.INFORMATION_MESSAGE);
} // main(args[])
//</editor-fold>
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroupDebug;
private javax.swing.JButton jButtonDoIt;
private javax.swing.JCheckBox jCheckActCoeff;
private javax.swing.JCheckBoxMenuItem jCheckBoxMenuSEDdebug;
private javax.swing.JCheckBox jCheckReverse;
private javax.swing.JCheckBox jCheckTable;
private javax.swing.JComboBox jComboBoxModel;
private javax.swing.JComboBox jComboBoxTol;
private javax.swing.JLabel jLabelBar;
private javax.swing.JLabel jLabelData;
private javax.swing.JLabel jLabelHD;
private javax.swing.JLabel jLabelHeight;
private javax.swing.JLabel jLabelIonicStr;
private javax.swing.JLabel jLabelIonicStrM;
private javax.swing.JLabel jLabelModel;
private javax.swing.JLabel jLabelNbrPText;
private javax.swing.JLabel jLabelP;
private javax.swing.JLabel jLabelPltFile;
private javax.swing.JLabel jLabelPointsNbr;
private javax.swing.JLabel jLabelPressure;
private javax.swing.JLabel jLabelProgress;
private javax.swing.JLabel jLabelStatus;
private javax.swing.JLabel jLabelT;
private javax.swing.JLabel jLabelTC;
private javax.swing.JLabel jLabelTemperature;
private javax.swing.JLabel jLabelTol;
private javax.swing.JMenuBar jMenuBar;
private javax.swing.JMenuItem jMenuCancel;
private javax.swing.JMenu jMenuDebug;
private javax.swing.JMenu jMenuFile;
private javax.swing.JMenuItem jMenuFileMakeD;
private javax.swing.JMenuItem jMenuFileOpen;
private javax.swing.JMenuItem jMenuFileXit;
private javax.swing.JMenuItem jMenuHF_dbg;
private javax.swing.JMenu jMenuHelp;
private javax.swing.JMenuItem jMenuHelpAbout;
private javax.swing.JMenuItem jMenuSave;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanelActC;
private javax.swing.JPanel jPanelDiagram;
private javax.swing.JPanel jPanelFiles;
private javax.swing.JPanel jPanelParameters;
private javax.swing.JPanel jPanelStatusBar;
private javax.swing.JPanel jPanelT;
private javax.swing.JScrollBar jScrollBarHeight;
private javax.swing.JScrollBar jScrollBarNbrPoints;
private javax.swing.JScrollPane jScrollPaneMessg;
private javax.swing.JTabbedPane jTabbedPane;
private javax.swing.JTextArea jTextAreaA;
private javax.swing.JTextField jTextFieldDataFile;
private javax.swing.JTextField jTextFieldIonicStgr;
private javax.swing.JTextField jTextFieldPltFile;
// End of variables declaration//GEN-END:variables
} // class SED
| 172,885 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
Plot.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/SED/src/simpleEquilibriumDiagrams/Plot.java | package simpleEquilibriumDiagrams;
import lib.common.Util;
import lib.kemi.chem.Chem;
import lib.kemi.graph_lib.GraphLib;
/** Methods to create a chemical equilibrium diagram.
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class Plot {
private SED sed = null;
// this and other fields are also used in the Table class
static int nbrSpeciesInPlot;
static int[] speciesInPlot;
/** max. number of species that need two labels in the diagram */
private static final int L2 = 20;
/** the max y-value for each curve in the diagram */
private static double[] yMax;
/** values of conc. or log(activity) for each point c0[Ms][nP] */
static double c0[][];
/** values of solubility or tot. conc. for each point tot0[Na][nP] */
static double tot0[][];
/** If true, the concentration is displayed as is. If false, the
* concentration is displayed as milli molal, micro molal, or nano molal. */
private static boolean xMolal = true;
private static final java.util.Locale engl = java.util.Locale.ENGLISH;
/** Where errors will be printed. It may be <code>System.err</code>.
* If null, <code>System.err</code> is used. */
private final java.io.PrintStream err;
/** Where messages will be printed. It may be <code>System.out</code>.
* If null, <code>System.out</code> is used. */
private final java.io.PrintStream out;
private static final String nl = System.getProperty("line.separator");
/** Constructor.
* @param sed0
* @param err0 Where errors will be printed. It may be <code>System.err</code>.
* If null, <code>System.err</code> is used.
* @param out0 Where messages will be printed. It may be <code>System.out</code>.
* If null, <code>System.out</code> is used.
*/
public Plot(SED sed0, java.io.PrintStream err0, java.io.PrintStream out0) {
this.sed = sed0;
if(err0 != null) {this.err = err0;} else {this.err = System.err;}
if(out0 != null) {this.out = out0;} else {this.out = System.out;}
} //constructor
//<editor-fold defaultstate="collapsed" desc="preparePlot(ch)">
/** Create arrays to store the diagram data
* @param ch where the data for the chemical system are stored */
void preparePlot(Chem ch) {
if(sed.dbg) {out.println("--- preparePlot(ch)");}
Chem.ChemSystem cs = ch.chemSystem;
Chem.ChemSystem.ChemConcs csC = cs.chemConcs;
Chem.ChemSystem.NamesEtc namn = cs.namn;
Chem.Diagr diag = ch.diag;
//chem.Chem.DiagrConcs dgrC = ch.diagrConcs;
yMax = new double[cs.Ms+L2];
for(int i=0; i < yMax.length; i++) {yMax[i] =0;}
c0 = new double[cs.Ms][sed.nSteps+1];
tot0 = new double[cs.Na][sed.nSteps+1];
// Values for the Y-axis
// plotType=1 fraction diagram compY= main component
// plotType=2 log solubility diagram
// plotType=3 log (conc) diagram
// plotType=4 log (ai/ar) diagram compY= reference species
// plotType=5 pe in Y-axis
// plotType=6 pH in Y-axis
// plotType=7 log (activity) diagram
// plotType=8 H-affinity diagram
//---- what species to diagramData ----
nbrSpeciesInPlot = cs.Ms;
speciesInPlot = new int[cs.Ms+L2];
if(diag.plotType == 2) { // solubility diagram
nbrSpeciesInPlot = 0;
for(int n =0; n < cs.Na; n++) {
String t = namn.identC[n];
if(Util.isElectron(t) ||
Util.isProton(t) ||
Util.isWater(t)) {continue;}
nbrSpeciesInPlot++;
speciesInPlot[nbrSpeciesInPlot-1] = n;
} //for n
} else if(diag.plotType ==5 || diag.plotType ==6) { //pe or pH in the Y-AXIS
for(int n =0; n < cs.Ms; n++) {
String t = namn.ident[n];
if(diag.plotType ==5) {//pe
if(Util.isElectron(t)) {speciesInPlot[0] = n; break;}
} else { //pH
if(Util.isProton(t)) {speciesInPlot[0] = n; break;}
}
} //for n
nbrSpeciesInPlot = 1;
} else if(diag.plotType ==8) { //H-affinity diagram
nbrSpeciesInPlot = 1;
speciesInPlot[0] = diag.Hplus;
} else { //Log(c), Log(a), Fraction and log(ai/ar)
nbrSpeciesInPlot = 0;
for(int n =0; n < cs.Ms; n++) {
String t = namn.ident[n].toUpperCase();
//if not log(a): exclude electrons
if(diag.plotType !=7 && Util.isElectron(t)) {continue;}
if(diag.plotType ==4) { //log (ai/ar)
if(n == diag.compY) {
nbrSpeciesInPlot++;
speciesInPlot[nbrSpeciesInPlot-1] = n;
continue;
}
if(diag.compY >= cs.Na) {
//relative diagram where the reference species is not a component
if(n < cs.Na && Math.abs(cs.a[diag.compY][n]) <= 1e-10) {continue;}
nbrSpeciesInPlot++;
speciesInPlot[nbrSpeciesInPlot-1] = n;
continue;
}
if(n < cs.Na) {continue;}
//include only species related to the reference species
if(Math.abs(cs.a[n-cs.Na][diag.compY]) > 1e-10) {
nbrSpeciesInPlot++;
speciesInPlot[nbrSpeciesInPlot-1] = n;
}
} else {
nbrSpeciesInPlot++;
speciesInPlot[nbrSpeciesInPlot-1] = n;
}
} //for n
} //Log(c), Log(a), Fraction and log(ai/ar)
} //preparePlot
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="storePlotData(nP, ch)">
/** Store diagram data for this point (an equilibrium composition)
* in the arrays provided in this class.
* @param nP the point number (along the x-axis)
* @param ch where the data for the chemical system are stored */
void storePlotData(int nP, Chem ch) {
if(sed.dbg) {out.println("--- storePlotData("+nP+", ch)");}
Chem.ChemSystem cs = ch.chemSystem;
Chem.ChemSystem.ChemConcs csC = cs.chemConcs;
Chem.Diagr diag = ch.diag;
//chem.Chem.DiagrConcs dgrC = ch.diagrConcs;
// Values for the Y-axis
// plotType=1 fraction diagram compY= main component
// plotType=2 log solubility diagram
// plotType=3 log (conc) diagram
// plotType=4 log (ai/ar) diagram compY= reference species
// plotType=5 pe in Y-axis
// plotType=6 pH in Y-axis
// plotType=7 log (activity) diagram
// plotType=8 H-affinity diagram
double w, y, z;
// save conc. or log(activity)
for(int i =0; i < cs.Ms; i++) {
c0[i][nP] = 0;
if(diag.plotType ==4 || diag.plotType ==7) {c0[i][nP] = -9999;} // log(a) or log(ai/ar)
if(diag.plotType ==5 || diag.plotType ==6) {c0[i][nP] = +9999;} // pe/Eh or pH
if(csC.isErrFlagsSet(2) || csC.isErrFlagsSet(3) || csC.isErrFlagsSet(4)
|| csC.isErrFlagsSet(6)) {continue;}
if(diag.plotType < 4) { // fraction, log(c), or log(solub)
if(csC.C[i] > 1.e+35) {c0[i][nP] = 1.e+35;}
else if(Math.abs(csC.C[i]) <= 1.e+35)
{c0[i][nP] = csC.C[i];}
} else {
if(diag.plotType ==8) {continue;} // H-affinity
//for log(ai/ar), log(activity) or pe or pH diagrams: set highest limit
if(csC.logA[i] > 1.e+35) {c0[i][nP] = 1.e+35;}
w = Math.abs(csC.logA[i]);
//set lowest limit, and if loga =0 check if concentration =0
if(w <= 1e+35 && (w > 0 || Math.abs(csC.C[i]) > 0))
{c0[i][nP] = csC.logA[i];}
if(cs.noll[i] && (w > 0 && w <= 1e+35))
{c0[i][nP] = csC.logA[i];}
}
} //for i
// save tot.conc. or solubility
for(int j =0; j < cs.Na; j++) {
tot0[j][nP] = 0.d;
if(csC.errFlags < -1) {continue;}
if(diag.plotType ==2) { //log(solub)
if(Math.abs(csC.solub[j]) < 1.e+35d)
{tot0[j][nP] = csC.solub[j];}
} else {
if(Math.abs(csC.tot[j]) < 1.e+35d)
{tot0[j][nP] = csC.tot[j];}
}
} //for j
// for H-affinity diagrams:
if(diag.plotType ==8 && (diag.Hplus >=0 && diag.Hplus < cs.Ms)) {
//c0[0][nP]=C(H+) c0[1][nP]=LOGA(H+) c0[2][nP]=C(OH-)
if(Math.abs(csC.C[diag.Hplus]) <= 1e+35)
{c0[0][nP] = csC.C[diag.Hplus];}
w = Math.abs(csC.logA[diag.Hplus]);
if(w <= 1e+35 &&
(w >= 1e-35 || Math.abs(csC.C[diag.Hplus]) >= 1e-35))
{c0[1][nP] = csC.logA[diag.Hplus];}
if(diag.OHmin > -1) {if(Math.abs(csC.C[diag.OHmin]) <= 1e+35)
{c0[2][nP] = csC.C[diag.OHmin];}}
//get Max and Min values for Y-axis
if(nP > 0) {
w = c0[1][nP] - c0[1][nP-1];
y = (tot0[diag.Hplus][nP]-c0[0][nP]+c0[2][nP])
- (tot0[diag.Hplus][nP-1]-c0[0][nP-1]+c0[2][nP-1]);
z = 0;
if(Math.abs(w) >= 1e-30) {z = y/w;}
if(z < diag.yLow) {diag.yLow = z;}
if(z > diag.yHigh) {diag.yHigh = z;}
} // if nP >0
} // H-affinity
} //storePlotData()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="drawPlot(plotFile, ch)">
/** Create a diagram. Saving the diagram information in a PltData() object
* and simultaneously store the data in a plot file.
* @param plotFile where the diagram will be saved
* @param ch where the data for the chemical system are stored
*/
void drawPlot(java.io.File plotFile, Chem ch) throws GraphLib.WritePlotFileException {
Chem.ChemSystem cs = ch.chemSystem;
Chem.ChemSystem.ChemConcs csC = cs.chemConcs;
Chem.ChemSystem.NamesEtc namn = cs.namn;
Chem.Diagr diag = ch.diag;
Chem.DiagrConcs dgrC = ch.diagrConcs;
if(sed.dbg) {
out.println("--- drawPlot("+plotFile.toString()+", ch)"+System.getProperty("line.separator")+
"Drawing the plot...");
}
//-- display of concentrations: units and notation
// default is that:
// 1- if the temperature is between 0 and 45 Celsius and the pressure
// is below 50 bars, then units = "M" (molar) and the notation is
// engineering (millimolar, micromolar, etc)
// 2- otherwise units = "molal" and the notation is engineering
// (10'-3` molal, 10'-6` molal, etc)
sed.conc_units = Math.min(2, Math.max(sed.conc_units, -1));
sed.conc_nottn = Math.min(2, Math.max(sed.conc_nottn, 0));
if(sed.conc_nottn == 0) {sed.conc_nottn = 2;} // engineering
if( (Double.isNaN(diag.temperature) || (diag.temperature >= 0 && diag.temperature <= 45))
&& (Double.isNaN(diag.pressure) || diag.pressure <=50)) {
// temperatures around 25 and low pressures
if(sed.conc_units == 0) {sed.conc_units = 2;} // units = "M"
}
String cUnit = sed.cUnits[(sed.conc_units+1)];
String mUnit = ("×10'-3` "+cUnit).trim();
String uUnit = ("×10'-6` "+cUnit).trim();
String nUnit = ("×10'-9` "+cUnit).trim();
if(sed.conc_units == 2) {mUnit = " mM"; uUnit = " $M"; nUnit = " nM";}
//---- Max and Min values in the axes: xLow,xHigh, yLow,yHigh
double xLow = sed.bt[diag.compX][0];
double xHigh = sed.bt[diag.compX][(sed.bt[0].length-1)];
// Concentration types:
// hur =1 for "T" (fixed Total conc.)
// hur =2 for "TV" (Tot. conc. Varied)
// hur =3 for "LTV" (Log(Tot.conc.) Varied)
// hur =4 for "LA" (fixed Log(Activity) value)
// hur =5 for "LAV" (Log(Activity) Varied)
if(dgrC.hur[diag.compX] ==3) { // LTV
xLow = Math.log10(xLow);
xHigh = Math.log10(xHigh);
}
if(Util.isProton(namn.identC[diag.compX]) ||
Util.isElectron(namn.identC[diag.compX])) {
if(dgrC.hur[diag.compX] !=5) {diag.pInX = 0;} // not LAV
else { // LAV
xLow = -xLow; xHigh = -xHigh;
if(diag.pInX == 3) {
xLow = sed.peEh * xLow;
xHigh = sed.peEh * xHigh;
}
} // if LAV
} // is H+ or engl-
// standard scale in X-axis
xMolal = true;
if(dgrC.hur[diag.compX] <=2) { // T or TV
if((sed.conc_nottn == 2 || (sed.conc_nottn == 0 && sed.conc_units == 2)) &&
Math.abs(xLow) <0.9 && Math.abs(xHigh) <0.9) {
//milli units in X-axis
xMolal = false;
xLow = xLow * 1000.; xHigh = xHigh * 1000.;
}
} //T or TV
//Values for the Y-axis
/** the low limit for the y-axis */
double yLow = diag.yLow;
/** the high limit for the y-axis */
double yHigh = diag.yHigh;
// plotType=1 fraction diagram compY= main component
// plotType=2 log solubility diagram
// plotType=3 log (conc) diagram
// plotType=4 log (ai/ar) diagram compY= reference species
// plotType=5 pe in Y-axis
// plotType=6 pH in Y-axis
// plotType=7 log (activity) diagram
// plotType=8 H-affinity diagram
if(diag.plotType <= 3 && !diag.inputYMinMax) { // fraction, log(c) or log(solub)
if(diag.plotType ==2) {yLow =-16;} //log(solub)
else if(diag.plotType ==3) {yLow =-9;} // log(c)
else {yLow =0;} //fraction
if(diag.plotType ==2) {yHigh =+2;} //log(solub)
else {yHigh =1;} //fraction or log(conc.)
}
if(diag.plotType == 8) {yLow = Math.min(yLow, 0);} // for H-affinity diagram
/** For a curve to show in the graph: at least 0.5% of the Y-axis span
* (3% in fraction diagrams (0.03 fraction)) */
double yMin = yLow + 0.005 * (yHigh - yLow);
if(diag.plotType == 1) {yMin = yLow + (double)diag.fractionThreshold * (yHigh - yLow);} //fraction namn
//---- Get the length of the axes labels
int nTextX = 6 + namn.nameLength[namn.iel[diag.compX]];
if(diag.pInX ==1 || diag.pInX ==2) {nTextX =2;} // pH or pe
else if(diag.pInX ==3) {nTextX =8;} // "E`SHE' / V"
int nTextY = 8;
if(diag.plotType ==3) {nTextY =9;} //log(conc.)
else if(diag.plotType ==2) {nTextY =10;} //log(solub)
else if(diag.plotType ==4) {nTextY =12;} //log(ai/aref)
else if(diag.plotType ==5 || diag.plotType ==6) {nTextY = 2;} //pH or pe
//---- Dimensions of the diagramData, Size of text: height. Origo: xOr,yOr
float xAxl =15; float yAxl = 10;
float heightAx = 0.035f * yAxl;
if(sed.tHeight > 0.0001) {heightAx = (float)sed.tHeight*heightAx;}
float xOr; float yOr;
xOr = 7.5f * heightAx;
yOr = 4.0f * heightAx;
float xMx = xOr + xAxl; float yMx = yOr + yAxl;
// xL and yL are scale factors, according to
// the axis-variables (pH, pe, Eh, log{}, log[]tot, etc)
float xL = xAxl / (float)(xHigh - xLow); float xI = xL * (float)xLow - xOr;
float yL = yAxl / (float)(yHigh - yLow); float yI = yL * (float)yHigh - yMx;
if(!xMolal) {xL = xL * 1000;} // T or TV and "milli units"
// pInX=0 "normal" X-axis
// pInX=1 pH in X-axis
// pInX=2 pe in X-axis
// pInX=3 Eh in X-axis
if(diag.pInX ==1 || diag.pInX == 2) {xL = -xL;}
else if(diag.pInX ==3) {xL = -xL * (float)sed.peEh;}
// -------------------------------------------------------------------
// Create a PltData instance
sed.dd = new GraphLib.PltData();
// Create a GraphLib instance
GraphLib g = new GraphLib();
boolean textWithFonts = true;
try {g.start(sed.dd, plotFile, textWithFonts);}
catch (GraphLib.WritePlotFileException ex) {sed.showErrMsgBx(ex.getMessage(),1); g.end(); return;}
sed.dd.axisInfo = false;
g.setLabel("-- SED DIAGRAM --");
// -------------------------------------------------------------------
// Draw Axes
g.setIsFormula(true);
g.setPen(1);
//g.setLabel("-- AXIS --");
g.setPen(-1);
// draw axes
try {g.axes((float)xLow, (float)xHigh, (float)yLow, (float)yHigh,
xOr,yOr, xAxl,yAxl, heightAx,
false, false, false);}
catch (GraphLib.AxesDataException ex) {sed.showMsg(ex); g.end(); return;}
//---- Write text under axes
// Y-axis
float xP; float yP;
yP =((yAxl/2f)+yOr)-((((float)nTextY)/2f)*(1.3f*heightAx));
//xP = 1.1f*heightAx;
xP = xOr - 6.6f*heightAx;
// Values for the Y-axis
// plotType=1 fraction diagram compY= main component
// plotType=2 log solubility diagram
// plotType=3 log (conc) diagram
// plotType=4 log (ai/ar) diagram compY= reference species
// plotType=5 pe in Y-axis
// plotType=6 pH in Y-axis
// plotType=7 log (activity) diagram
// plotType=8 H-affinity diagram
String t = "Fraction";
if(diag.plotType ==2) {t="Log Solubl.";}
else if(diag.plotType ==3) {t="Log Conc.";}
else if(diag.plotType ==4) {t="Log (a`i'/a`ref')";}
else if(diag.plotType ==5) {
t="pe";
if(diag.Eh) {t="E`H'";}
}
else if(diag.plotType ==6) {t="pH";}
else if(diag.plotType ==7) {t="Log Activity";}
else if(diag.plotType ==8) {t="d([H+]`bound')/d(-pH)";} //H-affinity (proton-affinity)
g.setLabel("Y-AXIS TEXT"); g.moveToDrawTo(0, 0, 0);
g.sym(xP, yP, heightAx, t, 90, 0, false);
// ---- X-axis label (title)
yP = yOr - 3.6f*heightAx;
xP =((xAxl/2f)+xOr)-((((float)nTextX)/2f)*(1.1429f*heightAx));
// Concentration types:
// hur =1 for "T" (fixed Total conc.)
// hur =2 for "TV" (Tot. conc. Varied)
// hur =3 for "LTV" (Log(Tot.conc.) Varied)
// hur =4 for "LA" (fixed Log(Activity) value)
// hur =5 for "LAV" (Log(Activity) Varied)
if(dgrC.hur[diag.compX] ==5) { //"LAV"
if(diag.pInX ==0) {
if(Util.isGas(namn.identC[diag.compX])) {t = "Log P`"+namn.identC[diag.compX]+"'";}
else {t = "Log {"+namn.identC[diag.compX]+"}";} // not Gas
} // pInX=0
else if(diag.pInX ==1) {t="pH";}
else if(diag.pInX ==2) {t="pe";}
else //if(pInX ==3)
{t="E`SHE' / V";}
} //"LAV"
else if(dgrC.hur[diag.compX] ==2) { //"TV"
t = "["+namn.identC[diag.compX]+"]`TOT'";
if(xMolal) {t = t + " "+cUnit;}
else {t = t + " "+mUnit;}
} else { // if(dgrC.hur[diag.compX] ==3) "LTV"
t = "Log ["+namn.identC[diag.compX]+"]`TOT'";
}
if(dgrC.hur[diag.compX] ==2 || dgrC.hur[diag.compX] ==3 || dgrC.hur[diag.compX] ==5) {
g.setLabel("X-AXIS TEXT"); g.moveToDrawTo(0, 0, 0);
g.sym((float)xP, (float)yP, (float)heightAx, t, 0, 0, false);}
// -------------------------------------------------------------------
// Draw the Curves
g.setLabel("-- CURVES --"); g.setPen(1);
//--- values for X-axis
float[] xax = new float[sed.nSteps+1];
for(int i =0; i < sed.nSteps+1; i++) {
if(dgrC.hur[diag.compX] ==3) { //"LTV"
xax[i] = (float)(xL*Math.log10(sed.bt[diag.compX][i])-xI);}
else{xax[i] = (float)(xL*sed.bt[diag.compX][i]-xI);}
} //for i
float[] yax = new float[sed.nSteps+1];
for(int i =0; i < yax.length; i++) {yax[i] =0f;}
//--- curve counter: k
int i, j, curvePoint;
int xtraLabel = 0;
boolean aPointIsShown, aPointIsShownNextNot, secondLabel, curveStarted;
double yLow1 = yLow;
if(diag.plotType ==1) {yLow1 = 0.005;} //fraction
int[] maxPoint = new int[cs.Ms+L2];
int k = 0; // k is a curve counter
do { // while (k < nbrSpeciesInPlot);
kLoop:
while(true) {
i = speciesInPlot[k];
if(diag.plotType ==1) {//fraction
if(i>cs.Ms) {break;} //kLoop
for(j=0; j < (sed.nSteps+1); j++) {
if(Math.abs(tot0[diag.compY][j]) > 1.e-30) {
double o;
if(i < cs.Na) {if(i==diag.compY) {o=1;} else {o=0;}}
else {o =cs.a[i-cs.Na][diag.compY];}
yax[j]=(float)(o*c0[i][j]/tot0[diag.compY][j]);
if(yax[j] >= 1.f && yax[j] <= 1.05f) {yax[j]=1.0f-1.E-5f;}
} else {yax[j] = 0f;}
} //for j
} else if(diag.plotType ==2) {//log solubility
for(j=0; j < (sed.nSteps+1); j++) {
yax[j] = -50f;
if(tot0[i][j] > 1.E-35f) {yax[j]=(float)Math.log10(tot0[i][j]);}
} //for j
} else if(diag.plotType ==3) {//log conc.
for(j=0; j < (sed.nSteps+1); j++) {
yax[j] = -99.f;
if(c0[i][j] > 1.E-35f) {yax[j]=(float)Math.log10(c0[i][j]);}
} //for j
} else if(diag.plotType ==4) {//log(ai/ar) diagram
for(j=0; j < (sed.nSteps+1); j++) {yax[j] = (float)(c0[i][j] - c0[diag.compY][j]);}
} else if(diag.plotType ==5) {//calc. pe
for(j=0; j < (sed.nSteps+1); j++) {
if(!diag.Eh) {yax[j] = (float)(-c0[i][j]);}
else {yax[j] = (float)(-c0[i][j]*sed.peEh);}
} //for j
} else if(diag.plotType ==6) {//calc. pH
for(j=0; j < (sed.nSteps+1); j++) {yax[j] = (float)(-c0[i][j]);}
} else if(diag.plotType ==7) {//log act.
for(j=0; j < (sed.nSteps+1); j++) {yax[j] = (float)(c0[i][j]);}
} else if(diag.plotType ==8) {//H-affinity "d(H-bound)/d(-pH)"
if(diag.Hplus >= 0 || diag.Hplus <= cs.Ms) {
//C0[0][n]=C(H+) C0[1][n]=LOGA(H+) C0[2][n]=C(OH-)
double w1, w2, y1, y2 = 0;
w1 = c0[1][1]-c0[1][0];
w2 = (tot0[diag.Hplus][1]-c0[0][1]+c0[2][1])
- (tot0[diag.Hplus][0]-c0[0][0]+c0[2][0]);
yax[0] =0f;
if(Math.abs(w1) >= 1e-35) yax[0]= (float)(w2 / w1);
for(j=1; j < sed.nSteps; j++) {
w1 = c0[1][j]-c0[1][j-1];
w2 = (tot0[diag.Hplus][j]-c0[0][j]+c0[2][j])
- (tot0[diag.Hplus][j-1]-c0[0][j-1]+c0[2][j-1]);
y1 = 0;
if(Math.abs(w1) >= 1e-35) y1= (float)(w2 / w1);
w1 = c0[1][j+1]-c0[1][j];
w2 = (tot0[diag.Hplus][j+1]-c0[0][j+1]+c0[2][j+1])
- (tot0[diag.Hplus][j]-c0[0][j]+c0[2][j]);
y2 = 0;
if(Math.abs(w1) >= 1e-35) y2= (float)(w2 / w1);
yax[j] = (float)((y1+y2)/2);
} //for j
yax[sed.nSteps] = (float)y2;
}
} else {
err.println("Programming error in \"drawPlot\"; plotType = "+diag.plotType);
g.end();
return;
}
//--- Determine the Maximum values for the curve
// where the label(s) to the curves will be plotted
double w;
maxPoint[k] =-1;
yMax[k] = yMin;
yMax[nbrSpeciesInPlot+xtraLabel]=yMin;
aPointIsShown =false;
aPointIsShownNextNot =false;
secondLabel =false;
for(j=0; j < (sed.nSteps+1); j++) {
if(aPointIsShown && (yax[j] < yMin)) {aPointIsShownNextNot =true;}
if(aPointIsShownNextNot && (yax[j] > yMin)) {
if(xtraLabel < L2) {
if(yax[j] >= yMax[nbrSpeciesInPlot+xtraLabel] && yax[j] <= yHigh) {
secondLabel = true;
maxPoint[nbrSpeciesInPlot+xtraLabel] = j;
yMax[nbrSpeciesInPlot+xtraLabel] = yax[j];
}
}
} else {
if(yax[j] < yMax[k] || yax[j] > yHigh) {continue;}
aPointIsShown =true;
maxPoint[k] = j;
yMax[k] = yax[j];
}
} //for j
if(secondLabel) {
speciesInPlot[nbrSpeciesInPlot+xtraLabel] = speciesInPlot[k];
xtraLabel++;
}
//--- Do NOT plot if curve does not appear between YMIN and YHIGH
if(maxPoint[k] <0) {break;} // kLoop
if(diag.plotType ==2) {g.setLabel(namn.identC[i]);} // solubility namn
else {g.setLabel(namn.ident[i]);}
g.setPen(-(speciesInPlot[k]+1));
//--- Draw the curve
curveStarted = false;
curvePoint = 0;
if(yax[curvePoint] >yLow1 && yax[curvePoint] < yHigh) {
g.moveToDrawTo(xax[curvePoint],yL*yax[curvePoint]-yI,0);
curveStarted = true;
}
for(curvePoint = 1; curvePoint < (sed.nSteps+1); curvePoint++) {
if(yax[curvePoint] >yLow1 && yax[curvePoint] < yHigh) {
if(!curveStarted) {
j= curvePoint-1;
if(yax[j] > yLow1) {
//xax2[k]= xax[j]+(xax[curvePoint]-xax[j])*((float)yHigh-yax[j]) /(yax[curvePoint]-yax[j]);
w = xax[j]+(xax[curvePoint]-xax[j])*((float)yHigh-yax[j])
/(yax[curvePoint]-yax[j]);
yMax[k]= yHigh;
g.moveToDrawTo(w,yMx,0);
} else if(yax[j] == yLow1) {
g.moveToDrawTo(xax[j],yOr,0);
} else { // if (yax[j] < yLow1)
xP= xax[j]+(xax[curvePoint]-xax[j])*((float)yLow-yax[j])
/(yax[curvePoint]-yax[j]);
xP=Math.min(xMx,Math.max(xOr,xP));
g.moveToDrawTo(xP, yOr, 0);
}
curveStarted = true; // do not remove this line
}
g.moveToDrawTo(xax[curvePoint],yL*yax[curvePoint]-yI,1);
} else { //point outside yLow1 - yHigh range
if(curveStarted) {
j= curvePoint-1;
if(yax[curvePoint] > yLow1) {
//xax2[k]= xax[j]+(xax[curvePoint]-xax[j])*((float)yHigh-yax[j])/(yax[curvePoint]-yax[j]);
w = xax[j]+(xax[curvePoint]-xax[j])*((float)yHigh-yax[j])
/(yax[curvePoint]-yax[j]);
yMax[k]= yHigh;
g.moveToDrawTo(w,yMx,1);
} else if(yax[curvePoint] == yLow1) {
g.moveToDrawTo(xax[curvePoint],yOr,1);
} else {//if (yax[n] < yLow1)
xP= xax[j]+(xax[curvePoint]-xax[j])*((float)yLow-yax[j])
/(yax[curvePoint]-yax[j]);
xP=Math.min(xMx,Math.max(xOr,xP));
g.moveToDrawTo(xP, yOr, 1);
}
curveStarted = false; // do not remove this line
}
}
} //for curvePoint
break; // kLoop
} //kLoop: while(true) - breaks will go here...
k++;
} while (k < nbrSpeciesInPlot);
// -------------------------------------------------------------------
// Draw Labels on the Curves
float[] xPl = new float[cs.Ms+L2];
float[] yPl = new float[cs.Ms+L2];
double w;
if(diag.plotType !=5 && diag.plotType !=6 &&
diag.plotType !=8) { // no labels for pe pH or H-affinity
g.setLabel("-- LABELS ON CURVES --");
g.setPen(1);
for(k =0; k < nbrSpeciesInPlot+xtraLabel; k++) {
if(maxPoint[k] <0) {continue;}
i = speciesInPlot[k];
float xP1 = 0.5f*namn.nameLength[i]*heightAx;
xP = xax[maxPoint[k]] -xP1;
xP = Math.min(xMx-xP1, Math.max(xP,xOr+0.4f*heightAx));
xPl[k] = (float)xP;
yPl[k] = (float)(yL*yMax[k]+0.5*heightAx-yI);
} //for k
// Check that labels do not overlap
boolean overlap; float yPl0; int iSign; int inkr;
for(k =0; k < nbrSpeciesInPlot+xtraLabel; k++) {
if(maxPoint[k] <0) {continue;}
if(k >0) {//not first label
yPl0 = yPl[k]; iSign = -1; inkr =1;
do {//loop until a non-overlapping Y-position is found
overlap = false;
for(int ij = 0; ij <k; ij++) {
if(maxPoint[ij] <0) {continue;}
if((yPl[k] > yPl[ij]+1.5*heightAx) ||
(yPl[k] < yPl[ij]-1.5*heightAx)) {continue;}
if((xPl[k] > xPl[ij]+heightAx*namn.nameLength[speciesInPlot[ij]]) ||
(xPl[ij] > xPl[k]+heightAx*namn.nameLength[speciesInPlot[k]])) {continue;}
overlap = true; break;
} //for ij
if(overlap) {
yPl[k] = yPl0 + (iSign * inkr * (float)heightAx/6.f);
iSign = -iSign; if(iSign ==-1) {inkr++;}
}
} while (overlap);
//at this point the label does not overlap with any other
} //nor first label
// diagramData the label:
if(diag.plotType ==2) {t = namn.identC[speciesInPlot[k]];} //log (solubl.)
else {t = namn.ident[speciesInPlot[k]];}
g.setLabel(t); // make it possible to change the color automatically by writing the name
g.setPen(-(speciesInPlot[k]+1));
g.sym(xPl[k], yPl[k], (float)heightAx, t, 0f, -1, false);
} //for k
} // labels only for pe pH or H-affinity
// -------------------------------------------------------------------
// Text with concentrations as a Heading
g.setLabel("-- HEADING --"); g.setPen(1); g.setPen(-1);
if(sed.dbg) {
out.print("Heading; concentration units: \""+sed.cUnits[sed.conc_units+1]+"\"");
if(sed.conc_nottn == 2 || (sed.conc_nottn == 0 && sed.conc_units == 2)) {out.print(", notation: engineering");}
if(sed.conc_nottn == 1 || (sed.conc_nottn == 0 && sed.conc_units != 2)) {out.print(", notation: scientific");}
out.println();
}
float headColumnX = 0.5f*heightAx;
int headRow = 0;
int headRowMax = Math.max(2,(2+cs.Na)/2);
yP = yMx + heightAx; // = yMx + 0.5f*heightAx in PREDOM
float yPMx = yMx;
double wa;
// Concentration types:
// hur =1 for "T" (fixed Total conc.)
// hur =2 for "TV" (Tot. conc. Varied)
// hur =3 for "LTV" (Log(Tot.conc.) Varied)
// hur =4 for "LA" (fixed Log(Activity) value)
// hur =5 for "LAV" (Log(Activity) Varied)
for(j =0; j < cs.Na; j++) {
if(dgrC.hur[j] !=1 && dgrC.hur[j] !=4) {continue;} //"T" or "LA" only
if(dgrC.hur[j] ==4 && Util.isWater(namn.ident[j])) {continue;}
i = namn.iel[j];
yP = yP + 2f*heightAx;
headRow++;
if(headRow == headRowMax) {
headColumnX = headColumnX + (33f*heightAx);
yP = yMx + 3f*heightAx; // = yMx + 2.5f*heightAx in PREDOM
}
yPMx = Math.max(yPMx,yP);
String value;
if(dgrC.hur[j] == 1) { //"T"
w = csC.tot[j]; wa = Math.abs(w);
// use engineering notation?
if(sed.conc_nottn == 2 || (sed.conc_nottn == 0 && sed.conc_units == 2)) {
if(wa < 1.E-99) {value = String.format(engl,"=%8.2f",(float)w);}
else if(wa < 1. && wa >= 0.9999E-4) {
w = w*1.E+3;
value = String.format(engl,"=%8.2f"+mUnit,(float)w);
} else if(wa < 0.9999E-4 && wa >= 0.9999E-7) {
w = w*1.E+6;
value = String.format(engl,"=%8.2f"+uUnit,(float)w);
} else if(wa < 0.9999E-7 && wa >= 0.9999E-10) {
w = w*1.E+9;
value = String.format(engl,"=%8.2f"+nUnit,(float)w);
} else if(wa <= 9999.99 && wa >= 0.99) {
value = String.format(engl,"=%8.2f "+cUnit,(float)w);
} else {
value = "= "+double2String(w)+" "+cUnit;
}
} else {
if(wa < 1.E-99) {value = String.format(engl,"=%8.2f",(float)w);}
else if(wa <= 9999.99 && wa >= 0.99) {
value = String.format(engl,"=%8.2f "+cUnit,(float)w);
} else {
value = "= "+double2String(w)+" "+cUnit;
}
}
t = "["+namn.ident[i]+"]`TOT' "+value;
} // hur=1: "T"
else //if(sed.hur[j] == 4) { //"LA"
{ String c;
boolean volt = false;
if(Util.isElectron(namn.ident[j])) {
w = -dgrC.cLow[j];
if(diag.Eh){c = "E`H' = "; w = w*sed.peEh; volt = true;}
else {c = "pe =";}
} //isElectron
else if(Util.isProton(namn.ident[i])) {
w = -dgrC.cLow[j]; c = "pH=";}
else if(Util.isGas(namn.ident[i])) {
w = dgrC.cLow[j]; c = "Log P`"+namn.ident[i]+"' =";}
else {w = dgrC.cLow[j]; c = "Log {"+namn.ident[i]+"} =";}
if(Math.abs(w) < Double.MIN_VALUE) {w = 0;} // no negative zero!
value = String.format(engl,"%7.2f",(float)w);
t = c + value;
if(volt) {t = t+" V";}
} //hur=4: "LA"
g.sym(headColumnX, yP, heightAx, t, 0f, -1, false);
} //for j
// ---- Ionic Strength
if(!Double.isNaN(diag.ionicStrength) &&
Math.abs(diag.ionicStrength) > 1.e-10) {
g.setLabel("-- Ionic Strength --");
g.setPen(-1);
yP = yP + 2f*heightAx;
headRow++;
if(headRow == headRowMax) {
headColumnX = headColumnX + (33f*heightAx);
yP = yMx + 3f*heightAx; // = yMx + 2.5f*heightAx in PREDOM
}
if(yP > (yPMx + 0.1f*heightAx)) {headColumnX = (0.5f*heightAx); yPMx = yP;}
if(diag.ionicStrength > 0) {
t = String.format(engl,"I=%6.3f "+cUnit,diag.ionicStrength);
} else {t = "I= varied";}
g.sym(headColumnX, yP, heightAx, t, 0, -1, false);
} // if ionicStrength != NaN & !=0
// ---- Temperature + Pressure (in the heading)
if(!Double.isNaN(diag.temperature)) {
if(Double.isNaN(diag.pressure) || diag.pressure < 1.02) {
g.setLabel("-- Temperature --");
} else {g.setLabel("-- Temperature and Pressure --");}
g.setPen(-1);
t = String.format(engl,"t=%3d~C",Math.round((float)diag.temperature));
if(!Double.isNaN(diag.pressure) && diag.pressure > 1.02) {
if(diag.pressure < 220.64) {
t = t + String.format(java.util.Locale.ENGLISH,", p=%.2f bar",diag.pressure);
} else {
if(diag.pressure <= 500) {t = t + String.format(", p=%.0f bar",diag.pressure);}
else {t = t + String.format(java.util.Locale.ENGLISH,", p=%.1f kbar",(diag.pressure/1000.));}
}
}
yP = yP + 2f*heightAx;
headRow++;
if(headRow == headRowMax) {
headColumnX = headColumnX + (33f*heightAx);
yP = yMx + 3f*heightAx; // = yMx + 2.5f*heightAx in PREDOM
}
if(yP > (yPMx + 0.1f*heightAx)) {headColumnX = (0.5f*heightAx); yPMx = yP;}
g.sym(headColumnX, yP, heightAx, t, 0, -1, false);
} //if temperature >0
// ---- Title
if(diag.title != null && diag.title.trim().length() > 0) {
g.setLabel("-- TITLE --");
g.setPen(2); g.setPen(-2);
g.sym(0, yPMx+(3.5f*heightAx), heightAx, diag.title, 0, -1, false);
} // plotTitle != null
// -------------------------------------------------------------------
// Finished
g.end();
} //drawPlot()
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="double2String">
/** Returns a text representing a double in the format
* 1.23×10'-1`.
* @param d
* @return a string such as 1.23×10'-1`
*/
private static String double2String(double d) {
if(Double.isNaN(d) || Double.isInfinite(d)) {return String.valueOf(d);}
if(d == 0) {return "0.00";}
boolean ok = true;
// txt = number_in_scientific_notation
final String txt = String.format(engl,"%10.2e",d).trim();
int e = txt.indexOf('e');
String exp = "", sign="";
if(e >= 0) {
exp = txt.substring(e+1);
final int length =exp.length();
if(length > 1) {
int i, j;
sign = exp.substring(0,1);
if(sign.equals("+") || sign.equals("-")) {j=1;} else {j=0; sign="";}
if(length > j+1) {
for (i = j; i < length-1; i++) {
if (exp.charAt(i) != '0') {break;}
}
exp = exp.substring(i);
} else {ok = false;}
} else {ok = false;}
} else {
ok = false;
}
int k;
try{k = Integer.parseInt(exp);} catch (Exception ex) {
System.err.println(ex.getMessage());
k=0;
ok = false;
}
if(ok && k == 0) {return txt.substring(0, e);}
if(ok && exp.length() >0) {
return txt.substring(0, e)+"×10'"+sign+exp+"`";
} else {return txt;}
}
//</editor-fold>
}// class Plot
| 38,061 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
Debugging.java | /FileExtraction/Java_unseen/ignasi-p_eq-diagr/SED/src/simpleEquilibriumDiagrams/Debugging.java | package simpleEquilibriumDiagrams;
import lib.kemi.chem.Chem;
/** Display a dialog to choose level of debug-printout.
* <br>
* Copyright (C) 2014-2020 I.Puigdomenech.
*
* 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
* 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/
*
* @author Ignasi Puigdomenech */
public class Debugging extends javax.swing.JDialog {
private boolean finished = false;
private final SED sed;
private final java.awt.Dimension windowSize;
/** Where errors will be printed. It may be <code>System.err</code>.
* If null, <code>System.err</code> is used. */
private final java.io.PrintStream err;
/** New-line character(s) to substitute "\n" */
private static final String nl = System.getProperty("line.separator");
/** Creates new form Debugging
* @param parent
* @param modal
* @param sed0
* @param err0 */
public Debugging(java.awt.Frame parent, boolean modal, SED sed0, java.io.PrintStream err0) {
super(parent, modal);
if(err0 != null) {this.err = err0;} else {this.err = System.err;}
initComponents();
this.sed = sed0;
finished = false;
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
//--- Close window on ESC key
javax.swing.KeyStroke escKeyStroke = javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE,0, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escKeyStroke,"ESCAPE");
javax.swing.Action escAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
closeWindow();
}};
getRootPane().getActionMap().put("ESCAPE", escAction);
//--- Alt-Q quit
javax.swing.KeyStroke altQKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altQKeyStroke,"ALT_Q");
getRootPane().getActionMap().put("ALT_Q", escAction);
//--- Alt-X eXit
javax.swing.KeyStroke altXKeyStroke = javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK, false);
getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(altXKeyStroke,"ALT_X");
javax.swing.Action altXAction = new javax.swing.AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) {
jButtonOK.doClick();
}};
getRootPane().getActionMap().put("ALT_X", altXAction);
//---- forward/backwards arrow keys
java.util.Set<java.awt.AWTKeyStroke> keys = getFocusTraversalKeys(java.awt.KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS);
java.util.Set<java.awt.AWTKeyStroke> newKeys = new java.util.HashSet<java.awt.AWTKeyStroke>(keys);
newKeys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_RIGHT, 0));
//newKeys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_DOWN, 0));
setFocusTraversalKeys(java.awt.KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,newKeys);
keys = getFocusTraversalKeys(java.awt.KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS);
newKeys = new java.util.HashSet<java.awt.AWTKeyStroke>(keys);
newKeys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_LEFT, 0));
//newKeys.add(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_UP, 0));
setFocusTraversalKeys(java.awt.KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,newKeys);
//--- Title, etc
//getContentPane().setBackground(new java.awt.Color(255, 255, 153));
this.setTitle(" "+SED.progName+": Debugging in HaltaFall");
// Centre the window on the screen
int left = Math.max(0,(SED.screenSize.width-this.getWidth())/2);
int top = Math.max(0,(SED.screenSize.height-this.getHeight())/2);
this.setLocation(Math.min(SED.screenSize.width-100, left),
Math.min(SED.screenSize.height-100, top));
windowSize = this.getSize();
// debugging in HaltaFall
int calcDbgHalta = Math.max(0, Math.min(jComboBoxDbgH.getItemCount()-1,sed.dbgHalta));
jComboBoxDbgH.setSelectedIndex(calcDbgHalta);
jLabel1.setToolTipText("Default value = "+Chem.DBGHALTA_DEF);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jComboBoxDbgH = new javax.swing.JComboBox();
jLabel2 = new javax.swing.JLabel();
jButtonOK = new javax.swing.JButton();
jButtonCancel = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel1.setText("<html>Select output level from HaltaFall</html>");
jComboBoxDbgH.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "0 - none", "1 - errors only", "2 - errors + results", "3 - errors + results + input", "4 = 3 + output from Fasta", "5 = 3 + output from activity coeffs.", "6 = 4 + lots of output" }));
jLabel2.setText("<html>Note: printout is <u>only</u> performed on<br> the first calculation point.</html>");
jButtonOK.setMnemonic('O');
jButtonOK.setText("OK");
jButtonOK.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonOK.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonOKActionPerformed(evt);
}
});
jButtonCancel.setMnemonic('c');
jButtonCancel.setText("Cancel");
jButtonCancel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonCancelActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jComboBoxDbgH, 0, 284, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(jButtonOK, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButtonCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBoxDbgH, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonOK)
.addComponent(jButtonCancel))
.addContainerGap(29, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButtonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOKActionPerformed
sed.dbgHalta = Integer.parseInt(jComboBoxDbgH.getSelectedItem().toString().substring(0,2).trim());
closeWindow();
}//GEN-LAST:event_jButtonOKActionPerformed
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
closeWindow();
}//GEN-LAST:event_formWindowClosing
private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
if(windowSize != null) {
int w = windowSize.width;
int h = windowSize.height;
if(this.getHeight()<h){this.setSize(this.getWidth(), h);}
if(this.getWidth()<w){this.setSize(w,this.getHeight());}
}
}//GEN-LAST:event_formComponentResized
private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelActionPerformed
closeWindow();
}//GEN-LAST:event_jButtonCancelActionPerformed
private void closeWindow() {
finished = true;
this.notify_All();
this.dispose();
} // closeWindow()
private synchronized void notify_All() {notifyAll();}
/** this method will wait for this dialog frame to be closed */
public synchronized void waitFor() {
while(!finished) {
try {wait();} catch (InterruptedException ex) {}
} // while
} // waitFor()
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButtonCancel;
private javax.swing.JButton jButtonOK;
private javax.swing.JComboBox jComboBoxDbgH;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
// End of variables declaration//GEN-END:variables
}
| 11,853 | Java | .java | ignasi-p/eq-diagr | 18 | 3 | 0 | 2018-08-17T08:25:37Z | 2023-04-30T09:33:35Z |
RSASignatureTransformer.java | /FileExtraction/Java_unseen/googleweb_power-rule-plugin/src/main/java/com/janetfilter/plugins/powerrule/RSASignatureTransformer.java | package com.janetfilter.plugins.powerrule;
import com.janetfilter.core.plugin.MyTransformer;
import jdk.internal.org.objectweb.asm.ClassReader;
import jdk.internal.org.objectweb.asm.ClassWriter;
import jdk.internal.org.objectweb.asm.Opcodes;
import jdk.internal.org.objectweb.asm.tree.*;
public class RSASignatureTransformer implements MyTransformer {
@Override
public String getHookClassName() {
return "sun/security/rsa/RSASignature";
}
@Override
public byte[] transform(String className, byte[] classBytes, int order) {
ClassReader reader = new ClassReader(classBytes);
ClassNode node = new ClassNode(Opcodes.ASM5);
reader.accept(node, 0);
for (MethodNode mn : node.methods) {
if (mn.name.equals("engineVerify") && mn.desc.equals("([B)Z")) {
InsnList instructions = mn.instructions;
for (int i = 0; i < instructions.size(); i++) {
if (instructions.get(i) instanceof MethodInsnNode && instructions.get(i + 1) instanceof VarInsnNode) {
MethodInsnNode methodInsnNode = (MethodInsnNode) instructions.get(i);
VarInsnNode varInsnNode = (VarInsnNode) instructions.get(i + 1);
if (methodInsnNode.owner.equals("sun/security/rsa/RSASignature") && methodInsnNode.name.equals("getDigestValue") && methodInsnNode.desc.equals("()[B") && varInsnNode.getOpcode() == Opcodes.ASTORE) {
InsnList list = new InsnList();
//函数入参
list.add(new VarInsnNode(Opcodes.ALOAD, 1));
//publicKey
list.add(new VarInsnNode(Opcodes.ALOAD, 0));
list.add(new FieldInsnNode(Opcodes.GETFIELD, "sun/security/rsa/RSASignature", "publicKey", "Ljava/security/interfaces/RSAPublicKey;"));
//getDigestValue,digest计算后的真实值
//先构造ASN.1格式数据
list.add(new VarInsnNode(Opcodes.ALOAD, 0));
list.add(new FieldInsnNode(Opcodes.GETFIELD, "sun/security/rsa/RSASignature", "digestOID", "Lsun/security/util/ObjectIdentifier;"));
list.add(new VarInsnNode(Opcodes.ALOAD, varInsnNode.var));
list.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "sun/security/rsa/RSASignature", "encodeSignature", "(Lsun/security/util/ObjectIdentifier;[B)[B", false));
//填充
list.add(new VarInsnNode(Opcodes.ALOAD, 0));
list.add(new FieldInsnNode(Opcodes.GETFIELD, "sun/security/rsa/RSASignature", "padding", "Lsun/security/rsa/RSAPadding;"));
list.add(new InsnNode(Opcodes.SWAP));
list.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "sun/security/rsa/RSAPadding", "pad", "([B)[B", false));
//传入以上三个参数
list.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "com/janetfilter/plugins/powerrule/RSASignatureFilter", "testFilter", "([BLjava/security/interfaces/RSAPublicKey;[B)V", false));
mn.instructions.insert(instructions.get(i + 1), list);
}
}
}
}
}
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
node.accept(writer);
return writer.toByteArray();
}
}
| 3,608 | Java | .java | googleweb/power-rule-plugin | 20 | 11 | 0 | 2022-01-16T13:45:22Z | 2022-01-16T13:52:25Z |
RSASignatureFilter.java | /FileExtraction/Java_unseen/googleweb_power-rule-plugin/src/main/java/com/janetfilter/plugins/powerrule/RSASignatureFilter.java | package com.janetfilter.plugins.powerrule;
import java.math.BigInteger;
import java.security.interfaces.RSAPublicKey;
public class RSASignatureFilter {
public static void testFilter(byte[] data, RSAPublicKey pub,byte[] result) {
System.out.println("\n\n\n\n-------power rule-------\n"+"EQUAL,"+new BigInteger(1,data)+","+pub.getPublicExponent()+","+pub.getModulus()+"->"+new BigInteger(1,result)+"\n------------------------\n\n\n\n");
}
}
| 457 | Java | .java | googleweb/power-rule-plugin | 20 | 11 | 0 | 2022-01-16T13:45:22Z | 2022-01-16T13:52:25Z |
PowerRule.java | /FileExtraction/Java_unseen/googleweb_power-rule-plugin/src/main/java/com/janetfilter/plugins/powerrule/PowerRule.java | package com.janetfilter.plugins.powerrule;
import com.janetfilter.core.plugin.MyTransformer;
import com.janetfilter.core.plugin.PluginEntry;
import java.util.ArrayList;
import java.util.List;
public class PowerRule implements PluginEntry {
private final List<MyTransformer> transformers = new ArrayList<>();
public PowerRule() {
transformers.add(new RSASignatureTransformer());
}
@Override
public String getName() {
return "PowerRule";
}
@Override
public String getAuthor() {
return "googleweb";
}
@Override
public String getVersion() {
return "v1.0";
}
@Override
public String getDescription() {
return "Generate result replcae rule for plugin-power";
}
@Override
public List<MyTransformer> getTransformers() {
return transformers;
}
}
| 866 | Java | .java | googleweb/power-rule-plugin | 20 | 11 | 0 | 2022-01-16T13:45:22Z | 2022-01-16T13:52:25Z |
ServiceExceptionTest.java | /FileExtraction/Java_unseen/alex73_Skarynka/test/org/alex73/skarynka/scan/ServiceExceptionTest.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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 org.alex73.skarynka.scan;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class ServiceExceptionTest {
@Test
public void check() {
String msg = new ServiceException("BOOK_OPEN", "aaaa", "bbbb").getMessage();
assertTrue(msg.contains("aaaa"));
assertTrue(msg.contains("bbbb"));
}
}
| 1,262 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
HIDDeviceTest.java | /FileExtraction/Java_unseen/alex73_Skarynka/test/org/alex73/skarynka/scan/hid/HIDDeviceTest.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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 org.alex73.skarynka.scan.hid;
import javax.usb.util.UsbUtil;
import org.alex73.skarynka.scan.hid.HIDScanController;
public class HIDDeviceTest {
public static void main(String[] args) throws Exception {
HIDScanController p = new HIDScanController("093a:2510", null);
byte[] buffer = new byte[UsbUtil
.unsignedInt(p.usbPipe.getUsbEndpoint().getUsbEndpointDescriptor().wMaxPacketSize())];
while (true) {
int length = p.usbPipe.syncSubmit(buffer);
if (length > 0 && buffer[0] > 0) {
System.out.println("HID Scan button #" + buffer[0]);
for(int i=0;i<length;i++) {
System.out.print(Integer.toHexString(buffer[i])+" ");
}
System.out.println();
}
}
}
}
| 1,746 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
Book2Test.java | /FileExtraction/Java_unseen/alex73_Skarynka/test/scan2/Book2Test.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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 scan2;
import org.alex73.skarynka.scan.Book2;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class Book2Test {
@Test
public void checkIncPage() {
assertEquals("00002", Book2.incPage("1", 1));
assertEquals("00003", Book2.incPage("1", 2));
assertEquals("00011", Book2.incPage("9", 2));
assertEquals("00002", Book2.incPage("5", -3));
assertEquals("", Book2.incPage("2", -3));
assertEquals("00001b", Book2.incPage("00001a", 1));
assertEquals("00001c", Book2.incPage("00001a", 2));
assertEquals("00001z", Book2.incPage("00001y", 1));
assertEquals("", Book2.incPage("00001a", -1));
assertEquals("00001a", Book2.incPage("1b", -1));
assertEquals("00001a", Book2.incPage("1d", -3));
assertEquals("00001ab", Book2.incPage("00001aa", 1));
assertEquals("00001ac", Book2.incPage("00001aa", 2));
assertEquals("00001ba", Book2.incPage("00001az", 1));
assertEquals("00001bb", Book2.incPage("00001az", 2));
assertEquals("00001mo", Book2.incPage("00001mn", 1));
assertEquals("00001zz", Book2.incPage("00001zy", 1));
assertEquals("", Book2.incPage("00001aa", -1));
assertEquals("00001ax", Book2.incPage("00001az", -2));
assertEquals("00001az", Book2.incPage("00001ba", -1));
assertEquals("00001ax", Book2.incPage("00001ba", -3));
assertEquals("", Book2.incPage("00001zy", 2));
}
@Test
public void checkIncPagePos() {
assertEquals("00002", Book2.incPagePos("1", false, 1));
assertEquals("00003", Book2.incPagePos("1", false, 2));
assertEquals("00011", Book2.incPagePos("9", false, 2));
assertEquals("00002", Book2.incPagePos("5", false, -3));
assertEquals("", Book2.incPagePos("2", false, -3));
assertEquals("00001b", Book2.incPagePos("00001a", true, 1));
assertEquals("00002a", Book2.incPagePos("00001a", false, 1));
assertEquals("00001c", Book2.incPagePos("00001a", true, 2));
assertEquals("00003a", Book2.incPagePos("00001a", false, 2));
assertEquals("00001z", Book2.incPagePos("00001y", true, 1));
assertEquals("", Book2.incPagePos("00001a", true, -1));
assertEquals("00001a", Book2.incPagePos("1b", true, -1));
assertEquals("00000a", Book2.incPagePos("1a", false, -1));
assertEquals("", Book2.incPagePos("1a", false, -2));
assertEquals("00001a", Book2.incPagePos("1d", true, -3));
assertEquals("00001ab", Book2.incPagePos("00001aa", true, 1));
assertEquals("00001ac", Book2.incPagePos("00001aa", true, 2));
assertEquals("00001ba", Book2.incPagePos("00001az", true, 1));
assertEquals("00001bb", Book2.incPagePos("00001az", true, 2));
assertEquals("00001mo", Book2.incPagePos("00001mn", true, 1));
assertEquals("00001zz", Book2.incPagePos("00001zy", true, 1));
assertEquals("", Book2.incPagePos("00001aa", true, -1));
assertEquals("00001ax", Book2.incPagePos("00001az", true, -2));
assertEquals("00001az", Book2.incPagePos("00001ba", true, -1));
assertEquals("00001ax", Book2.incPagePos("00001ba", true, -3));
assertEquals("", Book2.incPagePos("00001zy", true, 2));
}
}
| 4,211 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
ServiceException.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/ServiceException.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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 org.alex73.skarynka.scan;
import java.text.MessageFormat;
/**
* Known exception, that have localization in message bundle.
*
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
public class ServiceException extends RuntimeException {
public ServiceException(String errorCode) {
super(Messages.getString("ERROR_" + errorCode));
}
public ServiceException(String errorCode, String... params) {
super(MessageFormat.format(Messages.getString("ERROR_" + errorCode), (Object[]) params));
}
}
| 1,443 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
ActionErrorListener.java | /FileExtraction/Java_unseen/alex73_Skarynka/src/org/alex73/skarynka/scan/ActionErrorListener.java | /**************************************************************************
Skarynka - software for scan, process scanned images and build books
Copyright (C) 2016 Aleś Bułojčyk
This file is part of Skarynka.
Skarynka 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.
Skarynka 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 org.alex73.skarynka.scan;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import org.slf4j.Logger;
/**
* Action with error display on UI.
*
* @author Aleś Bułojčyk <alex73mail@gmail.com>
*/
public abstract class ActionErrorListener implements ActionListener {
private final Component parentComponent;
private final String messageKey;
private final Logger log;
private final String logMessage;
public ActionErrorListener(Component parentComponent, String messageKey, Logger log, String logMessage) {
this.parentComponent = parentComponent;
this.messageKey = messageKey;
this.log = log;
this.logMessage = logMessage;
}
abstract protected void action(ActionEvent e) throws Exception;
@Override
public void actionPerformed(ActionEvent e) {
try {
action(e);
} catch (Throwable ex) {
log.error(logMessage, ex);
JOptionPane.showMessageDialog(parentComponent,
Messages.getString(messageKey) + ": " + ex.getClass() + " / " + ex.getMessage(),
Messages.getString("ERROR_TITLE"), JOptionPane.ERROR_MESSAGE);
}
}
}
| 2,190 | Java | .java | alex73/Skarynka | 10 | 3 | 0 | 2016-03-25T16:46:26Z | 2022-11-30T19:00:14Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.