Creating an SWT FileDialog

Main.java:

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
 
public class Main { 
   static Display display;
   static Shell shell;
   static Color color;
    
   public static void main(String[] args) {
      display = new Display();
      shell = new Shell(display);
 
      // pos x, pos y, width, height
      shell.setBounds(200, 200, 400, 200);
      shell.setText("SWT FileDialog Demonstration");
      shell.setLayout(new GridLayout());
 
      final Group buttonGroup = new Group(shell, SWT.NONE);
      GridLayout gridLayout = new GridLayout();
      gridLayout.numColumns = 3;
      buttonGroup.setLayout(gridLayout);
      buttonGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
       
      final Button directoryDialogButton = new Button(buttonGroup, SWT.PUSH);
      directoryDialogButton.setText("FileDialog");
      Label label1 = new Label(buttonGroup, SWT.NONE);
      label1.setText("File selected:");
      final Label label2 = new Label(buttonGroup, SWT.NONE);      
      label2.setText("");
 
      final String [] filterNames = { "All Files", "JPG Files", "GIF Files" };
      final String [] filterExtensions = { "*.*", "*.jpg", "*.gif" };
 
      SelectionListener selectionListener = new SelectionAdapter () {
         public void widgetSelected(SelectionEvent event) {
            FileDialog dialog = new FileDialog(shell, SWT.MODELESS);
            dialog.setFileName ("esuslogo.gif");
            dialog.setFilterNames (filterNames);
            dialog.setFilterExtensions (filterExtensions);
            dialog.setText("Select Image File");
            String result = dialog.open();
            label2.setText("" + result);
            buttonGroup.layout();
         };
      };   
        
      directoryDialogButton.addSelectionListener(selectionListener);
       
      shell.open();
 
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
      if (color != null && !color.isDisposed()) {
         color.dispose();
      }
      display.dispose();
   }
}

Creating an SWT Text(Area)

Main.java:

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
 
public class Main {
   public static void main(String[] args) {
      Display display = new Display();
      Shell shell = new Shell(display);
 
      // pos x, pos y, width, height
      shell.setBounds(200, 200, 300, 200);
      shell.setText("SWT Text Demonstration");
      shell.setLayout(new GridLayout());
 
      shell.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
 
      Text text = new Text(shell, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.WRAP);
      text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL));
       
      text.setText("Did you know..." +
                   "nn" +
                   "It is impossible to lick your elbow." +
                   "nnnnnnnnnnnnnnn" +
                   "Over 75% of people who read thisn" +
                   "will try to lick their elbow.");
       
      shell.open();
 
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
       
      display.dispose();
   }
}

Catching a specific SIGNAL/Interrupt in Java

You can use the undocumented class sun.misc.Signal. But beware of using the Sun packages.

This program allows you to catch any of the following signals:

   Windows:
      	ABRT	SIGABRT
	FPE 	SIGFPE
    	SEGV	SIGSEGV
	INT	SIGINT
	TERM	SIGTERM
	ILL	SIGILL


   Solaris/Linux:
	HUP	SIGHUP
	INT	SIGINT
	QUIT	SIGQUIT
	ILL	SIGILL
	TRAP	SIGTRAP
	ABRT	SIGABRT
	IOT	SIGIOT (*)
	EMT	SIGEMT (*)
	FPE	SIGFPE
	KILL	SIGKILL
	BUS	SIGBUS
	SEGV	SIGSEGV
	SYS	SIGSYS
	PIPE	SIGPIPE
	ALRM	SIGALRM
	TERM	SIGTERM
	STKFLT	SIGSTKFLT
	USR1	SIGUSR1
	USR2	SIGUSR2
	CHLD	SIGCHLD
	PWR	SIGPWR
	WINCH	SIGWINCH
	URG	SIGURG
	POLL	SIGPOLL
	IO	SIGIO
	STOP	SIGSTOP
	TSTP	SIGTSTP
	CONT	SIGCONT
	TTIN	SIGTTIN
	TTOU	SIGTTOU
	VTALRM	SIGVTALRM
	PROF	SIGPROF
	XCPU	SIGXCPU
	XFSZ	SIGXFSZ
	UNUSED	SIGUNUSED
	SWI	SIGSWI

