Creating a scrollable JPanel

Create a JScrollPane and pass your panel to its constructor. Then add the scrollpane to the container. Make sure your panel has a size in case you use the null layout manager (with setSize and setPreferredSize). Here’s an example that uses a BorderLayout.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() {
      getContentPane().setLayout(new BorderLayout());
 
      JPanel panel = createPanel();
 
      getContentPane().add(BorderLayout.CENTER, new JScrollPane(panel));
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static JPanel createPanel() {
      JPanel panel = new JPanel();
      panel.setLayout(new GridLayout(20, 4, 10, 10));
 
      for (int i=0; i<20; i++) {
         for (int j=0; j<4; j++) {
            JLabel label = new JLabel("label " + i + ", " + j);
            label.setFont(new Font("Helvetica", Font.PLAIN, 30));
            panel.add(label);            
         }
      }
 
      return panel;
   }
 
   public static void main(String [] args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   } 
} 

Find out what JTabbedPane tab is selected

Note:
1.Each Tab in a Tabbed Pane is a JPanel i.e it has a name
2.The first Tab index is ’0′, 2′nd tab ’1′ and so on.
3.’StateChanged’ event is fired on selection of a tab.

....
....
....
tabbedPane.addChangeListener(changeListener)
....
....
public void stateChanged(changeEvent)
{
   if(e.getSource() == tabbedPane)
   {
      int i = tabbedPane.getSelectedIndex();
      Component c = tabbedPane.getSelectedComponent();
   }
}
....
....

Adding a vertical line separator to a JToolBar

The method addSeparator in the JToolBar class only adds blank space. You could add JSeparator components to your JToolBar with add but then you run into trouble when changing the orientation. In the following example, this has been solved by listening to propertyChangeEvents and changing the JSeparator orientation so that they are opposite to the JToolBar’s orientation.

Main.java:

import javax.swing.border.*;
import java.awt.event.*;
import javax.swing.*;
import java.beans.*;
import java.awt.*;
  
public class Main extends JFrame {
   public Main() {
      super("JToolBar example");
 
      final JTextArea textArea = new JTextArea(5, 30);
      MyJToolBar toolBar = new MyJToolBar();
 
      JButton gifButton = new JButton(new ImageIcon("gifIcon.gif"));
      JButton jpgButton = new JButton(new ImageIcon("jpgIcon.gif"));
      JButton tiffButton = new JButton(new ImageIcon("tiffIcon.gif"));
 
      gifButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            textArea.append("gifButton clicked!n");
         }
      });
  
      jpgButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            textArea.append("jpgButton clicked!n");
         }
      });
        
      tiffButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            textArea.append("tiffButton clicked!n");
         }
      });
 
      toolBar.add(gifButton);
      toolBar.add(new JToolBar.Separator());
      toolBar.add(new JSeparator(JSeparator.VERTICAL));
      toolBar.add(new JToolBar.Separator());
      toolBar.add(jpgButton);
      toolBar.add(new JToolBar.Separator());
      toolBar.add(new JSeparator(JSeparator.VERTICAL));
      toolBar.add(new JToolBar.Separator());
      toolBar.add(tiffButton);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
 
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(BorderLayout.NORTH, toolBar);
      getContentPane().add(BorderLayout.CENTER, new JScrollPane(textArea));
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   }
}
 
class MyJToolBar extends JToolBar
{
   public MyJToolBar() {
      super();
      listenForOrientationChange();
   }
 
   public MyJToolBar(int orientation) {
      super(orientation);
      listenForOrientationChange();
   }
 
   public MyJToolBar(String name) {
      super(name);
      listenForOrientationChange();
   }
 
   public MyJToolBar(String name, int orientation) {
      super(name, orientation);
      listenForOrientationChange();
   }
 
   protected void listenForOrientationChange() {
      addPropertyChangeListener(new PropertyChangeListener() {
         public void propertyChange(PropertyChangeEvent evt) {
            MyJToolBar toolBar = MyJToolBar.this;
            Component[] components = toolBar.getComponents();
            for (int i=0; i<components.length; i++) {
               if (components[i] instanceof javax.swing.JSeparator) {
                  JSeparator separator = (JSeparator) components[i];
                  if (toolBar.getOrientation() == SwingConstants.HORIZONTAL) {
                     separator.setOrientation(JSeparator.VERTICAL);      
                     separator.setMaximumSize(new Dimension(2,
                                              toolBar.getPreferredSize().width));
                  }
                  else {
                     separator.setOrientation(JSeparator.HORIZONTAL);
                     separator.setMaximumSize(new Dimension(
                                              toolBar.getPreferredSize().height, 2));
                  }
               }
            }
         }
      });
   }
}

Programmatically closing a JInternalFrame

Use this:

   frame.getDesktopPane().getDesktopManager().closeFrame(frame);

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.net.*;
 
public class Main extends JFrame {
   JDesktopPane desktop;
   int nframes = 0;
 
   JMenu internalFrameMenu;
   Action closeAction = new CloseAction();
 
