Creating a multi-line text JLabel

The easiest way is to hardcode HTML inside your JLabel text. JLabel has the functionality to render HTML. Another way is to write a custom Jlabel UI for your l&f that is able to understand escape sequences like n.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JLabel label = new JLabel("<html>Java resources at<br>esus.com<html>");
      getContentPane().add(label);     
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      pack();
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Showing the EURO symbol in a JLabel

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      final JLabel label = new JLabel("Become a member for u20AC14.95");
      getContentPane().add(label);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      pack();
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Setting the icon of a JFileChooser

showOpenDialog takes a component as its first argument. It is called the parent and used for several purposes. One of these it to find out which is the nearest JFrame, from which it will inherit the top-left icon. So the icon will be inherited. If you want your own customized icon, just create a dummy JFrame with another icon.

   JFrame dummy = new JFrame();
   ImageIcon icon = new ImageIcon("c:\test.gif");
   dummy.setIconImage(icon.getImage());
   ...
   fc.showOpenDialog(dummy);

Here’s a working code example:

import java.awt.event.*;
import javax.swing.*;
import java.io.*;
 
public class Main extends JFrame
{
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
 
   public Main() {
      JButton fileButton = new JButton("Select File");
      fileButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            File file = getFileFromUser();
            if (file != null)
               System.out.println(file.getName());
         }
      });
      getContentPane().add(fileButton);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
 
      // set the icon
      ImageIcon icon = new ImageIcon("c:\test.gif");
      setIconImage(icon.getImage());
 
      pack();
   }
   
   public File getFileFromUser() {
      JFileChooser fc = new JFileChooser();
 
      // use current directory
      fc.setCurrentDirectory(new File("c:\"));
 
      // set default name
      fc.setSelectedFile(new File("autoexec.bat"));
 
      // show dialog for opening files
      int result = fc.showOpenDialog(this);
 
      if (result != fc.APPROVE_OPTION) 
         return null;
      
      return fc.getSelectedFile();
   }
}

Detecting a double-click on a row in a JTable

Make sure your class implements the MouseListener interface, and use the following code to detect a double-click on a table row:

public void mouseClicked(MouseEvent e) {
   if (e.getClickCount() == 2) {
      JTable target = (JTable)e.getSource();
      int row = target.getSelectedRow();
      ...
   }
}

Creating a JTable with headers with JTooltips

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



ToolTipHeaderTableExample.java:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;

/**
 * @version 1.0 02/25/99
 */
public class ToolTipHeaderTableExample extends JPanel {

  public ToolTipHeaderTableExample(){
    setLayout(new BorderLayout());
    String[] headerStr  = {"default","jw"      ,"ja"      ,"la"   ,"unknown"};
    String[] toolTipStr = {""       ,"Javanese","Japanese","Latin"};
    
    DefaultTableModel dm = new DefaultTableModel(headerStr, 4);
    JTable table = new JTable(dm);
    
    ToolTipHeader header = new ToolTipHeader(table.getColumnModel());
    header.setToolTipStrings(toolTipStr);
    header.setToolTipText("Default ToolTip TEXT");
    table.setTableHeader(header);
    
    JScrollPane pane = new JScrollPane(table);
    add(pane, BorderLayout.CENTER);
  }

  public static void main(String[] args) {
    JFrame f= new JFrame("ToolTipHeaderTable Example");
    f.getContentPane().add(new ToolTipHeaderTableExample(), BorderLayout.CENTER);
    f.setSize(400, 100);
    f.setVisible(true);
    f.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {System.exit(0);}
    });
  }
    
  class ToolTipHeader extends JTableHeader {
    String[] toolTips;
  
    public ToolTipHeader(TableColumnModel model) {
      super(model);
    }
    
    public String getToolTipText(MouseEvent e) {
      int col  = columnAtPoint(e.getPoint());
      int modelCol = getTable().convertColumnIndexToModel(col);
      String retStr;
      try {
        retStr = toolTips[modelCol];
      } catch (NullPointerException ex) {
        retStr = "";
      } catch (ArrayIndexOutOfBoundsException ex) {
        retStr = "";
      }
      if (retStr.length() < 1) {
        retStr = super.getToolTipText(e);
      }
      return retStr;
    }   
    
    public void setToolTipStrings(String[] toolTips) {
      this.toolTips = toolTips;
    } 
  }
}

Creating a JTable with editable headers

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