The example program (Linux/Solaris) demonstrates to catch and perform a System.exit only with a SIGTERM. A SIGHUP will not cause the program to exit.

Main.java:

import sun.misc.Signal;
import sun.misc.SignalHandler;
import java.lang.reflect.*;
 
public class Main
{
   public static void main(String []args) {
      DebugSignalHandler.listenTo("HUP");
      DebugSignalHandler.listenTo("INT");
      DebugSignalHandler.listenTo("KILL");
      DebugSignalHandler.listenTo("TERM");
 
      while (true) {
         try {
            Thread.sleep(1000);
         }
         catch(InterruptedException e) {
         }
      }
   }
}
 
class DebugSignalHandler implements SignalHandler
{
   public static void listenTo(String name) {
      Signal signal = new Signal(name);
      Signal.handle(signal, new DebugSignalHandler());
   }

   public void handle(Signal signal) {
      System.out.println("Signal: " + signal);
      if (signal.toString().trim().equals("SIGTERM")) {
         System.out.println("SIGTERM raised, terminating...");
         System.exit(1);
      }
   }
}

Dynamically add JARs from an application’s lib directory

This example assumes you have the JDBC mm.mysql driver residing in an ext subdirectory.

Main.java:

import java.util.*;
import java.net.*;
import java.io.*;
import java.sql.*;
 
public class Main
{
   public static void main(String []args) throws Exception {
      ClassLoader cl = loadExt();
      if (cl != null) {
         cl.loadClass("org.gjt.mm.mysql.Driver").newInstance();
         System.out.println("mysql driver successfully loaded!");
         Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/esus", "USER", "PASS");
 
         //. . .
      }
   }
 
   public static URLClassLoader loadExt() {
      try {
         Vector urls = new Vector();
         File file = new File("ext");
         String[] list = file.list();
         for (int i=0; i<list.length; i++) {
            if (list[i].endsWith(".jar")) {
               urls.add(new URL("file:" + file.getName() + "/" + list[i]));
            }
         }
         return new URLClassLoader((URL[]) urls.toArray( new URL[] { } ));
      } catch ( java.net.MalformedURLException me ) { 
         me.printStackTrace();
      }
 
      return null;
   }
}

Changing the color of one JTable cell

Main.java:

import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame {
   public Main() {
      super("TableModel Demonstration");
  
      // create our own custom TableModel
      WineTableModel wineModel = new WineTableModel();
      JTable table = new JTable(wineModel);
 
      // since we're using values of floats and boolean here, we need
      // to set the cell renderer for every column. 
      for (int i =0; i<wineModel.getColumnCount();i++) {
         table.setDefaultRenderer(table.getColumnClass(i), new WineCellRenderer());
      }
       
      // add rows to our TableModel, each row is represented as a Wine object
      wineModel.addWine(new Wine("Chateau Meyney, St. Estephe", "1994", 18.75f, true));
      wineModel.addWine(new Wine("Chateau Montrose, St. Estephe", "1975", 54.25f, true));
      wineModel.addWine(new Wine("Chateau Gloria, St. Julien", "1993", 22.99f, false));
      wineModel.addWine(new Wine("Chateau Beychevelle, St. Julien", "1970", 61.63f, false));
      wineModel.addWine(new Wine("Chateau La Tour de Mons, Margeaux", "1975", 57.03f, true));
      wineModel.addWine(new Wine("Chateau Brane-Cantenac, Margeaux", "1978", 49.92f, false));
 
      // create the scroll pane and add the table to it. 
      JScrollPane scrollPane = new JScrollPane(table);
 
      // add the scroll pane to this window.
      getContentPane().add(scrollPane, BorderLayout.CENTER);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      main.pack();
      main.setVisible(true);
   }
}
 
// a simple object that holds data about a particular wine
class Wine {
   private String  name;
   private String  vintage;
   private float   price;
   private boolean inStock;
 
