Assigning a shortcut key to a JCheckBox

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

import javax.swing.*;
import java.util.*;
import java.awt.*;
   
public class Main extends JFrame
{
   public Main() throws Exception {
      JCheckBox cbox1 = new JCheckBox("Check me or press ALT-C");
      JCheckBox cbox2 = new JCheckBox("Check me or press ALT-D");
      cbox1.setMnemonic('C');
      cbox2.setMnemonic('D');
 
      getContentPane().setLayout(new GridLayout(2, 1));
      getContentPane().add(cbox1);
      getContentPane().add(cbox2);
      pack();
 
      cbox1.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent evt) {
            System.out.println("First JCheckBox checked!");
         }
      });

      cbox2.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent evt) {
            System.out.println("Second JCheckBox checked!");
         }
      });
 
      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();
   }
}

Creating an editable JComboBox

Use the method setEditable. Here’s an example:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame
{ 
   public Main() {
      getContentPane().setLayout(new BorderLayout());
      final JComboBox combobox = new JComboBox();
      final JList list = new JList(new DefaultListModel());
 
      getContentPane().add(BorderLayout.NORTH, combobox);
      getContentPane().add(BorderLayout.CENTER, list); 
 
      combobox.setEditable(true);
      combobox.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent ie) {
            if (ie.getStateChange() == ItemEvent.SELECTED) {
               ((DefaultListModel) list.getModel()).addElement(combobox.getSelectedItem());
               combobox.insertItemAt(combobox.getSelectedItem(), 0);
            }
         }
      });
 
      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);
   }
}

Scrolling a JList to the selected item

You can use the method ensureIndexIsVisible as shown 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();
      for (int i=0; i<50; i++) {
         v.addElement("Item #" + i);
      }
      final JList list = new JList(v);
 
      final JTextField textfield = new JTextField(5);
      getContentPane().add(new JLabel("Scroll to:"));
      getContentPane().add(textfield);
      JButton button = new JButton("Scroll!");
      getContentPane().add(button);
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            int n = Integer.parseInt(textfield.getText());
            list.ensureIndexIsVisible(n);
         }
      });
      getContentPane().add(new JScrollPane(list));    
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(200, 230);
   }
   
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Adding a general JComponent to a JMenu

Create your own version of the JComponent that you would like to add to your Menu and have it implement the methods of MenuElement. Here’s an example that shows a JMenu with a JTextField and a JSlider as its elements:

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("Menu");
      JMenuItem menuItem1 = new JMenuItem("item 1");
      JMenuItem menuItem2 = new JMenuItem("item 2");
      JMenuItemTextField menuItem3 = new JMenuItemTextField(20);
      JMenuItem menuItem4 = new JMenuItem("item 4");
      JMenuItemSlider menuItem5 = new JMenuItemSlider();
      menuItem5.setMajorTickSpacing(20);
      menuItem5.setMinorTickSpacing(5);
      menuItem5.setPaintTicks(true);
      JMenuItem menuItem6 = new JMenuItem("item 6");
 
      menu.add(menuItem1);
      menu.add(menuItem2);
      menu.add(menuItem3);
      menu.add(menuItem4);
      menu.add(menuItem5);
      menu.add(menuItem6);
 
      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();
   }
}
 
class JMenuItemTextField extends JTextField implements MenuElement
{
   public JMenuItemTextField(int length) {
      super(length);
   }
 
   public Component getComponent() {
      return this;
   }
 
   public MenuElement[] getSubElements() {
      return null;
   }
 
   public void menuSelectionChanged(boolean changed) {
   }
 
   public void processKeyEvent(KeyEvent kevt, MenuElement[] me, MenuSelectionManager msm) {
   }
 
   public void processMouseEvent(MouseEvent mevt, MenuElement[] me, MenuSelectionManager msm) {
   }
}
 
class JMenuItemSlider extends JSlider implements MenuElement
{
   public JMenuItemSlider() {
      super();
   }
 
   public Component getComponent() {
      return this;
   }
 
   public MenuElement[] getSubElements() {
      return null;
   }
 
   public void menuSelectionChanged(boolean changed) {
   }
 
   public void processKeyEvent(KeyEvent kevt, MenuElement[] me, MenuSelectionManager msm) {
   }
 
   public void processMouseEvent(MouseEvent mevt, MenuElement[] me, MenuSelectionManager msm) {
   }
}

Changing the color of a JSlider component

The JSlider component consists of several subcomponents (ticks, lines, labels, knob, …). Look at the plaf UI source code (eg. javax.swing.plaf.basic.BasicSliderUI) and you’ll notice that several times Color.black is hardcoded. So unless you rewrite a custom UI class for your JSlider, you will only be able to partially control the overall color.

This following example shows you how to set the JSlider fore and background color as well as the fore and background color for the labels.

Main.java:

