Specifying a JButton’s icon height and width

Main.java:

import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
 
public class Main {
 
   public static ImageIcon zoom(ImageIcon imI, double width, double height) {
      Image source = imI.getImage();
 
      BufferedImage dest = new BufferedImage(
            (int) (imI.getIconWidth() * width),
            (int) (imI.getIconHeight() * height),
            BufferedImage.TYPE_INT_RGB);
 
      AffineTransform ta = new AffineTransform();
 
      ta.scale(width, height);
 
      Graphics2D g2d = dest.createGraphics();
      g2d.drawImage(source, ta, null);
      g2d.dispose();
 
      return new ImageIcon(dest);
   }
 
   public static void main(String args[]) {
      JFrame f = new JFrame();
      JButton b = new JButton("test", new ImageIcon("button1.jpg"));
      b.setIcon(Main.zoom((ImageIcon) b.getIcon(), 0.5, 0.8));
      f.getContentPane().add(b);
      f.setSize(150, 150);
      f.setVisible(true);
   }
}

Showing a different tooltip for every item in a JComboBox

Modify the behavior of the ListRenderer such that it includes the currently selected JComboBox item in determining the tooltip text. Here’s an example:

import javax.swing.plaf.basic.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
    
public class Main extends JFrame
{ 
   public Main() {
      getContentPane().setLayout(new FlowLayout());
      
      final JComboBox combobox = new JComboBox(new String[] { "Item 1", "Item 2", "Item 3" });
 
      getContentPane().add(combobox);
 
      combobox.setRenderer(new BasicComboBoxRenderer() {
         public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { 
            if (isSelected) { 
               setBackground(list.getSelectionBackground()); 
               setForeground(list.getSelectionForeground()); 
               if (index > -1) {
                  list.setToolTipText("Tooltip #" + new Integer(index).toString()); 
               }
            }
            else { 
               setBackground(list.getBackground()); 
               setForeground(list.getForeground()); 
            } 
            setFont(list.getFont()); 
            setText((value == null) ? "" : value.toString()); 
 
            return this; 
         }
      });
 
      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);
   }
}

Creating a JTextField as an element of JList

This example uses an EditableJList, a custom JList that only allows an EditableJList.EditableListModel as model. Our EditableListModel can only contain JTextComponents (JTextField, JTextArea, …) items.
The behavior is such that when double-clicking on the JList, the selected item is detected using the method locationToIndex and a border is added to it. The border will be removed when the textfield looses focus. To ensure that the JList element is being updated while editing the textfield, every DocumentEvent is captured and fireContentsChanged is called.
Main.java:

import javax.swing.event.*;
import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
  
public class Main extends JFrame {
 
   public Main() {
      getContentPane().setLayout(new BorderLayout());
 
      EditableJList.EditableListModel listModel = new EditableJList.EditableListModel();
 
      // populate listmodel
      Random r = new Random();
      for (int i=0; i<50; i++) {
         String item = "list item # " + (Math.abs(r.nextInt()) % 100);
         JTextField tc = new JTextField(item);
//         JTextArea tc = new JTextArea(item);
//         JEditorPane tc = new JEditorPane("text/html", "<h3>" + item + "</h3>");
         listModel.addElement(tc);
      }
 
      EditableJList list = new EditableJList(listModel); 
      getContentPane().add(BorderLayout.CENTER, new JScrollPane(list));    
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      pack();
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}
 
class EditableJList extends JList {
   public EditableJList(EditableListModel listModel) {
      setModel(listModel);
      addMouseListener();
 
      // set our custom cell renderer
      setCellRenderer(new TextComponentCellRenderer()); 
   }
 
   private void addMouseListener() {  
      MouseListener mouseListener = new MouseAdapter() {
         public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
               EditableListModel listModel = (EditableListModel) getModel();
 
               // determine the clicked item
               int index = locationToIndex(e.getPoint());
               Object value = listModel.getElementAt(index);
               final JTextComponent tc = (JTextComponent) value;
 
               // set the appropriate border for editing 
               String classname = tc.getClass().getName().toString();
               classname = classname.substring(classname.lastIndexOf("."));
               tc.setBorder(UIManager.getBorder(classname + "border"));
 
               // make this border appear in the JList
               listModel.updateItem(index);
 
               tc.addFocusListener(new FocusListener() {
                  public void focusGained(FocusEvent fe) {
                     // no selection color desired when editing a JTextComponent
                     clearSelection();
                  }
 
                  public void focusLost(FocusEvent fe) {
                     // remove the border again when stopped editing
                     tc.setBorder(null);
                  }
               });
 
               // request the focus on this component to be able to edit it
               tc.requestFocus();
 
               // listen to all key events on the JTextComponent and update the 
               // JList item every time.  Without this, you won't see the changes.           
               tc.getDocument().addDocumentListener(new UpdateListDocumentListener(listModel, index));
            }
         }
      };
 