   public Wine(String name, String vintage, float price, boolean inStock) {
      this.name = name;
      this.vintage = vintage;
      this.price = price;
      this.inStock = inStock;
   }
 
   public String getName()     { return name; }
   public String getVintage()  { return vintage; }
   public float  getPrice()    { return price; } 
   public boolean getInStock() { return inStock; }
 
   public String toString() { 
      return "[" + name + ", " + vintage + ", " + price + ", " + inStock + "]"; }
}
 
class WineTableModel extends AbstractTableModel {
   // holds the strings to be displayed in the column headers of our table
   final String[] columnNames = {"Name", "Vintage", "Price", "In stock?"};
 
   // holds the data types for all our columns
   final Class[] columnClasses = {String.class, String.class, Float.class, Boolean.class};
 
   // holds our data
   final Vector data = new Vector();
  
   // adds a row
   public void addWine(Wine w) {
      data.addElement(w);
      fireTableRowsInserted(data.size()-1, data.size()-1);
   }
 
   public int getColumnCount() {
      return columnNames.length;
   }
         
   public int getRowCount() {
      return data.size();
   }
 
   public String getColumnName(int col) {
      return columnNames[col];
   }
 
   public Class getColumnClass(int c) {
      return columnClasses1;
   }
 
   public Object getValueAt(int row, int col) {
      Wine wine = (Wine) data.elementAt(row);
      if (col == 0)      return wine.getName();
      else if (col == 1) return wine.getVintage();
      else if (col == 2) return new Float(wine.getPrice());
      else if (col == 3) return new Boolean(wine.getInStock());
      else return null;
   }
 
   public Object getValueAtRow(int row) {
      Wine wine = (Wine) data.elementAt(row);
      return wine;
   }
 
   public boolean isCellEditable(int row, int col) {
      return false;
   }
}
 
class WineCellRenderer extends DefaultTableCellRenderer {
   public Component getTableCellRendererComponent(
            JTable table, Object value, boolean isSelected,
            boolean hasFocus, int row, int column)
   {
      WineTableModel wtm = (WineTableModel) table.getModel();
      Wine wine = (Wine) wtm.getValueAtRow(row);
 
      if (column == 3 && wine.getInStock() == false) {
         setBackground(Color.red);
      }
      else {
         setBackground(Color.white);
      }
 
      return super.getTableCellRendererComponent(table, value, isSelected, 
                                                 hasFocus, row, column);
   }
}

Setting the a connect timeout on an URLConnection

JDK1.5 allows you to set connect and read timeouts on URLConnection (HttpURLConnection, etc.).

Here is an example:

Main.java:

import java.net.*;

public class Main
{
   public static void main(String []args) throws Exception {
      if (args.length != 1) {
         System.err.println("Usage: java Main <URL>");
         System.exit(0);
      }
          
      URL url = new URL(args[0]);
      URLConnection connection = url.openConnection();
 
      connection.setConnectTimeout(5000);
      connection.connect();
   }
}

Publishing a Websphere MQ ConnectionFactory in an LDAP

The following working code sample allows you to create a QueueConnectionFactory (MQQueueConnectionFactory) and register it as an administered object in an LDAP tree.

I used iPlanet Directory Server 5.0 to test it out.

RegisterWebsphereMQ.java:

import  com.ibm.mq.jms.MQQueueConnectionFactory;
import  javax.naming.*;
import  javax.jms.*;
 
import  java.util.*;
 
public class RegisterWebsphereMQ
{
   public static void main(String args[])
   {
      if (args.length != 5) {
         System.err.println("Usage: RegisterWebsphereMQ LDAP-url base queue-manager username password");
         System.err.println("  eg.:      ldapurl        ldap://127.0.0.1:389");
         System.err.println("            providername   ou=dev,ou=test,o=esus.com");
         System.err.println("            queue-manager  name of the queue manager, eg. MQS1");
         System.err.println("            username       uid=user,ou=People,o=esus.com");
         System.err.println("            password       pw");
         System.exit(1);
      }
      String ldapurl=args[0];
      String base=args[1];
      String queuemgr=args[2];
      String username=args[3];
      String password=args[4];
 
      try {
         Context context = getInitialContext(ldapurl, username, password);
 
         createLDAPObject(context, base, "QueueConnectionFactory");
         createQueueConnectionFactory(context, base, queuemgr);
 
         System.out.println("Registration successful");
      } catch(Exception e) {
         System.out.println("Registration failed: " + e);
         e.printStackTrace();
      }
   }
 
