Disable the cancel button on a JFileChooser

To disable the cancel Button you have to use following lines:

JFileChooser chooser = new JFileChooser();
 
( ( JButton ) ( ( JPanel ) chooser.getComponent( 5 ) ).
  getAccessibleContext().getAccessibleChild( 5 ).
  getAccessibleContext().getAccessibleChild( 2 ) ).
  setVisible( false );

Adding a JTable background image that does not scroll

Make sure all your internal JTable components have the opaqueness property set to false. Setting the JTable opaque property to false won’t work as the table is added to a JScrollPane. Extend the JScrollPane class and override the paint method to paint the image every time an event occurs where a repainting is necessary.

Main.java:

import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() {
      JTable table = new JTable(100, 5) {
         public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
            Component c = super.prepareRenderer(renderer, row, column);
            if (c instanceof JComponent) {
                ((JComponent) c).setOpaque(false);
            }
            return c;
         }
      };
 
      ImageJScrollPane isp = new ImageJScrollPane(table);
 
      isp.setBackgroundImage(new ImageIcon("c:\mong.jpg"));
 
      getContentPane().add(isp);
 
      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);
   } 
} 
 
class ImageJScrollPane extends JScrollPane 
{
   private ImageIcon image = null;
 
   public ImageJScrollPane() {
      this(null, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_AS_NEEDED);
   }
 
   public ImageJScrollPane(Component view) {
      this(view, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_AS_NEEDED);
   }
   
   public ImageJScrollPane(Component view, int vsbPolicy, int hsbPolicy) {
      super(view, vsbPolicy, hsbPolicy);
      if (view instanceof JComponent) {
         ((JComponent) view).setOpaque(false);
      }
   }
 
   public ImageJScrollPane(int vsbPolicy, int hsbPolicy) {
      this(null, vsbPolicy, hsbPolicy);
   }
 
   public void setBackgroundImage(ImageIcon image) {
      this.image = image;
   }
 
   public void paint(Graphics g) {
      // Do not use cached image for scrolling
      getViewport().setBackingStoreEnabled(false);
 
      if (image != null) {
         Rectangle rect = getViewport().getViewRect();
         for (int x=0; x<rect.width; x+=image.getIconWidth()) {
            for (int y=0; y<rect.height; y+=image.getIconHeight()) {
               g.drawImage(image.getImage(), x, y, null, null); 
            }
         }
 
         super.paint(g);
      }
   }
}

Here’s the image I used:

Creating a JTable with a different background color per column

The trick is to contrive a custom DefaultTableCellRenderer and apply it to individual columns provided by the table’s backing column model. The following snippet demonstrates rendering the first column of the table so it displays with grey background and blue foreground highlighting:

Main.java:

import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() {
      JTable table = new JTable(100, 5);
 
      TableColumn tm = table.getColumnModel().getColumn(0);
      tm.setCellRenderer(new ColorColumnRenderer(Color.lightGray, Color.blue));
 
      getContentPane().add(new JScrollPane(table));
  
      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);
   } 
} 
 
/**
* Applied background and foreground color to single column of a JTable
* in order to distinguish it apart from other columns.
*/ 
class ColorColumnRenderer extends DefaultTableCellRenderer 
{
   Color bkgndColor, fgndColor;
 	
   public ColorColumnRenderer(Color bkgnd, Color foregnd) {
      super(); 
      bkgndColor = bkgnd;
      fgndColor = foregnd;
   }
  	
   public Component getTableCellRendererComponent
	    (JTable table, Object value, boolean isSelected,
	     boolean hasFocus, int row, int column) 
   {
      Component cell = super.getTableCellRendererComponent
         (table, value, isSelected, hasFocus, row, column);
 
      cell.setBackground( bkgndColor );
      cell.setForeground( fgndColor );
     
      return cell;
   }
}

Embedding a JTextArea in a JTable cell

JTextAreaTableExample.java:

import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
  
public class JTextAreaTableExample extends JFrame {
 
