Creating a JTable with fixed columns

You can call the following method:

   table.getTableHeader().setResizingAllowed(false);

However, be aware that this will disable resizing for all columns, and will still resize the columns proportionally when resizing the container in which the JTable is hosted. To fix the size of one column, you have to think about what behavior you want and override the method sizeColumnsToFit().

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);
 
      // 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));
 
 
      // don't allow resizing columns
      table.getTableHeader().setResizingAllowed(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 boolean isCellEditable(int row, int col) {
      return false;
   }
}

Creating a JTable with a multi-line header

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



MultiLineHeaderExample.java:

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
  
/**
 * @version 1.0 11/09/98
 */
public class MultiLineHeaderExample extends JFrame {
  MultiLineHeaderExample() {
    super( "Multi-Line Header Example" );
 
    DefaultTableModel dm = new DefaultTableModel();
    dm.setDataVector(new Object[][]{{"a","b","c"},
                                    {"A","B","C"}},
                     new Object[]{"1stnalpha","2ndnbeta","3rdngamma"});
 
    JTable table = new JTable( dm );
    MultiLineHeaderRenderer renderer = new MultiLineHeaderRenderer();
    Enumeration enum = table.getColumnModel().getColumns();
    while (enum.hasMoreElements()) {
      ((TableColumn)enum.nextElement()).setHeaderRenderer(renderer);
    }   
    JScrollPane scroll = new JScrollPane( table );
    getContentPane().add( scroll );
    setSize( 400, 110 );
    setVisible(true);
  }
 
  public static void main(String[] args) {
    MultiLineHeaderExample frame = new MultiLineHeaderExample();
    frame.addWindowListener( new WindowAdapter() {
      public void windowClosing( WindowEvent e ) {
        System.exit(0);
      }
    });
  }
}

MultiLineHeaderRenderer.java:

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


/**
 * @version 1.0 11/09/98
 */
public class MultiLineHeaderRenderer extends JList implements TableCellRenderer {
  public MultiLineHeaderRenderer() {
    setOpaque(true);
    setForeground(UIManager.getColor("TableHeader.foreground"));
    setBackground(UIManager.getColor("TableHeader.background"));
    setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    ListCellRenderer renderer = getCellRenderer();
    ((JLabel)renderer).setHorizontalAlignment(JLabel.CENTER);
    setCellRenderer(renderer);
  }
 
  public Component getTableCellRendererComponent(JTable table, Object value,
                   boolean isSelected, boolean hasFocus, int row, int column) {
    setFont(table.getFont());
    String str = (value == null) ? "" : value.toString();
    BufferedReader br = new BufferedReader(new StringReader(str));
    String line;
    Vector v = new Vector();
    try {
      while ((line = br.readLine()) != null) {
        v.addElement(line);
      }
    } catch (IOException ex) {
      ex.printStackTrace();
    }
    setListData(v);
    return this;
  }
}

Changing the color of entire rows of a JTable

Write your own cell renderer. This example colors all rows green where the price of
the wine is < 55, red otherwise.

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 (wine.getPrice() < 55) {
         setBackground(Color.green);
      }
      else {
         setBackground(Color.red);
      }
 
      return super.getTableCellRendererComponent(table, value, isSelected, 
                                                 hasFocus, row, column);
   }
}

Listing all the default values of the look and feel

UIDefaults is a class derived from Hashtable that contains a map of the default values
for the installed UI look and feel (LAF). The following program produces a sorted list:

Main.java:

import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main {
   public static void main(String[] args) {
      UIDefaults defaults = UIManager.getDefaults();
 
      String[] ar = new String[defaults.size()];
      int count=0;
      Enumeration enum = defaults.keys();
      while (enum.hasMoreElements()) { 
         ar[count++] = (String) enum.nextElement();
      }
 
      // sort values
      Arrays.sort(ar);
 
      // print out
      for (int i=0; i<ar.length; i++) {
         System.out.println(ar[i]);
      } 
 
      // exit program (AWT event thread running)
      System.exit(1);
   }
}

outputs:

