JTable: AUTO_RESIZE_OFF and setPreferredSize

Hi, I know this has been asked befre but i could find no answer. I have a JTable that I want to set each columns width. I have to use AUTO_RESIZE_OFF so that I get the scrollbar, but then my code to resize columns seems to make no change. I have also tried setMinWidth and setMinWidth but that did nothing.
Thanks
US101

TableColumn column = null;
String str = new String();
int width = 0;
for (int i = 0; i < columns.length; ++i) {
        str = columns;
     tblModel.addColumn(str);
     column = tbl.getColumnModel().getColumn(i);
     width = 10;
column.setPreferredWidth(width);
     column.setMinWidth(width);
     column.setMaxWidth(width);               
tbl.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
tbl is a JTable
columns[] is an array of table header names {"name", age"} etc...

Similar Messages

  • JTable, JScrollPane, and JinternalFrame problems.

    I have this internal frame in my application that has a scrollpane and table in it. Some how it won't let me selelct anything in the table. Also it scrolls really weird. There's a lot of chopping going on. Here's my code for the internal frame:
    public class BCDEObjectWindow extends javax.swing.JInternalFrame{
        private Vector bcdeObjects = new Vector();
        private DefaultTableModel tModel;
        public BCDEObjectWindow(JavaDrawApp p) {
            initComponents();
            this.setMaximizable(false);
            this.setClosable(false);
            this.setIconifiable(true);
            this.setDoubleBuffered(true);
            objectTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
            listScrollPane.setColumnHeaderView(new ObjectWindowHeader());
            pack();
            this.setVisible(true);
            parent = p;
            getAllBCDEFigures();
            setPopupMenu();
            tModel = (DefaultTableModel) objectTable.getModel();
            objectTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        public void getAllBCDEFigures() {
            bcdeObjects.removeAllElements();
            int i;
            for (i = 0; i < bcdeObjects.size(); i++) {
                tModel.removeRow(0);
        public void addBCDEFigure(BCDEFigure b) {
            bcdeObjects.add(b);
            tModel.addRow(new Object[]{b.BCDEName, "incomplete"});
        public void changeLabelName(BCDEFigure b) {
            if (bcdeObjects.contains(b)) {
                int index = bcdeObjects.indexOf(b);
                tModel.removeRow(index);
                tModel.insertRow(index, new Object[]{b.BCDEName, "incomplete"});
        public void removeBCDEFigure(BCDEFigure b) {
            int index = 0;
            if (bcdeObjects.contains(b)) {
                index = bcdeObjects.indexOf(b);
                bcdeObjects.remove(b);
                tModel.removeRow(index);
        public void removeAllBCDEFigures(){
            int i;
            for (i = 0; i < bcdeObjects.size(); i++) {
                tModel.removeRow(0);
            bcdeObjects.removeAllElements();
        /** 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() {
            jPanel1 = new javax.swing.JPanel();
            listScrollPane = new javax.swing.JScrollPane();
            objectTable = new javax.swing.JTable();
            getContentPane().setLayout(new java.awt.FlowLayout());
            setBackground(new java.awt.Color(255, 255, 255));
            setIconifiable(true);
            setTitle("BCDE Objects");
            listScrollPane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
            listScrollPane.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
            listScrollPane.setPreferredSize(new java.awt.Dimension(250, 150));
            objectTable.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                new String [] {
                    "Name", "Status"
                boolean[] canEdit = new boolean [] {
                    true, false
                public boolean isCellEditable(int rowIndex, int columnIndex) {
                    return canEdit [columnIndex];
            objectTable.setColumnSelectionAllowed(true);
            listScrollPane.setViewportView(objectTable);
            jPanel1.add(listScrollPane);
            getContentPane().add(jPanel1);
            pack();
        }// </editor-fold>
        // Variables declaration - do not modify
        private javax.swing.JPanel jPanel1;
        private javax.swing.JScrollPane listScrollPane;
        private javax.swing.JTable objectTable;
        // End of variables declaration
    }and this is how i create the object in my JFrame:
    bcdeOW = new BCDEObjectWindow(this);
            bcdeOW.setLocation(400, 0);
            if (getDesktop() instanceof JDesktopPane) {
                ((JDesktopPane)getDesktop()).setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
                ((JDesktopPane)getDesktop()).add(bcdeOW, JLayeredPane.PALETTE_LAYER);
            } else
                getDesktop().add(bcdeOW);Any help would be great. Thanks a lot.

    Rajb1 wrote:
    to get the table name to appear
    create a scollpane and put the table in the scrollpane and then add the the scollpane to the component:
    //declare
    scrollpane x;
    //body code
    scrollpane x - new scrollpane();
    table y = new table();
    getContentPane().add(x(y));What language is this in, the lambda calculus -- add(x(y))!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  • JTable: AUTO_RESIZE_OFF for Scrollbar, but fitting table in Container?

    Hi!
    I have a Panel extended from a JScrollPane and a JTable in it. I have set it to AUTO_RESIZE_OFF, because I want to have Scrollbars if the value in the column is larger than the view.
    How can I achieve it to resize the table if the window was resized?
    Thank you all for your postings.
    Regards, Robert

    Works fine for me:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=623692
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • Must click then click and drag for JTable Drag and Drop

    Hi All,
    I've been using Java 1.4 to drag and drop data between two tables in our application. Basically I need to drag the data from individual rows of the source table and insert it into one of the cells in the new table. This works absolutely fine and has made a huge improvement to this portion of our app. I've included example source code below that does a similar thing by transferring data from one table and inserting it into another (it's quite big and also not as well done as the example in our real app but unfortunately I can't send the source for that).
    The thing I've noticed though is that in order to start dragging data I need to click to select it and then press and hold the mouse button to start dragging, whereas under W**dows and just about every other OS you can just press and hold and start dragging straight away. If you try this with a JTable though it just changes the rows you have selected so the drag and drop works but feels a bit clunky and amateurish. I'd like to do something about this such that it works like Windows Explorer (or similar) where you can just press the mouse button and start dragging.
    Any help would be greatly appreciated - and if anybody finds the code useful you're more than welcome to it. Note that the business end of this is CustomTransferHandler.java - this will show you how to insert data at a specific position in a JTable, it's a bit of a faff but not too bad once you've got it sussed.
    Thanks,
    Bart Read
    ===============================================================
    TestFrame.java
    * TestFrame.java
    * Created on October 21, 2002, 4:59 PM
    import java.awt.*;
    import java.awt.datatransfer.*;
    import java.awt.dnd.*;
    import java.awt.event.*;
    import java.util.TooManyListenersException;
    import javax.swing.*;
    * @author  readb
    public class TestFrame extends javax.swing.JFrame
         private static final String [] NAMES     = {
              "John", "Geoff", "Madeleine", "Maria", "Flanders",
              "Homer", "Marge", "Bart", "Lisa", "Weird Baby" };
         private JTable source;
         private JTable dest;
         private MyTableModel     sourceModel;
         private MyTableModel     destModel;
         private Clipboard          clipboard;
         /** Creates a new instance of TestFrame */
         public TestFrame()
              clipboard = getToolkit().getSystemClipboard();
              Container c = getContentPane();
              c.setLayout( new BorderLayout( 40, 40 ) );
              source = new MyJTable();
              sourceModel = new MyTableModel();
              source.setModel( sourceModel );
              source.setDragEnabled( true );
              CustomTransferHandler handler = new CustomTransferHandler( "Source handler" );
              source.setTransferHandler( handler );
              try
                   source.getDropTarget().addDropTargetListener( handler );
              catch ( TooManyListenersException tmle )
                   tmle.printStackTrace();
              dest = new MyJTable();
              destModel = new MyTableModel();
              dest.setModel( destModel );
              dest.setDragEnabled( true );
              handler = new CustomTransferHandler( "Dest handler" );
              dest.setTransferHandler( handler );
              try
                   dest.getDropTarget().addDropTargetListener( handler );
              catch ( TooManyListenersException tmle )
                   tmle.printStackTrace();
              c.add( new JScrollPane( source ), BorderLayout.WEST );
              c.add( new JScrollPane( dest ), BorderLayout.EAST );
              populate();
         private void populate( MyTableModel model )
              for ( int index = 0; index < NAMES.length; ++index )
                   model.setRow( index, new DataRow( index + 1, NAMES[ index ] ) );
         private void populate()
              populate( sourceModel );
              populate( destModel );
         public static void main( String [] args )
              TestFrame app = new TestFrame();
              app.addWindowListener(
                   new WindowAdapter() {
                        public void windowClosing( WindowEvent we )
                             System.exit( 0 );
              app.pack();
              app.setSize( 1000, 600 );
              app.show();
         private class MyJTable extends JTable
              public boolean getScrollableTracksViewportHeight()
                   Component parent = getParent();
                   if (parent instanceof JViewport)
                        return parent.getHeight() > getPreferredSize().height;
                   return false;
    }=====================================================================
    MyTableModel.java
    * MyTableModel.java
    * Created on October 21, 2002, 4:43 PM
    import java.util.ArrayList;
    * @author  readb
    public class MyTableModel extends javax.swing.table.AbstractTableModel
         private static final int          NUMBER               = 0;
         private static final int          NAME               = 1;
         private static final String []     COLUMN_HEADINGS     = { "Number", "Name" };
         private ArrayList data;
         /** Creates a new instance of MyTableModel */
         public MyTableModel()
              super();
              data = new ArrayList();
         public int getColumnCount()
              return COLUMN_HEADINGS.length;
         public String getColumnName( int index )
              return COLUMN_HEADINGS[ index ];
         public Class getColumnClass( int index )
              switch ( index )
                   case NUMBER:
                        return Integer.class;
                   case NAME:
                        return String.class;
                   default:
                        throw new IllegalArgumentException( "Illegal column index: " + index );
         public int getRowCount()
              return ( null == data ? 0 : data.size() );
         public Object getValueAt( int row, int column )
              DataRow dataRow = ( DataRow ) data.get( row );
              switch ( column )
                   case NUMBER:
                        return new Integer( dataRow.getNumber() );
                   case NAME:
                        return dataRow.getName();
                   default:
                        throw new IllegalArgumentException( "Illegal column index: " + column );
         public void addRow( DataRow row )
              int rowIndex = data.size();
              data.add( row );
              fireTableRowsInserted( rowIndex, rowIndex );
         public void addRows( DataRow [] rows )
              int firstRow = data.size();
              for ( int index = 0; index < rows.length; ++index )
                   data.add( rows[ index ] );
              fireTableRowsInserted( firstRow, data.size() - 1 );
         public void setRow( int index, DataRow row )
              if ( index == data.size() )
                   data.add( row );
              else
                   data.set( index, row );
              fireTableRowsUpdated( index, index );
         public void insertRows( int index, DataRow [] rows )
              for ( int rowIndex = rows.length - 1; rowIndex >= 0; --rowIndex )
                   data.add( index, rows[ rowIndex ] );
              fireTableRowsInserted( index, index + rows.length - 1 );
         public DataRow getRow( int index )
              return ( DataRow ) data.get( index );
         public DataRow removeRow( int index )
              DataRow retVal = ( DataRow ) data.remove( index );
              fireTableRowsDeleted( index, index );
              return retVal;
         public boolean removeRow( DataRow row )
              int index = data.indexOf( row );
              boolean retVal = data.remove( row );
              fireTableRowsDeleted( index, index );
              return retVal;
         public void removeRows( DataRow [] rows )
              for ( int index = 0; index < rows.length; ++index )
                   data.remove( rows[ index ] );
              fireTableDataChanged();
    }=====================================================================
    DataRow.java
    * DataRow.java
    * Created on October 21, 2002, 4:41 PM
    import java.io.Serializable;
    * @author  readb
    public class DataRow implements Serializable
         private int          number;
         private String     name;
         /** Creates a new instance of DataRow */
         public DataRow( int number, String name )
              this.number = number;
              this.name = name;
         public int getNumber()
              return number;
         public String getName()
              return name;
         public String toString()
              return String.valueOf( number ) + ": " + name;
    }======================================================================
    CustomTransferHandler.java
    * CustomTransferHandler.java
    * Created on October 22, 2002, 8:36 AM
    import java.awt.*;
    import java.awt.datatransfer.Clipboard;
    import java.awt.datatransfer.ClipboardOwner;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.Transferable;
    import java.awt.datatransfer.UnsupportedFlavorException;
    import java.awt.dnd.*;
    import java.awt.event.InputEvent;
    import java.io.IOException;
    import java.util.Arrays;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JComponent;
    import javax.swing.JTable;
    import javax.swing.TransferHandler;
    * @author  readb
    public class CustomTransferHandler
                   extends TransferHandler
                   implements Transferable, ClipboardOwner, DropTargetListener
         public static final DataFlavor     ROW_ARRAY_FLAVOR     = new DataFlavor( DataRow[].class, "Multiple rows of data" );
         private String               name;
         private ImageIcon          myIcon;
         private     DataRow []          data;
         private boolean               clipboardOwner                    = false;
         private int                    rowIndex                         = -1;
         /** Creates a new instance of CustomTransferHandler */
         public CustomTransferHandler( String name )
              this.name = name;
         public boolean canImport( JComponent comp, DataFlavor [] transferFlavors )
              System.err.println( "CustomTransferHandler::canImport" );
              if ( comp instanceof JTable && ( ( JTable ) comp ).getModel() instanceof MyTableModel )
                   for ( int index = 0; index < transferFlavors.length; ++index )
                        if ( ! transferFlavors[ index ].equals( ROW_ARRAY_FLAVOR ) )
                             return false;
                   return true;
              else
                   return false;
         protected Transferable createTransferable( JComponent c )
              System.err.println( "CustomTransferHandler::createTransferable" );
              if ( ! ( c instanceof JTable ) || ! ( ( ( JTable ) c ).getModel() instanceof MyTableModel ) )
                   return null;
              this.data = null;
              JTable               table     = ( JTable ) c;
              MyTableModel     model     = ( MyTableModel ) table.getModel();
              Clipboard          cb          = table.getToolkit().getSystemClipboard();
              cb.setContents( this, this );
              clipboardOwner = true;
              int [] selectedRows = table.getSelectedRows();
              Arrays.sort( selectedRows );
              data = new DataRow[ selectedRows.length ];
              for ( int index = 0; index < data.length; ++index )
                   data[ index ] = model.getRow( selectedRows[ index ] );
              return this;
         public void exportAsDrag( JComponent comp, InputEvent e, int action )
              super.exportAsDrag( comp, e, action );
              Clipboard          cb          = comp.getToolkit().getSystemClipboard();
              cb.setContents( this, this );
         protected void exportDone( JComponent source, Transferable data, int action )
              System.err.println( "CustomTransferHandler::exportDone" );
              if ( TransferHandler.MOVE == action && source instanceof JTable && ( ( JTable ) source ).getModel() instanceof MyTableModel )
                   JTable table = ( JTable ) source;
                   MyTableModel model = ( MyTableModel ) table.getModel();
                   int [] selected = table.getSelectedRows();
                   for ( int index = selected.length - 1; index >= 0; --index )
                        model.removeRow( selected[ index ] );
         public void exportToClipboard( JComponent comp, Clipboard clip, int action )
              System.err.println( "CustomTransferHandler::exportToClipboard" );
         public int getSourceActions( JComponent c )
              System.err.println( "CustomTransferHandler::getSourceActions" );
              if ( ( c instanceof JTable ) && ( ( JTable ) c ).getModel() instanceof MyTableModel )
                   return MOVE;
              else
                   return NONE;
          *     I've commented this out because it doesn't appear to work in any case.
          *     The image isn't null but as far as I can tell this method is never
          *     invoked.
    //     public Icon getVisualRepresentation( Transferable t )
    //          System.err.println( "CustomTransferHandler::getVisualRepresentation" );
    //          if ( t instanceof CustomTransferHandler )
    //               if ( null == myIcon )
    //                    try
    //                         myIcon = new ImageIcon( getClass().getClassLoader().getResource( "dragimage.gif" ) );
    //                    catch ( Exception e )
    //                         System.err.println( "CustomTransferHandler::getVisualRepresentation: exception loading image" );
    //                         e.printStackTrace();
    //                    if ( null == myIcon )
    //                         System.err.println( "CustomTransferHandler::getVisualRepresentation: myIcon is still NULL" );
    //               return myIcon;
    //          else
    //               return null;
         public boolean importData( JComponent comp, Transferable t )
              System.err.println( "CustomTransferHandler::importData" );
              super.importData( comp, t );
              if ( ! ( comp instanceof JTable ) )
                   return false;
              if ( ! ( ( ( JTable ) comp ).getModel() instanceof MyTableModel ) )
                   return false;
              if ( clipboardOwner )
                   return false;
              if ( !t.isDataFlavorSupported( ROW_ARRAY_FLAVOR ) )
                   return false;
              try
                   data = ( DataRow [] ) t.getTransferData( ROW_ARRAY_FLAVOR );
                   return true;
              catch ( IOException ioe )
                   data = null;
                   return false;
              catch ( UnsupportedFlavorException ufe )
                   data = null;
                   return false;
         public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException
              System.err.println( "MyTransferable::getTransferData" );
              if ( flavor.equals( ROW_ARRAY_FLAVOR ) )
                   return data;
              else
                   throw new UnsupportedFlavorException( flavor );
         public DataFlavor[] getTransferDataFlavors()
              System.err.println( "MyTransferable::getTransferDataFlavors" );
              DataFlavor [] flavors = new DataFlavor[ 1 ];
              flavors[ 0 ] = ROW_ARRAY_FLAVOR;
              return flavors;
         public boolean isDataFlavorSupported( DataFlavor flavor )
              System.err.println( "MyTransferable::isDataFlavorSupported" );
              return flavor.equals( ROW_ARRAY_FLAVOR );
         public void lostOwnership( Clipboard clipboard, Transferable transferable )
              clipboardOwner = false;
         /** Called while a drag operation is ongoing, when the mouse pointer enters
          * the operable part of the drop site for the <code>DropTarget</code>
          * registered with this listener.
          * @param dtde the <code>DropTargetDragEvent</code>
         public void dragEnter(DropTargetDragEvent dtde)
         /** Called while a drag operation is ongoing, when the mouse pointer has
          * exited the operable part of the drop site for the
          * <code>DropTarget</code> registered with this listener.
          * @param dte the <code>DropTargetEvent</code>
         public void dragExit(DropTargetEvent dte)
         /** Called when a drag operation is ongoing, while the mouse pointer is still
          * over the operable part of the drop site for the <code>DropTarget</code>
          * registered with this listener.
          * @param dtde the <code>DropTargetDragEvent</code>
         public void dragOver(DropTargetDragEvent dtde)
         /** Called when the drag operation has terminated with a drop on
          * the operable part of the drop site for the <code>DropTarget</code>
          * registered with this listener.
          * <p>
          * This method is responsible for undertaking
          * the transfer of the data associated with the
          * gesture. The <code>DropTargetDropEvent</code>
          * provides a means to obtain a <code>Transferable</code>
          * object that represents the data object(s) to
          * be transfered.<P>
          * From this method, the <code>DropTargetListener</code>
          * shall accept or reject the drop via the
          * acceptDrop(int dropAction) or rejectDrop() methods of the
          * <code>DropTargetDropEvent</code> parameter.
          * <P>
          * Subsequent to acceptDrop(), but not before,
          * <code>DropTargetDropEvent</code>'s getTransferable()
          * method may be invoked, and data transfer may be
          * performed via the returned <code>Transferable</code>'s
          * getTransferData() method.
          * <P>
          * At the completion of a drop, an implementation
          * of this method is required to signal the success/failure
          * of the drop by passing an appropriate
          * <code>boolean</code> to the <code>DropTargetDropEvent</code>'s
          * dropComplete(boolean success) method.
          * <P>
          * Note: The data transfer should be completed before the call  to the
          * <code>DropTargetDropEvent</code>'s dropComplete(boolean success) method.
          * After that, a call to the getTransferData() method of the
          * <code>Transferable</code> returned by
          * <code>DropTargetDropEvent.getTransferable()</code> is guaranteed to
          * succeed only if the data transfer is local; that is, only if
          * <code>DropTargetDropEvent.isLocalTransfer()</code> returns
          * <code>true</code>. Otherwise, the behavior of the call is
          * implementation-dependent.
          * <P>
          * @param dtde the <code>DropTargetDropEvent</code>
         public void drop(DropTargetDropEvent dtde)
              System.err.println( "CustomTransferHandler::drop" );
              Component c = dtde.getDropTargetContext().getDropTarget().getComponent();
              if ( ! ( c instanceof JComponent ) )
                   dtde.rejectDrop();
                   return;
              JComponent comp = ( JComponent ) c;
              if ( ! ( c instanceof JTable ) || ! ( ( ( JTable ) c ).getModel() instanceof MyTableModel ) )
                   dtde.rejectDrop();
                   return;
              dtde.acceptDrop( TransferHandler.MOVE );
              //     THIS is such a mess -- you can't do the following because
              //     getTransferable() throws an (undocumented) exception - what's that
              //     all about.
    //          Transferable t = dtde.getTransferable();
    //               if ( !t.isDataFlavourSupported( ROW_ARRAY_FLAVOR ) )
    //                    dtde.rejectDrop();
    //                    return false;
    //          TransferHandler handler = comp.getTransferHandler();
    //          if ( null == handler || ! handler.importData( comp, t ) )
    //               dtde.rejectDrop();
    //               return;
              Point p = dtde.getLocation();
              JTable table = ( JTable ) comp;
              rowIndex = table.rowAtPoint( p );
              //     So you have to do this instead and use the data that's been
              //     stored in the data member via import data.  Total mess.
              if ( null == data )
                   dtde.rejectDrop();
                   return;
              MyTableModel model = ( MyTableModel ) table.getModel();
              if ( rowIndex == -1 )
                   model.addRows( data );
              else
                   model.insertRows( rowIndex, data );
              dtde.acceptDrop( TransferHandler.MOVE );
         /** Called if the user has modified
          * the current drop gesture.
          * <P>
          * @param dtde the <code>DropTargetDragEvent</code>
         public void dropActionChanged(DropTargetDragEvent dtde)
    }

    Hi again,
    Well I've tried using the MouseListener / MouseMotionListener approach but it doesn't quite seem to work, although it does get the events correctly. I think the reason is that it doesn't interact correctly with the Java DnD machinery which is something that V.V hinted at. It's something that I may need to look into if / when I have more time available.
    I have to say though that I haven't had any problems with scrollbars - we're making fairly heavy use of large tables and if you drag over a table with a scroll bar and move to the top or bottom then it scrolls as you would expect and allows you to drop the data where you like. For this situation I've used pretty much the same approach as for the toy example above except that I've implemented separate source and destination TransferHandlers (the source table is read-only, and it really doesn't make sense to allow people to drag from the destination table so I've essentially split the functionality of the example handler down the middle).
    I'm not actually particularly in favour of messing too much with the mechanics of DnD, more because of lack of time than anything else. Guess I'll just have to put up with this for the moment. Doesn't help that DnD is so poorly documented by Sun.
    Thanks for all your help.
    Bart

  • JTable sorting and filtering

    I want to sort and Filter JTable.
    Sample code is avialable for this ?.
    Also i would like to know about 3rd party classes.
    Renjith

    Hi,
    There is a such sample on the tutorials for swing/JTable. In this tutorial, u will find 2 files and then make the corresponding classes :
    TableMap and TableSorter
    u can use them like this :
    TableSorter sorter = new TableSorter(myModel);
    //JTable table = new JTable(myModel); //OLD
    JTable table = new JTable(sorter);
    sorter.addMouseListenerToHeaderInTable(table);
    It is very simple, and you can easily modifie these classes to add filters..
    Regards, JFB

  • Nested sub-header (Groupable Header) JTable Example and JDK 1.5

    There is an old Nobuo Tamemasa example of making a JTable with grouped column headers at:
    http://www.codeguru.com/java/articles/124.shtml
    I made a couple of minor mods to get it to run under JDK 1.4. It works like a charm. If I run the same code under JDK 1.5.1, only the lowest level column headers are painted.
    Has anyone noticed this and come up with a fix?
    Here are the 4 classes (with my minor mods) required to run the test...
    package GroupableColumnTable;
    //File: ColumnGroup.java
    * (swing1.1beta3)
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
      * ColumnGroup
      * @version 1.0 10/20/98
      * @author Nobuo Tamemasa
    public class ColumnGroup {
      protected TableCellRenderer renderer;
      protected Vector v;
      protected String text;
      protected int margin=0;
      public ColumnGroup(String text) {
         this(null,text);
      public ColumnGroup(TableCellRenderer renderer,String text) {
         if (renderer == null) {
           this.renderer = new DefaultTableCellRenderer() {
             public Component getTableCellRendererComponent(JTable table, Object value,
                        boolean isSelected, boolean hasFocus, int row, int column) {
               JTableHeader header = table.getTableHeader();
               if (header != null) {
              setForeground(header.getForeground());
              setBackground(header.getBackground());
              setFont(header.getFont());
               setHorizontalAlignment(JLabel.CENTER);
               setText((value == null) ? "" : value.toString());
               setBorder(UIManager.getBorder("TableHeader.cellBorder"));
               return this;
         } else {
           this.renderer = renderer;
         this.text = text;
         v = new Vector();
       * @param obj    TableColumn or ColumnGroup
      public void add(Object obj) {
         if (obj == null) { return; }
         v.addElement(obj);
       * @param c    TableColumn
       * @param v    ColumnGroups
      public Vector getColumnGroups(TableColumn c, Vector g) {
         g.addElement(this);
         if (v.contains(c)) return g;     
         Enumeration enum = v.elements();
         while (enum.hasMoreElements()) {
           Object obj = enum.nextElement();
           if (obj instanceof ColumnGroup) {
             Vector groups =
               (Vector)((ColumnGroup)obj).getColumnGroups(c,(Vector)g.clone());
             if (groups != null) return groups;
         return null;
      public TableCellRenderer getHeaderRenderer() {
         return renderer;
      public void setHeaderRenderer(TableCellRenderer renderer) {
         if (renderer != null) {
           this.renderer = renderer;
      public Object getHeaderValue() {
         return text;
      public Dimension getSize(JTable table) {
         Component comp = renderer.getTableCellRendererComponent(
             table, getHeaderValue(), false, false,-1, -1);
         int height = comp.getPreferredSize().height;
         int width  = 0;
         Enumeration enum = v.elements();
         while (enum.hasMoreElements()) {
           Object obj = enum.nextElement();
           if (obj instanceof TableColumn) {
             TableColumn aColumn = (TableColumn)obj;
             width += aColumn.getWidth();
             width += margin;
           } else {
             width += ((ColumnGroup)obj).getSize(table).width;
         return new Dimension(width, height);
      public void setColumnMargin(int margin) {
         this.margin = margin;
         Enumeration enum = v.elements();
         while (enum.hasMoreElements()) {
           Object obj = enum.nextElement();
           if (obj instanceof ColumnGroup) {
             ((ColumnGroup)obj).setColumnMargin(margin);
    package GroupableColumnTable;
    //File: GroupableHeaderExample.java
    /* (swing1.1beta3)
    * |-----------------------------------------------------|
    * |     |     Name       |         Language          |
    * |     |-----------------|--------------------------|
    * |  SNo.     |      |       |        |       Others     |
    * |     |   1      |    2   | Native |-----------------|
    * |     |      |       |        |   2    |     3    |     
    * |-----------------------------------------------------|
    * |     |      |       |        |         |          |
    //package jp.gr.java_conf.tame.swing.examples;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    * @version 1.0 11/09/98
    public class GroupableHeaderExample extends JFrame {
      GroupableHeaderExample() {
         super( "Groupable Header Example" );
        DefaultTableModel dm = new DefaultTableModel();
         dm.setDataVector(new Object[][]{
           {"119","foo","bar","ja","ko","zh"},
           {"911","bar","foo","en","fr","pt"}},
         new
    Object[]{"SNo.","1","2","Native","2","3"});
        JTable table = new JTable( dm ) {
           protected JTableHeader createDefaultTableHeader() {
             return new GroupableTableHeader(columnModel);
         TableColumnModel cm = table.getColumnModel();
         ColumnGroup g_name = new ColumnGroup("Name");
         g_name.add(cm.getColumn(1));
         g_name.add(cm.getColumn(2));
         ColumnGroup g_lang = new ColumnGroup("Language");
         g_lang.add(cm.getColumn(3));
         ColumnGroup g_other = new ColumnGroup("Others");
         g_other.add(cm.getColumn(4));
         g_other.add(cm.getColumn(5));
         g_lang.add(g_other);
         GroupableTableHeader header = (GroupableTableHeader)table.getTableHeader();
         header.addColumnGroup(g_name);
         header.addColumnGroup(g_lang);
         JScrollPane scroll = new JScrollPane( table );
         getContentPane().add( scroll );
         setSize( 400, 120 );  
      public static void main(String[] args) {
         GroupableHeaderExample frame = new GroupableHeaderExample();
         frame.addWindowListener( new WindowAdapter() {
           public void windowClosing( WindowEvent e ) {
             System.exit(0);
         frame.setVisible(true);
    package GroupableColumnTable;
    //File: GroupableTableHeader.java
    * (swing1.1beta3)
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
      * GroupableTableHeader
      * @version 1.0 10/20/98
      * @author Nobuo Tamemasa
    public class GroupableTableHeader extends JTableHeader {
      private static final String uiClassID = "GroupableTableHeaderUI";
      protected Vector columnGroups = null;
      public GroupableTableHeader(TableColumnModel model) {
         super(model);
         setUI(new GroupableTableHeaderUI());
         setReorderingAllowed(false);
      public void setReorderingAllowed(boolean b) {
         reorderingAllowed = false;
      public void addColumnGroup(ColumnGroup g) {
         if (columnGroups == null) {
           columnGroups = new Vector();
         columnGroups.addElement(g);
      public Enumeration getColumnGroups(TableColumn col) {
         if (columnGroups == null) return null;
         Enumeration enum = columnGroups.elements();
         while (enum.hasMoreElements()) {
           ColumnGroup cGroup = (ColumnGroup)enum.nextElement();
           Vector v_ret = (Vector)cGroup.getColumnGroups(col,new Vector());
           if (v_ret != null) {
             return v_ret.elements();
         return null;
      public void setColumnMargin() {
         if (columnGroups == null) return;
         int columnMargin = getColumnModel().getColumnMargin();
         Enumeration enum = columnGroups.elements();
         while (enum.hasMoreElements()) {
           ColumnGroup cGroup = (ColumnGroup)enum.nextElement();
           cGroup.setColumnMargin(columnMargin);
    package GroupableColumnTable;
    //File: GroupableTableHeaderUI.java
    * (swing1.1beta3)
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.plaf.basic.*;
    public class GroupableTableHeaderUI extends BasicTableHeaderUI {
      public void paint(Graphics g, JComponent c) {
         Rectangle clipBounds = g.getClipBounds();
         if (header.getColumnModel() == null) return;
         ((GroupableTableHeader)header).setColumnMargin();
         int column = 0;
         Dimension size = header.getSize();
         Rectangle cellRect  = new Rectangle(0, 0, size.width, size.height);
         Hashtable h = new Hashtable();
         int columnMargin = header.getColumnModel().getColumnMargin();
         Enumeration enumeration = header.getColumnModel().getColumns();
         while (enumeration.hasMoreElements()) {
           cellRect.height = size.height;
           cellRect.y       = 0;
           TableColumn aColumn = (TableColumn)enumeration.nextElement();
           Enumeration cGroups = ((GroupableTableHeader)header).getColumnGroups(aColumn);
           if (cGroups != null) {
             int groupHeight = 0;
             while (cGroups.hasMoreElements()) {
               ColumnGroup cGroup = (ColumnGroup)cGroups.nextElement();
               Rectangle groupRect = (Rectangle)h.get(cGroup);
               if (groupRect == null) {
              groupRect = new Rectangle(cellRect);
              Dimension d = cGroup.getSize(header.getTable());
              groupRect.width  = d.width;
              groupRect.height = d.height;     
              h.put(cGroup, groupRect);
               paintCell(g, groupRect, cGroup);
               groupHeight += groupRect.height;
               cellRect.height = size.height - groupHeight;
               cellRect.y      = groupHeight;
           cellRect.width = aColumn.getWidth() + columnMargin;
           if (cellRect.intersects(clipBounds)) {
             paintCell(g, cellRect, column);
           cellRect.x += cellRect.width;
           column++;
      private void paintCell(Graphics g, Rectangle cellRect, int columnIndex) {
         TableColumn aColumn = header.getColumnModel().getColumn(columnIndex);
         TableCellRenderer renderer = header.getDefaultRenderer ();
         Component component = renderer.getTableCellRendererComponent(
           header.getTable(), aColumn.getHeaderValue(),false, false, -1, columnIndex);
         rendererPane.add(component);
         rendererPane.paintComponent(g, component, header, cellRect.x, cellRect.y,
                            cellRect.width, cellRect.height, true);
      private void paintCell(Graphics g, Rectangle cellRect,ColumnGroup cGroup) {
         TableCellRenderer renderer = cGroup.getHeaderRenderer();
         Component component = renderer.getTableCellRendererComponent(
           header.getTable(), cGroup.getHeaderValue(),false, false, -1, -1);
         rendererPane.add(component);
         rendererPane.paintComponent(g, component, header, cellRect.x, cellRect.y,
                            cellRect.width, cellRect.height, true);
      private int getHeaderHeight() {
         int height = 0;
         TableColumnModel columnModel = header.getColumnModel();
         for(int column = 0; column < columnModel.getColumnCount(); column++) {
           TableColumn aColumn = columnModel.getColumn(column);
           TableCellRenderer renderer = header.getDefaultRenderer();
           Component comp = renderer.getTableCellRendererComponent(
             header.getTable(), aColumn.getHeaderValue(), false, false,-1, column);
           int cHeight = comp.getPreferredSize().height;
           Enumeration enum = ((GroupableTableHeader)header).getColumnGroups(aColumn);       
           if (enum != null) {
             while (enum.hasMoreElements()) {
               ColumnGroup cGroup = (ColumnGroup)enum.nextElement();
               cHeight += cGroup.getSize(header.getTable()).height;
           height = Math.max(height, cHeight);
         return height;
      private Dimension createHeaderSize(long width) {
         TableColumnModel columnModel = header.getColumnModel();
         width += columnModel.getColumnMargin() * columnModel.getColumnCount();
         if (width > Integer.MAX_VALUE) {
           width = Integer.MAX_VALUE;
         return new Dimension((int)width, getHeaderHeight());
      public Dimension getPreferredSize(JComponent c) {
         long width = 0;
         Enumeration enumeration = header.getColumnModel().getColumns();
         while (enumeration.hasMoreElements()) {
           TableColumn aColumn = (TableColumn)enumeration.nextElement();
           width = width + aColumn.getPreferredWidth();
         return createHeaderSize(width);
    }

    To anyone interested
    I came across this example today, and had the same problem too.
    The solution is very simple:
    The main problem is that GroupableTableHeader UI is set on its constructor, and it should be on the overriden method for that purpose.
    Here is the solution:
    1. remove
    setUI (new GroupableTableHeaderUI ());from the constructor
    2. override the method
    public void setUI (javax.swing.plaf.TableHeaderUI ui) {
    super.setUI (new GroupableTableHeaderUI ());
    }in this class.
    Now it is only need to get column width fixed because of borders in the header, as the example dun take this into account...
    Hope this helps, the same way as many other posts had help me to solve other problems;) and sorry for any spelling or grammar error.

  • Remove JTable row and column in one event

    Hello,
    I 've using matrix table in one application.
    i need to remove both column and row in single event.
    For this i construct
    JTable(data[][], header[]);
    because dynamically increase data's and header's
    What can i do for this?

    Create a method that does:
    DefaultTableModel model = (DefaultTableModel)table.getModel();
    model.removeRow(...)
    model.setRowCount(...)
    Read the DefaultTableModel API for more information.

  • Urgent Regarding Jtable TAB and Arrow keys

    Hi guys and gals,
    In my project i need urgnet help regarding Jtable.I want to use DOWN ARROW key same as TAB function.When i reach the first row last editing coulmn by using arrow key,then i habe to creating a new row with default values.And if press UP key if that row contains no values i have to delete.Plz help me in this regard.
    sreeni

    I meant that the laptop freezes in gdm and in console (tty1). In gdm i can't even type any character. And in console i can login but when i press the tab key (autocompletation) it stops. The only thing i can do is press the power button.
    Actually my keymap is es_ES. And i think that it's working fine because the n tilde and pipes work fine.

  • Dates in Jtable - tried and tried and tried

    I have a table cell renderer to handle the date fields as follows.
    The dates appear MM/dd/yyyy when the table is loaded as I want.
    SimpleDateFormat cdnDate = new SimpleDateFormat("MM/dd/yyyy");
    if (((Vector)fieldInfo.elementAt(i)).elementAt(2).equals ("DATE")) {
          // set format for date display
         column = PassportTable.getColumnModel().getColumn(i);
         // Now get column renderer
         // and set cell renderer for column
         column.setCellRenderer(new DefaultTableCellRenderer() {
              public Component getTableCellRendererComponent(JTable table,
    Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                   Component renderer = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                    // Create and put formatted date in cell
                   setText(cdnDate.format((java.util.Date)value));
                   return renderer;
    );The problem I have is I cannot get the date that appears as the user edits the field
    in this format. I have got yyyy-MM-dd for example the cell shows "01/01/1900"
    when the user starts to edit the field "1900-01-01" appears. I have managed
    to make a variety of different formats appear but never the one I want.
    I have tried the many variations of the following two methods to edit a date in a table cell.
    Nothing I have tried has worked.
    public void setUpDateEditor(JTable table) {
         //Set up the editor for the date cells.
         try {
              String str = "01/01/1900";
              java.util.Date passDate = cdnDate.parse(str);
              final LimitedDateField dateField = new LimitedDateField(passDate);
              DefaultCellEditor dateEditor = new DefaultCellEditor(dateField) {
                   public Object getCellEditorValue() { // return a date
                        //return new java.util.Date(dateField.getValue()); //no compile
                        return dateField.getValue();
              table.setDefaultEditor(java.util.Date.class, dateEditor);
         catch (Exception showUpdatelEx) {}
    Where my LimitedDateField class is as follows:public class LimitedDateField extends JTextField implements GlobalInterface {
         private Toolkit toolkit;
         private SimpleDateFormat cdnDate = new SimpleDateFormat("MM/dd/yyyy");
         private char slaSign = '/';
         private int columnLimit;
         private java.util.Date retVal;
         public LimitedDateField(java.util.Date value) {
              //super(columns);
              columnLimit = 11;
              toolkit = Toolkit.getDefaultToolkit();
              setDocument(new DateDocument());
              setValue(value);
         public java.util.Date getValue() {
              String str = "01/01/1900";
              try {
                   // retVal = cdnDate.parse(str);
                   retVal = cdnDate.parse(getText());
              catch (ParseException e) {Toolkit.getDefaultToolkit().beep();}
              return retVal;
         public void setValue(java.util.Date value) {
              setText(cdnDate.format(value));
         protected class DateDocument extends PlainDocument {
              public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
                   char[] source = str.toCharArray();               
                   char[] result = new char[source.length];
                   char[] hResult = new char[source.length]; // save
                   int j = 0;
                   if (super.getLength() > columnLimit - 1){toolkit.beep();}
                   else {
                        for (int i = 0; i < result.length; i++) {
                             if (Character.isDigit(source)) {result[j++] = source[i];}
                             else if (source[i] == slaSign) {result[j++] = source[i];}
                             else {toolkit.beep();}
    When this failed I tried something simpler - to no avail.
    public void setUpDateEditor(JTable table) {
         //Set up the editor for the date cells.
         try {
              SimpleDateFormat cdnDate = new SimpleDateFormat("MM/dd/yyyy");
              DateFormatter df = new DateFormatter(cdnDate);
              JFormattedTextField ftf1 = new JFormattedTextField(df);
         catch (Exception showUpdatelEx) {}Any suggestions????
    Thanks
    rykk

    Try again as Format code missing
    I have a table cell renderer to handle the date fields as follows.
    The dates appear MM/dd/yyyy when the table is loaded as I want.
    SimpleDateFormat cdnDate = new SimpleDateFormat("MM/dd/yyyy");
    if (((Vector)fieldInfo.elementAt(i)).elementAt(2).equals ("DATE")) {
          // set format for date display
         column = PassportTable.getColumnModel().getColumn(i);
         // Now get column renderer
         // and set cell renderer for column
         column.setCellRenderer(new DefaultTableCellRenderer() {
              public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                   Component renderer = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                    // Create and put formatted date in cell
                   setText(cdnDate.format((java.util.Date)value));
                   return renderer;
    );The problem I have is I cannot get the date that appears as the user edits the field
    in this format. I have got yyyy-MM-dd for example the cell shows "01/01/1900"
    when the user starts to edit the field "1900-01-01" appears. I have managed
    to make a variety of different formats appear but never the one I want.
    I have tried the many variations of the following two methods to edit a date in a table cell.
    Nothing I have tried has worked.
    public void setUpDateEditor(JTable table) {
         //Set up the editor for the date cells.
         try {
              String str = "01/01/1900";
              java.util.Date passDate = cdnDate.parse(str);
              final LimitedDateField dateField = new LimitedDateField(passDate);
              DefaultCellEditor dateEditor = new DefaultCellEditor(dateField) {
                   public Object getCellEditorValue() { // return a date
                        //return new java.util.Date(dateField.getValue()); //no compile
                        return dateField.getValue();
              table.setDefaultEditor(java.util.Date.class, dateEditor);
         catch (Exception showUpdatelEx) {}
    }Where my LimitedDateField class is as follows:
    public class LimitedDateField extends JTextField implements GlobalInterface {
         private Toolkit toolkit;
         private SimpleDateFormat cdnDate = new SimpleDateFormat("MM/dd/yyyy");
         private char slaSign = '/';
         private int columnLimit;
         private java.util.Date retVal;
         public LimitedDateField(java.util.Date value) {
              //super(columns);
              columnLimit = 11;
              toolkit = Toolkit.getDefaultToolkit();
              setDocument(new DateDocument());
              setValue(value);
         public java.util.Date getValue() {
              String str = "01/01/1900";
              try {
                   // retVal = cdnDate.parse(str);
                   retVal = cdnDate.parse(getText());
              catch (ParseException e) {Toolkit.getDefaultToolkit().beep();}
              return retVal;
         public void setValue(java.util.Date value) {
              setText(cdnDate.format(value));
         protected class DateDocument extends PlainDocument {
              public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
                   char[] source = str.toCharArray();               
                   char[] result = new char[source.length];
                   char[] hResult = new char[source.length]; // save
                   int j = 0;
                   if (super.getLength() > columnLimit - 1){toolkit.beep();}
                   else {
                        for (int i = 0; i < result.length; i++) {
                             if (Character.isDigit(source)) {result[j++] = source[i];}
                             else if (source[i] == slaSign) {result[j++] = source[i];}
                             else {toolkit.beep();}
    When this failed I tried something simpler - to no avail.
    public void setUpDateEditor(JTable table) {
         //Set up the editor for the date cells.
         try {
              SimpleDateFormat cdnDate = new SimpleDateFormat("MM/dd/yyyy");
              DateFormatter df = new DateFormatter(cdnDate);
              JFormattedTextField ftf1 = new JFormattedTextField(df);
         catch (Exception showUpdatelEx) {}Any suggestions????
    Thanks
    rykk

  • JTABLE INPUT AND OUTPUT...ALMOST WORKING! PLZ HELP!

    Here's my program. Please try it out for yourself first, PLEASE. And do the following when you run it:
    1) Click the modify entries button (the table displays perfectly).
    3) Click the back button.
    4) Click the modify entries button AGAIN.
    5) WHY WON'T THE TABLE SHOW UP?
    PLEASE HELP MY CPT IS DUE TOMORROW!
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.DefaultTableModel;
    import java.util.*;
    import java.io.*;
    public class CPT extends JPanel implements ActionListener
        JButton ModifyEntriesButton, ViewEntriesButton, SearchEntriesButton, SaveButton, BackButton, AddRowButton;
        JLabel SplashLabel;
        JTable contentTable;
        String aLine;
        Vector columnNames = new Vector ();
        Vector data = new Vector ();
        DefaultTableModel model = new DefaultTableModel (data, columnNames);
        public void createTable ()
            try
                FileInputStream fileInput = new FileInputStream ("entries.data");
                BufferedReader DBInput = new BufferedReader (new InputStreamReader (fileInput));
                StringTokenizer st1 = new StringTokenizer (DBInput.readLine (), "|");
                while (st1.hasMoreTokens ())
                    columnNames.addElement (st1.nextToken ());
                while ((aLine = DBInput.readLine ()) != null)
                    StringTokenizer st2 = new StringTokenizer (aLine, "|");
                    Vector row = new Vector ();
                    while (st2.hasMoreTokens ())
                        row.addElement (st2.nextToken ());
                    data.addElement (row);
                DBInput.close ();
            catch (Exception e)
                e.printStackTrace ();
        public CPT ()
            setLayout (null);
            ImageIcon splashimage = createImageIcon ("logo.JPG", "Swisha Computer House");
            SplashLabel = new JLabel ("Image and Text", splashimage, JLabel.CENTER);
            ModifyEntriesButton = new JButton ("Modify Entries");
            ModifyEntriesButton.setVerticalTextPosition (AbstractButton.TOP);
            ModifyEntriesButton.setHorizontalTextPosition (AbstractButton.LEFT);
            ModifyEntriesButton.setToolTipText ("Click this button to modify database entries.");
            ModifyEntriesButton.setMnemonic (KeyEvent.VK_M);
            ModifyEntriesButton.setActionCommand ("ModifyEntries");
            ModifyEntriesButton.addActionListener (this);
            ViewEntriesButton = new JButton ("View Entries");
            ViewEntriesButton.setVerticalTextPosition (AbstractButton.CENTER);
            ViewEntriesButton.setHorizontalTextPosition (AbstractButton.LEFT);
            ViewEntriesButton.setToolTipText ("Click this button to add view all database entries.");
            ViewEntriesButton.setMnemonic (KeyEvent.VK_V);
            ViewEntriesButton.setActionCommand ("ViewEntries");
            ViewEntriesButton.addActionListener (this);
            SearchEntriesButton = new JButton ("Search Entries");
            SearchEntriesButton.setVerticalTextPosition (AbstractButton.BOTTOM);
            SearchEntriesButton.setHorizontalTextPosition (AbstractButton.LEFT);
            SearchEntriesButton.setToolTipText ("Click this button to search through all database entries.");
            SearchEntriesButton.setMnemonic (KeyEvent.VK_S);
            SearchEntriesButton.setActionCommand ("SearchEntries");
            SearchEntriesButton.addActionListener (this);
            SaveButton = new JButton ("Save");
            SaveButton.setVerticalTextPosition (AbstractButton.TOP);
            SaveButton.setHorizontalTextPosition (AbstractButton.RIGHT);
            SaveButton.setToolTipText ("Click this button to save database entries.");
            SaveButton.setMnemonic (KeyEvent.VK_S);
            SaveButton.setActionCommand ("Save");
            SaveButton.addActionListener (this);
            BackButton = new JButton ("Back");
            BackButton.setVerticalTextPosition (AbstractButton.BOTTOM);
            BackButton.setHorizontalTextPosition (AbstractButton.RIGHT);
            BackButton.setToolTipText ("Click this button to return to the main menu.");
            BackButton.setMnemonic (KeyEvent.VK_B);
            BackButton.setActionCommand ("Back");
            BackButton.addActionListener (this);
            AddRowButton = new JButton ("Add Row");
            AddRowButton.setVerticalTextPosition (AbstractButton.BOTTOM);
            AddRowButton.setHorizontalTextPosition (AbstractButton.RIGHT);
            AddRowButton.setToolTipText ("Click this button to add a row.");
            AddRowButton.setMnemonic (KeyEvent.VK_A);
            AddRowButton.setActionCommand ("AddRow");
            AddRowButton.addActionListener (this);
            SplashLabel.setSize (250, 195);
            SplashLabel.setLocation (20, -25);
            add (SplashLabel);
            ModifyEntriesButton.setSize (250, 30);
            ModifyEntriesButton.setLocation (20, 140);
            add (ModifyEntriesButton);
            ViewEntriesButton.setSize (250, 30);
            ViewEntriesButton.setLocation (20, 170);
            add (ViewEntriesButton);
            SearchEntriesButton.setSize (250, 30);
            SearchEntriesButton.setLocation (20, 200);
            add (SearchEntriesButton);
        public void actionPerformed (ActionEvent e)
            if ("ModifyEntries".equals (e.getActionCommand ()))
                removeAll ();
                createTable ();
                JTable modifyTable = new JTable (model);
                JScrollPane tableScroll = new JScrollPane (modifyTable);
                tableScroll.setSize (250, 120);
                tableScroll.setLocation (20, 20);
                add (tableScroll);
                AddRowButton.setSize (250, 30);
                AddRowButton.setLocation (20, 140);
                add (AddRowButton);
                SaveButton.setSize (250, 30);
                SaveButton.setLocation (20, 170);
                add (SaveButton);
                BackButton.setSize (250, 30);
                BackButton.setLocation (20, 200);
                add (BackButton);
                updateUI ();
            if ("ViewEntries".equals (e.getActionCommand ()))
                removeAll ();
                BackButton.setLocation (20, 200);
                add (BackButton);
                updateUI ();
            if ("SearchEntries".equals (e.getActionCommand ()))
                removeAll ();
                BackButton.setLocation (20, 200);
                add (BackButton);
                updateUI ();
            if ("Back".equals (e.getActionCommand ()))
                removeAll ();
                add (ModifyEntriesButton);
                add (ViewEntriesButton);
                add (SearchEntriesButton);
                add (SplashLabel);
                updateUI ();
            if ("AddRow".equals (e.getActionCommand ()))
                model.addRow (new Vector ());
            if ("Save".equals (e.getActionCommand ()))
        // Creates the GUI and shows it.
        // For thread safety, this method should be invoked from the event-dispatching thread.
        private static void createAndShowGUI ()
            //Window decorations.
            JFrame.setDefaultLookAndFeelDecorated (true);
            //Create and set up the window.
            JFrame frame = new JFrame ("Swisha Computer House");
            frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
            frame.setResizable (false);
            //Create and set up the content pane.
            JComponent newContentPane = new CPT ();
            newContentPane.setOpaque (true); //Content panes must be opaque.
            frame.setContentPane (newContentPane);
            //Displays the window.
            frame.pack ();
            frame.setSize (300, 280);
            frame.setVisible (true);
        //Returns either an image icon or null if the path was invalid.
        protected static ImageIcon createImageIcon (String path, String description)
            java.net.URL imgURL = CPT.class.getResource (path);
            if (imgURL != null)
                return new ImageIcon (imgURL, description);
            else
                System.err.println ("Couldn't find file: " + path);
                return null;
        public static void main (String[] args)
            //Schedules a job for the event-dispatching thread.
            //Creates and shows this application's GUI.
            javax.swing.SwingUtilities.invokeLater (new Runnable ()
                public void run ()
                    createAndShowGUI ();
    }

    actually, i got around it by doing the following:
    try
                PrintWriter out2 = new PrintWriter (new FileWriter ("entries.dat"));
                out2.print ("Item Number|Description|Price|");
                out2.println ();
                for (int j = 0 ; j < rows ; j++)
                    for (int k = 0 ; k < columns ; k++)
                        String value = (String) modifyTable.getValueAt (j, k);
                        out2.print (value);
                        out2.print ("|");
                    out2.println ();
                out2.close ();
            catch (IOException ee)
                throw new RuntimeException (ee);
            }so...again, i havent found the code to do it? oh camickr.
    p.s. hell no im not giving u the honour of basking your name beside mine on a sheet of paper.
    the hard part was implementing all this code into the overall program, using my layout which you hate so much for adding and removing components. and i pursued this method because i knew how much youd hate it. yes....heh...yes....
    good game. i win.

  • Retreiving Point location with JTable row and column

    If I have the row and column in a JTable (in a JPanel), how do I get the Point location offset from the location Point of the JTable or JPanel ?

    I think that this may do it.
    Point objPoint = new Point( objTable_.getLocation() );
    int intRow = objTable_.getSelectedRow();
    int intColumn = objTable_.getSelectedColumn();
    int intColumnWidth = objTable_.getColumnModel().getColumn( intColumn ).getWidth();
    int intColumnMargin = objTable_.getColumnModel().getColumnMargin();
    int x = (int) objPoint.getX() + ( (intColumn+1) * intColumnWidth) );
    // perhaps * (intColumnWidth + intColumnMargin)
    int y = (int) objPoint.getY() + ( (intRow+1) * objTable_.getRowHeight());
    // perhaps * (objTable_.getRowHeight() + objTable_.getRowMargin())

  • JTable Creation and Viewing

    I want to create a table and display it along with the column names on it?
    i.e
    if I have two columns Names, Properties
    When I run I want to see
    Names Properties
    row1 row1properties
    row2 row2properties
    ...etc
    I tried giving this
    DataModelClass newDataModelClass = new DataModelClass();
    public JTable jTable1 = new JTable(newDataModelClass.data);
    which is displaying only the data not the column names.
    How can I get the column names also when I run?
    Thanks.

    It seems you need to study more. Go here to learn.
    http://www2.gol.com/users/tame/swing/examples/SwingExamples.html

  • JTable, Clipboard and charset encoding...

    I'm trying to paste data into JTable. Here's a part of the code:
    private BufferedReader getReaderFromTransferable(Transferable t)
    throws IOException, UnsupportedFlavorException
    if (t == null)
    throw new NullPointerException();
    DataFlavor[] dfs = t.getTransferDataFlavors();
    for (int i = 0; i < dfs.length; i++)
    System.out.println(dfs);
    DataFlavor df = DataFlavor.selectBestTextFlavor(dfs);
    df = df.getTextPlainUnicodeFlavor();
    Reader r = df.getReaderForText(t);
    return new BufferedReader(r);
    When I'm copying data from Excel everything is fine because
    DataFlavor of mimetype=text/plain...charset=utf-16le is supported.
    However, if I try to copy and paste data only inside my JTable,
    I'm getting UnsupportedFlavorException. It happens because
    there are only two mimetype=text/plain supported none of which is
    charset=utf-16le. API says that utf-16le is used for Windows as
    default Unicode encoding. What am I supposed to do? How can I set
    utf-16le encoding for my JTable? Or maybe I should do something
    different.

    Hi,
    You dont have to set utf-16le encoding to JTable..instead you have to create your own flawor type which supports current encoding. I have some code example somewhere on my HD, but i'm too lazy to check it out. You can find examples of creating your own data flawor by putting "creating own data flawors" in search field in java.sun.com web site. This can be a really "bloodpath" but try to survive.

  • [Jtable Unicode and Save Dialog]

    Hi all,
    I'm doing a swing application in which I use Jtable.
    In this Jtable, i want that the user can enter unicode character so
    i do this :
    Font font_unicode = new Font("Arial Unicode MS", Font.PLAIN, 13);
    table.setFont(font_unicode);It works fine : the user can enter japanese character.
    My problem is that when i want to save data that are in my jtable. I want to save it in a txt file(I use a txt filter), I loose unicode character.
    I use a save dialog as you can see :
    JFileChooser chooser = new JFileChooser();
              chooser.setFileFilter(info.main.Filter);
              chooser.setCurrentDirectory(new File("."));
              if (chooser.showSaveDialog(chooser) == JFileChooser.APPROVE_OPTION) {
                   try {
                        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(chooser
                                  .getSelectedFile(), false));
                        PrintWriter fileWriter = new PrintWriter(bufferedWriter);
    }I saw that in excel(office) there is a possibility to save in "unicode text" and I would like to know if it's also possible in swing. I really need it.
    I'm waiting for your answer..
    THX

    thanks for your answer but i don't find the code for unicode.
    and also i don't know if it's possible to add code for this :
    BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(chooser
                                  .getSelectedFile(), false));
                        PrintWriter fileWriter = new PrintWriter(bufferedWriter);

  • JTable Focus and InputVerifier nightmares

    I have been wrestling with JTable in 1.3 and 1.4, specifically its focus management and InputVerifiers.
    I have searched all over to find out why there is abnormal behavior in the focus manager, while overriding, setting properties to terminate a cell being edited, etc.
    I found ways to get the cell editors to provide InputVerifier support, though there are still quirks in some instances where the InputVerifier is not consulted.
    So to the Swing team, great job so far really...but the JTable really needs a LOT of work and bug votes don't make up for a non-releasable product.
    Sincerely,
    Jeremy Hanna

    Thanks qussev,
    that looks promising but I cannot find more than a picture (no code) where the focus is outside the selection. Does anybody know how this can be done?

Maybe you are looking for