Changing a JTable's model

Hello everyone,
I dont have a whole lot of experience w/ JTables and this problem has been troubling me for a while now. I have a JTable that significantly changes when the user hits the calculate button, so instead of going through the trouble of completely reformatting the table by adding/removing columns and table headers, I simple make a new model and set the table's model to the new one, and then call table.updateUI(). The problem is that my custom cell renderer that displays a down or up arrow depending on how the given column is sorted stops working. The sorter works properly and the table displays properly, but the arrows do not change from up to down or vise versa when a column is resorted. The whole process works just fine the first time, but the more times the user pushes the calculate button the more off it gets. I have added a flag in the actionPerformed method in my cell renderer that tells me when the table header is clicked. Every time the calculate button is hit, more flags appear when the table header is clicked. Therefore the arrows change position on odd numbers and do not on evens (because the evens cancel eachother out and the arrow appears to sit still), however the sorter still works properly. It seems as though somehow a new mouse listener or cell renderer is added after each time the calculate button is pressed. Either that or the entire table is not being reset somehow and something is still invisible in the background.
Here is some of my code.
// The initial table with no data
String[] str = {"class 1", "class 2", "class 3", "class 4", "class 5", "= GPA"};
String[][]  data= {{"", "", "", "", "", ""},
pmModel = new ProjectionModel(str, data);
mainTable = new JTable(pmModel);
mainTable.getTableHeader().setDefaultRenderer(new SortButtonRenderer());
// After the calculate button has been pushed:
// The table is reset here. TableSorter extends TableMap
    ProjectionModel newModel = new ProjectionModel(courseList, charList);
    TableSorter sorter = new TableSorter(newModel);
    // this method is shown below
    sorter.addMouseListenerToHeaderInTable(mainTable);
    sorter.sortedUp = false;
    mainTable.addNotify();
    mainTable.setModel(sorter);
    // SortButtonRenderer extends TableCellRenderer
    SortButtonRenderer renderer = new SortButtonRenderer();
    mainTable.getTableHeader().setDefaultRenderer(renderer);
    // set the arrow to DOWN on the first column
    renderer.setSelectedColumn(0);
    renderer.setSelectedColumn(0);
    mainTable.updateUI();
// This is the addMouseListenerToTable(JTable table) found in the TableSorter class
    public void addMouseListenerToHeaderInTable(JTable table) {
        final TableSorter sorter = this;
        final JTable tableView = table;
        tableView.setColumnSelectionAllowed(false);
        MouseAdapter listMouseListener = new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                TableColumnModel columnModel = tableView.getColumnModel();
                int viewColumn = columnModel.getColumnIndexAtX(e.getX());
                int column = tableView.convertColumnIndexToModel(viewColumn);
                if (e.getClickCount() == 1 && column != -1) {
                  SortButtonRenderer renderer =
                        (SortButtonRenderer)tableView.getTableHeader().getDefaultRenderer();
                    //int shiftPressed = e.getModifiers()&InputEvent.SHIFT_MASK;
                    //boolean ascending = (shiftPressed == 0);
                    boolean ascending = (renderer.getLastColumn() == column && !sortedUp);
                    renderer.setLastColumn(column);
                    sorter.sortByColumn(column, ascending);
                    if (ascending) sortedUp = true;
                    else sortedUp = false;
                    renderer.setSelectedColumn(column);
                    // the flag that prints the column that is pressed
                    System.out.println(column + " " + sortedUp);
        JTableHeader th = tableView.getTableHeader();
        th.addMouseListener(listMouseListener); // it seems like i need a way to remove any
// previous mouseListeners here, i think this would solve the problem
    }The flag's output looks something like this:
< first time calculate button is clicked >
< column 0 is clicked> 0 false
< column 0 is clicked again > 0 true
< second time calculate button is clicked >
< column 0 is clicked >
0 false
0 true
notice they cancel eachother out so the arrow stays in the same position
< third time calculate button is clicked >
< column 0 is clicked >
0 false
0 true
0 false
notice they dont cancel eachother out, so the arrow changes positions
This problem is really bugging me. I appreciate any help. Thanks.
-kc

Well I fixed my problem but I kind of cheated...
I used a static variable in the class that inits the GUI to keep track of the MouseListeners that are added to the table headers by the TableSorter. In the TableSorter class's addMouseListenerToTableHeader(JTable table) class I added a line of code before the "th.addMouseListener(listListener)" line: "th.removeMouseListener(Projector.lastListener))"
It works but it kind of sucks. If there is a better way to do it that would be great. I'm sorry if you read through all of that stuff and then I ended up fixing my own problem anyway :(
Thanks anyway.
-kc

Similar Messages

  • Change log for Distribution model and partner profile

    Hello All,
    Could any one please suggest how to get teh change log of the distribution model and partner profiles in SAP.
    Thank you!
    Arvind

    Hello,
    The documentation says what distribution model is used for. My question is can we have change log for any change in the distribution model like user, time and date.
    In production system if distribution model and partner profiles are changed by someone to a destination which should not be used, then how can we trace who has changed it.
    I hope I am able to explain.
    Arvind

  • How can I change the cardinality of Model Node?

    Hi everybody
    How can I change the cardinality of Model Node?
    Previous:
    I import a Model RFC, and some nodes has the cardinality 0..1, but with this configuration, when I bind to the text fields of my webdynpro and deploy, all my fields text are unables when I shows the webdynpro.
    I check RFC and all the fields and estructures are obligatories.

    Hi Jesus,
    You cannot change the cardinality of the model node. All  the properties of the Model node are derived from the Model object.
    Your input fields are disabled because you are not creating your model object properly.
    You can import the example project TutWD_FlightList, which is available in c:\Program Files\SAP\IDE\IDE70\eclipse\examples.
    Import it in NWDS and you can see how to initialize model object properly.
    Thanks
    Prashant

  • Determining when a JTable's model event is changed

    Hello,
    I have a JTable and I want a class I programmed to register to TableModelEvent events of the table model. The problem is that if the table model is changed, my class will not be registered to the events anymore. Is there a way to get notified whenever the table model is changed so I can register my class to the new model?
    Thanks.

    Swing related questions should be posted in the Swing forum.
    Since you did post the question there, then you should be responding to that posting stating that you have an answer so people, like me, don't waste their time reading a question that has already been answered.

  • Data changes in JTable cell.

    Hi all,
    On editing a cell in a Jtable ,necessary changes must get enforced in the corresponding cells of the same JTable.For example,I have fields called Quantity ,SalePrice and TotalAmount in a Jtable,where the Quantity field is editable.When i edit the Quantity value,a calculation (Changed Quantity *SalePrice)=TotalPrice must happen .Hence the Total Amount field must get Updated now.This must occur when I edit the Quantity and press Tab.No Button action is involved.Please tell me how to do this.the JTable does not use any TableModel.Thanks in advance.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    As I said in your other post, your table does have a model.
    What you seem to be saying is that your table has some calculated columns. If so then you should create an explicit table model so that when a cell is update the setValueAt() method performs any calculations based on this change and updates the rest of the model.
    Remember to fire the appropriate events after the change.

  • Detecting changes in JTable

    I am using a JTable to display information that the user will update. I would like to wait until all of the changes have been made, then process the updates in response to a button click. Is there a way to determine which cells have been updated without going through the whole table and checking for equality?

    A simple way is this:
    Use the DefaultTableModel.
    Create a custom Class row extends Vector. this represents a row Vector in your data model.
    Add to row class an attribute: for example: boolean changed and set it false in the constructor.
    Now you must write the setValueAt method of the model, where you must read the previous value, sets the new value, and then check for changes and set the changed attribute.
    Finally, in the save ButtonListener you check the changed boolean for all rows.

  • How to change URL of Webservice Model without reconfiguring or creating new

    Hi,
    I have create a WebService Model with DEV url (some Dev URL ) using
    Import WebService Model DEPRECATED option
    Now my application is moving to TEST and PROD.
    Is it possible to change DEV URL in webdynpro application application without reconfiguring MODEL or recreating new
    with TEST and PROD urls.
    Please help me

    Hi,
    You need to use adaptive webservice model to change the webservice URL based on the environment i.e. Dev,Test or production which is availiable in NWDS 2004s environment.
    You can refer to links mentioned in below forum.
    Re: Differnce between adptive web service model and webservice model(depricated
    if you you are using webservice model then you need to write the code to generate URL for end point dynamically based on the application environment.
    and then you need to set EndPoint of webservice model with that URL befroe execution of the model.
    e.g.
    String l_endpointurl ="http://"+ l_Server+ ":"+ l_port+ "/webservice name/Config1?style=document";
    l_modeloobject.modelObject()._setEndPoint(l_endpointurl);
    //if service is secured....
    l_modeloobject.modelObject()._setUser(l_userID);
    l_modeloobject.modelObject()._setPassword(l_pwd);
    l_modeloobject.modelObject().execute();
    Regards,
    Shruti.

  • Change Process Number when modeling DFD

    Hello everyone, I'm currently modeling a Data Flow Diagram for one of my classes. The requirement for the diagram is that each process must have a number like 1.0, 1.1, 1.2, etc. However, when I go to the properties for the process, I can see no way to change this. Every time I create a new process, it just goes 1, 2, 3, etc. So if I create a process out of step, I can't change the number. How do I do this? Thanks.

    Hello,
    use diagram dialog to reorder processes belonging to that diagram.
    Philip

  • Way to listen for change in JTable cell?

    I am having troubles trying to catch a key event while the user is entering text inside a given JTable cell (x/y location). The JTable only seems to manage String objects in it's cells so I can't place a JTextField in there with a KeyListener on it.
    Currently, I can only get control of the application once the user has left the cell they are editing.
    Does anyone have an example of a JTable 'cell KeyListener' scenario? At this point I want to see if I can print 'hello world' each time I type a character within a cell. Then I'll go from there....

    If you want to know when the contents of a cell have been updated you should use a TableModelListener.
    If you want to know when a character is added/removed from the cell editor then you need to first understand how this works with a simple text field.
    Typically you would use a DocumentListener to receive notifies of a change to the text field. However, within the DocumentEvent you wouldn't be able to change the text field as this notification comes after the text field has already been updated.
    If you need to ability to intercept changes to the text field before they happen, then you would need to use a DocumentFilter. An example of using a DocumentFilter is given in the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html#filter]Text Component Features.
    Once you get your regular text field working the way you want, the next step to create a DefaultCellEditor using this JTextField and use this editor in your JTable. The above tutorial also has a section on using editors in a table.

  • Automating scrolling of a JTable when model gets updated

    Hi,
    I have a JTable in a JScrollPane with a table model that updates in real time and I need to keep the currently selected row on the same place on screen (for example when a row is inserted before the selected row I'd like the scroll pane to automatically scroll one row down so the selected row remains at the same location on screen).
    the scrollpane before the row insertion:
    row A
    row B
    row C
    row D (selected)
    row E
    now 'row F' is inserted between B and C
    row B
    row F
    row C
    row D (selected)
    row E
    (row A is scrolled out of sigth and D remains (visually) the 4th row in the view)
    Is there any easy way how to achieve this ? I tried a number of approaches but all end up with an annoying scrollpane jitter.

    I'd try to call JViewPort's scrollRectToVisible(Rectangle contentRect) for the JScrollPane.getViewPort() and keep the parameter Rectangle's size the same (JViewPort.getViewRect()) but adjust the y-position by amount returned by JTable.getRowHeight() + JTable.getRowmargin(). This would be done after row wuold be added and only if vertical scrollbar is visible.
    Maybe this is what you have tried already. Anyway I hope this helps.

  • Changing from full recovery model to simple in sql 2012 always on

    how do I change from a full recovery model to simple in an always on sql 2012 setup? When I try to change it it gave this error

    The physical size of the log file will not change unless you manually shrink the file.  A backup marks the log space as "reusable" internally.
    Please see:
    http://msdn.microsoft.com/en-us/library/ms365418.aspx

  • Where are my columnheader in JTable with model?

    I have drawn a JTable in a form with JBuilder and use the following code. The table is fiiled properly but I don't see the columnheaders.
    How can i make them visible?
    DefaultTableModel model = new DefaultTableModel();
    model.addColumn("Bezoeker_id");
    model.addColumn("Voorletters");
    model.addColumn("Tussenvoegsel");
    model.addColumn("Achternaam");
    model.addColumn("Adres");
    model.addColumn("Postcode");
    model.addColumn("Woonplaats");
    model.addColumn("Telefoonnummer");
    DataInputStream dis = null;
    String record = null;
    int recCount = 0;
    try
    FileInputStream fis = new FileInputStream("C:\\BEZOEKER.dat");
    BufferedInputStream bis = new BufferedInputStream(fis);
    dis = new DataInputStream(bis);
    while ( (record=dis.readLine()) != null )
    if (recCount > 0)
    String[] items = record.split("\t");
    model.addRow(items);
    recCount++;
    catch (IOException ie)
    finally
    // if the file opened okay, make sure we close it
    if (dis != null)
    try
    dis.close();
    catch (IOException ioe)
    jTable1.setModel(model);
    [b/]

    Here is the whole class. The JTabvle is inside a scrollpane but the columnheader still aren't visible. Any idea?
    package thuiszorg;
    import java.awt.BorderLayout;
    import javax.swing.JFrame;
    import javax.swing.JButton;
    import java.awt.*;
    import javax.swing.JTable;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.*;
    import java.util.ArrayList;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.JScrollPane;
    import javax.swing.JPanel;
    import javax.swing.table.*;
    import javax.swing.JScrollBar;
    import javax.swing.JPanel;
    * <p>Title: Thuiszorg</p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2007</p>
    * <p>Company: Avans</p>
    * @author DT2-I4-Groep2
    * @version 1.0
    public class FrameMain extends JFrame {
        public FrameMain() {
            try {
                jbInit();
            } catch (Exception exception) {
                exception.printStackTrace();
        private void jbInit() throws Exception {
            getContentPane().setLayout(null);
            this.setJMenuBar(null);
            this.setResizable(false);
            this.setState(Frame.ICONIFIED);
            this.setTitle("Test");
            jButton2.setBounds(new Rectangle(20, 120, 120, 23));
            jButton2.setText("Hulpmiddelen");
            jButton1.setBounds(new Rectangle(19, 218, 120, 23));
            jButton1.setText("Facturen");
            jButton4.setBounds(new Rectangle(18, 186, 120, 23));
            jButton4.setText("Verhuren");
            jButton3.setBounds(new Rectangle(20, 154, 120, 23));
            jButton3.setText("Hulpmiddelsoorten");
            cmdBezoekers.addActionListener(new FrameMain_cmdBezoekers_actionAdapter(this));
            jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            scrollPane1.setBounds(new Rectangle(181, 86, 590, 358));
            this.getContentPane().add(cmdBezoekers);
            this.getContentPane().add(jButton2);
            this.getContentPane().add(jButton3);
            this.getContentPane().add(jButton4);
            this.getContentPane().add(jButton1);
            this.getContentPane().add(scrollPane1);
            scrollPane1.add(jTable1);
            cmdBezoekers.setBounds(new Rectangle(18, 85, 120, 23));
            cmdBezoekers.setText("Bezoekers");
        public static void main(String[] args) {
            FrameMain framemain = new FrameMain();
            framemain.setSize(800, 600);
            framemain.show();
        JButton jButton2 = new JButton();
        JButton cmdBezoekers = new JButton();
        JButton jButton3 = new JButton();
        JButton jButton4 = new JButton();
        JButton jButton1 = new JButton();
        JTable jTable1 = new JTable();
        ScrollPane scrollPane1 = new ScrollPane();
        public void cmdBezoekers_actionPerformed(ActionEvent e) {
            ArrayList arr = new ArrayList();
            ArrayList arrItem = new ArrayList();
            //DefaultTableModel model = new DefaultTableModel();
            DefaultTableModel model = new DefaultTableModel()
                public boolean isCellEditable(int row, int column) {
                    return false ;
            model.addColumn("Bezoeker_id");
            model.addColumn("Voorletters");
            model.addColumn("Tussenvoegsel");
            model.addColumn("Achternaam");
            model.addColumn("Adres");
            model.addColumn("Postcode");
            model.addColumn("Woonplaats");
            model.addColumn("Telefoonnummer");
            DefaultTableModel f = (DefaultTableModel)jTable1.getModel();
                            f.addColumn("YourName1");
                            f.addColumn("YourName2");
                            f.addColumn("YourName3");
            int listCount = 0;
            DataInputStream dis = null;
            String record = null;
            int recCount = 0;
            try {
                FileInputStream fis = new FileInputStream("C:\\BEZOEKER.dat");
                BufferedInputStream bis = new BufferedInputStream(fis);
                dis = new DataInputStream(bis);
                while ((record = dis.readLine()) != null) {
                    if (recCount > 0) {
                        Bezoeker persoon = new Bezoeker();
                        String[] items = record.split("\t");
                        // persoon.SetBezoekerId((int)items[0]);
                        persoon.SetVoorletters(items[1]);
                        persoon.SetTussenvoegsel(items[2]);
                        persoon.SetAchternaam(items[3]);
                        persoon.SetAdres(items[4]);
                        persoon.SetPostcode(items[5]);
                        persoon.SetWoonplaats(items[6]);
                        persoon.SetTelefoonNummer(items[7]);
                        model.addRow(items);
                    recCount++;
            } catch (IOException ie) {
            } finally {
                // if the file opened okay, make sure we close it
                if (dis != null) {
                    try {
                        dis.close();
                    } catch (IOException ioe) {
           jTable1.setModel(model);
            //JScrollPane myScrollPane = new JScrollPane(jTable1);;
            this.getContentPane().add(scrollPane1);
    class FrameMain_cmdBezoekers_actionAdapter implements ActionListener {
        private FrameMain adaptee;
        FrameMain_cmdBezoekers_actionAdapter(FrameMain adaptee) {
            this.adaptee = adaptee;
        public void actionPerformed(ActionEvent e) {
            adaptee.cmdBezoekers_actionPerformed(e);
    }

  • Howto implement temporary changes / rollback in my model?

    First some background information: I'm building a project management tool. It's based on JEE, Struts 2 and uses AJAX. The model exists as a singleton within the application-server. The model is basically an object tree which consists of projects, releases, usecases, tasks, team members and employees. The model uses the observer pattern to update data when it's necessary. For instance if you change the amount of work required to solve a task, the total amount of work to finish the usecase and the total amount of work to finish the release are updated.
    I've got a dialog where a user can add and remove team members from a task and set multiple attributes on each team member. All these changes will affect the whole model (for instance, if you add an employee to the task-team this has an effect on the availability of this employee for other tasks). In the UI the user will see the result of his actions immediately, for that i need to update the model. But, what if the user hits the Cancel button? Or worse, leaves the dialog open and closes the browser? In that case I need to rollback my model. But since it's almost impossible to notice the closing of the browser reliably, rollback is not an option. So the best thing would be to work on a temporary model when the dialog opens. Then the user may change whatever he wants, and when he finally hits the OK button the temporary model needs to be merged with the "real" singleton-model (Since another user may have changed something in another task).
    Now to my question: How would you implement this? Is there a pattern one could use? Do I really have to clone the whole object tree or is there a better way to solve this?
    Thanks for your replies,
    André

    Thanks for your answers. They gave me some fresh ideas.
    Both approaches go into the same direction somehow. I like the idea of having a simple facade, that hides the complex stuff (like the copy-on-write implementation). Anyway, it really looks like my singleton implementation is too simple for what I'm doing here sigh.

  • Data changes in JTable

    hi experts
    i'm tring to detect the data change in the JTable. The java.sun.com
    gives one ex on this using "TableModelListener". but the program is
    giving errors on using that. I want to detect the data changes
    and also to save the data in its new form. how can i do it??
    Also, if ur having a large table data and the user changes only one cell , do i have to write the whole table back to the database ???
    Ashish

    here is the code. if i write "implements TableModelListener" then
    an error occurs
    import java.sql.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class TableDisplay extends JFrame implements TableModelListener{
    private Connection connection;
    private JTable table;
    public TableDisplay()
    //using JDBC to connect to a Microsoft ODBC database.
    String url = "jdbc:odbc:trial";
    String username = "ashish";
    String password = "ashish";
    // Load the driver to allow connection to the database
    try {
    Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
    connection = DriverManager.getConnection(
    url, username, password );
    catch ( ClassNotFoundException cnfex ) {
    System.err.println(
    "Failed to load JDBC/ODBC driver." );
    cnfex.printStackTrace();
    System.exit( 1 ); // terminate program
    catch ( SQLException sqlex ) {
    System.err.println( "Unable to connect" );
    sqlex.printStackTrace();
    getTable();
    setSize( 500, 350 );
    show();
    private void getTable()
    Statement statement;
    ResultSet resultSet;
    try {
    String query = "SELECT * FROM shippers";
    statement = connection.createStatement();
    resultSet = statement.executeQuery( query );
    displayResultSet( resultSet );
    statement.close();
    catch ( SQLException sqlex ) {
    sqlex.printStackTrace();
    private void displayResultSet( ResultSet rs )
    throws SQLException
    // position to first record
    boolean moreRecords = rs.next();
    // If there are no records, display a message
    if ( ! moreRecords ) {
    JOptionPane.showMessageDialog( this,
    "ResultSet contained no records" );
    setTitle( "No records to display" );
    return;
    Vector columnHeads = new Vector();
    Vector rows = new Vector();
    try {
    // get column heads
    ResultSetMetaData rsmd = rs.getMetaData();
    for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
    columnHeads.addElement( rsmd.getColumnName( i ) );
    // get row data
    do {
    rows.addElement( getNextRow( rs, rsmd ) );
    } while ( rs.next() );
    // display table with ResultSet contents
    table = new JTable( rows, columnHeads );
         table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    JScrollPane scroller = new JScrollPane( table );
    getContentPane().add(
    scroller, BorderLayout.CENTER );
    validate();
    catch ( SQLException sqlex ) {
    sqlex.printStackTrace();
    private Vector getNextRow( ResultSet rs,
    ResultSetMetaData rsmd )
    throws SQLException
    Vector currentRow = new Vector();
    for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
    /* switch( rsmd.getColumnType( i ) ) {
    case Types.VARCHAR:
    currentRow.addElement( rs.getString( i ) );
    break;
    case Types.INTEGER:
    currentRow.addElement(
    new Long( rs.getLong( i ) ) );
    break;
    default:
    System.out.println( "Type was: " +
    rsmd.getColumnTypeName( i ) );
    currentRow.addElement( rs.getString( i ) );
    return currentRow;
    public void shutDown()
    try {
    connection.close();
    catch ( SQLException sqlex ) {
    System.err.println( "Unable to disconnect" );
    sqlex.printStackTrace();
    public static void main( String args[] )
    final TableDisplay app = new TableDisplay();
    app.addWindowListener(
    new WindowAdapter() {
    public void windowClosing( WindowEvent e )
    app.shutDown();
    System.exit( 0 );

  • Change of Jtable feature select in 1.5?

    I have a JTable Object, with 12 columns and 32 rows.
    when the user want to populate the first eight rows there is no problem, they begin ant the rown 0 column 0, But when the user want to capture only from the 9 to 16 row, they select those range, but until the version 1.4.2, the cursos was positioned in the first row&colum selected.
    But after jdk 1.5.x, the cursor focus focus is in the last row&column selected..
    How can I make that the first position select get the focus in the JTable?
    In other worksheet have this feature, fouc son the first colun&row selected.
    why Java change it?
    Please help me out.

    The problem is not how to select an interval.
    The problem is the position of the cursor when finalizing the selection of an interval.
    In the versions prior at the 1.5 was positioned at the beginning of the selection and not to end.
    But since version 1.5, the focus on the table have the last position selected.
    Look the excel feature or another worksheet, and the focus always is the first cell selected.
    Thnaks

Maybe you are looking for