Using the BorderFactory in Swing

If you have lots of components with borders in your Swing GUI, you could create a Border instance for every component. The BorderFactory class provides a way to share border instances among different components. When using the class for the first time, it creates a number of static borders that it reuses and returns when you call one of the static create methods that the class exposes.

Main.java:

import javax.swing.border.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() {
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
 
      JLabel label1 = new JLabel("Label 1");
      label1.setBorder(BorderFactory.createLoweredBevelBorder()); 
 
      // reuse border
      JLabel label2 = new JLabel("Label 2");
      label2.setBorder(BorderFactory.createLoweredBevelBorder()); 
 
      getContentPane().add(label1);
      getContentPane().add(label2);
      
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String [] args) {
      Main main = new Main();
      main.pack();
      main.setVisible(true);
   } 
} 

Disabling the maximize-icon in a JFrame

First thing you can try is changing the resizable property from the Frame class:

 
import javax.swing.*;
import java.awt.*;
  
public class DisableMax extends JFrame {
 
   public DisableMax() {
      setSize(100, 100);

      setResizable(false);
   }
 
   public static void main(String args[]) {
      new DisableMax().setVisible(true);     
   }
}

However, in this example the maximize icons will still be there. Moreover, the frame will not be resizable anymore (might not be the functionality you want!).
Extend from a JDialog instead and your window will only have the X icon visible.

 
import javax.swing.*;
import java.awt.*;
   
public class DisableMax2 extends JDialog {
 
   public DisableMax2() {
      setSize(100, 100);
 
      setResizable(false);
   }
 
   public static void main(String args[]) {
      new DisableMax2().setVisible(true);     
   }
}

Scrolling a JScrollPane to the bottom programmatically

Call the method scrollRectToVisible of the component that is added to the JScrollPane container as shown in following example:

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() throws Exception {
      getContentPane().setLayout(new BorderLayout());
 
      final JPanel panel = createPanel(); 
      final JScrollPane scrollpane = new JScrollPane(panel);
 
      JButton button = new JButton("Scroll to bottom!");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            panel.scrollRectToVisible(
              new Rectangle(0, panel.getHeight()-1, 1, 1));
         }
      });
 
      getContentPane().add(BorderLayout.NORTH, button);
      getContentPane().add(BorderLayout.CENTER, scrollpane);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static JPanel createPanel() throws Exception {
      JPanel panel = new JPanel();
      panel.setLayout(new GridLayout(50, 20, 10, 10));
 
      for (int i=0; i<50; i++) {
         for (int j=0; j<20; j++) {
            JLabel label = new JLabel("label " + i + ", " + j);
            panel.add(label);    
         }
      }
 
      return panel;
   }
 
   public static void main(String [] args) throws Exception  {
      Main main = new Main();
      main.setSize(600, 600);
      main.setVisible(true);
   } 
} 

Programmatically selecting a tab of a JTabbedPane

Use the method setSelectedIndex and pass it the index of the tab that you want to be selected. Here’s an example:

import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.net.*;
 
public class Main extends JFrame implements ActionListener {
   JTabbedPane tabbedPane;
   int ntabs = 0;
 
   public Main() {
      getContentPane().setLayout(new BorderLayout());
      tabbedPane = new JTabbedPane();
      createTab();
 
      getContentPane().add(BorderLayout.CENTER, tabbedPane);
      setJMenuBar(createMenuBar());
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   
      setTitle("JTabbedPane Orientation Demonstration");
      setSize(new Dimension(400, 400));
   }
 
   protected JMenuBar createMenuBar() {
      JMenuBar menuBar = new JMenuBar();
 
      JMenu menu1 = new JMenu("JTabbedPane");
      JMenuItem menuItem1 = new JMenuItem("Create new tab");
      menuItem1.addActionListener(this);
      menu1.add(menuItem1);
      JMenu menu2 = new JMenu("Select tab");
      JMenuItem menuItem2 = new JMenuItem("Random tab");
      menuItem2.addActionListener(this);
      menu2.add(menuItem2);
      menuBar.add(menu1);
      menuBar.add(menu2);
 
      return menuBar;
   }
  
   public void actionPerformed(ActionEvent e) {
      if (e.getActionCommand().equals("Create new tab")) {
         createTab();
      }
      else if (e.getActionCommand().equals("Random tab")) {
         selectRandomTab();
      }
   }
 
   protected void createTab() {
      ntabs++;
      tabbedPane.addTab("Tab #" + ntabs, new JLabel("Tab #" + ntabs));
   }
 
   protected void selectRandomTab() {
      Random r = new Random();
      int tabToSelect = r.nextInt(ntabs);
      tabbedPane.setSelectedIndex(tabToSelect);
   }
  
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}

Creating a JToolBar with a drop-down menu as one of the items

Main.java:

import javax.swing.border.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
  