      addMouseListener(mouseListener);
   }
 
   // DocumentListener that takes care of updating a JList item
   // when editing it.  Calls updateItem on our custom EditableListModel
   private class UpdateListDocumentListener implements DocumentListener {
      private EditableListModel elm;
      private int index;
 
      public UpdateListDocumentListener(EditableListModel elm, int index) {
         this.elm = elm;
         this.index = index;
      }
 
      public void insertUpdate(DocumentEvent e) {
         elm.updateItem(index);
      }
 
      public void removeUpdate(DocumentEvent e) {
         elm.updateItem(index);
      }
 
      public void changedUpdate(DocumentEvent e) {
         elm.updateItem(index);
      }
   }
 
   private class TextComponentCellRenderer implements ListCellRenderer {
      public Component getListCellRendererComponent(
         JList list,
         Object value,            // value to display
         int index,               // cell index
         boolean isSelected,      // is the cell selected
         boolean cellHasFocus)    // the list and the cell have the focus
      {
         JTextComponent tc = (JTextComponent) value;
         if (isSelected) {
            tc.setBackground(list.getSelectionBackground());
            tc.setForeground(list.getSelectionForeground());
         }
         else {
            tc.setBackground(list.getBackground());
            tc.setForeground(list.getForeground());
         }
 
         tc.setEnabled(list.isEnabled());
         tc.setFont(list.getFont());
         tc.setBorder(null);
 
         return (Component) value;
      }
   }
 
   public static class EditableListModel extends DefaultListModel {
      public void updateItem(int index) {
         fireContentsChanged(this, index, index);
      }

      public void addElement(JTextComponent tc) {
         super.addElement(tc);
      }
   }
}

Disable the keyboard accellerator that has been assigned to a JMenuItem

Set the accelerator to null. This example assigns accelerators to the JMenuItems ‘male’ and ‘female’. Press CTRL-M and CTRL-F to invoke them. After 5 selections, the accelerators will be disabled.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame implements ActionListener {
   JMenuItem menuItem1;
   JMenuItem menuItem2;
 
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JMenuBar menuBar = new JMenuBar();
      JMenu menu = new JMenu("Sex");
      menuItem1 = new JMenuItem("male");
      menuItem2 = new JMenuItem("female");
 
      // add the MenuItems to the Menu 
      menu.add(menuItem1);
      menu.add(menuItem2);
      menuItem1.setAccelerator(KeyStroke.getKeyStroke('M', Event.CTRL_MASK));
      menuItem2.setAccelerator(KeyStroke.getKeyStroke('F', Event.CTRL_MASK));
 
      // listen for events on these MenuItems
      menuItem1.addActionListener(this);
      menuItem2.addActionListener(this);
 
      menuBar.add(menu);
 
      this.setJMenuBar(menuBar); 
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(400, 400);
   }
 
   private int count = 0;
   public void actionPerformed(ActionEvent ae) {
      System.out.println(ae.getActionCommand());
 
      count++;
      if (count == 5) {
         System.out.println("now disabling accelerators");
 
         menuItem1.setAccelerator(null);
         menuItem2.setAccelerator(null);
      }
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Having different tooltips for each tick on a JSlider

This example shows you how to create your own custom (Metal) UI which overrides some paintLabel methods to save the x, y location of each label. It also overrides the JSlider component to add an extra method setToolTipTextAt that allows you to set a tooltip for a particular label. It overrides the getToolTipText method to determine if the mouse is located on top of one of 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 TTJSlider slider = new TTJSlider(JSlider.HORIZONTAL, 0, 30, 15);
      slider.setToolTipTextAt(0, "zero");
      slider.setToolTipTextAt(10, "ten");
      slider.setToolTipTextAt(20, "twenty");
      slider.setToolTipTextAt(30, "thirty");
 
      // 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.setToolTipText("rest of JSlider tooltip");
 
      getContentPane().add(slider);
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      pack();
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}
 
class TTJSlider extends JSlider
{
   private Hashtable htToolTips = new Hashtable();
   private int lastX = 0;
   private int lastY = 0;
   // for faster access to our own UI
   TTMetalSliderUI ttUI;
 
   public TTJSlider(int orientation, int min, int max, int value) {
      super(orientation, min, max, value);
      addMouseMotionListener(new MouseMotionAdapter() {
         public void mouseMoved(MouseEvent event) {
            if (event != null)  {
               lastX = event.getX();
               lastY = event.getY();
            }
         }
      });
      ttUI = new TTMetalSliderUI();
      setUI(ttUI);
   }
 
   public void setToolTipTextAt(int index, String toolTipText) {
      htToolTips.put(new Integer(index), toolTipText);
   }
 
   public String getToolTipText() {
      int value = ttUI.getLabelForLocation(lastX, lastY);
 
      String toolTipText = (String) htToolTips.get(new Integer(value));
      if (toolTipText == null) 
         return super.getToolTipText();
      else
         return toolTipText;
   }
   
}
 
class TTMetalSliderUI extends MetalSliderUI
{
   // contains label - rectangle pair
   Hashtable labelRects = null;
  
   public void paintLabels(Graphics g) {
      labelRects = new Hashtable();
 
      super.paintLabels(g);
   }
 