Button.background
Button.border
Button.disabledText
Button.focus
Button.font
Button.foreground
Button.margin
Button.select
Button.textIconGap
Button.textShiftOffset
ButtonUI
CheckBox.background
CheckBox.border
CheckBox.disabledText
CheckBox.focus
CheckBox.font
CheckBox.foreground
CheckBox.icon
CheckBox.margin
CheckBox.textIconGap
CheckBox.textShiftOffset
CheckBoxMenuItem.acceleratorFont
CheckBoxMenuItem.acceleratorForeground
CheckBoxMenuItem.acceleratorSelectionForeground
CheckBoxMenuItem.arrowIcon
CheckBoxMenuItem.background
CheckBoxMenuItem.border
CheckBoxMenuItem.borderPainted
CheckBoxMenuItem.checkIcon
CheckBoxMenuItem.disabledForeground
CheckBoxMenuItem.font
CheckBoxMenuItem.foreground
CheckBoxMenuItem.margin
CheckBoxMenuItem.selectionBackground
CheckBoxMenuItem.selectionForeground
CheckBoxMenuItemUI
CheckBoxUI
Checkbox.select
ColorChooser.background
ColorChooser.cancelText
ColorChooser.font
ColorChooser.foreground
ColorChooser.hsbBlueText
ColorChooser.hsbBrightnessText
ColorChooser.hsbGreenText
ColorChooser.hsbHueText
ColorChooser.hsbNameText
ColorChooser.hsbRedText
ColorChooser.hsbSaturationText
ColorChooser.okText
ColorChooser.previewText
ColorChooser.resetText
ColorChooser.rgbBlueMnemonic
ColorChooser.rgbBlueText
ColorChooser.rgbGreenMnemonic
ColorChooser.rgbGreenText
ColorChooser.rgbNameText
ColorChooser.rgbRedMnemonic
ColorChooser.rgbRedText
ColorChooser.swatchesDefaultRecentColor
ColorChooser.swatchesNameText
ColorChooser.swatchesRecentSwatchSize
ColorChooser.swatchesRecentText
ColorChooser.swatchesSwatchSize
ColorChooserUI
ComboBox.background
ComboBox.disabledBackground
ComboBox.disabledForeground
ComboBox.font
ComboBox.foreground
ComboBox.listBackground
ComboBox.listForeground
ComboBox.selectionBackground
ComboBox.selectionForeground
ComboBoxUI
Desktop.background
DesktopIcon.background
DesktopIcon.border
DesktopIcon.font
DesktopIcon.foreground
DesktopIconUI
DesktopPaneUI
EditorPane.background
EditorPane.border
EditorPane.caretBlinkRate
EditorPane.caretForeground
EditorPane.font
EditorPane.foreground
EditorPane.inactiveForeground
EditorPane.keyBindings
EditorPane.margin
EditorPane.selectionBackground
EditorPane.selectionForeground
EditorPaneUI
FileChooser.acceptAllFileFilterText
FileChooser.cancelButtonMnemonic
FileChooser.cancelButtonText
FileChooser.cancelButtonToolTipText
FileChooser.detailsViewButtonAccessibleName
FileChooser.detailsViewButtonToolTipText
FileChooser.detailsViewIcon
FileChooser.directoryDescriptionText
FileChooser.fileDescriptionText
FileChooser.fileNameLabelMnemonic
FileChooser.fileNameLabelText
FileChooser.filesOfTypeLabelMnemonic
FileChooser.filesOfTypeLabelText
FileChooser.helpButtonMnemonic
FileChooser.helpButtonText
FileChooser.helpButtonToolTipText
FileChooser.homeFolderAccessibleName
FileChooser.homeFolderIcon
FileChooser.homeFolderToolTipText
FileChooser.listViewButtonAccessibleName
FileChooser.listViewButtonToolTipText
FileChooser.listViewIcon
FileChooser.lookInLabelMnemonic
FileChooser.lookInLabelText
FileChooser.newFolderAccessibleNam
FileChooser.newFolderErrorSeparator
FileChooser.newFolderErrorText
FileChooser.newFolderIcon
FileChooser.newFolderToolTipText
FileChooser.openButtonMnemonic
FileChooser.openButtonText
FileChooser.openButtonToolTipText
FileChooser.saveButtonMnemonic
FileChooser.saveButtonText
FileChooser.saveButtonToolTipText
FileChooser.upFolderAccessibleName
FileChooser.upFolderIcon
FileChooser.upFolderToolTipText
FileChooser.updateButtonMnemonic
FileChooser.updateButtonText
FileChooser.updateButtonToolTipText
FileChooserUI
FileView.computerIcon
FileView.directoryIcon
FileView.fileIcon
FileView.floppyDriveIcon
FileView.hardDriveIcon
FocusManagerClassName
InternalFrame.activeTitleBackground
InternalFrame.activeTitleForeground
InternalFrame.border
InternalFrame.closeIcon
InternalFrame.font
InternalFrame.icon
InternalFrame.iconifyIcon
InternalFrame.iconizeIcon
InternalFrame.inactiveTitleBackground
InternalFrame.inactiveTitleForeground
InternalFrame.maximizeIcon
InternalFrame.minimizeIcon
InternalFrame.paletteBorder
InternalFrame.paletteCloseIcon
InternalFrame.paletteTitleHeight
InternalFrame.titleFont
InternalFrameUI
Label.background
Label.disabledForeground
Label.disabledShadow
Label.font
Label.foreground
LabelUI
List.background
List.cellRenderer
List.focusCellHighlightBorder
List.font
List.foreground
List.selectionBackground
List.selectionForeground
ListUI
Menu.acceleratorFont
Menu.acceleratorForeground
Menu.acceleratorSelectionForeground
Menu.arrowIcon
Menu.background
Menu.border
Menu.borderPainted
Menu.checkIcon
Menu.consumesTabs
Menu.disabledForeground
Menu.font
Menu.foreground
Menu.margin
Menu.selectionBackground
Menu.selectionForeground
MenuBar.background
MenuBar.border
MenuBar.font
MenuBar.foreground
MenuBarUI
MenuItem.acceleratorDelimiter
MenuItem.acceleratorFont
MenuItem.acceleratorForeground
MenuItem.acceleratorSelectionForeground
MenuItem.arrowIcon
MenuItem.background
MenuItem.border
MenuItem.borderPainted
MenuItem.checkIcon
MenuItem.disabledForeground
MenuItem.font
MenuItem.foreground
MenuItem.margin
MenuItem.selectionBackground
MenuItem.selectionForeground
MenuItemUI
MenuUI
OptionPane.background
OptionPane.border
OptionPane.buttonAreaBorder
OptionPane.cancelButtonText
OptionPane.errorIcon
OptionPane.font
OptionPane.foreground
OptionPane.informationIcon
OptionPane.messageAreaBorder
OptionPane.messageForeground
OptionPane.minimumSize
OptionPane.noButtonText
OptionPane.okButtonText
OptionPane.questionIcon
OptionPane.warningIcon
OptionPane.yesButtonText
OptionPaneUI
Panel.background
Panel.font
Panel.foreground
PanelUI
PasswordField.background
PasswordField.border
PasswordField.caretBlinkRate
PasswordField.caretForeground
PasswordField.font
PasswordField.foreground
PasswordField.inactiveForeground
PasswordField.keyBindings
PasswordField.margin
PasswordField.selectionBackground
PasswordField.selectionForeground
PasswordFieldUI
PopupMenu.background
PopupMenu.border
PopupMenu.font
PopupMenu.foreground
PopupMenuSeparatorUI
PopupMenuUI
ProgressBar.background
ProgressBar.backgroundHighlight
ProgressBar.border
ProgressBar.cellLength
ProgressBar.cellSpacing
ProgressBar.font
ProgressBar.foreground
ProgressBar.foregroundHighlight
ProgressBar.selectionBackground
ProgressBar.selectionForeground
ProgressBarUI
RadioButton.background
RadioButton.border
RadioButton.disabledText
RadioButton.focus
RadioButton.font
RadioButton.foreground
RadioButton.icon
RadioButton.margin
RadioButton.select
RadioButton.textIconGap
RadioButton.textShiftOffset
RadioButtonMenuItem.acceleratorFont
RadioButtonMenuItem.acceleratorForeground
RadioButtonMenuItem.acceleratorSelectionForeground
RadioButtonMenuItem.arrowIcon
RadioButtonMenuItem.background
RadioButtonMenuItem.border
RadioButtonMenuItem.borderPainted
RadioButtonMenuItem.checkIcon
RadioButtonMenuItem.disabledForeground
RadioButtonMenuItem.font
RadioButtonMenuItem.foreground
RadioButtonMenuItem.margin
RadioButtonMenuItem.selectionBackground
RadioButtonMenuItem.selectionForeground
RadioButtonMenuItemUI
RadioButtonUI
ScrollBar.background
ScrollBar.darkShadow
ScrollBar.foreground
ScrollBar.highlight
ScrollBar.maximumThumbSize
ScrollBar.minimumThumbSize
ScrollBar.shadow
ScrollBar.thumb
ScrollBar.thumbDarkShadow
ScrollBar.thumbHighlight
ScrollBar.thumbLightShadow
ScrollBar.thumbShadow
ScrollBar.track
ScrollBar.trackHighlight
ScrollBar.width
ScrollBarUI
ScrollPane.background
ScrollPane.border
ScrollPane.font
ScrollPane.foreground
ScrollPaneUI
Separator.background
Separator.foreground
Separator.highlight
Separator.shadow
SeparatorUI
Slider.background
Slider.focus
Slider.focusInsets
Slider.foreground
Slider.highlight
Slider.horizontalThumbIcon
Slider.majorTickLength
Slider.shadow
Slider.trackWidth
Slider.verticalThumbIcon
SliderUI
SplitPane.background
SplitPane.border
SplitPane.dividerSize
SplitPane.highlight
SplitPane.shadow
SplitPaneUI
StandardDialogUI
TabbedPane.background
TabbedPane.contentBorderInsets
TabbedPane.darkShadow
TabbedPane.focus
TabbedPane.font
TabbedPane.foreground
TabbedPane.highlight
TabbedPane.lightHighlight
TabbedPane.selectHighlight
TabbedPane.selected
TabbedPane.selectedTabPadInsets
TabbedPane.shadow
TabbedPane.tabAreaBackground
TabbedPane.tabAreaInsets
TabbedPane.tabInsets
TabbedPane.tabRunOverlay
TabbedPane.textIconGap
TabbedPaneUI
Table.background
Table.focusCellBackground
Table.focusCellForeground
Table.focusCellHighlightBorder
Table.font
Table.foreground
Table.gridColor
Table.scrollPaneBorder
Table.selectionBackground
Table.selectionForeground
TableHeader.background
TableHeader.cellBorder
TableHeader.font
TableHeader.foreground
TableHeaderUI
TableUI
TextArea.background
TextArea.border
TextArea.caretBlinkRate
TextArea.caretForeground
TextArea.font
TextArea.foreground
TextArea.inactiveForeground
TextArea.keyBindings
TextArea.margin
TextArea.selectionBackground
TextArea.selectionForeground
TextAreaUI
TextField.background
TextField.border
TextField.caretBlinkRate
TextField.caretForeground
TextField.font
TextField.foreground
TextField.inactiveForeground
TextField.keyBindings
TextField.margin
TextField.selectionBackground
TextField.selectionForeground
TextFieldUI
TextPane.background
TextPane.border
TextPane.caretBlinkRate
TextPane.caretForeground
TextPane.font
TextPane.foreground
TextPane.inactiveForeground
TextPane.keyBindings
TextPane.margin
TextPane.selectionBackground
TextPane.selectionForeground
TextPaneUI
TitledBorder.border
TitledBorder.font
TitledBorder.titleColor
ToggleButton.background
ToggleButton.border
ToggleButton.disabledBackground
ToggleButton.disabledSelectedBackground
ToggleButton.disabledSelectedText
ToggleButton.disabledText
ToggleButton.focus
ToggleButton.font
ToggleButton.foreground
ToggleButton.margin
ToggleButton.select
ToggleButton.text
ToggleButton.textIconGap
ToggleButton.textShiftOffset
ToggleButtonUI
ToolBar.background
ToolBar.border
ToolBar.dockingBackground
ToolBar.dockingForeground
ToolBar.floatingBackground
ToolBar.floatingForeground
ToolBar.font
ToolBar.foreground
ToolBar.separatorSize
ToolBarSeparatorUI
ToolBarUI
ToolTip.background
ToolTip.border
ToolTip.font
ToolTip.foreground
ToolTipUI
Tree.background
Tree.changeSelectionWithFocus
Tree.closedIcon
Tree.collapsedIcon
Tree.drawsFocusBorderAroundIcon
Tree.editorBorder
Tree.expandedIcon
Tree.font
Tree.foreground
Tree.hash
Tree.leafIcon
Tree.leftChildIndent
Tree.line
Tree.openIcon
Tree.rightChildIndent
Tree.rowHeight
Tree.scrollsOnExpand
Tree.selectionBackground
Tree.selectionBorderColor
Tree.selectionForeground
Tree.textBackground
Tree.textForeground
TreeUI
Viewport.background
Viewport.font
Viewport.foreground
ViewportUI
activeCaption
activeCaptionBorder
activeCaptionText
control
controlDkShadow
controlHighlight
controlLtHighlight
controlShadow
controlText
desktop
inactiveCaption
inactiveCaptionBorder
inactiveCaptionText
info
infoText
menu
menuText
scrollbar
text
textHighlight
textHighlightText
textInactiveText
textText
window
windowBorder
windowText

