Right-aligning a JTable column

Main.java:

import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame 
{
   public Main() {
      super("Table example, Wines from Bordeaux");
 
      Object[][] tabledata = {
            { "Chateau Meyney, St. Estephe", 	   new Integer(1994), "$18.75"},
            { "Chateau Montrose, St. Estephe", 	   new Integer(1975), "$54.25" },
            { "Chateau Gloria, St. Julien", 	   new Integer(1993), "$22.99" },
            { "Chateau Beychevelle, St. Julien",   new Integer(1970), "$61.63" },
            { "Chateau La Tour de Mons, Margeaux", new Integer(1975), "$57.03" },
            { "Chateau Brane-Cantenac, Margeaux",  new Integer(1978), "$49.92" },
      };
 
      String columnheaders[] = { "Wine", "Vintage", "Price" };
 
      JTable table = new JTable(tabledata, columnheaders);
      table.setPreferredScrollableViewportSize(new Dimension(500, 70));
 
      // right align 2nd column
      TableColumnModel columnModel = table.getColumnModel();
      TableColumn column = columnModel.getColumn(1);  
      DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
      renderer.setHorizontalAlignment(JLabel.RIGHT);
      column.setCellRenderer(renderer);
 
      // right align 2nd column when editing
      JTextField tf = new JTextField();
      tf.setHorizontalAlignment(JTextField.RIGHT);
      column.setCellEditor(new DefaultCellEditor(tf));
 
      JScrollPane scrollPane = new JScrollPane(table);
      getContentPane().add(scrollPane);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      pack();
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}

Disabling selection in my JTable

Look at the three lines of code in this working program to find out how to disallow any selection.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame 
{
   public Main() {
      super("Table example, Wines from Bordeaux");
 
      Object[][] tabledata = {
            { "Chateau Meyney, St. Estephe", 	   new Integer(1994), "$18.75"},
            { "Chateau Montrose, St. Estephe", 	   new Integer(1975), "$54.25" },
            { "Chateau Gloria, St. Julien", 	   new Integer(1993), "$22.99" },
            { "Chateau Beychevelle, St. Julien",   new Integer(1970), "$61.63" },
            { "Chateau La Tour de Mons, Margeaux", new Integer(1975), "$57.03" },
            { "Chateau Brane-Cantenac, Margeaux",  new Integer(1978), "$49.92" },
      };
 
      String columnheaders[] = { "Wine", "Vintage", "Price" };
 
      JTable table = new JTable(tabledata, columnheaders);
      table.setPreferredScrollableViewportSize(new Dimension(500, 70));
      JScrollPane scrollPane = new JScrollPane(table);
 
      getContentPane().add(scrollPane);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      // disable selection
      table.setRowSelectionAllowed(false);
      table.setColumnSelectionAllowed(false);
      table.setCellSelectionEnabled(false);
 
      pack();
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}

Changing the colors of a JOptionPane

Main.java:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public static void main(String []args) {
      UIManager.put("OptionPane.background", Color.blue);
      UIManager.put("Panel.background", Color.blue);
      UIManager.put("Button.background", Color.white);
 
      String value = JOptionPane.showInputDialog("Enter your name");
      System.out.println("Hello " + value); 
 
      // exit awt thread
      System.exit(1);
   }
}

Binding a control key to a JTextArea component

In the following example, the CTRL-L key is mapped to an Action when pressed in the JTextArea.

Main.java:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() {
      JTextArea ta = new JTextArea();
      getContentPane().add(new JScrollPane(ta));
 
      Action gotoLineAction = new AbstractAction("gotoline") {
         public void actionPerformed(ActionEvent ae) {
            String value = JOptionPane.showInputDialog("Goto line no");
            System.out.println("Include functionality here to goto line " + value); 
         }
      };
 
      ta.getInputMap().put(KeyStroke.getKeyStroke("control L"), "gotoline");
      ta.getActionMap().put(gotoLineAction.getValue(Action.NAME), gotoLineAction);
  
      ta.setText("Press CTRL-L!");
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
}

Turn off copy/paste in a JTextArea

Main.java:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() {
      JTextArea ta = new JTextArea();
      getContentPane().add(new JScrollPane(ta));
 
      ta.getInputMap().put(KeyStroke.getKeyStroke("control C"), "none");
      ta.getInputMap().put(KeyStroke.getKeyStroke("control V"), "none");
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
}

Creating an editable JList

Courtesy of Nobuo Tamemasa (http://www2.gol.com/users/tame/swing/examples/JTableExamples1.html)



EditableListExample.java:

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
 
/**
 * @version 1.0 12/24/98
 */
public class EditableListExample extends JFrame {
 
  public EditableListExample() {
    super("Editable List Example");
    
    String[] data = {"a","b","c","d","e","f","g"};
    
    JList list = new JList( data );
    JScrollPane scrollList = new JScrollPane( list );
    scrollList.setMinimumSize(new Dimension(100,80));
    Box listBox = new Box(BoxLayout.Y_AXIS);
    listBox.add(scrollList);
    listBox.add(new JLabel("JList"));
         
    DefaultTableModel dm = new DefaultTableModel();
    Vector dummyHeader = new Vector();
    dummyHeader.addElement("");
    dm.setDataVector(
      strArray2Vector(data),
      dummyHeader);
    JTable table = new JTable( dm );
    table.setShowGrid(false);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    JScrollPane scrollTable = new JScrollPane( table );
    scrollTable.setColumnHeader(null);
    scrollTable.setMinimumSize(new Dimension(100,80));
    Box tableBox = new Box(BoxLayout.Y_AXIS);
    tableBox.add(scrollTable);
    tableBox.add(new JLabel("JTable"));
    
    Container c = getContentPane();
    c.setLayout(new BoxLayout(c, BoxLayout.X_AXIS));
    c.add(listBox);
    c.add(new JSeparator(SwingConstants.VERTICAL));
    //c.add(new JLabel("test"));
    //c.add(new JSeparator(SwingConstants.HORIZONTAL));
    c.add(tableBox);
    setSize( 220, 130 );
    setVisible(true);
  } 
   
  private Vector strArray2Vector(String[] str) {
    Vector vector = new Vector();
    for (int i=0;i<str.length;i++) {
      Vector v = new Vector();
      v.addElement(str[i]);
      vector.addElement(v);
    }
    return vector;
  }

  public static void main(String[] args) {
    final EditableListExample frame = new EditableListExample();
    frame.addWindowListener( new WindowAdapter() {
      public void windowClosing( WindowEvent e ) {
        System.exit(0);
      }
    });
  }
}

Writing a dynamic proxy class

The following example uses a dynamic proxy class to keep track of how much time it takes to execute a method.

Two classes are implemented: JMSTransporter and TibcoTransporter, both implementing the interface Transporter.

interface Transporter {  
   public void sendMessage(String message);
}
 
class TibcoTransporter implements Transporter {
   public void sendMessage(String message) {
      ...
   }
}
 
class JMSTransporter implements Transporter {
   public void sendMessage(String message) {
      ...
   }
}

Suppose we need to do some performance tests to see how long each transporter takes to perform its task. The typical way of doing this is to record a timestamp in the beginning of the method and at the end and printing out the difference:

   long start = System.currentTimeMillis();
 
   .. perform job
 
   long stop = System.currentTimeMillis();
   System.out.println("Total time it took: " + (stop - start));

We would have to do that for the TibcoTransporter as well as the JMSTransporter. It also uglifies the code, makes it harder to maintain (remove when it goes in production) and may introduce bugs. You could also write a wrapper around it, but this is a tedious task and would require you to do this for every interface.

Since JDK1.3, you can simplify this task using a dynamic proxy class. A dynamic proxy class is a class that implements a list of interfaces at runtime. An instance of this class can handle method invocations of the interface(s) and dispatches them to the object that implements the interface.

Writing a proxy class is simple: implement the InvocationHandler interface and its method

   public Object invoke(Object proxy, Method method, Object[] args)            
                     throws Throwable; 

To instantiate a proxy object:

   Proxy.newProxyInstance(ClassLoader loader,
                          Class[] interfaces,
                          InvocationHandler h) 

In our example, the proxy class TimerProxy is created. All method invocations to the interfaces that were specified when instantiating the proxy object with newProxyInstance are dispatched to the TimerProxy.

Main.java:

import java.lang.reflect.*;
 
interface Transporter
{
   public void sendMessage(String message);
}
 
class TibcoTransporter implements Transporter
{
   public void sendMessage(String message) {
      // let's assume the message takes 1 second to send 
      // using Tiboc RendezVous
      try {
         Thread.sleep(1000);
      }
      catch(InterruptedException e) {
      }
      System.out.println("Message '" + message + "' sent with the TibcoTransporter");
   }
}
 
class JMSTransporter implements Transporter
{
   public void sendMessage(String message) {
      // let's assume the message takes 2 seconds to send 
      // using a JMS implementation
      try {
         Thread.sleep(2000);
      }
      catch(InterruptedException e) {
      }
      System.out.println("Message '" + message + "' sent with the JMSTransporter");
   }
}
   
public class Main
{
   public static void main(String []args) {
      TibcoTransporter tibcoTransporter = new TibcoTransporter();

      Transporter transporter1 = (Transporter) TimerProxy.newInstance(new TibcoTransporter());
      transporter1.sendMessage("Hi");

      Transporter transporter2 = (Transporter) TimerProxy.newInstance(new JMSTransporter());
      transporter2.sendMessage("Hi");
   }
}

class TimerProxy implements InvocationHandler
{
   private Object obj;
 
   public TimerProxy(Object obj) {
      this.obj = obj;
   }
  
   public static Object newInstance(Object obj) {
      return Proxy.newProxyInstance(obj.getClass().getClassLoader(),
                                    obj.getClass().getInterfaces(),
                                    new TimerProxy(obj));
   }
 
   public Object invoke(Object proxy, Method m, Object[] args) throws Throwable
   {
      Object result = null;
      long start, stop;
      System.out.println("- Entering " + m.getName() + " in class " + obj.getClass());
      start = System.currentTimeMillis();
      try {
         result = m.invoke(obj, args);
      }
      catch(InvocationTargetException e) {
         throw e.getTargetException();
      }
      catch(Exception e) {
         throw new RuntimeException(e.getMessage());
      }
      finally {
         stop = System.currentTimeMillis();
         System.out.println("- Total time it took: " + (stop - start));
      }
      System.out.println("- Exiting " + m.getName() + " in class " + obj.getClass());
 
      return result;
   }
}

outputs:

- Entering sendMessage in class class TibcoTransporter
Message 'Hi' sent with the TibcoTransporter
- Total time it took: 1002
- Exiting sendMessage in class class TibcoTransporter
- Entering sendMessage in class class JMSTransporter
Message 'Hi' sent with the JMSTransporter
- Total time it took: 2003
- Exiting sendMessage in class class JMSTransporter

Other uses for a dynamic proxy are logging, parameter validation, access control, error handling, …

For more information on Dynamic Proxy Classes, check here

Saving the contents of a JPanel in a JPG image

The following example saves the content of the JPanel in the file test.jpg when the JFrame is closed. Play around with the saveComponent method that takes any sort of Component as a parameter.

Main.java:

import com.sun.image.codec.jpeg.*;
import javax.swing.border.*;
import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
 
public class Main extends JFrame 
{
   JPanel panel;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) { 
            saveComponent(panel, "test.jpg");
            System.exit(0);
         }
      });
 
      panel = createContactPanel();
 
      JScrollPane sp = new JScrollPane();
      sp.setViewportView(panel);
 
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(sp, BorderLayout.CENTER); 
   }
 
   public JPanel createContactPanel() {
      JLabel titleLbl      = new JLabel("Title");
      JLabel firstNameLbl  = new JLabel("First name");
      JLabel lastNameLbl   = new JLabel("Last name");
      JLabel addressLbl    = new JLabel("Address");
      JLabel cityLbl       = new JLabel("City");
      JLabel zipLbl        = new JLabel("Postal code");
      JLabel countryLbl    = new JLabel("Country");
      JLabel phoneLbl      = new JLabel("Phone number");
      JLabel faxLbl        = new JLabel("Fax number");
      JLabel emailLbl      = new JLabel("E-mail");
      JLabel birthdayLbl   = new JLabel("Birthdate");
      JLabel pickchoiceLbl = new JLabel("Pick a choice");
      JLabel creditCardTypeLbl     = new JLabel("Credit card type");
      JLabel creditCardNumberLbl   = new JLabel("Credit card number");
      JLabel expirationLbl         = new JLabel("Expiration date");
 
      JComboBox titleCombo = new JComboBox(
             new String[] { "-", "Mr", "Mrs", "Miss" });
      JTextField firstNameTf    = new JTextField();
      JTextField lastNameTf     = new JTextField();
      JTextField address1Tf     = new JTextField();
      JTextField address2Tf     = new JTextField();
      JTextField cityTf         = new JTextField();
      JTextField zipTf          = new JTextField();
      JTextField countryTf      = new JTextField();
      JTextField phoneTf        = new JTextField();
      JTextField faxTf          = new JTextField();
      JTextField emailTf        = new JTextField();
      JComboBox bd1Combo = new JComboBox();
      for (int i=1; i<=12; i++) bd1Combo.addItem(""+i);
      JComboBox bd2Combo = new JComboBox();
      for (int i=1; i<=31; i++) bd2Combo.addItem(""+i);
      JComboBox bd3Combo = new JComboBox();
      for (int i=1900; i<2000; i++) bd3Combo.addItem(""+i);
      JComboBox referCombo = new JComboBox();
      referCombo.addItem("Friend");
      referCombo.addItem("Search engine");
      referCombo.addItem("Print Media");
      referCombo.addItem("Banner Add");
      referCombo.addItem("Other");
      JComboBox creditCardTypeCombo = new JComboBox();
      creditCardTypeCombo.addItem("VISA");
      creditCardTypeCombo.addItem("MasterCard");
      creditCardTypeCombo.addItem("American Express");
      JTextField creditCardNumberTf = new JTextField();
      JComboBox expiration1Combo = new JComboBox();
      for (int i=1; i<=12; i++) expiration1Combo.addItem(""+i);
      JComboBox expiration2Combo = new JComboBox();
      for (int i=1; i<=31; i++) expiration2Combo.addItem(""+i);
      JComboBox expiration3Combo = new JComboBox();
      for (int i=1900; i<=2000; i++) expiration3Combo.addItem(""+i);
 
      JPanel panelGeneral = new JPanel();
      panelGeneral.setLayout(null);
      panelGeneral.add(titleLbl);
      panelGeneral.setBorder(new TitledBorder("General Information"));
      titleLbl.setBounds(20, 20, 150, 20);
      panelGeneral.add(firstNameLbl);
      firstNameLbl.setBounds(20, 50, 150, 20);
      panelGeneral.add(lastNameLbl);
      lastNameLbl.setBounds(20, 80, 150, 20);
      panelGeneral.add(addressLbl);
      addressLbl.setBounds(20, 110, 150, 20);
      panelGeneral.add(cityLbl);
      cityLbl.setBounds(20, 170, 150, 20);
      panelGeneral.add(zipLbl);
      zipLbl.setBounds(20, 200, 150, 20);
      panelGeneral.add(countryLbl);
      countryLbl.setBounds(20, 230, 150, 20);
      panelGeneral.add(phoneLbl);
      phoneLbl.setBounds(20, 260, 150, 20);
      panelGeneral.add(faxLbl);
      faxLbl.setBounds(20, 290, 150, 20);
      panelGeneral.add(emailLbl);
      emailLbl.setBounds(20, 320, 150, 20);
      panelGeneral.add(birthdayLbl);
      birthdayLbl.setBounds(20, 350, 150, 20); 
      panelGeneral.add(titleCombo);
      titleCombo.setBounds(150, 20, 60, 20);
      panelGeneral.add(firstNameTf);
      firstNameTf.setBounds(150, 50, 200, 20);
      panelGeneral.add(lastNameTf);
      lastNameTf.setBounds(150, 80, 200, 20);
      panelGeneral.add(address1Tf);
      address1Tf.setBounds(150, 110, 200, 20);  
      panelGeneral.add(address2Tf);
      address2Tf.setBounds(150, 140, 200, 20);  
      panelGeneral.add(cityTf);
      cityTf.setBounds(150, 170, 200, 20);
      panelGeneral.add(zipTf);
      zipTf.setBounds(150, 200, 200, 20);
      panelGeneral.add(countryTf);
      countryTf.setBounds(150, 230, 200, 20);
      panelGeneral.add(phoneTf);
      phoneTf.setBounds(150, 260, 200, 20);
      panelGeneral.add(faxTf);
      faxTf.setBounds(150, 290, 200, 20);
      panelGeneral.add(emailTf);
      emailTf.setBounds(150, 320, 200, 20);
      panelGeneral.add(bd1Combo);
      bd1Combo.setBounds(150, 350, 60, 20);
      panelGeneral.add(bd2Combo);
      bd2Combo.setBounds(220, 350, 60, 20);
      panelGeneral.add(bd3Combo);
      bd3Combo.setBounds(290, 350, 60, 20);
 
      JPanel panelReferral = new JPanel();
      panelReferral.setLayout(null);
      panelReferral.setBorder(new TitledBorder("Where did you hear about us?"));
      panelReferral.add(pickchoiceLbl);
      pickchoiceLbl.setBounds(20, 20, 150, 20);
      panelReferral.add(referCombo);
      referCombo.setBounds(150, 20, 100, 20);
 
      JPanel panelCreditCard = new JPanel();
      panelCreditCard.setLayout(null);
      panelCreditCard.setBorder(new TitledBorder("Payment method"));
      panelCreditCard.add(creditCardTypeLbl);
      creditCardTypeLbl.setBounds(20, 20, 150, 20);
      panelCreditCard.add(creditCardNumberLbl);
      creditCardNumberLbl.setBounds(20, 50, 150, 20);
      panelCreditCard.add(expirationLbl);
      expirationLbl.setBounds(20, 80, 150, 20);
 
      panelCreditCard.add(creditCardTypeCombo);
      creditCardTypeCombo.setBounds(150, 20, 100, 20);
      panelCreditCard.add(creditCardNumberTf);
      creditCardNumberTf.setBounds(150, 50, 150, 20);
      panelCreditCard.add(expiration2Combo);
      expiration2Combo.setBounds(220, 80, 60, 20);
      panelCreditCard.add(expiration3Combo);
      expiration3Combo.setBounds(290, 80, 60, 20);
 
      JPanel panel = new JPanel();
      panel.setLayout(null);
      panel.add(panelGeneral);
      panelGeneral.setBounds(10, 20, 370, 400);
      panel.add(panelReferral);
      panelReferral.setBounds(10, 430, 370, 50);
      panel.add(panelCreditCard);
      panelCreditCard.setBounds(10, 490, 370, 120);
      
      panel.setPreferredSize(new Dimension(380, 620)); 
 
      return panel;
   }
 
   public void saveComponent(Component c, String filename) {
      Dimension d = c.getPreferredSize();
      BufferedImage bi = new BufferedImage((int) d.getWidth(), (int) d.getHeight(),
                                           BufferedImage.TYPE_INT_RGB);
 
      Graphics2D g2 = bi.createGraphics();
      g2.setClip(0, 0, (int) d.getWidth(), (int) d.getHeight());
      c.paint(g2);
      try {
         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filename));
         JPGWrite(bi, bos);
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   }
 
   public static void JPGWrite(BufferedImage bi, OutputStream out) throws IOException {
      JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
      JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
      param.setQuality(1f, true);
      encoder.encode(bi, param);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
}