   public static Context getInitialContext(String ldapurl, String username, String password)
                            throws NamingException
   {
      Properties env=System.getProperties();
      env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
      env.put(Context.PROVIDER_URL, ldapurl);
      env.put(Context.SECURITY_PRINCIPAL, username);
      env.put(Context.SECURITY_CREDENTIALS, password);
 
      // Retrieve the initial context
      return new InitialContext(env);
   }
 
   public static void createLDAPObject(Context context, String base, String ouName)
                        throws NamingException
   {
      try {
         context.bind("ou=" + ouName + "," + base, new LDAPObject(ouName));
         System.out.println("Created OU [" + ouName + "]");
      }
      catch(NameAlreadyBoundException e) {
         System.out.println("Name " + ouName + " is already bound under " + base);
      }
   }
 
   public static void createQueueConnectionFactory(Context context, String base, String queuemgr)
                         throws NamingException, JMSException
   {
      QueueConnectionFactory qcf = new MQQueueConnectionFactory();
      ((MQQueueConnectionFactory) qcf).setQueueManager(queuemgr);
 
      // Bind the connection factory into the JNDI repository
      context.rebind("cn=queuefactory,ou=QueueConnectionFactory,"+base, qcf);
   }   
}

LDAPObject.java:

import javax.naming.*;
import javax.naming.directory.*;
import java.util.*;
 
class LDAPObject implements DirContext {
   Attributes attributes;
   String name;
    
   public LDAPObject(String name) {
      this.name = name;
 
      attributes = new BasicAttributes(true);
      // case ignore
      Attribute oc = new BasicAttribute("objectclass");
      oc.add("organizationalunit");
      oc.add("top");
 
      attributes.put(oc);
   }
 
   public Attributes getAttributes(String name) throws NamingException {
      if (!name.equals("")) {
         throw new NameNotFoundException();
      }
      return (Attributes) attributes.clone();
   }
 
   public Attributes getAttributes(Name name) throws NamingException {
      return getAttributes(name.toString());
   }
 
   public Attributes getAttributes(String name, String[] ids)
          throws NamingException {
      if (!name.equals("")) {
         throw new NameNotFoundException();
      }
 
      Attributes answer = new BasicAttributes(true);
      Attribute target;
      for (int i = 0; i < ids.length; i++) {
         target = attributes.get(ids[i]);
         if (target != null) {
            answer.put(target);
         }
      }
      return answer;
   }
 
   public Attributes getAttributes(Name name, String[] ids)
          throws NamingException {
      return getAttributes(name.toString(), ids);
   }
 
   public String toString() {
      return name;
   }
 
