JTable renderers!!

Im looking for an example where different renderers are used for different columns in a table. I am trying to display a boolean value as a checkbox in the table, and in the same table, use a different renderer to display the date......any pointers to examples would be great.

Its ok i managed to find the solution by overwriting the getColumnClass, with a few simple 'if' statements, which i tried already but couldnt get to work. All the columns were returning the Object.class, and i had to say which columns had to return which class.....but thanks anyways.

Similar Messages

  • Trouble understanding JTable renderers

    I dont properly understand how to JTable.
    In the application I'm writing, I have on main JFrame, with a menu.
    Onto this I load a jTabbed pane and then onto this a JTable , with
    some data loaded from a file , some coulmns are text , others integers
    floats and theres one date column
    I've successfully set up a TableModel extending AbstractTableModel
    as a separate class java file. I can set column widths ok too.
    But I cant get the renderer working , the numeric coumns are left aligned.
    Question 1 :How do I get a column of numeric data in a JTable to be right aligned? Some examples I have found seem to refer to specific cells eg
    // in the custom renderer...
    if(value instanceof Double)
    setHorizontalAlignment(SwingConstants.RIGHT);
    setText(value);
    I've also read this sites JTable tutorial but still dont understand the
    renderer bit.
    Question 2 : where do I put the renderer code, in with the table model
    class file , or in my main application (where I define the column widths)?
    [The JDK is 1.4, the OS is win 98.]
    Thanks in advance for any help
    Mike2z

    HONK !
    Thanks for the reply. The code
    public Class getColumnClass(int c)
    switch (c)
    case 0: return Integer.class;
    case 1: return String.class;
    case 2: return String.class;
    case 3: return String.class;
    case 4: return String.class;
    case 5: return String.class;
    case 6: return Integer.class;
    case 7: return Float.class;
         case 8: return Float.class;
    case 9: return Float.class;
    case 10: return Floatclass;
    default : return getValueAt(0, c).getClass();
    // return getValueAt(0, c).getClass();
    // return Object.class;
    seems to be the key. When I use that (instead of either of the commented
    out lines I was trying before) it works in that numbers are right
    aligned.
    However when I attemp to right scroll on the scroll pane I get a garbled display and the error :
    java.lang.IllegalArgumentException: Cannot format given Object as a Number
         at java.text.NumberFormat.format(NumberFormat.java:219)
         at java.text.Format.format(Format.java:133)
         at javax.swing.JTable$DoubleRenderer.setValue(JTable.java:3348)
         at javax.swing.table.DefaultTableCellRenderer.getTableCellRendererComponent(DefaultTableCellRenderer.java:160)
         at javax.swing.JTable.prepareRenderer(JTable.java:3682)
         at javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:1149)
         at javax.swing.plaf.basic.BasicTableUI.paintCells(BasicTableUI.java:1051)
         at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:974)
         at javax.swing.plaf.ComponentUI.update(ComponentUI.java:142)
         at javax.swing.JComponent.paintComponent(JComponent.java:537)
         at javax.swing.JComponent.paint(JComponent.java:804)
         at javax.swing.JComponent.paintChildren(JComponent.java:643)
         at javax.swing.JComponent.paint(JComponent.java:813)
         at javax.swing.JViewport.paint(JViewport.java:707)
         at javax.swing.JComponent.paintChildren(JComponent.java:643)
         at javax.swing.JComponent.paint(JComponent.java:813)
         at javax.swing.JComponent._paintImmediately(JComponent.java:4642)
         at javax.swing.JComponent.paintImmediately(JComponent.java:4464)
         at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:404)
         at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:117)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:178)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:443)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:190)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:144)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:130)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:98)
    If I just use
    public Class getColumnClass(int c)
    return getValueAt(0, c).getClass();          // this
    // return Object.class;          // or this
    I can right scroll without that error appearing, but am back to the original problem of left aligned numeric data.
    Don't suppose you encountered the same problem?
    Mike2z

  • How to set different renderers to different cells in same column of JTable?

    Hello Friends,
    I need your help again...
    Does any body knows, how to set different renderer's for different cells of same column in JTable..??
    For ex.
    Col1 Col2 Col3 Col4
    A       A       A      A
    A       A       A      B
    A       A       A      C
    A       A      A       D
    Where A B C D would be different Renderers.  I want set exactly same ,,, ie. one column with different renderer at different cell positions..
    Right now i m setting renderer using statement bellow :
    table.getColumnModel().getColumn(int).setCellRenderer(rederer_Instance);But with this, effect in the last renderer is applicable whole column....
    Can any body help me out ?????????
    please refer this thread for similar kind of discussion...
    http://forums.sun.com/thread.jspa?forumID=57&threadID=571445Thanks
    Suyog

    Please refer to the first reply of [this thread|http://forums.sun.com/thread.jspa?forumID=57&threadID=571445] for the answer. If you have a specific problem implementing it, post you code with a specific question.

  • Custom Renderers in JTreeTable (or extending JTable)?

    I am wondering about what the best approach is to display a table in a Swing component. My table will by default have all rows collapsed (occupying a single line), but someone may click on a row to expand it (so it occupies multiple lines and displays more information). Nothing in the table should be editable.
    Example:
    (collapsed) 1. data     data     data
    (expanded) 2. data     data     data
    ...more data that wouldn't fit on on one line...
    ... still more data (additional data doesn't have same column format as collapsed rows)...
    (collapsed) 3. data     data     dataSo the additional data displayed when a row is expanded aren't conceptually `children' of the data in the collapsed display. I've looked at JTreeTable, but I'm not sure it's right for this purpose, and it seems complicated.
    For one thing, I need some of my columns to have custom renderers--for example, renderers that display a button with text or an image instead of just a label. However, it looks like the JTreeTable approach forces you to declare the JTree (extension) as the renderer of everything in a row, so would that prevent me from specifying custom renderers for other columns, or am I misunderstanding?
    Another feature I need is to be able to filter out entire rows from the view (so they don't show up at all). I will also want to add custom sort buttons that can apply four different sorts to each column.
    Would I be better off using a JTreeTable for this or somehow using custom renderers or otherwise extending an ordinary JTable to make the column larger and display additional information when the user clicks the expand icon?
    Also, how do I specify a different renderer for header rows than for other rows?
    Message was edited by:
    The.Joy.of.Java

    Check how editingStopped is being done. For a ComboBox there is no common operation that one can assume means that the user is done with the editing component. By default JTable leaves it active until the mouse clicks somewhere outside it, then does, essentially, fireEditingStopped() to give the cell back to the renderer. Then a second mouse click is required to start a new cell editor.
    If you're using ComboBox as a custom editor, you have to decide what event you want to be final and call fireEditingStopped() yourself. For instance, in your TableCellEditor:
        @Override
        public Component getTableCellEditorComponent(final JTable table,
                                                     final Object value,
                                                     final boolean isSelected,
                                                     final int row,
                                                     final int column) {
    ...             if( editor.supportsCustomEditor() )  {
                        JComboBox c = (JComboBox)editor.getCustomEditor();
                        c.removeActionListener( this );
                        c.addActionListener( this );
                        return c;
        @Override
        public void actionPerformed ( final ActionEvent ev ) {
            else if( "comboBoxChanged".equals( ev.getActionCommand() ) )  {
                fireEditingStopped();
        }The actionEvent is fired when just about anything happens in the ComboBox, including selection of the currently selected item. But unless you have a more specific requirement, it should be good enough.

  • JTable loses cell renderers

    Well I just had an annoying bug that took me a long time to diagnose.
    Under certain circumstances, my JTable would suddenly redraw using all default cell renderers - my overriding renderers just stopped being used.
    Until today I was not able to reproduce it consistently, but I finally managed to do so, and I found the reason for it.
    It turned out that due to a bug in my code, I was occasionally callingfireTableRowsDeleted(first, last);with first set to -1. This apparently causes any column renderers you've set to be discarded!
    Hopefully this post will be useful if anyone else sees the same loss of renderers.

    It turned out that due to a bug in my code, I was occasionally calling
    fireTableRowsDeleted(first, last);Doesn't seem right. Here is the code from the JTable. A negative value seems to be handled.
    private void tableRowsDeleted(TableModelEvent e)
        int start = e.getFirstRow();
        int end = e.getLastRow();
        if (start < 0)
             start = 0;
        if (end < 0)
            end = getRowCount()-1;
    ...This problem is usually caused by invoking the fireTableStructureChanged() method (which is automatically invoked when you use setModel() or setDataVector()). This method does indeed cause the TableColumnModel to be recreated, which means the TableColumns are also recreated so you lose the old renderers and editors.
    You can prevent this by using the following:
    table.setAutoCreateColumnsFromModel( false );

  • JTable loses renderers (Urgent!!!)

    When I refresh my data, the job is done in a thread. When job is finished I call fireTableDataChanged of TableModel with invokeLater system.
    But after that, in some cases, the JTable loses its renderers which are replacing by defaults.
    I use JDK 1.3 on Windows NT or Linux

    Had this problem as well, I solved it by removing my TableColumnModel and replacing it with a defualt one. Then refreshing the data and finally adding my model back. Something like
    TableColumnModel tcm = myJTable.getColumnModel();
    myJTable.setColumnModel(new DefaultTableColumnModel());
    // Refresh
    myJTable.setColumnModel(tcm);
    Might not be optimal but it worked in my app.

  • JTables how to apply multiple cell renderers to a cell

    I have a complicated table with many different cell renderers depending on column type. (i.e check boxes, editable text fields, formatted fields, fields with icons etc..) Now I need to add the capability to color rows depending on a certain status value of a column. How can I add this capability since I already have renderers for the cells> Most examples I have seen for manipulating row colors simply extends DefaultCellRenderer for the entire table, but I already have renderers for these cells.

    Create an interface and make each renderer implement a method that colours in the background for you. Just an idea, haven't tried it myself

  • Making some Custom Column Renderers for a JTable

    Hello People
    I've been playing around with a JTable by following the tutorial "How to Use Tables". (I am using netBeans 4.1 to "sculpt" my swing objects onto the nice palette in the IDE. I don't know if this has anything to do with the errors but, it seems like netBeans requires some Gui components be initialized via this abovementioned "palette")
    I believe that I need to somehow tell the JTable about what kinds of objects are in it so that it can render itself properly. I have a table set up with some default values in it
    ->Strings both Editable and Not-Editable
    -> Integers both Editable and Not-Editable
    -> Boolean rendered as a check box Editable
    So upon startup, my progarm renders the table correctly. I have a button to clear all of the elements in the table, which works fine. It is only when I switch to another window, then switch back to an empty table ... the JTable needs to redraw itself. This is when I'm getting the error:
    java.lang.NullPointerException
            at ElementHelp.PrimitiveManager$MyVectorTableModel.getColumnClass(PrimitiveManager.java:93)
            at javax.swing.JTable.getColumnClass(JTable.java:1752)
            at javax.swing.JTable.getCellRenderer(JTable.java:3700)
            at javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:1148)
            at javax.swing.plaf.basic.BasicTableUI.paintCells(BasicTableUI.java:1051)
            at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:974)
            at javax.swing.plaf.ComponentUI.update(ComponentUI.java:142)
            at javax.swing.JComponent.paintComponent(JComponent.java:541)
            at javax.swing.JComponent.paint(JComponent.java:808)
    ...blah blah more exception stack.....
           I think that because there are no elements in the table that the call to "getClass" for an element in the table returns a NullPointerException. I think I can avoid this via telling the JTable about the types of objects each column will contain. The tutorial suggests one of two solutions: (neither of which I can get to work)
    1) Use a class that extends the DefaultTableCellRenderer
    2) I should write somthing that ...extends JLabel and implements TableCellRenderer.... such as the tutorials ColorRenderer example. Which solution should I work out if I want my table to add/delete rows and be able to have a few cells edited. (It will never be restructured .. the column types won't change)
    Also, I've created my own TableModel for it ... a class that extends AbstractTableModel ... (although not declaired, it also implemnts/overwrites functions from the TableModel interface)
    Any suggestions on avoiding the abovementioned error?
    thanks and happy holidays to everyone

    I think that because there are no elements in the table that the call to "getClass" for an element in the table returns a NullPointerExceptionWell, if you have no data in the table then your TableModel should be returning "0" for the number of rows in the table and it won't be a problem.
    Also, I've created my own TableModel for it ... Why? Use the DefaultTableModel it supports String, Integers and Booleans without any need for custom coding.

  • Problems with JTable custom cell renderers

    Hi All,
    I'm having a bit of a problem writing a custom renderer for a JTable.
    What seems to be happening is that the changes I apply in the renderer to the component are applied to ALL cells.
    All I want to do is have a different background color for certain cells....
    Ive derived from DefaultTableCellRenderer, so Im using its getTableCellRendererComponent to do most of the work.
    So, Ive got something like this:
    private class DirtyCacheRenderer extends DefaultTableCellRenderer
        public Component getTableCellRendererComponent(JTable table, Object value,
                              boolean isSelected, boolean hasFocus, int row, int column)
          // Modifies 'this'
          super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
          // If the row/column is 'dirty' (I.e - if I want 2 color it diferently)
          if(((EditableTableModel)table.getModel()).isDirty(row,column))
            // The column is dirty. Set the color accordingly:
            super.setBackground(DIRTY_COLOR);
          return this;
      }The effect is that as soon as ONE cell gets its color set above, all of the cells do!
    Please help, its driving me mad!!!
    D

    I tried this and it worked. Tell me if it is OK for you.
    import javax.swing.table.TableCellRenderer;
    import java.awt.Color;
    import java.awt.Component;
    import javax.swing.JTable;
    import javax.swing.JLabel;
    public class testRenderer implements TableCellRenderer {
    JLabel cell = new JLabel();
    Color dirty = new Color(100,100,100);
    Color clear = new Color(0,0,0);
    public testRenderer() {
    cell.setOpaque(true);
    public Component getTableCellRendererComponent(JTable table,Object value,
    boolean isSelected,boolean hasFocus, int row, int column) {
    cell.setText(value.toString());
    // The column is dirty. Set the color
    if (row == column)     {
    cell.setBackground(dirty);
    } else {
    cell.setBackground(table.getBackground());
    return cell;
    }

  • JTable custom column renderers

    Hi,
    I am using a custom column renderer to format a date value in the table, and am passing back a checkbox. However, i am unable get the jTextField to look/act like the default rendered componenets, ie. if i select them they have the same uneditable colour. How can i get the same behaviour.
    Thanks
    Rudy

    Hi,
    I think this could be a possible bug in Java, because when i changed my LookAndFeel to the default (metal) the entire table row appeared selected when it was selected. Each of the textFields rendered correctly. However, when i change it to my system look and feel (windows) the jTables rows to not render correctly and the textfield columns of the selected row appear to have a white background, and a white foreground. Which means the text which is originally black disappears??
    Any suggestions greatly welcomed.
    Rudy

  • Renderers for JTable

    Can any one tell a good book for renderers..

    I found that the Addison-Wessley set of Graphic Java books were quite useful - the Swing one's the one to look at here obviously.
    A bit bland but quite "official".

  • JTable - help with custom cell renderers and editors

    I've got myself into a bit of a mess with cell renderers and editors.
    I've got a custom component that wants displaying in a column and then hand over all functionality to this component when you start editing it.
    Now how I went out about this was to create a custom cell renderer that extends this component and implements TableCellRenderer.
    I then created a table cell editor that extends AbstractCellEditor and implements TableCellEditor and this cell editor creates a new component when it's initialized. I then use setCellEditor(new MyCellEditor()) on the column and setCellRenderer(new MyCellRenderer()).
    This works slightly but I'm wondering how this is all implemented.
    When I set the cell editor on it's own it seems to be sharing a reference to the single component that's being used which means that if you edit one cell all the cells get changed to the new value.
    Thanks for the help,
    Alex

    only a few forums are actually browsedAnd theSwing forum is one of the most active. Did you search it for editiing examples? I've seen many editing examples posted in a SSCCE format.
    SSCEE is also impossible as the functionality spans over about 10 classes We did not ask for your application, we asked for a SSCCE. The whole point of a SSCCE is to simplify the 10 classes into a single class and maybe an inner class for the editor to make sure you haven't made a silly mistake that is hidden because of the complexity of your real application.

  • URGENT HELP NEEDED FOR JTABLE PROBLEM!!!!!!!!!!!!!!!!!

    firstly i made a jtable to adds and deletes rows and passes the the data to the table model from some textfields. then i wanted to add a tablemoselistener method in order to change the value in the columns 1,2,3,4 and set the result of them in the column 5. when i added that portion of code the buttons that added and deleted rows had problems to function correctly..they dont work at all..can somebody have a look in my code and see wot is wrong..thanx in advance..
    below follows the code..sorry for the mesh of the code..you can use and run the code and notice the problem when you press the add button..also if you want delete the TableChanged method to see that the add button works perfect.
    * Created on 03-Aug-2005
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    * @author Administrator
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Vector;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import java.io.*;
    public class NodesTable extends JFrame implements TableModelListener, ActionListener {
    JTable jt;
    DefaultTableColumnModel dtcm;
    TableColumn column[] = new TableColumn[100];
    DefaultTableModel dtm;
    JLabel Name,m1,w1,m2,w2;
    JTextField NameTF,m1TF,w1TF,m2TF,w2TF;
    String c [] ={ "Name", "Assessment1", "Weight1" , "Assessment2","Weight2 ","TotalMark"};
    float x=0,y=0,tMark=0,z = 0;
    float j=0;
    int i;
         JButton DelButton;
         JButton AddButton;
         JScrollPane scrollPane;
         JPanel mainPanel,buttonPanel;
         JFrame frame;
         Object[][] data =
              {"tami", new Float(1), new Float(1.11), new Float(1.11),new Float(1),new Float(1)},
              {"tami", new Float(1), new Float(2.22), new Float(2.22),new Float(1),new Float(1)},
              {"petros", new Float(1), new Float(3.33), new Float(3.33),new Float(1),new Float(1)},
              {"petros", new Float(1), new Float(4.44), new Float(4.44),new Float(1),new Float(1)}
    public NodesTable() {
    super("Student Marking Spreadsheet");
    this.AddNodesintoTable();
    setSize(400,250);
    setVisible(true);
    public void AddNodesintoTable(){
    // Create a vector object and load them with the data
    // to be placed on each row of the table
    dtm = new DefaultTableModel(data,c);
    dtm.addTableModelListener( this );
    jt = new JTable(dtm){
         // 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();
              // The Cost is not editable
              public boolean isCellEditable(int row, int column)
                   int modelColumn = convertColumnIndexToModel( column );
                   return (modelColumn == 5) ? false : true;
    //****************************User Input**************************
    //Add another node
    //Creating and setting the properties
    //of the panel's component (panels and textfields)
    Name = new JLabel("Name");
    Name.setForeground(Color.black);
    m1 = new JLabel("Mark1");
    m1.setForeground(Color.black);
    w1 = new JLabel("Weigth1");
    w1.setForeground(Color.black);
    m2= new JLabel("Mark2");
    m2.setForeground(Color.black);
    w2 = new JLabel("Weight2");
    w2.setForeground(Color.black);
    NameTF = new JTextField(5);
    NameTF.setText("Node");
    m1TF = new JTextField(5);
    w1TF = new JTextField(5);
    m2TF=new JTextField(5);
    w2TF=new JTextField(5);
    //creating the buttons
    JPanel buttonPanel = new JPanel();
    AddButton=new JButton("Add Row");
    DelButton=new JButton("Delete") ;
    buttonPanel.add(AddButton);
    buttonPanel.add(DelButton);
    //adding the components to the panel
    JPanel inputpanel = new JPanel();
    inputpanel.add(Name);
    inputpanel.add(NameTF);
    inputpanel.add(m1);
    inputpanel.add(m1TF);
    inputpanel.add(w1);
    inputpanel.add(w1TF);
    inputpanel.add(m2);
    inputpanel.add(m2TF);
    inputpanel.add(w2TF);
    inputpanel.add(w2);
    inputpanel.add(AddButton);
    inputpanel.add(DelButton);
    //creating the panel and setting its properties
    JPanel tablepanel = new JPanel();
    tablepanel.add(new JScrollPane(jt, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED
    , JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
    getContentPane().add(tablepanel, BorderLayout.CENTER);
    getContentPane().add(inputpanel, BorderLayout.SOUTH);
    //Method to add row for each new entry
    public void addRow()
    Vector r=new Vector();
    r=createBlankElement();
    dtm.addRow(r);
    jt.addNotify();
    public Vector createBlankElement()
    Vector t = new Vector();
    t.addElement((String) " ");
    t.addElement((String) " ");
    t.addElement((String) " ");
    t.addElement((String) " ");
    t.addElement((String) " ");
    return t;
    // Method to delete a row from the spreadsheet
    void deleteRow(int index)
    if(index!=-1) //At least one Row in Table
    dtm.removeRow(index);
    jt.addNotify();
    // Method that adds and deletes rows
    // from the table by pressing the
    //corresponding buttons
    public void actionPerformed(ActionEvent ae){
         Float z=new Float (m2TF.getText());
    String Name= NameTF.getText();
    Float x= new Float(m1TF.getText());
    Float y= new Float(w1TF.getText());
    Float j=new Float (w2TF.getText());
    JFileChooser jfc2 = new JFileChooser();
    String newdata[]= {Name,String.valueOf(x),String.valueOf(y),
    String.valueOf(z),String.valueOf(j)};
    Object source = ae.getSource();
    if(ae.getSource() == (JButton)AddButton)
    addRow();
    if (ae.getSource() ==(JButton) DelButton)
    deleteRow(jt.getSelectedRow());
    //method to calculate the total mark in the TotalMark column
    //that updates the values in every other column
    //It takes the values from the column 1,2,3,4
    //and changes the value in the column 5
    public void tableChanged(TableModelEvent e) {
         System.out.println(e.getSource());
         if (e.getType() == TableModelEvent.UPDATE)
              int row = e.getFirstRow();
              int column = e.getColumn();
              if (column == 1 || column == 2 ||column == 3 ||column == 4)
                   TableModel model = jt.getModel();
              float     q= ((Float)model.getValueAt(row,1)).floatValue();
              float     w= ((Float)model.getValueAt(row,2)).floatValue();
              float     t= ((Float)model.getValueAt(row,3)).floatValue();
              float     r= ((Float)model.getValueAt(row,4)).floatValue();
                   Float tMark = new Float((q*w+t*r)/(w+r) );
                   model.setValueAt(tMark, row, 5);
    // Which cells are editable.
    // It is only necessary to implement this method
    // if the table is editable
    public boolean isCellEditable(int row, int col)
    { return true; //All cells are editable
    public static void main(String[] args) {
         NodesTable t=new NodesTable();
    }

    There are too many mistakes in your program. It looks like you are new to java.
    Your add and delete row buttons are not working because you haven't registered your action listener with these buttons.
    I have modifide your code and now it works fine. Just put some validation code for the textboxes becuase it throws exception when user presses add button without entering anything.
    Here is the updated code: Do the diff and u will know my changes
    * Created on 03-Aug-2005
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    * @author Administrator
    * TODO To change the template for this generated type comment go to Window -
    * Preferences - Java - Code Style - Code Templates
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.DefaultTableColumnModel;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableModel;
    public class NodesTable extends JFrame implements TableModelListener,
              ActionListener {
         JTable jt;
         DefaultTableColumnModel dtcm;
         TableColumn column[] = new TableColumn[100];
         DefaultTableModel dtm;
         JLabel Name, m1, w1, m2, w2;
         JTextField NameTF, m1TF, w1TF, m2TF, w2TF;
         String c[] = { "Name", "Assessment1", "Weight1", "Assessment2", "Weight2 ",
                   "TotalMark" };
         float x = 0, y = 0, tMark = 0, z = 0;
         float j = 0;
         int i;
         JButton DelButton;
         JButton AddButton;
         JScrollPane scrollPane;
         JPanel mainPanel, buttonPanel;
         JFrame frame;
         public NodesTable() {
              super("Student Marking Spreadsheet");
              this.AddNodesintoTable();
              setSize(400, 250);
              setVisible(true);
         public void AddNodesintoTable() {
              // Create a vector object and load them with the data
              // to be placed on each row of the table
              dtm = new DefaultTableModel(c,0);
              dtm.addTableModelListener(this);
              jt = new JTable(dtm) {
                   // The Cost is not editable
                   public boolean isCellEditable(int row, int column) {
                        int modelColumn = convertColumnIndexToModel(column);
                        return (modelColumn == 5) ? false : true;
              //****************************User Input**************************
              //Add another node
              //Creating and setting the properties
              //of the panel's component (panels and textfields)
              Name = new JLabel("Name");
              Name.setForeground(Color.black);
              m1 = new JLabel("Mark1");
              m1.setForeground(Color.black);
              w1 = new JLabel("Weigth1");
              w1.setForeground(Color.black);
              m2 = new JLabel("Mark2");
              m2.setForeground(Color.black);
              w2 = new JLabel("Weight2");
              w2.setForeground(Color.black);
              NameTF = new JTextField(5);
              NameTF.setText("Node");
              m1TF = new JTextField(5);
              w1TF = new JTextField(5);
              m2TF = new JTextField(5);
              w2TF = new JTextField(5);
              //creating the buttons
              JPanel buttonPanel = new JPanel();
              AddButton = new JButton("Add Row");
              AddButton.addActionListener(this);
              DelButton = new JButton("Delete");
              DelButton.addActionListener(this);
              buttonPanel.add(AddButton);
              buttonPanel.add(DelButton);
              //adding the components to the panel
              JPanel inputpanel = new JPanel();
              inputpanel.add(Name);
              inputpanel.add(NameTF);
              inputpanel.add(m1);
              inputpanel.add(m1TF);
              inputpanel.add(w1);
              inputpanel.add(w1TF);
              inputpanel.add(m2);
              inputpanel.add(m2TF);
              inputpanel.add(w2TF);
              inputpanel.add(w2);
              inputpanel.add(AddButton);
              inputpanel.add(DelButton);
              //creating the panel and setting its properties
              JPanel tablepanel = new JPanel();
              tablepanel.add(new JScrollPane(jt,
                        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                        JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
              getContentPane().add(tablepanel, BorderLayout.CENTER);
              getContentPane().add(inputpanel, BorderLayout.SOUTH);
         //Method to add row for each new entry
         public void addRow() {
              Float z = new Float(m2TF.getText());
              String Name = NameTF.getText();
              Float x = new Float(m1TF.getText());
              Float y = new Float(w1TF.getText());
              Float j = new Float(w2TF.getText());
              String newdata[] = { Name, String.valueOf(x), String.valueOf(y),
                        String.valueOf(z), String.valueOf(j) };
              dtm.addRow(newdata);
         // Method to delete a row from the spreadsheet
         void deleteRow(int index) {
              if (index != -1) //At least one Row in Table
                   dtm.removeRow(index);
                   jt.addNotify();
         // Method that adds and deletes rows
         // from the table by pressing the
         //corresponding buttons
         public void actionPerformed(ActionEvent ae) {
              Object source = ae.getSource();
              if (ae.getSource() == (JButton) AddButton) {
                   addRow();
              if (ae.getSource() == (JButton) DelButton) {
                   deleteRow(jt.getSelectedRow());
         //method to calculate the total mark in the TotalMark column
         //that updates the values in every other column
         //It takes the values from the column 1,2,3,4
         //and changes the value in the column 5
         public void tableChanged(TableModelEvent e) {
              System.out.println(e.getSource());
              //if (e.getType() == TableModelEvent.UPDATE) {
                   int row = e.getFirstRow();
                   int column = e.getColumn();
                   if (column == 1 || column == 2 || column == 3 || column == 4) {
                        TableModel model = jt.getModel();
                        float q = (new Float(model.getValueAt(row, 1).toString())).floatValue();
                        float w = (new Float(model.getValueAt(row, 2).toString())).floatValue();
                        float t = (new Float(model.getValueAt(row, 3).toString())).floatValue();
                        float r = (new Float(model.getValueAt(row, 4).toString())).floatValue();
                        Float tMark = new Float((q * w + t * r) / (w + r));
                        model.setValueAt(tMark, row, 5);
         // Which cells are editable.
         // It is only necessary to implement this method
         // if the table is editable
         public boolean isCellEditable(int row, int col) {
              return true; //All cells are editable
         public static void main(String[] args) {
              NodesTable t = new NodesTable();
    }

  • How to get mouse events inside the components of a JTable

    Hi!
    I have question, I think this is related to very basics of swing, however I couldn't find a solution/answer on the web.
    I have a JMyTable(a descendant of JTable), and one value on a row/column is a special class, ie. MyClass. for this class I registered a cell renderer, MyRenderer. and this renderer returns a JMyComponent, which is actually a descendant of JComponent.
    Now, if I call enableEvents(AWTEvent.MOUSE_EVENT_MASK) in the constructor of JMyTable I get events posted on processMouseEvent method. However, the same doesn't work for JMyComponent. I mean, I call enableEvents, however processMouseEvent method is not triggered.
    Could someone explain/help me with this issue?
    Thanks,
    Ozgur

    Your cell renderer components are just that: renderers. They're not added to the table and do not appear in the component hierarchy. This is because tables may be very large and adding components in would be very resource hungry.
    See here for details
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
    If you want to detect events you will need to listen to events on the JTable itself, and use the rowAtPoint()/columnAtPoint() methods to determine the cell. So for instance where you might want mouseEntered() on your cell component you would have to use mouseMoved() on the table and detect when the cursor moves to a new cell.

  • Is it OK to re-use 1 instance of editors and renderers?

    Hi,
    The simple version of the question, is can I make 1 instance of my custom cell editor and cell renderer classes and safely use it in all my JTable instances?
    For example, I have a DateRenderer class, and instantiate it in a static member, and use it in all Date columns and tables, many of which will be instatiated at one time. If a column needs a non-default format, then I guess I'd create a special instance for it, other wise it would use the default instance.
    It seems to be OK so far, but but my program hasn't received any serious usage yet.
    As to why, I'm thinking this way, I've been messing around with CellEditors and renderers and despite wanting to use default functionality whenver possible, I find that I'm using custom versions for every situation... so if possible, I'd like to keep the number of instances to a minimum.
    Regards
    Iain

    OK, I see what you mean.
    Stop cell editing on focus lost isn't the default behaviour, but I've had to use it anyway (it seems to make sense).
    The reason I asked is that, to get the behaviour that I want, it looks like I'll have to have my custom renderers and editors on every column of every table so I'd like to avoid unneccessary instantiation.
    I'm aiming for a system where:
    - 1 click selects the row (default behaviour),
    - 2 clicks starts editing the cell (also default),
    - but tabbing or pressing enter after editing a cell keeps you in editing mode.
    I don't suppose that many people here have had experience with this, but entering Japanese (and presumably other non ascii type character sets) using MS's IME doesn't work very well with the standard JTable behaviour. If you don't double click, the entered japanese text appears in a little IME window somewhere on the screen (no neccessarily near the editing cell) and just gets lost when you press enter. You have to double click every time, and I can't see the users accepting that.
    I'll be investigating this over tme, and hopefully will be able to get it working smoothly.
    Thanks,
    Iain

Maybe you are looking for

  • Firewall allows only https acess; how to have multiple instances

    Hi, We have a server that is accessible from the internet only using https. Right now we have 3 Web apps. deployed to a single Weblogic instance listening on 443. Is there a way to have 3 separate Weblogic instances, one for each Web. app. so that so

  • Lion Server File Sharing Crashes

    We have a brand new Mac Pro (12 core with 64GB of RAM) running OS X Lion Server in a corporate environment. The server is running only file sharing and software update servers, and we have around 40 users who need to be connected over AFP at all time

  • If we create more indexes in what way it decreases performance ??

    If we create more indexes in what way it decreases performance

  • QR Code Preview and Reader

    I'm looking for an QR code APP that works on the Curve (I have a few models at our office).  I'd like to APP to offer a QR code Preview before blindly reading the code. Norton has such an APP (free) for iPhone and Android, but not BlackBerry. Does an

  • WRE54G expander setting static ip address, then no internet?

    I have set a static ip address on my wired computer for the expander. I can access the setup page, but not the internet. So, I went and set my computer back to " obtain ip address automatically ". Now I can access internet, but not the expander set u