Forcing the JColorChooser to display only the RGB tab

Get the panels through the method getChooserPanels and remove the ones that
area not DefaultRGBChooserPanels.

Main.java:

import javax.swing.colorchooser.*;
import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   public Main() {
      super("JColorChooser Demonstration");
   
      getContentPane().setLayout(new FlowLayout()); 
      JColorChooser colorChooser = new JColorChooser(); 
 
      AbstractColorChooserPanel[] panels = colorChooser.getChooserPanels(); 
      for (int i=0; i<panels.length; i++) {
         if (panels[i].toString().indexOf("DefaultRGBChooserPanel") == -1) {
            colorChooser.removeChooserPanel(panels[i]);
         }
      }
 
      getContentPane().add(colorChooser); 
  
      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);
   }
}

Previewing textfiles in a JFileChooser

Use the setAccessory method!

Main.java:

import javax.swing.filechooser.*;
import java.awt.event.*;
import javax.swing.*;
import java.beans.*;
import java.awt.*;
import java.io.*;
  
public class Main extends JFrame {
   public static void main(String[] args) {
      JFileChooser fc = new JFileChooser();
 
      // show only directories and .txt files       
      fc.addChoosableFileFilter(new TextfileFilter());
 
      // set the accessory JComponent to our panel that previews textfiles
      fc.setAccessory(new TextfilePreview(fc));
 
      int returnVal = fc.showDialog(new JFrame(), "Open");
 
      if (returnVal == JFileChooser.APPROVE_OPTION) {
         File file = fc.getSelectedFile();
      }
 
      System.exit(0);
   }
}
 
class TextfileFilter extends javax.swing.filechooser.FileFilter
{
   public boolean accept(File f) {
      if (f.isDirectory()) return true;
 
      return f.getName().toLowerCase().endsWith(".txt");
   }
 
   public String getDescription() {
      return "TextFiles (*.txt)";
   }
}
 
class TextfilePreview extends JPanel
                      implements PropertyChangeListener {
   File textfile;
   JTextArea ta;
 
   public TextfilePreview(JFileChooser fc) {
      fc.addPropertyChangeListener(this);
      ta = new JTextArea();
      JScrollPane sp = new JScrollPane(ta);
      setLayout(new BorderLayout());
      add(BorderLayout.CENTER, sp);
      setPreferredSize(new Dimension(150, 200));
   }
 
   public void loadTextfile() {
      if (textfile == null) return;
 
      try {
         ta.setText("");
         BufferedReader br = new BufferedReader(new FileReader(textfile));
         String line;
         while ((line = br.readLine()) != null) {
            ta.append(line + "n");
         }
         br.close();
      }
      catch(IOException e) {
      }
   } 
 
   public void propertyChange(PropertyChangeEvent e) {
      String prop = e.getPropertyName();
      if (prop.equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) {
         textfile = (File) e.getNewValue();
         if (isShowing()) {
            loadTextfile();
            repaint();
         }
      }
   }
}

Creating a JTable with hideable columns

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



HideColumnTableExample.java:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
 
/**
 * @version 1.0 05/31/99
 */
public class HideColumnTableExample extends JFrame {

  public HideColumnTableExample(){
    super( "HideColumnTable Example" );
    
    JTable table = new JTable(5, 7);
    ColumnButtonScrollPane pane = new ColumnButtonScrollPane(table);
    getContentPane().add(pane);
  }

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

ColumnButtonScrollPane.java:

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
import javax.swing.event.*;
import jp.gr.java_conf.tame.swing.layout.*;
import jp.gr.java_conf.tame.swing.border.*;
import jp.gr.java_conf.tame.swing.icon.*;
 
/**
 * @version 1.0 05/31/99
 */
public class ColumnButtonScrollPane extends JScrollPane {
  Component columnButton;