  public JTextAreaTableExample() {
    super( "JTextAreaTableExample Example" );
  
    DefaultTableModel dtm = new DefaultTableModel() {
       // make first cell uneditable
       public boolean isCellEditable(int row, int column)
       {
          return !(column == 0);
       }
    };
 
    dtm.setDataVector(new Object[][]{{ "JTextArea1", "This is a testnon long linesn" },
                                     { "JTextArea2", "Hello, world!" }},
                      new Object[]{ "String","JTextArea"});
                     
    JTable table = new JTable(dtm);
    table.getColumn("JTextArea").setCellRenderer(new TextAreaRenderer());
    table.getColumn("JTextArea").setCellEditor(new TextAreaEditor());
 
    table.setRowHeight(80);
    JScrollPane scroll = new JScrollPane(table);
    getContentPane().add(scroll);
 
    setSize( 400, 250 );
    setVisible(true);
  }
 
  public static void main(String[] args) {
    JTextAreaTableExample frame = new JTextAreaTableExample();
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
  }
}
  
class TextAreaRenderer extends JScrollPane implements TableCellRenderer
{
   JTextArea textarea;
 
   public TextAreaRenderer() {
      textarea = new JTextArea();
      textarea.setLineWrap(true);
      textarea.setWrapStyleWord(true);
      textarea.setBorder(new TitledBorder("This is a JTextArea"));
      getViewport().add(textarea);
   }
 
   public Component getTableCellRendererComponent(JTable table, Object value,
                                  boolean isSelected, boolean hasFocus,
                                  int row, int column)
   {
      if (isSelected) {
         setForeground(table.getSelectionForeground());
         setBackground(table.getSelectionBackground());
         textarea.setForeground(table.getSelectionForeground());
         textarea.setBackground(table.getSelectionBackground());
      } else {
         setForeground(table.getForeground());
         setBackground(table.getBackground());
         textarea.setForeground(table.getForeground());
         textarea.setBackground(table.getBackground());
      }
 
      textarea.setText((String) value); 
      textarea.setCaretPosition(0);
      return this;
   }
}
 
class TextAreaEditor extends DefaultCellEditor {
   protected JScrollPane scrollpane;
   protected JTextArea textarea; 
 
   public TextAreaEditor() {
      super(new JCheckBox());
      scrollpane = new JScrollPane();
      textarea = new JTextArea();  
      textarea.setLineWrap(true);
      textarea.setWrapStyleWord(true);
      textarea.setBorder(new TitledBorder("This is a JTextArea"));
      scrollpane.getViewport().add(textarea);
   }
 
   public Component getTableCellEditorComponent(JTable table, Object value,
                                   boolean isSelected, int row, int column) {
      textarea.setText((String) value);
 
      return scrollpane;
   }
 
   public Object getCellEditorValue() {
      return textarea.getText();
   }
}

Changing the icons of a JTree

Just use the methods setOpenIcon, setClosedIcon and setLeafIcon defined in the DefaultCellRenderer class.

Here’s an example.

Main.java:

import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
 
public class Main extends JFrame
{
   public Main() {
      DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
      DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("Child 1");
      root.add(child1);
      DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("Child 2");
      root.add(child2);
      JTree tree = new JTree(root);
 
      DefaultTreeCellRenderer cr = new DefaultTreeCellRenderer();
      cr.setOpenIcon(new ImageIcon("openicon.jpg"));
      cr.setClosedIcon(new ImageIcon("closedicon.jpg"));
      cr.setLeafIcon(new ImageIcon("leaficon.jpg"));
  
      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);
   }
}

The icons used in this program:


Detecting the native Look and Feel

Call the static method getSystemLookAndFeelClassName() of the UIManager class. It will return the name of the LookAndFeel class that implements the native systems look and feel if there is one, otherwise the default LookAndFeel class.

import javax.swing.*;
 
public class Main2
{ 
   public static void main(String[] args) {
      System.out.println(UIManager.getSystemLookAndFeelClassName());
   } 
}

Store a Java object in a file on the local file system using JNDI

You can bind an object into a context, provided your object is a Reference or implements the Referenceable interface. The object is stored in a file called .bindings as a set of properties.

The following example shows how to store the object Member containing two Strings username and email.

Write.java:

import javax.naming.*;
import java.util.*;
import java.io.*;
  
