Creating a JLabel with the text on top of the image

You can play around with the methods setHorizontalTextAlignment and setVerticalTextAlignment as shown in the following example:

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("esus.com", new ImageIcon("esuslogo.gif"), JLabel.CENTER);
      label.setHorizontalTextPosition(JLabel.CENTER); 
      getContentPane().add(label);     
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      pack();
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Drawing a shape inside a JLabel

You can override the paint() method, call super.paint(g) and draw your shape as shown in following example.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   JLabel label;
 
   public Main() {
      label = new JLabel("This label will be overwritten with circles") {
         public void paint(Graphics g) {
            super.paint(g);
            double width = this.getSize().getWidth();
            double height = this.getSize().getHeight();
            g.setColor(Color.red);
            for (int i=0; i<width; i+=height) {
               g.drawOval(i, 0, (int) height, (int) height);
            }
         }
      };
      label.setForeground(Color.blue);
      label.setOpaque(true);
      getContentPane().add(BorderLayout.SOUTH, label);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      }); 
  
      setSize(350, 150);
   }
  
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
   }
}

Setting a file filter in a JFileChooser dialog

Here’s an example that shows you how to restrict the files shown in the dialog. It will only show the .gif files. The idea is to create a FileFilter and implement the method accept that will be invoked for every file in the selected directory. You can specify any custom filtering in there.