  public ColumnButtonScrollPane(JTable table) {
    super(table);
    TableColumnModel cm = table.getColumnModel();
    LimitedTableHeader header = new LimitedTableHeader(cm);
    table.setTableHeader(header);
    columnButton = createUpperCorner(header);
    setCorner(UPPER_RIGHT_CORNER, columnButton);
    setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_ALWAYS);
    ColumnButtonScrollPaneLayout layout = new ColumnButtonScrollPaneLayout();
    setLayout(layout);
    layout.syncWithScrollPane(this);
  }
  
  protected Component createUpperCorner(JTableHeader header) {
    ColumnButton corner = new ColumnButton(header);
    return corner;
  }

  
  public class LimitedTableHeader extends JTableHeader {
    public LimitedTableHeader(TableColumnModel cm) {
      super(cm);
    }
       
    // actually, this is a not complete way. but easy one.
    // you can see last column painted wider, short time :) 
    // If you don't like this kind cheap fake,
    // you have to overwrite the paint method in UI class.
    public void paintComponent(Graphics g) {
      super.paintComponent(g);
      columnButton.repaint();
    }    
  }

  
  public class ColumnButton extends JPanel {    
    JTable table;
    TableColumnModel cm;
    JButton revealButton; 
    JButton hideButton;
    Stack stack;  
    
    public ColumnButton(JTableHeader header) {
      setLayout(new GridLayout(1,2));
      setBorder(new LinesBorder(SystemColor.controlShadow, new Insets(0,1,0,0)));
      
      stack = new Stack();
      table = header.getTable();
      cm    = table.getColumnModel();
      
      revealButton = createButton(header, SwingConstants.WEST);
      hideButton   = createButton(header, SwingConstants.EAST);
      add(revealButton);
      add(hideButton);   
         
      revealButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {      
          TableColumn column = (TableColumn)stack.pop();
          cm.addColumn(column);
          if (stack.empty()) {
            revealButton.setEnabled(false);
          }
          hideButton.setEnabled(true);
          table.sizeColumnsToFit(-1);
        }
      });
      hideButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {      
          int n = cm.getColumnCount();
          TableColumn column = cm.getColumn(n -1);
          stack.push(column);
          cm.removeColumn(column);
          if (n < 3) {
            hideButton.setEnabled(false);
          }
          revealButton.setEnabled(true);
          table.sizeColumnsToFit(-1);
        }
      });
      
      if (1 < cm.getColumnCount()) {
        hideButton.setEnabled(true);
      } else {
        hideButton.setEnabled(false);
      }
      revealButton.setEnabled(false);
    }
    
    protected JButton createButton(JTableHeader header,
                                   int direction) {
      //int iconHeight = header.getPreferredSize().height - 6;
      int iconHeight = 8;
      JButton button = new JButton();
      button.setIcon(new ArrowIcon(iconHeight, direction, true));
      button.setDisabledIcon(new ArrowIcon(iconHeight, direction, false));
      button.setRequestFocusEnabled(false);
      button.setForeground(header.getForeground());
      button.setBackground(header.getBackground());
      button.setBorder(UIManager.getBorder("TableHeader.cellBorder"));
      return button;
    }    
  }
}

ColumnButtonScrollPaneLayout.java:

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


/**
 * @version 1.0 05/29/99
 */
public class ColumnButtonScrollPaneLayout extends  ScrollPaneLayout {

