Setting the selected file in a the filename textfield JFileChooser when it starts up

You just have to create a new File and set it as selectedFile before starting the FileChooser. Depending on what you want to do with the selected file you should check the file with File.canRead(), File.canWrite() or File.exists(). Here is an example:

File file = new File(date + " " + user + ".pdf");
JFileChooser fc = new JFileChooser();
fc.setSelectedFile(file);
int returnValue = fc.showSaveDialog(this);

This must be wrapped in a try-catch-block, because creating a File could throw an exception.

Changing the foreground and background colors of JTable cells

Override the JTable’s cell renderer and set the fore- and background color. This example makes use of such a custom cell renderer. In the example, a cell item is of type ColoredItem that encapsulates an object and a Color.
Main.java:

import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   JTable table;
   MyTableModel tableModel;
 
   public Main() {
      super("Colored JTable Demonstration");
 
      tableModel = new MyTableModel(10, 5);
      table = new JTable(tableModel);
 
      DefaultTableCellRenderer colorRenderer = new DefaultTableCellRenderer() {
         public void setValue(Object value) {
            if (value instanceof ColoredItem) {
               Color fcolor = ((ColoredItem) value).getForeground();
               Color bcolor = ((ColoredItem) value).getBackground();
               this.setForeground(fcolor);
               this.setBackground(bcolor);
               setText(value.toString());
            }
         }
      };
  
      table.setDefaultRenderer(Object.class, colorRenderer);
      table.setDefaultEditor(Object.class, new DefaultCellEditor(new JTextField()));
 
      JScrollPane scrollPane = new JScrollPane(table);

      getContentPane().add(scrollPane, BorderLayout.CENTER);

      JPanel radioPanel = new JPanel(new GridLayout(1, 5));
      JRadioButton redRadio = new JRadioButton("Red");
      JRadioButton greenRadio = new JRadioButton("Green");
      JRadioButton blueRadio = new JRadioButton("Blue");
      JRadioButton yellowRadio = new JRadioButton("Yellow");
      JRadioButton blackRadio = new JRadioButton("Black");

      // Group the radio buttons.
      ButtonGroup group = new ButtonGroup();
      group.add(redRadio);
      group.add(greenRadio);
      group.add(blueRadio);
      group.add(yellowRadio);
      group.add(blackRadio);

      radioPanel.add(redRadio);
      radioPanel.add(greenRadio);
      radioPanel.add(blueRadio);
      radioPanel.add(yellowRadio);
      radioPanel.add(blackRadio);
 
      RadioListener radioListener = new RadioListener();
      redRadio.addActionListener(radioListener);
      greenRadio.addActionListener(radioListener);
      blueRadio.addActionListener(radioListener);
      yellowRadio.addActionListener(radioListener);
      blackRadio.addActionListener(radioListener);
 
      // add radiopanel to container
      JPanel panel = new JPanel(new GridLayout(2, 1));
      panel.add(new JLabel("Select color for selected cell:"));
      panel.add(radioPanel);     
      getContentPane().add(BorderLayout.SOUTH, panel);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
   }
 
   class RadioListener implements ActionListener {
      public void actionPerformed(ActionEvent ae) {
         int row = table.getSelectedRow();
         int column = table.getSelectedColumn();
         ColoredItem ci = (ColoredItem) tableModel.getValueAt(row, column);
 
         if (ae.getActionCommand().equals("Red"))
            ci.setForeground(Color.red);
         else if (ae.getActionCommand().equals("Green"))
            ci.setForeground(Color.green);
         else if (ae.getActionCommand().equals("Blue"))
            ci.setForeground(Color.blue);
         else if (ae.getActionCommand().equals("Yellow"))
            ci.setForeground(Color.yellow);
         else if (ae.getActionCommand().equals("Black"))
            ci.setForeground(Color.black);
 
         // necessary to cause a fireTableCellUpdated event
         tableModel.setValueAt(ci, row, column);
      }
   }
 
   private class ColoredItem {
      private Object object;
      private Color foreground;
      private Color background;
 
      public ColoredItem(Object object, Color foreground, Color background) {
         this.object = object;
         this.foreground = foreground;
         this.background = background;
      }
  
      public void setObject(Object object) {
         this.object = object;
      }
  
      public void setForeground(Color foreground) {
         this.foreground = foreground;
      }
 
      public void setBackground(Color background) {
         this.background = background;
      }
 
      public Object getObject() {
         return object;
      }
 
      public Color getForeground() {
         return foreground;
      }
 
      public Color getBackground() {
         return background;
      }
 
      public String toString() {
         return object.toString(); 
      }
   }
 
   class MyTableModel extends AbstractTableModel {
      String [] columnNames;
      Object [][] data;
 
      MyTableModel(int rows, int columns) {
         columnNames = createColumnElements(columns);
         data = createTableElements(rows, columns);         
      }
 
      public int getColumnCount() {
         return columnNames.length;
      }
        
      public int getRowCount() {
         return data.length;
      }
 
      public String getColumnName(int col) {
         return columnNames[col];
      }
 
      public Object getValueAt(int row, int col) {
         return data[row][col];
      }
 
      public Class getColumnClass(int c) {
         return getValueAt(0, c).getClass();
      }
 
      public void setValueAt(Object value, int row, int col) {
         data[row][col] = value;
         fireTableCellUpdated(row, col);
      }
 
      private String[] createColumnElements(int columns) {
         String[] data;
 
         data = new String[columns];
         for (int i=0; i<columns; i++) {
            data[i] = new String("Column " + i);
         }
 
         return data;
      }
 
      private Object[][] createTableElements(int rows, int columns) {
         ColoredItem [][]data;
         data = new ColoredItem[rows][];
         for (int i=0; i<rows; i++) {
            data[i] = new ColoredItem[columns];
            for (int j=0; j<columns; j++) {
               data[i][j] = new ColoredItem("(" + i + " , " + j + ")", Color.green, Color.white);
            }
         }
 
         return data;
      } 
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.pack();
      main.setVisible(true);
   }
}