import javax.swing.plaf.metal.*;
import javax.swing.event.*;
import javax.swing.plaf.*;
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 JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 30, 15);
      // draw the major tick marks (one for every tick label)
      slider.setMajorTickSpacing(10);
      // draw the minor tick marks (between the tick labels)
      slider.setMinorTickSpacing(1);
      // draw the tick marks
      slider.setPaintTicks(true);
      // draw the tick mark labels
      slider.setPaintLabels(true);
 
      slider.setForeground(Color.red);
      slider.setBackground(Color.yellow);
 
      Dictionary dictionary = slider.getLabelTable();
      if (dictionary != null) {
         Enumeration keys = dictionary.keys();
         while (keys.hasMoreElements()) {
            JLabel label = (JLabel) dictionary.get(keys.nextElement());
            label.setForeground(Color.blue);
            // uncomment these following lines to get a background for your labels
            label.setOpaque(true);
            label.setBackground(Color.green); 
         }
      }
 
      getContentPane().add(slider);
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      pack();
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Creating a JFormattedTextField that only accepts telephone numbers

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() throws Exception
   {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      final JFormattedTextField formattedTf =
                   new JFormattedTextField(new MaskFormatter("(###) ###-####"));
 
      final JTextField normalTf = new JTextField(25);
      JButton button = new JButton("Get value");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) { 
            normalTf.setText(""+formattedTf.getValue());
         }
      });
 
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
      getContentPane().add(formattedTf);
      getContentPane().add(button);
      getContentPane().add(normalTf);
 
      formattedTf.setPreferredSize(normalTf.getPreferredSize());
   }
  
   public static void main(String args[]) throws Exception 
   {
      Main main = new Main();
      main.setSize(300, 150);
      main.setVisible(true);
   }
}

Creating an editable JLabel

You can use a CardLayout, assign card 1 a JLabel and assign card 2 a JTextField. Show card 1 and switch to card 2 when it is time to edit. In the following example, the behavior is defined to edit the JLabel whenever the mouse moves 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!");
      final JTextField textfield = new JTextField();
 
      final CardLayout cl = new CardLayout();
      final JPanel panel = new JPanel(cl);
 
      panel.add(label, "label component");
      panel.add(textfield, "textfield component");
 
      getContentPane().add(panel);
  
      label.addMouseListener(new MouseAdapter() {
         public final void mouseEntered(MouseEvent evt) { 
            textfield.setText(label.getText());
            cl.show(panel, "textfield component");
         } 
      });
 
      textfield.addMouseListener(new MouseAdapter() {
         public final void mouseExited(MouseEvent evt) { 
            label.setText(textfield.getText());
            cl.show(panel, "label component");
         } 
      }); 
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(300, 200);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Get started with a JColorChooser

Instantiate a JColorChooser component and add it to a container. To receive an event when the selected color has changed, add a ChangeListener to the selection model of the colorchooser and implement the method stateChanged.

This example shows you how to listen for color change events and modify the background color of a JPanel.

Main.java:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   public Main() {
      super("JColorChooser Demonstration");
 
      getContentPane().setLayout(new GridLayout(1, 2)); 
      final JPanel panel = new JPanel();
      final JColorChooser colorChooser = new JColorChooser();
 
      getContentPane().add(panel);
      getContentPane().add(colorChooser);
 
      colorChooser.getSelectionModel().addChangeListener(
         new ChangeListener() {
            public void stateChanged(ChangeEvent e) {
               Color newColor = colorChooser.getColor();
               panel.setBackground(newColor);
            }
         }    
      );
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      main.pack();
      main.setVisible(true);
   }
}

Setting the selected file in a the filename textfield JFileChooser when it starts up

You just have to create a new File and set it as selectedFile before starting the FileChooser. Depending on what you want to do with the selected file you should check the file with File.canRead(), File.canWrite() or File.exists(). Here is an example:

File file = new File(date + " " + user + ".pdf");
JFileChooser fc = new JFileChooser();
fc.setSelectedFile(file);
int returnValue = fc.showSaveDialog(this);

This must be wrapped in a try-catch-block, because creating a File could throw an exception.

Changing the foreground and background colors of JTable cells

Override the JTable’s cell renderer and set the fore- and background color. This example makes use of such a custom cell renderer. In the example, a cell item is of type ColoredItem that encapsulates an object and a Color.
Main.java:

