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

Displaying a popup menu when right-clicking on a JTree node

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 = createNodes();
      JTree tree = new JTree(root);
 
      final TreePopup treePopup = new TreePopup(tree);
      tree.addMouseListener(new MouseAdapter() {
         public void mouseReleased (MouseEvent e) {
            if (e.isPopupTrigger()) {
               treePopup.show(e.getComponent(), e.getX(), e.getY());
            }
         }
      });
  
      getContentPane().add(new JScrollPane(tree));
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static DefaultMutableTreeNode createNodes() {
      DefaultMutableTreeNode root = new DefaultMutableTreeNode("Java");
      
      DefaultMutableTreeNode j2se = new DefaultMutableTreeNode("J2SE");
      DefaultMutableTreeNode j2ee = new DefaultMutableTreeNode("J2EE");
      DefaultMutableTreeNode j2me = new DefaultMutableTreeNode("J2ME");
 
      j2se.add(new DefaultMutableTreeNode("http://java.sun.com/j2se/"));
      j2ee.add(new DefaultMutableTreeNode("http://java.sun.com/j2ee/"));
      j2me.add(new DefaultMutableTreeNode("http://java.sun.com/j2me/"));
 
      root.add(j2se);
      root.add(j2ee);
      root.add(j2me);
 
      return root;
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
}
 
class TreePopup extends JPopupMenu {
   public TreePopup(JTree tree) {
      JMenuItem itemDelete = new JMenuItem("Delete");
      JMenuItem itemAdd = new JMenuItem("Add");
      itemDelete.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.out.println("Delete child");
         }
      });
      itemAdd.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.out.println("Add child");
         }
      });
 
      add(itemDelete);
      add(new JSeparator());
      add(itemAdd);
   }
}

Using a Look and Feel for one component and another Look and Feel for another component

Main.java:

import javax.swing.plaf.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.io.*; 
  
public class Main extends JFrame
{
   public Main() throws Exception {
      getContentPane().setLayout(new BorderLayout(30, 30)); 
 
      Vector v = new Vector();
      v.addElement("item 1");
      v.addElement("item 2");
      v.addElement("item 3");
 
      JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
      panel1.add(new JButton("Button"));
      panel1.add(new JCheckBox("CheckBox"));
      panel1.add(new JTextField(10));
      panel1.add(new JComboBox(v));
 
      JPanel panel2 = new JPanel(new FlowLayout(FlowLayout.LEFT));
      panel2.add(new JButton("Button"));
      panel2.add(new JCheckBox("CheckBox"));
      panel2.add(new JTextField(10));
      panel2.add(new JComboBox(v));
 
      getContentPane().add(BorderLayout.NORTH, panel1);
      getContentPane().add(BorderLayout.SOUTH, panel2);
 
      UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
      SwingUtilities.updateComponentTreeUI(panel1);
 
      UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
      SwingUtilities.updateComponentTreeUI(panel1);
 
      pack();
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String args[]) throws Exception {
      Main main = new Main();
      //main.setSize(300, 300);
      main.setVisible(true);
   }
}

Right-aligning a JTable column

Main.java:

import javax.swing.table.*;
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));
 
      // right align 2nd column
      TableColumnModel columnModel = table.getColumnModel();
      TableColumn column = columnModel.getColumn(1);  
      DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
      renderer.setHorizontalAlignment(JLabel.RIGHT);
      column.setCellRenderer(renderer);
 
      // right align 2nd column when editing
      JTextField tf = new JTextField();
      tf.setHorizontalAlignment(JTextField.RIGHT);
      column.setCellEditor(new DefaultCellEditor(tf));
 
      JScrollPane scrollPane = new JScrollPane(table);
      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();
   }
}

Changing the traversal keys that control focus

In 1.4, you can use the following method.

Main.java:

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");
   JButton button = new JButton("Button");
   JTextField textfield1 = new JTextField();
   JTextField textfield2 = new JTextField();
 
   public Main() {
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  
      Container contentPane = getContentPane();
      contentPane.setLayout(new BorderLayout());
      JPanel panel = new JPanel(new GridLayout(4, 1, 10, 10));
      panel.add(label);
      panel.add(textfield1);   
      panel.add(textfield2);   
      panel.add(button);
      contentPane.add(BorderLayout.NORTH, panel);
 
      // add "alt f" as an alternative to TAB 
      Set set = contentPane.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS);
      KeyStroke altf = KeyStroke.getKeyStroke("alt F");
      set = new HashSet(set);
      set.add(altf);
      contentPane.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, set);
 
      // add "alt b" as an alternative to SHIFT-TAB 
      set = contentPane.getFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS);
      KeyStroke altb = KeyStroke.getKeyStroke("alt B");
      set = new HashSet(set);
      set.add(altb);
      contentPane.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, set);
   } 
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(350, 200);
      main.setVisible(true);
   }
}

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);
   }
}