EditableHeaderTableExample.java:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
 
/**
 * @version 1.0 08/22/99
 */
public class EditableHeaderTableExample extends JFrame {

  public EditableHeaderTableExample(){
    super( "EditableHeader Example" );
    
    JTable table = new JTable(7, 5);
    TableColumnModel columnModel = table.getColumnModel();
    table.setTableHeader(new EditableHeader(columnModel));
    
    JScrollPane pane = new JScrollPane(table);
    getContentPane().add(pane);
  }

  public static void main(String[] args) {
    EditableHeaderTableExample frame = new EditableHeaderTableExample();
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    frame.setSize( 300, 100 );
    frame.setVisible(true);
  }
}

EditableHeader.java:

import java.util.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;


/**
 * @version 1.0 08/21/99
 */
public class EditableHeader extends JTableHeader
                         implements CellEditorListener {
  public final int HEADER_ROW = -10;
  transient protected int editingColumn;
  transient protected TableCellEditor cellEditor;
  transient protected Component       editorComp;

  public EditableHeader(TableColumnModel columnModel) {
    super(columnModel);
    setReorderingAllowed(false);
    cellEditor = null;
    recreateTableColumn(columnModel);
  }
  
  public void updateUI(){
    setUI(new EditableHeaderUI());
    resizeAndRepaint();
    invalidate();
  }
  
  protected void recreateTableColumn(TableColumnModel columnModel) {
    int n = columnModel.getColumnCount();
    EditableHeaderTableColumn[] newCols = new EditableHeaderTableColumn[n];
    TableColumn[] oldCols = new TableColumn[n];
    for (int i=0;i<n;i++) {
      oldCols[i] = columnModel.getColumn(i);
      newCols[i] = new EditableHeaderTableColumn();
      newCols[i].copyValues(oldCols[i]);
    }
    for (int i=0;i<n;i++) {
      columnModel.removeColumn(oldCols[i]);
    }
    for (int i=0;i<n;i++) {
      columnModel.addColumn(newCols[i]);
    }
  }

  public boolean editCellAt(int index){
    return editCellAt(index);
  }
  
  public boolean editCellAt(int index, EventObject e){
    if (cellEditor != null && !cellEditor.stopCellEditing()) { 
      return false;
    }
    if (!isCellEditable(index)) {
      return false;
    }    
    TableCellEditor editor = getCellEditor(index);
    
    if (editor != null && editor.isCellEditable(e)) {
      editorComp = prepareEditor(editor, index);
      editorComp.setBounds(getHeaderRect(index));
      add(editorComp);
      editorComp.validate();
      setCellEditor(editor);
      setEditingColumn(index);
      editor.addCellEditorListener(this);

      return true;
    }    
    return false;
  }

  
  public boolean isCellEditable(int index) {
    if (getReorderingAllowed()) {
      return false;
    }
    int columnIndex = columnModel.getColumn(index).getModelIndex();
    EditableHeaderTableColumn col = (EditableHeaderTableColumn)columnModel.getColumn(columnIndex);
    return col.isHeaderEditable();
  }
  
  public TableCellEditor getCellEditor(int index) {
    int columnIndex = columnModel.getColumn(index).getModelIndex();
    EditableHeaderTableColumn col = (EditableHeaderTableColumn)columnModel.getColumn(columnIndex);
    return col.getHeaderEditor();
  }
  
  public void setCellEditor(TableCellEditor newEditor) {
    TableCellEditor oldEditor = cellEditor;
    cellEditor = newEditor;
    
    // firePropertyChange
    
    if (oldEditor != null && oldEditor instanceof TableCellEditor) {
      ((TableCellEditor)oldEditor).removeCellEditorListener((CellEditorListener)this);
    }
    if (newEditor != null && newEditor instanceof TableCellEditor) {
      ((TableCellEditor)newEditor).addCellEditorListener((CellEditorListener)this);
    }
  }

  public Component prepareEditor(TableCellEditor editor, int index) {
    Object       value = columnModel.getColumn(index).getHeaderValue();
    boolean isSelected = true;
    int            row = HEADER_ROW;
    JTable       table = getTable();
    Component comp = editor.getTableCellEditorComponent(table,
                       value, isSelected, row, index);
    if (comp instanceof JComponent) { 
            ((JComponent)comp).setNextFocusableComponent(this);             
    }
    return comp;
  }
  
  public TableCellEditor getCellEditor() {
    return cellEditor;
  }
  
  public Component getEditorComponent() {
    return editorComp;
  }
  
  public void setEditingColumn(int aColumn) {
    editingColumn = aColumn;
  }
  
  public int getEditingColumn() {
    return editingColumn;
  }
  
  public void removeEditor() {
    TableCellEditor editor = getCellEditor();
    if (editor != null) {
      editor.removeCellEditorListener(this);

      requestFocus();
      remove(editorComp);
      
      int index = getEditingColumn();
      Rectangle cellRect = getHeaderRect(index);

      setCellEditor(null);
      setEditingColumn(-1);
      editorComp = null;

      repaint(cellRect);
    }
  }
  
  public boolean isEditing() {
    return (cellEditor == null)? false : true;
  }

  
  //
  // CellEditorListener
  //
  public void editingStopped(ChangeEvent e) {
    TableCellEditor editor = getCellEditor();
    if (editor != null) {
      Object value = editor.getCellEditorValue();
      int index = getEditingColumn();
      columnModel.getColumn(index).setHeaderValue(value);
      removeEditor();
    }
  }

  public void editingCanceled(ChangeEvent e) {
    removeEditor();
  }
  
  
  //
  // public void setReorderingAllowed(boolean b) {
  //   reorderingAllowed = false;
  // }

}

