Allowing multiple selections in a JList

A JList has three different selection modes:

1) SINGLE_SELECTION: allows only one item to be selected at a time

2) SINGLE_INTERVAL_SELECTION: allows contiguous items to be selected at a time

3) MULTIPLE_INTERVAL_SELECTION: (default) allows any combination of items to be selected at a time

Following example shows you how to apply them
Main.java:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
  
public class Main extends JFrame implements ActionListener {
   JList list; 
 
   public Main() {
      getContentPane().setLayout(new BorderLayout());
 
      final DefaultListModel listModel = new DefaultListModel();   
 
      // populate listmodel
      for (int i=0; i<10; i++) {
         listModel.addElement("list item #" + i);
      }
 
      list = new JList(listModel); 
      getContentPane().add(BorderLayout.CENTER, new JScrollPane(list));    
 
      JPanel panel = new JPanel(new GridLayout(3, 1));
      JRadioButton rb1 = new JRadioButton("SINGLE_SELECTION");
      rb1.addActionListener(this);
      JRadioButton rb2 = new JRadioButton("SINGLE_INTERVAL_SELECTION");
      rb2.addActionListener(this);
      JRadioButton rb3 = new JRadioButton("MULTIPLE_INTERVAL_SELECTION");
      rb3.addActionListener(this);
      ButtonGroup bg = new ButtonGroup();
      bg.add(rb1);
      bg.add(rb2);
      bg.add(rb3);
      panel.add(rb1);
      panel.add(rb2);
      panel.add(rb3);
      getContentPane().add(BorderLayout.EAST, panel);
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      pack();
   }
 
   public void actionPerformed(ActionEvent ae) {
      if (ae.getActionCommand().equals("SINGLE_SELECTION"))
         list.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      else if (ae.getActionCommand().equals("SINGLE_INTERVAL_SELECTION"))
         list.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
      else if (ae.getActionCommand().equals("MULTIPLE_INTERVAL_SELECTION"))
         list.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
   }
   
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Changing the orientation of a JSlider

You can either specify the orientation when you create your JSlider object or afterwards with the method setOrientation.

Main.java:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame implements ActionListener {
   private JSlider slider;
 
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JMenuBar menuBar = new JMenuBar();
      JMenu menu = new JMenu("JSlider Orientation");
      JMenuItem menuItem1 = new JMenuItem("HORIZONTAL");
      JMenuItem menuItem2 = new JMenuItem("VERTICAL");
      menu.add(menuItem1);
      menu.add(menuItem2);
      menuItem1.addActionListener(this);
      menuItem2.addActionListener(this);
      menuBar.add(menu); 
      setJMenuBar(menuBar);
      
      slider = new JSlider(JSlider.HORIZONTAL, 0, 30, 15);
 
      getContentPane().add(slider);

      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(400, 400);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
 
   public void actionPerformed(ActionEvent ae) {
      if (ae.getActionCommand().equals("HORIZONTAL"))
         slider.setOrientation(JSlider.HORIZONTAL);
      else if (ae.getActionCommand().equals("VERTICAL"))
         slider.setOrientation(JSlider.VERTICAL);
   }
}

Catching the Enter key event on a JTextField

The following example shows a JDialog with one JTextField. When the Enter key is detected, it will perform a doClick on the OK button.

Main.java:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JDialog
{
   public Main() {
      getContentPane().setLayout(new GridLayout(2, 1, 20, 20)); 
      final JTextField inputField = new JTextField();
      getContentPane().add(inputField);
 
      final JButton okButton = new JButton("Ok");
      JButton cancelButton = new JButton("Cancel");
      JPanel panel = new JPanel(new GridLayout(1, 2));
      panel.add(okButton);
      panel.add(cancelButton);
 
      getContentPane().add(panel);     
        
      okButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.out.println("Ok pressed, textfield = " + inputField.getText());
            System.exit(0);
         }
      });
      cancelButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.out.println("Cancel pressed, textfield = " + inputField.getText());
            System.exit(0);
         }
      });
 
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      // catch the enter key in the JTextField and perform an OK click on the JButton
      inputField.addKeyListener(new KeyAdapter() {
         public void keyPressed(KeyEvent e) {
            if (e.getKeyCode()==KeyEvent.VK_ENTER) {
               okButton.doClick();
            }
         }
      });
 
      pack();
      centerDialog();
   }
 
   public void centerDialog() {
      Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
      int x = (int) ((d.getWidth() - getWidth()) / 2);
      int y = (int) ((d.getHeight() - getHeight()) / 2);
      setLocation(x, y);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
   }
}

Creating a JLabel with the text underlined

The easiest way is to use the HTML tag u. If you don’t want to use the HTML feature, check out How do I create an underlined JLabel without using HTML?

Main.java:

import java.awt.event.*;
import java.awt.font.*; 
import javax.swing.*;
import java.util.*;
import java.text.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JLabel label = new JLabel("<html><u>Underlined text with HTML</u></html>");
      getContentPane().add(label);
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(300, 200);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Displaying a menu when right clicking on a cell

Try this:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame 
{
   JTable table;
   TablePopup tablePopup;
 
   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" };
 
      table = new JTable(tabledata, columnheaders);
      table.setPreferredScrollableViewportSize(new Dimension(500, 70));
      JScrollPane scrollPane = new JScrollPane(table); 
      tablePopup = new TablePopup(table);
 
      table.addMouseListener(new MouseAdapter() {
            public void mouseReleased (MouseEvent e) {
                if (e.isPopupTrigger()) {
                   tablePopup.show (e.getComponent(), e.getX(), e.getY());
                }
            }
      });
  
      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();
   }
 
   class TablePopup extends JPopupMenu {
      public TablePopup(JTable table) {
         JMenuItem itemDelete = new JMenuItem("Delete row");
         JMenuItem itemAdd = new JMenuItem("Add row");
         itemDelete.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
               System.out.println("Delete row");
            }
         });
         itemAdd.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
               System.out.println("Add row");
            }
         });
 
         add(itemDelete);
         add(new JSeparator());
         add(itemAdd);
      }
   }
}

