Frequently Used Java Commands: February 5, 2019 Native Java Documentation Integer
Frequently Used Java Commands: February 5, 2019 Native Java Documentation Integer
February 5, 2019
Integer
String str = Integer.toString(iValue);
int iValue = (Integer.valueOf(str)).intValue();
Double
String str = Double.toString(dValue);
double dValue = (Double.valueOf(str)).doubleValue();
String
Index Numbers
abcdefgh
012345678
Arrays
int iLength = iArray.length;
For Each
int[] iArray;
for (int iElement : iArray) {
System.out.println(iElement);
}
2
Vector
Vector<Class> vec = new Vector<Class>(); Class: String, Integer , etc
int iLocs = vec.size();
vec.removeAllElements();
vec.addElement(str);
String str = (String)vec.elementAt(iLocation);
vec.addElement(new Integer(iValue));
int iValue = ((Integer)(vec.elementAt(iLocation))).intValue();
List of Files
File f = new File(strDirectoryPath);
String[] strList = f.list(); // Includes all files in directory
String[] strList = f.list(new MyFilter); // Includes only “filtered” files
import java.io.FilenameFilter;
class MyFilter implements FilenameFilter {
public boolean accept(File fDirectory, String strFilename) {
if(…) return true;
return false;
}
}
Font (java.awt.Font)
Font fontNew = new Font(strFontName, iFontStyle, iSize)
strFontName = Font.DIALOG, Font.MONOSPACED, Font.SERIF, Font.SANS_SERIF, …
iFontStyle = Font.PLAIN, Font.BOLD, Font.ITALIC, …
Exceptions
Throw(new Exception(“Exception message.”));
String strMessage = exc.getMessage();
Focus
component.requestFocusInWindow();
Unicode Characters
char cUnicode = 0x00A9 // 00A9 is the Unicode copyright symbol
Colors
Color colorNew = new Color(0xFF0000) // FF0000 is the red hex spec
3
getInformation();
.
.
return information;
JList
JList<Class> list = new JList<Class>(); Class: String, Integer, …
list.setListData(Object[]);
list.setListData(Vector);
list.setListData(new Vector()) // clears list
list.setVisibleRowCount(iRows);
list.setSelectedIndex(iIndex);
list.setSelectedValue(“Value”), true); // true allows scrolling
int iIndex = list.getSelectedIndex();
str strEntry = (String)list.getSelectedValue(); // null if none selected
boolean3sum = (list.getModel()).getSize();
str strIndex = (String)(list.getModel()).getElementAt(iIndex);
JComboBox
JComboBox<Class> list = new JComboBox<Class>(); Class: String, Integer, …
jComboBox.addItem(iValue);
jComboBox.setSelectedIndex(iIndex)
jComboBox.getSelectedIndex()
jComboBox.addItem(str);
jComboBox.setSelectedItem(str);
str = (String) jComboBox.getSelectedItem();
Unicode
char cUnicode = 0x____;
Tuples
See TestTuple.java.
4
JProgressBar
private void startTask() { // Call by the action button or whatever
// Set progress bar parameters
progressBar.setMaximum(100);
progressBar.setValue(0);
progressBar.setStringPainted(true); // Print text or percent completed
TaskInnerClass task = new TaskInnerClass();
textPane = new JTextPaneOutput(scrollPane_1);
task.start();
}
class TaskInnerClass extends Thread {
public void run() {
progressBar.setVisible(true);
runTask();
progressBar.setVisible(false);
}
}
private void runTask() {
progressBar.setValue(iIteration)
progressBar.setString(str); // Print str rather than percent completed
// Do the work
}
JFileChooserFilters
fcc.setFileFilter(new SpecialFileFilter());
}
}
ButtonGroup
ButtonGroup bg = new ButtonGroup();
bg.add(jButton);
Scrolling
Swing Containers: JScrollPane
Put component in the JScrollPane
5
Callbacks
// Specific method calls a general purpose method
// General purpose method needs info that is specific to the specific class
interface CallBackInterface {
public xxxx interfaceMethod(…); // “Placemark” for interface method
}
// Define interface method that provides interface info that is specific to this class
public xxxx interfaceMethod(…) {
// Code that is called by calling class
.
.
.
return vbl;
}
public specificMethodThatCallsGeneralPurposeMethod(…) {
GeneralPurposeClass generalPurposeClass = new GeneralPurposeClass(…);
generalPurposeClass.generalPurposeMethod(this, …);
}
}
class GeneralPurposeClass {
public xxxx generalPurposeMethod (CallBackInterface cbi, …) {
xxxx vbl = cbi.interfaceMethod(); // Get vbl info from interfaceMethod()
.
.
.
}
}
Interfaces
// Interface file
public interface InterfaceName
{
public xxxx interfaceMethod(…); // “Placeholder” for interface method
}
// The root class calls the interface method either in ClassToBeCallled1 or ClassToBeCalled2
Class RootClass
InterfaceName inter = new ClassToBeCalled1 or ClassToBeCalled2
inter.interfaceMethod(…);
Abstract Classes
class CallingClass {
ClassAbstract classabs;
classabs.methodabstract()
System
System.out.print(str);
System.out.println(str);
System.getProperty(str)
java.version Java Runtime Environment version
java.vendor Java Runtime Environment vendor
java.vendor.url Java vendor URL
java.home Java installation directory
java.vm.specification.version Java Virtual Machine specification version
java.vm.specification.vendor Java Virtual Machine specification vendor
java.vm.specification.name Java Virtual Machine specification name
java.vm.version Java Virtual Machine implementation version
java.vm.vendor Java Virtual Machine implementation vendor
java.vm.name Java Virtual Machine implementation name
java.specification.version Java Runtime Environment specification version
java.specification.vendor Java Runtime Environment specification vendor
java.specification.name Java Runtime Environment specification name
java.class.version Java class format version number
java.class.path Java class path
java.library.path List of paths to search when loading libraries
java.io.tmpdir Default temp file path
java.compiler Name of JIT compiler to use
java.ext.dirs Path of extension directory or directories
os.name Operating system name
os.arch Operating system architecture
os.version Operating system version
file.separator File separator ("/" on UNIX)
path.separator Path separator (":" on UNIX)
line.separator Line separator ("\n" on UNIX)
user.name User's account name
user.home User's home directory
user.dir User's current working directory
Terminating a Process
System.exit(iErrorCode) // Typically, iErrorCode = 0.
8
FW Library Documentation
(FW) ConvertString
String[] ConvertString.toString(str, strDelimiter);
int[] ConvertString.toInteger(str, strDelimiter);
double[] ConvertString.toDouble(str, strDelimiter);
boolean[] ConvertString.toBoolean(str, strDelimiter); // strDelimiter: add + to eliminate empty cells
double[] ConvertString.stripComment(str[]);
double ConvertString.stripComment(str);
String ConvertString.clean(str);
String ConvertString.substring(str, iBegin, iEnd)
(FW) ConvertStringToArray
String[] ConvertStringToArray.toString(strSource);
String[] ConvertStringToArray.toString(strSource, strDelimitor);
int[] ConvertStringToArray.toInteger(strSource);
int[] ConvertStringToArray.toInteger(strSource, strDelimitor);
double[] ConvertStringToArray.toDouble(strSource);
double[] ConvertStringToArray.toDouble(strSource, strDelimitor);
(FW) FormattedOutput
String FormattedOutput.encode(iValue [,strAllign, iLength]);
String FormattedOutput.encode(dValue, iLength);
String FormattedOutput.encode(dValue, strAllign, iLength, iDecimals);
String FormattedOutput.encode(iBlanks);
String FormattedOutput.insertCommas(str);
String FormattedOutput.encodeDollarsAndCents(dValue [,strAllign, iLength]);
(FW) JavaMail
JavaMail(strMailServer, strSender, strAddressee, strMessage) throws Exception
boolean isMailOK();
(FW) Clipboard
Clipboard.setText(this, str);
String Clipboard.getText(this);
(FW) JWindowUtility
JWindowUtility.center(parentWindow, window);
JWindowUtility.center(window);
JWindowUtility.resizeForInsets(window);
boolean JWindowUtility.resizeComponent(jComponent, bWidth, bHeight);
String JWindowUtility.getMyDocumentsPath(strDirectory);
String JWindowUtility.getMyDocumentsPath();
String JWindowUtility.constructTitle(strModule, strVersion, strFilename);
String JWindowUtility.constructTitle(strModule, strVersion);
9
(FW) DateTimeAux
long lTime = DateTimeAux.getTime(); // Get current time
long lTime = DateTimeAux.getTime(lMilliSeconds);
long lTime = DateTimeAux.getTime(iYear, iMonth, iDay, iHour, iMinute, iSecond) ;
str = DateTimeAux.formatDate(lMilliSeconds);
str = DateTimeAux.formatDate(lMilliSeconds, strSeparator);
str = DateTimeAux.formatTime(lMilliSeconds);
str = DateTimeAux.formatTime(lMilliSeconds, strSeparator);
int[] = DateTimeAux.getDate(lMilliSeconds);
int[] = DateTimeAux.getDateAndTime(lMilliSeconds);
int = DateTimeAux.getDayOfWeek(lMilliSeconds);
(FW) Sorters
void Sorters.sortArray(strArray);
void Sorters.sortArray(iArray);
void Sorters.sortArray(lArray);
void Sorters.sortArray(dArray);
int[] Sorters.sortArrayIndices(strArray);
int[] Sorters.sortArrayIndices(iArray);
int[] Sorters.sortArrayIndices(lArray);
int[] Sorters.sortArrayIndices(dArray);
(FW) JQueryBox
JQueryBox qb = new JQueryBox(strTitle, strMessage, strLabel);
JQueryBox qb = new JQueryBox(strTitle, strMessage, strLabelArray);
qb.isButton(strLabel);
qb.dispose();
10
(FW) JTextPaneOutput
JtextPaneOutput jTextPane = new JtextPaneOutput(jScrollPane);
jTextPaneOutput.setText(str);
jTextPaneOutput.append(str);
jTextPaneOutput.clearAttributes();
jTextPaneOutput.setForegroundColor(c);
jTextPaneOutput.setBold(bool);
jTextPaneOutput.setItalics(bool);
jTextPaneOutput.setUnderline(bool);
jTextPaneOutput.setSubscript(bool);
jTextPaneOutput.setSuperscript(bool)
jTextPaneOutput.setTab(int);
jTextPaneOutput.setTabs(int[]);
jTextPaneOutput.setTabs(int[], strAlign[]); // strAlign “l”, “r”, “c”, “d”
jTextPaneOutput.setLeftIndent(int)
jTextPaneOutput.setAlignment(strAlign); // strAlign “l”, “r”, “c”, “d”
11
(FW) JGraph
JGraph graph = new JGraph(label, strAxisRange, strAxisNames, strAxisNumericalLabels);
strAxisRange = XMin YMin XMax YMax [XLabelDisplayFactor YLabelDisplayFactor]
strAxisNames = “XName YName”;
strAxisNumericalLabels = “ T/F T/F”;
JGraph graph = new JGraph(label, strAxisRange);
drawAxes();
setFontName(strFontName);
setFontColor(color);
setFontSize(iFontSize);
drawString(str, dX, dY, cPosition [, iFontSize, color]);
cPosition
U or ^: above and center horizontally
D or _: below and center horizontally
L or <: left and center vertically
R or >: right and center vertically
blank: right and no centering
getStringHeight(str);
getStringWidth(str);
double[] getMouseXYCoordinates();
Use WindowBuilder to add a motion listener to graph label;
then add call to getMouseXYCoordinates() to get mouse coordinates:
label.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseXXXX(MouseEvent e) { // XXXX: Dragged, Pressed, …
dMouseXYCoordinates = graph.getMouseXYCoordinates();
}
});
12
(FW) JWebCopyUtility
JWebCopyUtility(progressbar)
copyFile(strUrlPath, strPCPath)
13
String getDocumentsPath()
String getDocumentsPath(strDirectory)
String correctFileSeparator(strFilePath)
String[] getFileDirectoryNameExtension(strFilePath)
String getFileDirectory(strFilePath)
String getFileName(strFilePath)
String getFileExtension(strFilePath)
boolean existsFile(strFilePath)
boolean existsDirectory(strDirectoryPath)
long lastModified(strFilePath)
void setLastModified(strFilePath, lDate)
boolean createDirectory(strDirectory)
boolean removeDirectoryTree(strDirectory)
boolean removeDirectory(strDirectory)
String[] getListOfFiles(strDirectory)
String[] getListOfDirectories(strDirectory)
String stripAndAppendSeparator(str)
String appendSeparator(str)
String stripSeparator(str)
String abbreviateFilePathName(strFilePathName)
14
String str;
while( (str = far.readLine()) != null) {
// process
}
far.close();
}
catch (Exception e) {
String str = e.toString() ;
}
faw.println(str);
faw.flush();
faw.close();
}
double[] dVector;
fow.writeObject(dVector);
String[][] strArray;
fow.writeObject(String[][]);
fow.flush();
fow.close();
}
15
frrw.writeInt(iValue);
frrw.writeDouble(dValue);
frrw.write(bArray);
frrw.writeUTF(str)
frrw.writeBoolean(bValue);
}
16
(FW) JFileChooserCheckApplication1
JFileChooserCheckApplication fcca = new JFileChooserCheckApplication();
JFileChooserCheckApplication fcca = new JFileChooserCheckApplication(strExtension);
JFileChooserCheckApplication fcca = new JFileChooserCheckApplication(strExtensionArray);
fcca.setMultiSelection(b);
String[] = fcca.getFilePaths(b); // String.length = 0 if no file selected
String fcca.getFileName();
String fcca.getTitle(strTitle);
boolean fcca.isApplication();
(FW) JFileChooserCheckApplet
JFileChooserCheckApplet fcca =
new JFileChooserCheckApplet(strWebLocation, strDirectoryFileName);
strWebLocation = http://....
strDirectoryFileName:
Description for File 1 File1Name.Ext
Description for File 2 File2Name.Ext
String fcca.getFileName();
String fcca.getTitle(strTitle);
boolean fcca.isApplication();
1
Swing: (FW) JFileChooserCheck (Used by JFileChooserApplication)
JFileChooserCheck fcc = new JFileChooserCheck();
JFileChooserCheck fcc = new JFileChooserCheck(bMustExist);
JFileChooserCheck fcc = new JFileChooserCheck(bMustExist, strExtension);
JFileChooserCheck fcc = new JFileChooserCheck(bMustExist, strExtensionArray);
fcc.setTitle(strTitle);
fcc.setFileExtension(strExtension);
fcc.setFileExtension(strExtensionArray);
fcc.setFileMustExist(bMustExist);
fcc.setVisible(true/false);
String fcc.getFilePath();
String fcc.getFileDirectory();
String fcc.getFileName();
String fcc.getFileExtension();
17
(FW) JSpreadSheet
Column and Row Notation
strColumnNames[0] strColumnNames[1] strColumnNames[2] …
strArray[0][0] strArray[0][1] strArray[0][2] …
strArray[1][0] strArray[1][1] strArray[1][2] …
strArray[2][0] strArray[2][1] strArray[2][2] …
If there are row names, the first strArray column, strArray[i][0], contains the names.
Constructors: Two types – one for separate column names and array and one for entire spreadsheet
JSpreadSheet ss =
// Separate column names and data
JSpreadSheet(this, JScrollPane scrollPane, String[][] strArray, String[] strColumnNames,
boolean bLockFirstColumn, boolean[][] bCellEditable)
JSpreadSheet(this, JScrollPane scrollPane, String[][] strArray, String[] strColumnNames,
boolean bLockFirstColumn)
// NB: All strArray cells will be editable.
JSpreadSheet(this, JScrollPane scrollPane, String[][] strArray, String[] strColumnNames)
// NB: All strArray cells will be editable and first column is locked.
// Interface routine:
public boolean isCellChangeValid(int iRow, int iColumn, String str) {
// When appropriate, use ss.isDouble() to check for valid entry.
..
.
}
// Auxillary routines:
ss.flush(); // Called to flush out last spread sheet entry
ss.isDouble(); // Used by isCellChangeValid to check for valid entry
ss.getDouble();
ss.clearSpreadSheet();
18
(FW) FixedPointsIntegerDialog
// Interface routines:
public void getMappedPoint() {
..
.
}
public String getSummaryText() {
return null; for the default summary
..
.
19
(FW) SimulationThread
class MyParent
// To set initial text, visibility, and enabling of buttons, checkbox, and label
// call this in the addNotify() method:
SimulationThread(Jbutton jButtonStartContinue, Jbutton jButtonStop,
JcheckBox jCheckBoxPause, Jlabel jLabelRepetitions);
super.setInterface(this);
..
.
}
// Auxillary routines:
super.startSimulation();
super.stopSimulation();
// Interface routines:
public void runOneRepetition() {
..
.
}
public void reportResults() {
..
.
}
20
(FW) FileManagement
class MyParentFrame implements JFileManagementInterface
Create the following:
• File JMenuBar, JMenu, JMenuItem
• The following menu items: New, Open, Save, SaveAs, and Close
NB: Typically, you want to pass the data entry class (e.g., the class that contains the
spread sheet to that this class can have access to the data.
// Interface routines:
public void initializeFile() { // Sets up and initializes the data classes
..
.
}
public void readFile() {
..
.
}
public void writeFile() {
..
.
}
public void clearFile() { // Don’t know what this does
..
.
}
JEconLabUtility
(FW) JEconLabUtility.JEconLabSlider
class JEconLabUtility econLabUtility = new JEconLabUtility();
JEconLabUtility.JEconLabSlider slider = econLabUtility.new JEconLabSlider(scrollbar [, label, strPrefix])
init(strSpecs)
init(strSpecs, strPrefix) // strSpecs = “minimum maximum iteration default”
setSliderMinimum(strMinimum)
setSliderMinimum(strMaximum)
setSliderMinimum(strIncrement)
setSliderMinimum(strDefault)
setSliderPrefix(strPrefix)
setSliderDecimals(iDecimals)
setSliderVisible(bIsVisible)
setSliderValue(dValue)
getSliderInteger()
getSliderDouble()
getSliderString()
getSliderMinimum()
getSliderMaximum()
getSliderIncrement()
getSliderDefault()
isSliderValueEqual(dValue)
isSliderVisible()
updateSliderValue()
(FW) JEconLabUtility.JEconLabSearch
class JEconLabUtility econLabUtility = new JEconLabUtility();
JEconLabUtility.JEconLabSearch search = econLabUtility.new JEconLabSearch(sliderSearch
[, labelSearch, strSearchMessages])
init(strSearchMessages)
isSliderValueOptimal(dOptimalValue)
(FW) JEconLabUtility.JEconLabSearch
class JEconLabUtility econLabUtility = new JEconLabUtility();
JEconLabUtility.JEconLabSearch search = econLabUtility.new JEconLabSearch(sliderSearch
[, labelSearch, strSearchMessages])
init(strSearchMessages)
isSliderValueOptimal(dOptimalValue)
(FW) JEconLabUtility.JEconLabButtonGroup
class JEconLabUtility econLabUtility = new JEconLabUtility();
JEconLabUtility.JEconLabButtonGroup econLabButtonGroup =
econLabUtility.new JEconLabButtonGroup (buttonGroup);
updateButtonGroup(buttonSelected);
22
double[] JEconLabUtility.JEconLabElasticityUtility.ConvertElasticityToFunctionConstantAndSlope(
dElasticity, dQuantity, dPrice);
double[] JEconLabUtility.JEconLabElasticityUtility. ConvertElasticityToCurveInteceptAndSlope(
dElasticity, dQuantity, dPrice);
double[] JEconLabUtility.JEconLabDemandFunctionAndCurveUtility.calDemandFunctionConstantAndSlope(
dDemandCurveIntercept, dDemandCurveSlope)
Creating a project:
• Toolbar Menu: New icon’s drop down list (not the icon itself) – Java Project
• Specify the name of the project.
• Finish
Creating a panel
• Apparently the WindowBuilder Designer does not work properly until one component has been
attached to the contentPane “by hand.” So, use the JPanelTemplate.java in the subdirectory
eclipse\Templates which includes btnDummy which can be deleted later.
Displaying panels
• Window (menu item) - Show View (drop down box)
Accessing WindowBuilder
• Right click Java file
• Open Java file - Open With – WindowBuilder Editor
Create a Runnable Jar Application File and an Ant file: Produces a jar file that can be run as an
application or applet and an ANT file which can be used in the future to create the jar file.
• Highlight the “root” file for the application.
• File (menu item): Select Export
• Export window: Select Runnable JAR file
• Runnable JAR File Export window: NB: Be careful to specify the correct Launch
configuration, Export destination, and ANT script location. Eclipse saves the last ones so if
you are creating a new jar file you must change all three.
o Launch configuration: Select
o Export destination: Click Browse
o Library handling: Select “Extract required …”
o Save as ANT script: Check
o ANT script location: Click Browse
• Finish
Create a Runnable Jar Application File from an Ant file: Produces a jar file that can be run as an
application or applet
• In Eclipse, Right click the ANT file which has an xml extension.
• Click Run As
• Click 1 Ant Build
Jar Creation Xml Ant files do not appear in Eclipse’s Project Explorer
• In Window’s Explorer, cut the files and paste to somewhere else.
• Cut the files from where they were pasted.
• In Eclipse, paste them to the appropriate project.
Launch Configurations
• To determine which launch configuration an application is using:
o Run the application.
o Click Run in the Eclipse menu and then click Run Launch Configuration.
o The launch configuration used will be lightly highlighted.
• To determine if a launch configuration is being used by some application
o Click Run in the Eclipse menu and then click Run Launch Configuration.
o Double click on the launch configuration in question.
o If the launch configuration is being used, the application will run; otherwise and
error ensues.