EditableHeaderUI.java:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import javax.swing.plaf.basic.*;


/**
 * @version 1.0 08/21/99
 */
public class EditableHeaderUI extends BasicTableHeaderUI {
    
  protected MouseInputListener createMouseInputListener() {
    return new MouseInputHandler((EditableHeader)header);
  }

  public class MouseInputHandler extends BasicTableHeaderUI.MouseInputHandler {
    private Component dispatchComponent;
    protected EditableHeader header;

    public MouseInputHandler(EditableHeader header) {
      this.header = header;
    }

    private void setDispatchComponent(MouseEvent e) { 
      Component editorComponent = header.getEditorComponent();
      Point p = e.getPoint();
      Point p2 = SwingUtilities.convertPoint(header, p, editorComponent);
      dispatchComponent = SwingUtilities.getDeepestComponentAt(editorComponent, 
                                                               p2.x, p2.y);
    }

    private boolean repostEvent(MouseEvent e) { 
      if (dispatchComponent == null) {
        return false; 
      }
      MouseEvent e2 = SwingUtilities.convertMouseEvent(header, e, dispatchComponent);
      dispatchComponent.dispatchEvent(e2); 
      return true; 
    }
    
    public void mousePressed(MouseEvent e) {
      if (!SwingUtilities.isLeftMouseButton(e)) {
        return;
      }
      super.mousePressed(e);

      if (header.getResizingColumn() == null) {
        Point p = e.getPoint();
        TableColumnModel columnModel = header.getColumnModel();
        int index = columnModel.getColumnIndexAtX(p.x);
        if (index != -1) {
          if (header.editCellAt(index, e)) {
            setDispatchComponent(e); 
            repostEvent(e); 
          }
        }
      }
    }

    public void mouseReleased(MouseEvent e) {
      super.mouseReleased(e);
      if (!SwingUtilities.isLeftMouseButton(e)) {
        return;
      }
      repostEvent(e); 
      dispatchComponent = null;    
    }
        
  } 
}

EditableHeaderTableColumn.java:

import javax.swing.*;
import javax.swing.table.*;


/**
 * @version 1.0 08/21/99
 */
public class EditableHeaderTableColumn extends TableColumn {

  protected TableCellEditor headerEditor;
  protected boolean isHeaderEditable;

  public EditableHeaderTableColumn() {
    setHeaderEditor(createDefaultHeaderEditor());
    isHeaderEditable = true;
  }
  
  public void setHeaderEditor(TableCellEditor headerEditor) {
    this.headerEditor = headerEditor;
  }
  
  public TableCellEditor getHeaderEditor() {
    return headerEditor;
  }
  
  public void setHeaderEditable(boolean isEditable) {
    isHeaderEditable = isEditable;
  }
  
  public boolean isHeaderEditable() {
    return isHeaderEditable;
  }
  
  public void copyValues(TableColumn base) {    
    modelIndex     = base.getModelIndex();
    identifier     = base.getIdentifier();
    width          = base.getWidth();
    minWidth       = base.getMinWidth();
    setPreferredWidth(base.getPreferredWidth());
    maxWidth       = base.getMaxWidth();
    headerRenderer = base.getHeaderRenderer();
    headerValue    = base.getHeaderValue();
    cellRenderer   = base.getCellRenderer();
    cellEditor     = base.getCellEditor();
    isResizable    = base.getResizable();
  }
  
