Putting a Image on a JButton

Check out the API! You’ll see that there is a constructor taking an Icon object as parameter. Here’s an example showing two buttons with the following animated gifs on 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 FlowLayout());
 
      JButton mbutton = new JButton("female", new ImageIcon("male.gif"));
      JButton fbutton = new JButton("male", new ImageIcon("female.gif"));
      mbutton.addActionListener(this);
      fbutton.addActionListener(this);
      getContentPane().add(mbutton);
      getContentPane().add(fbutton);
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      pack();
   }
 
   public void actionPerformed(ActionEvent ae) {
      System.out.println("Your pressed the " + ae.getActionCommand() + " button");
   }
   
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Removing all the elements of a JList

The quickest way to find an answer to these kind of questions is to look at the API. You can call either removeAllElements or clear on the list model. clear is preferred.

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());
 
      final DefaultListModel listModel = new DefaultListModel();   
 
      // populate listmodel
      for (int i=0; i<5; i++) {
         listModel.addElement("list item #" + i);
      }
 
      final JList list = new JList(listModel); 
 
      getContentPane().add(new JScrollPane(list));    
      JButton removeAllButton = new JButton("Remove all elements");
      removeAllButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
 
            listModel.clear();
 
         }
      });
      getContentPane().add(removeAllButton);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      pack();
   }
   
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Showing a popup-menu when a user right-clicks on an element in a JList

This example creates a JList and shows a popupmenu only when the user clicked on the selected item.
Main.java:

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());
 
      final DefaultListModel listModel = new DefaultListModel();   
 
      // populate listmodel
      for (int i=0; i<5; i++) {
         listModel.addElement("list item #" + i);
      }
 
      final JList list = new JList(listModel); 
      getContentPane().add(new JScrollPane(list));    
 
      final JPopupMenu popupMenu = new JPopupMenu();
      popupMenu.add(new JMenuItem("PopupItem 1"));
      popupMenu.add(new JMenuItem("PopupItem 2"));
      popupMenu.add(new JPopupMenu.Separator());
      popupMenu.add(new JMenuItem("PopupItem 3"));
 
      list.addMouseListener(new MouseAdapter() {
         public void mouseClicked(MouseEvent me) {
            if (SwingUtilities.isRightMouseButton(me)    // if right mouse button clicked
                  && !list.isSelectionEmpty()            // and list selection is not empty
                  && list.locationToIndex(me.getPoint()) // and clicked point is
                     == list.getSelectedIndex()) {       //   inside selected item bounds
               popupMenu.show(list, me.getX(), me.getY());
            }
         }
      });
 
      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 SSNs

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 a JLabel with strike-through text

The easiest way is to use the HTML tag strike.

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><strike>Strike-through text</strike></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();
   }
}

Deleting all rows from a JTable

Here’s what I do:

In your JTable class, add this method:

public synchronized void clearTable()
{
   TableModel model = this.getModel(); 
   int numrows = model.getRowCount(); 
   for(int i = numrows - 1; i >=0; i--)
   {
	model.removeRow(i); 
   }
}

Using a JList component as a cell inside a JTable

JListTableExample.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 JListTableExample extends JFrame {
 
  public JListTableExample() {
    super( "JList inside JTable Example" );
  
    DefaultTableModel dtm = new DefaultTableModel() {
       // make first cell uneditable
       public boolean isCellEditable(int row, int column)
       {
          return !(column == 0);
       }
    };

    final MyListModel dlm1 = new MyListModel(new Object[] { "value1", "value2", "value3",
                                                            "value4", "value5", "value6" });
    final MyListModel dlm2 = new MyListModel(new Object[] { "value7", "value8", "value9",
                                                            "value10", "value11", "value12" });

    dtm.setDataVector(new Object[][]{ { "JList1", dlm1},
                                      { "JList2", dlm2} },
                      new Object[]{ "String","JList"});
                     
    JTable table = new JTable(dtm);
    table.getColumn("JList").setCellRenderer(new JListRenderer());
    table.getColumn("JList").setCellEditor(new JListEditor());
    table.setRowHeight(80);

    JButton addButton = new JButton("Add an element to List1");
    addButton.addActionListener(new ActionListener() {
       public void actionPerformed(ActionEvent ae) {
          dlm1.addElement("new value");
       }
    });

    JScrollPane scroll = new JScrollPane(table);
    getContentPane().setLayout(new BorderLayout(10, 10));
    getContentPane().add(BorderLayout.CENTER, scroll);
    getContentPane().add(BorderLayout.SOUTH, addButton);

    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) { 
        System.out.println(dlm1);
        System.out.println(dlm2);
        System.exit(0);
      }
    });
  }
 
  public static void main(String[] args) {
    JListTableExample frame = new JListTableExample();
 
    frame.setSize(400, 250);
    frame.setVisible(true);
  }
}
  