import javax.swing.filechooser.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.File;
 
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(getGifFileFilter());
            if (file != null)
               System.out.println(file.getName());
         }
      });
      getContentPane().add(fileButton);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
 
      pack();
   }
   
   public FileFilter getGifFileFilter() {
      FileFilter ff = new FileFilter() {
         public boolean accept(File f) {
            if (f.isDirectory()) 
               return true;
            else if (f.getName().toLowerCase().endsWith(".gif"))
               return true;
            return false;
         }
 
         public String getDescription() {
            return "GIF image";
         }
      };
 
      return ff;
   }
   
   public File getFileFromUser(FileFilter ff) {
      JFileChooser fc = new JFileChooser();
 
      // use current directory
      fc.setCurrentDirectory(new File("c:\"));
 
      // set file filter if specified
      if (ff != null)
         fc.setFileFilter(ff);
 
      // show dialog for opening files
      int result = fc.showOpenDialog(this);
 
      if (result != fc.APPROVE_OPTION) 
         return null;
       
      return fc.getSelectedFile();
   }
}

Detecting row selection in a JTable

Add a MouseListener to the table, and code the mousePressed event like this…

  public void mousePressed(MouseEvent e)
  {
    if ((e.getModifiers() & InputEvent.BUTTON1_MASK)!=0)
    {
      int row = JTable_Name.getSelectedRow();
      System.out.println(row);
    }
  }

Creating a JTable with nested headers

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



GroupableHeaderExample.java:

/* (swing1.1beta3)
 *
 * |-----------------------------------------------------|
 * |        |       Name      |         Language         |
 * |        |-----------------|--------------------------|
 * |  SNo.  |        |        |        |      Others     |
 * |        |   1    |    2   | Native |-----------------|
 * |        |        |        |        |   2    |   3    |  
 * |-----------------------------------------------------|
 * |        |        |        |        |        |        |
 *
 */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
 
/**
 * @version 1.0 11/09/98
 */
public class GroupableHeaderExample extends JFrame {
 
  GroupableHeaderExample() {
    super( "Groupable Header Example" );
 
    DefaultTableModel dm = new DefaultTableModel();
    dm.setDataVector(new Object[][]{
      {"119","foo","bar","ja","ko","zh"},
      {"911","bar","foo","en","fr","pt"}},
    new Object[]{"SNo.","1","2","Native","2","3"});
 
    JTable table = new JTable( dm ) {
      protected JTableHeader createDefaultTableHeader() {
        return new GroupableTableHeader(columnModel);
      }
    };
    TableColumnModel cm = table.getColumnModel();
    ColumnGroup g_name = new ColumnGroup("Name");
    g_name.add(cm.getColumn(1));
    g_name.add(cm.getColumn(2));
    ColumnGroup g_lang = new ColumnGroup("Language");
    g_lang.add(cm.getColumn(3));
    ColumnGroup g_other = new ColumnGroup("Others");
    g_other.add(cm.getColumn(4));
    g_other.add(cm.getColumn(5));
    g_lang.add(g_other);
    GroupableTableHeader header = (GroupableTableHeader)table.getTableHeader();
    header.addColumnGroup(g_name);
    header.addColumnGroup(g_lang);
    JScrollPane scroll = new JScrollPane( table );
    getContentPane().add( scroll );
    setSize( 400, 120 );   
  }
 
  public static void main(String[] args) {
    GroupableHeaderExample frame = new GroupableHeaderExample();
    frame.addWindowListener( new WindowAdapter() {
      public void windowClosing( WindowEvent e ) {
        System.exit(0);
      }
    });
    frame.setVisible(true);
  }
}

ColumnGroup.java:

import java.util.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
 
  
/**
  * ColumnGroup
  *
  * @version 1.0 10/20/98
  * @author Nobuo Tamemasa
  */
 
public class ColumnGroup {
  protected TableCellRenderer renderer;
  protected Vector v;
  protected String text;
  protected int margin=0;
 
  public ColumnGroup(String text) {
    this(null,text);
  }
 
  public ColumnGroup(TableCellRenderer renderer,String text) {
    if (renderer == null) {
      this.renderer = new DefaultTableCellRenderer() {
        public Component getTableCellRendererComponent(JTable table, Object value,
                         boolean isSelected, boolean hasFocus, int row, int column) {
          JTableHeader header = table.getTableHeader();
          if (header != null) {
            setForeground(header.getForeground());
            setBackground(header.getBackground());
            setFont(header.getFont());
          }
          setHorizontalAlignment(JLabel.CENTER);
          setText((value == null) ? "" : value.toString());
          setBorder(UIManager.getBorder("TableHeader.cellBorder"));
          return this;
        }
      };
    } else {
      this.renderer = renderer;
    }
    this.text = text;
    v = new Vector();
  }
 
   
  /**
   * @param obj    TableColumn or ColumnGroup
   */
  public void add(Object obj) {
    if (obj == null) { return; }
    v.addElement(obj);
  }
 
  
  /**
   * @param c    TableColumn
   * @param v    ColumnGroups
   */
  public Vector getColumnGroups(TableColumn c, Vector g) {
    g.addElement(this);
    if (v.contains(c)) return g;    
    Enumeration enum = v.elements();
    while (enum.hasMoreElements()) {
      Object obj = enum.nextElement();
      if (obj instanceof ColumnGroup) {
        Vector groups = 
          (Vector)((ColumnGroup)obj).getColumnGroups(c,(Vector)g.clone());
        if (groups != null) return groups;
      }
    }
    return null;
  }
    
  public TableCellRenderer getHeaderRenderer() {
    return renderer;
  }
    
  public void setHeaderRenderer(TableCellRenderer renderer) {
    if (renderer != null) {
      this.renderer = renderer;
    }
  }
    
  public Object getHeaderValue() {
    return text;
  }
  
  public Dimension getSize(JTable table) {
    Component comp = renderer.getTableCellRendererComponent(
        table, getHeaderValue(), false, false,-1, -1);
    int height = comp.getPreferredSize().height; 
    int width  = 0;
    Enumeration enum = v.elements();
    while (enum.hasMoreElements()) {
      Object obj = enum.nextElement();
      if (obj instanceof TableColumn) {
        TableColumn aColumn = (TableColumn)obj;
        width += aColumn.getWidth();
        width += margin;
      } else {
        width += ((ColumnGroup)obj).getSize(table).width;
      }
    }
    return new Dimension(width, height);
  }
 
  public void setColumnMargin(int margin) {
    this.margin = margin;
    Enumeration enum = v.elements();
    while (enum.hasMoreElements()) {
      Object obj = enum.nextElement();
      if (obj instanceof ColumnGroup) {
        ((ColumnGroup)obj).setColumnMargin(margin);
      }
    }
  }
}

GroupableTableHeader.java:

import java.util.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
 
/**
  * GroupableTableHeader
  *
  * @version 1.0 10/20/98
  * @author Nobuo Tamemasa
  */
 
public class GroupableTableHeader extends JTableHeader {
  private static final String uiClassID = "GroupableTableHeaderUI";
  protected Vector columnGroups = null;
    
  public GroupableTableHeader(TableColumnModel model) {
    super(model);
    setUI(new GroupableTableHeaderUI());
    setReorderingAllowed(false);
  }
  
  public void setReorderingAllowed(boolean b) {
    reorderingAllowed = false;
  }
    
  public void addColumnGroup(ColumnGroup g) {
    if (columnGroups == null) {
      columnGroups = new Vector();
    }
    columnGroups.addElement(g);
  }
 
  public Enumeration getColumnGroups(TableColumn col) {
    if (columnGroups == null) return null;
    Enumeration enum = columnGroups.elements();
    while (enum.hasMoreElements()) {
      ColumnGroup cGroup = (ColumnGroup)enum.nextElement();
      Vector v_ret = (Vector)cGroup.getColumnGroups(col,new Vector());
      if (v_ret != null) { 
        return v_ret.elements();
      }
    }
    return null;
  }
   
  public void setColumnMargin() {
    if (columnGroups == null) return;
    int columnMargin = getColumnModel().getColumnMargin();
    Enumeration enum = columnGroups.elements();
    while (enum.hasMoreElements()) {
      ColumnGroup cGroup = (ColumnGroup)enum.nextElement();
      cGroup.setColumnMargin(columnMargin);
    }
  } 
}

GroupableTableHeaderUI.java:

import java.util.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.plaf.basic.*;
 
public class GroupableTableHeaderUI extends BasicTableHeaderUI {
  
  public void paint(Graphics g, JComponent c) {
    Rectangle clipBounds = g.getClipBounds();
    if (header.getColumnModel() == null) return;
    ((GroupableTableHeader)header).setColumnMargin();
    int column = 0;
    Dimension size = header.getSize();
    Rectangle cellRect  = new Rectangle(0, 0, size.width, size.height);
    Hashtable h = new Hashtable();
    int columnMargin = header.getColumnModel().getColumnMargin();
    
    Enumeration enumeration = header.getColumnModel().getColumns();
    while (enumeration.hasMoreElements()) {
      cellRect.height = size.height;
      cellRect.y      = 0;
      TableColumn aColumn = (TableColumn)enumeration.nextElement();
      Enumeration cGroups = ((GroupableTableHeader)header).getColumnGroups(aColumn);
      if (cGroups != null) {
        int groupHeight = 0;
        while (cGroups.hasMoreElements()) {
          ColumnGroup cGroup = (ColumnGroup)cGroups.nextElement();
          Rectangle groupRect = (Rectangle)h.get(cGroup);
          if (groupRect == null) {
            groupRect = new Rectangle(cellRect);
            Dimension d = cGroup.getSize(header.getTable());
            groupRect.width  = d.width;
            groupRect.height = d.height;    
            h.put(cGroup, groupRect);
          }
          paintCell(g, groupRect, cGroup);
          groupHeight += groupRect.height;
          cellRect.height = size.height - groupHeight;
          cellRect.y      = groupHeight;
        }
      }      
      cellRect.width = aColumn.getWidth() + columnMargin;
      if (cellRect.intersects(clipBounds)) {
        paintCell(g, cellRect, column);
      }
      cellRect.x += cellRect.width;
      column++;
    }
  }
 
  private void paintCell(Graphics g, Rectangle cellRect, int columnIndex) {
    TableColumn aColumn = header.getColumnModel().getColumn(columnIndex);
    TableCellRenderer renderer = aColumn.getHeaderRenderer();
    Component component = renderer.getTableCellRendererComponent(
      header.getTable(), aColumn.getHeaderValue(),false, false, -1, columnIndex);
    rendererPane.add(component);
    rendererPane.paintComponent(g, component, header, cellRect.x, cellRect.y,
                                cellRect.width, cellRect.height, true);
  }
 
  private void paintCell(Graphics g, Rectangle cellRect,ColumnGroup cGroup) {
    TableCellRenderer renderer = cGroup.getHeaderRenderer();
    Component component = renderer.getTableCellRendererComponent(
      header.getTable(), cGroup.getHeaderValue(),false, false, -1, -1);
    rendererPane.add(component);
    rendererPane.paintComponent(g, component, header, cellRect.x, cellRect.y,
                                cellRect.width, cellRect.height, true);
  }
 
  private int getHeaderHeight() {
    int height = 0;
    TableColumnModel columnModel = header.getColumnModel();
    for(int column = 0; column < columnModel.getColumnCount(); column++) {
      TableColumn aColumn = columnModel.getColumn(column);
      TableCellRenderer renderer = aColumn.getHeaderRenderer();
      Component comp = renderer.getTableCellRendererComponent(
        header.getTable(), aColumn.getHeaderValue(), false, false,-1, column);
      int cHeight = comp.getPreferredSize().height;
      Enumeration enum = ((GroupableTableHeader)header).getColumnGroups(aColumn);      
      if (enum != null) {
        while (enum.hasMoreElements()) {
          ColumnGroup cGroup = (ColumnGroup)enum.nextElement();
          cHeight += cGroup.getSize(header.getTable()).height;
        }
      }
      height = Math.max(height, cHeight);
    }
    return height;
  }
 
  private Dimension createHeaderSize(long width) {
    TableColumnModel columnModel = header.getColumnModel();
    width += columnModel.getColumnMargin() * columnModel.getColumnCount();
    if (width > Integer.MAX_VALUE) {
      width = Integer.MAX_VALUE;
    }
    return new Dimension((int)width, getHeaderHeight());
  }
 
  public Dimension getPreferredSize(JComponent c) {
    long width = 0;
    Enumeration enumeration = header.getColumnModel().getColumns();
    while (enumeration.hasMoreElements()) {
      TableColumn aColumn = (TableColumn)enumeration.nextElement();
      width = width + aColumn.getPreferredWidth();
    }
    return createHeaderSize(width);
  }
}

Create borders for JTable cells

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



CellBorderTableExample.java:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import javax.swing.border.*;
 
/**
 * @version 1.0  3/06/99
 */
public class CellBorderTableExample extends JFrame {

  public CellBorderTableExample() {
    super( &quot;Cell Border Example&quot; );
    
    final Color color = UIManager.getColor(&quot;Table.gridColor&quot;);
        
    DefaultTableModel dm = new DefaultTableModel(12,6) {
      public void setValueAt(Object obj, int row, int col) {
        if (obj instanceof MyData) {
          super.setValueAt(obj, row, col);
        } else {
          MyData myData=null;
          Object oldObject = getValueAt(row, col);
          if (oldObject == null) {
            myData = new MyData(obj, new LinesBorder(color,0));
          } else if (oldObject instanceof MyData) {
            myData = (MyData)oldObject;
          } else {
            System.out.println(&quot;error&quot;);
            return;
          }
          myData.setObject(obj);
          super.setValueAt(myData, row, col);
        }
      }
    };
    
    JTable table = new JTable( dm );
    table.setIntercellSpacing(new Dimension(0,0));
    table.setCellSelectionEnabled(true);
    table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    table.setDefaultRenderer(Object.class, new BorderCellRenderer());

    JScrollPane scroll = new JScrollPane( table );
    ThicknessPanel thicknessPanel = new ThicknessPanel();
    Box box = new Box(BoxLayout.Y_AXIS);    
    box.add(thicknessPanel);
    box.add(new ButtonPanel(table, thicknessPanel));
    getContentPane().add(scroll, BorderLayout.CENTER);
    getContentPane().add(box,    BorderLayout.EAST);
  }

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

  
  class ThicknessPanel extends JPanel {    
    JComboBox[] combos;
    
    ThicknessPanel() {
      String[] str = {&quot;top&quot;,&quot;left&quot;,&quot;bottom&quot;,&quot;right&quot;};
      int n = str.length;
      setLayout(new GridLayout(n,2));
      setBorder(new TitledBorder(&quot;Thickness&quot;));
      combos = new JComboBox[n];
      for (int i=0;i&lt;n;i++) {
        combos[i] = new JComboBox(new Object[]{&quot;0&quot;,&quot;1&quot;,&quot;2&quot;,&quot;3&quot;});
        add(new JLabel(str[i]));
        add(combos[i]);
      }
    }
     
    public Insets getThickness() {
      Insets insets = new Insets(0,0,0,0);
      insets.top    = combos[0].getSelectedIndex();      
      insets.left   = combos[1].getSelectedIndex();      
      insets.bottom = combos[2].getSelectedIndex();      
      insets.right  = combos[3].getSelectedIndex();      
      return insets;      
    }
  }

  
  class ButtonPanel extends JPanel {
    JTable table;
    ThicknessPanel thicknessPanel;
    Color color = UIManager.getColor(&quot;Table.gridColor&quot;);
    
    ButtonPanel(JTable table, ThicknessPanel thicknessPanel) {
      this.table = table;
      this.thicknessPanel = thicknessPanel;
      setLayout(new GridLayout(3,1));
      setBorder(new TitledBorder(&quot;Append Lines&quot;));
      final JCheckBox oneBlock = new JCheckBox(&quot;Block&quot;);
      JButton b_and = new JButton(&quot;REPLACE&quot;);
      JButton b_or  = new JButton(&quot;OR&quot;);
      add(oneBlock);
      add(b_and);
      add(b_or);
      b_and.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          setCellBorder(true, oneBlock.isSelected());
        }
      });
      b_or.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          setCellBorder(false, oneBlock.isSelected());
        }
      });
    }  
    
    private void setCellBorder(boolean isReplace, boolean isBlock) {
      boolean isTop,isLeft,isBottom,isRight;
      Insets insets = thicknessPanel.getThickness();
      int[] columns = table.getSelectedColumns();
      int[] rows    = table.getSelectedRows();
      int rowMax    = rows.length;
      int columnMax = columns.length;
      
      for (int i=0;i&lt;rowMax;i++) {
        int row = rows[i];
        isTop    = (i == 0       )? true: false;
        isBottom = (i == rowMax-1)? true: false;
        
        for (int j=0;j&lt;columnMax;j++) {
          int column = columns[j];
          isLeft  = (j == 0          )? true: false;
          isRight = (j == columnMax-1)? true: false;
          
          MyData myData = (MyData)table.getValueAt(row, column);
          if (myData == null) {
            myData = new MyData(&quot;&quot;, new LinesBorder(color,0));
          }
          LinesBorder border = (LinesBorder)myData.getBorder();
          
          if (isBlock) {
            Insets tmp = new Insets(0,0,0,0);
            if (isTop)    tmp.top    = Math.max(tmp.top    ,insets.top);
            if (isLeft)   tmp.left   = Math.max(tmp.left   ,insets.left);
            if (isBottom) tmp.bottom = Math.max(tmp.bottom ,insets.bottom);
            if (isRight)  tmp.right  = Math.max(tmp.right  ,insets.right);
            border.append(tmp, isReplace);
          } else {
            border.append(insets, isReplace);
          }
          
          table.setValueAt(myData, row, column);
        }
      }
      table.clearSelection();
      table.revalidate();
      table.repaint();
    }  
  }
 
  class MyData implements CellBorder {
    private Border border;
    private Object obj;
    
    public MyData(Object obj, Border border) {
      this.obj    = obj;
      this.border = border;
    }
    
    public void setObject(Object obj) {
      this.obj = obj;
    }    
    public String toString() {
      return obj.toString();
    }
    
    // CellBorder   
    public void setBorder(Border border) {
      this.border = border;
    }   
    public Border getBorder() {
      return border;
    }
    public void setBorder(Border border, int row, int col) {}
    public Border getBorder(int row, int col) { return null; }
  }
}

