Custom table model, table sorter, and cell renderer to use hidden columns

Hello,
I'm having a hard time figuring out the best way to go about this. I currently have a JTable with an custom table model to make the cells immutable. Furthermore, I have a "hidden" column in the table model so that I can access the items selected from a database by their recid, and then another hidden column that keeps track of the appropriate color for a custom cell renderer.
Subject -- Sender -- Date hidden rec id color
Hello Pete Jan 15, 2003 2900 blue
Basically, when a row is selected, it grabs the record id from the hidden column. This essentially allows me to have a data[][] object independent of the one that is used to display the JTable. Instinctively, this does not seem right, but I don't know how else to do it. I know that the DefaultTableModel uses a Vector even when it's constructed with an array and I've read elsewhere that it's not a good idea to do what I'm trying to do.
The other complication is that I have a table sorter as well. So, when it sorts the objects in the table, I have it recreate the data array and then set the data array of the ImmutableTableModel when it has rearranged all of the items in the array.
On top of this, I have a custom cell renderer as well. This checks yet another hidden field and displays the row accordingly. So, not only does the table sort need to inform the table model of a change in the data structure, but also the cell renderer.
Is there a better way to keep the data in sync between all of these?

To the OP, having hidden columns is just fine, I do that all the time.. Nothing says you have to display ALL the info you have..
Now, the column appears to be sorting properly
whenever a new row is added. However, when I attempt
to remove the selected row, it now removes a seemingly
random row and I am left with an unselectable blank
line in my JTable.I have a class that uses an int[] to index the data.. The table model displays rows in order of the index, not the actual order of the data (in my case a Vector of Object[]'s).. Saves a lotta work when sorting..
If you're using a similar indexing scheme: If you're deleting a row, you have to delete the data in the vector at the INDEX table.getSelectedRow(), not the actual data contained at
vector.elementAt(table.getSelectedRow()). This would account for a seemingly 'random' row getting deleted, instead of the row you intend.
Because the row is unselectable, it sounds like you have a null in your model where you should have a row of data.. When you do
vector.removeElementAt(int), the Vector class packs itself. An array does not. If you have an array, when you delete the row you must make sure you dont have that gap.. Make a new array of
(old array length-1), populate it, and give it back to your model.. Using Vectors makes this automatic.
Also, you must make sure your model knows the data changed:
model.fireTableDataChanged(); otherwise it has no idea anything happened..
IDK if that's how you're doing it, but it sounds remarkably similar to what I went thru when I put all this together..

Similar Messages

  • My camera Canon G3 (i know it's old) no longer connects to iPhoto (8.1.2) on my iMac, I have checked with my friends iMac same model iPhoto version and it works fine using my cable, I would appreciate any help getting this sorted

    My camera Canon G3 (i know it's old) no longer connects to iPhoto (8.1.2) on my iMac, I have checked with my friends iMac same model iPhoto version and it works fine using my cable, I would appreciate any help getting this sorted

    As a Test:
    Hold down the option (or alt) key and launch iPhoto. From the resulting menu select 'Create Library'
    Import a few pics into this new, blank library. Is the Problem repeated there?

  • Copyig Data from a TABLE MODEL (TABLE) TO A FILE

    Hi guys,
    I wont to copy data from a Default Table Model to a File can someone write a pease of code that will do that for me.
    DefaultTableModel model = new DefaultTableModel();
    JTable table;
    public basic()
              super();
                  model.addColumn("Full Name");
                  model.addColumn("House No");
                  model.addColumn("Address");
                  model.addColumn("Town/County");
                  model.addColumn("Postcode");
                  model.addColumn("Telephone Number");
                  model.addColumn("Email Address");             
                  String[] socrates = { "Example", "33", "York RD", "Poole", "BH18 9RE", "01202776655", "[email protected]" };
                  model.addRow(socrates);
              /**This is the main setup for the Address Book
              *This has the main settings for the size, title
              *And main features of the Address book.
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.setSize(new Dimension(800, 600));
              this.setTitle("Large Print Address Book");
              this.setLayout(new FlowLayout ());
              //Main Application Parts
              JLabel welcome = new JLabel("Welcome to Thomas's Address Book v2.0.1");
              welcome.setFont(arial20);
              this.add(welcome);
              //Menu Bar
              JMenuBar mb = new JMenuBar();
              this.setJMenuBar(mb);
              //Table
              table = new JTable(model);
              this.add(table);
              JMenu fm = new JMenu("File");
              fm.setFont(arial20);
              mb.add(fm);
              //Menu Items          
              JMenuItem Add = new JMenuItem("Add Record");
              Add.setFont(arial20);
              Add.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e) 
                        addw a = new addw();                    
              fm.add(Add);
              //Import from a file
              JMenuItem inp = new JMenuItem("Import Records");
              inp.setFont(arial20);
              inp.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e) 
                        //Opens Import Window.
                        inportw i = new inportw();                    
              fm.add(inp);
              JMenuItem quit = new JMenuItem("Exit");
              quit.setFont(arial20);
              fm.add(quit);
              quit.addActionListener(this);
    class inportw extends JFrame
              //*Add Window Properties and Settings
              public inportw ()
                   this.setSize(new Dimension(400, 150));
                   this.setTitle("Inport Records");
                   this.setLayout(new FlowLayout ());
                   this.setVisible(true);
                   //Nmae
                   JLabel error_note = new JLabel("Error Here - Need to make table final!?");
                   error_note.setFont(arial20);
                   this.add(error_note);
                   //Add Button
                   JButton binport = new JButton("Inport");
                   binport.addActionListener(new ActionListener()
                        public void actionPerformed(ActionEvent e) 
                             ArrayList data = new ArrayList();          
                   this.add(binport);
         public void actionPerformed(ActionEvent e)
              System.out.println("Application Exit");
              System.exit(0);
         public static void main(String[] args)
              basic b = new basic();
              The information from the atable needs to go into a .txt file with each row on a new line. It also needs to be in the inport/export window that is in a class on its own when someone clicks export.
    A complete peace of code would be helpfull that would do this for me. Thankyou guys.

    Rite then,
    In answer to both post yes i have done my own homework if thats what you wont to call it.
    And to the second post yes i have put in a File to export to. the code has not be pasted on my origanal post.
    //Export Button - Export Window
                   JButton bexport = new JButton("Export (BUAB)");
                   bexport.addActionListener(new ActionListener()
                        public void actionPerformed(ActionEvent e) 
                             System.out.println("Export Pressed ");
                             try
                                 FileWriter file = new FileWriter("AddressData.txt");
                                BufferedWriter out = new BufferedWriter(file);
                                 out.write("AddressBook data File");
                                out.close();
                             catch (Exception ei)
                             System.err.println("Error: " + ei.getMessage());
                   this.add(bexport);This is the export button,
    I think the code for the table model should be something like this:
    I wont to do something like this
    model.getModel().getValueAt(0, 0);
    Arrylist data = new arrylist();
    try
                                 FileWriter ffile = new FileWriter("AddressData.txt");
                                BufferedWriter out = new BufferedWriter(file);
                                 out.write(data);
                                out.close();
                             catch (Exception ei)
                             System.err.println("Error: " + ei.getMessage());
                                 }          Im not 100% sure how to get the information from the model into the arrylist, though a loop.
    If there is a section of a webpage that may help could someone please post it for me.
    Unfortunatly for me Im visualy impaired and find some of this hard. I learn though looking at examples and creating my own programs that do something similar.
    If no one wonts to help then that fine with me !

  • Custom tool bar for sorting and summing in alv grid

    what is the function module to use the tool bar in the alv output screen which has - summing , sorting and other button above the alv grid control.

    It is part of the class CL_GUI_ALV_GRID. Have a look at this class, especially the methods within this class, and search for 'SORT' or 'TOTAL' using the button with 'Binoculars' icon.

  • Sorting and Grouping by multi-value Choice columns - any options?

    I found out the hard way that SharePoint doesn't support sorting or grouping lists by Choice columns that are set to "Allow Multiple Values." I'm stunned by this missing capability, and my project has come to a complete halt without it. It's like Microsoft only implemented hafl the feature -- you can put data in, but then you can't do anything with it. You can't even use the column in a formula in another column, so you can't parse it.
    I'm not posting just to gripe though. Does anyone have any suggestions for alternatives? What do you do when you need to let people make multiple selections, and then you want to sort or group by those values? Are there any add-on products that allow this? At this point my only option seems to be to not allow multiple choices, but that's taking away a rather significant feature.
    Thanks for any ideas,
    Steve

    Hi Paul,
    Thank you for the reply and the additional questions. For my situation I want to use the multi-value choice to indicate a "belongs to" relationship, as in "this item belongs to projectA, projectB, and project C. Because there are more than 10 projects, I didn't want to create a separate Yes/No checkbox for each one.
    For viewing the information, I'm looking primarily for a "group by" function.  So if an item belongs to projectA, projectB, and projectC, it would appear three times, once under the grouping for each project. What I don't want is for a row that only belongs to projectA to be grouped separately from a row that belongs to both projectA and projectB. I want to see all the rows that belong to projectA grouped together, regardless of whether they also belong to other projects.
    I'll look into using a grid control, but if you have any other suggestions I'll certainly listen.
    Steve

  • How can I export table and cell styles to use in another InDesign document?

    I've been looking…and looking but can't find out how to export table styles within InDesign CC. If there is a load table styles option within the panel, it stands to reason there should be an export. Any help would be appreciated, thanks.

    Frank,   John's solution is it.    But that also requires that you have those old files easily on hand to access.  Maybe even searching for them in the future, 3 months down the road, could be a pain.   You can always save a Library for that file and drag some of those styled elements into that library.   Save the library in a place that you will keep access to and readily pull assets from.   In the future doc open that library and drag the styled element into your new document and the styles are now in the new doc to reuse.   I have a library saved just for tables.

  • What is the best way to dynamically create table partition by year and month based on a date column?

    Hi,
    I have a huge table and it will keep growing. I have a date column in this table and thought of partition the table by year and month. Can any you suggest better approach so that partition will create automatically for new data also along with the existing
    data? Nothing but automatically/dynamically partition should create along with file group and partition files.
    Thanks in advance!
    Palash 

    Also this one
    http://weblogs.sqlteam.com/dang/archive/2008/08/30/Sliding-Window-Table-Partitioning.aspx
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • Setting Table Cell Renderer for a row or cell

    I need to make a JTable that has the following formats:
    Row 1 = number with no decimals and columns
    Row 2 = number with no decimals and columns
    Row 3 = percent with 4 decimals
    I can use a table cell renderer to set each COLUMN as one or the other formats like this:
    NumDispRenderer ndr = new NumDispRenderer();
    for(int i = 1;i<dates.size();i++) {
    table.getColumnModel().getColumn(i).setCellRenderer(ndr);
    Where NumDispRenderer is a class as follows:
    public class NumDispRenderer extends DefaultTableCellRenderer {
    public Component getTableCellRendererComponent (JTable table, Object value,boolean isSelected, boolean isFocused, int row, int column) {
    Component component = super.getTableCellRendererComponent (table,value,isSelected,isFocused,row,column);
    if (value != null && value instanceof Double) {
    DecimalFormat df = new DecimalFormat("###,###");
    String output = df.format(value);
    ((JLabel)component).setText(output);
    ((JLabel)component).setHorizontalAlignment(JLabel.RIGHT);
    } else {
    ((JLabel)component).setText(value == null ? "" : value.toString());
    return component;
    This is fine for the first two rows, but the third row (which is also an instance of Double) I would like to format differently.
    The tutorial and other postings have not given a solution to this problem. Any suggestions would be very appreciated.

    Hi,
    the method getTableCellRendererComponent() of your renderer gets the row as a parameter. So just create the label depending on that value. For 0<=row<=1 you create the label as is, and for row=2 you create another label with the Double formatted as you wish.
    Andre

  • Sort and filter option missing in table view

    Hi,
    I am not able to see the sort and filter option for all the columns in table view. Could anyone please help me if i need to add something to see that option.
    Thanks,
    Kamesh Bathla

    Hi,
    Thanks for the reply, yes its web UI issue, i am having search and result view and i need sorting option for all the columns in result view. I thought that it is standard functionality, do i need to add something to html file or anyother place to see the sorting options?
    Regards,
    Kamesh Bathla

  • TableSorter + custom cell renderer: how to get DISPLAYED value?

    Hi!
    I have a JTable with a custom cell renderer. This renderer translates numerical codes, which are stored in the table model, into textual names. E.g. the table model stores country codes, the renderer displays the name of the country.
    Now, having a reference on the JTable, how can I get the DISPLAYED value, i.e. the country name? Is there some method like ....getRenderer().getText()?
    Thanx,
    Thilo

    Well, a renderer can be anything. It may be rendering an image not text so you can't assume a method like getText(). However, since you know the component being used to render the cell you should be able to do something like:
    TableCellRenderer renderer = table.getCellRenderer(row, column);
    Component component = table.prepareRenderer(renderer, row, column);
    Now you can cast the component and use get text.
    Another option would be to store a custom class on the table cell. This class would contain both the code and value. The toString() method would return the value. Whenever you want the code you would use the table.getValueAt(...) method and then use the classes getCode() method. Using this approach you would not need a custom renderer. This thread shows how you can use this approach using a JComboBox, but the concept is the same for JTable as well:
    http://forum.java.sun.com/thread.jsp?forum=31&thread=417832

  • Table Rendering - Row level vs Column level

    Normally renderers are specified for a given class of data or column of data.
    So, how would you handle rendering requirements that are row or table dependent? For example, how do I:
    a) color alternate lines in a table
    b) change the border of the selected cell
    Traditional Approach
    Most answers in the forum would be something like "use a custom render". Sounds great, but what does it really mean? If all your data is displayed as a String then it really isn't too difficult to create a single renderer with the required logic and add it to the table as the default renderer.
    However, what if you table contains, String's, Dates, Integer's, Double's and Boolean's and you want your cell to retain the default formatting of each data type in addition to the above requirement? Now you have two options:
    a) render by class (multiple renderers). Each renderer would need to implement the default "formatting" of the data (dates: dd-MMM-yyy, numbers: right justified, etc) in addition to the "row/table" rendering requirements. So the answer really becomes "use five custom renderers". Now the "row/table" rendering code is found in 5 classes. Of course you could always move the "row/table" rendering code up to a common base class.
    b) render by table (single renderer). A single custom renderer would be created and would need to implement the default "formatting" for all data types in the table, in addition to the "row/table" rendering. The benefit is that all the rendering code is in one class. An example solution is include for this approach.
    Alternative Approach
    I recently came across an approach where the "formatting" of the data is still done by the default renderers and the "row/table" rendering is done at the table level by overriding the prepareRenderer() method. This approach is much simpler, but the rendering is done in two different places. Is this a problem?
    So, my question is which approach do you prefer:
    a) Traditional Approach - multiple renderers
    b) Triditional Approach - single renderer
    c) Alternative Approach
    Me, I like the alternative approach, but I'm more of a problem solver than I am a designer, so I don't know how the solution fits in a large scale application.
    Hopefully your response will consider:
    a) OO design principles
    b) class reusability
    c) class maintenance
    d) anything else you can think of
    import java.awt.*;
    import java.text.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    public class TableRowRendering extends JFrame
        JTable table;
        Border selected = new LineBorder(Color.GREEN);
        public TableRowRendering()
            //  Model used by both tables
            Object[] columnNames = {"Type", "Date", "Company", "Shares", "Price"};
            Object[][] data =
                {"Buy", new Date(), "IBM", new Integer(1000), new Double(80.50)},
                {"Sell",new Date(), "MicroSoft", new Integer(2000), new Double(6.25)},
                {"Sell",new Date(), "Apple", new Integer(3000), new Double(7.35)},
                {"Buy", new Date(), "Nortel", new Integer(4000), new Double(20.00)}
            DefaultTableModel model = new DefaultTableModel(data, columnNames)
                public Class getColumnClass(int column)
                    return getValueAt(0, column).getClass();
            //  Traditional Approach
            table = new JTable( model );
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            getContentPane().add(new JScrollPane( table ), BorderLayout.WEST);
            TableCellRenderer custom = new CustomRenderer();
            table.setDefaultRenderer(Object.class, custom);
            table.setDefaultRenderer(String.class, custom);
            table.setDefaultRenderer(Date.class, custom);
            table.setDefaultRenderer(Number.class, custom);
            table.setDefaultRenderer(Double.class, custom);
            //  Alternative Approach
            table = new JTable( model )
                public Component prepareRenderer(
                    TableCellRenderer renderer, int row, int column)
                    Component c = super.prepareRenderer(renderer, row, column);
                    if (!isRowSelected(row))
                        String type = (String)getModel().getValueAt(row, 0);
                        c.setBackground(row % 2 == 0 ? null : Color.LIGHT_GRAY );
                    if (isRowSelected(row) && isColumnSelected(column))
                        ((JComponent)c).setBorder(selected);
                    return c;
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            getContentPane().add(new JScrollPane( table ), BorderLayout.EAST);
        //  Custom renderer used by Traditional approach
        class CustomRenderer extends DefaultTableCellRenderer
            DateFormat dateFormatter = SimpleDateFormat.getDateInstance(DateFormat.MEDIUM);
            NumberFormat numberFormatter = NumberFormat.getInstance();
            public Component getTableCellRendererComponent(
                JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column)
                super.getTableCellRendererComponent(
                    table, value, isSelected, hasFocus, row, column);
                //  Code for data formatting
                setHorizontalAlignment(SwingConstants.LEFT);
                if ( value instanceof Date)
                    setText(dateFormatter.format((Date)value));
                if (value instanceof Number)
                    setHorizontalAlignment(SwingConstants.RIGHT);
                    if (value instanceof Double)
                        setText(numberFormatter.format(((Number) value).floatValue()));
                //  Code for highlighting
                if (!isSelected)
                    String type = (String)table.getModel().getValueAt(row, 0);
                    setBackground(row % 2 == 0 ? null : Color.LIGHT_GRAY );
                if (table.isRowSelected(row) && table.isColumnSelected(column))
                    setBorder(selected);
                return this;
        public static void main(String[] args)
            TableRowRendering frame = new TableRowRendering();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setLocationRelativeTo( null );
            frame.setVisible(true);
    }Before you make your final decision. What changes would be required for each solution in the following "what if " scenarios:
    a) what if, you added a Boolean column to the table
    b) what if, you added a second Double column to the table which should be formatted as a currency (ie. 1,234.5 --> $1,234.50).
    Here is an example of a currency renderer:
    class CurrencyRenderer extends DefaultTableCellRenderer
         private NumberFormat formatter;
         public CurrencyRenderer()
              super();
              formatter = NumberFormat.getCurrencyInstance();
              setHorizontalAlignment( SwingConstants.RIGHT );
         public void setValue(Object value)
              if ((value != null) && (value instanceof Number))
                   value = formatter.format(value);
              super.setValue(value);
    }

    Well, here's a partila solution using technique from a link you cited in another thread.
    import tests.basic.tables.ColorProvider;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.text.NumberFormat;
    public class DecoratedTablePrepareRenderer extends JFrame {
        JTable table;
        private DefaultTableModel model;
        public DecoratedTablePrepareRenderer() {
            Object[] columnNames = {"Type", "Company", "Price", "Shares", "Closed"};
            Object[][] data =
                        {"Buy", "IBM", new Double(80.50), new Double(1000), Boolean.TRUE},
                        {"Sell", "MicroSoft", new Double(6.25), new Double(2000), Boolean.FALSE},
                        {"Sell", "Apple", new Double(7.35), new Double(3000), Boolean.TRUE},
                        {"Buy", "Nortel", new Double(20.00), new Double(4000), Boolean.FALSE}
            model = new DefaultTableModel(data, columnNames);
            table = new JTable(model) {
                //  Returning the Class of each column will allow different
                //  renderers to be used based on Class
                public Class getColumnClass(int column) {
                    return getValueAt(0, column).getClass();
                public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
                    Component c = super.prepareRenderer(renderer, row, column);
                    if (isRowSelected(row))
                        c.setFont(c.getFont().deriveFont(Font.BOLD));
                    return c;
            ColorProvider prov = new TransactionColorProvider();
            ColorTableCellRenderer renderer = new ColorTableCellRenderer(table.getDefaultRenderer(Object.class),prov);
            ColorTableCellRenderer boolrenderer = new ColorTableCellRenderer(table.getDefaultRenderer(Boolean.class),prov);
            ColorTableCellRenderer doublerenderer = new ColorTableCellRenderer(table.getDefaultRenderer(Double.class),prov);
                    int priceIndex = model.findColumn("Price");
              table.getColumnModel().getColumn(priceIndex).setCellRenderer( new EtchedBorderTableCellRenderer(new ColorTableCellRenderer(new CurrencyRenderer(),prov) ));
            table.setDefaultRenderer(Object.class,new EtchedBorderTableCellRenderer(renderer));
            table.setDefaultRenderer(Double.class,new EtchedBorderTableCellRenderer(doublerenderer));
            table.setDefaultRenderer(Boolean.class, new EtchedBorderTableCellRenderer(boolrenderer));
            JScrollPane scrollPane = new JScrollPane(table);
            getContentPane().add(scrollPane);
        class CurrencyRenderer extends DefaultTableCellRenderer {
            private NumberFormat formatter;
            public CurrencyRenderer() {
                super();
                formatter = NumberFormat.getCurrencyInstance();
                setHorizontalAlignment(SwingConstants.RIGHT);
            public void setValue(Object value) {
                if ((value != null) && (value instanceof Number)) {
                    value = formatter.format(value);
                super.setValue(value);
        public static void main(String[] args) {
            DecoratedTablePrepareRenderer frame = new DecoratedTablePrepareRenderer();
            frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        class ColorTableCellRenderer implements TableCellRenderer{
            protected TableCellRenderer delegate;
            protected ColorProvider provider;
            public ColorTableCellRenderer(TableCellRenderer delegate, ColorProvider provider) {
                this.delegate = delegate;
                this.provider = provider;
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                Component c = delegate.getTableCellRendererComponent(table, value,isSelected,hasFocus,row, column);
                  c.setBackground(provider.getBackgroundColor(row, column));
                return c;
          class EtchedBorderTableCellRenderer implements TableCellRenderer{
            protected TableCellRenderer delegate;
            public EtchedBorderTableCellRenderer(TableCellRenderer delegate) {
                this.delegate = delegate;
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                JComponent c = (JComponent)delegate.getTableCellRendererComponent(table, value,isSelected,hasFocus,row, column);
                  JPanel panel = new JPanel(new GridLayout(0,1));
                  panel.add(c);
                  panel.setBorder(BorderFactory.createEtchedBorder());
                return panel;
        class TransactionColorProvider implements ColorProvider {
            private int keyIndex = 0;
            private Color sellColor = Color.yellow;
            private Color buyColor = Color.green;
            public TransactionColorProvider() {
                keyIndex = model.findColumn("Type");
            public Color getBackgroundColor(int row, int column) {
                 if( model.getValueAt(row,keyIndex).equals("Sell")){
                     return sellColor;
                else {
                     return buyColor;
            public Color getForegroundColor(int row, int column) {
                return Color.black;
    }Boolean values are problematical since JCheckBox does seem to like borders, using a panel as I did in the Etched renderer seems to work. This solution need a little more work, this is submitted as a prototype
    Cheers
    DB

  • JTable: Custom cell renderer on T(row, col)

    Sorry if this was posted before, but the whole Search function doesn't seem to work these days (hasn't been working for a week now). Anyways:
    I know how to create custom cell renderers. My problem lies with which cells I want to apply that cell renderer to. It seems I am limited in setting a cell renderer to a whole column, which I don't want.
    For instance, I'd like to apply cell renderer R1 to (0,0) but not to (1,0) and not to (3,0). Instead I want cell renderer R2 on (2,0) and (3,0).
    Example of my table:
    |--icon--|--filename--|--extension--|
    |   R1   |  file1.txt |     txt     |
    |   R2   |  img1.jpg  |     jpg     |
    |   R1   |  file2.txt |     txt     |
    |   R2   |  img2.jpg  |     jpg     |
    |-----------------------------------|Is there any possibility this can be achieved? I am probably overlooking some method or class, but I don't know which. Some pointers or clues in the right directions are appreciated.
    Thanks

    Camickr, again you've been a great help. Works great, but a NullPointerException is being thrown and I can't find out what points to a null object.
    Code is this:
        public TableCellRenderer getCellRenderer(int row, int column) {
            if (getValueAt(row, 3).equals("jpg") && column == 0) {
                return new IconCellRenderer(Klue.iconAdd);
            } else {
                return super.getCellRenderer(row, column);
        }Solution is catching the NullPointerException in this method, but I'd rather have an if statement checking for it. But what to check? Any ideas?

  • FireTableStructureChanged and cell renderers

    Greetings,
    I am having an issue that google hasn't been able to resolve.
    I have a JTable with a few columns whose cells are "multi-line" (aka, Strings with one or more '\n' in them). Since the default renderers don't display the newlines, I searched google for a solution. I found this article: [http://www.javaspecialists.eu/archive/Issue106.html|http://www.javaspecialists.eu/archive/Issue106.html] and copy/pasted it into my program, and it completely solved my problems. I just set the cell renderer for the proper columns to be that renderer.
    My problem is this: I also need to implement custom headers that refresh immediately upon being selected. I have a table model that I just send the new headers to, it repopulates the TableModel headers and data, and then I call fireTableStructureChanged(). This works beautifully, except it seems to erase the custom renderers mentioned above.
    A google result site suggested setting table.setAutoCreateColumnsFromModel(false).. However, this seems to do nothing but completely disable the fireTableStructureChanged() method from working.
    I will work on getting a compilable example soon, but I am posting this just incase anyone is familiar with this issue, it will save me the trouble.
    Thank you.

    I understand and agree. However, resetting the renderers doesn't seem to be working.
    Here is the code I tried to use to implement the renderers:
            WatchListTable.getModel().addTableModelListener(new TableModelListener() {
                public void tableChanged(TableModelEvent e) {
                    if(e.getFirstRow() == TableModelEvent.ALL_COLUMNS){
                        TableColumn column3;
                        column3 = WatchListTable.getColumn("Location");
                        column3.setCellRenderer(new TextAreaRenderer());
                        column3 = WatchListTable.getColumn("Available Quantity");
                        column3.setCellRenderer(new TextAreaRenderer());
            });The code inside the if statement is copy/paste what I use to set the original renderers, so that code works in general, just not here for some unknown reason?
    That event and if statement both execute well (System.out.prints show that the if statement executes). But the set cell renderer methods don't change anything.
    I've also tried setting the viewPortView for the table's scroll pane and WatchListTable.repaint() and nothing seems to do anything.
    Any suggestions?

  • JTable Cell Renderer problems

    Hi,
    I ahve created a cellRenderer so that it renders jCheckBox in the cell. However, the check boxes are intended for use by boolean values, and thats how they work best. However the problem i am having is that i want to render the boxes into cells that have either a 1 or 0. I have managed to do this and display the correct state of the box but when i want to make changes i have to change the value 0 or 1 inorder to change the check box. Is there a way i can select or deselect the checkbox when editing???
    Thanks in advance
    Rudy

    Hi,
    I am going to change my table model to try and make it more generic. However before i do so and mess everything up i would like to know if the following will work.
    1. I will pass to the constructor names of columns that i want to be rendered as checkboxes.
    2. I will then get the column index of that column using
    public int getColumnIndex(String name) {
        for(int i = 0; i < columnNames.length; i++){
          if(columnNames.trim().equals(name)){
    return i;
    return -1; //if fails
    3. In my get columnclass which is implemented as follows (from java demo)
    public Class getColumnClass(int column) {
        int type;
        try {
          type = metaData.getColumnType(column + 1);
        catch (SQLException e) {
          return super.getColumnClass(column);
        switch (type) {
          case Types.CHAR:
          case Types.VARCHAR:
          case Types.LONGVARCHAR:
            return String.class;
          case Types.BIT:
            return Boolean.class;
          case Types.TINYINT:
          case Types.SMALLINT:
          case Types.INTEGER:
            return Integer.class;
          case Types.BIGINT:
            return Long.class;
          case Types.FLOAT:
          case Types.DOUBLE:
            return Double.class;
          case Types.DATE:
          case Types.TIMESTAMP:
            return java.sql.Date.class;
          default:
            return Object.class;
    }I can add a condition that "if column (int) == the indexes if previously retrieved then return boolean class"
    With this work columns that has either Y, N or null or 0, 1, or null???
    I may change the columnNames to a vector so that i can use the contains method and therefore not need to find the index.
    Will this work???
    Thanks
    Rudy

  • Sorting the Model vs sorting the JTable

    So,
    now that I'm starting the rewrite of my program, I wanted to avoid as much dependencies as possible from the table component.
    This, because my table (SwingX JXTable actually) gave me occasional problems and artefacts.
    So, when I want to sort the data in the table, or filter it for example,
    would it be faster to:
    - sort the data model and reset the data in the table
    or
    - don't do anything with the model and let the table do the sorting and filtering?
    Thanks in advance.

    To OP:
    Your question is contradictory.
    First you want to avoid dependencies "from the table component" (I ssume you mean "on JXTable API"). Then you go on asking what would be "faster".
    Other criteria that might be of interest (in addition to "dependencies maintenance" and "speed"), could be:
    - memory usage: if you already know to filter, at the model level, your 1-M customer orders table, into a 10-lines summary for the current customer, then obviously you'll gain memory at the view level.
    - ease of programming: if all order data are in-memory, and you can switch from one customer to the other, filtering at the view level spares one call into the model layer, and probably one DB call as well. A UI developper will be more confortable.
    These are contrived examples, I just want to point out that "it depends" on what are your constraints (interactions, app-specific requirements, staff skill,...).
    AFAIC, I don't remember having problems with sorting and filtering using Swing's native RowSorter API (I did shoot myself in the foot because I sometimes forgot to convert indices, view-to-model and model-to-view, in the event handlers, but once you remember that you're safe).
    Maybe check on a SwingX forum for the (maybe SwingX-specific) artefacts.
    Edited by: jduprez on Jul 13, 2009 7:10 AM

Maybe you are looking for

  • Firefox wont restore my previous session, for the first time, and I need it back!

    I use "restore previous session" religiously. Whenever i shut down, whether due to a problem or just normally, "restore previous session" is there and restores all my tabs. Sometimes after a crash, I get the "well, this is embarrassing" but when I cl

  • JSF doesn't set values for optionally rendered fields

    When I enter a value into an optionally rendered inputText, the resulting object property is never updated, but when I remove the "rendered=" code then the objects set property works every time. I am using the version of JSF that downloads with the l

  • Mail.app signature bug

    I'm attempting to edit a rather massive email signature on my iPhone 4 which I need for work (16 lines) and I have found that after I attempted to re-edit it, that I was no longer able to view the editing box on the screen fully.  The screen had jamm

  • Dynamic connection pooling

    Hi! Is there a way I can create a dynamic connection pool and associate it to a DataSource using weblogic. I know I can't create a datasource dynamically, so are there any work arounds to bind the dynamically created connection pool to configured dat

  • [Solved]Fail to use wired connection, but can still use wireless.

    I had suspected the problem to be related to a recent package update from any time between 6/2 to 6/5, though the problem only started yesterday(6/6 in my time zone). I have already tried downgrading internet related packages that has recent upgrades