Frequently Used Java Commands - Amherst
[Pages:32]Frequently Used Java Commands
January 1, 2023
Native Java Documentation
Integer String str = Integer.toString(iValue); String str = Integer.toHexString(iValue); int iValue = (Integer.valueOf(str));
Double String str = Double.toString(dValue); double dValue = Double.valueOf(str);
String String substr = str.substring(iBegin,iEnd); String substr = str.substring(iBegin);
int indexMatch = str.indexOf(strFind); int indexMatch = str.lastIndexOf(strFind);
int iLength = str.length();
boolean bMatch = str.equals(strCompare);
Arrays int iLength = iArray.length;
ClassName[] classArray = new ClassName[nClasses]; classArray[0] = new ClassName(); classArray[1] = new ClassName();
int[] iArray = new int[nLocs]; int[] iArray = {0,1,2};
int[][] iMatrix = new int[nLocsFirst][]; iMatrix[0] = new int[nLocs0]; iMatrix[1] = new int[nLocs1];
For Each int[] iArray; for (int iElement : iArray) { System.out.println(iElement); }
Array Copy System.arraycopy(strSrc[], iSrcElement, strDest[], iDestElement, iLength);
Tuples Create a class that includes all variables as globals. The constructor stores the variables and then gets retrive them. See TestTuple.java in the TestProgramming package.
Parameterizing Raw to Generic Type Vector vecName = new Vector(); JList listName = new JList();
2
Vector Vector vec = new Vector(); 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();
ClassName c = new ClassName(); v.addElement(c); ClassName c = (ClassName)(v.elementAt(iLocation));
Exceptions Throw(new Exception("Exception message.")); String strMessage = exc.getMessage();
WWW File Names String strFileName = "";
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, ...
Unicode Characters
char cUnicode = 0x00A9
// 00A9 is the Unicode copyright symbol
String strUnicode = String.valueOf(cUnicode);
Colors Color colorRed = Color.red; Color colorNew = new Color(0xFF0000)
// FF0000 is the red hex spec
Detecting "Special" Keys addMouseListener(new MouseAdapter() { public void mouse Released(MouseEvent e) { e.isControlDown(), e.isAltDown(), e.isMetaDown(), e.isShiftDown() } }
Catching Key Strokes public void jListPlayers_keyReleased(KeyEvent e) { int iKeyCode = e.getKeyCode(); if(iKeyCode == KeyEvent.VK_UP || iKeyCode == KeyEvent.VK_DOWN) {
} }
3
JFrame setAlwaysOnTop(boolean); setUndocorated(boolean);
JDialog ? Modal Mode setModal(true); setVisible(true);
// false: Prevent return until closed setVisible(false)
JList
JList list = new JList(); list.setListData(Object[]); list.setListData(Vector); list.setListData(new Vector())
Class: String, Integer, ... // clears list
list.setVisibleRowCount(iRows);
list.setSelectedIndex(iIndex); list.setSelectedValue("Value"), true); int iIndex = list.getSelectedIndex(); str strEntry = (String)list.getSelectedValue();
// true allows scrolling // null if none selected
boolean3sum = (list.getModel()).getSize(); str strIndex = (String)(list.getModel()).getElementAt(iIndex);
JComboBox JComboBox comboBox = new JComboBox();
Class: String, Integer, ...
comboBox.addItem(iValue); comboBox.setSelectedIndex(iIndex) comboBox.getSelectedIndex()
comboBox.addItem(str); comboBox.setSelectedItem(str); str = (String) comboBox.getSelectedItem();
JComponent (JLabels, etc.) component.setForeground(color);
component.setBackground(color);
component.setOpaque(true);
// This is necessary and can be done in the constructor
Border border = BorderFactory.createLineBorder(color, iWidth); component.setBorder(border);
JCheckBox itemStateChanged(): Captures a checkbox click (Others don't do so as effectively)
JTable: See JTableAux
4
JProgressBar
private void startTask() {
// Call by the action button or whatever
// Set progress bar parameters
progressBar.setMaximum(100);
progressBar.setValue(0);
progressBar.setStringPainted(boolean); // true: Print; false: Print nothing
TaskInnerClass task = new TaskInnerClass();
task.start();
}
private void runTask() {
progressBar.setValue(iIteration)
progressBar.setString(str);
// If null, prints percent complete
// Do the work
}
class TaskInnerClass extends Thread { public void run() { progressBar.setVisible(true); runTask(); progressBar.setVisible(false); }
}
JFileChooserFilters fcc.setFileFilter(new SpecialFileFilter());
class MySpecialFileFilter extends javax.swing.filechooser.FileFilter { public String getDescription() { return "Special files(*.*)"; } public boolean accept(File f) { String str = f.getName(); if(str.indexOf("~") < 0) return true; return false; }
ButtonGroup ButtonGroup bg = new ButtonGroup(); bg.add(jButton);
In Eclipse: Right click on button in the design window.
Scrolling Swing Containers: JScrollPane Put component in the JScrollPane
Focus component.requestFocus(); component.requestFocusInWindow();
5
Abstract Classes class CallingClass { ClassAbstract classAbstract;
classAbstract = new ClassGeneric1(); or classAbstract = new ClassGeneric2();
classAbstract.methodAbstract () }
public abstract class ClassAbstract { abstract xxxx methodAbstract();
}
public class ClassGeneric1 extends ClassAbstract { public xxxx methodAbstract() { }
} public class ClassGeneric2 extends ClassAbstract {
public xxxx methodAbstract() { } }
Interfaces CallingClass.java class CallingClass implements ImplementedClass Interface { // Calling class must include the methods specified in ImplementedClassInterface.java : public void requiredInterfaceMethod1(...) { ... } public void requiredInterfaceMethod2(...){ ... }
// When created, the class ImplementedClass constructor must include "this" in its // argument list to connect CallingClass to ImplementedClass
Impl...ementedClass implementedClass = new ImplementedClass (this, ...); }
ImplementedClass.java class ImplementedClass { ImplementedClassInterface inter;
ImplementedClass(ImplementedClassInterface inter, ...) {
this.i...nter = inter;
// Save CallingClass location
}
inter.requiredInterfaceMethod1(...); inter.requiredInterfaceMethod2(...); }
// Return to CallingClass // Return to CallingClass
ImplementedClassInterface.java public interface ImplementedClassInterface { public void requiredInterfaceMethod1(...); public vo...id requiredInterfaceMethod2(...); }
6
Inner and Static Nested Classes TestMainClass testMainClass = new TestMainClass(); TestMainClass.TestInnerClass testInnerClass = testMainClass.new TestInnerClass(); System.out.println(testInnerClass.subroutine()); System.out.println(TestMainClass.TestStaticNestedClass.subroutine());
public class TestMainClass { public class TestInnerClass { public String subroutine() { return "TestInnerClass: subroutine()"; }
}
public static class TestStaticNestedClass { public static String subroutine() { return "TestStaticNestedClass: subroutine()"; }
} }
addNotify() Some operations cannot be completed in the constructor and an error results. To resolve this use the following code and implement the operations there (See CadView.java for implementation):
boolean bFirst = true; public void addNotify() {
super.addNotify(); if (bFirst) {
//viewGraph.setGraphDefaults();
bFirst = false; } }
7
Mouse Listener gLabel.addMouseListener(new MouseAdapter() { public void mouseExited(MouseEvent event) { Insert code here; }
public void mouseReleased(MouseEvent event) { Insert code here;
}
public void mousePressed(MouseEvent event) { Insert code here;
} });
Determine which mouse button: bRightButton = SwingUtilities.isRightMouseButton(event);
Mouse Motion Listener gLabel.addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent event) { Insert code here; }
public void mouseMoved(MouseEvent event) { Insert code here;
} });
Mouse Event Information Mouse button bRightButton = SwingUtilities.isRightMouseButton(event);
Mouse location iX = event.getX(); iY = event.getY();
Component Listerners component.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { Insert code here; } });
component.addFocusListener(new FocusAdapter() { public void focusGained(FocusEvent e) { Insert code here; }
});
component.addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) { Insert code here; }
});
8
List of Files File f = new File(strDirectoryPath); String[] strList = f.list(); String[] strList = f.list(new MyFilter);
// Includes all files in directory // Includes only "filtered" files
import java.io.FilenameFilter; class MyFilter implements FilenameFilter {
public boolean accept(File fDirectory, String strFilename) { if(...) return true; return false;
} }
Window Closing Action setDefaultCloseOperation(...); EXIT_ON_CLOSE HIDE_ON_CLOSE DISPOSE_ON_CLOSE DO_NOTHING_ON_CLOSE
// Catch closing setDefaul...tCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) { Insert code here.
} });
Convert String to Array strArray[] strArray = str.split(" ");
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related download
- java syntax examples tutorial kart
- structural testing white box exercises github pages
- linked lists bu
- must have cheat sheets for java developers
- the list adt western university
- collections in java aau
- nullaway practical type based null safety for java
- add e e method example tutorials point
- java collections list set map stanford university
- java list adt university of pennsylvania
Related searches
- 500 most frequently used words
- 100 most frequently used words
- most frequently used words list
- 300 most frequently used words
- frequently used words in english
- 1000 most frequently used words
- most frequently used japanese words
- most frequently used spanish words
- frequently used word list
- most frequently used english words
- frequently used words list
- frequently used synonym