BorderCellRenderer.java:

import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.border.*;
 
/**
 * @version 1.0 03/06/99
 */
public class BorderCellRenderer extends JLabel
    implements TableCellRenderer {
  protected Border noFocusBorder; 
  protected Border columnBorder; 
 
  public BorderCellRenderer() {
    noFocusBorder = new EmptyBorder(1, 2, 1, 2);
    setOpaque(true);
  }
 
  public Component getTableCellRendererComponent(JTable table, Object value,
                 boolean isSelected, boolean hasFocus, int row, int column) {
    if (isSelected) {
      setForeground(table.getSelectionForeground());
      setBackground(table.getSelectionBackground());
    } else {
      setForeground(table.getForeground());
      setBackground(table.getBackground());
    }
    setFont(table.getFont());
    
    if (hasFocus) {
      setBorder( UIManager.getBorder(&quot;Table.focusCellHighlightBorder&quot;) );
      if (table.isCellEditable(row, column)) {
        setForeground( UIManager.getColor(&quot;Table.focusCellForeground&quot;) );
        setBackground( UIManager.getColor(&quot;Table.focusCellBackground&quot;) );
      }
    } else {
      if (value instanceof CellBorder) {
        Border border = ((CellBorder)value).getBorder();
        setBorder(border);
      } else {
        if (columnBorder != null) {
          setBorder(columnBorder);
        } else {
          setBorder(noFocusBorder);
        }
      }
    }
    setText((value == null) ? &quot;&quot; : value.toString());        
    return this;
  }
  
  public void setColumnBorder(Border border) {
    columnBorder = border;
  }
   
  public Border getColumnBorder() {
    return columnBorder;
  }
     
}