Making the cells of a JTable transparent so that background image shows through

Author: Zafir Anjum

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
 
public class Table
{
   public static void main(String[] args) {
      JFrame frame = new JFrame("Table");
      frame.addWindowListener( new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            Window win = e.getWindow();
            win.setVisible(false);
            win.dispose();
            System.exit(0);
         }
      } );	
 
      // Create your own sub-class of JTable rather than using anonymous class
      JTable table = new JTable( 15, 3 ) {
         public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
            Component c = super.prepareRenderer( renderer, row, column);
            // We want renderer component to be transparent
            // so background image is visible
            if( c instanceof JComponent )
               ((JComponent)c).setOpaque(false);
               return c;
            }

            // Hard coded value. In your sub-class add a function for this.
            ImageIcon image = new ImageIcon( "codeguruwm.gif" );

            public void paint( Graphics g ) {
               // First draw the background image - tiled 
               Dimension d = getSize();
               for( int x = 0; x < d.width; x += image.getIconWidth() )
                  for( int y = 0; y < d.height; y += image.getIconHeight() ) 
                     g.drawImage( image.getImage(), x, y, null, null );
               // Now let the regular paint code do it's work
               super.paint(g);
           }
      };
 
      // Set the table transparent
      table.setOpaque(false);
		
      JScrollPane sp = new JScrollPane( table );
      frame.getContentPane().add( sp );	

      frame.pack();
      frame.show();
   }
}

Changing the margins between JTable grid lines and cell data

You can do so with the JTable method setIntercellSpacing.

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" },
      };
 
      String columnheaders[] = { "Wine", "Vintage", "Price" };
 
      JTable table = new JTable(tabledata, columnheaders);
      table.setPreferredScrollableViewportSize(new Dimension(500, 70));
      JScrollPane scrollPane = new JScrollPane(table);
 
      table.setIntercellSpacing(new Dimension (10,20));
  
      getContentPane().add(scrollPane);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      pack();
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}

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()

Creating an underlined JLabel without using HTML

Main.java:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
 