  public ColumnButtonScrollPaneLayout() {
    super.setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_ALWAYS);
  }

  public void setVerticalScrollBarPolicy(int x) {
    // VERTICAL_SCROLLBAR_ALWAYS
    super.setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_ALWAYS);
  }
  
  public void layoutContainer(Container parent) {
    super.layoutContainer(parent);
    
    if ((colHead == null) || (! colHead.isVisible()) ||
        (upperRight == null) || (vsb == null)) {
      return;
    }
    
    Rectangle vsbR = new Rectangle(0, 0, 0, 0);
    vsbR = vsb.getBounds(vsbR);
    
    Rectangle colHeadR = new Rectangle(0, 0, 0, 0);
    colHeadR = colHead.getBounds(colHeadR);
    colHeadR.width -= vsbR.width;
    colHead.getBounds(colHeadR);
    
    Rectangle upperRightR = upperRight.getBounds();
    upperRightR.x     -= vsbR.width;
    upperRightR.width += vsbR.width + 1;
    upperRight.setBounds(upperRightR);
  }  
}

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 < northThickness; i++)  {
      g.drawLine(x, y+i, x+width-1, y+i);
    }
    g.setColor(southColor);
    for (int i = 0; i < southThickness; i++)  {
      g.drawLine(x, y+height-i-1, x+width-1, y+height-i-1);
    }
    g.setColor(eastColor);
    for (int i = 0; i < westThickness; i++)  {
      g.drawLine(x+i, y, x+i, y+height-1);
    }
    g.setColor(westColor);
    for (int i = 0; i < 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);
    }
  }
}

ArrowIcon.java:

import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;
  
/**
 * @version 1.0 02/26/99
 */
public class ArrowIcon implements Icon, SwingConstants {
  private static final int DEFAULT_SIZE = 11;
  //private static final int DEFAULT_SIZE = 5;

  private int size;
  private int iconSize;
  private int direction;
  private boolean isEnabled;
  private BasicArrowButton iconRenderer;

  public ArrowIcon(int direction, boolean isPressedView) {
    this(DEFAULT_SIZE, direction, isPressedView);
  }

  public ArrowIcon(int iconSize, int direction, boolean isEnabled) {
    this.size = iconSize / 2;
    this.iconSize = iconSize;
    this.direction = direction;
    this.isEnabled = isEnabled;
    iconRenderer = new BasicArrowButton(direction);
  }

  public void paintIcon(Component c, Graphics g, int x, int y) {
    iconRenderer.paintTriangle(g, x, y, size, direction, isEnabled);
  }

  public int getIconWidth() {
    //int retCode;
    switch (direction) {
      case NORTH:
      case SOUTH: return iconSize;
      case EAST:
      case WEST:  return size;
    }
    return iconSize;
  }

  public int getIconHeight() {
    switch (direction) {
      case NORTH:
      case SOUTH: return size;
      case EAST:
      case WEST:  return iconSize;
    }
    return size;
  }
}

Having a JRadioButton cell in a JTable

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



JRadioButtonTableExample.java:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
 
class RadioButtonRenderer implements TableCellRenderer {
  public Component getTableCellRendererComponent(JTable table, Object value,
                   boolean isSelected, boolean hasFocus, int row, int column) {
    if (value==null) return null;
    return (Component)value;
  }
}
 
class RadioButtonEditor extends    DefaultCellEditor
                        implements ItemListener {
  private JRadioButton button;
 
  public RadioButtonEditor(JCheckBox checkBox) {
    super(checkBox);
  }
 
  public Component getTableCellEditorComponent(JTable table, Object value,
                   boolean isSelected, int row, int column) {
    if (value==null) return null;
    button = (JRadioButton)value;
    button.addItemListener(this);
    return (Component)value;
  }
 
  public Object getCellEditorValue() {
    button.removeItemListener(this);
    return button;
  }
 
  public void itemStateChanged(ItemEvent e) {
    super.fireEditingStopped();
  }
}
 
public class JRadioButtonTableExample extends JFrame {
 