public class Main extends JFrame {
   public Main() {
      super("JToolBar example");
 
      try {
         UIManager.setLookAndFeel(
   	    "com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
      }
      catch(Exception e) { }
 
      final JTextArea textArea = new JTextArea(5, 30);
      JToolBar toolBar = new JToolBar();
      toolBar.setLayout(new FlowLayout(FlowLayout.LEFT));
 
      JButton actionButton = new JButton("Back", new ImageIcon("backdis.gif"));
      actionButton.setRolloverIcon(new ImageIcon("backen.gif"));
      actionButton.setRolloverEnabled(true);
 
      JPopupMenu popupMenu = new JPopupMenu();
      popupMenu.add("JToolBar (Java 2 Platform SE v1.4.0)");
      popupMenu.add("Overview (Java 2 Platform SE v1.4.0)");
      popupMenu.add("Google");
 
      DropDownButton dropDownButton = new DropDownButton(actionButton, popupMenu);
 
      toolBar.add(dropDownButton);
      toolBar.add(new JButton("Forward"));
      toolBar.add(new JButton("Stop"));
      toolBar.add(new JButton("Home"));
      toolBar.setRollover(true);
 
      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 DropDownButton extends AbstractButton
{
   JButton actionButton;
   JToggleButton menuButton;
   JPopupMenu popupMenu;
 
   public DropDownButton(JButton _actionButton, JPopupMenu _popupMenu) {
      this.popupMenu = _popupMenu;
      this.actionButton = _actionButton;
 
      setLayout(new BorderLayout());
      actionButton.setBorderPainted(false);
      add(BorderLayout.CENTER, actionButton);
      menuButton = new JToggleButton(new ImageIcon("down.jpg"));
      menuButton.setPreferredSize(new Dimension(15, 10));
      add(BorderLayout.EAST, menuButton);
      menuButton.setBorderPainted(false);
  
      MouseAdapter ma = new MouseAdapter() {
         public void mouseClicked(MouseEvent me) { }
         public void mousePressed(MouseEvent me) { 
            if (me.getSource() == actionButton) {
               menuButton.setSelected(true);
            }
         }
         public void mouseReleased(MouseEvent me) {
            if (me.getSource() == actionButton) {
               menuButton.setSelected(false);
            }
         }
         public void mouseEntered(MouseEvent me) { 
            setRolloverBorder(); 
         }
         public void mouseExited(MouseEvent me) { 
            unsetRolloverBorder();
         }
      };
 
      actionButton.addMouseListener(ma);
      menuButton.addMouseListener(ma);
 
      menuButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            popupMenu.show(actionButton, 0, actionButton.getSize().height);
         }
      });
   }  
 
   protected void setRolloverBorder() {
      actionButton.setBorderPainted(true);
      menuButton.setBorderPainted(true);
   }
 
   protected void unsetRolloverBorder() {
      actionButton.setBorderPainted(false);
      menuButton.setBorderPainted(false);
   }
}

Images used:

backdis.gif:
backen.gif:
down.jpg:

Capturing a close event on a JInternalFrame

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.beans.*;
import java.util.*;
import java.awt.*;
import java.net.*;
 
public class Main extends JFrame {
   JDesktopPane desktop;
   int nframes = 0;
  
   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);
 
      return menuBar;
   }
 
   protected void createInternalFrame() {
      nframes++;
      String title = "JInternalFrame #" + nframes;
      MyJInternalFrame frame = new MyJInternalFrame(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) {}
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(500, 300);
      main.setVisible(true);
   }
} 
 
class MyJInternalFrame extends JInternalFrame 
                       implements VetoableChangeListener { 
   public MyJInternalFrame(String title, boolean resizable, 
                           boolean closable, boolean maximizable, 
                           boolean iconifiable) { 
      super(title, resizable, closable, maximizable, iconifiable); 
      addVetoableChangeListener(this); 
   } 
 
   public void vetoableChange(PropertyChangeEvent pce) 
                                 throws PropertyVetoException { 
      if (pce.getPropertyName().equals(IS_CLOSED_PROPERTY)) { 
         boolean changed = ((Boolean) pce.getNewValue()).booleanValue(); 
         if (changed) { 
            int option = JOptionPane.showOptionDialog(this, "Close " + 
                                                       getTitle() + "?", 
                                                       "Close Confirmation", 
                                                       JOptionPane.YES_NO_OPTION, 
                                                       JOptionPane.QUESTION_MESSAGE, 
                                                       null, null, null); 
            if (option != JOptionPane.YES_OPTION) { 
               throw new PropertyVetoException("Cancelled",null); 
            } 
         } 
      } 
   }
} 

Center a text over a JButton’s icon

Use the JButton’s methods setHorizontalTextPosition and setVerticalTextPosition.
Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame implements ActionListener {
   JList list; 
 
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JButton fbutton = new JButton("Text Over Image", new ImageIcon("female.gif"));
      fbutton.addActionListener(this);
      fbutton.setVerticalTextPosition(SwingConstants.CENTER);
      fbutton.setHorizontalTextPosition(SwingConstants.CENTER); 
 
      getContentPane().add(BorderLayout.CENTER, fbutton);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(400, 400);
   }
 
   public void actionPerformed(ActionEvent ae) {
      System.out.println("Your pressed the "" + ae.getActionCommand() + "" button");
   }
   
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Creating a JComboBox with a divider separator line

