Centring Strings in a JTable

I am stuck with which method to call to have the strings displayed in a simple JTable centred, they are currently left-aligned.
Any help would be much appreciated

Hi,
for that u have to use your own class that implements TableCellRenderer and extends JLabel
In the function
( this function needs to be there mandatory )
public Component getTableCellRendererComponent( JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column)
setHorizontalAlignment(SwingConstants.CENTER);
Hope this helps
Cheers :)
Nagaraj

Similar Messages

  • How to get String form java JTable row?

    Hello everybody,
    Can anybody tell me how to get value as String form java JTable row?

    I found solution:
            table.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent evt) {
                    if (evt.getClickCount() == 2){
                        int col = table.getSelectedColumn();
                        int row = table.getSelectedRow();
                        String tableUrl = ((String)table.getModel().getValueAt(row, col));
                        ur.openUrl(tableUrl);
            });

  • JTable -showing column headers and displaying multi-line strings

    Hi,
    This is two questions really.
    #1 - Does anyone know why my column headers aren't showing in my jtable using the model below?
    #2 - Does anyone know how I can display, mulitple line strings in a jtable? Currently my newline character ('\n') is just being displayed as a character.
    any help very much appreciated,
    Tom
    private class TaskHistoryTableModel extends AbstractTableModel {
    private List taskHistory = new ArrayList();
    public Object getValueAt(int row, int col) {
    if (col == 0) {
    return ((TaskHistoryItem) taskHistory.get(row)).getText();
    } else {
    return ((TaskHistoryItem) taskHistory.get(row)).getDate().getTime();
    public int getRowCount() {
    return taskHistory == null ? 0 : taskHistory.size();
    public int getColumnCount() {
    return 2;
    /** Getter for property taskHistory.
    * @return Value of property taskHistory.
    public List getTaskHistory() {
    return taskHistory;
    /** Setter for property taskHistory.
    * @param taskHistory New value of property taskHistory.
    public void setTaskHistory(List taskHistory) {
    this.taskHistory = taskHistory;
    public String getColumnName (int col) {
    return col == 0 ? "Text" : "Entered At";
    public boolean isCellEditable(int row, int col) {
    return false;
    }

    fixed my own problem - make your mulit-line string into html format e.g.
    this string will appear on two lines in a jtable
    "<html><p>A much more interesting entry</p> <p>on multiple lines</p></html>"

  • Retrieving values entered in a JTable

    Hi!
    I have made a sudoku solver as many others, but in the purpose of learning recursion, and now I am implementing GUI to that program. I have bean strugling to set up a table that shows the sudokutable, and most of all how to recieve the values entered into the table. I have looked at forums and search at google, but all the topics on this is not good enough. I just simply do not understand what they mean. Most often they just say: "Just paste this code in and it will turn out as intended". I want to know how it works.
    I have added the code below:
    import javax.swing.*;
    import javax.imageio.*;
    import java.awt.*;
    import java.awt.event.*;
    import easyIO.*;
    import java.util.*;
    import java.io.*;
    * Klassen Oblig3 som inneholder main metoden som starter programmet.
    * Dette er Utsynen for programmet.
    * @Param ru - Peker til klassen Rute.
    * @Param br - Peker til klassen Brett.
    * @Param skrivebord - En ny desktpoPane som representerer hovedvinduet..
    public class Oblig3 extends JFrame implements ActionListener {
         Rute  ru   = new Rute();
         Brett br   = new Brett(ru);
         ImageIcon icon;
         Image image;
         JDesktopPane skrivebord;
          * Konstrukt�ren Oblig3 som setter opp hovedvinduet.
          * @Param skjemrStorelse - Lagrer st�relsen p� skjermen.
         public Oblig3() {
              super("Oblig3");
              int innrykk = 400;
              Dimension skjermStorelse = Toolkit.getDefaultToolkit().getScreenSize();
              setBounds(innrykk, innrykk, skjermStorelse.width  - innrykk*3, skjermStorelse.height - innrykk*2);
              skrivebord = new JDesktopPane()
                   Image im = (new ImageIcon("bilder/panzer.gif")).getImage();
                   public void paintComponent(Graphics g){
                        g.drawImage(im,0,0,this);
              setContentPane(skrivebord);
              setJMenuBar(lagMenyList());
              skrivebord.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
         } // Slutt p� konstrukt�ren Oblig3
         * JMenuBar metoden som gir menyen til hovedvinduet.
         * @Param menyList - Peker p� et MenuBar objekt.
         * @Param meny# - Menyene p� menylisten.
         * @Param menyObjekt - Et valg p� gitt meny.
         protected JMenuBar lagMenyList() {
              JMenuBar menyList = new JMenuBar();
              // F�rste menyen
              JMenu meny1 = new JMenu("Fil");
              meny1.setMnemonic(KeyEvent.VK_F);
              menyList.add(meny1);
                   // Gruppe1 med JMenuObjekt
                   JMenuItem menyObjekt = new JMenuItem("�pne brett", new ImageIcon("bilder/folder.gif"));
                   menyObjekt.setMnemonic(KeyEvent.VK_O);
                   menyObjekt.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
                   menyObjekt.setActionCommand("�pne brett");
                   menyObjekt.addActionListener(this);
                   meny1.add(menyObjekt);
                   menyObjekt = new JMenuItem("Spare brett", new ImageIcon("bilder/floppy.gif"));
                   menyObjekt.setMnemonic(KeyEvent.VK_S);
                   menyObjekt.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
                   menyObjekt.setActionCommand("Spare brett");
                   menyObjekt.addActionListener(this);
                   meny1.add(menyObjekt);
                   meny1.addSeparator();
                   menyObjekt = new JMenuItem("Exit");
                   menyObjekt.setMnemonic(KeyEvent.VK_ESCAPE);
                   menyObjekt.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, ActionEvent.CTRL_MASK));
                   menyObjekt.setActionCommand("Exit");
                   menyObjekt.addActionListener(this);
                   meny1.add(menyObjekt);
              // Lage den andre menyen
              JMenu meny2 = new JMenu("Edit");
              meny1.setMnemonic(KeyEvent.VK_E);
              menyList.add(meny2);
                   // Gruppe2 med JMenObjekt
                   menyObjekt = new JMenuItem("L�s Brett");
                   menyObjekt.setMnemonic(KeyEvent.VK_L);
                   menyObjekt.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
                   menyObjekt.setActionCommand("L�s Brett");
                   menyObjekt.addActionListener(this);
                   meny2.add(menyObjekt);
                   menyObjekt = new JMenuItem("Lag eget brett");
                   menyObjekt.setMnemonic(KeyEvent.VK_L);
                   menyObjekt.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.ALT_MASK));
                   menyObjekt.setActionCommand("Lag eget brett");
                   menyObjekt.addActionListener(this);
                   meny2.add(menyObjekt);
              // Lage den tredje menyen
              JMenu meny3 = new JMenu("Hjelp");
              meny1.setMnemonic(KeyEvent.VK_H);
              menyList.add(meny3);
                   // Gruppe3 med JMenObjekt
                   menyObjekt = new JMenuItem("Version?");
                   menyObjekt.setActionCommand("Version?");
                   menyObjekt.addActionListener(this);
                   meny3.add(menyObjekt);
                   menyObjekt = new JMenuItem("www.dresas.com");
                   menyObjekt.setActionCommand("www.dresas.com?");
                   menyObjekt.addActionListener(this);
                   meny3.add(menyObjekt);
              return menyList;
         } // Slutt p� JMenuBar metoden.
         * Metode som lytter p� menyval mm.
         public void actionPerformed(ActionEvent e) {
              if(e.getActionCommand().equals("�pne brett")) {
                   lesFraFil();
              } else if (e.getActionCommand().equals("L�s Brett")) {
                   losning();
              } else if (e.getActionCommand().equals("Exit")) {
                   System.exit(0);
              } else if (e.getActionCommand().equals("Version?")) {
                   version();
              } else if (e.getActionCommand().equals("www.dresas.com")) {
                   link();
              } else if (e.getActionCommand().equals("Lag eget brett")) {
                   lagEgetBrett();
              } // Slutt p� if-else-if setning.
         * Metoden lesFraFil som ber om navn p� fil fra bruker
         * via grensesnittet.
         protected void lesFraFil() {
              final String losFraFil = JOptionPane.showInputDialog(null, "Skriv inn navn p� filen.");
              svarLesFraFil(losFraFil + ".txt");
         } // Slutt p� metoden losFraFil
         * Metoden svarLesFaFil som gir resultat p� inlesning fra fil.
         protected void svarLesFraFil(String filnavn) {
              boolean rF = br.lesBrettFraFil(filnavn);
              if(rF == true) {
                    JOptionPane.showMessageDialog(this, "Filen er lest inn");
              } else {
                    JOptionPane.showMessageDialog(this, "Filen ble ikke lest inn,\n (husk sm� og store bokstaver)");
              } // Slutt p� if-else
         } // Slutt p� metoden svarLosFraFil
         * Metoden losning som gir resultat p� l�st brett.
         protected void losning() {
              ru.provAlleSifferMegOgResten(0);
              br.skrivLosning();
         } // Slutt p� metoden losning
         protected void version() {
              JOptionPane.showMessageDialog(null, "Dette er version 0.7");
         protected void link() {
              OpenBrowser op = new OpenBrowser();
              op.displayURL("www.dresas.com");
         } // Slutt p� metoden link
         * Metoden lagEgetBrett som lar brukeren tegne sitt eget
         * brett og l�se det.
         * @Param ramme - Peker p� objektet av klassen InternRamme som
         *                setter opp det interne vinduet.
         protected void lagEgetBrett() {
              int boksBredde = 3;
              int boksHojde  = 3;
              int brettStorelse = 9;
              boolean b1 = true;
              while (b1) {
                   boksBredde = Integer.parseInt(JOptionPane.showInputDialog(null, "Skriv inn Bredde p� boksen. (2-4)"));
                   if (boksBredde > 1 && boksBredde < 5) {
                        boksHojde  = Integer.parseInt(JOptionPane.showInputDialog(null, "Skriv inn H�jde p� boksen. (3-4)"));
                        if (boksHojde > 2 && boksHojde < 5) {
                             b1 = false;
                        } else {
                             JOptionPane.showMessageDialog(null, "M� vaere mellom 3 og 4.");
                             continue;
                   } else {
                        JOptionPane.showMessageDialog(null, "M� vaere mellom 2 og 4.");
                        continue;
              brettStorelse = boksBredde * boksHojde;
              InternRamme ramme = new InternRamme(brettStorelse * 16, brettStorelse * 16);
                   Object[][] data = new Object[brettStorelse][brettStorelse];
                   for (int i = 0;i < brettStorelse;i++) {
                        for (int j = 0; j < brettStorelse;j++) {
                             data[i][j] = 0;
                   String[] columnNames = new String[brettStorelse];
                   for (int i = 0; i < brettStorelse;i++) {
                        int b = 1 + i;
                        columnNames[i] = String.valueOf(b);
                   JTable sudokuTabell = new JTable(data, columnNames);
                   sudokuTabell.setGridColor (new Color (tilfeldig(256), tilfeldig(256), tilfeldig(256)));
                   sudokuTabell.setFont(new Font ("Tahoma", Font.PLAIN, 16));
                   setVisible(true);
              ramme.add(sudokuTabell);
              ramme.setVisible(true);
              skrivebord.add(ramme);
              try {
                   ramme.setSelected(true);
              } catch (java.beans.PropertyVetoException e) {}
         } // Slutt p� klassen lagEgetBrett
         * Metode som returnerer tilfeldigt verdi st�rre en 0 og mindre
         * en maks.
         public static int tilfeldig (int maks) {
              return (int) (Math.random () * maks);
        * Metoden utsyn som tegner opp programmet p� skjermen.
        * @Param frame - Peker p� objektet Oblig3.
        private static void utsyn() {
            //Create and set up the window.
            Oblig3 frame = new Oblig3();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Display the window.
            frame.setVisible(true);
        } // Slutt p� metoden utsyn.
        * Metoden main som starter programmet.
        public static void main(String[] args) {
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    utsyn();
         } //  Slutt p� metoden main.
    } // Slutt p� klassen Oblig3.
    * Brukt av Oblig3
    class InternRamme extends JInternalFrame {
         static int tellOpneRammer = 0;
         static final int xOffset = 30, yOffset = 30;
         InternRamme(int bredde, int hojde) {
              super("Lag eget Brett #" + (++tellOpneRammer),
                     true, //resizable
                     true, //closable
                     true, //maximizable
                     true);//iconifiable
              //...Create the GUI and put it in the window...
              //...Then set the window size or call pack...
              setSize(bredde,hojde);
              //Set the window's location.
              setLocation(xOffset*tellOpneRammer, yOffset*tellOpneRammer);
    }

    Here is the method in mind, translated...
    protected void ConstructOwnBoard() {
         int boxWidth = 3;
         int boxHeight = 3;
         int BoardSize = 9;
         boolean b1 = true;
         while (b1) {
              boxWidth = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter Width. (2-4)"));
              if (boxWidth > 1 && boxWidth < 5) {
                   boxHeight = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter Height. (3-4)"));
                   if (boxHeight > 2 && boxHeight < 5) {
                        b1 = false;
                   } else {
                        JOptionPane.showMessageDialog(null, "Must be btween 3 og 4.");
                        continue;
              } else {
                   JOptionPane.showMessageDialog(null, "Must be between 2 og 4.");
                   continue;
         BoardSize = boxWidth * boxHeight ;
         InternalFrame frame = new InternalFrame(BoardSize * 16, BoardSize * 16);
         Object[][] data = new Object[BoardSize ][BoardSize ];
         for (int i = 0;i < BoardSize ;i++) {
              for (int j = 0; j < BoardSize ;j++) {
                   data[i][j] = 0;
         String[] columnNames = new String[BoardSize ];
         for (int i = 0; i < BoardSize ;i++) {
              int b = 1 + i;
              columnNames[i] = String.valueOf(b);
         JTable sudokuTable = new JTable(data, columnNames);
         sudokuTable.setGridColor (new Color (tilfeldig(256), tilfeldig(256), tilfeldig(256)));
         sudokuTable.setFont(new Font ("Tahoma", Font.PLAIN, 24));
         TableColumn column = null;
         for (int i = 0; i < BoardSize ; i++) {
              column = sudokuTable.getColumnModel().getColumn(i);
              column.setMinWidth(25);
              column.setMaxWidth(25);
              column.setResizable(false);
         setVisible(true);
         frame.add(sudokuTable);
         frame.setVisible(true);
         desktop.add(ramme);
         try {
              frame.setSelected(true);
         } catch (java.beans.PropertyVetoException e) {}
    } // end of class

  • Print a JTable with several Header and Footers

    Hi everybody,
    my name is Lothar and I come from Germany. My english is not very well, but I hope you understand me an my problem.
    I want to print a JTable, but I want to print a header with several headers and footers.
    For example:
    h3. Header
    h5. 1. Subtitle
    h5. 2. Subtitle
    Table
    h5. 3. Subtitle
    h5. Footer
    But, I do not know how I can do that. Can anybody tell me, how I can solve my problem. Please, explain for a newbie because I have learned Java since two months ;)
    Here the code:
    import java.awt.*;
    import java.awt.event.*;
    import java.text.*;
    import java.util.Date;
    import javax.swing.*;
    public class Beispiel extends JFrame implements ActionListener {
        private JTable table;
        public static void main(String[] args) {
            Beispiel tl = new Beispiel();
            tl.setVisible(true);
            tl.pack();
        public Beispiel() {
            setLayout(new BorderLayout());
            // DruckButton
            JButton print = new JButton("Print");
            add(print, BorderLayout.SOUTH);
            print.addActionListener(this);
            // Tabelle
            add(new JScrollPane(createTable()), BorderLayout.CENTER);
            // schlie&szlig;t das Frame
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public JTable createTable() {
            // titel
            String[] title = new String[] { "Datum", "Von", "Bis",
                    "Dauerinsgesamt", "Bemerkung" };
            // daten
            String[][] data = new String[][] { { "", "", "", "", "" },
            table = new JTable(data, title);
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            return table;
        public void actionPerformed(ActionEvent e1) {
            MessageFormat header = new MessageFormat("Header");
            MessageFormat footer = new MessageFormat("Footer");
            try {
                table.print(JTable.PrintMode.FIT_WIDTH, header, footer);
            } catch (Exception e2) {
                System.err.format("Cannot print %s%n", e2.getMessage());
    }

    Nobody?
    Can nobody solve my problem?

  • How to outline selected cells during drag and drop in the jtable

    Hi,
    I have spent a lot of time to find out how to outline selected cells during drag in the jtable, but I did not find the answer.
    Can anybody give me a tip, where to read more about this problem or even better, give an example...
    I have the following situation:
    1.Table has 10 rows and 10 columns
    2.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION) and setCellSelectionEnabled(true)
    3.user select 5 cells in 4th row (for example cell45,cell46,cell47,cell48 and cell49)
    4.user starts dragging. During dragging an outline should be drawn. Outline should be a rectangular with width of 5 cells and height of one cell. Outline should move according to the mouse position.
    5.rectangular disappears when dropped
    Regards,
    Primoz

    In "createTransferable" you can create a drag image
    which you can paint in "dragOver" and clear in "drop" method of DropTarget :
    package dnd;
    * DragDropJTableCellContents.java
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.datatransfer.*;
    import java.awt.dnd.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    public class DragDropJTableCellContents extends JFrame {
        public DragDropJTableCellContents() {
            setTitle("Drag and Drop JTable");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            getContentPane().add(createTable("JTable"), BorderLayout.CENTER);
            setSize(400, 300);
            setLocationRelativeTo(null);
        private JPanel createTable(String tableId) {
            DefaultTableModel model = new DefaultTableModel();
            for (int i = 0; i < 10; i++) {
                model.addColumn("Column "+i);
            for (int i = 0; i < 10; i++) {
                String[] rowData = new String[10];
                for (int j = 0; j < 10; j++) {
                    rowData[j] = tableId + " " + i + j;
                model.addRow(rowData);
            JTable table = new JTable(model);
            table.getTableHeader().setReorderingAllowed(false);
            table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
            table.setCellSelectionEnabled(true);
            JScrollPane scrollPane = new JScrollPane(table);
            table.setDragEnabled(true);
            TableTransferHandler th = new TableTransferHandler();
            table.setTransferHandler(th);
            table.setDropTarget(new TableDropTarget(th));
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            JPanel panel = new JPanel(new BorderLayout());
            panel.add(scrollPane);
            panel.setBorder(BorderFactory.createTitledBorder(tableId));
            return panel;
        public static void main(String[] args) {
            new DragDropJTableCellContents().setVisible(true);
        abstract class StringTransferHandler extends TransferHandler {
            public int dropAction;
            protected abstract String exportString(JComponent c);
            protected abstract void importString(JComponent c, String str);
            @Override
            protected Transferable createTransferable(JComponent c) {
                return new StringSelection(exportString(c));
            @Override
            public int getSourceActions(JComponent c) {
                return COPY;
            @Override
            public boolean importData(JComponent c, Transferable t) {
                if (canImport(c, t.getTransferDataFlavors())) {
                    try {
                        String str = (String) t.getTransferData(DataFlavor.stringFlavor);
                        importString(c, str);
                        return true;
                    } catch (UnsupportedFlavorException ufe) {
                    } catch (IOException ioe) {
                return false;
            @Override
            public boolean canImport(JComponent c, DataFlavor[] flavors) {
                for (int ndx = 0; ndx < flavors.length; ndx++) {
                    if (DataFlavor.stringFlavor.equals(flavors[ndx])) {
                        return true;
                return false;
        class TableTransferHandler extends StringTransferHandler {
            private int dragRow;
            private int[] dragColumns;
            private BufferedImage[] image;
            private int row;
            private int[] columns;
            public JTable target;
            @Override
            protected Transferable createTransferable(JComponent c) {
                JTable table = (JTable) c;
                dragRow = table.getSelectedRow();
                dragColumns = table.getSelectedColumns();
                createDragImage(table);
                return new StringSelection(exportString(c));
            protected String exportString(JComponent c) {
                JTable table = (JTable) c;
                row = table.getSelectedRow();
                columns = table.getSelectedColumns();
                StringBuffer buff = new StringBuffer();
                for (int j = 0; j < columns.length; j++) {
                    Object val = table.getValueAt(row, columns[j]);
                    buff.append(val == null ? "" : val.toString());
                    if (j != columns.length - 1) {
                        buff.append(",");
                return buff.toString();
            protected void importString(JComponent c, String str) {
                target = (JTable) c;
                DefaultTableModel model = (DefaultTableModel) target.getModel();
                String[] values = str.split("\n");
                int colCount = target.getSelectedColumn();
                int max = target.getColumnCount();
                for (int ndx = 0; ndx < values.length; ndx++) {
                    String[] data = values[ndx].split(",");
                    for (int i = 0; i < data.length; i++) {
                        String string = data;
    if(colCount < max){
    model.setValueAt(string, target.getSelectedRow(), colCount);
    colCount++;
    public BufferedImage[] getDragImage() {
    return image;
    private void createDragImage(JTable table) {
    if (dragColumns != null) {
    try {
    image = new BufferedImage[dragColumns.length];
    for (int i = 0; i < dragColumns.length; i++) {
    Rectangle cellBounds = table.getCellRect(dragRow, i, true);
    TableCellRenderer r = table.getCellRenderer(dragRow, i);
    DefaultTableModel m = (DefaultTableModel) table.getModel();
    JComponent lbl = (JComponent) r.getTableCellRendererComponent(table,
    table.getValueAt(dragRow, dragColumns[i]), false, false, dragRow, i);
    lbl.setBounds(cellBounds);
    BufferedImage img = new BufferedImage(lbl.getWidth(), lbl.getHeight(),
    BufferedImage.TYPE_INT_ARGB_PRE);
    Graphics2D graphics = img.createGraphics();
    graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f));
    lbl.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
    lbl.paint(graphics);
    graphics.dispose();
    image[i] = img;
    } catch (RuntimeException re) {
    class TableDropTarget extends DropTarget {
    private Insets autoscrollInsets = new Insets(20, 20, 20, 20);
    private Rectangle rect2D = new Rectangle();
    private TableTransferHandler handler;
    public TableDropTarget(TableTransferHandler h) {
    super();
    this.handler = h;
    @Override
    public void dragOver(DropTargetDragEvent dtde) {
    handler.dropAction = dtde.getDropAction();
    JTable table = (JTable) dtde.getDropTargetContext().getComponent();
    Point location = dtde.getLocation();
    int row = table.rowAtPoint(location);
    int column = table.columnAtPoint(location);
    table.changeSelection(row, column, false, false);
    paintImage(table, location);
    autoscroll(table, location);
    super.dragOver(dtde);
    public void dragExit(DropTargetDragEvent dtde) {
    clearImage((JTable) dtde.getDropTargetContext().getComponent());
    super.dragExit(dtde);
    @Override
    public void drop(DropTargetDropEvent dtde) {
    Transferable data = dtde.getTransferable();
    JTable table = (JTable) dtde.getDropTargetContext().getComponent();
    clearImage(table);
    handler.importData(table, data);
    super.drop(dtde);
    private final void paintImage(JTable table, Point location) {
    Point pt = new Point(location);
    BufferedImage[] image = handler.getDragImage();
    if (image != null) {
    table.paintImmediately(rect2D.getBounds());
    rect2D.setLocation(pt.x - 15, pt.y - 15);
    int wRect2D = 0;
    int hRect2D = 0;
    for (int i = 0; i < image.length; i++) {
    table.getGraphics().drawImage(image[i], pt.x - 15, pt.y - 15, table);
    pt.x += image[i].getWidth();
    if (hRect2D < image[i].getHeight()) {
    hRect2D = image[i].getHeight();
    wRect2D += image[i].getWidth();
    rect2D.setSize(wRect2D, hRect2D);
    private final void clearImage(JTable table) {
    table.paintImmediately(rect2D.getBounds());
    private Insets getAutoscrollInsets() {
    return autoscrollInsets;
    private void autoscroll(JTable table, Point cursorLocation) {
    Insets insets = getAutoscrollInsets();
    Rectangle outer = table.getVisibleRect();
    Rectangle inner = new Rectangle(outer.x + insets.left,
    outer.y + insets.top,
    outer.width - (insets.left + insets.right),
    outer.height - (insets.top + insets.bottom));
    if (!inner.contains(cursorLocation)) {
    Rectangle scrollRect = new Rectangle(cursorLocation.x - insets.left,
    cursorLocation.y - insets.top,
    insets.left + insets.right,
    insets.top + insets.bottom);
    table.scrollRectToVisible(scrollRect);
    Edited by: Andre_Uhres on Nov 18, 2007 10:03 PM

  • Print JTable with Multiple pages and rows

    I took the printing example at http://java.sun.com/developer/onlineTraining/Programming/JDCBook/advprint.html#pe and modified it a bit to include the following:
    1) To Print Multiple pages
    2) To wrap lines that is too long for the column
    3) To print with a more proffesional style, so that it doesn't look like a screen capture is printed
    4) To align the numbers to the right and center column headings
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.print.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.Dimension;
    import javax.print.*;
    import javax.print.attribute.*;
    import javax.print.attribute.standard.*;
    import java.text.*;
    public class Report implements Printable
         private final int LEFT_ALIGN = -1;
         private final int CENTER_ALIGN = 0;
         private final int RIGHT_ALIGN = 1;
         private JFrame frame;
         private JTable tableView;
         private String lastPrintDate;
         private Font defaultFont;
         private Font headerFont;
         private Font footerFont;
         private int headerHeight;
         private int footerHeight;
         private int cellBuffer = 5;
         private boolean first_pass;
         private ArrayList pages;
         public Report()
              frame = new JFrame("Sales Report");
              frame.addWindowListener(new WindowAdapter()
                   public void windowClosing(WindowEvent e)
                        System.exit(0);
              final String[] headers =
                   "ID",
                   "Description",
                   "open price",
                   "latest price",
                   "End Date",
                   "Quantity"
              int count = 0;
              final Object[][] data =
                   {new Integer(count++), "Box of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of Biros ppppppppppppppp", "1.00", "4.99", new Date(), new Integer(200000)},
                   {new Integer(count++), "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
                   {new Integer(count++), "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
                   {new Integer(count++), "tape", "1.00", "1.49", new Date(), new Integer(1)},
                   {new Integer(count++), "stapler", "4.00", "4.49", new Date(), new Integer(1)},
                   {new Integer(count++), "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
                   {new Integer(count++), "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
                   {new Integer(count++), "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
                   {new Integer(count++), "tape", "1.00", "1.49", new Date(), new Integer(1)},
                   {new Integer(count++), "stapler", "4.00", "4.49", new Date(), new Integer(1)},
                   {new Integer(count++), "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
                   {new Integer(count++), "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
                   {new Integer(count++), "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
                   {new Integer(count++), "tape", "1.00", "1.49", new Date(), new Integer(1)},
                   {new Integer(count++), "stapler", "4.00", "4.49", new Date(), new Integer(1)},
                   {new Integer(count++), "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
                   {new Integer(count++), "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
                   {new Integer(count++), "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
                   {new Integer(count++), "tape", "1.00", "1.49", new Date(), new Integer(1)},
                   {new Integer(count++), "stapler", "4.00", "4.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
                   {new Integer(count++),  "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
                   {new Integer(count++),  "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "tape", "1.00", "1.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "stapler", "4.00", "4.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
                   {new Integer(count++),  "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
                   {new Integer(count++),  "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "tape", "1.00", "1.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "stapler", "4.00", "4.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)}
              TableModel dataModel = new AbstractTableModel()
                   public int getColumnCount() { return headers.length; }
                   public int getRowCount() { return data.length;}
                   public Object getValueAt(int row, int col)
                        return data[row][col];
                   public String getColumnName(int column)
                        return headers[column];
                   public Class getColumnClass(int col)
                        return getValueAt(0,col).getClass();
                   public boolean isCellEditable(int row, int col)
                        return (col==1);
                   public void setValueAt(Object aValue, int row, int column)
                        data[row][column] = aValue;
              tableView = new JTable(dataModel);
              JScrollPane scrollpane = new JScrollPane(tableView);
              scrollpane.setPreferredSize(new Dimension(500, 80));
              frame.getContentPane().setLayout(new BorderLayout());
              frame.getContentPane().add(BorderLayout.CENTER,scrollpane);
              frame.pack();
              JButton printButton= new JButton();
              printButton.setText("print me!");
              frame.getContentPane().add(BorderLayout.SOUTH,printButton);
              // for faster printing turn double buffering off
              RepaintManager.currentManager(frame).setDoubleBufferingEnabled(false);
              printButton.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent evt)
                        doPrint();
              frame.setVisible(true);
          * Reset variables before printing
         private void prepareForPrint()
              pages = new ArrayList();
              first_pass = true;
          * Display a print dialog with some hardcoded defaults
          * The print fonts are also hardcoded
         public void doPrint()
              try
                   String jobName = "Java Report";
                   defaultFont = new Font("Arial", Font.PLAIN, 8);
                   footerFont = new Font("Arial", Font.PLAIN, 6);
                   headerFont = new Font("Arial", Font.BOLD, 10);
                   PrinterJob prnJob = PrinterJob.getPrinterJob();
                   prnJob.setPrintable(this);
                   PrintRequestAttributeSet prnSet = new HashPrintRequestAttributeSet();
                   prnSet.add(new Copies(1));
                   prnSet.add(new JobName(jobName, null));
                   prnSet.add(MediaSizeName.ISO_A4);
                   PageFormat pf = prnJob.defaultPage();
                   pf.setOrientation(java.awt.print.PageFormat.PORTRAIT);
                   prnJob.setJobName(jobName);
                   PrintService[] services = PrinterJob.lookupPrintServices();
                   if (services.length > 0)
                        if (prnJob.printDialog(prnSet))
                              * Get print date
                             String dateFormat = "dd/MM/yyyy HH:mm:ss";
                             DateFormat m_DateFormat = new SimpleDateFormat(dateFormat);
                             lastPrintDate = m_DateFormat.format(new Date()).toString();
                             prepareForPrint();
                             prnJob.print(prnSet);
                   else
                        JOptionPane.showMessageDialog(frame, "No Printer was found!!", "Printer Error", JOptionPane.ERROR_MESSAGE);
                        return;
              catch (PrinterException e)
                   e.printStackTrace();
         public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException
               * Check if this is the first time the print method is called for this print action.
               * It is not guaranteed that the print will be called with synchronous pageIndex'es,
               * so we need to calculate the number of pages and which rows appear on which pages.
               * Then the correct page will be printed regardless of which pageIndex is sent through.
              if (first_pass)
                   calcPages(g, pageFormat);
              first_pass = false;
              // Stop printing if the pageIndex is out of range
              if (pageIndex >= pages.size())
                   return NO_SUCH_PAGE;
              Graphics2D     g2 = (Graphics2D) g;
              g2.setColor(Color.black);
              // The footer will be one line at the bottom of the page, cater for this.
              g2.setFont(footerFont);
              footerHeight = g2.getFontMetrics().getHeight() + g2.getFontMetrics().getDescent();
              g2.setFont(defaultFont);
              FontMetrics fontMetrics = g2.getFontMetrics();
              int fontHeight = fontMetrics.getHeight();
              int fontDescent = fontMetrics.getDescent();
              double pageHeight = pageFormat.getImageableHeight() + pageFormat.getImageableY();
              double pageWidth = pageFormat.getImageableWidth();
              double tableWidth = (double) tableView.getColumnModel().getTotalColumnWidth();
              // Shrink or expand the table to fit the page width
              double scale = pageWidth / (tableWidth+ (cellBuffer * tableView.getColumnCount()));
              // Calculate the width in pixels for each column
              double[] columnWidths = new double[tableView.getColumnCount()];
              for(int i = 0; i < tableView.getColumnCount(); i++)
                   columnWidths[i] = (double)tableView.getColumnModel().getColumn(i).getWidth() * scale;
              // Reset the view to the start of the page
              g2.translate(0, 0);
              // Draw a rectangle to see the printable area
              g2.draw3DRect((int)pageFormat.getImageableX(),
                        (int)pageFormat.getImageableY(),
                        (int)pageFormat.getImageableWidth(),
                        (int)pageFormat.getImageableHeight(),
                        false);
              // Calculate the header height
              g2.setFont(headerFont);
              fontMetrics = g2.getFontMetrics();
              // Print the headers and retreive the starting position for the data
              int next_row = printLine(g2, pageFormat, fontMetrics, -1, (int)pageFormat.getImageableY() + fontHeight, columnWidths);
              g2.setFont(defaultFont);
              fontMetrics = g2.getFontMetrics();
              // Start printing the detail
              ArrayList page = (ArrayList)pages.get(pageIndex);
              int start = ((Integer)page.get(0)).intValue();
              int end = ((Integer)page.get(1)).intValue();
              for (int i = start; i <= end; i++)
                   next_row = printLine(g2, pageFormat, fontMetrics, i, next_row, columnWidths);
              // Print the footer
              g2.setFont(footerFont);
              String pageFooter = "Page " + (pageIndex + 1) + " - " + lastPrintDate;
              g2.drawString(pageFooter,
                             (int)pageFormat.getWidth() / 2 - (fontMetrics.stringWidth(pageFooter) / 2),
                             (int)(pageHeight - fontDescent));
              return PAGE_EXISTS;
          * We can't guarantee that the same amount of rows will be displayed on each page,
          * the row heights are dynamic and may wrap onto 2 or more lines.
          * Thus we need to calculate the height of each row and then test how may rows
          * fit on a specific page. eg. Page 1 contains rows 1 to 10, Page 2 contains rows 11 to 15 etc.
         public void calcPages(Graphics g, PageFormat pageFormat) throws PrinterException
              Graphics2D     g2 = (Graphics2D) g;
              g2.setColor(Color.black);
              // The footer will be one line at the bottom of the page, cater for this.
              g2.setFont(footerFont);
              footerHeight = g2.getFontMetrics().getHeight() + g2.getFontMetrics().getDescent();
              g2.setFont(defaultFont);
              FontMetrics fontMetrics = g2.getFontMetrics();
              int fontHeight = fontMetrics.getHeight();
              int fontDescent = fontMetrics.getDescent();
              double pageHeight = pageFormat.getImageableHeight() - fontHeight;
              double pageWidth = pageFormat.getImageableWidth();
              double tableWidth = (double) tableView.getColumnModel().getTotalColumnWidth();
              // Shrink or expand the table to fit the page width
              double scale = pageWidth / (tableWidth+ (cellBuffer * tableView.getColumnCount()));
              // Calculate the width in pixels for each column
              double[] columnWidths = new double[tableView.getColumnCount()];
              for(int i = 0; i < tableView.getColumnCount(); i++)
                   columnWidths[i] = (double)tableView.getColumnModel().getColumn(i).getWidth() * scale;
              // Calculate the header height
              int maxHeight = 0;
              g2.setFont(headerFont);
              fontMetrics = g2.getFontMetrics();
              for (int j = 0; j < tableView.getColumnCount(); j++)
                   String value = tableView.getColumnName(j).toString();
                   int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
                   if (numLines > maxHeight)
                        maxHeight = numLines;
              headerHeight = g2.getFontMetrics().getHeight() * maxHeight;
              g2.setFont(defaultFont);
              fontMetrics = g2.getFontMetrics();
              int pageNum = 0;
              int bottom_of_page = (int)(pageFormat.getImageableHeight() + pageFormat.getImageableY()) - footerHeight;
              int prev_row = 0;
              int next_row = (int)pageFormat.getImageableY() + fontHeight + headerHeight;
              int i = 0;
              ArrayList page = new ArrayList();
              page.add(new Integer(0));
              for (i = 0; i < tableView.getRowCount(); i++)
                   maxHeight = 0;
                   for (int j = 0; j < tableView.getColumnCount(); j++)
                        String value = tableView.getValueAt(i, j).toString();
                        int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
                        if (numLines > maxHeight)
                             maxHeight = numLines;
                   prev_row = next_row;
                   next_row += (fontHeight * maxHeight);
                   // If we've reached the bottom of the page then set the current page's end row
                   if (next_row > bottom_of_page)
                        page.add(new Integer(i - 1));
                        pages.add(page);
                        page = new ArrayList();
                        page.add(new Integer(i));
                        pageNum++;
                        next_row = (int)pageFormat.getImageableY()
                                       + fontHeight
                                       + ((int)pageFormat.getHeight() * pageNum)
                                       + headerHeight;
                        bottom_of_page = (int)(pageFormat.getImageableHeight()
                                            + pageFormat.getImageableY())
                                            + ((int)pageFormat.getHeight() * pageNum)
                                            - footerHeight;
                        //Include the current row on the next page, because there is no space on this page
                        i--;
              page.add(new Integer(i - 1));
              pages.add(page);
          * Print the headers or a row from the table to the graphics context
          * Return the position of the row following this one
         public int printLine(Graphics2D g2,
                                       PageFormat pageFormat,
                                       FontMetrics fontMetrics,
                                       int rowNum,
                                       int next_row,
                                       double[] columnWidths)
                   throws PrinterException
              int lead = 0;
              int maxHeight = 0;
              for (int j = 0; j < tableView.getColumnCount(); j++)
                   String value = null;
                   int align = LEFT_ALIGN;
                   if (rowNum > -1)
                        Object obj = tableView.getValueAt(rowNum, j);
                        if (obj instanceof Number)
                             align = RIGHT_ALIGN;
                        value = obj.toString();
                   else
                        align = CENTER_ALIGN;
                        value = tableView.getColumnName(j);
                   int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
                   if (numLines > maxHeight)
                        maxHeight = numLines;
                   if (fontMetrics.stringWidth(value) < columnWidths[j])
                        // Single line
                        int offset = 0;
                        // Work out the offset from the start of the column to display alignment correctly
                        switch (align)
                             case RIGHT_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)); break;
                             case CENTER_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)) / 2; break;
                             default: offset = 0; break;
                        g2.drawString(value,
                                       lead + (int)(pageFormat.getImageableX() + offset),
                                       next_row);
                   else
                        for(int a = 0; a < numLines; a++)
                             //Multi-Line
                             int x = 0;
                             int width = 0;
                             for(x = 0; x < value.length(); x++)
                                  width += fontMetrics.charWidth(value.charAt(x));
                                  if (width > columnWidths[j])
                                       break;
                             int offset = 0;
                             // Work out the offset from the start of the column to display alignment correctly
                             switch (align)
                                  case RIGHT_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)); break;
                                  case CENTER_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)) / 2; break;
                                  default: offset = 0; break;
                             g2.drawString(value.substring(0, x),
                                            lead + (int)(pageFormat.getImageableX() + offset),
                                            next_row + (fontMetrics.getHeight() * a));                    
                             value = value.substring(x);
                   lead += columnWidths[j] + cellBuffer;
              // Draw a solid line below the row
              g2.draw(new Line2D.Double(pageFormat.getImageableX(),
                             next_row + (fontMetrics.getHeight() * (maxHeight - 1)) + fontMetrics.getDescent(),
                             pageFormat.getImageableY() + pageFormat.getImageableWidth(),
                             next_row + (fontMetrics.getHeight() * (maxHeight - 1)) + fontMetrics.getDescent()));
              // Return the position of the row following this one
              return next_row + (fontMetrics.getHeight() * maxHeight);
         public static void main(String[] args)
              new Report();
    }

    Fixed some bugs and added a title. Just pass in a JTable and the class will do the rest.
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.print.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.print.*;
    import javax.print.attribute.*;
    import javax.print.attribute.standard.*;
    import java.text.*;
    import java.math.*;
    public class PrintJTable implements Printable
         private final int LEFT_ALIGN = -1;
         private final int CENTER_ALIGN = 0;
         private final int RIGHT_ALIGN = 1;
         private JFrame m_parent;
         private String m_title;
         private JTable tableView;
         private String lastPrintDate;
         private Font defaultFont;
         private Font headerFont;
         private Font footerFont;
         private int headerHeight;
         private int footerHeight;
         private int cellBuffer = 5;
         private boolean first_pass;
         private ArrayList pages;
         public PrintJTable(JFrame parent, JTable table)
              m_parent = parent;
              tableView = table;
              doPrint();
         public PrintJTable(JFrame parent, String title, JTable table)
              m_parent = parent;
              m_title = title;
              tableView = table;
              doPrint();
          * Reset variables before printing
         private void prepareForPrint()
              pages = new ArrayList();
              first_pass = true;
          * Display a print dialog with some hardcoded defaults
          * The print fonts are also hardcoded
         public void doPrint()
              try
                   String jobName = "Java Report";
                   defaultFont = new Font("Arial", Font.PLAIN, 8);
                   footerFont = new Font("Arial", Font.PLAIN, 6);
                   headerFont = new Font("Arial", Font.BOLD, 8);
                   PrinterJob prnJob = PrinterJob.getPrinterJob();
                   prnJob.setPrintable(this);
                   PrintRequestAttributeSet prnSet = new HashPrintRequestAttributeSet();
                   prnSet.add(new Copies(1));
                   prnSet.add(new JobName(jobName, null));
                   prnSet.add(MediaSizeName.ISO_A4);
                   PageFormat pf = prnJob.defaultPage();
                   pf.setOrientation(java.awt.print.PageFormat.PORTRAIT);
                   prnJob.setJobName(jobName);
                   PrintService[] services = PrinterJob.lookupPrintServices();
                   if (services.length > 0)
                        if (prnJob.printDialog(prnSet))
                              * Get print date
                             String dateFormat = "dd/MM/yyyy HH:mm:ss";
                             DateFormat m_DateFormat = new SimpleDateFormat(dateFormat);
                             lastPrintDate = m_DateFormat.format(new Date()).toString();
                             prepareForPrint();
                             prnJob.print(prnSet);
                   else
                        JOptionPane.showMessageDialog(m_parent, "No Printer was found!!", "Printer Error", JOptionPane.ERROR_MESSAGE);
                        return;
              catch (PrinterException e)
                   e.printStackTrace();
         public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException
               * Check if this is the first time the print method is called for this print action.
               * It is not guaranteed that the print will be called with synchronous pageIndex'es,
               * so we need to calculate the number of pages and which rows appear on which pages.
               * Then the correct page will be printed regardless of which pageIndex is sent through.
              if (first_pass)
                   calcPages(g, pageFormat);
              first_pass = false;
              // Stop printing if the pageIndex is out of range
              if (pageIndex >= pages.size())
                   return NO_SUCH_PAGE;
              Graphics2D     g2 = (Graphics2D) g;
              g2.setColor(Color.black);
              // The footer will be one line at the bottom of the page, cater for this.
              g2.setFont(footerFont);
              footerHeight = g2.getFontMetrics().getHeight() + g2.getFontMetrics().getDescent();
              g2.setFont(defaultFont);
              FontMetrics fontMetrics = g2.getFontMetrics();
              int fontHeight = fontMetrics.getHeight();
              int fontDescent = fontMetrics.getDescent();
              double pageHeight = pageFormat.getImageableHeight() + pageFormat.getImageableY();
              double pageWidth = pageFormat.getImageableWidth();
              double tableWidth = (double) tableView.getColumnModel().getTotalColumnWidth();
              // Shrink or expand the table to fit the page width
              double scale = (pageWidth - (cellBuffer * tableView.getColumnCount())) / tableWidth;
              // Calculate the width in pixels for each column
              double[] columnWidths = new double[tableView.getColumnCount()];
              double test = 0;
              for(int i = 0; i < tableView.getColumnCount(); i++)
                   columnWidths[i] = (double)Math.floor(tableView.getColumnModel().getColumn(i).getWidth() * scale);
                   test += columnWidths;
              // Reset the view to the start of the page
              g2.translate(0, 0);
              // Draw a rectangle to see the printable area
              g2.draw3DRect((int)pageFormat.getImageableX(),
                        (int)pageFormat.getImageableY(),
                        (int)pageFormat.getImageableWidth(),
                        (int)pageFormat.getImageableHeight(),
                        false);
              // Calculate the header height
              g2.setFont(headerFont);
              fontMetrics = g2.getFontMetrics();
              // Print the headers and retreive the starting position for the data
              int next_row = (int)pageFormat.getImageableY() + fontMetrics.getHeight();
              if ((m_title != null) && (!m_title.equalsIgnoreCase("")))
                   g2.drawString(m_title,
                                       (int)(pageFormat.getImageableX()),
                                       next_row);
                   Color current_color = g2.getColor();
                   g2.setColor(Color.lightGray);
                   int y = next_row + fontMetrics.getDescent();
                   g2.draw(new Line2D.Double(pageFormat.getImageableX(),
                                  y,
                                  (pageFormat.getImageableY() + pageFormat.getImageableWidth()),
                                  y));
                   g2.setColor(current_color);
                   next_row += fontMetrics.getHeight();
              next_row = printLine(g2, pageFormat, fontMetrics, -1, next_row, columnWidths);
              g2.setFont(defaultFont);
              fontMetrics = g2.getFontMetrics();
              // Start printing the detail
              ArrayList page = (ArrayList)pages.get(pageIndex);
              int start = ((Integer)page.get(0)).intValue();
              int end = ((Integer)page.get(1)).intValue();
              for (int i = start; i <= end; i++)
                   next_row = printLine(g2, pageFormat, fontMetrics, i, next_row, columnWidths);
              // Print the footer
              g2.setFont(footerFont);
              String pageFooter = "Page " + (pageIndex + 1) + " - " + lastPrintDate;
              g2.drawString(pageFooter,
                             (int)pageFormat.getWidth() / 2 - (fontMetrics.stringWidth(pageFooter) / 2),
                             (int)(pageHeight - fontDescent));
              return PAGE_EXISTS;
         * We can't guarantee that the same amount of rows will be displayed on each page,
         * the row heights are dynamic and may wrap onto 2 or more lines.
         * Thus we need to calculate the height of each row and then test how may rows
         * fit on a specific page. eg. Page 1 contains rows 1 to 10, Page 2 contains rows 11 to 15 etc.
         public void calcPages(Graphics g, PageFormat pageFormat) throws PrinterException
              Graphics2D     g2 = (Graphics2D) g;
              g2.setColor(Color.black);
              // The footer will be one line at the bottom of the page, cater for this.
              g2.setFont(footerFont);
              footerHeight = g2.getFontMetrics().getHeight() + g2.getFontMetrics().getDescent();
              g2.setFont(defaultFont);
              FontMetrics fontMetrics = g2.getFontMetrics();
              int fontHeight = fontMetrics.getHeight();
              int fontDescent = fontMetrics.getDescent();
              double pageHeight = pageFormat.getImageableHeight() - fontHeight;
              double pageWidth = pageFormat.getImageableWidth();
              double tableWidth = (double) tableView.getColumnModel().getTotalColumnWidth();
              // Shrink or expand the table to fit the page width
              double scale = (pageWidth - (cellBuffer * tableView.getColumnCount())) / tableWidth;
              // Calculate the width in pixels for each column
              double[] columnWidths = new double[tableView.getColumnCount()];
              for(int i = 0; i < tableView.getColumnCount(); i++)
                   columnWidths[i] = (double)Math.floor(tableView.getColumnModel().getColumn(i).getWidth() * scale);
              // Calculate the header height
              int maxHeight = 0;
              g2.setFont(headerFont);
              fontMetrics = g2.getFontMetrics();
              headerHeight = 0;
              if ((m_title != null) && (!m_title.equalsIgnoreCase("")))
                   headerHeight = fontMetrics.getHeight();
              for (int j = 0; j < tableView.getColumnCount(); j++)
                   String value = tableView.getColumnName(j).toString();
                   int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
                   if (numLines > maxHeight)
                        maxHeight = numLines;
              headerHeight += g2.getFontMetrics().getHeight() * maxHeight;
              g2.setFont(defaultFont);
              fontMetrics = g2.getFontMetrics();
              int pageNum = 0;
              int bottom_of_page = (int)(pageFormat.getImageableHeight() + pageFormat.getImageableY()) - footerHeight;
              int prev_row = 0;
              int next_row = (int)pageFormat.getImageableY() + fontHeight + headerHeight;
              int i = 0;
              ArrayList page = new ArrayList();
              page.add(new Integer(0));
              for (i = 0; i < tableView.getRowCount(); i++)
                   maxHeight = 0;
                   for (int j = 0; j < tableView.getColumnCount(); j++)
                        String value = formatObject(tableView.getValueAt(i, j));
                        int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
                        if (numLines > maxHeight)
                             maxHeight = numLines;
                   prev_row = next_row;
                   next_row += (fontHeight * maxHeight);
                   // If we've reached the bottom of the page then set the current page's end row
                   if (next_row > bottom_of_page)
                        page.add(new Integer(i - 1));
                        pages.add(page);
                        page = new ArrayList();
                        page.add(new Integer(i));
                        pageNum++;
                        next_row = (int)pageFormat.getImageableY()
                                       + fontHeight
                                       + ((int)pageFormat.getHeight() * pageNum)
                                       + headerHeight;
                        bottom_of_page = (int)(pageFormat.getImageableHeight()
                                            + pageFormat.getImageableY())
                                            + ((int)pageFormat.getHeight() * pageNum)
                                            - footerHeight;
                        //Include the current row on the next page, because there is no space on this page
                        i--;
              page.add(new Integer(i - 1));
              pages.add(page);
         * Print the headers or a row from the table to the graphics context
         * Return the position of the row following this one
         public int printLine(Graphics2D g2,
                                       PageFormat pageFormat,
                                       FontMetrics fontMetrics,
                                       int rowNum,
                                       int next_row,
                                       double[] columnWidths)
                   throws PrinterException
              int lead = 0;
              int maxHeight = 0;
              for (int j = 0; j < tableView.getColumnCount(); j++)
                   String value = null;
                   int align = LEFT_ALIGN;
                   if (rowNum > -1)
                        Object obj = tableView.getValueAt(rowNum, j);
                        if (obj instanceof Number)
                             align = RIGHT_ALIGN;
                        value = formatObject(obj);
                   else
                        //align = CENTER_ALIGN;
                        value = tableView.getColumnName(j);
                   int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
                   if (numLines > maxHeight)
                        maxHeight = numLines;
                   if (fontMetrics.stringWidth(value) < columnWidths[j])
                        // Single line
                        int offset = 0;
                        // Work out the offset from the start of the column to display alignment correctly
                        switch (align)
                             case RIGHT_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)); break;
                             case CENTER_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)) / 2; break;
                             default: offset = 0; break;
                        g2.drawString(value,
                                       lead + (int)(pageFormat.getImageableX() + offset),
                                       next_row);
                   else
                        for(int a = 0; a < numLines; a++)
                             //Multi-Line
                             int x = 0;
                             int width = 0;
                             for(x = 0; x < value.length(); x++)
                                  width += fontMetrics.charWidth(value.charAt(x));
                                  if (width > columnWidths[j])
                                       break;
                             int offset = 0;
                             // Work out the offset from the start of the column to display alignment correctly
                             switch (align)
                                  case RIGHT_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value.substring(0, x))); break;
                                  case CENTER_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value.substring(0, x))) / 2; break;
                                  default: offset = 0; break;
                             g2.drawString(value.substring(0, x),
                                            lead + (int)(pageFormat.getImageableX() + offset),
                                            next_row + (fontMetrics.getHeight() * a));                    
                             value = value.substring(x);
                   lead += columnWidths[j] + cellBuffer;
              // Draw a solid line below the row
              Color current_color = g2.getColor();
              g2.setColor(Color.lightGray);
              int y = next_row + (fontMetrics.getHeight() * (maxHeight - 1)) + fontMetrics.getDescent();
              g2.draw(new Line2D.Double(pageFormat.getImageableX(),
                             y,
                             (pageFormat.getImageableY() + pageFormat.getImageableWidth()),
                             y));
              g2.setColor(current_color);
              // Return the position of the row following this one
              return next_row + (fontMetrics.getHeight() * maxHeight);
         public String formatObject(Object obj)
              String value = (obj == null) ? "" : obj.toString();
              return value;

  • How to use drop down menu in JTables

    Hi, i'm trying to add an drop down menu to my jtable so that people can select a set number of texts from an enum type. How can this be accomplished?
    My current Code: /**
    * Bill Huang
    * Started: Nov 07, 2007
    * Dossier
    package packageSolo;
    import javax.swing.*;
    import java.awt.*;
    public class SpreadSheetGUI extends JPanel{
         private void debug(int x){
              //System.out.println(x);
         protected static Object[][] data;
         protected static int classroomAmount = 0;
         protected static JTable jtable;
         protected static String[] columnNames = { "Class Room Number", "Period One", "Period Two", "Period Three", "Period Four" };
         public SpreadSheetGUI(){
              super(new GridLayout(1,0));
              String input;
              int flag2 = 0;
              int flag4 = 0;
              int flag5 = 0;
              int flag8 = 0;
              input = JOptionPane
                        .showInputDialog("How many classrooms are there?");
               * see if the user wantes to quit at this point
              if (input == null) {
                   debug(4);
                   int exitint = 0;
                   exitint = JOptionPane.showConfirmDialog(null,
                             "Do you want to exit?", "Exit?",
                             JOptionPane.OK_CANCEL_OPTION);
                   if (exitint == 0) {
                        try {
                             System.exit(1);
                        } catch (SecurityException eb) {
                             System.out.println("exit");
              while (flag4 == 0) {
                    * this while loop with flag2 is for checking if the thing is of int
                    * class
                   while (flag2 == 0) {
                         * try to get a integer, check for a bad input class
                        try {
                              * parse, and if success set flag2 to 1 and break out this
                              * while loop
                             classroomAmount = Integer.parseInt(input);
                             flag2 = 1;
                             debug(2);
                        } catch (NumberFormatException ec) {
                             debug(3);
                              * ops user input was not a integer class
                             JOptionPane
                                       .showMessageDialog(null,
                                                 "Enter a positive integer only",
                                                 "Number Format is Wrong",
                                                 JOptionPane.ERROR_MESSAGE);
                             input = JOptionPane
                                       .showInputDialog("How many months are there?");
                              * see if the user wantes to quit at this point
                             if (input == null) {
                                  debug(4);
                                  int exitint = 0;
                                  exitint = JOptionPane.showConfirmDialog(null,
                                            "Do you want to exit?", "Exit?",
                                            JOptionPane.OK_CANCEL_OPTION);
                                  if (exitint == 0) {
                                       try {
                                            System.exit(1);
                                       } catch (SecurityException eb) {
                                            System.out.println("exit");
                    * this while loop sees if the integer is smaller than 0 so the
                    * array cannot be a real one
                   while (flag5 == 0) {
                        // numamountint = Integer.parseInt(numamount);
                        if (classroomAmount < 0 || classroomAmount > 12) {
                             debug(5);
                             JOptionPane
                                       .showMessageDialog(null,
                                                 "Enter a positive integer that is smaller than 12",
                                                 "Number Format/Size is Wrong",
                                                 JOptionPane.ERROR_MESSAGE);
                             input = JOptionPane
                                       .showInputDialog("How many months are there?");
                             if (input == null) {
                                  int exitint = 0;
                                  exitint = JOptionPane.showConfirmDialog(null,
                                            "Do you want to exit?", "Exit?",
                                            JOptionPane.OK_CANCEL_OPTION);
                                  if (exitint == 0) {
                                       try {
                                            System.exit(1);
                                       } catch (SecurityException eb) {
                                            System.out.println("exit");
                              * this while loop check for number format again
                             while (flag8 == 0) {
                                  try {
                                       debug(6);
                                       classroomAmount = Integer.parseInt(input);
                                       flag8 = 1;
                                  } catch (NumberFormatException ec) {
                                       debug(7);
                                       JOptionPane.showMessageDialog(null,
                                                 "Enter a positive integer only",
                                                 "Number Format is Wrong",
                                                 JOptionPane.ERROR_MESSAGE);
                                       input = JOptionPane
                                                 .showInputDialog("How many months are there?");
                                       if (input == null) {
                                            int exitint = 0;
                                            exitint = JOptionPane.showConfirmDialog(null,
                                                      "Do you want to exit?", "Exit?",
                                                      JOptionPane.OK_CANCEL_OPTION);
                                            if (exitint == 0) {
                                                 try {
                                                      System.exit(1);
                                                 } catch (SecurityException eb) {
                                                      System.out.println("exit");
                        } else {
                              * here the input is greater than 0 so it sets flag5 and 4
                              * then break out of the while loops
                             debug(8);
                             flag5 = 1;
                             flag4 = 1;
              data = new String[classroomAmount][5];
              jtable = new JTable(data, columnNames);
              jtable.setPreferredScrollableViewportSize(new Dimension(800, 600));
              JScrollPane scrollPane = new JScrollPane(jtable);
              this.add(scrollPane);
              this.show();
    }

            Object[] possibilities = {"1", "2", "3"};
            input = (String) JOptionPane.showInputDialog(null,
                    "Please choose the number of classrooms:",
                    "How many classrooms are there?",
                    JOptionPane.PLAIN_MESSAGE,
                    null, possibilities, "1");Edited by: Andre_Uhres on Nov 8, 2007 8:22 AM
    I thought you need a combo for JTable row set. Seems I misunderstood.
    See next posting.

  • Jtable Update problem .. Please help !!!!!!!!

    Hi ,
    I am trying to get my updated Jtable, stored in a table of database over a previous table ......after updating it via drag n drop ....
    But even after I change the cell position to make the changes ... it still takes up the old value of that cell and not the new one while writing the data in the database table...
    Here is the code .... Please see it and tell me if it is possible :
    package newpackage;
    import java.sql.*;
    import java.util.Vector;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Dimension;
    import java.text.*;
    import newpackage.ExcelExporter;
    import java.awt.Dimension;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import java.awt.datatransfer.*;
    import java.awt.dnd.*;
    import java.awt.image.*;
    import java.io.*;
    import java.util.*;
    import java.awt.print.*;
    import java.awt.*;
    import java.io.*;
    import java.util.Random.*;
    import javax.swing.*;
    import java.text.*;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JComboBox;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableColumn;
    public class tab7le extends javax.swing.JFrame {
        Vector columnNames = new Vector();
        Vector data = new Vector();
        Connection con;
    Statement stat;
    ResultSet rs;
    int li_cols = 0;
    Vector allRows;
    Vector row;
    Vector newRow;
    Vector colNames;
    String dbColNames[];
    String pkValues[];
    String tableName;
    ResultSetMetaData myM;
    String pKeyCol;
    Vector deletedKeys;
    Vector newRows;
    boolean ibRowNew = false;
    boolean ibRowInserted = false;
        private Map<String, Color> colormap = new HashMap<String, Color>();
        /** Creates new form tab7le */
        public tab7le() {
            populate();
            initComponents();
           public void updateDB(){
                     try{
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
          catch (ClassNotFoundException e){
                System.out.println("Cannot Load Driver!");
          try{
             String url = "jdbc:odbc:FAMS";
             con = DriverManager.getConnection(url);
             stat = con.createStatement();
             rs = stat.executeQuery("Select * from SubAllot");
             deletedKeys = new Vector();
             newRows = new Vector();
             myM = rs.getMetaData();
             tableName = myM.getTableName(1);
             li_cols = myM.getColumnCount();
             dbColNames = new String[li_cols];
             for(int col = 0; col < li_cols; col ++){
                dbColNames[col] = myM.getColumnName(col + 1);
             allRows = new Vector();
             while(rs.next()){
                newRow = new Vector();
                for(int i = 1; i <= li_cols; i++){
                   newRow.addElement(rs.getObject(i));
                } // for
                allRows.addElement(newRow);
             } // while
          catch(SQLException e){
             System.out.println(e.getMessage());
    String updateLine[] = new String[dbColNames.length];
          try{
             DatabaseMetaData dbData = con.getMetaData();
             String catalog;
             // Get the name of all of the columns for this table
             String curCol;
             colNames = new Vector();
             ResultSet rset1 = dbData.getColumns(null,null,tableName,null);
             while (rset1.next()) {
                curCol = rset1.getString(4);
                colNames.addElement(curCol);
             rset1.close();
             pKeyCol = colNames.firstElement().toString();
             // Go through the rows and perform INSERTS/UPDATES/DELETES
             int totalrows;
             totalrows = allRows.size();
             String dbValues[];
             Vector currentRow = new Vector();
             pkValues = new String[allRows.size()];
             // Get column names and values
             for(int i=0;i < totalrows;i++){
                currentRow = (Vector) allRows.elementAt(i);
                int numElements = currentRow.size();
                dbValues = new String[numElements];
                for(int x = 0; x < numElements; x++){
                   String classType = currentRow.elementAt(x).getClass().toString();
                   int pos = classType.indexOf("String");
                   if(pos > 0){ // we have a String
                      dbValues[x] = "'" + currentRow.elementAt(x) + "'";
                      updateLine[x] = dbColNames[x] + " = " + "'" + currentRow.elementAt(x) + "',";
                      if (dbColNames[x].toUpperCase().equals(pKeyCol.toUpperCase())){
                        pkValues[i] = currentRow.elementAt(x).toString() ;
                   pos = classType.indexOf("Integer");
                   if(pos > 0){ // we have an Integer
                      dbValues[x] = currentRow.elementAt(x).toString();
                      if (dbColNames[x].toUpperCase().equals(pKeyCol.toUpperCase())){
                         pkValues[i] = currentRow.elementAt(x).toString();
                      else{
                         updateLine[x] = dbColNames[x] + " = " + currentRow.elementAt(x).toString() + ",";
                   pos = classType.indexOf("Boolean");
                   if(pos > 0){ // we have a Boolean
                      dbValues[x] = currentRow.elementAt(x).toString();
                      updateLine[x] = dbColNames[x] + " = " + currentRow.elementAt(x).toString() + ",";
                      if (dbColNames[x].toUpperCase().equals(pKeyCol.toUpperCase())){
                         pkValues[i] = currentRow.elementAt(x).toString() ;
                } // For Loop
                // If we are here, we have read one entire row of data. Do an UPDATE or an INSERT
                int numNewRows = newRows.size();
                int insertRow = 0;
                boolean newRowFound;
                for (int z = 0;z < numNewRows;z++){
                   insertRow = ((Integer) newRows.get(z)).intValue();
                   if(insertRow == i+1){
                      StringBuffer InsertSQL = new StringBuffer();
                      InsertSQL.append("INSERT INTO " + tableName + " (");
                      for(int zz=0;zz<=dbColNames.length-1;zz++){
                         if (dbColNames[zz] != null){
                            InsertSQL.append(dbColNames[zz] + ",");
                      // Strip out last comma
                      InsertSQL.replace(InsertSQL.length()-1,InsertSQL.length(),")");
                      InsertSQL.append(" VALUES(" + pkValues[i] + ",");
                      for(int c=1;c < dbValues.length;c++){
                         InsertSQL.append(dbValues[c] + ",");
                      InsertSQL.replace(InsertSQL.length()-1,InsertSQL.length(),")");
                      System.out.println(InsertSQL.toString());
                      stat.executeUpdate(InsertSQL.toString());
                      ibRowInserted=true;
                } // End of INSERT Logic
                // If row has not been INSERTED perform an UPDATE
                if(ibRowInserted == false){
                   StringBuffer updateSQL = new StringBuffer();
                   updateSQL.append("UPDATE " + tableName + " SET ");
                   for(int z=0;z<=updateLine.length-1;z++){
                      if (updateLine[z] != null){
                         updateSQL.append(updateLine[z]);
                   // Replace the last ',' in the SQL statement with a blank. Then add WHERE clause
                   updateSQL.replace(updateSQL.length()-1,updateSQL.length()," ");
                   updateSQL.append(" WHERE " + pKeyCol + " = " + pkValues[i] );
                   System.out.println(updateSQL.toString());
                   stat.executeUpdate(updateSQL.toString());
                   } //for
             catch(Exception ex){
                System.out.println("SQL Error! Cannot perform SQL UPDATE " + ex.getMessage());
             // Delete records from the DB
             try{
                int numDeletes = deletedKeys.size();
                String deleteSQL;
                for(int i = 0; i < numDeletes;i++){
                   deleteSQL = "DELETE FROM " + tableName + " WHERE " + pKeyCol + " = " +
                                                ((Integer) deletedKeys.get(i)).toString();
                System.out.println(deleteSQL);
                   stat.executeUpdate(deleteSQL);
                // Assume deletes where successful. Recreate Vector holding PK Keys
                deletedKeys = new Vector();
             catch(Exception ex){
                System.out.println(ex.getMessage());
        public void populate()
            try
                //  Connect to the Database
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                Connection con = DriverManager.getConnection("Jdbc:Odbc:FAMS"," "," ");
                System.out.println("ok1");
                //  Read data from a table
                String sql;
                 sql = "Select * from SubAllot";
                 System.out.println("ok1");
                Statement stmt = con.createStatement();
                System.out.println("ok1");
                ResultSet rs = stmt.executeQuery( sql );
                System.out.println("ok1");
                ResultSetMetaData md = rs.getMetaData();
                System.out.println("ok1");
                int columns = md.getColumnCount();
                for(int i = 0;i<columns;i++){
                    columnNames.addElement(md.getColumnName(i+1));
                    System.out.println("ok2");
                while (rs.next())
                    Vector row = new Vector(columns);
                    for (int i = 1; i <columns+1; i++)
                        row.addElement( rs.getObject(i) );
                    data.addElement( row );
            catch(Exception e){
                e.printStackTrace();
                 public void dropmenu(JTable table,TableColumn subpref1) {
            //Set up the editor for the sport cells.
            JComboBox comboBox = new JComboBox();
          for (int i = 0;i<=20;i++)
           comboBox.addItem(i);
            subpref1.setCellEditor(new DefaultCellEditor(comboBox));
            //Set up tool tips for the sport cells.
            DefaultTableCellRenderer renderer =
                    new DefaultTableCellRenderer();
            renderer.setToolTipText("Click for combo box");
            subpref1.setCellRenderer(renderer);
                       abstract class StringTransferHandler extends TransferHandler {
            public int dropAction;
            protected abstract String exportString(final JComponent c);
            protected abstract void importString(final JComponent c, final String str);
            @Override
            protected Transferable createTransferable(final JComponent c) {
                return new StringSelection(exportString(c));
            @Override
            public int getSourceActions(final JComponent c) {
                return MOVE;
            @Override
            public boolean importData(final JComponent c, final Transferable t) {
                if (canImport(c, t.getTransferDataFlavors())) {
                    try {
                        String str = (String) t.getTransferData(DataFlavor.stringFlavor);
                        importString(c, str);
                        return true;
                    } catch (UnsupportedFlavorException ufe) {
                    } catch (IOException ioe) {
                return false;
            @Override
            public boolean canImport(final JComponent c, final DataFlavor[] flavors) {
                for (int ndx = 0; ndx < flavors.length; ndx++) {
                    if (DataFlavor.stringFlavor.equals(flavors[ndx])) {
                        return true;
                return false;
        class TableTransferHandler extends StringTransferHandler {
            private int dragRow;
            private int[] dragColumns;
            private BufferedImage[] image;
            private int row;
            private int[] columns;
            public JTable target;
            private Map<String, Color> colormap;
            private TableTransferHandler(final Map<String, Color> colormap) {
                this.colormap = colormap;
            @Override
            protected Transferable createTransferable(final JComponent c) {
                JTable table = (JTable) c;
                dragRow = table.getSelectedRow();
                dragColumns = table.getSelectedColumns();
                createDragImage(table);
                return new StringSelection(exportString(c));
            protected String exportString(final JComponent c) {
                JTable table = (JTable) c;
                row = table.getSelectedRow();
                columns = table.getSelectedColumns();
                StringBuffer buff = new StringBuffer();
                colormap.clear();
                for (int j = 0; j < columns.length; j++) {
                    Object val = table.getValueAt(row, columns[j]);
                    buff.append(val == null ? "" : val.toString());
                    if (j != columns.length - 1) {
                        buff.append(",");
                    colormap.put(row+","+columns[j], Color.LIGHT_GRAY);
                table.repaint();
                return buff.toString();
            protected void importString(final JComponent c, final String str) {
                target = (JTable) c;
                DefaultTableModel model = (DefaultTableModel) target.getModel();
                String[] values = str.split("\n");
                int colCount = target.getSelectedColumn();
                int max = target.getColumnCount();
                for (int ndx = 0; ndx < values.length; ndx++) {
                    String[] data = values[ndx].split(",");
                    for (int i = 0; i < data.length; i++) {
                        String string = data;
    if(colCount < max){
    Object val = model.getValueAt(target.getSelectedRow(), colCount);
    model.setValueAt(string, target.getSelectedRow(), colCount);
    model.setValueAt(val, dragRow, dragColumns[i]);
    colCount++;
    public BufferedImage[] getDragImage() {
    return image;
    private void createDragImage(final JTable table) {
    if (dragColumns != null) {
    try {
    image = new BufferedImage[dragColumns.length];
    for (int i = 0; i < dragColumns.length; i++) {
    Rectangle cellBounds = table.getCellRect(dragRow, i, true);
    TableCellRenderer r = table.getCellRenderer(dragRow, i);
    DefaultTableModel m = (DefaultTableModel) table.getModel();
    JComponent lbl = (JComponent) r.getTableCellRendererComponent(table,
    table.getValueAt(dragRow, dragColumns[i]), false, false, dragRow, i);
    lbl.setBounds(cellBounds);
    BufferedImage img = new BufferedImage(lbl.getWidth(), lbl.getHeight(),
    BufferedImage.TYPE_INT_ARGB_PRE);
    Graphics2D graphics = img.createGraphics();
    graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f));
    lbl.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
    lbl.paint(graphics);
    graphics.dispose();
    image[i] = img;
    } catch (RuntimeException re) {
    class TableDropTarget extends DropTarget {
    private Insets autoscrollInsets = new Insets(20, 20, 20, 20);
    private Rectangle rect2D = new Rectangle();
    private TableTransferHandler handler;
    public TableDropTarget(final TableTransferHandler h) {
    super();
    this.handler = h;
    @Override
    public void dragOver(final DropTargetDragEvent dtde) {
    handler.dropAction = dtde.getDropAction();
    JTable table = (JTable) dtde.getDropTargetContext().getComponent();
    Point location = dtde.getLocation();
    int row = table.rowAtPoint(location);
    int column = table.columnAtPoint(location);
    table.changeSelection(row, column, false, false);
    paintImage(table, location);
    autoscroll(table, location);
    super.dragOver(dtde);
    public void dragExit(final DropTargetDragEvent dtde) {
    clearImage((JTable) dtde.getDropTargetContext().getComponent());
    super.dragExit(dtde);
    @Override
    public void drop(final DropTargetDropEvent dtde) {
    Transferable data = dtde.getTransferable();
    JTable table = (JTable) dtde.getDropTargetContext().getComponent();
    clearImage(table);
    handler.importData(table, data);
    super.drop(dtde);
    private final void paintImage(final JTable table, final Point location) {
    Point pt = new Point(location);
    BufferedImage[] image = handler.getDragImage();
    if (image != null) {
    table.paintImmediately(rect2D.getBounds());
    rect2D.setLocation(pt.x - 15, pt.y - 15);
    int wRect2D = 0;
    int hRect2D = 0;
    for (int i = 0; i < image.length; i++) {
    table.getGraphics().drawImage(image[i], pt.x - 15, pt.y - 15, table);
    pt.x += image[i].getWidth();
    if (hRect2D < image[i].getHeight()) {
    hRect2D = image[i].getHeight();
    wRect2D += image[i].getWidth();
    rect2D.setSize(wRect2D, hRect2D);
    private final void clearImage(final JTable table) {
    table.paintImmediately(rect2D.getBounds());
    private Insets getAutoscrollInsets() {
    return autoscrollInsets;
    private void autoscroll(final JTable table, final Point cursorLocation) {
    Insets insets = getAutoscrollInsets();
    Rectangle outer = table.getVisibleRect();
    Rectangle inner = new Rectangle(outer.x + insets.left,
    outer.y + insets.top,
    outer.width - (insets.left + insets.right),
    outer.height - (insets.top + insets.bottom));
    if (!inner.contains(cursorLocation)) {
    Rectangle scrollRect = new Rectangle(cursorLocation.x - insets.left,
    cursorLocation.y - insets.top,
    insets.left + insets.right,
    insets.top + insets.bottom);
    table.scrollRectToVisible(scrollRect);
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
    jScrollPane1 = new javax.swing.JScrollPane();
    table = new javax.swing.JTable();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    table.setModel(new javax.swing.table.DefaultTableModel(
    data, columnNames
    jScrollPane1.setViewportView(table);
    //populate();
    table.getTableHeader().setReorderingAllowed(false);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.setCellSelectionEnabled(true);
    table.setDragEnabled(true);
    TableTransferHandler th = new TableTransferHandler(colormap);
    table.setTransferHandler(th);
    table.setDropTarget(new TableDropTarget(th));
    dropmenu(table, table.getColumnModel().getColumn(11));
    jButton1.setText("Update");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton1ActionPerformed(evt);
    jButton2.setText("Ex");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton2ActionPerformed(evt);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(92, 92, 92)
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 605, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(layout.createSequentialGroup()
    .addGap(347, 347, 347)
    .addComponent(jButton1)
    .addGap(115, 115, 115)
    .addComponent(jButton2)))
    .addContainerGap(73, Short.MAX_VALUE))
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(47, 47, 47)
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 354, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(58, 58, 58)
    .addComponent(jButton1)
    .addContainerGap(83, Short.MAX_VALUE))
    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jButton2)
    .addGap(65, 65, 65))))
    pack();
    }// </editor-fold>
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    updateDB(); // TODO add your handling code here:
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    try {
    String pathToDesktop = System.getProperty("user.home")+File.separator+"Desktop";
    pathToDesktop = pathToDesktop + "//Final Allotment.xls";
    ExcelExporter exp = new ExcelExporter();
    exp.exportTable(table, new File(pathToDesktop));
    JOptionPane.showMessageDialog(this,"File exported and saved on desktop!");
    catch (IOException ex) {
    System.out.println(ex.getMessage());
    ex.printStackTrace();
    } // TODO add your handling code here:
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new tab7le().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable table;
    // End of variables declaration
    Please help !!!!!!!!
    Thanks in advance.....                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                

    Here is the code Do you expect people to read through 400 lines of code to understand what you are doing?
    Why post code with access to a database? We can't access the database.
    Search the forum for my "Database Information" (without the space) example class which shows you how to refresh a table with new data.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.

  • MouseListener for JTable cells using html

    Hello,
    I'm trying to write a MouseListener that determines whether the cursor is positioned over a certain string within a JTable cell. The cell contains an html string to allow for some formatting.
    For instance, the table data for a certain cell could be "<html><b>SomeBoldText</b>moreText<html>". I would like to detect when a mouse click occurs on the bold text.
    My current solution is to create the glyph vector corresponding to the cell content stripped of all html tags and then check if the cursor position is within one of the glyphs that form the string. However, that obviously doesn't take into account the formatting done by html, so its not working very well.
    Any suggestions?

    the only way you could possibly do this, if you used JEditorPane as a renderer. even then i'm not sure.

  • Drag and Drop in a JTable (ContentTable)

    Hello Friends,
    I am designing a tool which can be used for daily task distribution, according to time (as we setup in a outlook calendar) using JTable.
    Now I am planning to use a Drag and Drop option where in the task from "one date and time" can be moved to "another date and time" i.e row/column.
    E.g : Suppose the new task which is scheduled at 12:30pm on 22/03/07 has to be rescheduled at 3:00pm 26/03/07. The drag and drop should automatically recognise.
    It would be greate if anyone can throw in thier ideas.. 10 DUKE points..
    Thanks and Rgds,
    Pradeep

    Here's an example of drag and drop of a cell in JTable.
    You can move or copy (using Ctrl) a cell to another location:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.StringSelection;
    import java.awt.datatransfer.Transferable;
    import java.awt.datatransfer.UnsupportedFlavorException;
    import java.io.IOException;
    import javax.swing.BorderFactory;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.ListSelectionModel;
    import javax.swing.TransferHandler;
    import javax.swing.table.DefaultTableModel;
    public class DnD_Demo extends JFrame {
        public DnD_Demo() {
            setTitle("DnD Demo (Version 3)");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel panel = new JPanel(new GridLayout(1,1));
            panel.add(createTable("Table A"));
            getContentPane().add(panel,BorderLayout.CENTER);
            pack();
        private JPanel createTable(String tableId) {
            DefaultTableModel model = new DefaultTableModel();
            model.addColumn("Column 0");
            model.addColumn("Column 1");
            model.addColumn("Column 2");
            model.addColumn("Column 3");
            model.addRow(new String[]{tableId+" 00", tableId+" 01", tableId+" 02", tableId+" 03"});
            model.addRow(new String[]{tableId+" 10", tableId+" 11", tableId+" 12", tableId+" 13"});
            model.addRow(new String[]{tableId+" 20", tableId+" 21", tableId+" 22", tableId+" 23"});
            model.addRow(new String[]{tableId+" 30", tableId+" 31", tableId+" 32", tableId+" 33"});
            JTable table = new JTable(model);
            table.getTableHeader().setReorderingAllowed(false);
            table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
            JScrollPane scrollPane = new JScrollPane(table);
            scrollPane.setPreferredSize(new Dimension(400,100));
            table.setDragEnabled(true);
            table.setTransferHandler(new TableTransferHandler());
            JPanel panel = new JPanel();
            panel.add(scrollPane);
            panel.setBorder(BorderFactory.createTitledBorder(tableId));
            return panel;
        public static void main(String[] args) {
            new DnD_Demo().setVisible(true);
        abstract class StringTransferHandler extends TransferHandler {
            protected abstract String exportString(JComponent c);
            protected abstract void importString(JComponent c, String str);
            protected abstract void cleanup(JComponent c, boolean remove);
            protected Transferable createTransferable(JComponent c) {
                return new StringSelection(exportString(c));
            public int getSourceActions(JComponent c) {
                return COPY_OR_MOVE;
            public boolean importData(JComponent c, Transferable t) {
                if (canImport(c, t.getTransferDataFlavors())) {
                    try {
                        String str = (String)t.getTransferData(DataFlavor.stringFlavor);
                        importString(c, str);
                        return true;
                    } catch (UnsupportedFlavorException ufe) {
                    } catch (IOException ioe) {
                return false;
            protected void exportDone(JComponent c, Transferable data, int action) {
                cleanup(c, action == MOVE);
            public boolean canImport(JComponent c, DataFlavor[] flavors) {
                for (int i = 0; i < flavors.length; i++) {
                    if (DataFlavor.stringFlavor.equals(flavors)) {
    return true;
    return false;
    class TableTransferHandler extends StringTransferHandler {
    public JTable target;
    public int row = -1;
    public int col = -1;
    protected String exportString(JComponent c) {
    JTable table = (JTable)c;
    row = table.getSelectedRow();
    col = table.getSelectedColumn();
    return table.getValueAt(row, col).toString();
    protected void importString(JComponent c, String str) {
    target = (JTable)c;
    int row = target.getSelectedRow();
    int col = target.getSelectedColumn();
    target.getModel().setValueAt(str, row, col);
    protected void cleanup(JComponent c, boolean remove) {
    JTable table = (JTable)c;
    if (remove)
    table.getModel().setValueAt("", row, col);
    Message was edited by:
    Rodney_McKay

  • Rebuilding JTable

    I'm trying to build a table by first selecting a table name. then i press a button and the table appears. When i change the table name and press the button again the table doesn't change. What is going wrong????
    Here's the code:
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import java.sql.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.JInternalFrame;
    public class IPMAC extends JInternalFrame {
         private Connection connection;
    private Statement statement;
         private ResultSet resultSet;
         String selectedGroep;
         private JTable table;
         private int AAP = 1;
    static final int xOffset = 480, yOffset = 10;
         int y, // De y waarde declareren
    x; // De x waarde declareren
    private JComboBox groepKeuze;
    Vector result;
    JDesktopPane desktop;
         public IPMAC()
         throws
                        ClassNotFoundException,
                        SQLException,
                        IllegalAccessException,
                        InstantiationException{
    super("IP MAC",
              false, //resizable
         true, //closable
         false, //maximizable
         true);//iconifiable
              //Set up the GUI.
    desktop = new JDesktopPane(); //a specialized layered pane
    setContentPane(desktop);
    //Set the window's location.
    setLocation(xOffset, yOffset);
    final String url = "jdbc:mysql://localhost/IPMAN";
              final String username = "";
              final String password = "";
              Class.forName("org.gjt.mm.mysql.Driver").newInstance();
         connection = DriverManager.getConnection( url, username, password );
         Label label1 = new Label();
         Label label2 = new Label();
         Label label3 = new Label();
         final TextField macadresveld = new TextField();
         final TextField ipadresveld = new TextField();
         Button button1 = new Button();
         Button button2 = new Button();
         Button button3 = new Button();
              label1.setText("MAC Adres");
              getContentPane().add(label1);
              label1.setBounds(370,60,70,25);
              label2.setText("IP Adres");
              getContentPane().add(label2);
              label2.setBounds(370,110,70,25);
              label3.setText("Groepnaam");
              getContentPane().add(label3);
              label3.setBounds(370,160,70,25);
              getContentPane().add(macadresveld);
              macadresveld.setBounds(440,60,156,20);
              getContentPane().add(ipadresveld);
              ipadresveld.setBounds(440,110,156,20);
              button1.setLabel("Koppel MAC");
              getContentPane().add(button1);
              button1.setBackground(java.awt.Color.lightGray);
              button1.setBounds(506,10,90,25);
              button1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
                   JOptionPane.showMessageDialog
                   ( null, "MAC Adres is being added...", "Updating...",     JOptionPane.INFORMATION_MESSAGE);
    try {
              Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
              connection = DriverManager.getConnection( url, username, password );
              Statement stmt = connection.createStatement();
              int numUpdated01 = stmt.executeUpdate("UPDATE ip SET MacAdres = '" + macadresveld.getText() + "' WHERE IpAdres = '" + ipadresveld.getText() + "' ");
              connection.close();
              catch ( ClassNotFoundException cnfex )
              System.err.println(
         "Failed to load JDBC/ODBC driver." );
              cnfex.printStackTrace();
              System.exit( 1 ); // terminate program
              catch ( SQLException sqlex )
              System.err.println( "Unable to connect" );
              sqlex.printStackTrace();
                   JOptionPane.showMessageDialog
                   ( null, "Data has been updated...", "Updated...",     JOptionPane.INFORMATION_MESSAGE);
              button2.setLabel("Save / Exit");
              getContentPane().add(button2);
              button2.setBackground(java.awt.Color.lightGray);
              button2.setBounds(506,300,90,25);
              button2.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    setVisible(false);
    dispose();
              button3.setLabel("View Data");
              getContentPane().add(button3);
              button3.setBackground(java.awt.Color.lightGray);
              button3.setBounds(506,265,90,25);
              button3.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                             System.out.println("de gekozen Groep is:" + selectedGroep);
                             try     {
                        getTable();
                             catch(Exception ex)     { }
    groepKeuze = new JComboBox(getContents());
    groepKeuze.setMaximumRowCount(4);
         groepKeuze.setBounds(440,160,156,20);
    groepKeuze.setBackground(java.awt.Color.white);
         getContentPane().add( groepKeuze );
    groepKeuze.addItemListener(new ItemListener() {
         public void itemStateChanged( ItemEvent e ) {
              selectedGroep = groepKeuze.getSelectedItem().toString();
              System.out.println( "de gekozen Groep is:" + selectedGroep );
         setSize(616,370);
              show();
              private Vector getContents()
              throws
              ClassNotFoundException,
              SQLException,
              IllegalAccessException,
              InstantiationException
                   Connection connection;
              Statement statement;
                   ResultSet resultSet;
         final String url = "jdbc:mysql://localhost/IPMAN";
                   final String username = "";
                   final String password = "";
                   Class.forName("org.gjt.mm.mysql.Driver").newInstance();
              connection = DriverManager.getConnection( url, username, password );
                   result = new Vector();
                   String query = "SELECT DISTINCT Groep FROM ip";
              statement = connection.createStatement();
              resultSet = statement.executeQuery( query );
                   while (resultSet.next()) {
                   result.addElement(resultSet.getString("Groep"));
              statement.close();
              return result;
         private void getTable()     throws
              ClassNotFoundException,
              SQLException,
              IllegalAccessException,
              InstantiationException
    Statement statement;
    ResultSet resultSet;
    String query = "SELECT NetwerkAdres,IpAdres,KlasseNetwerk,Groep FROM ip WHERE Groep = '" + selectedGroep + "'";
    statement = connection.createStatement();
    resultSet = statement.executeQuery( query );
    displayResultSet( resultSet );
    statement.close();
    selectedGroep = "";
    private void displayResultSet( ResultSet rs )
         throws
              ClassNotFoundException,
              SQLException,
              IllegalAccessException,
              InstantiationException {
    boolean moreRecords = rs.next();
    if ( ! moreRecords ) {
    JOptionPane.showMessageDialog( this,
    "ResultSet contained no records" );
    setTitle( "No records to display" );
    return;
    Vector columnHeads = new Vector();
    Vector rows = new Vector();
    ResultSetMetaData rsmd = rs.getMetaData();
    for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
    columnHeads.addElement( rsmd.getColumnName( i ) );
    do {
    rows.addElement( getNextRow( rs, rsmd ) );
    } while ( rs.next() );
    table = new JTable( rows, columnHeads );
    JScrollPane scroller = new JScrollPane( table );
    getContentPane().add(scroller);
              scroller.setBounds(0,0,370,325);
    validate();
    private Vector getNextRow( ResultSet rs,
    ResultSetMetaData rsmd )
         throws     ClassNotFoundException,
                   SQLException,
                   IllegalAccessException,
                        InstantiationException{
    Vector currentRow = new Vector();
    for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
    switch( rsmd.getColumnType( 1 ) ) {
    case Types.VARCHAR:
    currentRow.addElement( rs.getString( i ) );
    break;
    case Types.INTEGER:
    currentRow.addElement(
    new Long( rs.getLong( 1 ) ) );
    break;
    default:
    System.out.println( "Type was: " +
    rsmd.getColumnTypeName( i ) );
    return currentRow;
    Could somebody try to answer this question???
    thanks!!

    try
    table.getModel().fireTableStructureChanged();
    where you have the validate() line just to see.. I've never actually created a new JTable for every new display, I just manipulate the models and then run the fireTableDataChanged() or fireTableStructureChanged() methods.. That takes care of all this stuff automatically, and I think that'd be a more efficient way of doing things..
    If THAT doens't work, then I'd be suspicious of your scrollpane not redrawing itself.. Do a System.out.println( (String)table.getValueAt(1,1) ); and see if the table actually has the new values or not.. If it DOES but it's not on screen, then you know this is the case.. Then I'd try scroller.revalidate() and scroller.repaint().
    doug

  • Giving names to the columns in a JTable

    Hi,
    I am using JTable(int numRows, int numColumns) constructor to create a JTable. After I built my application I came to knw that I cannot change the column names. The JTable in my GUI will keep on changing and the no. of rows,columns and even the column names may also change. I just wanted to know what constructor I should shift to.
    Thanks,
    Adhiraj

    I would use something like the following:
    DefaultTableModel model = new DefaultTableModel(columnNames, rowCount);
    JTable table = new JTable( model );
    The following code gives some examples on using the DefaultTableModel to add rows and columns:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class TableRowColumn extends JFrame
         private final static String LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
         JTable table;
         DefaultTableModel model;
         JPanel buttonPanel;
         JButton button;
         public TableRowColumn()
              //  Create table
              Object[][] data = { {"1", "A"}, {"2", "B"}, {"3", "C"} };
              String[] columnNames = {"Number","Letter"};
              model = new DefaultTableModel(data, columnNames);
              table = new JTable(model);
              table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
              //  Add table and a Button panel to the frame
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
              buttonPanel = new JPanel();
              getContentPane().add( buttonPanel, BorderLayout.SOUTH );
              button = new JButton( "Add Row" );
              buttonPanel.add( button );
              button.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        model.addRow( createRow() );
                        int row = table.getRowCount() - 1;
                        table.changeSelection(row, 0, false, false);
                        table.requestFocusInWindow();
              button = new JButton( "Insert Row" );
              buttonPanel.add( button );
              button.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        model.insertRow( 0, createRow() );
                        table.changeSelection(0, 0, false, false);
                        table.requestFocusInWindow();
              button = new JButton( "Empty Row" );
              buttonPanel.add( button );
              button.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        model.setRowCount( model.getRowCount() + 1 );
                        int row = table.getRowCount() - 1;
                        table.changeSelection(row, 0, false, false);
                        table.requestFocusInWindow();
              button = new JButton( "Add Column" );
              buttonPanel.add( button );
              button.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        String header = "Col" + (table.getColumnCount() + 1);
                        model.addColumn( header );
                        table.requestFocusInWindow();
              button = new JButton( "Add Column & Data" );
              buttonPanel.add( button );
              button.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        String header = "Col" + (table.getColumnCount() + 1);
                        int rows = table.getRowCount();
                        String[] values = new String[rows];
                        for (int j = 0; j < rows; j++)
                             values[j] = Integer.toString(j);
                        model.addColumn( header, values );
                        table.requestFocusInWindow();
              button = new JButton( "Add Column - No Reordering" );
              buttonPanel.add( button );
              button.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        //  Use this method when you don't want existing columns
                        //  to be rebuilt from the model.
                        //  (ie. moved columns will not be reordered)
                        table.setAutoCreateColumnsFromModel( false );
                        String header = "Col" + (table.getColumnCount() + 1);
                        model.addColumn( header );
                        //  AutoCreate is turned off so create table column here
                        TableColumn column = new TableColumn( table.getColumnCount() );
                        column.setHeaderValue( header );
                        table.addColumn( column );
                        // These won't work once setAutoCreate... has been set to false
                        buttonPanel.getComponent(3).setEnabled( false );
                        buttonPanel.getComponent(4).setEnabled( false );
                        table.requestFocusInWindow();
              button = new JButton( "Remove Last Column" );
              buttonPanel.add( button );
              button.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        int columns = model.getColumnCount();
                        if (columns > 0)
                             if (!table.getAutoCreateColumnsFromModel())
                                  int view =
                                       table.convertColumnIndexToView(columns - 1);
                                  TableColumn column =
                                       table.getColumnModel().getColumn(view);
                                  table.getColumnModel().removeColumn( column );
                             model.setColumnCount(columns - 1);
                        table.requestFocusInWindow();
         private Object[] createRow()
              Object[] newRow = new Object[2];
              int row = table.getRowCount() + 1;
              newRow[0] = Integer.toString( row );
              newRow[1] = LETTERS.substring(row-1, row);
              return newRow;
         public static void main(String[] args)
              TableRowColumn frame = new TableRowColumn();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

  • Move multiple columns in jtable

    I have multiple tab and each tab have a table with multiple columns. I move like this for example-
    col1 col2 col3 col4 col5 col6 col7 col8 col9
    after columns move
    col2 col1 col3 col5 col4 col6 col8 col7 col9
    I save table and get it, it works fine. But when i move columns like this-
    col4 col3 col5 col1 col6 col2 col7 col8 col9
    it never work as i save and get table. please tell what's wrong in below code.
    here are the codes-
    Table save code-
    try {
      Map<String, Map<String, Vector<Object>>> tableMap = new HashMap<String, Map<String, Vector<Object>>>();
      private static Map<String, Object> tables = new HashMap<String, Object>();
      Set<String> tabNames = tables.keySet();
      for (String tabName : tabNames) {
      JTable tab = (JTable) tables.get(tabName);
      Map<String, Vector<Object>> colNameValues = new HashMap<String, Vector<Object>>();
      Enumeration<TableColumn> tabCols = tab.getColumnModel()
      .getColumns();
      while (tabCols.hasMoreElements()) {
      Vector<Object> colums = new Vector<Object>();
      TableColumn col = tabCols.nextElement();
      int modelIndex = col.getModelIndex();
      int viewIndex = tab.convertColumnIndexToView(modelIndex);
      String field = Utils.toString(col.getIdentifier());
      Integer width = col.getWidth();
      if (isTableSelected) {
      boolean visible = !(viewIndex == -1 || col.getWidth() == 0);
      colums.add(visible); // pos 0 visible
      colums.add(field); // pos 1 field
      colums.add(width); // pos 2 width
      colums.add(modelIndex); // pos 3 model index
      colums.add(tab.convertColumnIndexToView(modelIndex)); // pos
      // 4
      // view
      // index
      colNameValues.put(field, colums);
      tableMap.put(tabName, colNameValues);
      if (dataStore.isColumnsSelected()) {
      if (personalizedDataStore != null) {
      Map<String, Map<String, Vector<Object>>> mapOld = personalizedDataStore
      .getInstructionTable();
      if (mapOld != null) {
      if (mapOld.size() > 0) {
      Set<String> oldTabNames = mapOld.keySet();
      for (String oldTabName : oldTabNames) {
      if (!tableMap.containsKey(oldTabName)) {
      tableMap.put(oldTabName,
      mapOld.get(oldTabName));
      dataStore.setInstructionTable(tableMap);
    code for get Table-
    private void applyPesonalizeSettings(String tabName, JTable tab) {
      if (!" ".equals(tabName)) {
      if (personalizedDataStore != null) {
      Map<String, Map<String, Vector<Object>>> oldTables = personalizedDataStore
      .getInstructionTable();
      for (int viewIndex = 0, count = tab.getRowCount(); viewIndex < count; viewIndex++) {
      if (oldTables != null) {
      Map<String, Vector<Object>> oldTabCols = oldTables
      .get(tabName);
      Enumeration<TableColumn> tableColumns = tab
      .getColumnModel().getColumns();
      while (tableColumns.hasMoreElements()) {
      TableColumn col = tableColumns.nextElement();
      String field = Utils.toString(col.getIdentifier());
      if (oldTabCols != null) {
      if (oldTabCols.containsKey(field)) {
      boolean vis = (Boolean) oldTabCols.get(field)
      .get(0);
      int prefWidth = (Integer) oldTabCols.get(field)
      .get(2);
      int modelInd = (Integer) oldTabCols.get(field)
      .get(3);
      int viewInd = (Integer) oldTabCols.get(field)
      .get(4);
      // setting visible
      if (!vis) {
      tab.getColumn(field).setMinWidth(0);
      tab.getColumn(field).setMaxWidth(0);
      tab.getColumn(field).setPreferredWidth(0);
      } else {
      // setting column width
      tab.getColumn(field).setPreferredWidth(
      prefWidth);
      // setting index
      if (modelInd != viewInd) {
      tab.moveColumn(
      tab.convertColumnIndexToView(modelInd),
      viewInd);
    here is the code for set table change property with popup-
    @Override
      protected void doOK() {
      Map<String, Vector<Object>> labelAndRow = new HashMap<String, Vector<Object>>();  //req 22
      for (int viewIndex = 0, count = super.getRowCount(); viewIndex < count; viewIndex++) {
      Vector<Object> row = super.getRow(viewIndex);
      boolean visible = (Boolean) row.get(0);
      String label = (String) row.get(1);
      String field = (String) row.get(2);
      labelAndRow.put(field,row); //req 22
      Integer modelIndex = (Integer) row.get(3);
      Integer width = (Integer) row.get(4);                              
      TableColumn col = jxtable.getColumn(field);
      if (visible) {
      if (width <= 0) {
      width = 75;
      if (width != col.getWidth()) {
      col.setMinWidth(15);
      col.setMaxWidth(1000);
      col.setPreferredWidth(width);
      } else {
      col.setMinWidth(0);
      col.setMaxWidth(0);
      col.setWidth(0);
      col.setPreferredWidth(0);
      col.setHeaderValue(label);
      jxtable.moveColumn(jxtable.convertColumnIndexToView(modelIndex), viewIndex);
      jxtable.moveColumn(jxtable.convertColumnIndexToView(modelIndex), viewIndex);
      super.dispose();
      for (TableColumn col : (List<TableColumn>) jxtable.getColumns()) {
      int modelIndex = col.getModelIndex();
      int viewIndex = jxtable.convertColumnIndexToView(modelIndex);
      String label = Utils.toString(col.getHeaderValue());
      String field = Utils.toString(col.getIdentifier());
      Integer width = col.getWidth();                       
      boolean visible = !(viewIndex == -1 || col.getWidth() == 0);
      dialog.getTableModel().addRow(new Object[]{visible, label, field, modelIndex, width});
      dialog.setVisible(true);

    I have multiple tab and each tab have a table with multiple columns. I move like this for example-
    col1 col2 col3 col4 col5 col6 col7 col8 col9
    after columns move
    col2 col1 col3 col5 col4 col6 col8 col7 col9
    I save table and get it, it works fine. But when i move columns like this-
    col4 col3 col5 col1 col6 col2 col7 col8 col9
    it never work as i save and get table. please tell what's wrong in below code.
    here are the codes-
    Table save code-
    try {
      Map<String, Map<String, Vector<Object>>> tableMap = new HashMap<String, Map<String, Vector<Object>>>();
      private static Map<String, Object> tables = new HashMap<String, Object>();
      Set<String> tabNames = tables.keySet();
      for (String tabName : tabNames) {
      JTable tab = (JTable) tables.get(tabName);
      Map<String, Vector<Object>> colNameValues = new HashMap<String, Vector<Object>>();
      Enumeration<TableColumn> tabCols = tab.getColumnModel()
      .getColumns();
      while (tabCols.hasMoreElements()) {
      Vector<Object> colums = new Vector<Object>();
      TableColumn col = tabCols.nextElement();
      int modelIndex = col.getModelIndex();
      int viewIndex = tab.convertColumnIndexToView(modelIndex);
      String field = Utils.toString(col.getIdentifier());
      Integer width = col.getWidth();
      if (isTableSelected) {
      boolean visible = !(viewIndex == -1 || col.getWidth() == 0);
      colums.add(visible); // pos 0 visible
      colums.add(field); // pos 1 field
      colums.add(width); // pos 2 width
      colums.add(modelIndex); // pos 3 model index
      colums.add(tab.convertColumnIndexToView(modelIndex)); // pos
      // 4
      // view
      // index
      colNameValues.put(field, colums);
      tableMap.put(tabName, colNameValues);
      if (dataStore.isColumnsSelected()) {
      if (personalizedDataStore != null) {
      Map<String, Map<String, Vector<Object>>> mapOld = personalizedDataStore
      .getInstructionTable();
      if (mapOld != null) {
      if (mapOld.size() > 0) {
      Set<String> oldTabNames = mapOld.keySet();
      for (String oldTabName : oldTabNames) {
      if (!tableMap.containsKey(oldTabName)) {
      tableMap.put(oldTabName,
      mapOld.get(oldTabName));
      dataStore.setInstructionTable(tableMap);
    code for get Table-
    private void applyPesonalizeSettings(String tabName, JTable tab) {
      if (!" ".equals(tabName)) {
      if (personalizedDataStore != null) {
      Map<String, Map<String, Vector<Object>>> oldTables = personalizedDataStore
      .getInstructionTable();
      for (int viewIndex = 0, count = tab.getRowCount(); viewIndex < count; viewIndex++) {
      if (oldTables != null) {
      Map<String, Vector<Object>> oldTabCols = oldTables
      .get(tabName);
      Enumeration<TableColumn> tableColumns = tab
      .getColumnModel().getColumns();
      while (tableColumns.hasMoreElements()) {
      TableColumn col = tableColumns.nextElement();
      String field = Utils.toString(col.getIdentifier());
      if (oldTabCols != null) {
      if (oldTabCols.containsKey(field)) {
      boolean vis = (Boolean) oldTabCols.get(field)
      .get(0);
      int prefWidth = (Integer) oldTabCols.get(field)
      .get(2);
      int modelInd = (Integer) oldTabCols.get(field)
      .get(3);
      int viewInd = (Integer) oldTabCols.get(field)
      .get(4);
      // setting visible
      if (!vis) {
      tab.getColumn(field).setMinWidth(0);
      tab.getColumn(field).setMaxWidth(0);
      tab.getColumn(field).setPreferredWidth(0);
      } else {
      // setting column width
      tab.getColumn(field).setPreferredWidth(
      prefWidth);
      // setting index
      if (modelInd != viewInd) {
      tab.moveColumn(
      tab.convertColumnIndexToView(modelInd),
      viewInd);
    here is the code for set table change property with popup-
    @Override
      protected void doOK() {
      Map<String, Vector<Object>> labelAndRow = new HashMap<String, Vector<Object>>();  //req 22
      for (int viewIndex = 0, count = super.getRowCount(); viewIndex < count; viewIndex++) {
      Vector<Object> row = super.getRow(viewIndex);
      boolean visible = (Boolean) row.get(0);
      String label = (String) row.get(1);
      String field = (String) row.get(2);
      labelAndRow.put(field,row); //req 22
      Integer modelIndex = (Integer) row.get(3);
      Integer width = (Integer) row.get(4);                              
      TableColumn col = jxtable.getColumn(field);
      if (visible) {
      if (width <= 0) {
      width = 75;
      if (width != col.getWidth()) {
      col.setMinWidth(15);
      col.setMaxWidth(1000);
      col.setPreferredWidth(width);
      } else {
      col.setMinWidth(0);
      col.setMaxWidth(0);
      col.setWidth(0);
      col.setPreferredWidth(0);
      col.setHeaderValue(label);
      jxtable.moveColumn(jxtable.convertColumnIndexToView(modelIndex), viewIndex);
      jxtable.moveColumn(jxtable.convertColumnIndexToView(modelIndex), viewIndex);
      super.dispose();
      for (TableColumn col : (List<TableColumn>) jxtable.getColumns()) {
      int modelIndex = col.getModelIndex();
      int viewIndex = jxtable.convertColumnIndexToView(modelIndex);
      String label = Utils.toString(col.getHeaderValue());
      String field = Utils.toString(col.getIdentifier());
      Integer width = col.getWidth();                       
      boolean visible = !(viewIndex == -1 || col.getWidth() == 0);
      dialog.getTableModel().addRow(new Object[]{visible, label, field, modelIndex, width});
      dialog.setVisible(true);

  • Problem in cell selection in JTable Java Swing

    hii
    I am using JTable that shows data from database. I have developed one functionality. I change one cell value and then select multiple cell. If I press F12 function key then it copies first selected value and past it to another selected cells. it is working properly but when I press F12 it sets the last selected cell in editable mode. I want that all cell which has been pasted should be selected (with default blue colour not in editing mode). I am using ListSelectionListener for JTable Cell Selection and KeyListener for F12 functionality.
    Please give some solution
    I can not override editCellAt Method because i have already extended JFrame. and i tried to do this with Jtable.getSelectedColumn and getSelectedRow it is displaying the same value, by this how can I get the particular area of selection means Row nd Column Selected.
    How would I know the current selection when user selects more than one cell???
    Thanks
    Edited by: 850979 on 11-Apr-2011 02:13
    Edited by: 850979 on 11-Apr-2011 03:59

    camickr wrote:
    Presumably, JTable installs an action for the F12 key that results in starting editing the last selected cell.
    There are no bindings for F12. See the [url http://www.camick.com/java/blog.html?name=key-bindings]Key Bindings listing. (...)
    Right.
    Of course it doesn't make sense that a F? key should invoke the editorI thought he meant F2 ("edit" on Windows), so that sounded natural.
    All KeyEvents are passed to the editor for the cell and the editor is psuedo invoked. That is, the caret is not placed on the text field used as the editor, but the character typed is added to the editor. You can then either use tab/enter to save the text or use the escape key to cancel the editing.Thanks for the explanation. I had never noticed (I kept on double-clicking my JTable cells when I wanted to edit them! :o)
    Of course it doesn't make sense that a F? key should invoke the editor, but this is a by product of all KeyEvents being forwarded so you don't have to have special Key Bindings for every character.You're right - as always.
    They (Sun) could have filtered out some of the keys such as those, though, because as noted by the OP the current behavior is unintuitive.
    To better control when the cell is editable based on the KeyEvent you can override the table with code like <snipped>
    As you suggested using a Key Binding will prevent this behaviour as well (but only for that key).Right again, but in this specific case that is acceptable (the developer wants to attach a specific behavior to a specific key only).
    OP here is an SSCCE of that second approach:
    public class TestKeyBindingsOnJTable {
        public static void main(String... args) {
            final DefaultTableModel dtm = new DefaultTableModel(new String[] {"A", "B"}, 0);
            dtm.addRow(new String[]{"A1", "B1"});
            dtm.addRow(new String[]{"A2", "B2"});
            dtm.addRow(new String[]{"A3", "B3"});
            JTable table = new JTable(dtm);
            table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0), "clear");
            table.getActionMap().put("clear", new AbstractAction() {
                public void actionPerformed(ActionEvent e) {
                    dtm.removeRow(0);
            JOptionPane.showMessageDialog(null, table);
    }Edited by: jduprez on Apr 8, 2011 9:36 PM

Maybe you are looking for

  • Solaris intel (x86) DCA not saving when rebooted.

    I'm working with a Panasonic CF-71 toughbook laptop. I have loaded the 2.6 Solaris intel OS and the Xig PCMCIA patch. I have been successful in getting a 3Com 3C589D card to work, but only if I enter into DCA at boot time and delete the PnP ISA PCMCI

  • Little problem with parallax

    i use for stage (this is responsive) width : with % heigth : with px i have in my compositionReady some fixebale element like that $("body").append($("#Stage_element").css("position", "fixed")); and function for parallax : yepnope({     load: "http:/

  • Custom barcode component not working properly

    package jpicedt.graphic.view; import jpicedt.graphic.model.*; // all elements + drawing import jpicedt.graphic.PECanvas; import jpicedt.graphic.PicPoint; import jpicedt.graphic.PicVector; import jpicedt.graphic.PEToolKit; import jpicedt.graphic.event

  • Can't use UTF-16 encoding with XML Parser for Java v2.

    This is my XML Document: <?xml version="1.0" encoding="UTF-16" ?> <Content> <Title>Documento de Prueba de gestin de contenidos.</Title> <Creator>Roberto P     rez Lita</Creator> </Content> This is the way in which i parse de document: DOMParser pars

  • Why File Name is Same Name as The Public Class Name

    Hi Friends, What is the reason for Naming the File Name is puvlic class name?? thanks in advance.