   public Main() {
      desktop = new JDesktopPane(); 
      setContentPane(desktop);
      setJMenuBar(createMenuBar());
      createInternalFrame(); 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   protected JMenuBar createMenuBar() {
      JMenuBar menuBar = new JMenuBar();
 
      JMenu createMenu = new JMenu("Create");
      createMenu.setMnemonic(KeyEvent.VK_C);
      JMenuItem newMenuItem = new JMenuItem("New");
      newMenuItem.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            createInternalFrame();
         }
      }); 
      newMenuItem.setMnemonic(KeyEvent.VK_N);
      createMenu.add(newMenuItem);
      menuBar.add(createMenu);
 
      internalFrameMenu = new JMenu("Close");
      internalFrameMenu.setMnemonic(KeyEvent.VK_C);
  
      menuBar.add(internalFrameMenu);     
 
      return menuBar;
   }
 
   protected void createInternalFrame() {
      nframes++;
      String title = "JInternalFrame #" + nframes;
      JInternalFrame frame = new JInternalFrame(title,
         true,    // resizable
         true,    // closable
         true,    // maximizable
         true);   // iconifiable
      frame.setVisible(true); 
      desktop.add(frame);
      frame.setSize(200, 200);
      frame.setLocation(30*nframes, 30*nframes);
      try {
         frame.setSelected(true);
      } catch (java.beans.PropertyVetoException e) {}
 
      JMenuItem menuItem = new JMenuItem(title);
      internalFrameMenu.add(menuItem);
      menuItem.addActionListener(closeAction);
      frames.put(title, frame);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(500, 300);
      main.setVisible(true);
   }
 
   public class CloseAction extends AbstractAction
   {
      public CloseAction() {
         super("Close Action");
      }
 
      public void actionPerformed(ActionEvent ae) {
         JMenuItem menuItem = ((JMenuItem) ae.getSource());
         JInternalFrame frame = (JInternalFrame) frames.get(menuItem.getText());
         // close the frame
         frame.getDesktopPane().getDesktopManager().closeFrame(frame);
         // remove JMenuItem from JMenu
         JMenu parent = (JMenu) ((JPopupMenu) menuItem.getParent()).getInvoker();
         parent.remove(menuItem);
      }
   }
}

Assinging a shortcut key to a JButton

Swings JButton inherits from AbstractButton that defines a method setMnemonic.
You can use it as follows:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
   
public class Main extends JFrame
{
   public Main() throws Exception {
      JButton button = new JButton("Click or press ALT-C");
      button.setMnemonic('C');
 
      getContentPane().add(button);
      pack();
 
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent evt) {
            System.out.println("Button clicked!");
         }
      });
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String args[]) throws Exception {
      Main main = new Main();
      main.show();
   }
}

Invoking a JPopupMenu from a JComboBox

Add a MouseListener:

import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
    
public class Main extends JFrame
{ 
   public Main() {
      getContentPane().setLayout(new FlowLayout());
      
      final JComboBox combobox = new JComboBox(new String[] { "Item 1", "Item 2", "Item 3" });
      final JPopupMenu popup = new JPopupMenu();
      JMenuItem mi1 = new JMenuItem("Popup Item 1");
      JMenuItem mi2 = new JMenuItem("Popup Item 2");
      popup.add(mi1);
      popup.add(mi2);
 
      ((JButton) combobox.getComponent(0)).addMouseListener(new MouseAdapter() {
         public void mousePressed(MouseEvent me) {
            if (me.isPopupTrigger()) {
               popup.show(combobox, me.getX(), me.getY());
            }
         }
 
         public void mouseReleased(MouseEvent me) {
            if (me.isPopupTrigger()) {
               popup.show(combobox, me.getX(), me.getY());
            }
         }
      });
 
      getContentPane().add(combobox);
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });      
   
      setSize(new Dimension(200, 200));
   } 
 
   public static void main(String[] args) throws Exception {
      Main main = new Main();
      main.setVisible(true);
   }
}

Changing the color of every element in a JList

Customize the CellRenderer as in following example:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
  
public class Main extends JFrame {
 
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      Vector v = new Vector();
      final JList list = new JList(
         new Colorable[] { new ColoredItem("Item 1", Color.yellow),
                           new ColoredItem("Item 2"),
                           new ColoredItem("Item 3", Color.blue),
                           new ColoredItem("Item 4", Color.red),
                           new ColoredItem("Item 5", Color.green)
                         });
 
      list.setCellRenderer(new ColoredCellRenderer());
      getContentPane().add(new JScrollPane(list));    
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(200, 300);
   }
   
   public static void main(String[] args) {
      (new Main()).show();
   }
}
 
class ColoredCellRenderer extends DefaultListCellRenderer implements ListCellRenderer {
   public Component getListCellRendererComponent(
      JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)    
   {
      setText((value == null) ? "" : value.toString());
      Color c = ((Colorable) value).getColor();
      if (isSelected) {
         setBackground(list.getSelectionBackground());
         setForeground(c);
      }
      else {
         setBackground(list.getBackground());
         setForeground(c);
      }
 
      setEnabled(list.isEnabled());
      setFont(list.getFont());
 
      return this;
   }
}
 
class ColoredItem implements Colorable {
   Object  object;
   Color   color;
                            
   public ColoredItem(Object object, Color color) {
      this.object = object;
      this.color = color;
   }
                             
   ColoredItem(Object object) {
      this(object, Color.black);
   }
 
   public Color getColor() {
      return color;
   } 
 
   public void setColor(Color color) {
      this.color = color;
   }                           
                            
   public String toString() {
      return object.toString();
   }
}
                         
interface Colorable {
   public Color getColor();
   public void setColor(Color c);
}

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