Refreshing the contents of a JList

JListExample.java:

 
// Created with JBuilder (c) Philip Craiger
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
/**
 * Title:        A JList Programming Example
 * Description:
 * Copyright:    Copyright (c) 2001
 * Company:
 * @author Dr. Philip Craiger
 * @version 1.0
 */
 
public class JListExample extends JFrame {
  private JButton btnMove = new JButton();
  private JButton bthRemove = new JButton();
 
  // Model View Controller: We change contents of the JList through
  // manipulation of a MODEL, not the actual JList.
  
 
  private DefaultListModel model_1 = new DefaultListModel();
  private DefaultListModel model_2 = new DefaultListModel();
 
  private JList jList1 = new JList(model_2);
  private JList jList2 = new JList(model_1);
  
  // JLists do not scroll by default.  We need to add them to
  // an encompassing JScrollPane
  private JScrollPane jScrollPane1 = new JScrollPane();
  private JScrollPane jScrollPane2 = new JScrollPane();
 
  public JListExample() {     // our constructor
    super("A JList Example"); // call to super constructor
    try {
      jbInit();
    }
    catch(Exception e) {
      e.printStackTrace();
    }
  }
 
  public static void main(String[] args) {
    JListExample foo = new JListExample();
    foo.setSize(new Dimension(450,200));
    foo.show();
  }
 
  private void jbInit() throws Exception {
 
  // Note we are adding and removing JList items from the MODEL
  // NOT directly from the JList.  Because JList is associated with the
  // model, the JList contents are updated automatically
 
    model_1.addElement("Java");
    model_1.addElement("Visual Basic");
    model_1.addElement("C++");
    model_1.addElement("C");
    model_1.addElement("Common LISP");
    model_1.addElement("Fortran");
    model_1.addElement("Pascal");
    model_1.addElement("Python");
    this.getContentPane().setLayout(null);
 
    btnMove.setText("Move >>");
    btnMove.setBounds(new Rectangle(150, 35, 98, 36));
    btnMove.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(ActionEvent e) {
        btnMove_actionPerformed(e);
      }
    });
 
    bthRemove.setText("<< Remove");
    bthRemove.setBounds(new Rectangle(152, 87, 97, 36));
    bthRemove.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(ActionEvent e) {
        bthRemove_actionPerformed(e);
      }
    });
 
    jScrollPane1.setBounds(new Rectangle(286, 15, 109, 133));
    jScrollPane2.setBounds(new Rectangle(14, 15, 106, 136));
 
    // Allow user to select a single item from JList
    jList1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    jList2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
 
    this.getContentPane().add(jScrollPane2, null);
    jScrollPane2.getViewport().add(jList2, null); // Must add JList
    this.getContentPane().add(jScrollPane1, null); // to a JScrollPane
    this.getContentPane().add(btnMove, null);
    this.getContentPane().add(bthRemove, null);
    jScrollPane1.getViewport().add(jList1, null); // JList to JScrollPane
    jList2.setSelectedIndex(0);
  }
 
  void btnMove_actionPerformed(ActionEvent e) {
    model_2.addElement(jList2.getSelectedValue());  // change the MODEL
    model_1.removeElement(jList2.getSelectedValue());  // change the MODEL
    jList2.setSelectedIndex(0);       // Highlight first item in JList
  }
 
  void bthRemove_actionPerformed(ActionEvent e) {
    model_1.addElement(jList1.getSelectedValue());  // change the MODEL
    model_2.removeElement(jList1.getSelectedValue()); // change the MODEL
    jList2.setSelectedIndex(0);       // Highlight first item in JList
  }
}

Catching the event when a JMenuItem has been selected