CharSets available on your machine

Main.java:

import java.nio.charset.*;
import java.util.*;
 
public class Main
{
   public static void main(String []args) {
      SortedMap charsets = Charset.availableCharsets();
 
      Collection c = charsets.values();
      Iterator charsetIterator = c.iterator();
      while (charsetIterator.hasNext()) {
         Charset charset = (Charset) charsetIterator.next();         
         System.out.println(charset + " with aliases:");
 
         Set aliases = charset.aliases();
         Iterator aliasIterator = aliases.iterator();
         while (aliasIterator.hasNext()) {
            String alias = (String) aliasIterator.next();
            System.out.println("t" + alias);
         }
         System.out.println();
      }
   }
}

outputs on my Win2000 machine:

ISO-8859-1 with aliases:
	ISO_8859-1:1987
	ISO8859_1
	8859_1
	iso-ir-100
	cp819
	ISO_8859_1
	ISO8859-1
	latin1
	IBM819
	IBM-819
	l1
	ISO_8859-1
	csISOLatin1
	819

ISO-8859-15 with aliases:
	8859_15
	923
	LATIN9
	ISO_8859-15
	ISO8859_15_FDIS
	cp923
	L9
	LATIN0
	csISOlatin9
	ISO8859-15
	IBM923
	ISO-8859-15
	IBM-923
	csISOlatin0

US-ASCII with aliases:
	us
	ISO_646.irv:1991
	ANSI_X3.4-1968
	iso-ir-6
	646
	ISO646-US
	cp367
	ANSI_X3.4-1986
	csASCII
	ASCII
	iso_646.irv:1983
	IBM367

UTF-16 with aliases:
	UTF_16

UTF-16BE with aliases:
	X-UTF-16BE
	ISO-10646-UCS-2
	UTF_16BE

UTF-16LE with aliases:
	UTF_16LE
	X-UTF-16LE

UTF-8 with aliases:
	UTF8

windows-1252 with aliases:
	cp1252