Use of AbstractTableModel

Hi,
Is it possible to alter the size of a JTable using abstractTableModel? I've tried setSize on the JTable and height on the scrollpane, but nothing happens. My JTable displays 25 rows, and it's a bit too many. Anyone who can help me on this? Thanks.

Whurr. Sorry. I had a mental abberation and thought that setPreferredScrollableViewportSize would use rows. It doesn't, it uses pixels.
It's kind-of poor that they provide a method on JList which is setVisibleRowCount but that they do not provide the equivalent method on JTable. Your best bet therefore might be to copy the implementation of JList.getPreferredScrollableViewportSize into your own method MyTable.getPreferredScrollableViewportSize. Alternatively, duplicate the method into your own external code and use it to calculate the height in pixels, then call JTable.setPreferredScrollableViewportSize with the result.
Sorry if I misled you into thinking it was easier than it is.
Huw

Similar Messages

  • Updating a JTable when using an AbstractTableModel

    Hi,
    I have tried to create a JTable with an AbstractTableModel but I am obviously missing something in all the tutorials and examples as I cannot get the table to update when using my model.
    My application reads data in from a CSV file that is selectable at run time, but I have written a small app that demonstrates the problem I am having.
    If you uncomment the DefaultTableModel lines of code all is OK, but I need to use my Abstract Class as I intend to colour certain rows and add a Boolean column, that I would like to display as a CheckBox and not just the String representation.
    Any help would be great as I am tearing my hair out here!!
    My Test Class
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.util.*;
    public class TestTable extends JFrame implements ActionListener
    private JPanel jpTestTable = new JPanel();          
    private Vector vColumnNames = new Vector();
    private Vector vCellValues = new Vector();
    private DefaultTableModel dtmTestTable;
    private CustomTableModel ctmTestTable;
    private JTable jtTestTable;
    private JScrollPane jspTestTable;
    private JButton jbGo = new JButton();
         public TestTable()
         dtmTestTable = new DefaultTableModel();
         ctmTestTable = new CustomTableModel();
         //jtTestTable = new JTable( dtmTestTable );  //using this instead of my CustomModel works fine
         jtTestTable = new JTable( ctmTestTable );
         jtTestTable.setAutoCreateRowSorter(true);
         jtTestTable.setFillsViewportHeight( true );
         jspTestTable = new JScrollPane( jtTestTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS ,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );
         jspTestTable.setBounds( 10, 10, 350, 400 );
         jspTestTable.setBorder( BorderFactory.createLoweredBevelBorder() );
         jbGo.setText( "Go" );
         jbGo.setBorder( BorderFactory.createRaisedBevelBorder() );
         jbGo.setBounds( 125, 430, 100, 25 );
         jbGo.addActionListener(this);
         jpTestTable.setLayout( null );
         jpTestTable.setBounds( 0, 0, 375, 500 );     
         jpTestTable.add( jspTestTable );
         jpTestTable.add( jbGo );
         this.setTitle( "Test Table" );
         this.getContentPane().setLayout( null );
         this.setBounds( 200, 50, 375, 500 );
         this.getContentPane().add( jpTestTable );
         this.setResizable( false );
         public void actionPerformed( ActionEvent e )
         updateTable();
         public void updateTable()
         vColumnNames.add( "Please" );
         vColumnNames.add( "work" );
         vColumnNames.add( "you" );
         vColumnNames.add( "git!" );
         vColumnNames.trimToSize();
         Vector vRow = new Vector();
              for( int i = 0; i < 10; i++ )
                   for( int x = 0; x < vColumnNames.size(); x++ )
                        vRow.add( "" + i + "" + x );
              vCellValues.add( vRow );
         //dtmTestTable.setDataVector( vCellValues, vColumnNames );  //using this instead of my CustomModel works fine
         ctmTestTable.setDataVector( vCellValues, vColumnNames );
         public void processWindowEvent(WindowEvent e)
         super.processWindowEvent(e);
              if(e.getID() == WindowEvent.WINDOW_CLOSING)
              exit();
         public void exit()
         System.exit( 0 );     
         public static void main(String args[])
         TestTable tt = new TestTable();
         tt.setVisible( true );
    }And my CustomTableModel Class
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.util.*;
    public class CustomTableModel extends AbstractTableModel
    protected Vector columnIdentifiers  = new Vector();
    protected Vector dataVector = new Vector();
         public CustomTableModel()
         public CustomTableModel( Vector data, Vector columnNames )
         setDataVector( data, columnNames );
         public int getColumnCount()
         return columnIdentifiers.size();
         public int getRowCount()
         return dataVector.size();
         public String getColumnName( int col )
         return "" + columnIdentifiers.get( col );
         public Object getValueAt( int row, int col )
         Vector vRow = new Vector();
         vRow = (Vector) dataVector.get( row );
         return (Object) vRow.get( col );
         public Class getColumnClass(int c)
         return getValueAt(0, c).getClass();
         public boolean isCellEditable(int row, int col)
              if (col < 2)
                   return false;
              else
                   return true;
         public void setValueAt( Object value, int row, int col )
         Vector vTemp = (Vector) dataVector.get( row );
         Vector<Object> vRow = new Vector<Object>();
              for( int i = 0; i < vTemp.size(); i++ )
                   vRow.add( (Object) vTemp.get( i ) );
         vRow.remove( col );
         vRow.add( col, value );
         vRow.trimToSize();     
         dataVector.remove( row );
         dataVector.add( row, vRow );
         dataVector.trimToSize();
         fireTableCellUpdated(row, col);
         public void setDataVector( Vector data, Vector columnNames )
         columnIdentifiers  = (Vector) columnNames.clone();
         dataVector = (Vector) data.clone();
         fireTableDataChanged();
    }I have just tried adding the following code after reading another example, but same result - arrrrrrrgggggggghhhhhhhhh!!!!
    ctmTestTable = (CustomTableModel) jtTestTable.getModel();
    ctmTestTable.fireTableDataChanged();Edited by: Mr_Bump180 on Jul 28, 2008 2:51 PM

    Hi camickr,
    Well that is good news as my Abstact class is about as much good as an ashtray on a motorbike. I think I must have misread or misunderstood the Table Tutorials as I thought I had to use an Abstrat class to get colurs based on conditions and to get Check Boxes to represent Boolean variables.
    I am clearly struggling with this concept - which I have never used before - do you know of any tutorials, that explain how to update a JTable with file data at runtime, as all the ones I have looked at set it as part of the java code - which is no good to me.
    Also am I overriding the DefaultTableModel Class correctly - I have written a seperate Model class but wounder if I need to include it in with my JTable class. I was trying to make it generic so I didn't have to write one for each JTable - but as I can't get it to work I should perhaps try to walk before I run.
    I'm not asking for the code, but just a guide to how close I am to where I want to be, and some links to tutorials that are closer to what I want to achieve. I will reread the Java Table Tutorial tonight - and you never know the penny may drop all on it's own this time!!!
    Thanks

  • Using icons Abstracttablemodel

    I'm trying to use icons in my cells. But it does not appear as it should. I've read about custom renders but don't really understand how to use them. But I know some kind of help method to convert the string to image or something. Which I did as you can see in the abstracttablemodel code, but the cell is empty
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableModel;
    import javax.swing.Icon;
    public class Database extends JFrame implements ActionListener {
         private static Database application = new Database();
         private final int WIDTH = 900;
         private final int HEIGHT = 700;
         private JTable table = new JTable();
         private JButton addDVD = new JButton();
         private JButton addCD = new JButton();
         private JButton addBook = new JButton();
         private JButton borrow = new JButton();
         private JButton recieve = new JButton();
         private JButton remove = new JButton();
         private JButton receipt = new JButton();
         private JPanel buttonPanel = new JPanel();
         private JPanel mainPanel = new JPanel();
         private Directory items = new Directory();
         Icon icon1 = new ImageIcon("C:\\Users\\Johan\\Desktop\\mp3.jpg");
         public Database() {
              super("Database");
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setVisible(true);
              setSize(WIDTH, HEIGHT);
              buttonPanel.add(addBook);
              addBook.setText("New Book");
              buttonPanel.add(addDVD);
              addDVD.setText("New DVD");
              buttonPanel.add(addCD);
              addCD.setText("New CD");
              buttonPanel.add(remove);
              remove.setText("Remove");
              buttonPanel.add(borrow);
              borrow.setText("Borrow");
              buttonPanel.add(recieve);
              recieve.setText("Recieve");
              buttonPanel.add(receipt);
              receipt.setText("Receipt");
              addBook.addActionListener(this);
              addDVD.addActionListener(this);
              addCD.addActionListener(this);
              remove.addActionListener(this);
              borrow.addActionListener(this);
              recieve.addActionListener(this);
              receipt.addActionListener(this);
              Directory dir = new Directory();
              Objects kent = new Objects("mp3.jpg", "Röd", "2009", "SME", "56 min",
                        "Rock");
              Objects nightwish = new Objects("mp3.jpg", "Once", "2004", "WMS", "55",
                        "Rock");
              dir.add(kent);
              dir.add(nightwish);
              table = new JTable(dir);
              table.setRowHeight(20);
              JScrollPane JScroll = new JScrollPane(table);
              mainPanel.setLayout(new BorderLayout());
              mainPanel.add("North", buttonPanel);
              mainPanel.setLayout(new BorderLayout());
              mainPanel.add("North", buttonPanel);
              mainPanel.add("Center", JScroll);
              getContentPane().add(mainPanel);
         public void actionPerformed(ActionEvent arg) {
         public static void main(String[] argv) {
              new Database();
              BufferedImage image = null;
              try {
                   File imageFile = new File("C:\\Users\\Johan\\Desktop\\database.jpg");
                   image = ImageIO.read(imageFile);
              } catch (IOException e) {
                   e.printStackTrace();
              application.setIconImage(image);
              application.setVisible(true);
    }Here is the code for the abstracttablemodel
    import java.util.ArrayList;
    import javax.swing.Icon;
    import javax.swing.table.AbstractTableModel;
    public class Directory extends AbstractTableModel {
         private ArrayList<Objects> obj = new ArrayList<Objects>();
         public void add(Objects o) {
              obj.add(o);
         public void remove(Objects o) {
              obj.remove(o);
         public int getColumnCount() {
              return 6;
         public int getRowCount() {
              return obj.size();
         public Object getValueAt(int row, int col) {
              Objects o = obj.get(row);
              switch (col) {
              case 0:
                   return o.getImage();
              case 1:
                   return o.getTitle();
              case 2:
                   return o.getYear();
              case 3:
                   return o.getPublisher();
              case 4:
                   return o.getLenght();
              case 5:
                   return o.getGenre();
              default:
                   return null;
         public String getColumnName(int col) {
              switch (col) {
              case 0:
                   return "Type";
              case 1:
                   return "Title";
              case 2:
                   return "Year";
              case 3:
                   return "Publisher";
              case 4:
                   return "Lenght";
              case 5:
                   return "Genre";
              return null;
         public Class<?> getColumnClass(int col) {
              switch (col) {
              case 0:
                   return Icon.class;
              default:
                   return super.getColumnClass(col);
    }Edited by: iTech34 on Dec 29, 2009 6:36 AM

    iTech34 wrote:
    Hii
    I've checked those links and many else. But I don't get it. What don't you get?
    I know I need to make some kind of render, either the default or custom.Then why does your example use an extension of AbstractTableModel? That's not a Renderer.
    Since normally the jtable only takes strings and I need to convert it to icon as i did. But the image does not display. I need some kind of method so it will display it. I would really appreciate an easy example. Not really good at java, specially not JTable. But trying... :)[Easy example.|http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#renderer]

  • Deleting a row from a JTable using AbstractTableModel

    Hi,
    Can someone please help me on how should i go about deleting a row in a jtable using the AbstractTableModel. Here i know how to delete it by using vector as one of the elements in the table. But i want to know how to delete it using an Object[][] as the row field.
    Thanks for the help

    Hi,
    I'm in desperate position for this please help

  • Is it better to use AbstractTableModel or DefaultTableModel...?

    Is it better to use AbstractTableModel or DefaultTableModel when subclassing your jtable model? I ask this because while the java tutorial seems to point to the former I've read some people to recommend using the defaulttablemodel. What is the general consensus? Do you have to implement all the methods you need in the defaulttablemodel also? Because right now I think that's the biggest drawback that abstracttablemodel has...

    I ask this because while the java tutorial seems to point to the former (AbstractTableModel)Because they are trying to show an example of how to implement a TableModel. This does not mean you need to create a custom TableModel every time you use a JTable
    I've read some people to recommend using the defaulttablemodel.Because it is fully functional. DefaultTableModel already extends AbstractTableModel to provide this functionality. If it has the functionality that you require then there is no need to create another custom TableModel
    Is it better to use AbstractTableModel or DefaultTableModel...?In general, if the DefaultTableModel does not meet your needs because of the format of your data then you would extend the AbstractTableModel. But if your needs are similiar to the functionality already provided by the DTM then it may be faster/easier to extend it.
    You can't use the AbstractTableModel as is and therefore always need to extend it to implement the functionality that you require. Extending the AbstractTableModel every time doesn't make any sense because you keep doing extra work. So if you do need to extend it you should extend it in a generic way that the classes are reusable.
    Which is why I created the [List Table Model|http://www.camick.com/java/blog.html?name=list-table-model] and [Bean Table Model|http://www.camick.com/java/blog.html?name=bean-table-model]. The idea is to minimize the coding effort involved. They allow you to work with Lists. They can be used as is, or with smaller customization than required if you use the ATM every time.
    Edited by: camickr on May 9, 2009 1:01 AM

  • Updating a JTable using CachedRowSet data

    Hello, I would like to know how I can update my already created JTable receiving data from a CachedRowSet without creating a new table model (this is the method I have been using). I have read about using the fireTableDataChanged() method but I cant figure out how to use this works. Maybe an explanation on how the information in the CachedRowSet is updated in the JTable when notifiers are used will help.
    Any help will be appreciated

    camickr wrote:
    table.setAutoCreateColumnsFromModel( false );
    Perfect. This works well for my issue. I can now use the setModel() method without having the columns reordered.Damn camickr, that is a bloody good thing to know (it's often so much easier to recreate the table model, here's a very neat solution to one of the pitfalls)! Thanks :)
    Since this is solved, I still want to know how I can use the fireTableDataChanged() method and AbstractTableModel interface with CachedRowSet (just out of curiosity). I have been looking through jduprez's suggestion to figure this out too. I am currently faced with the issue,
    I have two classes, one for the CachedRowSet and the other with the table implementationsAs you describe it, I don't think that's a good approach: what I meant wad an implementation of TableModel , not a subclass of JTable : the stock JTable already knows how to work with any model implementation, as long as it implements TableModel .
    Where do I need to use the AbstractTableModel interface?It is a class, not an interface: it implements TableModel and provides useful defaults for some methods (at least, the management of the list of TableModelListener )
    My suggestion was that you define a custom class that extends AbstractTableModel , and uses its fireXxx judiciously.
    here is an example:
    public class RowSetAwareTableModel extends AbstractTableModel {
        public void setUpdateddata(RowSet newData) {
            this rowSet = newdata;
            super.fireTabledataChanged();
        /** Implementation of TableModel */
        public int getRowCount() {
            return rowset.getMaxRows();
        // etc...
    }

  • Updating a JTable using a JTable

    I am looking to update an empty JTable using the data from a JTable containing a set of data.
    I am aware that addRow can be used with the DefaultTableModel from previous discussions on this forum, but I have found this call isn't available when using AbstractTableModel.
    The reason I have been having some problems with this as it is necessary for the AbstractTableModel to be used in the context of the GUI, and I am asking if there is a way to solve this using the AbstractTableModel?
    I am using an AbstractTableModel for both the data table and the table showing all currently and previously selected rows.

    I am using an AbstractTableModel for both the data table and the table showing all currently and previously selected rows.No you aren't. You can't create an Abstract class because not all the methods are implements. You are using a class that extends AbstractTableModel.
    So why not use the DefaultTableModel and make your life simple?

  • Using the fireTableRowsDeleted Event

    hii all , :( I had develope a small application where i am using the JTable and also sorter for filtering the content , In Jtable i am using the AbstractTableModel , and on a click of the checkbox in jTable i delete the row for which i had written the code in the TableModel File in the function " setValueAt " Every thing is working fine like i can able to fire a query and delete the record but at the same time i want the jtable to be updated and delete the respective row from the view , but when ever i call the fireTableRowsDeleted(row,row) It gives the exception --> java.lang.IndexOutOfBoundsException: Invalid range .
    Please help me getting out of this :( i had been stucked up wid this since last 2 days :(

    The follow functions initiate the sorter just after initializing the components in the file student.dialog
    { void mySettings()
    //jTable1.rowSelectionAllowed();
    jTable1.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    //jTable1.setFont(new Font("Helvetica", Font.PLAIN, 10));
    jTable1.setModel(new StudentTableModel(jTable1,jLabel25));
    // MyTableModel model = new MyTableModel(this.rw,this.cl);
    sorter = new TableRowSorter(jTable1.getModel());
    jTable1.setRowSorter(sorter);
    //jTable1.getValueAt(rw, cl);
    // System.out.println(jTable1.getColumnModel().getColumn(2));
    jTable1.getSelectionModel().addListSelectionListener(
    new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent event) {
    int viewRow = jTable1.getSelectedRowCount();
    //jLabel1.setText(String.valueOf(jTable1.getSelectedRowCount()));
    if (viewRow < 0) {
    //Selection got filtered away.
    // statusText.setText("");
    } else {
    //int modelRow =
    // jTable1.convertRowIndexToModel(viewRow);
    firstName.getDocument().addDocumentListener(
    new DocumentListener() {
    @Override
    public void changedUpdate(DocumentEvent e) {
    newFilter();
    @Override
    public void insertUpdate(DocumentEvent e) {
    newFilter();
    @Override
    public void removeUpdate(DocumentEvent e) {
    newFilter();
    lastName.getDocument().addDocumentListener(
    new DocumentListener() {
    @Override
    public void changedUpdate(DocumentEvent e) {
    newFilter();
    @Override
    public void insertUpdate(DocumentEvent e) {
    newFilter();
    @Override
    public void removeUpdate(DocumentEvent e) {
    newFilter();
    After this when a user select a filter and table get sorted only 10 records appear there int the jtable from which a user select just one and press the remove button on that click i have written this
    {int rowArr [] =jTable1.getSelectedRows();
    for(int rowId:rowArr)
    try
    // System.out.println(sorter.convertRowIndexToModel(rowId));
    sorter.getModel().fireTableRowsDeleted(jTable1.convertRowIndexToModel(rowId), jTable1.convertRowIndexToModel(rowId));
    //sorter.rowsDeleted(rowId, rowId);
    int stuId = Integer.valueOf(String.valueOf(jTable1.getValueAt(rowId, 0)));
    int sessId= Singleton.getInstance().session_id;
    conn = Singleton.getInstance().makeConnection();
    query="DELETE FROM student_class WHERE student_id =? AND admClass<>1 AND session_id=?"; // 7
    s=conn.prepareStatement(query);
    s.setInt(1,stuId);
    s.setInt(2,sessId);
    s.execute();
    }catch(Exception e)
    e.printStackTrace();
    Do not think that i want multiple records to be delete i m selecting only one record but when i click on the remove button it gives me the following stack trace:
    java.lang.IndexOutOfBoundsException: Invalid range
         at javax.swing.DefaultRowSorter.checkAgainstModel(DefaultRowSorter.java:921)
         at javax.swing.DefaultRowSorter.rowsDeleted(DefaultRowSorter.java:878)
         at javax.swing.JTable.notifySorter(JTable.java:4277)
         at javax.swing.JTable.sortedTableChanged(JTable.java:4121)
         at javax.swing.JTable.tableChanged(JTable.java:4398)
         at javax.swing.table.AbstractTableModel.fireTableChanged(AbstractTableModel.java:296)
         at dps.StudentTableModel.fireTableChanged(StudentTableModel.java:465)
         at javax.swing.table.AbstractTableModel.fireTableRowsDeleted(AbstractTableModel.java:261)
         at dps.StudentTableModel.fireTableRowsDeleted(StudentTableModel.java:475)
         at dps.StudentDialog.jButton5ActionPerformed(StudentDialog.java:1360)
         at dps.StudentDialog.access$1600(StudentDialog.java:56)
         at dps.StudentDialog$18.actionPerformed(StudentDialog.java:441)
         at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
         at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
         at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
         at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
         at java.awt.Component.processMouseEvent(Component.java:6504)
         at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
         at java.awt.Component.processEvent(Component.java:6269)
         at java.awt.Container.processEvent(Container.java:2229)
         at java.awt.Component.dispatchEventImpl(Component.java:4860)
         at java.awt.Container.dispatchEventImpl(Container.java:2287)
         at java.awt.Component.dispatchEvent(Component.java:4686)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
         at java.awt.Container.dispatchEventImpl(Container.java:2273)
         at java.awt.Window.dispatchEventImpl(Window.java:2713)
         at java.awt.Component.dispatchEvent(Component.java:4686)
         at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:707)
         at java.awt.EventQueue.access$000(EventQueue.java:101)
         at java.awt.EventQueue$3.run(EventQueue.java:666)
         at java.awt.EventQueue$3.run(EventQueue.java:664)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
         at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
         at java.awt.EventQueue$4.run(EventQueue.java:680)
         at java.awt.EventQueue$4.run(EventQueue.java:678)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:677)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
         at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

  • Drag n Drop in JTable with AbstractTableModel

    Dear Experts,
    I would like to drag and drop rows in a JTable. For example, if I have 6 rows in a JTable based on an AbstractTableModel and if I am trying to drag row number 5 and wish to drop it at row number 2, then the 5th row which was dragged should be pasted as 3rd row and the rows 3 and 4 should be rearranged (ie, moved one place down).
    Can anyone help me in achieving this? Any readymade code available? :-)
    I tried running the code in the Java Tutorial in the link
    http://java.sun.com/docs/books/tutorial/uiswing/examples/dnd/index.html
    but, this didnt help as it was mainly for a DefaultTableModel I guess. Also, when I used the StringTransferHandler and TableTransferHandler, I was able achieve just copying the dragged row and pasting at the dropped row. The row rearrangement was not functioning.
    Pls Help...
    Thanks & Regards
    Irfaan

    I have 6 rows in a JTable based on an AbstractTableModelDo you know what "Abstract" means? I suggest you look it up in your Java text book.
    You are not using the AbstractTableModel, you are using a TableModel that extends AbstractTableModel.
    but, this didnt help as it was mainly for a DefaultTableModel That is exactly why you should be using the DefaultTableModel since it supports the concept of moving rows. If you want to use a custom TableModel, then you need to implement the concept of moving rows yourself. So why write a custom TableModel when this has already been done for you??

  • AbstractTableModel

    I am having trouble using an abstractTableModel with my dataStructure.
    If I edit a cell the code successfully updates the model which is shown in the print statement. However If I change my model using the buttons, the model is changed but the table does not seem to be updated.
    How can i update the table?
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import javax.swing.*;
    import javax.swing.table.*;
    class Main {
        public static void main(String[] args) {
            new JTableExample().createGui();
    class JTableExample {
        private JTable table;
        private People people = new People();
        public void createGui() {
            table = new JTable(new People());
            JFrame f = new JFrame("JTableExample");
            f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            f.getContentPane().add(new JScrollPane(table));
            JPanel pane = new JPanel(new BorderLayout());
            pane.add(new JScrollPane(table), BorderLayout.CENTER);
            pane.add(getButtonPanel(), BorderLayout.SOUTH);
            f.add(pane);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        public JPanel getButtonPanel(){
            JButton changeNameButton = new JButton("Change Tom's Name");
            changeNameButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    people.getPeopleArray().get(0).setName("Changed");
                    people.printPeople();
                    table.revalidate();
                    table.repaint();
            JButton changeDataButton = new JButton("New Data");
            changeDataButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    ArrayList<Person> newPeople = new ArrayList<Person>();
                    newPeople.add(new Person());
                    newPeople.add(new Person());
                    newPeople.add(new Person());
                    newPeople.add(new Person());
                    people.setPeopleArray(newPeople);
                    people.printPeople();
                    table.revalidate();
                    table.repaint();
            JButton addPersonButton = new JButton("Add person");
            addPersonButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    people.getPeopleArray().add(new Person());
                    people.printPeople();
                    table.createDefaultColumnsFromModel();
                    table.revalidate();
                    table.repaint();
            JPanel buttonPanel = new JPanel();
            buttonPanel.add(changeNameButton);
            buttonPanel.add(changeDataButton);
            buttonPanel.add(addPersonButton);
            return buttonPanel;
    class People extends AbstractTableModel{
        private ArrayList<Person> peopleArray = new ArrayList<Person>();
        private static final int COLUMN_COUNT = 2;
        private static final String[] COLUMN_NAMES = {"Name","Age"};
        public People() {
            super();
            peopleArray.add(new Person(2, "Tom", 3));
            peopleArray.add(new Person(3, "Hary", 3));
            peopleArray.add(new Person(2, "Bor", 3));
            peopleArray.add(new Person(5, "lucy", 3));
            peopleArray.add(new Person(10, "char", 4));
        @Override
        public int getRowCount() {
            if(peopleArray == null){
                return 0;
            }else{
                return peopleArray.size();
        @Override
        public int getColumnCount() {
            if(peopleArray == null){
                return 0;
            }else{
                return COLUMN_COUNT;
        @Override
        public String getColumnName(int column) {
            return COLUMN_NAMES[column];
        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            switch (columnIndex) {
                case 0:
                    return peopleArray.get(rowIndex).getName();
                case 1:
                    return peopleArray.get(rowIndex).getAge();
                default:
                    return null;
        @Override
        public boolean isCellEditable(int row, int col) {
                return true;
        @Override
        public void setValueAt(Object value, int row, int col) {
            switch (col) {
                case 0:
                    peopleArray.get(row).setName(value.toString());
                    break;
                case 1:
                    peopleArray.get(row).setAge(Double.parseDouble(value.toString()));
                    break;
            printPeople();
            fireTableCellUpdated(row, col);
        public ArrayList<Person> getPeopleArray() {
            return peopleArray;
        public void setPeopleArray(ArrayList<Person> people) {
            this.peopleArray = people;
        public void printPeople(){
            System.out.println("\nPrinting People Array ");
            for(int i = 0;i<peopleArray.size();i++){
                System.out.println("Person "+i+" "+peopleArray.get(i).getName()+" "+peopleArray.get(i).getAge()+" "+peopleArray.get(i).getHeight());
    class Person {
        private double age;
        private String name;
        private double height;
        public Person() {
            this(21, "Chris", 2);
        public Person(double age, String name, double height) {
            super();
            this.age = age;
            this.name = name;
            this.height = height;
        public double getAge() {
            return age;
        public double getHeight() {
            return height;
        public String getName() {
            return name;
        public void setAge(double age) {
            this.age = age;
        public void setHeight(double height) {
            this.height = height;
        public void setName(String name) {
            this.name = name;
    }Thanks in advance
    sorry the example is pretty long
    Calypso

    Well the original advice given was:
    Do not access the data directly, instead make methods on the model itself to modify the data and have those methods fire the appropriate events.
    So you need to create an addRow(...) method.
    Since addRow(...) invokes insertRow(...), I guess you have to look deeper to see what events are fired.

  • AbstractTableModel - getColumnClass()

    Hi,
    When I create one of the tables in my program, it always crashes painting the table from the method
    getColumnClass() from the tableModel class the table use (tableModel in my case extends AbstractTableModel() ).
    When I remove the method, the table is painted ok with no run-time errors - as soon as I put the method back in - it will not paint - I have many other tables and none of these crash?
    I have used the AbstractTableModel from the tutorial on Swing JTable and so I guess the method is constructed ok:-
       public Class getColumnClass(int c) {
         return getValueAt(0, c).getClass();
       public Object getValueAt(int row, int col) {
          return ((Vector)data.elementAt(row)).elementAt(col);
        }Has anyone seen this before? I'm most baffled!
    Ta for any feedback.

    This is just a wild guess. Have you populated the data in your table model. You didn't say exactly what was happening or the error messages you got but I think the getColumnClass( ) method maybe returning null because there isn't anything in table.
    As I said, this is just a guess. You may want to post stack trace or error you're getting.
    DB

  • JTable AbstractTableModel and TableChanged Event

    Could someone give me an example of inserting rows visually (on runtime) by using Abstract Table model and TableChangedEvent ?
    Thank you in advance

    Actually i used AbstractTableModel and java let me to use. Like this:And that only works because you extended the AbstractTableModel. You created something called an "Annonymous Inner Class". What you did is similiar to creating a new source file with code like:
    public class MyCustomTableModel extends AbstractTableModel
            public int getRowCount() {
                return heading.length;
            public int getColumnCount() {
                return data.length;
            public Object getValueAt(int rowIndex, int columnIndex) {
                return data[rowIndex][columnIndex];
            }It will not work if you try to do:
    AbstractTableModel model = new AbstractTableModel();
    But this was the sentence that i need:And I already stated that when I said:
    So the DefaultTableModel "DOES" use the AbstractTableModel because it extends the AbstractTableModel
    The concept of "inheritance" is basic to Java. Inheritance is accomplished by "extending" another class. If you do not understand this basic concept then you need to start reading because we don't have the time to explain the basics especially when you bad mouth the person that attempts to help.

  • Centering texts with DefaultTableCellRenderer

    Hi,
    I 've created a JTable and now I am trying to center the text in the cells of the table.
    I am using an AbstractTableModel for this table and the data are store in a vector.
    I tried to extends DefaultTableCellRenderer like this but it did not work because (I think) of the vector.
    Here a snippet:
    class centerTextRenderer extends DefaultTableCellRenderer{
    public centerTextRenderer(){
    setHorizontalAlignment(CENTER );
    public void setValue( Object value){
    setText( value.toString() );
    Does anyone have a suggestion?
    --kirk123

    Your class looks OK (you don't even need to override the setValue() method). Did you tell your table to use your renderer?
    table.setDefaultRenderer(Object.class, new CenterTextRenderer());
    Note: the Java convention is to use upper case characters for all words in a class name.

  • Makignone column in jtable NOT sortable

    hi
    i am using a TAbleSorter that sun provides to sort my table
    JTable importsTable=new JTable();
    MyTableModel model = new MyTableModel(handler.getImportableObjects());
    MyTableSorter sorter = new MyTableSorter(model, 0);
    sorter.setTableHeader(importsTable.getTableHeader());
    importsTable.setModel(sorter);
    MyTableModel is an AbstractTableModel that does soem custom stuff for me, nothign major.
    MyTableSorter is a table sorter that overrides isCellEditable. i am doing this so that i can make the one column iwnat non-sortable not editable. it is however nto working. help?
    thank you

    Well.. u r using an abstractTableModel.. so the cells r anyways not editable.. U ve made all the columns except the first one editable by overriding the isCellEditable method.. It s not working?? There must be some other prob.. Post some more relevant part of the code wit tags

  • Table Sorting based on Column Selection

    Dear All,
    I am using an AbstractTableModel. I would like to implement the sorting based on Column selection. Could anyone help me in this please.
    Thanks in advance,
    Regards
    Irfaan

    check this
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.UIManager;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumnModel;
    import java.awt.Component;
    import java.awt.GridLayout;
    import java.awt.Insets;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.Hashtable;
    public class TableSorter extends JPanel
        private boolean             DEBUG       = false;
        private Object[]            columnNames = { "First Name", "Last Name", "Sport", "# of Years",
                                                    "Vegetarian"};
        private Object[][]          data        = { { "Mary", "Campione", "Snowboarding", 1, 2 },
                { "Alison", "Huml", "Rowing", 3, 4 }, { "Kathy", "Walrath", "Knitting", 5, 9 },
                { "Sharon", "Zakhour", "Speed reading", 6, 10 }, { "Philip", "Milne", "Pool", 7, 11 },
                { "Isaac", "Rabinovitch", "Nitpicking", 8, 12 }, };
        private SortFilterModel     m_modSortFilterModel;
        private TableColumnModel    m_modColumnModel;
        private TableHeaderRenderer m_btnSorterRenderer;
        protected boolean           m_bAbCOC    = true;
        JTable                      table       = new JTable();
        public TableSorter()
            super(new GridLayout(1, 0));
            m_modSortFilterModel = new SortFilterModel();
            m_modSortFilterModel.addMouseListener(table);
            table.setModel(m_modSortFilterModel);
            m_btnSorterRenderer = new TableHeaderRenderer();
            m_modColumnModel = table.getColumnModel();
            for (int i = 0; i < columnNames.length; i++)
                m_modColumnModel.getColumn(i).setHeaderRenderer(m_btnSorterRenderer);
            JScrollPane scrollPane = new JScrollPane(table);
            add(scrollPane);
        private class SortFilterModel extends AbstractTableModel
            int[]           indexes;
            ATSTableSorter  sorter;
            public String[] tableHeadersArray;
            boolean         isAscent = true;
            public void addMouseListener(final JTable table)
                table.getTableHeader().addMouseListener(new MouseAdapter()
                    public void mouseClicked(MouseEvent event)
                        int tableColumn = table.columnAtPoint(event.getPoint());
                        m_btnSorterRenderer.setPressedColumn(tableColumn);
                        m_btnSorterRenderer.setSelectedColumn(tableColumn);
                        if (TableHeaderRenderer.DOWN == m_btnSorterRenderer.getState(tableColumn))
                            isAscent = true;
                        else
                            isAscent = false;
                        // translate to table model index and sort
                        int modelColumn = table.convertColumnIndexToModel(tableColumn);
                        sortByColumn(modelColumn, isAscent);
            public Object getValueAt(int row, int col)
                int rowIndex = row;
                if (indexes != null)
                    rowIndex = indexes[row];
                return data[rowIndex][col];
            public void setValueAt(Object value, int row, int col)
                int rowIndex = row;
                if (indexes != null)
                    rowIndex = indexes[row];
                super.setValueAt(value, rowIndex, col);
            public void sortByColumn(int column, boolean isAscent)
                if (sorter == null)
                    sorter = new ATSTableSorter(this);
                sorter.sort(column, isAscent);
                fireTableDataChanged();
            public int[] getIndexes()
                int n = getRowCount();
                if (indexes != null)
                    if (indexes.length == n)
                        return indexes;
                indexes = new int[n];
                for (int i = 0; i < n; i++)
                    indexes[i] = i;
                return indexes;
            public int getRowCount()
                return data.length;
            public String getColumnName(int c)
                return columnNames[c].toString();
            public int getColumnCount()
                return columnNames.length;
            public Class getColumnClass(int col)
                switch (col)
                case 0:
                    return String.class;
                case 1:
                    return String.class;
                case 2:
                    return String.class;
                case 3:
                    return Integer.class;
                case 4:
                    return Integer.class;
                          default:
                    return Object.class;
        class ATSTableSorter
            SortFilterModel model;
            public ATSTableSorter(SortFilterModel model)
                this.model = model;
            public void sort(int column, boolean isAscent)
                int n = model.getRowCount();
                int[] indexes = model.getIndexes();
                for (int i = 0; i < n - 1; i++)
                    int k = i;
                    for (int j = i + 1; j < n; j++)
                        if (isAscent)
                            if (compare(column, j, k) < 0)
                                k = j;
                        else
                            if (compare(column, j, k) > 0)
                                k = j;
                    int tmp = indexes;
    indexes[i] = indexes[k];
    indexes[k] = tmp;
    public int compare(int column, int row1, int row2)
    Object o1 = model.getValueAt(row1, column);
    Object o2 = model.getValueAt(row2, column);
    if (o1 == null && o2 == null)
    return 0;
    else if (o1 == null)
    return -1;
    else if (o2 == null)
    return 1;
    else
    Class type = model.getColumnClass(column);
    if (type.getSuperclass() == Number.class)
    return compare((Number) o1, (Number) o2);
    else if (type == String.class)
    return ((String) o1).compareTo((String) o2);
    else
    return ((String) o1).compareTo((String) o2);
    public int compare(Number o1, Number o2)
    double n1 = o1.doubleValue();
    double n2 = o2.doubleValue();
    if (n1 < n2)
    return -1;
    else if (n1 > n2)
    return 1;
    else
    return 0;
    class TableHeaderRenderer extends JButton implements TableCellRenderer
    public static final int NONE = 0;
    public static final int DOWN = 1;
    public static final int UP = 2;
    int pushedColumn;
    Hashtable state;
    public TableHeaderRenderer()
    pushedColumn = -1;
    state = new Hashtable();
    setMargin(new Insets(0, 0, 0, 0));
    setHorizontalTextPosition(LEFT);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus,
    int row, int column)
    setText((value == null) ? "" : value.toString());
    setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    boolean isPressed = (column == pushedColumn);
    getModel().setPressed(isPressed);
    getModel().setArmed(isPressed);
    return this;
    public void setPressedColumn(int col)
    pushedColumn = col;
    public void setSelectedColumn(int col)
    if (col < 0)
    return;
    Integer value = null;
    Object obj = state.get(new Integer(col));
    if (obj == null)
    value = new Integer(DOWN);
    else
    if (((Integer) obj).intValue() == DOWN)
    value = new Integer(UP);
    else
    value = new Integer(DOWN);
    state.clear();
    state.put(new Integer(col), value);
    public int getState(int col)
    int retValue;
    Object obj = state.get(new Integer(col));
    if (obj == null)
    retValue = NONE;
    else
    if (((Integer) obj).intValue() == DOWN)
    retValue = DOWN;
    else
    retValue = UP;
    return retValue;
    private static void createAndShowGUI()
    JFrame frame = new JFrame("TableDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    TableSorter newContentPane = new TableSorter();
    newContentPane.setOpaque(true); // content panes must be opaque
    frame.setContentPane(newContentPane);
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args)
    javax.swing.SwingUtilities.invokeLater(new Runnable()
    public void run()
    createAndShowGUI();

Maybe you are looking for

  • Where can i find a demo of adf faces 11 preview??

    Where can i find a demo of adf faces 11 preview?? Just like the one in adf-faces-10_1_3_0_4.zip. I think it's the best tutorial to study adf faces 11! Anyone can help? Thank you!

  • Best practice to use contract(ME31K) in reference a PR

    Hi,      I create a PR(me51n) with service (the commitment is on the PR), next I create a contract(me31k) in reference with the PR. In the contract I do some change, I subdivide the service in two lines. After with ME57 I assign the contract with the

  • Need to get back to OSx 10.7 after complete HD failure

    I've had a complete HD failure on my first generation Intel mac pro.  (I mean couldn't it have waited the extra couple of weeks I needed to order the new mac pro?) My best guess to do this (which has hit a snag) would be the following: 1) Use my Snow

  • Syntax Error on script

    OC

  • HELP!! Unable to use glyphs CS6

    Hello, I am using CS6 on a MBP 10.9.4 and for some crazy reason my glyphs are not working. I have used them in the past week, they worked just fine, now suddenly, nothing. I have not done any updates, and nothing has changed with my preferences.  Whe