Add an ActionListener object. Here’s an example:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame implements ActionListener {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JMenuBar menuBar = new JMenuBar();
      JMenu menu = new JMenu(&quot;menu&quot;);
      JMenuItem menuItem1 = new JMenuItem(&quot;option 1&quot;);
      JMenuItem menuItem2 = new JMenuItem(&quot;option 2&quot;);
      JMenuItem menuItem3 = new JMenuItem(&quot;option 3&quot;);
      menuItem1.addActionListener(this);
      menuItem2.addActionListener(this);
      menuItem3.addActionListener(this);
      menu.add(menuItem1);
      menu.add(menuItem2);
      menu.add(new JSeparator());
      menu.add(menuItem3);
      menuBar.add(menu);
 
      this.setJMenuBar(menuBar); 
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(400, 400);
   }

   public void actionPerformed(ActionEvent ae) {
      System.out.println(ae.getActionCommand() + &quot; selected!&quot;);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Embedding a JSpinner inside a JTable cell

Main.java:

import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
  
public class JSpinnerTableExample extends JFrame {
 
  public JSpinnerTableExample(){
    super( &amp;amp;quot;JSpinnerTable Example&amp;amp;quot; );
    
    SpinnerNumberModel spinnerModel1 = new SpinnerNumberModel(10.0, -500.0, 500.0, .5);
    SpinnerDateModel spinnerModel2 = new SpinnerDateModel();
 
    DefaultTableModel dtm = new DefaultTableModel();
    dtm.setDataVector(new Object[][]{{ spinnerModel1, &amp;amp;quot;JSpinner1&amp;amp;quot; },
                                     { spinnerModel2, &amp;amp;quot;JSpinner2&amp;amp;quot; }},
                      new Object[]{&amp;amp;quot;JSpinner&amp;amp;quot;,&amp;amp;quot;String&amp;amp;quot;});
                     
    JTable table = new JTable(dtm);
    table.getColumn(&amp;amp;quot;JSpinner&amp;amp;quot;).setCellRenderer(new SpinnerRenderer());
    table.getColumn(&amp;amp;quot;JSpinner&amp;amp;quot;).setCellEditor(new SpinnerEditor());
 
    table.setRowHeight(20);
    JScrollPane scroll = new JScrollPane(table);
    getContentPane().add(scroll);
 
    setSize( 400, 100 );
    setVisible(true);
  }
 
  public static void main(String[] args) {
    JSpinnerTableExample frame = new JSpinnerTableExample();
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
  }
}
 
class SpinnerRenderer extends JSpinner implements TableCellRenderer {
   public SpinnerRenderer() {
      setOpaque(true);
   }
  
   public Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean hasFocus, int row, int column) {
      setModel((SpinnerModel) value);
  
      return this;
   }
}
  
class SpinnerEditor extends AbstractCellEditor implements TableCellEditor {
   protected JSpinner spinner;
  
   public SpinnerEditor() {
      spinner = new JSpinner();
   }
 
   public Component getTableCellEditorComponent(JTable table, Object value,
                    boolean isSelected, int row, int column) {
      spinner.setModel((SpinnerModel) value);
 
      return spinner;
   }
 
   public Object getCellEditorValue() {
      SpinnerModel sm = spinner.getModel();
      return sm;
   }
}

Creating a multi-colored JLabel

A couple of ways to do this. The easiest being that you can use HTML in labels and hence add the font tag inside your text (see example). Another way is to create a custom extended JLabel component that exposes some methods to set the color of individual characters or ranges or characters and create a custom JLabel UI that takes this extra information to render the JLabel correctly.

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() {
      getContentPane().setLayout(new FlowLayout());
 
      JLabel label = new JLabel("<html><font color=blue>Colored</font> <font color=yellow>label</font></html>");
 
      getContentPane().add(label);     
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(300, 100);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Setting the JProgressBar colors

You can set the progress rectangle color and remaining area color with setForeground and setBackground.
To set the color of the string drawn inside the progress bar, you have two choices (there is no trivial API method to set these colors, look at bug http://developer.java.sun.com/developer/bugParade/bugs/4226498.html.

  • Set the UIManager property values ProgressBar.selectionForeground and ProgressBar.selectionBackground before creating the JProgressBar. Beware that all your JProgressBar components will take on this color.
  • Extend the JProgressBar UI class to provide a method setSelectionForeground and setSelectionBackground

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame {
   public Main() {
      super("JProgressBar Color Demonstration");
 
      // sets the color of the string painted inside the progressbar
      // selectionForeground is the color of the string that appears
      //    in the rectangle that shows the progress
      // selectionBackground is the color of the string that appears
      //    in the rectangle that shows the remaining area
      UIManager.put("ProgressBar.selectionForeground", Color.red);
      UIManager.put("ProgressBar.selectionBackground", Color.green);
 
      JProgressBar pb = new JProgressBar(0, 100);
      pb.setValue(50); 
      pb.setStringPainted(true);
 
      // sets the foreground color, but only the 
      // rectangle that shows the progress, not the text  
      pb.setForeground(Color.green);
 
      // sets the background color, the rectangle that  
      // shows the remaining area
      pb.setBackground(Color.red);
 
      // add the scroll pane to this window.
      getContentPane().add(pb);
 
      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);
   }
}

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 color of entire rows of a JTable

Write your own cell renderer. This example colors all rows green where the price of
the wine is < 55, red otherwise.

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);
 
      // since we’re using values of floats and boolean here, we need
      // to set the cell renderer for every column. 
      for (int i =0; i<wineModel.getColumnCount();i++) {
         table.setDefaultRenderer(table.getColumnClass(i), new WineCellRenderer());
      }
       
      // 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));
 
      // 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 Object getValueAtRow(int row) {
      Wine wine = (Wine) data.elementAt(row);
      return wine;
   }
 
   public boolean isCellEditable(int row, int col) {
      return false;
   }
}
 