  protected TableCellEditor createDefaultHeaderEditor() {
    return new DefaultCellEditor(new JTextField());
  }
  
}

Change the orientation of a JTextArea, eg. right to left

You can use the method setComponentOrientation defined in the Component class, so
you can invoke it on most Swing components.
It does not seem to work properly using JDK1.2, but does with JDK1.3.

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
   
public class Main extends JFrame
{
   public Main() throws Exception {
      JTextArea tf = new JTextArea();
      getContentPane().add(tf);
      pack();

      tf.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String args[]) throws Exception {
      Main main = new Main();
      main.show();
   }
}

For international applications, you can determine the orientation using
the Locale:

      Locale arabic = new Locale("ar", "SA");
      jcomponent.setComponentOrientation(ComponentOrientation.getOrientation(arabic));

Retrieving the links in an HTML document

LinkExtractor.java:

package htmltools;
 
import java.net.URL;
import java.net.InetAddress;
import java.net.MalformedURLException;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

import java.util.Collection;
import java.util.ArrayList;

import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.*;

/**
 * This class takes a URL and, if it is valid, extracts all the external 
 * and local links and stores them in distinct ArrayLists.
 * It provides accessors to the two lists.
 */
public class LinkExtractor
{
    private URL m_zURL = null;
    private CallbackHandler m_zHandler;
    
    /**
     * Initialize the URL. 
     * You can provide URLs in the following form:<br>
     * <font color="blue">
     * http://www.something.ext<br>
     * www.something.ext<br>
     * something.ext<br>
     * </font>
     * In the last case the extractor assumes the URL is on the local
     * host and tries to open it at the local host
     */
    public LinkExtractor(String sURL) throws MalformedURLException, IOException {
	/* End-users don't like typing http, so 
	   we'll give them a hand */
	if (sURL.startsWith("www.")) {
	    sURL = "http://"+sURL;
	} else if (!sURL.startsWith("http")) {
	    /* there is neither an http protocol specified,
	       and the address does not start with www.
	       We will try to find this document on the local host.
	       Of course, this behavior does not cover all cases.
	       For example the user may try an ftp protocol, 
	       or, accostomed to modern day browsers, omit www altogether.
	       Oh well ...
	    */
	    InetAddress zAddr = InetAddress.getLocalHost();
	    sURL = "http://"+zAddr.getHostName()+"/"+sURL;
	}
	
	m_zURL = new URL(sURL);
	m_zHandler = new CallbackHandler();
	parse();
    }

    /**
     * return and ArrayList of all external links
     */
    public Collection getExternalLinks()  {
	if (null == m_zURL)
	    return null;
	return m_zHandler.m_clExternalLinks;    
    }
    
    /**
     * return and ArrayList of all local links
     */ 
    public Collection getLocalLinks()  {
	if (null == m_zURL)
	    return null;
	return m_zHandler.m_clLocalLinks;    
    }
  
  private void parse() throws IOException {
    // establish connection to site
      BufferedReader zReader = new BufferedReader
	  (new InputStreamReader(m_zURL.openStream()));
      // parse it to get the links
      new ParserDelegator().parse(zReader, m_zHandler, true);
      zReader.close();
  }
    
    private class CallbackHandler extends HTMLEditorKit.ParserCallback 
    {
	ArrayList m_clExternalLinks;
	ArrayList m_clLocalLinks;
	
	public CallbackHandler() {
	    
	    m_clExternalLinks = new ArrayList();
	    m_clLocalLinks = new ArrayList();
	}
	
	/**
	 * Invoked when text in the html document is encountered. Based on
	 * the current state, this will either do nothing
	 * or add an href attribute
	 */
	public void handleText(char[] data, int pos) {
	    // System.out.println(new String(data));
	}
	/**
	 * Invoked when a start tag is encountered. 
	 */
	public void handleStartTag(HTML.Tag zTag, 
				   MutableAttributeSet zAttributes,
				   int iPosition) {
	    String sLink = null;
	    
	    if (zTag.equals(HTML.Tag.A) ||
		zTag.equals(HTML.Tag.ADDRESS)) {
		
		sLink = (String)zAttributes.getAttribute(HTML.Attribute.HREF);
		if (null == sLink) { 
		    
		} else if (sLink.startsWith("http")) {
		    if (!m_clExternalLinks.contains((String)sLink)) {
			m_clExternalLinks.add((String)sLink);
		    }
		} else if (!m_clLocalLinks.contains((String)sLink)) {
		    m_clLocalLinks.add((String)sLink);
		} 
	    }
	}
	
	
	/**
	 * Invoked when the end of a tag is encountered. 
	 */
	public void handleEndTag(HTML.Tag t, int pos) {
	    
	}	    
   }