CellBorder.java:

import java.awt.*;
import javax.swing.border.*;
 
/**
 * @version 1.0 03/06/99
 */
public interface CellBorder {
  
  public Border getBorder();
  public Border getBorder(int row, int column);
  
  public void setBorder(Border border);
  public void setBorder(Border border, int row, int column);
}

LinesBorder.java:

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;

/**
 * @version 1.0 03/09/99
 */
public class LinesBorder extends AbstractBorder implements SwingConstants { 
  protected int northThickness;
  protected int southThickness;
  protected int eastThickness;
  protected int westThickness;  
  protected Color northColor;
  protected Color southColor;
  protected Color eastColor;
  protected Color westColor;
  
  public LinesBorder(Color color) {
    this(color, 1);
  }

  public LinesBorder(Color color, int thickness)  {
    setColor(color);
    setThickness(thickness);
  }

  public LinesBorder(Color color, Insets insets)  {
    setColor(color);
    setThickness(insets);
  }

  public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
    Color oldColor = g.getColor();
    
    g.setColor(northColor);
    for (int i = 0; i &lt; northThickness; i++)  {
      g.drawLine(x, y+i, x+width-1, y+i);
    }
    g.setColor(southColor);
    for (int i = 0; i &lt; southThickness; i++)  {
      g.drawLine(x, y+height-i-1, x+width-1, y+height-i-1);
    }
    g.setColor(eastColor);
    for (int i = 0; i &lt; westThickness; i++)  {
      g.drawLine(x+i, y, x+i, y+height-1);
    }
    g.setColor(westColor);
    for (int i = 0; i &lt; eastThickness; i++)  {
      g.drawLine(x+width-i-1, y, x+width-i-1, y+height-1);
    }
 