class WineCellRenderer extends DefaultTableCellRenderer {
   public Component getTableCellRendererComponent(
            JTable table, Object value, boolean isSelected,
            boolean hasFocus, int row, int column)
   {
      WineTableModel wtm = (WineTableModel) table.getModel();
      Wine wine = (Wine) wtm.getValueAtRow(row);
 
      if (wine.getPrice() < 55) {
         setBackground(Color.green);
      }
      else {
         setBackground(Color.red);
      }
 
      return super.getTableCellRendererComponent(table, value, isSelected, 
                                                 hasFocus, row, column);
   }
}

Adding a background image to a JTree that does not scroll

(1.3+)

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 = new DefaultMutableTreeNode("Root");
      for (int i=0; i<100; i++) {
         DefaultMutableTreeNode child = new DefaultMutableTreeNode("Child " + (i+1));
         root.add(child);
      }
      JTree tree = new JTree(root);
 
      tree.setOpaque( false );
  
 
      DefaultTreeCellRenderer cr = new DefaultTreeCellRenderer();
      cr.setOpaque(false);
      cr.setBackground(new Color(0, 0, 0, 0));  
      cr.setBackgroundNonSelectionColor(null);
      tree.setCellRenderer(cr);
 
      ImageJScrollPane scrollpane = new ImageJScrollPane(tree);
      scrollpane.setBackgroundImage(new ImageIcon("mong.jpg"));
 
      getContentPane().add(scrollpane);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
}
 
class ImageJScrollPane extends JScrollPane
{
   private ImageIcon image = null;
 
   public ImageJScrollPane() {
      this(null, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_AS_NEEDED);
   }
 
   public ImageJScrollPane(Component view) {
      this(view, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_AS_NEEDED);
   }
 
   public ImageJScrollPane(Component view, int vsbPolicy, int hsbPolicy) {
      super(view, vsbPolicy, hsbPolicy);
      if (view instanceof JComponent) {
         ((JComponent) view).setOpaque(false);
      }
      setOpaque(false);
      getViewport().setOpaque(false);
      getViewport().setScrollMode(JViewport.BLIT_SCROLL_MODE);
   }
 
   public ImageJScrollPane(int vsbPolicy, int hsbPolicy) {
      this(null, vsbPolicy, hsbPolicy);
   }
 
   public void setBackgroundImage(ImageIcon image) {
      this.image = image;
   }
 
   public void paint(Graphics g) {
      if (image != null) {
         Rectangle rect = getViewport().getViewRect();
         for (int x=0; x<rect.width; x+=image.getIconWidth()) {
            for (int y=0; y<rect.height; y+=image.getIconHeight()) {
               g.drawImage(image.getImage(), x, y, null, null);
            }
         }
         super.paint(g);
      }
 
   }
}

Image used:

Right-aligning a JTable column

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));
 
      // right align 2nd column
      TableColumnModel columnModel = table.getColumnModel();
      TableColumn column = columnModel.getColumn(1);  
      DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
      renderer.setHorizontalAlignment(JLabel.RIGHT);
      column.setCellRenderer(renderer);
 
      // right align 2nd column when editing
      JTextField tf = new JTextField();
      tf.setHorizontalAlignment(JTextField.RIGHT);
      column.setCellEditor(new DefaultCellEditor(tf));
 
      JScrollPane scrollPane = new JScrollPane(table);
      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();
   }
}