Create a cellRenderer that does not convert the element to a String in order to show it, but instead checks whether it is a JSeparator and returns that component instead. Then make sure the JSeparator itself cannot be selected by adding an ActionListener to the combobox.

Main.java:

import javax.swing.plaf.basic.*;
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 Object[] {
               "Item 1",
               "Item 2",
               "Item 3",
               new JSeparator(JSeparator.HORIZONTAL),
               "Item 4",
               "Item 5"
            }
         );
 
      getContentPane().add(combobox);
      combobox.setRenderer(new SeparatorComboBoxRenderer());
      combobox.addActionListener(new SeparatorComboBoxListener(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);
   }
}
 
class SeparatorComboBoxRenderer extends BasicComboBoxRenderer implements ListCellRenderer
{
   public SeparatorComboBoxRenderer() {
      super();
   }
   
   public Component getListCellRendererComponent( JList list, 
           Object value, int index, boolean isSelected, boolean cellHasFocus) {
      if (isSelected) {
          setBackground(list.getSelectionBackground());
          setForeground(list.getSelectionForeground());
      }
      else {
          setBackground(list.getBackground());
          setForeground(list.getForeground());
      }
 
      setFont(list.getFont());
      if (value instanceof Icon) {
         setIcon((Icon)value);
      }
      if (value instanceof JSeparator) {
         return (Component) value;
      }
      else {
         setText((value == null) ? "" : value.toString());
      }
 
      return this;
  }  
}
 
class SeparatorComboBoxListener implements ActionListener {
   JComboBox combobox;
   Object oldItem;
    
   SeparatorComboBoxListener(JComboBox combobox) {
      this.combobox = combobox;
      combobox.setSelectedIndex(0);
      oldItem = combobox.getSelectedItem();
   }
     
   public void actionPerformed(ActionEvent e) {
      Object selectedItem = combobox.getSelectedItem();
      if (selectedItem instanceof JSeparator) {
         combobox.setSelectedItem(oldItem);
      } else {
         oldItem = selectedItem;
      }
   }
}

Having a JList go to a specific item when a user presses a key

JListKeyPressed.java:

import javax.swing.*;
import java.awt.event.*;
 
public class JListKeyPressed extends JFrame {
   private JList list;
   private JPanel p;
 
   public JListKeyPressed() {
      super("JListKeyPressed");
      p = new JPanel();
      final String data[] = {"ah","bh","ch","dh","eh","fh","gh","hh","ih"};
      list = new JList(data);
 
      list.addKeyListener(new KeyAdapter() {
         public void keyPressed(KeyEvent e) {
            for(int i = 0; i < data.length; i++) {
               if(data[i].charAt(0) == Character.toLowerCase(e.getKeyChar())) {
                  list.setSelectedIndex(i);
               }
            }
         }
      });
 
      setContentPane(p);
      p.add(list);
      setSize(300,300);
 	
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            dispose();
            System.exit(0);
         }
      });
 	
      setVisible(true);
   }
 
   public static void main(String args[]) {
      JListKeyPressed j = new JListKeyPressed();
   }
}

Justifying the text on a JMenuItem

You have a number of functions:setHorizontalAlignment, setHorizontalTextPosition, setVerticalAlignment, setVerticalTextPosition. Look at the API docs for more information about their behaviour.

Main.java:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JMenuBar menuBar = new JMenuBar();
      JMenu menu = new JMenu("Sex");
      JMenuItem menuItem0 = new JMenuItem("NO ALIGNMENT");
      JMenuItem menuItem1 = new JMenuItem("CENTER");
      JMenuItem menuItem2 = new JMenuItem("LEFT");
      JMenuItem menuItem3 = new JMenuItem("RIGHT");
      JMenuItem menuItem4 = new JMenuItem("LEADING");
      JMenuItem menuItem5 = new JMenuItem("TRAILING");
 
      // add the MenuItems to the Menu 
      menu.add(menuItem0);
      menu.add(menuItem1);
      menu.add(menuItem2);
      menu.add(menuItem3);
      menu.add(menuItem4);
      menu.add(menuItem5);
   
      menuItem1.setHorizontalAlignment(SwingConstants.CENTER);
      menuItem2.setHorizontalAlignment(SwingConstants.LEFT);
      menuItem3.setHorizontalAlignment(SwingConstants.RIGHT);
      menuItem4.setHorizontalAlignment(SwingConstants.LEADING);
      menuItem5.setHorizontalAlignment(SwingConstants.TRAILING);
 
      menuBar.add(menu);
 
      this.setJMenuBar(menuBar); 
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(400, 400);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}