List out the elements that belong to a particular XML namespace

For more information about namespaces, check out http://www.jclark.com/xml/xmlns.htm.

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

<? xml version="1.0" encoding="UTF-8"?>
<customers xmlns='http://www.esus.com/custns'>
   <customer id="C12345" type="prio1">
      <name>Joris Van den Bogaert</name>
      <address>
         <addressline>Handelskaai 3</addressline>
         <zip>1000</zip>
         <location>Brussels</location>
         <country>BELGIUM</country>
      </address>
   </customer>
   <destination>
      <address xmlns='http://www.esus.com/destns'>123.321.1.20</address>
   </destination>
</customers>

Main.java:

import org.w3c.dom.*;
  
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
  
import java.io.*;
   
public class Main
{
   public static void main(String []args) {
      Document doc;
  
      try {
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         dbf.setNamespaceAware(true);
         DocumentBuilder db = dbf.newDocumentBuilder();
         doc = db.parse(new File("customers.xml"));
 
         Element root = doc.getDocumentElement();
         root.normalize();
 
         // display all custns elements
         NodeList nl = doc.getElementsByTagNameNS("http://www.esus.com/custns", "*");
         System.out.println("Elements that belong to http://www.esus.com/custns namespace:");
         printNodeList(nl);
 
         // display all destns elements
         nl = doc.getElementsByTagNameNS("http://www.esus.com/destns", "*");
         System.out.println("Elements that belong to http://www.esus.com/destns namespace:");
         printNodeList(nl);          
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   } 
 
   public static void printNodeList(NodeList nl) {
      for (int i=0; i<nl.getLength(); i++) {
         Node n = nl.item(i);
         System.out.println("t" + n.getNodeName());
         Node tn = n.getFirstChild();
         if (!tn.getNodeValue().trim().equals("")) {   
            System.out.println("tt" + tn.getNodeValue());
         }
         System.out.println();
      }
   }
}

outputs:

Elements that belong to http://www.esus.com/custns namespace:
	customers
 
