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

Embedding a JSpinner inside a JTable cell

Main.java:

import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
  
public class JSpinnerTableExample extends JFrame {
 
  public JSpinnerTableExample(){
    super( &amp;amp;quot;JSpinnerTable Example&amp;amp;quot; );
    
    SpinnerNumberModel spinnerModel1 = new SpinnerNumberModel(10.0, -500.0, 500.0, .5);
    SpinnerDateModel spinnerModel2 = new SpinnerDateModel();
 
    DefaultTableModel dtm = new DefaultTableModel();
    dtm.setDataVector(new Object[][]{{ spinnerModel1, &amp;amp;quot;JSpinner1&amp;amp;quot; },
                                     { spinnerModel2, &amp;amp;quot;JSpinner2&amp;amp;quot; }},
                      new Object[]{&amp;amp;quot;JSpinner&amp;amp;quot;,&amp;amp;quot;String&amp;amp;quot;});
                     
    JTable table = new JTable(dtm);
    table.getColumn(&amp;amp;quot;JSpinner&amp;amp;quot;).setCellRenderer(new SpinnerRenderer());
    table.getColumn(&amp;amp;quot;JSpinner&amp;amp;quot;).setCellEditor(new SpinnerEditor());
 
    table.setRowHeight(20);
    JScrollPane scroll = new JScrollPane(table);
    getContentPane().add(scroll);
 
    setSize( 400, 100 );
    setVisible(true);
  }
 
  public static void main(String[] args) {
    JSpinnerTableExample frame = new JSpinnerTableExample();
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
  }
}
 
class SpinnerRenderer extends JSpinner implements TableCellRenderer {
   public SpinnerRenderer() {
      setOpaque(true);
   }
  
   public Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean hasFocus, int row, int column) {
      setModel((SpinnerModel) value);
  
      return this;
   }
}
  
class SpinnerEditor extends AbstractCellEditor implements TableCellEditor {
   protected JSpinner spinner;
  
   public SpinnerEditor() {
      spinner = new JSpinner();
   }
 
   public Component getTableCellEditorComponent(JTable table, Object value,
                    boolean isSelected, int row, int column) {
      spinner.setModel((SpinnerModel) value);
 
      return spinner;
   }
 
   public Object getCellEditorValue() {
      SpinnerModel sm = spinner.getModel();
      return sm;
   }
}

Drawing an image in a JLabel

Very simple: look at the constructors of JLabel and you’ll see that some of them accept images. A JLabel can contain either text, an image or both. If you have both images and text, you can set the horizontal and vertical text position using the methods:

      setVerticalTextPosition
      setHorizontalTextPosition

Here’s a complete example:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   JLabel label;
 
   public Main() {
      label = new JLabel("The Logo", new ImageIcon("d:\ESUSLOGO.gif"), 

SwingConstants.CENTER);
      label.setVerticalTextPosition(SwingConstants.BOTTOM);
      label.setHorizontalTextPosition(SwingConstants.CENTER);
      getContentPane().add(BorderLayout.CENTER, label);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      setSize(300, 200);
   }
  
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
   }
}

Making a JLabel selectable

A common way is to create a JTextField and give the user the impression it’s a JLabel by changing some of its properties. Here’s an example:

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() {
      getContentPane().setLayout(new FlowLayout());
      JLabel label = new JLabel("BWOAAHAHAHA, you can't select me!");
      JTextField textfield = new JTextField("Grab me instead!   ");
 
      // give the textfield the impression it's a label
      textfield.setBorder(null);
      textfield.setEditable(false);
      textfield.setForeground(UIManager.getColor("Label.foreground"));
      textfield.setFont(UIManager.getFont("Label.font"));
 
      getContentPane().add(label);
      getContentPane().add(textfield);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String [] args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   } 
} 

Displaying a dialog window to open files

This following example will use Swings JFileChooser to display a dialog box and allow the user to select a file.
It will set the current directory to c: and set the default selection to autoexec.bat. Notice that multiple file selections are not implemented for the current look and feels (see the JFileChooser API).
The method showOpenDialog will block until a file has been selected. It returns APPROVE_OPTION if OK has been clicked, CANCEL_OPTION otherwise.

import java.awt.event.*;
import javax.swing.*;
import java.io.*;