  public JRadioButtonTableExample(){
    super( "JRadioButtonTable Example" );
    UIDefaults ui = UIManager.getLookAndFeel().getDefaults();    
    UIManager.put("RadioButton.focus", ui.getColor("control"));
 
    DefaultTableModel dm = new DefaultTableModel();
    dm.setDataVector(
      new Object[][]{
        {"Group 1",new JRadioButton("A")},
        {"Group 1",new JRadioButton("B")},
        {"Group 1",new JRadioButton("C")},
        {"Group 2",new JRadioButton("a")},
        {"Group 2",new JRadioButton("b")}},
      new Object[]{"String","JRadioButton"});
                      
    JTable table = new JTable(dm) {
      public void tableChanged(TableModelEvent e) {
        super.tableChanged(e);
        repaint();
      }
    };
    ButtonGroup group1 = new ButtonGroup();
    group1.add((JRadioButton)dm.getValueAt(0,1));
    group1.add((JRadioButton)dm.getValueAt(1,1));
    group1.add((JRadioButton)dm.getValueAt(2,1));
    ButtonGroup group2 = new ButtonGroup();
    group2.add((JRadioButton)dm.getValueAt(3,1));
    group2.add((JRadioButton)dm.getValueAt(4,1));
    table.getColumn("JRadioButton").setCellRenderer(new RadioButtonRenderer());
    table.getColumn("JRadioButton").setCellEditor(new RadioButtonEditor(new JCheckBox()));
    JScrollPane scroll = new JScrollPane(table);
    getContentPane().add( scroll );
    setSize( 200, 140 );
    setVisible(true);
  }
 
  public static void main(String[] args) {
    JRadioButtonTableExample frame = new JRadioButtonTableExample();
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
  }
}



JRadioButtonTableExample2.java:

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

/**
 * @version 1.2 08/13/99
 */
public class JRadioButtonTableExample2 extends JFrame {
 
  public JRadioButtonTableExample2(){
    super( "JRadioButtonTable Example" );
 
    DefaultTableModel dm = new DefaultTableModel();
    dm.setDataVector(
      new Object[][]{
        {"1",new Integer(-1)},
        {"2",new Integer(-1)},
        {"3",new Integer(0)},
        {"4",new Integer(1)},
        {"5",new Integer(2)}},
      new Object[]{"Question","Answer"});
                      
    JTable table = new JTable(dm);
    String[] answer = {"A","B","C"};
     
    table.getColumn("Answer").setCellRenderer(
      new RadioButtonRenderer(answer)
    );
    table.getColumn("Answer").setCellEditor(
      new RadioButtonEditor(new JCheckBox(), 
                            new RadioButtonPanel(answer))
    );
    JScrollPane scroll = new JScrollPane(table);
    getContentPane().add( scroll );
  }
   
  // Cell base
  class RadioButtonPanel extends JPanel {
    JRadioButton[] buttons;
     
    RadioButtonPanel(String[] str) {
      setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
      buttons = new JRadioButton[str.length];
      for (int i=0; i<buttons.length; i++) {
        buttons[i] = new JRadioButton(str[i]);
        buttons[i].setFocusPainted(false);
        add(buttons[i]);
      }      
    }
     
    public void setSelectedIndex(int index) {
      for (int i=0;i<buttons.length;i++) {
        buttons[i].setSelected(i == index);
      }
    }
     
    public int getSelectedIndex() {
      for (int i=0; i<buttons.length; i++) {
        if (buttons[i].isSelected()) {
          return i;
        }
      }      
      return -1;      
    }
     
    public JRadioButton[] getButtons() {
      return buttons;
    }
  }
 
 
   
  class RadioButtonRenderer extends    RadioButtonPanel
                            implements TableCellRenderer {    
    RadioButtonRenderer(String[] strs) {
      super(strs);
    }
     
    public Component getTableCellRendererComponent(JTable table, Object value,
                   boolean isSelected, boolean hasFocus, int row, int column) {
      if (value instanceof Integer) {
        setSelectedIndex(((Integer)value).intValue());
      }      
      return this;
    }
  }
 
 
 
  class RadioButtonEditor extends    DefaultCellEditor
                          implements ItemListener {
    RadioButtonPanel panel;
 
    public RadioButtonEditor(JCheckBox checkBox,RadioButtonPanel panel) {
      super(checkBox);
      this.panel = panel;
      ButtonGroup buttonGroup = new ButtonGroup();
      JRadioButton[] buttons  = panel.getButtons();
      for (int i=0; i<buttons.length; i++) {
        buttonGroup.add(buttons[i]);
        buttons[i].addItemListener(this);
      }                  
    }
 
    public Component getTableCellEditorComponent(JTable table, Object value,
                   boolean isSelected, int row, int column) {
      if (value instanceof Integer) {
        panel.setSelectedIndex(((Integer)value).intValue());
      }      
      return panel;
    }
 
    public Object getCellEditorValue() {
      return new Integer(panel.getSelectedIndex());
    }
 
    public void itemStateChanged(ItemEvent e) {
      super.fireEditingStopped();
    }
  }
 