   public Object lookup(Name name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public Object lookup(String name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void bind(Name name, Object obj) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void bind(String name, Object obj) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void rebind(Name name, Object obj) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void rebind(String name, Object obj) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void unbind(Name name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void unbind(String name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void rename(Name oldName, Name newName) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void rename(String oldName, String newName) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public NamingEnumeration list(Name name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public NamingEnumeration list(String name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public NamingEnumeration listBindings(Name name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public NamingEnumeration listBindings(String name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void destroySubcontext(Name name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void destroySubcontext(String name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public Context createSubcontext(Name name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public Context createSubcontext(String name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public Object lookupLink(Name name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public Object lookupLink(String name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public NameParser getNameParser(Name name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public NameParser getNameParser(String name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public String composeName(String name, String prefix)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public Name composeName(Name name, Name prefix)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public Object addToEnvironment(String propName, Object propVal)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public Object removeFromEnvironment(String propName)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public Hashtable getEnvironment() throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void close() throws NamingException {
      throw new OperationNotSupportedException();
   }
 
// -- DirContext
   public void modifyAttributes(Name name, int mod_op, Attributes attrs)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void modifyAttributes(String name, int mod_op, Attributes attrs)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void modifyAttributes(Name name, ModificationItem[] mods)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void modifyAttributes(String name, ModificationItem[] mods)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void bind(Name name, Object obj, Attributes attrs)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void bind(String name, Object obj, Attributes attrs)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void rebind(Name name, Object obj, Attributes attrs)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public void rebind(String name, Object obj, Attributes attrs)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public DirContext createSubcontext(Name name, Attributes attrs)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public DirContext createSubcontext(String name, Attributes attrs)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public DirContext getSchema(Name name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public DirContext getSchema(String name) throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public DirContext getSchemaClassDefinition(Name name)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public DirContext getSchemaClassDefinition(String name)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public NamingEnumeration search(Name name,
         Attributes matchingAttributes,
         String[] attributesToReturn)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public NamingEnumeration search(String name,
         Attributes matchingAttributes,
         String[] attributesToReturn)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public NamingEnumeration search(Name name,
         Attributes matchingAttributes)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public NamingEnumeration search(String name,
         Attributes matchingAttributes)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public NamingEnumeration search(Name name,
         String filter,
         SearchControls cons)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public NamingEnumeration search(String name,
         String filter,
         SearchControls cons)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public NamingEnumeration search(Name name,
         String filterExpr,
         Object[] filterArgs,
         SearchControls cons)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public NamingEnumeration search(String name,
         String filterExpr,
         Object[] filterArgs,
         SearchControls cons)
          throws NamingException {
      throw new OperationNotSupportedException();
   }
 
   public String getNameInNamespace() throws NamingException {
      throw new OperationNotSupportedException();
   }
}

Sample run:

C:myldap>java RegisterWebsphereMQ ldap://localhost:2000 ou=dev,ou=epais,o=philips.com MQS1 uid=user,ou=People,o=esus.com pw
Created OU [QueueConnectionFactory]
Registration successful

A Swing drag and drop code example

Drag and Drop is a powerful feature you should consider adding to your Java applications. When you check out the available tutorials on Java dnd, it may look fairly complex to you. Though it’s not all that hard, the hard part is remembering all the steps, objects and listeners involved. Here is a small example that shows you a basic drag and drop application (implemented with Swing).

A custom Drag and Drop (source) JList appears to the right and contains a file list of your root directory. Files with .txt extensions can be dragged upon our Drag and Drop JTextArea (target). The object transferred (Transferable) is a filename. When the drop occurs (you release the mouse button) the public void drop(DropTargetDropEvent event) is called. You can extract the filename from the Transferable object and go from there.

Main.java

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
 
public class Main extends JFrame
{
   private DNDJList list;
   private DNDJTextArea textarea;
 
   public static void main(String []args) {
      Main frame = new Main();
      frame.show();
   }
 
   public Main() {
      getContentPane().setLayout(new BorderLayout());
      list = new DNDJList(new DefaultListModel());
      getContentPane().add(BorderLayout.EAST, new JScrollPane(list));
      textarea = new DNDJTextArea();
      getContentPane().add(BorderLayout.CENTER, new JScrollPane(textarea));
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
 
      fillUpList(&quot;c:\&quot;);
 
      setSize(700, 300);
   }

   /**
    *  Fills up the JList with the entries in the specified directory
    */
   private void fillUpList(String directory) {
      File dir = new File(directory);
      File []files = dir.listFiles();
 
      DefaultListModel dlm = (DefaultListModel) list.getModel();
      for (int i=0; i&lt;files.length; i++) {
         dlm.addElement(directory + files[i].getName());
      }
   }
}

Our drag and drop JTextArea: DNDJTextArea.java

import java.awt.*;
import java.awt.dnd.*;
import java.awt.datatransfer.*;

import java.io.*;
import java.io.IOException;
 
import javax.swing.JTextArea;
 
public class DNDJTextArea extends JTextArea implements DropTargetListener
{
   DropTarget dropTarget = null;
  
   public DNDJTextArea() {
      // create a drop target
      dropTarget = new DropTarget(this, this);
   }
 
   public void dragEnter(DropTargetDragEvent event) { 
      event.acceptDrag(DnDConstants.ACTION_MOVE);
   }
 
   public void drop (DropTargetDropEvent event) {
      try {
         // get the object that is being transferred
         Transferable transferable = event.getTransferable();
       
         // DNDJTextArea accepts only Strings
         if (transferable.isDataFlavorSupported(DataFlavor.stringFlavor)) {
            event.acceptDrop(DnDConstants.ACTION_MOVE);
 
            String filename = (String) transferable.getTransferData(DataFlavor.stringFlavor);
            setText(readFile(filename));

            event.getDropTargetContext().dropComplete(true);
         } 
         else {
            event.rejectDrop();
         }
      }
      catch (UnsupportedFlavorException e) {
         setText(&quot;&quot;+e);
         event.rejectDrop();
      }
      catch (Exception e) {
         setText(&quot;&quot;+e);
         event.rejectDrop();
      } 
   }
 
   public void dragExit (DropTargetEvent event) { }
   public void dragOver (DropTargetDragEvent event) { }
   public void dropActionChanged (DropTargetDragEvent event) { }
 
   public String readFile(String filename) throws Exception {
      String LINEEND = System.getProperties().getProperty(&quot;line.separator&quot;);      
      StringBuffer sb = new StringBuffer();
      BufferedReader br = new BufferedReader(new FileReader(filename));
 
      String line;
      while ((line = br.readLine()) != null) {
         sb.append(line + LINEEND);
      }         
 
      return sb.toString();
   }
}

A drag and drop JList:DNDJList.java

import java.awt.dnd.*;
import java.awt.datatransfer.*;
import java.io.IOException;
import java.io.*;
 
import javax.swing.*;
 
public class DNDJList extends JList implements DragSourceListener, DragGestureListener    
{
   DragSource dragSource = null;
 
   public DNDJList(ListModel lm) {
      super(lm);
 
      // create a dragsource
      dragSource = new DragSource();
 
      // create a drag gesture recognizer
      dragSource.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_MOVE, this);
   }    
 
   public void dragGestureRecognized( DragGestureEvent event) {  
      String fileSelected = (String) getSelectedValue();
 
      if (fileSelected != null) {
         if (fileSelected.endsWith(&quot;.txt&quot;)) {
            // StringSelection implements Transferable, wraps the data into a transferable object
            StringSelection text = new StringSelection(fileSelected.toString()); 
        
            // start the dragging
            dragSource.startDrag(event, DragSource.DefaultMoveDrop, text, this);
         }
         else {
            SwingUtilities.invokeLater(new Runnable() {
               public void run() {
                  JOptionPane.showMessageDialog(SwingUtilities.getRootPane(DNDJList.this), 
                                                &quot;Only .txt files can be dragged!&quot;, &quot;Error&quot;,
                                                JOptionPane.ERROR_MESSAGE);
               } 
            });
         }
      } else {
         System.out.println( &quot;nothing was selected&quot;);   
      }
   }
 
   public void dragDropEnd (DragSourceDropEvent event) { }
   public void dragEnter (DragSourceDragEvent event) { }
   public void dragExit (DragSourceEvent event) { }
   public void dragOver (DragSourceDragEvent event) { }
   public void dropActionChanged ( DragSourceDragEvent event) { }
}

Scaling an image

You can use apply an AffineTransform object when drawing the image, or you can create a BufferedImage and perform an scaling operation on it.

Apply AffineTransform when drawing image

Main.java:

import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   private Image image;
   private double scalex = 1.0;
   private double scaley = 1.0;
   private JButton button1;
   private JButton button2;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      image = Toolkit.getDefaultToolkit().getImage("c:\djkrush.jpg");
      waitForImage(image);
 
      getContentPane().setLayout(new BorderLayout());
      
      button1 = new JButton("scale up by 5");
      button1.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            scalex += .1;
            scaley += .1;
            repaint();
         }
      });
 
      button2 = new JButton("scale down by 5");
      button2.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            scalex -= .1;
            scaley -= .1;
            repaint();
         }
      });
 
      JPanel panel = new JPanel(new GridLayout(1, 2));
      panel.add(button1);
      panel.add(button2);
      getContentPane().add(BorderLayout.SOUTH, panel);
   }
 
   public void paint(Graphics g) {
      Graphics2D g2d = (Graphics2D) g;
 
      AffineTransform at = new AffineTransform();
      at.scale(scalex, scaley);
      g2d.drawImage(image, at, this);
 
      button1.repaint();
      button2.repaint();
   }
 
   public void waitForImage(Image image) {
      MediaTracker mt = new MediaTracker(this);
 
      int id = 0;
      mt.addImage(image, id);
 
      try {
         mt.waitForID(id);
      }
      catch(InterruptedException e) {
         System.out.println("Image loading interrupted : " + e);
      }
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
}

Creating BufferedImage and scaling afterwards

Main.java:

import java.awt.event.*;
import java.awt.image.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   private Image image;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      image = Toolkit.getDefaultToolkit().getImage("c:\djkrush.jpg");
      waitForImage(image);
      image = scaleImage(image, 2.0, 2.0);
   }
 
   public void paint(Graphics g) {
      g.drawImage(image, 0, 0, this);
   }
 
   public void waitForImage(Image image) {
      MediaTracker mt = new MediaTracker(this);
 
      int id = 0;
      mt.addImage(image, id);
 
      try {
         mt.waitForID(id);
      }
      catch(InterruptedException e) {
         System.out.println("Image loading interrupted : " + e);
      }
   }
 
   public Image scaleImage(Image image, double scalex, double scaley) {
      BufferedImage bi = toBufferedImage(image);
 
      AffineTransformOp op = new AffineTransformOp(
                   AffineTransform.getScaleInstance(scalex, scaley), null); 
 
      return op.filter(bi, null); 
   }
 
   public BufferedImage toBufferedImage(Image image) {
      BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), 
                                           BufferedImage.TYPE_INT_RGB); 

      // copy the original image
      Graphics g = bi.createGraphics();
    
      g.drawImage(image, 0, 0, null);
      g.dispose();
 
      return bi;
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
}

Image used:

Why static fields are not serialized

Static fields of a class are shared among objects of that class. Just imaging they would be serialized, what would happen if you have instantiated an object of a class containing an important static variable and that you would deserialize an object of the same class. The static field would be overwritten. Sometimes, however, you may want this type of behavior. The solution is simple: just customize serialization through the methods writeObject and readObject as shown in following example.

Main.java:

import java.io.*;
 
public class Main {
   public static void main(String args[]) {
      try {
         Test t1 = new Test();
         t1.create();
 
         System.out.println("State of t1: " + t1);
 
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         ObjectOutputStream oos = new ObjectOutputStream(baos);
         oos.writeObject(t1);
         oos.flush();
 
         // make static variable count 0 to prove our point
         Test.count = 0;
 
         ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
         ObjectInputStream ois = new ObjectInputStream(bais);
         Test t2 = (Test) ois.readObject();
 
         System.out.println("State of t2: " + t2);  
      }
      catch(ClassNotFoundException e) {
         System.out.println(e); 
      }
      catch(IOException e) { 
         System.out.println(e); 
      }
   }
}
 
class Test implements Serializable {
   public int var = 0;
   public static int count = 0;
  
   Test() { }
 
   public void create() {
      var = 1;
      count++;
   }
 
   private void writeObject(ObjectOutputStream oos) throws IOException {
      oos.defaultWriteObject();
      // write static variable
      oos.writeInt(count);
   }
 
   private void readObject(ObjectInputStream ois) throws IOException, 
                                              ClassNotFoundException {
      ois.defaultReadObject();
      // read static variable
      count = ois.readInt();
   }
  
   public String toString() {
      return "var = " + var + "; count = " + count;
   }
}

outputs:

State of t1: var = 1; count = 1
State of t2: var = 1; count = 1