class JListRenderer extends JScrollPane implements TableCellRenderer
{
   JList list;
 
   public JListRenderer() {
      list = new JList();
      list.setSelectionBackground(Color.red);
      getViewport().add(list);
   }
 
   public Component getTableCellRendererComponent(JTable table, Object value,
                                  boolean isSelected, boolean hasFocus,
                                  int row, int column)
   {
      if (isSelected) {
         setForeground(table.getSelectionForeground());
         setBackground(table.getSelectionBackground());
         list.setForeground(table.getSelectionForeground());
         list.setBackground(table.getSelectionBackground());
      } else {
         setForeground(table.getForeground());
         setBackground(table.getBackground());
         list.setForeground(table.getForeground());
         list.setBackground(table.getBackground());
      }
 
      list.setModel((MyListModel) value) ;
      list.setSelectedIndices(((MyListModel) value).getSelectedIndices());

      return this;
   }
}

class JListEditor extends DefaultCellEditor {
   protected JScrollPane scrollpane;
   protected JList list; 
   protected MyListModel mlm;
 
   public JListEditor() {
      super(new JCheckBox());
      scrollpane = new JScrollPane();
      list = new JList();  
//      list.setSelectionForeground(Color.red);
      list.setSelectionBackground(Color.red);
      scrollpane.getViewport().add(list);
   }
 
   public Component getTableCellEditorComponent(JTable table, Object value,
                                   boolean isSelected, int row, int column) {
      list.setModel((MyListModel) value);

      mlm = (MyListModel) value;

      return scrollpane;
   }
 
   public Object getCellEditorValue() {
      mlm.setSelectedIndices(list.getSelectedIndices());
      return mlm;
   }
}


class MyListModel extends DefaultListModel
{
   private int[] selectedIndices;

   public MyListModel(Object[] data) {
      for (int i=0; i<data.length; i++) {
         addElement(data[i]);
      }
   }

   public void setSelectedIndices(int[] selectedIndices) {
      this.selectedIndices = selectedIndices;
   }

   public int[] getSelectedIndices() {
      if (selectedIndices == null) return new int[]{};
      return selectedIndices;
   }
 
   public String toString() {
      StringBuffer sb = new StringBuffer();
      sb.append(super.toString());
      if (selectedIndices != null) {
         sb.append("nSelected:n");
         for (int i=0; i<selectedIndices.length; i++) {
            sb.append(get(selectedIndices[i]) + "n");
         }
      }
      return sb.toString();
   }
}

Changing the font size of the column headers in a JTable

Main.java:

import javax.swing.table.*;
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);
 
      // set font for headers
      Font f = new Font("Arial", Font.BOLD, 25);
      JTableHeader header = table.getTableHeader();
      header.setFont(f);

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

Displaying a popup menu when right-clicking on a JTree node

Main.java:

import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;
 
public class Main extends JFrame
{
   public Main() {
      DefaultMutableTreeNode root = createNodes();
      JTree tree = new JTree(root);
 
      final TreePopup treePopup = new TreePopup(tree);
      tree.addMouseListener(new MouseAdapter() {
         public void mouseReleased (MouseEvent e) {
            if (e.isPopupTrigger()) {
               treePopup.show(e.getComponent(), e.getX(), e.getY());
            }
         }
      });
  
      getContentPane().add(new JScrollPane(tree));
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static DefaultMutableTreeNode createNodes() {
      DefaultMutableTreeNode root = new DefaultMutableTreeNode("Java");
      
      DefaultMutableTreeNode j2se = new DefaultMutableTreeNode("J2SE");
      DefaultMutableTreeNode j2ee = new DefaultMutableTreeNode("J2EE");
      DefaultMutableTreeNode j2me = new DefaultMutableTreeNode("J2ME");
 
      j2se.add(new DefaultMutableTreeNode("http://java.sun.com/j2se/"));
      j2ee.add(new DefaultMutableTreeNode("http://java.sun.com/j2ee/"));
      j2me.add(new DefaultMutableTreeNode("http://java.sun.com/j2me/"));
 
      root.add(j2se);
      root.add(j2ee);
      root.add(j2me);
 
      return root;
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
}
 
class TreePopup extends JPopupMenu {
   public TreePopup(JTree tree) {
      JMenuItem itemDelete = new JMenuItem("Delete");
      JMenuItem itemAdd = new JMenuItem("Add");
      itemDelete.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.out.println("Delete child");
         }
      });
      itemAdd.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.out.println("Add child");
         }
      });
 
      add(itemDelete);
      add(new JSeparator());
      add(itemAdd);
   }
}