public class Main extends JFrame
{
   public Main() {
      getContentPane().setLayout(new GridLayout(1, 2));
      JPanel panel1 = new JPanel();
      panel1.setLayout(new GridLayout(5, 1));
      panel1.add(new JLabel(&quot;JLabel/icon/LEFT&quot;, 
                           new ImageIcon(&quot;tiffIcon.gif&quot;), SwingConstants.LEFT));
      panel1.add(new JLabel(&quot;JLabel/icon/CENTER&quot;, 
                           new ImageIcon(&quot;tiffIcon.gif&quot;), SwingConstants.CENTER));
      panel1.add(new JLabel(&quot;JLabel/icon/RIGHT&quot;, 
                           new ImageIcon(&quot;tiffIcon.gif&quot;), SwingConstants.RIGHT));
      panel1.add(new JLabel(&quot;JLabel/icon/LEADING&quot;, 
                           new ImageIcon(&quot;tiffIcon.gif&quot;), SwingConstants.LEADING));
      panel1.add(new JLabel(&quot;JLabel/icon/TRAILING&quot;, 
                           new ImageIcon(&quot;tiffIcon.gif&quot;), SwingConstants.TRAILING));
 
      getContentPane().add(new JScrollPane(panel1));
 
      JPanel panel2 = new JPanel();
      panel2.setLayout(new GridLayout(5, 1));
      panel2.add(new UnderlinedJLabel(&quot;JLabel/icon/LEFT&quot;, 
                                      new ImageIcon(&quot;tiffIcon.gif&quot;), SwingConstants.LEFT));
      panel2.add(new UnderlinedJLabel(&quot;JLabel/icon/CENTER&quot;, 
                                      new ImageIcon(&quot;tiffIcon.gif&quot;), SwingConstants.CENTER));
      panel2.add(new UnderlinedJLabel(&quot;JLabel/icon/RIGHT&quot;, 
                                      new ImageIcon(&quot;tiffIcon.gif&quot;), SwingConstants.RIGHT));
      panel2.add(new UnderlinedJLabel(&quot;JLabel/icon/LEADING&quot;, 
                                      new ImageIcon(&quot;tiffIcon.gif&quot;), SwingConstants.LEADING));
      panel2.add(new UnderlinedJLabel(&quot;JLabel/icon/TRAILING&quot;, 
                                      new ImageIcon(&quot;tiffIcon.gif&quot;), SwingConstants.TRAILING));
 
      getContentPane().add(new JScrollPane(panel2));
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(300, 150);
      main.setVisible(true);   
   }
}
 
class UnderlinedJLabel extends JLabel
{
   public UnderlinedJLabel() {
   }
 
   public UnderlinedJLabel(Icon image) {
      super(image);
   }
 
   public UnderlinedJLabel(Icon image, int horizontalAlignment) {
      super(image, horizontalAlignment);
   }
 
   public UnderlinedJLabel(String text) {
      super(text);
   }

   public UnderlinedJLabel(String text, Icon icon, int horizontalAlignment) {
      super(text, icon, horizontalAlignment);
   }
 
   public UnderlinedJLabel(String text, int horizontalAlignment) {
      super(text, horizontalAlignment);
   }
 
   public void paint(Graphics g) {
      super.paint(g);
      underline(g);
   }
 
   protected void underline(Graphics g) {
      Insets insets = getInsets();
      FontMetrics fm = g.getFontMetrics();
      Rectangle textR = new Rectangle();
      Rectangle viewR = new Rectangle(
                                  insets.left, 
                                  insets.top, 
                                  getWidth() - (insets.right + insets.left), 
                                  getHeight() - (insets.bottom + insets.top));
  
      // compute and return location of the icons origin,
      // the location of the text baseline, and a possibly clipped
      // version of the compound label string.  Locations are computed 
      // relative to the viewR rectangle.
      String text = SwingUtilities.layoutCompoundLabel(
                         this,                        // this JLabel
                         fm,                          // current FontMetrics
                         getText(),                   // text
                         getIcon(),                   // icon
                         getVerticalAlignment(),      
                         getHorizontalAlignment(),
                         getVerticalTextPosition(),
                         getHorizontalTextPosition(), 
                         viewR,                       
                         new Rectangle(),             // don't care about icon rectangle
                         textR,                       // resulting text locations
                         getText() == null ? 0 : 
                            ((Integer)UIManager.get(&quot;Button.textIconGap&quot;)).intValue());
 
      // draw line
      int textShiftOffset = ((Integer) UIManager.get(&quot;Button.textShiftOffset&quot;)).intValue();
      g.fillRect(textR.x +
                 textShiftOffset - 4,
                 textR.y + fm.getAscent() + textShiftOffset + 2,
                 textR.width, 
                 1);
   }
}

Writing a custom FocusTraversalPolicy

[JDK 1.4+] Extend from FocusTraversalPolicy and implement the abstract methods!

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
  
public class Main extends JFrame
{
   JLabel label = new JLabel("Forward: TAB or alt-f, Backward: SHIFT-TAB or alt-b");
   ArrayList textfields = new ArrayList();
   JRadioButton leftToRight = new JRadioButton("Left to right", true);
   JRadioButton topToBottom = new JRadioButton("Top to bottom");
  
   public Main() {
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
      Container contentPane = getContentPane();
      contentPane.setLayout(new BorderLayout(10, 10));
  
      JPanel topPanel = new JPanel(new GridLayout(3, 1));
      topPanel.add(new JLabel("Change the focus traversal policy"));
 
      ButtonGroup group = new ButtonGroup();
      group.add(leftToRight);
      group.add(topToBottom);
      topPanel.add(leftToRight); 
      topPanel.add(topToBottom);
 
      JPanel bottomPanel = new JPanel(new GridLayout(4, 2));
      for (int i=0; i<4; i++) {
         for (int j=0; j<2; j++) { 
            JTextField textfield = new JTextField("" + i + ", " + j);
            textfields.add(textfield);
            bottomPanel.add(textfield);
         }
      }     
  
      contentPane.add(BorderLayout.NORTH, topPanel);
      contentPane.add(BorderLayout.SOUTH, bottomPanel);
  
      bottomPanel.setFocusTraversalPolicy(new MyFocusTraversalPolicy());
      bottomPanel.setFocusCycleRoot(true);
   } 
  
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(350, 200);
      main.setVisible(true);
   }
 
   class MyFocusTraversalPolicy extends FocusTraversalPolicy
   {
      // Returns the Component that should receive the focus after aComponent.
      public Component getComponentAfter(Container focusCycleRoot, Component aComponent) {
         if (leftToRight.isSelected()) {
            int index = textfields.indexOf(aComponent);
            return (Component) textfields.get((index + 1) % textfields.size());
         }
         else if (topToBottom.isSelected()) {
            int index = textfields.indexOf(aComponent);
            int nextIndex = (index + 2) % textfields.size();
            if (nextIndex == 0) nextIndex = 1;
            else if (nextIndex == 1) nextIndex = 0;
            return (Component) textfields.get(nextIndex);
         }
 
         if (!aComponent.isEnabled()) {
            return getComponentAfter(focusCycleRoot, aComponent);
         }          
 
         return aComponent;
      }
  
      // Returns the Component that should receive the focus before aComponent.
      public Component getComponentBefore(Container focusCycleRoot, Component aComponent) {
         if (leftToRight.isSelected()) {
            int index = textfields.indexOf(aComponent);
            index--;
            if (index < 0) index = textfields.size() - 1;
            return (Component) textfields.get(index);
         }
         else if (topToBottom.isSelected()) {
            int index = textfields.indexOf(aComponent);
            index -= 2;
            if (index < 0) index = textfields.size() - 3 - index;
            //else if (index == 0) index = textfields.size() - 1;
            //else if (index == 1) index = textfields.size() - 2;
            return (Component) textfields.get(index);
         }
 
         return aComponent;
      }
  
      // Returns the default Component to focus.
      public Component getDefaultComponent(Container focusCycleRoot) {
         return (Component) textfields.get(0);
      }
 
      // Returns the first Component in the traversal cycle.
      public Component getFirstComponent(Container focusCycleRoot) {
         return (Component) textfields.get(0);
      }
 
      // Returns the Component that should receive the focus when a Window is made visible for the first time. 
      public Component getInitialComponent(Window window) {
         return leftToRight;
      }
 
      // Returns the last Component in the traversal cycle. 
      public Component getLastComponent(Container focusCycleRoot) {
         return (Component) textfields.get(textfields.size() - 1);
      }
   }
}

Getting the Component with the current focus in Swing

There is a method in Window named getFocusOwner which returns the currently focused child of the window on which you invoke the method. Given that and the Frame.getFrames() method which returns all the frames created by the application, all you have to do is iterate over all the frames and find the focused component like this:

public static Component findFocusedComponent(){
  Frame [] allFrames = Frame.getFrames();
  for (int i=0;i<allFrames.length;i++){
    Frame frame = allFrames[i];
    Component focusOwner = frame.getFocusOwner();
    if (focusOwner!=null)
      return focusOwner;
  }
  return null; // if no focused component exists
}

Drawing a rectangle in Swing

Use the method drawRect and specify x, y coordinates (top left) and width and height of the rectangle.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
   }
 
   public void paint(Graphics g) {
      Graphics2D g2d = (Graphics2D) g;
  
      g2d.drawRect(10, 50, 15, 15);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(100, 100);
      main.setVisible(true);
   }
}