    /*
     * The main method is provided only for testing.
     */
    static void main(String[] asArgs) throws Exception {
	if (asArgs.length < 1) {
	    System.out.println("Usage: java GetLinks <URL>");
	    System.exit(0);
	}
	String sURL = asArgs[0];

	LinkExtractor gl = new LinkExtractor(sURL);
	ArrayList clLinks = (ArrayList) gl.getExternalLinks();
	
	for (int i=0;i<clLinks.size();i++) {
	    System.out.println((String)clLinks.get(i));
	}
	
	ArrayList clLocalLinks = (ArrayList) gl.getLocalLinks();	
	for (int i=0;i<clLocalLinks.size();i++) {
	    System.out.println((String)clLocalLinks.get(i));
	}
    }
}

Converting an XML to an HTML using XSLT with Xalan

Xalan is an Apache implementation of the W3C recommendations for XSL transformations, XSLT. XSLT allows you to transform xml documents in an HTML, another XML or whatever format you desire.

Download Xalan at http://xml.apache.org/xalan-j/index.html.

You can apply an XSL to an XML document with command line. Make sure xalan.xml is in your classpath before trying out this example. It will create an HTML file (check it out!) from an XML.

  
  java org.apache.xalan.xslt.Process -in customers.xml -xsl customers.xsl -out customers.html

customers.xml (!!remove the space between ? and xml):

<? xml version="1.0"?>
<!DOCTYPE customers SYSTEM "customers.dtd">
 
<customers>
   <customer id="cust1">
      <name>Joris Van den Bogaert</name>
      <address>
         <addressline1>Handelskaai 3</addressline1>
         <zip>1000</zip>
         <location>Brussels</location>
         <country>BE</country>
      </address>
      <address>
         <addressline1>A. Dewitstraat 50</addressline1>
         <zip>3078</zip>
         <location>Meerbeek</location>
         <country>BE</country>
      </address>
   </customer>
  
   <customer id="cust2">
      <name>Alicia Kolesnikova</name>
      <address>
         <addressline1>Handelskaai 3</addressline1>
         <zip>1000</zip>
         <location>Brussels</location>
         <country>BE</country>
      </address>
   </customer>
</customers>

customers.dtd:

<!ELEMENT customers (customer*)>
<!ELEMENT customer (name, address+)>
<!ELEMENT address (addressline1, addressline2, zip, location, country)>
 
<!ELEMENT name (#PCDATA)>
 
<!ELEMENT addressline1 (#PCDATA)>
<!ELEMENT addressline2 (#PCDATA)>
<!ELEMENT zip (#PCDATA)>
<!ELEMENT location (#PCDATA)>
<!ELEMENT country (#PCDATA)>
 
<!ATTLIST customer
   id NMTOKEN #REQUIRED
>

customers.xsl (!!remove the space between ? and xml):

<? xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
 
<xsl:template match="customers">
<html>
   <head><title>Customers</title></head>
   <body>
      <h1>Customers</h1>
      <table border="1">
         <th>Customer ID</th>
         <th>Name</th>
         <th>Addresses</th>
     
         <xsl:apply-templates/>
 
      </table>
   </body>
</html>
</xsl:template>
 
<xsl:template match="customer">
   <tr>
      <td><xsl:value-of select="@id"/></td>
      <td><xsl:value-of select="name"/></td>
 
      <td><xsl:apply-templates select="address"/></td>
   </tr>
</xsl:template>
 
<xsl:template match="address">
   <xsl:value-of select="addressline1"/>
   <xsl:if test="string(addressline2) != string('')">
      &#160;<xsl:value-of select="addressline2"/>
   </xsl:if>,
   <xsl:value-of select="zip"/>&#160;<xsl:value-of select="location"/> 
   [<xsl:value-of select="country"/>]<br/>
</xsl:template>
 
</xsl:stylesheet>