    g.setColor(oldColor);
  }

  public Insets getBorderInsets(Component c)       {
    return new Insets(northThickness, westThickness, southThickness, eastThickness);
  }
 
  public Insets getBorderInsets(Component c, Insets insets) {
    return new Insets(northThickness, westThickness, southThickness, eastThickness);    
  }
 
  public boolean isBorderOpaque() { return true; }
    
  public void setColor(Color c) {
    northColor = c;
    southColor = c;
    eastColor  = c;
    westColor  = c;
  }
  
  public void setColor(Color c, int direction) {
    switch (direction) {
      case NORTH: northColor = c; break;
      case SOUTH: southColor = c; break;
      case EAST:  eastColor  = c; break;
      case WEST:  westColor  = c; break;
      default: 
    }
  }
    
  public void setThickness(int n) {
    northThickness = n;
    southThickness = n;
    eastThickness  = n;
    westThickness  = n;
  }
    
  public void setThickness(Insets insets) {
    northThickness = insets.top;
    southThickness = insets.bottom;
    eastThickness  = insets.right;
    westThickness  = insets.left;
  }
  
  public void setThickness(int n, int direction) {
    switch (direction) {
      case NORTH: northThickness = n; break;
      case SOUTH: southThickness = n; break;
      case EAST:  eastThickness  = n; break;
      case WEST:  westThickness  = n; break;
      default: 
    }
  }
 
  public void append(LinesBorder b, boolean isReplace) {
    if (isReplace) {
      northThickness = b.northThickness;
      southThickness = b.southThickness;
      eastThickness  = b.eastThickness;
      westThickness  = b.westThickness;
    } else {
      northThickness = Math.max(northThickness ,b.northThickness);
      southThickness = Math.max(southThickness ,b.southThickness);
      eastThickness  = Math.max(eastThickness  ,b.eastThickness);
      westThickness  = Math.max(westThickness  ,b.westThickness);
    }
  }

  public void append(Insets insets, boolean isReplace) {
    if (isReplace) {
      northThickness = insets.top;
      southThickness = insets.bottom;
      eastThickness  = insets.right;
      westThickness  = insets.left;
    } else {
      northThickness = Math.max(northThickness ,insets.top);
      southThickness = Math.max(southThickness ,insets.bottom);
      eastThickness  = Math.max(eastThickness  ,insets.right);
      westThickness  = Math.max(westThickness  ,insets.left);
    }
  }
}