Setting the background color of a JTable inside a JScrollPane

Try the following (JDK1.3+):

   scrollPane.getViewport().setBackground(table.getBackground());

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame 
{
   public Main() {
      super(&quot;Table example, Wines from Bordeaux&quot;);
 
      Object[][] tabledata = {
            { &quot;Chateau Meyney, St. Estephe&quot;, 	   new Integer(1994), &quot;$18.75&quot;},
            { &quot;Chateau Montrose, St. Estephe&quot;, 	   new Integer(1975), &quot;$54.25&quot; },
            { &quot;Chateau Gloria, St. Julien&quot;, 	   new Integer(1993), &quot;$22.99&quot; },
            { &quot;Chateau Beychevelle, St. Julien&quot;,   new Integer(1970), &quot;$61.63&quot; },
            { &quot;Chateau La Tour de Mons, Margeaux&quot;, new Integer(1975), &quot;$57.03&quot; },
            { &quot;Chateau Brane-Cantenac, Margeaux&quot;,  new Integer(1978), &quot;$49.92&quot; },
      };
 
      String columnheaders[] = { &quot;Wine&quot;, &quot;Vintage&quot;, &quot;Price&quot; };
 
      JTable table = new JTable(tabledata, columnheaders);
      table.setPreferredScrollableViewportSize(new Dimension(500, 70));
 
      table.setBackground(Color.red);
  
      JScrollPane scrollPane = new JScrollPane(table);
      scrollPane.getViewport().setBackground(table.getBackground());
 
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(BorderLayout.CENTER, scrollPane);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(550, 300);
      main.setVisible(true);
   }
}

Making a JSlider cell editor for my JTable


Note: in JDK1.4, you don’t need to do the setSize() and updateUI in the SliderRenderer.

Main.java:

import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
  
public class JSliderTableExample extends JFrame {
 
  public JSliderTableExample() {
    super( "JSliderTableExample Example" );
 
    DefaultTableModel dtm = new DefaultTableModel();
    dtm.setDataVector(new Object[][]{{ "JSlider1", new Integer(10) },
                                     { "JSlider2", new Integer(12) }},
                      new Object[]{ "String","JSlider"});
                     
    JTable table = new JTable(dtm);
    table.getColumn("JSlider").setCellRenderer(new SliderRenderer(JSlider.HORIZONTAL, 0, 20, 10));
    table.getColumn("JSlider").setCellEditor(new SliderEditor(JSlider.HORIZONTAL, 0, 20, 10));
 
    table.setRowHeight(20);
    JScrollPane scroll = new JScrollPane(table);
    getContentPane().add(scroll);
 
    setSize( 400, 100 );
    setVisible(true);
  }
 
  public static void main(String[] args) {
    JSliderTableExample frame = new JSliderTableExample();
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
  }
}
  
class SliderRenderer extends JSlider implements TableCellRenderer
{
   public SliderRenderer(int orientation, int min, int max, int value) {
      super(orientation, min, max, value);
   }
 
   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());
      }
 
      TableColumnModel columnModel = table.getColumnModel();      
      TableColumn selectedColumn = columnModel.getColumn(column);      
      int columnWidth = selectedColumn.getWidth();
      int columnHeight = table.getRowHeight();
      setSize(new Dimension(columnWidth, columnHeight));
 
      setValue(((Integer)value).intValue());
      updateUI();
      return this;
   }
}
 
class SliderEditor extends DefaultCellEditor {
   protected JSlider slider;
 
   public SliderEditor(int orientation, int min, int max, int value) {
      super(new JCheckBox());
      slider = new JSlider(orientation, min, max, value);      
      slider.setOpaque(true);      
   }
 
   public Component getTableCellEditorComponent(JTable table, Object value,
                                   boolean isSelected, int row, int column) {
      if (isSelected) {
         slider.setForeground(table.getSelectionForeground());
         slider.setBackground(table.getSelectionBackground());
      } else {
         slider.setForeground(table.getForeground());
         slider.setBackground(table.getBackground());
      }
      slider.setValue(((Integer) value).intValue());
 
      return slider;
   }
 
   public Object getCellEditorValue() {
      return new Integer(slider.getValue());
   }
 
   public boolean stopCellEditing() {
      return super.stopCellEditing();
   }
 
   protected void fireEditingStopped() {
      super.fireEditingStopped();
   }
}

Turn off copy/paste in a JTextArea

Main.java:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() {
      JTextArea ta = new JTextArea();
      getContentPane().add(new JScrollPane(ta));
 
      ta.getInputMap().put(KeyStroke.getKeyStroke("control C"), "none");
      ta.getInputMap().put(KeyStroke.getKeyStroke("control V"), "none");
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
}

Embedding a JTextArea and ImageIcon 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"));
      JPanel panel = new JPanel();
      panel.setLayout(new BorderLayout());
      panel.add(BorderLayout.WEST, new JLabel(new ImageIcon("TrafficRed.gif")));
      panel.add(BorderLayout.CENTER, textarea);
      getViewport().add(panel);
   }
 
   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"));
      JPanel panel = new JPanel();
      panel.setLayout(new BorderLayout());
      panel.add(BorderLayout.WEST, new JLabel(new ImageIcon("TrafficRed.gif")));
      panel.add(BorderLayout.CENTER, textarea);
      scrollpane.getViewport().add(panel);
   }
 
   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();
   }
}

Image used: