Java
Local
- Checkbox
- Classpath, getting it programatically
- Close button from window manager
- Colors Default, getting them from the UIManager
- Cut and Paste
- Debug a raster in IDEA
- Debug, show GUI in a non GUI Application
- Diagnostics, Java
- Double Click handling
- JAI Java Advanced Imaging
- JFrame Iconify
- JNI (Java Native Interface)
- Graphics Context
- GUI, Java
- GUIDS
- Host Name Verifier
- HTML, getting parameters to an Applet
- HTTPS
- Image, Loading one from a file, or stream
- Image, Saving to a file
- Image Transform (scale rotate translate)
- Inner class, accessing Enclosing classes 'this'
- KeyListener
- Linux Java Plug-in Control Panel
- Mouse
- Moving a Raster
- Password Entry
- Printing
- Profiling
- Properties, Saving
- Quirks
- Rigid Area
- Screen Size
- JScrollPanel
- SSL
- JTable, column reordering
- Table Horizontal Scroll
- Text
- Text Area Notes
- Time Interval
- JTree
- JTree, finding Deepest Open Depth
- Text, determining bounds of it
- JTextField Validating it live
- Tomcat
- Translating a Raster
- Tree Selection Quirk
- Trust All Certificates
- Window close from window manager
- Window types from an OS viewpoint
- isWhiteSpace
External
Diagnostics, Java
Sun has an interesting jvm diagnostic tool named visualvm (google it for info).
JNI (Java Native Interface)
%JAVA_HOME%\javah -classpath target/classes/. -jni com.compay.ClassToGenJniFor
Saving Properties
Properties props = new Properties();
propFile = System.getProperty("user.home") + File.separatorChar + "myprops.txt";
try {
props.load(new FileInputStream(propFile));
} catch (FileNotFoundException e1) {
} catch (IOException e1) {
}
props.setProperty("nameofprop.with.dots.usually", "valueToSave");
try {
props.store(new FileOutputStream(this.propFile), "this is a one line comment put at the top of the file, it will automatically pre prefixed by the comment char (which is '#')");
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
GUIDS
- Use UID for values that don't need to be machine specific java.rmi.server.UID
- Use VMID for values that _do_ need to be machine specific java.rmi.dgc.VMID (VMIDs are made up of a UID and the host ip address)
Getting the classpath programatically
java.lang.System.getProperty("java.class.path");
Saving an Image to a file
ColorModel colorModel = javax.media.jai.PlanarImage.createColorModel(wr.getSampleModel());
BufferedImage bi;
bi = new java.awt.image.BufferedImage(colorModel, (WritableRaster)wr, true, null);
java.io.File f = new java.io.File("c:\\delme\\~NAME~" + wr.getWidth() + "~" + wr.getHeight() + "~" + wr.getNumBands() + "~" + ((new java.util.Date()).getTime()) + ".png");
javax.imageio.ImageIO.write(bi, "png", f);
Translating a Raster
Use Raster's method createTranslatedChild.
Debug a raster in IDEA
// How to write to a file:
(new java.io.RandomAccessFile("c:\\a.bin","rw")).write({PUT_BYTE[] HERE})
// How to get a byte[] from a Raster
((java.awt.image.DataBufferByte)(tile.getDataBuffer())).getData()
// How to get a byte[] from a JAIPyramidDataAccessor
((java.awt.image.DataBufferByte)(((JAIPyramidDataAccessor)(pyrRdas.toArray()[4])).getData().getDataBuffer())).getData()
// How to write from a Raster: 'tile'
(new java.io.RandomAccessFile("c:\\a.bin","rw")).write(((java.awt.image.DataBufferByte)(tile.getDataBuffer())).getData())
// How to write from a Raster
(new java.io.RandomAccessFile("c:\\a.bin","rw")).write(((java.awt.image.DataBufferByte)dstRaster.getDataBuffer()).getData())
// How to write from a Raster to a bin file named with the info needed to reconstruct it
(new java.io.RandomAccessFile("c:\\delme\\~NAME~" + tile.getWidth() + "~" + tile.getHeight() + "~" + tile.getNumBands() + ".bin","rw")).write(((java.awt.image.DataBufferByte)(tile.getDataBuffer())).getData())
try {
java.io.RandomAccessFile fout = new java.io.RandomAccessFile("c:\\delme\\~NAME~" + dest.getWidth() + "~" + dest.getHeight() + "~" + dest.getNumBands() + ".bin","rw");
fout.write(((java.awt.image.DataBufferByte)(dest.getDataBuffer())).getData(0));
fout.write(((java.awt.image.DataBufferByte)(dest.getDataBuffer())).getData(1));
fout.write(((java.awt.image.DataBufferByte)(dest.getDataBuffer())).getData(2));
fout.close();
} catch (Exception e) {
}
package debug.imagry;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ConvertRawToPNG {
/**
* @param args
*/
public static void main(String[] args) {
int at = 0;
String type = args[at++];
if (type.compareToIgnoreCase("3band") == 0) {
do3Bands(args, at);
} else if (type.compareToIgnoreCase("mono3") == 0) {
doMono3(args, at);
}
}
static void doMono3(String[] args, int at) {
String filename = args[at++];
int width = Integer.valueOf(args[at++]);
int height = Integer.valueOf(args[at++]);
int bands = Integer.valueOf(args[at++]);
DataInputStream dis = null;
try {
dis = new DataInputStream(new FileInputStream(filename));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte[] data = new byte[width * height];
try {
dis.read(data);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
int[] dataInt = new int[width * height * bands];
at = 0;
for (int i = 0; i < data.length; i++) {
dataInt[at++] = data[i];
dataInt[at++] = data[i];
dataInt[at++] = data[i];
}
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
WritableRaster wr = bi.getRaster();
wr.setPixels(0, 0, width, height, dataInt);
try {
ImageIO.write(bi, "png", new File("/zzz.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
static void do3Bands(String[] args, int at) {
String filename = args[at++];
int width = Integer.valueOf(args[at++]);
int height = Integer.valueOf(args[at++]);
int bands = Integer.valueOf(args[at++]);
DataInputStream dis = null;
try {
dis = new DataInputStream(new FileInputStream(filename));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte[] data = new byte[width * height * bands];
try {
dis.read(data);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
int[] dataInt = new int[width * height * bands];
for (int i = 0; i < dataInt.length; i++) {
dataInt[i] = data[i];
}
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
WritableRaster wr = bi.getRaster();
wr.setPixels(0, 0, width, height, dataInt);
try {
ImageIO.write(bi, "png", new File("/zzz.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
Debug, show GUI in a non GUI Application
// This blocks whenever something is shown
public void show() {
JDialog jDialog = new JDialog((Frame)null, true);
JPanel panel = new JPanel(new BorderLayout());
jDialog.add(panel);
//Thing to show:
JLabel label = new JLabel("Test");
panel.add(label, BorderLayout.CENTER);
jDialog.pack();
jDialog.setVisible(true);
}
Show an blocking message box
JOptionPane.showMessageDialog(null, "Exit");
Something to try, to use to make it run in a different thread (unverified as to whether this works)
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
show();
}
});
Text, determining bounds of it
(Where g is a Graphics2D)
FontRenderContext frc = g.getFontRenderContext();
TextLayout layout = new TextLayout("How big am I?", g.getFont(), frc);
Rectangle rText = layout.getBounds().getBounds();
JTree, finding Deepest Open Depth
public int getDeepestDisplayedLevel( JTree tree) {
int deepest = 0;
int rowCount = tree.getRowCount();
for (int i = 0; i < rowCount; i++) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getPathForRow(i).getLastPathComponent();
if (node.getLevel() > deepest) {
deepest = node.getLevel();
}
}
return deepest;
}
JTable, column reordering
JTable.getTableHeader().setReorderingAllowed()
JTextField Validating it live
Make sure to handle all 3 events:
JTextField tf;
tf.getDocument().addDocumentListener( new DocumentListener() {
public void insertUpdate(DocumentEvent e) { }
public void removeUpdate(DocumentEvent e) { }
public void changedUpdate(DocumentEvent e) { }
});
Image Transform (scale rotate translate)
If you want to place an Image translated, rotated and scaled. This is a nice way to do it. (Remember that transforms happen in the reverse order specified)
- g.translatate( targetPositionsCenterX, targetPositionsCenterY);
- g.rotate(theta);
- g.scale(scale, scale);
- g.translate( -iconsCenterX, -iconsCenterY);
- m_icon.paintIcon( component, g, 0, 0);
Printing
Host Name Verifier
Here is a host name verifier that checks with the naming service:
HostnameVerifier ver = new HostnameVerifier() {
public boolean verify(String urlHostname,String certHostname) {
return java.net.InetAddress.getByName(urlHostname).equals(java.net.InetAddress.getByName(certHostname));
}
};
com.sun.net.ssl.HttpsURLConnection con = ...(obtain connection);
con.setHostnameVerifier(ver);
Trust All Certificates
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String s, SSLSession sslSession) {
String str = sslSession.getPeerHost();
Logger.out("Verifying [" + s + "] on [" + str + "]");
return true;
}
});
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
};
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts,new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}
HTTPS
See SSL.
See Certificates, Trust All
Make sure to turn off Java's automatic follow of redirects (it looses cookies).
Use something like
setInstanceFollowRedirects(false)
SSL
See Certificates, Trust All
Use the vm setting -Djavax.net.debug=all to have it spew alot about settings,
including the Certificates it loads the unencrypted data it is sending or has recievied.
JFrame Iconify
JFrame frame = ...;
frame.setState( Frame.ICONIFIED); // to iconify
frame.setState( Frame.NORMAL); // to restore
Window types from an OS viewpoint
JDialog - closeable
JWindow - borderless
JFrame - bordered, close, maximize, minimize
JScrollPanel
To get info about the position of the scrolled area:
JScrollPane sp;
sp.getViewport().getViewRect();
sp.getViewport().getViewPosition();
Quirks
| Type | Description | Work around |
| Tree Selection |
The selection moves up from a child to its parent when the parent is collapsed |
Add a TreeSelectionListener and clear the selection when it moves up |
isWhiteSpace
Character.isWhiteSpace( {char} );
Inner class, accessing Enclosing classes 'this'
class Outer extends JPanel {
class Inner {
void func() {
Outer.this.repaint();
}
}
}
Profiling
To get params:
java -Xrunhprof:help
To run
java -Xrunhprof:depth=7 {classname}
or in plugin:
-Xrunhprof:depth=3
or maybe for plugin:
-classic -Xrunhprof:depth=8
Your applet must call System.exit( <val> ) for the applet use of hprof to dump trace info
Screen Size
Component pane;
pane.getToolkit().getScreenSize();
Double Click handling
_table.addMouseListener( new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if ( e.getClickCount() == 2) {
Point point = new Point( e.getX(), e.getY());
int row = _table.rowAtPoint( point);
processDoubleClick( row);
}
}
});
Mouse
Right Click
tree.addMouseListener( new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if ( SwingUtilities.isRightMouseButton(e)) {
}
}
});
Text
Bounds of text with Graphics2D
Graphics2D g = ...;
Font font = g.getFont();
FontRenderContext frc = g.getFontRenderContext();
TextLayout layout = new TextLayout(name, font, frc);
Rectangle2D bounds = layout.getBounds();
Graphics Context
To get one at any time use: Component.getGraphics();
Password Entry
JPasswordField password = new JPasswordField(8);
password.setEchoChar('*');
Colors Default, getting them from the UIManager
Tooltip background color: UIManager.getColor("info")
Tooltip foreground color: UIManager.getColor("infoText")
JTree
To make the root node show the expand/collapse symbol do: tree.setShowsRootHandles(true);
KeyListener
To make an arbitrary control a key listener, it must override:
public boolean isFocusable()
and return true
Cut and Paste
You can cut from a JTextArea that has setEditable(false), but not from one that is setEnabled(false)
Text Area Notes
To make word based line wrap work:
m_filterDescText = new JTextArea( 3, 25);
m_filterDescText.setDisabledTextColor( Color.black);
m_filterDescText.setLineWrap(true);
m_filterDescText.setWrapStyleWord(true);
Close button from window manager, Inhibiting close
On the dialog set:
<dialog box>.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
Then just manually hide the dialog if you want to close it.
Also use add a WindowHandler windowClosing event handler to detect when the window managers close button was clicked.
<dialog box>.addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent e) {
doClose();
}
});
Checkbox
| issue | desc |
| Retrieving value | checkbox.getModel().isSelected |
Image, Loading one from a file, or stream
Use: javax.imageio.ImageIO
Linux Java Plug-in Control Panel
Run:
java install path}/bin/ControlPanel
Table Horizontal Scroll
table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF);
scrollPane.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
Rigid Area
Box.createRigidArea( ...);
Tomcat
http://jakarta.apache.org/tomcat/
HTML, getting parameters to an Applet
In the HTML:
<OBJECT ...>
<PARAM NAME="variableName" VALUE="value">
</OBJECT>
In the Java:
class xxx extends JApplet {
...
getParameter( "sizeX");
...
}
Time Interval
Date start = new Date();
[Stuff]
Date end = new Date();
System.out.println( "Interval = " + (end.getTime() - start.getTime()));