Setting the font of a JTextArea

Use setFont(name, type, size):

import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame
{     
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
 
   public Main() {
      JTextArea jtextarea = new JTextArea();
      jtextarea.setFont(new Font("Tahoma", Font.ITALIC, 20));
      getContentPane().add(jtextarea);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
 
      setSize(400, 400);
   }
}

Render HTML documents

JEditorPane is able to display and edit different kinds of content. By default,
text/plain, text/html and text/rtf are recognized and passed on to the
EditorKit that is designed to handle it: DefaultEditorKit, HTMLEditorKit and
RTFEditorKit
. In the following example, a URL can be given in a JTextField.
Clicking GO will invoke the setPage method on the JEditorPane that will load
the page into a default document and set the content type. Using the
mime type of the page, the pane will automatically detect the correct EditorPane to
use.
Try: http://www.yahoo.com and http://www.esus.com/richtext.rtf

import javax.swing.text.html.*;
import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.awt.*;
import java.io.*;
 
public class Main extends JFrame
{
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
 
   public Main() {
 
      JButton uriButton = new JButton("Go!");
      // needs to be final to allow the inner class to access it!
      final JTextField uriTextField = new JTextField();
      final JEditorPane htmlPane = new JEditorPane();
      uriTextField.setText("http://www.yahoo.com");
      htmlPane.setEditable(false);
 
      uriButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            try {
               htmlPane.setPage(new URL(uriTextField.getText()));
            }
            catch(Exception e) {
               System.out.println(e);
            }
         }
      });
 
      getContentPane().setLayout(new BorderLayout());
      JPanel topPanel = new JPanel(new BorderLayout());
      topPanel.add(BorderLayout.CENTER, uriTextField);
      topPanel.add(BorderLayout.EAST, uriButton);
 
      getContentPane().add(BorderLayout.NORTH, topPanel);
      getContentPane().add(BorderLayout.CENTER, new JScrollPane(htmlPane));
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
 
      setSize(400, 400);
   }
}