public class Write
{
   public static void main(String []args) {
      try {
         Properties properties = new Properties();
         properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
         properties.put(Context.PROVIDER_URL, "file:///");
 
         InitialContext ctx = new InitialContext(properties);
 
         Context context = (Context) ctx.lookup("c:\temp\");
 
         Member member = new Member("Joris Van den Bogaert", "joris1@esus.com"); 
         context.rebind("member.obj", member);
 
         ctx.close(); 
      }
      catch(NamingException ne) {
         ne.printStackTrace();
      }
   }
}

Member.java:

import javax.naming.*;
 
class Member implements Referenceable 
{
   private String username;
   private String email;
 
   public Member(String username, String email) {
      this.username = username;
      this.email = email;
   }
 
   public String toString() {
      return "[" + username + ", " + email + "]";
   }
 
   public Reference getReference() throws NamingException {
      Reference reference = new Reference(Member.class.getName(),
                                          MemberFactory.class.getName(),
                                          null);
      reference.add(new StringRefAddr("username", username));
      reference.add(new StringRefAddr("email", email));
 
      return reference;
   }
}

MemberFactory.java:

import javax.naming.spi.ObjectFactory;
import javax.naming.*;
import java.util.*;
 
public class MemberFactory implements ObjectFactory
{
   public MemberFactory() { }
 
   public Object getObjectInstance(Object object, 
                                   Name name, 
                                   Context ctx, 
                                   Hashtable env) throws Exception {
      if (object instanceof Reference) {
         Reference reference = (Reference) object;
         if (reference.getClassName().equals(Member.class.getName())) {
            String username = (String) ((StringRefAddr) reference.get(0)).getContent();
            String email    = (String) ((StringRefAddr) reference.get(1)).getContent();
 
            return new Member(username, email);
         }
      }
 
      return null;
   }
}

The .bindings file, located in c:temp looks like a simple properties file:

#This file is used by the JNDI FSContext.
#Tue Jan 14 00:53:47 CET 2003
member.obj/RefAddr/0/Type=username
member.obj/RefAddr/1/Content=joris1@esus.com
member.obj/RefAddr/0/Content=Joris Van den Bogaert
member.obj/RefAddr/0/Encoding=String
member.obj/FactoryName=MemberFactory
member.obj/ClassName=Member
member.obj/RefAddr/1/Encoding=String
member.obj/RefAddr/1/Type=email

Moving the database resultset cursor backward and forward

With JDBC 2.0, you can use scrollable resultsets.

The following example operates on this table and will read the resultset backwards.

mysql> select * from customers;
+--------+-----------------------+-------------------------------+
| custid | name                  | email                         |
+--------+-----------------------+-------------------------------+
|      1 | Joris Van den Bogaert | joris_vandenbogaert@yahoo.com |
|      2 | Alicia Kolesnikova    | alicia@esus.com               |
+--------+-----------------------+-------------------------------+

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_INSENSITIVE,
                                               ResultSet.CONCUR_READ_ONLY);
 
         ResultSet rs = stmt.executeQuery("SELECT * FROM customers"); 
         rs.afterLast();
         while (rs.previous()) {
            System.out.print(rs.getInt("custid"));
            System.out.print("  " + rs.getString("name"));
            System.out.println("  " + rs.getString("email"));
         }
 
         stmt.close();
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   } 
}

outputs:

2  Alicia Kolesnikova  alicia@esus.com
1  Joris Van den Bogaert  joris_vandenbogaert@yahoo.com

Capturing an area of the native screen

Use the Robot class, introduced in JDK1.3. The method createScreenCapture creates a BufferedImage containing pixels read from the native screen.

This example reads the top left corner of my Win2000 screen and displays it inside a JFrame.

Main.java:

import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   BufferedImage background;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      try {
         Robot robot = new Robot();
         background = robot.createScreenCapture(
                         new Rectangle(0, 0, 100, 200)); 
      }
      catch(AWTException e) {
         e.printStackTrace();
      }
   }
 
   public void paint(Graphics g) {      
      if (background != null) {
         g.drawImage(background, 0, 0, getWidth(), getHeight(), this);   
      }
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(100, 200);
      main.setVisible(true);
   }
}