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

Making the cells of a JTable transparent so that background image shows through

Author: Zafir Anjum

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
 
public class Table
{
   public static void main(String[] args) {
      JFrame frame = new JFrame("Table");
      frame.addWindowListener( new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            Window win = e.getWindow();
            win.setVisible(false);
            win.dispose();
            System.exit(0);
         }
      } );	
 
      // Create your own sub-class of JTable rather than using anonymous class
      JTable table = new JTable( 15, 3 ) {
         public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
            Component c = super.prepareRenderer( renderer, row, column);
            // We want renderer component to be transparent
            // so background image is visible
            if( c instanceof JComponent )
               ((JComponent)c).setOpaque(false);
               return c;
            }

            // Hard coded value. In your sub-class add a function for this.
            ImageIcon image = new ImageIcon( "codeguruwm.gif" );

            public void paint( Graphics g ) {
               // First draw the background image - tiled 
               Dimension d = getSize();
               for( int x = 0; x < d.width; x += image.getIconWidth() )
                  for( int y = 0; y < d.height; y += image.getIconHeight() ) 
                     g.drawImage( image.getImage(), x, y, null, null );
               // Now let the regular paint code do it's work
               super.paint(g);
           }
      };
 
      // Set the table transparent
      table.setOpaque(false);
		
      JScrollPane sp = new JScrollPane( table );
      frame.getContentPane().add( sp );	

      frame.pack();
      frame.show();
   }
}

Changing the margins between JTable grid lines and cell data

You can do so with the JTable method setIntercellSpacing.

Main.java:

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);
 
      table.setIntercellSpacing(new Dimension (10,20));
  
      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);
   }
}

Changing the default look and feel for all my swing apps

You could set the Look And Feel by invoking UIManager.setLookAndFeel before any components are created, but that would set the Look And Feel for only that application.

If you want the default Look And Feel to be changed for all applications, create the file swing.properties (if it doesn’t exist) in the javaHomeDirectorylib directory and in which you specify the default l&f:
c:jdk1.2.2jrelibswing.properties:

# Swing properties

swing.defaultlaf=com.sun.java.swing.plaf.motif.MotifLookAndFeel