import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   JTable table;
   MyTableModel tableModel;
 
   public Main() {
      super("Colored JTable Demonstration");
 
      tableModel = new MyTableModel(10, 5);
      table = new JTable(tableModel);
 
      DefaultTableCellRenderer colorRenderer = new DefaultTableCellRenderer() {
         public void setValue(Object value) {
            if (value instanceof ColoredItem) {
               Color fcolor = ((ColoredItem) value).getForeground();
               Color bcolor = ((ColoredItem) value).getBackground();
               this.setForeground(fcolor);
               this.setBackground(bcolor);
               setText(value.toString());
            }
         }
      };
  
      table.setDefaultRenderer(Object.class, colorRenderer);
      table.setDefaultEditor(Object.class, new DefaultCellEditor(new JTextField()));
 
      JScrollPane scrollPane = new JScrollPane(table);

      getContentPane().add(scrollPane, BorderLayout.CENTER);

      JPanel radioPanel = new JPanel(new GridLayout(1, 5));
      JRadioButton redRadio = new JRadioButton("Red");
      JRadioButton greenRadio = new JRadioButton("Green");
      JRadioButton blueRadio = new JRadioButton("Blue");
      JRadioButton yellowRadio = new JRadioButton("Yellow");
      JRadioButton blackRadio = new JRadioButton("Black");

      // Group the radio buttons.
      ButtonGroup group = new ButtonGroup();
      group.add(redRadio);
      group.add(greenRadio);
      group.add(blueRadio);
      group.add(yellowRadio);
      group.add(blackRadio);

      radioPanel.add(redRadio);
      radioPanel.add(greenRadio);
      radioPanel.add(blueRadio);
      radioPanel.add(yellowRadio);
      radioPanel.add(blackRadio);
 
      RadioListener radioListener = new RadioListener();
      redRadio.addActionListener(radioListener);
      greenRadio.addActionListener(radioListener);
      blueRadio.addActionListener(radioListener);
      yellowRadio.addActionListener(radioListener);
      blackRadio.addActionListener(radioListener);
 
      // add radiopanel to container
      JPanel panel = new JPanel(new GridLayout(2, 1));
      panel.add(new JLabel("Select color for selected cell:"));
      panel.add(radioPanel);     
      getContentPane().add(BorderLayout.SOUTH, panel);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
   }
 
   class RadioListener implements ActionListener {
      public void actionPerformed(ActionEvent ae) {
         int row = table.getSelectedRow();
         int column = table.getSelectedColumn();
         ColoredItem ci = (ColoredItem) tableModel.getValueAt(row, column);
 
         if (ae.getActionCommand().equals("Red"))
            ci.setForeground(Color.red);
         else if (ae.getActionCommand().equals("Green"))
            ci.setForeground(Color.green);
         else if (ae.getActionCommand().equals("Blue"))
            ci.setForeground(Color.blue);
         else if (ae.getActionCommand().equals("Yellow"))
            ci.setForeground(Color.yellow);
         else if (ae.getActionCommand().equals("Black"))
            ci.setForeground(Color.black);
 
         // necessary to cause a fireTableCellUpdated event
         tableModel.setValueAt(ci, row, column);
      }
   }
 
   private class ColoredItem {
      private Object object;
      private Color foreground;
      private Color background;
 
      public ColoredItem(Object object, Color foreground, Color background) {
         this.object = object;
         this.foreground = foreground;
         this.background = background;
      }
  
      public void setObject(Object object) {
         this.object = object;
      }
  
      public void setForeground(Color foreground) {
         this.foreground = foreground;
      }
 
      public void setBackground(Color background) {
         this.background = background;
      }
 
      public Object getObject() {
         return object;
      }
 
      public Color getForeground() {
         return foreground;
      }
 
      public Color getBackground() {
         return background;
      }
 
      public String toString() {
         return object.toString(); 
      }
   }
 
   class MyTableModel extends AbstractTableModel {
      String [] columnNames;
      Object [][] data;
 
      MyTableModel(int rows, int columns) {
         columnNames = createColumnElements(columns);
         data = createTableElements(rows, columns);         
      }
 
      public int getColumnCount() {
         return columnNames.length;
      }
        
      public int getRowCount() {
         return data.length;
      }
 
      public String getColumnName(int col) {
         return columnNames[col];
      }
 
      public Object getValueAt(int row, int col) {
         return data[row][col];
      }
 
      public Class getColumnClass(int c) {
         return getValueAt(0, c).getClass();
      }
 
      public void setValueAt(Object value, int row, int col) {
         data[row][col] = value;
         fireTableCellUpdated(row, col);
      }
 
      private String[] createColumnElements(int columns) {
         String[] data;
 
         data = new String[columns];
         for (int i=0; i<columns; i++) {
            data[i] = new String("Column " + i);
         }
 
         return data;
      }
 
      private Object[][] createTableElements(int rows, int columns) {
         ColoredItem [][]data;
         data = new ColoredItem[rows][];
         for (int i=0; i<rows; i++) {
            data[i] = new ColoredItem[columns];
            for (int j=0; j<columns; j++) {
               data[i][j] = new ColoredItem("(" + i + " , " + j + ")", Color.green, Color.white);
            }
         }
 
         return data;
      } 
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.pack();
      main.setVisible(true);
   }
}