Drag and drop of tree nodes in Java/Swing These code snippets show how to move Swing JTree nodes with the mouse by the use of drag and drop. Two event listeners need to be installed. First a mouse motion listener to indicate the drag operation and second a mouse listener to catch the mouse released event at the time of drop. The mouse motion listeners mouseDragged() method is invoked as long as the mouse key remains pressed and reports all the positions along the way the mouse is moved. This offers the possibility to add actions during drag operation. We could think about to show a special cursor symbol over areas where the drop of our node is prohibited. In our sample we don't do this and introduce a flag to indicate if the method mouseDragged() is invoked the first time or not. We don't want to do to many activities every time the mouse position is changing: private boolean _treeDragging = false; First see the drag operation. At the end the method mouseDragOnTree() is invoked that is described later._tree.addMouseMotionListener( new MouseMotionAdapter() { Enter here only one time after drag operation started: if (!_treeDragging) { Set cursor: setCursor(new Cursor(Cursor.HAND_CURSOR)); Read node which is dragged: TreePath path =
_tree.getPathForLocation(e.getX(), e.getY()); Now the drop operation. The variable _tree.addMouseListener( new MouseAdapter() { The following method stores the dragged tree node in _treeDraggingNode and locks the tree during drag and drop operation. private TreeNode _treeDraggingNode = null; protected void mouseDropOnTree(MouseEvent e, TreeNode node) { The usual situation looks like this: Drag on node (2) and drop on node (3). (2) appears now below (3). All nodes below (2) are moving together with (2) to the new place. A more special case: Again drag on node (2) and drop on node (3). But this time (3) is part of the nodes below (2). We cannot move all nodes below (2)! (3) and all descendants must remain. This is how drag and drop of tree nodes can be implemented. There may be your own program covering your requirements. You may use this samples as starting point for a quick and easy implementation. A new concept for printing has been introduced in JDK 1.2 (Java 2) after changes in the java.awt.PrintJob way of printing resulted sometimes in huge amount of data sent to the printer for every page. This made the life not easy. The concept to start a page, draw to it and finish (dispose) it does not exist anymore. Instead a method is invoked by the print manager with the current page number as parameter. For every method call you must draw all items belonging to the requested page. The new classes can be found in: Start a print job This is a small code snipped to show the start of a print job. First of
all a print job has to be created with PrinterJob.getPrinterJob(). The default page can be referenced and
also modified afterwards. In our sample we change the paper orientation to landscape. PrinterJob printerJob =
PrinterJob.getPrinterJob(); Why not showing a page dialog to the user where he can set sizes and borders? This can be done by replacing the line printerJob.setPrintable(this, pageFormat); in the above sample: PageFormat userFormat =
printerJob.pageDialog(pageFormat); Print pages This is now a sample to show what a printable object is. A printable object is an object which implements the Printable interface. public class SampleClass implements Printable { ... The interface requires a print(Graphics, PageFormat, int) method. The last parameter is the zero based pageIndex. A PrinterJob calls the Printable objects print() method to request the page specified by pageIndex. Its now your turn to draw and write within this print() method all items belonging to the page specified by pageIndex. You may use methods like drawLine() and drawString() to send your items to the printer. If you printed all your data but the print() method is still called, return NO_SUCH_PAGE. If you sent data to the printer return PAGE_EXISTS. public int print(Graphics pg, PageFormat
pageFormat, int pageIndex) Unfortunately this method may be invoked many times with the same pageIndex. You have to send every time the same data to the printer. Handle errors If the Printable object runs into an error the print job throws a PrinterException. You may catch the following two sub classes of PrinterException:
Text position and height in Java If you have problems to position your text for instance on screen or printing panels one of these tips may help you:
The so-called height is the distance between two lines of text. To measure the real font height (lets call it font size) use FontMetrics's methods getAscent() + getDescent() together. Both classes Graphics and FontMetrics can be found in /java/awt Reading clipboard content with Java There may be situations where you like to read the clipboard content in Microsoft Windows or any other operating system as a string for debug reasons. You like to know exactly what is stored there to used it in your own program or to check if the string you sent to the clipboard is correct. This is how easy it works... First of all you need the following imports if you want to use the code snippet below in your own program: import java.awt.*; Get a reference to the clipboard: Clipboard clipboard = getToolkit().getSystemClipboard(); Catch a transferable content object. If the clipboard is empty or does not contain a character-based object, this method returns null: Transferable content =
clipboard.getContents(this); String
clipboardData = (String)
Save / restore file to / from database using JAVA and JDBC In this short tip, we want to present how to write data from a file to the an Oracle table using Java and JDBC. Then we want to restore this file from the database to the filesystem again. The source code have been reduced to the minimum to simplify the understanding of the used mechanisms. Checks like "file exists", "row exists" have been removed. We used the thin JDBC driver for this demonstration. Used Environment
Created Test Table CREATE TABLE image ( Write data from the file to the database import java.sql.*; // Write data from a file (binary) to a long raw
via JDBC Compile the Java Code using the java compiler $ javac file2db Now, write a text or binary file from the filesystem to the database. $ java file2db 1 myfile Inserting myfilet (991 Bytes) into the table IMAGE at row: 1 Restore data from the database in a file import java.sql.*; // Restore data from the database (long raw) to a
file via JDBC. Compile the Java Code using the java compiler $ javac db2file Now, restore text or binary file from the database back to the filesystem. $ java db2file 1 myfile_copy Get myfile_copy from the table IMAGE at row: 1 Download Download file2db.java Reading non plain ASCII from HTML into a Java Servlet When you want to read extended characters (e.g. ISO8859P1: ü,ö,ä) from a HTML Form into a Java Servlet, make sure you set the correct Characterset, before reading the values using getURLParameter(), or you will get only 7-Bit characters. // Get HTML-Form Parameters import java.util.*; public class GetFormParm { protected HTTP http = null; // Constructor // Get URL Parameter for strKey // Set URL character set
(default ISO-8859-1) return strValue; Stored Procedures with IN and OUT Paramerters using JDBC Christoph Gächter, Akadia AG JDBC provides a stored procedure SQL escape that allows stored procedures to be called in a standard way for all RDBMs. This escape syntax has one with and one without result parameter. If the result parameter is used, it must be registered as an OUT parameter. The other parameters can be used for input, output or both. All parameters are referred to sequentially, by number, beginning by 1. begin ? := func [(?,?,?...)]; end; According to the SQL92 syntax: {?= call func [(?,?,?...)]} The class CallableStatement inherits the class
PreparedStatement and this class is the successor of Statement. As the
names CallableStatement says, in this class extensions for IN and OUT parameter
are defined. IN parameter values are set using the set methods inherited from
PreparedStatement. OUT parameter must be registered prior to executing the stored
procedure. Their values are retrieved after execution via the predefined getXXX()
methods. Simple Stored Procedure The PL/SQL package java_demo defines the procedure get_emp(), using the IN parameter p_id and the OUT parameters p_ename, p_job, p_sal, analogous to the attributes of the table EMP (schema scott/tiger). import java.sql.*; class StoredProcedure { // You can put a database name
after // Register Oracle
driver // Connect to the
database // Prepare a PL/SQL call // The id argument is the first
? // Get the data // Close statement and
connection Simple Stored Function The PL/SQL package java_demo defines the function get_sal(), using the IN parameter p_id and the result parameter sal, analogous to the attributes of the table EMP (schema scott/tiger). ... // Declare that the first ? is
a return value of type DOUBLE // Get the data Stored Function with Record Set The PL/SQL package java_demo defines the procedure list_emp(), using the IN parameter p_job and the result parameter as ResultSet, analogous to the attributes of the table EMP (schema scott/tiger). The ResultSet contains all the employees matching the defined job. ... // Select all the SALESMAN
person // Loop the cursor This example shows the easy and smart way how to open and to use a cursor
defined in TYPE myreftype IS REF CURSOR RETURN emp%ROWTYPE; Christoph Gächter, Akadia AG Hier werden einige Möglichkeiten gezeigt, wie mit Java Arrays sortiert werden können . (Siehe dazu auch JDC Tech Tips vom 23. September 1999). Voraussetzung für die folgenden Code-Beispiele ist Java 2 SDK, 1.2.x. Primitive Typen Gemeint sind hier die Java Primitive Data Types und weniger unliebsame Zeitgenossen. Dazu gehören byte, char, double, float, int, long und short. Diese können äusserst einfach sortiert werden, indem die Methode sort() der Klasse Arrays aufgerufen wird: public class SortPrimitive { // Sorts an array of double
values for (int i = 0; i < dblAry.length; i++) { // Sort the array // Print the array Interface Comparable Objekte, welche das Interface Comparable implementieren, lassen sich ebenso einfach sortieren. Zu diesen Objekten gehört die Klasse String, wie folgendes Beispiel zeigt: import java.util.*; public class SortString { // Sorts an array of strings // Sort the array // Print the array Was aber, wenn die zu sortierende Klasse das Interface Comparable nicht implementiert? Hier gibt es zwei Möglichkeiten: Die erwähnte Klasse kann vererbt werden und gleichzeitig das Interface implementieren oder es wird eine Vergleichsklasse (Interface Comparator) implementiert. Sehen wir uns zuerst die Möglichkeit an, die Klasse zu vererben: Das Interface Comparable erfordert die Implementation der Methode compareTo(). Diese ermittelt anhand des übergebenen Objektes die Werte 1 (grösser), 0 (gleich gross) bzw. –1 (kleiner): import java.util.*; public class MyPoint extends Point implements Comparable { MyPoint(int x, int y) { public int compareTo(Object o) { if (d1 < d2) { Wiederum erfolgt die Sortierung äusserst einfach: import java.util.*; public class SortPoint { // Sorts an array of points for (int i = 0; i < pntAry.length; i++) { // Sort the array // Print the array Interface Comparator Falls es nicht möglich ist, die Klasse zu vererben, kann eine eigenständige Vergleichsklasse implementiert werden. Diese implementiert ihrerseits das Interface Comparator. Dieses Interface erfordert die Umsetzung der beiden Methoden compareTo() und equals(). Die Methode compareTo() kennen wir bereits aus vorherigem Kapitel, die Methode equals() gibt true zurück, falls die beiden Objekte gleich gross sind. Hier als Beispiel ein Comparator für die Klasse Points: import java.util.*; public class PointComparator implements Comparator { public int compare(Object o1, Object o2) { if (d1 < d2) { public boolean equals(Object o1, Object o2) { Die Sortierung des Arrays erfolgt wiederum mit der Methode sort(), diesmal wird nebst dem zu sortierenden Array auch noch der Comparator mitgegeben: import java.util.*; public class SortByComparator { // Sorts an array of points for (int i = 0; i < pntAry.length; i++) { // Sort the array // Print the array Fazit Java stellt einige gute Möglichkeiten zur Verfügung, beliebige Objekte in einem Array zu sortieren, ohne dass sich der Entwickler um die Details kümmern muss. Interessant erscheint uns auch die Möglichkeit, eigene Sortierkriterien zu implementieren unter Verwendung eines speziellen Comparators (z.B. Unterdrückung Gross-/ Kleinschreibung, Buchstaben vor Zahlen usw.). File Upload with Java using Oracle Application Server OAS Matthias Ehrsam, Sohard AG This Tip shows how to implement uploading a file from a HTTP client (Browser must support the File Input Tag) to the HTTP server. This is often used in intranet's to allow clients, which must usually first authorize on the server, to upload files from the local machine to a central directory. The following HTML form shows a possible user interface. The user can browse the local filesystem with the Browse button. Use the following HTML Code
Use the following Java Code for OAS import oracle.owas.wrb.services.http.*; // Class to Upload a file using Oracle Application
Server OAS public static final String WRITE_PATH = "<PathToUploadDir>"; byte b[] = null; // Entry Point Method, called by
main() // Get File Information from HTTP
client // Read File from HTTP client _start = boundary_length +
content_disposition.length() + amount = b.length - _start - boundary_length -6; // -6 and -8 have to be added
since readLine() // Setup Output Filename String path_a_file = null; StringTokenizer st = new StringTokenizer( st = new StringTokenizer(path_a_file,"\\/"); if (filename.substring(0,8).equals("filename")) { // Write the file to the local
Filesystem try { // Show Message to the HTTP
Client public static void main(String[] args) { Reading non plain ASCII from HTML forms into Java Servlet Applications When you want to read extended values (e.g. ISO8859P1: ü,ö,ä) from a HTML Form into a Java Servlet, make sure you set the correct Characterset, before reading the values, or you will get only 7-Bit characters. // Get HTML-Form Parameters import java.util.*; public class GetFormParm { protected HTTP http = null; // Constructor // Get URL Parameter for strKey // Set URL character set
(default ISO-8859-1) return strValue; Java Pitfall: the lost exception Source: "Thinking in Java, 2nd edition, Revision 10" Chapter 10, http://www.mindview.net/ In general, Java's exception implementation is quite outstanding, but unfortunately there's a flaw. Although exceptions are an indication of a crisis in your program and should never be ignored, it's possible for an exception to simply be lost. This happens with a particular configuration using a finally clause: // LostMessage.java class VeryImportantException extends Exception { class HoHumException extends Exception { public class LostMessage { The output is:
You can see that there's no evidence of the VeryImportantException, which is simply replaced by the HoHumException in the finally clause. This is a rather serious pitfall, since it means that an exception can be completely lost, and in a far more subtle and difficult-to-detect fashion than the example above. In contrast, C++ treats the situation in which a second exception is thrown before the first one is handled as a dire programming error. Perhaps a future version of Java will repair this problem. |