Using JAXB

JAXB allows for a mapping between Java objects and XML files. The following example goes through a couple steps so you get a feel of this powerful library.

Download the early-access implementation from http://java.sun.com/xml/jaxb, and add the JAR files to your classpath.

First, write a DTD that describes your object.
customer.dtd (!!remove the space between the ? and xml) :

<? xml version="1.0" encoding="UTF-8"?>
<!ELEMENT customer (name, addresses+, email)+ >
<!ATTLIST customer custid CDATA #REQUIRED>
 
<!ELEMENT name (#PCDATA)>
 
<!ELEMENT addresses (addline1, addline2, zip, location, state)>
<!ELEMENT addline1 (#PCDATA)>
<!ELEMENT addline2 (#PCDATA)>
<!ELEMENT zip (#PCDATA)>
<!ELEMENT location (#PCDATA)>
<!ELEMENT state (#PCDATA)>
 
<!ELEMENT email (#PCDATA)>

To map this description of a customer to an object (tree), you can invoke the schema to java compiler:

   java com.sun.tools.xjc.Main customer.dtd -roots customer

output:

   .Addresses.java
   .Customer.java
   .Email.java
   .Name.java

Two files have been created that are the equivalent of the DTD. You can further customize the mapping by creating a .xjs file. For example, in the following customer.xjs file, it is specified that the attribute custid is mapped onto an int in the Java object (the default was a String). Also, the classes are to be placed in the package
com.esus.jaxbtest.
customer.xjs (!!remove the space between ? and xml):

<? xml version="1.0" encoding="UTF-8"?>
<xml-java-binding-schema version="1.0ea">
  <options package="com.esus.jaxbtest"/>
 
  <element name="customer" type="class" root="true">
    <attribute name="custid" convert="long"/>
  </element>
</xml-java-binding-schema>

Now run the conversion utility again, but specify your customized mapping:

   java com.sun.tools.xjc.Main customer.dtd customer.xjs

output is now:

   .comesusjaxbtestAddresses.java
   .comesusjaxbtestCustomer.java
   .comesusjaxbtestEmail.java
   .comesusjaxbtestName.java

Now, let’s test the mapping and create an XML file data.xml that describes one customer.

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

<? xml version="1.0"?>
<customer>
   <name>Jefke McCann</name>
   <addresses>
      <addline1>516, S. 5th Ave.</addline1>
      <zip>59715</zip>
      <location>Bozeman</location>
      <state>MT</state>
   </addresses>
   <email>jefke.mccann@yahoo.com</email>
</customer>

java Main:

C:myxmljaxb>java Main
javax.xml.bind.MissingContentException: addline2
        at Addresses.validateThis(Addresses.java:93)
        at javax.xml.bind.Unmarshaller.unmarshal(Unmarshaller.java:209)
        at javax.xml.bind.Unmarshaller.unmarshal(Unmarshaller.java:133)
        at Customer.unmarshal(Customer.java:161)
        at javax.xml.bind.Unmarshaller.unmarshal(Unmarshaller.java:199)
        at javax.xml.bind.Unmarshaller.unmarshalRoot(Unmarshaller.java:222)
        at javax.xml.bind.Dispatcher.unmarshal(Dispatcher.java:350)
        at Customer.unmarshal(Customer.java:198)
        at Customer.unmarshal(Customer.java:192)
        at Customer.unmarshal(Customer.java:186)
        at Main.main(Main.java:10)

Notice that the conversion halts because data.xml does not contain the tag addline2 while it was required in the original DTD customer.dtd. Let’s make addline2 optional, and regenerate.

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

<? xml version="1.0" encoding="UTF-8"?>
<!ELEMENT customer (name, addresses+, email)+ >
<!ATTLIST customer custid CDATA #REQUIRED>
 
<!ELEMENT name (#PCDATA)>
 
<!ELEMENT addresses (addline1, addline2?, zip, location, state)>
<!ELEMENT addline1 (#PCDATA)>
<!ELEMENT addline2 (#PCDATA)>
<!ELEMENT zip (#PCDATA)>
<!ELEMENT location (#PCDATA)>
<!ELEMENT state (#PCDATA)>
 
<!ELEMENT email (#PCDATA)>
C:myxmljaxb>del *.class
 
C:myxmljaxb>java com.sun.tools.xjc.Main customer.dtd customer.xjs
.comesusjaxbtestAddresses.java
.comesusjaxbtestCustomer.java
.comesusjaxbtestEmail.java
.comesusjaxbtestName.java
 
C:myxmljaxb>javac Main.java
 
C:myxmljaxb>java Main
javax.xml.bind.MissingAttributeException: custid
        at com.esus.jaxbtest.Customer.validateThis(Customer.java:82)
        at javax.xml.bind.Unmarshaller.unmarshal(Unmarshaller.java:209)
        at javax.xml.bind.Unmarshaller.unmarshalRoot(Unmarshaller.java:222)
        at javax.xml.bind.Dispatcher.unmarshal(Dispatcher.java:350)
        at com.esus.jaxbtest.Customer.unmarshal(Customer.java:156)
        at com.esus.jaxbtest.Customer.unmarshal(Customer.java:150)
        at com.esus.jaxbtest.Customer.unmarshal(Customer.java:144)
        at Main.main(Main.java:10)

Notice now that the unmarshalling fails because our customer record does not contain the required custid attribute. Add it!
data.xml (!!remove the space between ? and xml):

<? xml version="1.0"?>
<customer custid="12345">
   <name>Jefke McCann</name>
   <addresses>
      <addline1>516, S. 5th Ave.</addline1>
      <zip>59715</zip>
      <location>Bozeman</location>
      <state>MT</state>
   </addresses>
   <email>jefke.mccann@yahoo.com</email>
</customer>

Now run again:

C:myxmljaxb>java Main
<<customer custid=12345 content=[<<name content=Jefke McCann>>, <<addresses addl
ine1=516, S. 5th Ave. zip=59715 location=Bozeman state=MT>>, <<email content=jef
ke.mccann@yahoo.com>>]>>

To go the other way:
Main.java:

import com.esus.jaxbtest.*;
import java.util.*;
import java.io.*;
 
public class Main
{
   public static Customer cust;
 
   public static void main(String []args) {
      try {
         cust = new Customer();
 
         buildTree();
         validate();
         marshal();
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   }
 
   public static void buildTree() throws Exception {
      // set custid attribute
      cust.setCustid(12345);
      List custEntries = cust.getContent();
      Name name = new Name();
      name.setContent("Joris Van den Bogaert");
      custEntries.add(name);
      Email email = new Email();
      email.setContent("joris1@esus.com");
      custEntries.add(email);
      Addresses address1 = new Addresses();
      address1.setAddline1("A. Dewitstraat 50");
      address1.setZip("3078");
      address1.setLocation("Meerbeek");
      address1.setState("BE");
      Addresses address2 = new Addresses();
      address2.setAddline1("Handelskaai 3");
      address2.setZip("1000");
      address2.setLocation("Brussel");
      address2.setState("BE");
      custEntries.add(address1);
      custEntries.add(address2);
   }
 
   public static void validate() throws Exception {
      cust.validate();
   }
 
   public static void marshal() throws Exception {
      FileOutputStream out = new FileOutputStream("out.xml");
      try {
         cust.marshal(out);
      } finally {
         out.close();
      }	
   }
}

After executing this program, the following file out.xml will be created:

<? xml version="1.0" encoding="UTF-8"?>

<customer custid="12345">
  <name>Joris Van den Bogaert</name>
  <email>joris1@esus.com</email>
  <addresses>
    <addline1>A. Dewitstraat 50</addline1>
    <zip>3078</zip>
    <location>Meerbeek</location>
    <state>BE</state></addresses>
  <addresses>
    <addline1>Handelskaai 3</addline1>
    <zip>1000</zip>
    <location>Brussel</location>
    <state>BE</state></addresses>
</customer>

How do I determine the Client’s browser type and version?

The

user-agent

header can be used to determine the browser type. Be aware that the format of this header is not standardized, and the original value can get lost if the request arrives via proxy. There are numerous websites that list user-agent values for various browsers.

Here’s a simple example:

public void checkBrowserType (HttpServletRequest req)
{
   String s = req.getHeader("user-agent");
   if (s == null)
      return;
   if (s.indexOf("MSIE") > -1)
      System.out.println("using Internet Explorer");
   else if (s.indexOf("Netscape") > -1)
      System.out.println("using Netscape");
   // etc ...	
}