	customer
 
	name
		Joris Van den Bogaert
 
	address
 
	addressline
		Handelskaai 3
 
	zip
		1000
 
	location
		Brussels
 
	country
		BELGIUM
 
	destination
 
Elements that belong to http://www.esus.com/destns namespace:
	address
		123.321.1.20

Creating a database table using JDBC

Check out the MySQL syntax for CREATE TABLE here.

Here’s an example that creates 4 tables in the database esus. Create your SQL create table query string and call executeUpdate on a Statement.

Main.java:

import java.util.*;
import java.sql.*;
 
public class Main {
   public static void main(String []args) {
      try {
         Database db = new Database("org.gjt.mm.mysql.Driver",
                                    "jdbc:mysql://192.168.0.1/esus",
                                    "joris",
                                    "mypass");
 
         db.createTable("customers", "custid int(10) not null auto_increment, " +
                                     "name varchar(30), " +
                                     "email varchar(50), " + 
                                     "primary key(custid)");
         db.createTable("products", "prodid int(10) not null auto_increment, " +
                                    "description varchar(100), " +
                                    "price float(6, 2), " +
                                    "itemsleft int(10), " +
                                    "primary key(prodid)");
         db.createTable("orders", "orderid int(10) not null auto_increment, " + 
                                  "custid int(10), " +
                                  "timestamp datetime, " +
                                  "status tinyint, " +
                                  "primary key(orderid), " +
                                  "index custid (custid)");
         db.createTable("orderitems", "orderid int(10) not null, " +
                                      "prodid int(10) not null, " + 
                                      "quantity int(5) not null, " +
                                      "price float(10, 2) not null, " + 
                                      "primary key(orderid, prodid)";
         db.createTable("accounts", "accountid int(10) not null auto_increment, " +
                                    "custid int(10), " +
                                    "balance float(10,2), " +
                                    "primary key(accountid)");
      }
      catch(Database.DatabaseException e) {
         e.printStackTrace();
      }
   }
}
 
class Database
{
   Connection connection = null;
  