   protected void paintHorizontalLabel(Graphics g, int value, Component label) { 
      int labelCenter = xPositionForValue( value );
      int labelLeft = labelCenter - (label.getPreferredSize().width / 2);
 
      Rectangle r = new Rectangle(
         labelLeft, 
         labelRect.y, 
         label.getPreferredSize().width,
         label.getPreferredSize().height);
 
      labelRects.put(r, new Integer(value));
 
      super.paintHorizontalLabel(g, value, label);
   }
 
   protected void paintVerticalLabel(Graphics g, int value, Component label) {
      int labelCenter = yPositionForValue(value);
      int labelTop = labelCenter - (label.getPreferredSize().height / 2);
 
      Rectangle r = new Rectangle(
         labelRect.x, 
         labelTop, 
         label.getPreferredSize().width,
         label.getPreferredSize().height);
 
      labelRects.put(r, new Integer(value));
 
      super.paintVerticalLabel(g, value, label);
   }
  
   public int getLabelForLocation(int x, int y) {
      Enumeration enum = labelRects.keys();
      while (enum.hasMoreElements()) {
         Rectangle r = (Rectangle) enum.nextElement(); 
         if (r.contains(x, y)) return ((Integer) labelRects.get(r)).intValue();
      }
 
      return -1;
   }
}

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

Changing the preview panel in a JColorChooser

Use the method setPreviewPanel to set your custom preview panel. Setting it to new JPanel() will remove the preview panel as a panel by default has no size. This example will create a new JPanel, set the size, and use it as the preview panel.

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 FlowLayout()); 
      final JPanel panel = new JPanel();
      panel.setPreferredSize(new Dimension(100, 30));
      final JColorChooser colorChooser = new JColorChooser();
 
      colorChooser.setPreviewPanel(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);
   }
}

Creating a JTable with fixed columns

You can call the following method:

   table.getTableHeader().setResizingAllowed(false);

However, be aware that this will disable resizing for all columns, and will still resize the columns proportionally when resizing the container in which the JTable is hosted. To fix the size of one column, you have to think about what behavior you want and override the method sizeColumnsToFit().

Main.java:

import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame {
   public Main() {
      super("TableModel Demonstration");
 
      // create our own custom TableModel
      WineTableModel wineModel = new WineTableModel();
      JTable table = new JTable(wineModel);
 
      // add rows to our TableModel, each row is represented as a Wine object
      wineModel.addWine(new Wine("Chateau Meyney, St. Estephe", "1994", 18.75f, true));
      wineModel.addWine(new Wine("Chateau Montrose, St. Estephe", "1975", 54.25f, true));
      wineModel.addWine(new Wine("Chateau Gloria, St. Julien", "1993", 22.99f, false));
      wineModel.addWine(new Wine("Chateau Beychevelle, St. Julien", "1970", 61.63f, false));
      wineModel.addWine(new Wine("Chateau La Tour de Mons, Margeaux", "1975", 57.03f, true));
      wineModel.addWine(new Wine("Chateau Brane-Cantenac, Margeaux", "1978", 49.92f, false));
 
 
      // don't allow resizing columns
      table.getTableHeader().setResizingAllowed(false);
 
 
      // create the scroll pane and add the table to it. 
      JScrollPane scrollPane = new JScrollPane(table);
 
      // add the scroll pane to this window.
      getContentPane().add(scrollPane, BorderLayout.CENTER);
 
      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);
   }
}
 
// a simple object that holds data about a particular wine
class Wine {
   private String  name;
   private String  vintage;
   private float   price;
   private boolean inStock;
 
   public Wine(String name, String vintage, float price, boolean inStock) {
      this.name = name;
      this.vintage = vintage;
      this.price = price;
      this.inStock = inStock;
   }
 
   public String getName()     { return name; }
   public String getVintage()  { return vintage; }
   public float  getPrice()    { return price; } 
   public boolean getInStock() { return inStock; }
 
   public String toString() { 
      return "[" + name + ", " + vintage + ", " + price + ", " + inStock + "]"; }
}
 
class WineTableModel extends AbstractTableModel {
   // holds the strings to be displayed in the column headers of our table
   final String[] columnNames = {"Name", "Vintage", "Price", "In stock?"};
 
   // holds the data types for all our columns
   final Class[] columnClasses = {String.class, String.class, Float.class, Boolean.class};
 
   // holds our data
   final Vector data = new Vector();
  
   // adds a row
   public void addWine(Wine w) {
      data.addElement(w);
      fireTableRowsInserted(data.size()-1, data.size()-1);
   }
 
   public int getColumnCount() {
      return columnNames.length;
   }
         
   public int getRowCount() {
      return data.size();
   }
 
   public String getColumnName(int col) {
      return columnNames[col];
   }
 
   public Class getColumnClass(int c) {
      return columnClasses1;
   }
 
   public Object getValueAt(int row, int col) {
      Wine wine = (Wine) data.elementAt(row);
      if (col == 0)      return wine.getName();
      else if (col == 1) return wine.getVintage();
      else if (col == 2) return new Float(wine.getPrice());
      else if (col == 3) return new Boolean(wine.getInStock());
      else return null;
   }
 
   public boolean isCellEditable(int row, int col) {
      return false;
   }
}