  public static void main(String[] args) {
    JRadioButtonTableExample2 frame = new JRadioButtonTableExample2();
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    frame.setSize( 230, 140 );
    frame.setVisible(true);
  }
}

Change the row height of a JTable that resides in a JFrame automatically when that frame is resized

Maybe this code gives you some ideas.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame 
{
   public Main() {
      super("Table example, Wines from Bordeaux");
 
      Object[][] tabledata = {
            { "Chateau Meyney, St. Estephe", 	   new Integer(1994), "$18.75"},
            { "Chateau Montrose, St. Estephe", 	   new Integer(1975), "$54.25" },
            { "Chateau Gloria, St. Julien", 	   new Integer(1993), "$22.99" },
            { "Chateau Beychevelle, St. Julien",   new Integer(1970), "$61.63" },
            { "Chateau La Tour de Mons, Margeaux", new Integer(1975), "$57.03" },
            { "Chateau Brane-Cantenac, Margeaux",  new Integer(1978), "$49.92" },
            { "Chateau Meyney, St. Estephe", 	   new Integer(1994), "$18.75"},
            { "Chateau Montrose, St. Estephe", 	   new Integer(1975), "$54.25" },
            { "Chateau Gloria, St. Julien", 	   new Integer(1993), "$22.99" },
            { "Chateau Beychevelle, St. Julien",   new Integer(1970), "$61.63" },
            { "Chateau La Tour de Mons, Margeaux", new Integer(1975), "$57.03" },
            { "Chateau Brane-Cantenac, Margeaux",  new Integer(1978), "$49.92" },
      };
 
      String columnheaders[] = { "Wine", "Vintage", "Price" };
 
      final JTable table = new JTable(tabledata, columnheaders);
      table.setPreferredScrollableViewportSize(new Dimension(500, 70));
      JScrollPane scrollPane = new JScrollPane(table);
 
      // initial height
      table.setRowHeight(20);
 
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(scrollPane);
 
      addComponentListener(new ComponentAdapter() {
         int oldHeight;
 
         public void componentResized(ComponentEvent e) {
            if (oldHeight > 0) {
               int newRowHeight = ( table.getRowHeight() * getHeight() ) / oldHeight;
               table.setRowHeight(newRowHeight);
            }
  
            oldHeight = getHeight();
         }
      });
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      pack();
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}

Adding a background image to a JTree

Main.java:

import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;
 
public class Main extends JFrame
{
   public Main() {
      DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
      for (int i=0; i<10; i++) {
         DefaultMutableTreeNode child = new DefaultMutableTreeNode("Child " + (i+1));
         root.add(child);
      }
      JTree tree = new JTree(root) {
         ImageIcon icon = new ImageIcon("mong.jpg");
 
         public void paint( Graphics g ) 
         { 
            // tile it
            Dimension d = this.getSize(); 
            for(int i=0; i<d.width; i+=icon.getIconWidth()) { 
               for(int j=0; j<d.height; j+=icon.getIconHeight()) { 
                  g.drawImage(icon.getImage(), i, j, null, null); 
               }
            }
 
            super.paint(g); 
         } 
      }; 
 
      tree.setOpaque( false );
  
 
      DefaultTreeCellRenderer cr = new DefaultTreeCellRenderer();
      cr.setOpaque(false);
      cr.setBackground(new Color(0, 0, 0, 0));  
      cr.setBackgroundNonSelectionColor(null);
      tree.setCellRenderer(cr);
 
      getContentPane().add(new JScrollPane(tree));
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
}

Image used: http://www.esus.com/images/mong.jpg

Using SAX

SAX stands for Simple API for XML. A SAX parser is event-based. Events are reported through callbacks as the parser moves through the XML document.

This example was compiled and run with JDK1.4, as the APIs and reference implementation are included. If you use a lower JDK version, download JAXP (Java APIs for XML Processing) on http://java.sun.com/xml/jaxp.html.

Main.java:

import org.xml.sax.helpers.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
import java.io.*;
 
public class Main 
{
   public static void main(String []args) {
      try {
         SAXParserFactory factory = SAXParserFactory.newInstance();
         SAXParser parser = factory.newSAXParser();
 
         InputSource is = new InputSource(new FileReader("example.xml"));
         parser.parse(is, new MySAXHandler());
      }
      catch(ParserConfigurationException e) {
         e.printStackTrace();
      }
      catch(SAXException e) {
         e.printStackTrace();
      }
      catch(IOException e) {
         e.printStackTrace();
      }        
   }
}
 
class MySAXHandler extends DefaultHandler
{
   int indent = 0;
 
   public void startDocument() throws SAXException {
      System.out.println("startDocument()");
   }
 
   public void endDocument() throws SAXException {
      indent(-3);
      System.out.println("endDocument()");
   }
 
   public void characters(char[] ch, int start, int length)  {
      String s = new String(ch, start, length);
      if (!s.trim().equals("")) {
         indent(0);
         System.out.println(s);
      }
   }
 
   public void ignorableWhitespace(char[] ch, int start, int length) {
      System.out.println("[whitespace]");
   }
 
   public void startElement(String uri, String localName, 
                            String qName, Attributes attributes) {
      indent(3);
      System.out.println("[element " + qName + "]");
      for (int i=0; i<attributes.getLength(); i++) {
         indent(0);
         System.out.println("[Attribute " + attributes.getQName(i) +
                            ", value=" + attributes.getValue(i) + "]");
      }
   }
 
   public void endElement(String uri, String localName, String qName) {
      indent(0);
      System.out.println("[endelement " + qName + "]");
      indent -= 3;
   }
 
   public void indent(int pos) {
      indent += pos;
      for (int i=0; i<indent; i++) {
         System.out.print(" ");
      }
   }
}

example.xml:

<?xml version="1.0"?>
<customer id="C123456">
   <name>Joris Van den Bogaert</name>
   <email>joris1@esus.com</email>
</customer>

output:

startDocument()
   [element customer]
   [Attribute id, value=C123456]
      [element name]
      Joris Van den Bogaert
      [endelement name]
      [element email]
      joris1@esus.com
      [endelement email]
   [endelement customer]
endDocument()

Traversing a DOM tree using a NodeIterator

(DOM Level 2!) A NodeIterator can come in pretty handy to walk over all the nodes, even though you loose the structure of the document. See the questions/answers about TreeWalker to retain the structure.

The following simple example shows you how it works. If you have played around with FileFilters before, it’s a no-brainer. It shows all the zip codes that contain a “8″.

For more information on the NodeIterator, the NodeFilter and their options, check out the API docs: NodeIterator, NodeFilter

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

<? xml version="1.0" encoding="UTF-8"?>
<customers>
   <customer id="C12345">
      <name>Joris Van den Bogaert</name>
      <address>
         <addressline>Handelskaai 3</addressline>
         <zip>1000</zip>
         <location>Brussels</location>
         <country>BELGIUM</country>
      </address>
   </customer>
   <customer id="C23495">
      <name>John Doe</name>
      <address>
         <addressline>5, S 5th Ave.</addressline>
         <zip>59715</zip>
         <location>Bozeman, MT</location>
         <country>US</country>
      </address>
   </customer>
   <customer id="C03429">
      <name>John Babcock</name>
      <address>
         <addressline>73, Broad street</addressline>
         <zip>06418</zip>
         <location>Chester, CT</location>
         <country>US</country>
      </address>
   </customer>
   <customer id="C12345">
      <name>Dominique Bodard</name>
      <address>
         <addressline>21-23, Rue de Madrid</addressline>
         <zip>75008</zip>
         <location>Paris</location>
         <country>FRANCE</country>
      </address>
   </customer>
</customers>

Main.java:

import org.w3c.dom.*;
import org.w3c.dom.traversal.*;
  
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();
         DocumentBuilder db = dbf.newDocumentBuilder();
         doc = db.parse(new File("customers.xml")); 
 
         if (!doc.isSupported("Traversal", "2.0")) {
            System.out.println("Traversal not supported in your parser version");
            System.exit(1);
         }
 
         DocumentTraversal dt = (DocumentTraversal) doc;
         NodeIterator iterator = dt.createNodeIterator(doc, 
                                                       NodeFilter.SHOW_ALL, 
                                                       new ZipFilter(), 
                                                       true);
         Node node;
         while ((node = iterator.nextNode()) != null) {
            System.out.println(node.getFirstChild().getNodeValue());
         }
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   } 
}
 