public class Main extends JFrame
{
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }

   public Main() {
      JButton fileButton = new JButton("Select File");
      fileButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            File file = getFileFromUser();
            if (file != null)
               System.out.println(file.getName());
         }
      });
      getContentPane().add(fileButton);

      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });

      pack();
   }
  
   public File getFileFromUser() {
      JFileChooser fc = new JFileChooser();

      // use current directory
      fc.setCurrentDirectory(new File("c:\"));

      // set default name
      fc.setSelectedFile(new File("autoexec.bat"));

      // enable multiple selection, not implemented yet in current L&F's
      fc.setMultiSelectionEnabled(true);

      // show dialog for opening files
      int result = fc.showOpenDialog(this);

      if (result != fc.APPROVE_OPTION) 
         return null;
      
      return fc.getSelectedFile();
   }
}

Get started with a simple JTable

Using a simple Swing table in your GUI apps doesn’t require a lot of code. Create a one-dimensional containing the table headers and a two-dimensional array that represents the contents. Create a JTable with those two arrays and add it to the container. This is the simpliest example. All cells are editable and column widths can be adjusted.
If you want to have more control over your JTables, you can create your own TableModel, CellRenderer and CellEditor.

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

Creating a JTable with multiline cells

Courtesy of Nobuo Tamemasa (http://www2.gol.com/users/tame/swing/examples/JTableExamples1.html)



MultiLineCellExample.java:

import javax.swing.*;
import javax.swing.table.*;
import javax.swing.border.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
 
/**
 * @version 1.0 11/09/98
 */
public class MultiLineCellExample extends JFrame {
  MultiLineCellExample() {
    super( &quot;Multi-Line Cell Example&quot; );
 
    DefaultTableModel dm = new DefaultTableModel() {
      public Class getColumnClass(int columnIndex) {
        return String.class;
      }
    };
    dm.setDataVector(new Object[][]{{&quot;ana&quot;,&quot;bnb&quot;,&quot;cnc&quot;},
                                    {&quot;AnA&quot;,&quot;BnB&quot;,&quot;CnC&quot;}},
                     new Object[]{&quot;1&quot;,&quot;2&quot;,&quot;3&quot;});
 
    JTable table = new JTable( dm );
    
    int lines = 2;
    table.setRowHeight( table.getRowHeight() * lines);
    
    //
    // table.setRowHeight(0);
    //
    // I got &quot;java.lang.IllegalArgumentException: New row height less than 1&quot;
    //
    table.setDefaultRenderer(String.class, new MultiLineCellRenderer());
    JScrollPane scroll = new JScrollPane( table );
    getContentPane().add( scroll );
    setSize( 400, 130 );
    setVisible(true);
  }
 
  public static void main(String[] args) {
    MultiLineCellExample frame = new MultiLineCellExample();
    frame.addWindowListener( new WindowAdapter() {
      public void windowClosing( WindowEvent e ) {
        System.exit(0);
      }
    });
  }
}
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.border.*;
import java.awt.*;
 
/**
 * @version 1.0 11/09/98
 */
 
public class MultiLineCellRenderer extends JTextArea implements TableCellRenderer {
 
  public MultiLineCellRenderer() {
    setLineWrap(true);
    setWrapStyleWord(true);
    setOpaque(true);
  }
 
  public Component getTableCellRendererComponent(JTable table, Object value,
               boolean isSelected, boolean hasFocus, int row, int column) {
    if (isSelected) {
      setForeground(table.getSelectionForeground());
      setBackground(table.getSelectionBackground());
    } else {
      setForeground(table.getForeground());
      setBackground(table.getBackground());
    }
    setFont(table.getFont());
    if (hasFocus) {
      setBorder( UIManager.getBorder(&quot;Table.focusCellHighlightBorder&quot;) );
      if (table.isCellEditable(row, column)) {
        setForeground( UIManager.getColor(&quot;Table.focusCellForeground&quot;) );
        setBackground( UIManager.getColor(&quot;Table.focusCellBackground&quot;) );
      }
    } else {
      setBorder(new EmptyBorder(1, 2, 1, 2));
    }
    setText((value == null) ? &quot;&quot; : value.toString());
    return this;
  }
}