   public Database(String driver, String url, String user, String pass) 
                      throws DatabaseException 
   {
      try {
         Class.forName(driver).newInstance();
 
         connection = DriverManager.getConnection(url, user, pass);
      }
      catch(Exception e) {
         throw new DatabaseException(e.getMessage());
      }
   }
 
   public void createTable(String table, String columns) throws DatabaseException {
      try {
         Statement stmt = connection.createStatement();
         stmt.executeUpdate("create table " + table + " (" + columns + ")");
         stmt.close();
      }
      catch(SQLException e) {
         throw new DatabaseException(e.getMessage());
      }
   }
 
   public class DatabaseException extends Exception {
      public DatabaseException() {
      }
 
      public DatabaseException(String message) {
         super(message);
      }
   }
}   

Updating a row in the resultset

You can always execute an UPDATE statement with the new changes. JDBC2.0 provides another way. It allows you to make changes to a row from ResultSet and reflect the changes in the database.

before:

+---------+--------+---------------------+--------+
| orderid | custid | timestamp           | status |
+---------+--------+---------------------+--------+
|       1 |      1 | 2001-10-13 17:33:11 |      0 |
|       2 |      1 | 1972-12-12 00:00:00 |      1 |
|       3 |      1 | 1999-02-01 00:00:00 |      2 |
|       4 |      2 | 2001-05-01 00:00:00 |      0 |
+---------+--------+---------------------+--------+

Main.java:

import java.util.*;
import java.text.*;
import java.sql.*;
  
public class Main {
   public static void main(String []args) throws Exception {
      try {
         Class.forName("org.gjt.mm.mysql.Driver").newInstance();
         Connection conn = DriverManager.getConnection("jdbc:mysql://192.168.0.1/esus", 
                                                       "joris",
                                                       "mypass");
 
         Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                                               ResultSet.CONCUR_UPDATABLE);
 
         ResultSet rs = stmt.executeQuery("SELECT * FROM orders WHERE orderid = 1"); 
 
         if (rs.next()) {
            // change the status column
            rs.updateInt("status", 1);
            // store changes in database
            rs.updateRow();
         }
 
         stmt.close();
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   } 
}

after:

+---------+--------+---------------------+--------+
| orderid | custid | timestamp           | status |
+---------+--------+---------------------+--------+
|       1 |      1 | 2001-10-13 17:33:11 |      1 |
|       2 |      1 | 1972-12-12 00:00:00 |      1 |
|       3 |      1 | 1999-02-01 00:00:00 |      2 |
|       4 |      2 | 2001-05-01 00:00:00 |      0 |
+---------+--------+---------------------+--------+

Creating an email containing attachments using JavaMail

This simple example creates an .eml file (which you can open with eg. Outlook Express) containing the file c:autoexec.bat as an attachment.

Creating an attachment with JavaMail is simple: pass a DataSource instance to the constructor of DataHandler and add it to a MimeBodyPart. Add all the MimeBodyParts to a Multipart instance and initialize the message with it.

Main.java:

import javax.activation.*;
import javax.mail.internet.*;
import javax.mail.*;
import java.io.*;
 
public class Main
{
   public static void main(String []args) throws Exception {
      Message message = new MimeMessage((Session) null);
      message.setFrom(new InternetAddress("source@source.com"));
      message.addRecipient(Message.RecipientType.TO, new InternetAddress("dest@dest.com"));
      message.setSubject("JavaMail attachment test");
 
      // create a multipart instance
      Multipart multipart = new MimeMultipart();
 
      // create the body of the email 
      BodyPart bodyPart = new MimeBodyPart();
      bodyPart.setText("Body of email");      
      multipart.addBodyPart(bodyPart);
 
      // create a file attachment
      bodyPart = new MimeBodyPart();
      DataSource source = new FileDataSource("c:\autoexec.bat");
      bodyPart.setDataHandler(new DataHandler(source));
      // remember the name of the file
      bodyPart.setFileName("autoexec.bat");
      multipart.addBodyPart(bodyPart);
 
      message.setContent(multipart);
 
      // write it to an .eml file [or send it with Transport.send(message) ]
      message.writeTo(new BufferedOutputStream(new FileOutputStream("test.eml")));
   }
}