Changing backgroundin JTable

I have a JTable wich display boolean. I want to change the background color depending on wich column i am. I tried using my own class extending DefaultCellRenderer but i remove "the checkbox" style of all the cells.
Any ideas of keeping the checkbox style and setting the bakground the color i want.
Thanks

myTable.getTableHeader().getColumnModel().getColumn(0).setHeaderValue("Foo");

Similar Messages

  • 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

  • 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.

  • 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.

  • 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

  • How to resize Labels size based on the column margin changes in JTable??

    I have a constructed JTable with 4 columns. Accordingly, I added 4 JLabels for each column. JTable and JLabels are attached to a scrollpane. That in turn, attached to a JFrame.
    What I need is, at the runtime, when I change the column margins of a column in JTable, accordingly, the size/margins of the Labels should change..
    I am extending AbstractTableModel in order to populate the data in the table, as I should have a checkbox in the constructed JTable.
    Please, help me out in finding a solution for this...

    Hi pritam,
    The “maintain proportions of window for different monitor
    resolutions” property will maintain the proportional size of the front panel
    (its x and y sizes) when opened in a different resolution. The front panel
    objects will not be resized and will appear larger (and may not fit inside the
    front panel) when saved in a higher resolution, and moved to a lower
    resolution. You can use the “Keep window proportions” property to achieve the
    same results.
    To have both the front panel dimensions and front panel
    controls scale, you need to have both the above property and the “scale all
    objects on front panel as the window resizes” selected. The labels will not be
    resized by this.
    I tried using both properties on two monitors and noticed
    that the change does not occur when the resolutions between the monitors are
    different. I had to lower both monitors’ resolution to see the change work
    properly.
    Please post back if you have any questions. Have a great day!
    Ryan D.
    District Sales Manager for Boston & Northern New England
    National Instruments

  • Changing default JTable column headings

    Hi,
    I've created a simple JTable using the following constructor:
    JTable table = new JTable ( numRows, numCols);
    and I would now like to change the default column headings ("A", "B", "C" etc) to something else. I'm trying to use the following method
    setColumnIdentifiers
    but how do I access the DefaultTableModel associated with table so that I can call this method?
    Is there another way of changing the headings of my simple table?
    Thanks a lot,
    Leori.

    myTable.getTableHeader().getColumnModel().getColumn(0).setHeaderValue("Foo");

  • 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.

  • Event cell change at JTable ?

    this my table column:
    Product Name, Price, Qty, Total
    and total=price*qty
    how to create event change in table,
    when cell of price or qty change total found ??
    this my code :
    package sample;
    import javax.swing.*;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.*;
    * @author Yusuf Hermanto
    public class Table1 extends JFrame {
        JTable tbl;
        private String tblCol[] = {
           "Product Name","Price","Qty","Total"
        private String tblRow[][]= {
            {"Computer","","",""},
            {"Phone","","",""}
        public Table1(){
            super("My Table");
            setSize(500,500);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            tbl = new JTable();
            tbl.setModel(tm);
            JScrollPane jsp = new JScrollPane(tbl);
            add(jsp);
        TableModel tm = new AbstractTableModel() {
            public int getRowCount() {
               return tblRow.length;
            public int getColumnCount() {
               return tblCol.length;
            public String getColumnName(int columnIndex) {
                return tblCol[columnIndex];
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                if(columnIndex==1 || columnIndex==2){
                    return true;
                }else{
                    return false;
            public Object getValueAt(int rowIndex, int columnIndex) {
                return tblRow[rowIndex][columnIndex];
            public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
               tblRow[rowIndex][columnIndex]=(String) aValue;
        public static void main(String[] args){
            new Table1().setVisible(true);
    }

    1) There is no need to create a custom TableModel for this. Learn how to use the DefaultTableModel.
    2) This link shows you how to use the DefaultTableModel and how to add a TableModelListener to it:
    [http://forums.sun.com/thread.jspa?forumID=57&threadID=566133]

  • How to change the Background color of a cell in JTable

    hi!
    Actually i want to change the background color of few cells in JTable
    is there any method to make this change in JTable ?
    and also is it possible to have 5 rows with single column and 5 rows with 3 columns in a single JTable

    i want to change the background color of few cells in JTableDepending on your requirements for the coloring of cells it may be easier to override the prepareRenderer() method of JTable:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=610474

  • Edited/Changed Value tracking in Jtable

    how will i keep track of all the values of a only those cells that are edited(changed) in Jtable having multiple row and columns.
    The reason for this is that I want to build a dynamic update query which updates only those cells(JTable corresponds to a resultset) that are changed.

    http://forum.java.sun.com/thread.jsp?forum=57&thread=234558

  • JTable Cell Focus Change

    Hi all,
    Is it possible to keep track the cell focus change in JTable so that I can perform appropriate validation. For example, user use the key to move from cell (2,3) to (2,4) or use the mouse to move from (2,4) to (5,3).
    I know that it is possible to use ListSelectionEvent on SelectionModel (for row change) and & ColumnModel (for change change) to do that. However, when both row & column change simultaneously, I need to do only 1 validation (in fact, the validation must have both information). My existing code gives me two separate event instead.
    Any idea ? Thanks in advance.

    This will be a decently hard nut to crack without making a slightly (or worse) cluttered solution.
    I've been part of a framework where applications-developer has requested solutions like you currently ask for. The solution we implemented was twofold.
    1) We made an centralised TableModel that people could use as-is or extend if nessecary. To this tablemodel we added a new set of events that could be consumed, or in some cases even replaced.
    The events was for instance 'beforeCellChange' and contained enough data on the current value, the new value, location in model and space for replacing any of the above values. Many more events was added as time went by as well.
    We made the event-listener fairly generalized and the type sent in the actual event, this allowed us to expand the events without having to change any interfaces. The drawback with this was that it forces the developer to check which type of event is happening, a bit like events happened in AWT 1.0.
    With the help of this, the developers just added the nessecary listeners to the table model and they could consume, change, validate any input to a table before it was committed.
    2) No good method for row-verification could really be found.
    There was a few futile tries, but since data could be entered in any order, the validation raised the amount of code with a order of magnitude. It does work, by listening on selection events, but quite a few extra checks has to be resolved, as instance with rows not validated etc etc.
    My recomendations, verify data carefully from events either from model or the table-editor. The result will most assurdly end in that you need to have an tablemodel on your own and also TableCellRenderer to accomplish all that you want to do.
    Yours sincerely
    Peter Norell

  • [Feature request] Runtime width of JTable columns based on attribute settings

    I'm wondering if it's possible to let 'JClient' dynamically resize the columns in a JTable. Eg: I have set the width of some attribute of some ViewObject to 3. But when I run the application all columns are equally sized. I tried changing the JTable's property autoResizeMode (figuring it might override settings by JClient), but that doesn't seem to have any effect.
    Also, 'grabbing' a column from the table through some manual coding and setting the width of that column doesn't seem to work either.
    I've posted something regarding JTable Re: for specifically RIZWAN from PAkistan or anyone, but I'm curious to know if this 'Specialised editor for Grid Control (JTable)' that Grant Ronald spoke of, will include some sort of applicable functionality.
    It's clear that we need some better (that is, 'any' ;)) way of manipulating columns in a JClient table.
    Any comments?
    Thanks.
    Arno

    We are currently looking into that.
    The column width should not be controlled from the model, it is a setting on JTable, We are considering providing a JClient control (JUTable ??), which is a JTable in a scrollpane and give you more power over column width, column headers etc....
    We are currently evaluating that.
    It would mean that you've got a table control with properties allowing you to set these things on the control itself.
    Currently you have to set the hints on the TableColumn.
    Here is an example :
    tableDeptView1.setModel(JUTableBinding.createAttributeListBinding(panelBinding, tableDeptView1, "DeptView1", null, "DeptView1Iter", new String[] {"Deptno", "Dname", "Loc"}));
    tableDeptView1.getColumn("Deptno").setMaxWidth(75);
    tableDeptView1.getColumn("Loc").setPreferredWidth(200);
    tableDeptView1.getColumn("Loc").setMinWidth(100);
    tableDeptView1.getColumn("Loc").setMaxWidth(450);

  • Setting the Size of a Column in a JTable

    Hi there,
    does anybody knows a way how to set the size of a specified column in a JTable without changinge the size of the other columns?
    thx anyway
    Errraddicator

    You've got to change the JTable's column resizing policy to prevent the other columns resizing:
    JTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF)Otherwise all the columns will be adjusted to fit into the width of the table - changing one column would have to result in at least one other column changing!
    Hope this helps.

Maybe you are looking for

  • Error after using a servlet in ADF  - unable to select another row in table

    Hello, I have a go button and when I select a row in a table it call a download servlet. After I open or save the document I'm unable to make other selection in the table or make another action. The table has single row selection active. The servlet

  • What's wrong with my xorg.conf?

    I just installed Arch + KDEmod and I think I'd like it, but I can't get any video driver to work correctly.  The open-source ati driver crashes immediately (just like in Ubuntu, I could never get that one to work) so I'm trying to catalyst drivers. 

  • How to order hard drive sled screws for MacPro HD sled?

    I got a refurb. 2.66 and it working great. However, when I tried to change out the Apple/Seagate drive the last screw looked like someone had used the wrong sized screw drive and slightly stripped the Philips head slots on the top of the screw. I man

  • Encryption vs performance

    As a laptop user I have always felt attracted by the use of encryption but as the laptop I am using is quite old (T23 - 1.13 Ghz / 256 RAM) I wonder if the gain of security would come at a too high price in terms of performance. Someone has used or i

  • Time based scheduling  of adaptors in NW 2004S

    Hi XI gurus, I know that time based scheduling  for adaptors(Let say polling starts at 2 AM daily) can be done in SP19 of NW2004. Could anyone tell me in NW2004S this feature  is availbale or not and if yes on which SP ? Regards Vijay