class ZipFilter implements NodeFilter
{
   public short acceptNode(Node n) {
      if (n.getNodeName().equals("zip") && n.getFirstChild().getNodeValue().indexOf("8") > -1) { 
         return FILTER_ACCEPT;
      }
      return FILTER_SKIP;
   }
}

outputs:

06418
75008

Retrieving rows from a database table using JDBC

Check out the MySQL syntax for SELECT here.

Here’s an example that gets all the rows from a customer table. You need to create a Statement object from a Connection and invoke executeQuery on it, passing it the SQL SELECT command. It returns a ResultSet containing the database rows that match your query. You can then iterate over the rows with the next method. The first call to next will position the “cursor” to the first row. You can get a particular column in that row with the getXXX methods, specifying either the column index or the column name. Make sure the database column type and the resulting variable type match, or a proper conversion is done. If types don’t match, a Bad format SQLException is thrown.

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");
         Connection con = db.getConnection();
         CustomerDAO custDAO = new CustomerDAO(con);
 
         Collection c = custDAO.getAllRows();
         Iterator iter = c.iterator();
         while (iter.hasNext()) {
            System.out.println(iter.next());
         }
  
         db.close();
      }
      catch(DatabaseException e) {
         e.printStackTrace();
      }
   }
}
 
class Customer
{
   private String name;
   private String email;
 
