Getting the JMenu object from the selected JMenuItem

Get the accessible parent from the accessibleContext.
Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame implements ActionListener {
   private JMenu menu1;
   private JMenu menu2;
 
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JMenuBar menuBar = new JMenuBar();
      menu1 = new JMenu("The weak sex");
      JMenuItem menuItem1 = new JMenuItem("male");
      menu2 = new JMenu("The strong sex");
      JMenuItem menuItem2 = new JMenuItem("female");
      menu1.add(menuItem1);
      menu2.add(menuItem2);
      menuBar.add(menu1);
      menuBar.add(menu2);
      menuItem1.addActionListener(this);
      menuItem2.addActionListener(this);
 
      this.setJMenuBar(menuBar); 
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(400, 400);
   }
 
   public void actionPerformed(ActionEvent ae) {
      JMenuItem menuItem = (JMenuItem) ae.getSource();
      JMenu menu = (JMenu) menuItem.getAccessibleContext().getAccessibleParent();
      System.out.println("Selected menu: " + menu.getText());
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Automatically transferring the focus when a JTextField column limit has been reached

You can do so by extending JTextField to catch every insertion and checking whether the limit has been reached. If so, you can use transferFocus to have the focus jumpt to the next component.

Main.java:

import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      getContentPane().add(new AutoFocusTextField("Try typing more", 15, 20));
      getContentPane().add(new AutoFocusTextField(10, 3));
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(300, 300);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}
 
class AutoFocusTextField extends JTextField
{
   private int maxCols = 0;
 
   public AutoFocusTextField(int maxCols) {
      super();
      this.maxCols = maxCols;
   }
 
   public AutoFocusTextField(int cols, int maxCols) {
      super(cols);
      this.maxCols = maxCols;
   }
  
   public AutoFocusTextField(String text, int maxCols) {
      super();
      this.maxCols = maxCols;
      setText(text);
   } 
 
   public AutoFocusTextField(String text, int cols, int maxCols) {
      super(cols);
      this.maxCols = maxCols;
      setText(text);
   }
 
   protected Document createDefaultModel() {
      return new AutoFocusDocument();
   }
  
   protected class AutoFocusDocument extends PlainDocument {
      public void insertString(int offset, String str, AttributeSet as) 
            throws BadLocationException  {
         if (str == null || getLength() + str.length() <= maxCols) {
            super.insertString(offset, str, as);
            if (offset == maxCols-1) {
               transferFocus();
            }
         }
         else {
            int remainder = maxCols - getLength();
            if (remainder > 0) {
               super.insertString(offset, str.substring(0, remainder), as);
            }
            transferFocus();
         }
      }
   }
}

Catching events when the mouse moves over a JLabel

You can add a MouseMotionListener for mouse movements or a MouseListener for other interesting mouse events. This example shows how to invert the color of the JLabel when the mouse is positioned over it.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      final JLabel label = new JLabel("Move your mouse over this JLabel!");
      label.setOpaque(true);
      getContentPane().add(label);  
 
      label.addMouseMotionListener(new MouseMotionAdapter() {
         public void mouseMoved(MouseEvent me) {
            System.out.println("Mouse is being moved over JLabel");
         }
      });
 
      label.addMouseListener(new MouseAdapter() {
         public void mouseEntered(MouseEvent evt) {
            Color c = label.getBackground();
            label.setBackground(label.getForeground());
            label.setForeground(c);
         }
 
         public final void mouseExited(MouseEvent evt) { 
            Color c = label.getBackground();
            label.setBackground(label.getForeground());
            label.setForeground(c);            
         } 
         
         public final void mouseClicked(MouseEvent evt) { 
            System.err.println("Mouse has been clicked on JLabel"); 
         } 
      }); 
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(300, 200);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Changing the default color of JToolTips

Use the Swing class UIManager for this and change the keys ToolTip.background and ToolTip.foreground. Here’s an example:

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame {
   public Main() {
      super("JToolTip Delay Demonstration");
 
      getContentPane().setLayout(new FlowLayout()); 
 
      JLabel label = new JLabel("How was I?");
      label.setToolTipText("too commercial");
 
      UIManager.put("ToolTip.background", Color.red);
      UIManager.put("ToolTip.foreground", Color.yellow);
   
      getContentPane().add(label);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
 
      setSize(400, 300);
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      main.setVisible(true);
   }
}

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