   public Customer() { }
 
   public Customer(String name, String email) {
      setName(name);
      setEmail(email);
   }
  
   public void setName(String name) {
      this.name = name;
   }
 
   public void setEmail(String email) {
      this.email = email;
   }
 
   public String getName() {
      return name;
   }
 
   public String getEmail() {
      return email;
   }
 
   public String toString() {
      return "Customer [name=" + getName() + ", email=" + getEmail() + "]";
   }
}
 
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 Connection getConnection() {
      return connection;
   }
 
   public void close() throws DatabaseException {
      try {
         connection.close();
      }
      catch(Exception e) {
         throw new DatabaseException(e.getMessage());
      }
   } 
}   
 
class DatabaseException extends Exception {
   public DatabaseException() {
   }
 
   public DatabaseException(String message) {
      super(message);
   }
}
 
class CustomerDAO 
{
   Connection connection = null;
 
   public CustomerDAO(Connection connection) {
      this.connection = connection;
   }
 
   public Collection getAllRows() throws DatabaseException {
      try {
         ArrayList al = new ArrayList();
 
         Statement stmt = connection.createStatement();
         ResultSet rs = stmt.executeQuery("SELECT * FROM customers");
         while (rs.next()) {
            Customer cust = new Customer();
            cust.setName(rs.getString("name"));
            cust.setEmail(rs.getString("email"));
            al.add(cust);
         }
         
         stmt.close();
 
         return al;
      }
      catch(SQLException e) {
         throw new DatabaseException(e.getMessage());
      }
   }
}