JTable SelectionListener?

Okay so I have 5 combo boxes, and only 1 is enabled to start with. When you make a selection in that first combo box it populates a JTable with the appropriate data based on the selection. Than I want the user to select the row in the JTable and it will enable the other 4 JComboBoxes and load the data from the 4 columns of the JTable into the JComboBoxes. The only part I am having trouble with is selecting the JTable Row. I tried using a ActionEventListner and that clearly did not work =). Any help is appreciated.

Wow Camickr you must have gotten all 27,000 of your posts being an asshole. And this is the Java Programming Forum..... And I solved my problem thanks....
For anyone who wants to know what I did here it is.
This goes where you initialize your components.
jTable1.getSelectionModel().addListSelectionListener(listener);and heres the class fired by the listener.
      public class SelectionListener implements ListSelectionListener {
        JTable table;
        SelectionListener(JTable table) {
            this.table = jTable1;
        public void valueChanged(ListSelectionEvent e) {
             if (jTable1.getValueAt(jTable1.getSelectedRow(), 0) == ""){
                  jcomboTitle.setSelectedItem(0);
             }else{
                  jcomboTitle.setSelectedItem(jTable1.getValueAt(jTable1.getSelectedRow(), 0));
             if (jTable1.getValueAt(jTable1.getSelectedRow(), 0) == ""){
                  jcomboArtist.setSelectedItem(0);
             }else{
                  jcomboArtist.setSelectedItem(jTable1.getValueAt(jTable1.getSelectedRow(), 1));
             if (jTable1.getValueAt(jTable1.getSelectedRow(), 0) == ""){
                  jcomboAlbum.setSelectedItem(0);
             }else{
                  jcomboAlbum.setSelectedItem(jTable1.getValueAt(jTable1.getSelectedRow(), 2));
             if (jTable1.getValueAt(jTable1.getSelectedRow(), 0) == ""){
                  jcomboGenre.setSelectedItem(0);
             }else{
                  jcomboGenre.setSelectedItem(jTable1.getValueAt(jTable1.getSelectedRow(), 3));
    }

Similar Messages

  • How to listen a JTable cell is changed?

    is it have any Listener can know the JTable cell cursor change to other?
    Thanks!

    JTable exposes a ListSelectionModel through getSelectionModel() that you can listen to for changes in the selected row. I think you need to get the TableColumnModel to detect changes in the selected column:
    table.getSelectionModel().addSelectionListener(selectionListener);
    table.getColumnModel().getSelectionModel().addSelectionListener(selectionListener);selectionListener should get notified if a change is made to the selected row or column.
    Hope this helps.

  • How can I use a column header to select columns in a JTable?

    Hello,
    I've been working for ages on this, but I still can't come up with a suitable solution. What I want to be able to do is select a column header from a JTable, which in turn would select the corresponding column in my JTable. I cant seem to do this with a mouse listener, and I can't see how to toggle the buttons of the header either.
    Any help would be gratefully appreciated.
    Mike

    I have both row and columns selected depending on what you do in the JTable. Here's my code:
    where you init your JTable add:
    addressTable = new JTable(addressTableModel, addressTableColumnModel);
    JTableHeader th = addressTable.getTableHeader();
    th.addMouseListener(new tableHeaderMouseAdapter(addressTable));
    addressTable.getSelectionModel().addListSelectionListener(new selectionListener(addressTable));
    addressTable.setColumnSelectionAllowed(true);
    tableHeaderMouseAdapter looks like this (it should look familiar):
    private class tableMouseAdapter extends MouseAdapter
         private JTable tableView;
         public tableMouseAdapter(JTable newTableView)
              tableView = newTableView;
         public void mouseClicked(MouseEvent e)
              int selectedRow = tableView.getSelectedRow();
              if ((e.getClickCount() == 1) && (selectedRow != -1))
                   tableView.clearSelection();
                   tableView.setRowSelectionInterval(selectedRow, selectedRow);
                   tableView.setColumnSelectionInterval(0, tableView.getColumnModel().getColumnCount() - 1);
    selectionListener looks like this:
    private class selectionListener implements ListSelectionListener
         private JTable tableView;
         private boolean changingSelection;
         public selectionListener(JTable newTableView)
              tableView = newTableView;
              changingSelection = false;
         public void valueChanged(ListSelectionEvent e)
              if ((!changingSelection) && (tableView.getSelectedColumnCount() < tableView.getColumnCount()) && (tableView.getSelectedRowCount() < tableView.getRowCount()))
                   changingSelection = true;
                   int selectedRow = tableView.getSelectedRow();
                   if (selectedRow >= 0)
                        tableView.clearSelection();
                        tableView.setRowSelectionInterval(selectedRow, selectedRow);
                   tableView.setColumnSelectionInterval(0, tableView.getColumnModel().getColumnCount() - 1);
                   changingSelection = false;
    I'm sure there is a better way to do this, but it's the first thing I could get to work.
    disclamer:
    Use this code at your own risk. I make no claims about this code whatsoever.

  • JTable ListSelection

    Hi,
    I have JTable and also a TableModel.
    The Table rows consists of two types of Data Objects say A object and B object. Multiple Selection is allowed.
    If the user selects on A object then only A object rows should be allowed for selection using CTRL kye.
    Similarly Viceversa.
    How to do this.
    Thanx in advance,
    Venkat

    Ok, it seems that both listeners fire events. Not sure what went wrong the last time. Still it does not work the way I want it.
    Again the problem is to make a jtable list selection listener to do smthing only if a double click occured. Let's say the current code is
    JTable xtable = new JTable(xdata, xheader);
    xtable.addMouseListener(new MouseListener() {           
            public void mouseClicked(MouseEvent e){
                   num_clicks = e.getClickCount();
                   System.out.println(num_clicks);
    SelectionListener x_listener = new SelectionListener();
    xtable.getSelectionModel().addListSelectionListener(x_listener);
    public class SelectionListener implements ListSelectionListener {
           public void valueChanged(ListSelectionEvent e) {
                if (num_clicks >= 2) {[do stmhing useful...]}
    }There are two problems with this code. The first is that the number of clicks is always one. Which does look unusual. The second is,
    that even if I somehow make the number of clicks equal 2 then a list selection event is fired first and the selection listener does not know the number of clicks.
    I wonder how to deal with this stuff.

  • JTable set single row color

    I have alternating colors for my jtable, and when a row is selected i pop up another window and clear the selection. i want to change the color of all selected rows, but if i dont clear the selection, it doesn't allow me to re-open the same record because of the way the selectionListener works. so basically i dont want to mark a row as selected, i jus want to change its color. anyone know how to do this?

    looks promising.. i'm going to give it a shot. why dont they just have a method like.. table.setRowColor (rowIndex), because im implementing a selectionlistener, so i already know the rowIndex that was selected, jus have to change its color. maybe coz that would be tooo easy lol. thanks

  • Cross-JTable selection

    In a scenario where there are two JTable's in order to implement "locked (frozen) columns", one has to address the cross-JTable selection issue that occurs when both tables' "columnSelection" and "rowSelection" properties are enabled, and the user clicks & drags the mouse to select a range of cells across the two JTables.
    Has anyone ever done this?
    Mert

    Interesting question - I would try to register one mouseListener to both tables that makes sure the events are redispatched if the mouse exits the one and enters the other during a addSelection.Or you can try to patch the BasicTableUI.MouseHandler to go on with addSelection even after a mouseExited during a mouseDragged. Never tried it, though. (Always assuming that one there is one selectionListener that extends a selection in one table to the other)
    Greetings
    Jeanette

  • Jtable return value of selecte row

    Hy
    I try to return from a class the value of the row selected in a Jtabel by mouse in an other caller class
    Now I try a code like this :
    table.addMouseListener (new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    if (e.getClickCount() == 1) {
    JTable target = (JTable)e.getSource();
    int row = target.getSelectedRow();
    return row; // not possible
    how can I take the value of row by return statement ?
    thanks in advance
    Dan

    Don't use a MouseListener, use a SelectionListener: that's what it's for.

  • How do I get at a JTable on a JInternalFrame?

    I've been working on this Multiple Document Interface application, and things have been great up to this point. The user chooses to run a "report" and then selects an entity to get the info for. I then hit the database. Each row returned from the database query goes into it's own data object, which is added to an ArrayList in my custom table model, and that ArrayList is used to generate the JTable, which is then added to a ScrollPane, which is then added to the JInternalFrame, which is then added to the JDesktop pane. Good stuff, right?
    I'm now trying to add Print functionality, and I'm at a loss. What I want to do is have the user do the standard File->Print, which will print out the JTable on the currently selected inner frame. I can get a JTable to print using JTable.print(). What I can't do is find a way to get the JTable from the selected frame.
    I can get the selected frame using desktop.getSelectedFrame(), but I'm at a loss as to what to do next. I've played around with .getComponent, but I'm not having any luck. the components returned don't seem to do me any good...for example, JViewPort?
    Am I going about this the wrong way? Have I poorly designed this? Am I missing the obvious?
    Thanks,
    -Adam

    Well, if you only have a single component on the internal frame then you can use getComponent(0). But then you need to go up the parent chain to get the actual table. You will initially get the JScrollPane, then use that to get the JViewport and then use that to get the viewport component.
    Another option is to extend the JInternalFrame class and insted using the add method to add a component you create get/setTable(...) methods. Then you can save the table as a class variable before adding it the scrollpane and adding the scrollpane to the internal frame.

  • JTable - Can I change the color of the text on a row by row basis?

    Hi All,
    I'm redoing a bit of old uni coursework (to model a stockmarket, stock ticker server & stock ticker application) to brush up my Java skills (esp Swing and Event Handling) and am programming the UI by hand using Swing (its the only way to learn something....(I've certianly nailed Layout Management!!))
    In the stocktickerserver GUI I'm using a JTable to display the details about stocks.
    The user can select a stock and view the details of the stock in another frame. In one panel in the JFrame I've got a JTable listing the history items for the stock (Price, Change, Date).
    Is it possible to color the rows of the JTable according to the value of the change column (or at least the value I insert there)?
    e.g
    if (change > 0){
    Blue;
    else{
    if (change < 0){
    Red;
    else{
    Green;
    I'm completly ignorant on how to achieve this (or even if its possible at all) so all your ideas welcome.
    Any help much appreciated
    Pete
    P.S.
    The Stock History is a class that I store in a [private] Vector in the Stock Class.
    For the selected Stock I loop through this vector getting the items (using various accessor methods)
    I extract the values from the return StockHistory object and build a DefaultTableModel from these
    Then I call JTable.setModel(theModel) to build the table

    implement TableCellRenderer and change foreground of the Renderer in the method getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) . Install this renderer to your table.

  • How to select a specific cell in a JTable?

    Hi there,
    in a JTable, I would like to select a specific cell (to highlight it) from a JButton.
    Here a sample code...
    Who could help me to fill it?
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TableSelection{
        public static void main (String args[]) {
          JFrame frame = new MyFrame();
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.show();
    class MyFrame extends JFrame{
      public MyFrame(){
        setTitle("TableSelection");
        setSize(WIDTH,HEIGHT);
        DefaultTableModel myModel = new DefaultTableModel(2,2);
        JTable myTable = new JTable(myModel);
        myTable.setCellSelectionEnabled(true);
        JButton button00 = new JButton("select 0,0");
        button00.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent event){
         System.out.println("selection of cell (0,0)");
         //--- what code is required to select the cell(0,0)?
        JButton button11 = new JButton("select 1,1");
        button11.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent event){
         System.out.println("selection of cell (1,1)");
         //--- what code is required to select the cell(1,1)?
        Box myBox = new Box(BoxLayout.Y_AXIS);
        myBox.add(new JScrollPane(myTable));
        myBox.add(button00);
        myBox.add(button11);
        getContentPane().add(myBox, BorderLayout.CENTER);
      private static final int WIDTH=200;
      private static final int HEIGHT=200;
    }Thanks a lot for your help.
    Denis

    Use the addColumnSelectionInterval(int index1, int index2)method ~ http://java.sun.com/j2se/1.4/docs/api/javax/swing/JTable.html#addColumnSelectionInterval(int,%20int)
    and the addRowSelectionInterval(int index1, int index2) method ~ http://java.sun.com/j2se/1.4/docs/api/javax/swing/JTable.html#addRowSelectionInterval(int,%20int)
    Hope that helped.
    afotoglidis

  • Create a JTable based on an ArrayList containing instances of a class.

    I have a class, IncomeBudgetItem, instances of which are contained in an ArrayList. I would like to create a JTable, based on this ArrayList. One variable is a string, while others are type double. Not all variables are to appear in the JTable.
    The internal logic of my program is already working. And my GUI is largely constructed. I'm just not sure how to make them talk to each other. The actually creation of the JTable is my biggest problem right now.

    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.util.ArrayList;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    public class TableDemo extends JPanel {
         private boolean DEBUG = false;
         public TableDemo() {
              super(new GridLayout(1, 0));
              ArrayList<MyObject> list = new ArrayList<MyObject>();
              list.add(new MyObject("Kathy", "Smith", "Snowboarding", new Integer(5),
                        new Boolean(false)));
              list.add(new MyObject("John", "Doe", "Rowing", new Integer(3),
                        new Boolean(true)));
              list.add(new MyObject("Sue", "Black", "Knitting", new Integer(2),
                        new Boolean(false)));
              list.add(new MyObject("Jane", "White", "Speed reading",
                        new Integer(20), new Boolean(true)));
              JTable table = new JTable(new MyTableModel(list));
              table.setPreferredScrollableViewportSize(new Dimension(500, 70));
              table.setFillsViewportHeight(true);
              // Create the scroll pane and add the table to it.
              JScrollPane scrollPane = new JScrollPane(table);
              // Add the scroll pane to this panel.
              add(scrollPane);
         class MyObject {
              String firstName;
              String lastName;
              String sport;
              int years;
              boolean isVeg;
              MyObject(String firstName, String lastName, String sport, int years,
                        boolean isVeg) {
                   this.firstName = firstName;
                   this.lastName = lastName;
                   this.sport = sport;
                   this.years = years;
                   this.isVeg = isVeg;
         class MyTableModel extends AbstractTableModel {
              private String[] columnNames = { "First Name", "Last Name", "Sport",
                        "# of Years", "Vegetarian" };
              ArrayList<MyObject> list = null;
              MyTableModel(ArrayList<MyObject> list) {
                   this.list = list;
              public int getColumnCount() {
                   return columnNames.length;
              public int getRowCount() {
                   return list.size();
              public String getColumnName(int col) {
                   return columnNames[col];
              public Object getValueAt(int row, int col) {
                   MyObject object = list.get(row);
                   switch (col) {
                   case 0:
                        return object.firstName;
                   case 1:
                        return object.lastName;
                   case 2:
                        return object.sport;
                   case 3:
                        return object.years;
                   case 4:
                        return object.isVeg;
                   default:
                        return "unknown";
              public Class getColumnClass(int c) {
                   return getValueAt(0, c).getClass();
          * Create the GUI and show it. For thread safety, this method should be
          * invoked from the event-dispatching thread.
         private static void createAndShowGUI() {
              // Create and set up the window.
              JFrame frame = new JFrame("TableDemo");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // Create and set up the content pane.
              TableDemo newContentPane = new TableDemo();
              newContentPane.setOpaque(true); // content panes must be opaque
              frame.setContentPane(newContentPane);
              // Display the window.
              frame.pack();
              frame.setVisible(true);
         public static void main(String[] args) {
              // Schedule a job for the event-dispatching thread:
              // creating and showing this application's GUI.
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        createAndShowGUI();
    }

  • Error in updating Jtable Database

    package desktopapplication1; import java.util.*; import java.sql.*; import javax.swing.JOptionPane; import javax.swing.table.*; public class Datab extends DefaultTableModel { private Connection conn; private Statement st; private ResultSet rs; private ResultSetMetaData rsmd; private int rows; public Datab(String driver, String url, String query) throws SQLException, ClassNotFoundException { Class.forName(driver); conn = DriverManager.getConnection(url); st = conn.createStatement(rs.TYPE_SCROLL_SENSITIVE,rs.CONCUR_UPDATABLE); if ( query.substring(0,3).equalsIgnoreCase("INS") ) { st.executeUpdate(query); } else if ( query.substring(0,3).equalsIgnoreCase("DEL") ) { st.executeUpdate(query); } else { rs = st.executeQuery(query); rsmd = rs.getMetaData(); rs.last(); rows = rs.getRow(); } fireTableStructureChanged(); } public String getColumnName(int column){ try{ return rsmd.getColumnName(column+1); }catch(Exception e){ e.printStackTrace(); } return ""; } public int getColumnCount(){ try{ return rsmd.getColumnCount(); }catch(Exception e){ e.printStackTrace(); } return 0; } public int getRowCount(){ try{ return rows; }catch(Exception e){ e.printStackTrace(); } return 0; } public Object getValueAt(int row, int column){ try{ rs.absolute(row+1); return rs.getObject(column+1); }catch(Exception e){ e.printStackTrace(); } return ""; } public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } public boolean isCellEditable(int row, int column) { if (column < 0) { return false; } else { return true; } } public void setValueAt(Object value, int row, int column){ try{ int conf = JOptionPane.showConfirmDialog(null,"You wanna reaplace "+getValueAt(row,column)+" with "+value+"?", null, 2); if ( conf == 0 ) { rs.absolute(row+1); System.out.println("ROW = "+row+"CURSOR = "+(row+1)+""+rs.getString(1)+column); rs.updateString("Recipe","test"); //i tried to use a simple update cause the normal was not running but same error+ rs.updateRow(); }else { System.out.println("0"); } }catch(SQLException sqle){ System.err.println("Error setting value at row "+row+" column "+column+" with value "+value); sqle.printStackTrace(); } } }
    hi, when i click on my table to edit a value, it give me an error and sometimes fill the cell with a value like [B@341j0j
    Error setting value at row 1 column 0 with value soup2
    java.sql.SQLException: [Microsoft][Driver ODBC Microsoft Access]Error in row
    at sun.jdbc.odbc.JdbcOdbcResultSet.setPos(JdbcOdbcResultSet.java:5271)
    at sun.jdbc.odbc.JdbcOdbcResultSet.updateRow(JdbcOdbcResultSet.java:4171)
    at desktopapplication1.Datab.setValueAt(Datab.java:104)
    at javax.swing.JTable.setValueAt(JTable.java:2719)
    at javax.swing.JTable.editingStopped(JTable.java:4721)
    at javax.swing.AbstractCellEditor.fireEditingStopped(AbstractCellEditor.java:125)
    at javax.swing.DefaultCellEditor$EditorDelegate.stopCellEditing(DefaultCellEditor.java:350)
    at javax.swing.DefaultCellEditor.stopCellEditing(DefaultCellEditor.java:215)
    at javax.swing.JTable$GenericEditor.stopCellEditing(JTable.java:5475)
    at javax.swing.DefaultCellEditor$EditorDelegate.actionPerformed(DefaultCellEditor.java:367)
    at javax.swing.JTextField.fireActionPerformed(JTextField.java:492)
    at javax.swing.JTextField.postActionEvent(JTextField.java:705)
    at javax.swing.JTextField$NotifyAction.actionPerformed(JTextField.java:820)
    at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1636)
    at javax.swing.JComponent.processKeyBinding(JComponent.java:2851)
    at javax.swing.JComponent.processKeyBindings(JComponent.java:2886)
    at javax.swing.JComponent.processKeyEvent(JComponent.java:2814)
    at java.awt.Component.processEvent(Component.java:6040)
    at java.awt.Container.processEvent(Container.java:2041)
    at java.awt.Component.dispatchEventImpl(Component.java:4630)
    at java.awt.Container.dispatchEventImpl(Container.java:2099)
    at java.awt.Component.dispatchEvent(Component.java:4460)
    at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1848)
    at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:704)
    at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:969)
    at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:841)
    at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:668)
    at java.awt.Component.dispatchEventImpl(Component.java:4502)
    at java.awt.Container.dispatchEventImpl(Container.java:2099)
    at java.awt.Window.dispatchEventImpl(Window.java:2475)
    at java.awt.Component.dispatchEvent(Component.java:4460)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
    my db is like
    RecipeName intvalue1 intvalue2 intvalue3 stringvalue4
    soup 3 2 11 fish
    chocolate 3 2 44 dessert
    Edited by: kainard on Aug 1, 2010 2:31 PM
    Edited by: kainard on Aug 1, 2010 2:37 PM

    Can you explain why you declare
    private Connection conn;
    private Statement st;
    private ResultSet rs;
    private ResultSetMetaData rsmd;
    as private

  • 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();
    }

  • Can not show the JCheckBox in JTable cell

    I want to place a JCheckBox in one JTable cell, i do as below:
    i want the column "d" be a check box which indicates "true" or "false".
    String[] columnNames = {"a","b","c","d"};
    Object[][] rowData = {{"", "", "", Boolean.FALSE}};
    tableModel = new DefaultTableModel(rowData, columnNames);
    dataTable = new JTable(tableModel);
    dataTable.getColumnModel().getColumn(3).setCellEditor(new DefaultCellEditor(new JCheckBox()));
    But when i run it, the "d" column show the string "false" or "true", not the check box i wanted.
    I do not understand it, can you help me?
    Thank you very much!
    coral9527

    Do not use DefaultTableModel, create your own table model and you should implement the method
    getColumnClass to display the boolean as checkbox ...
    I hope the following colde snippet helps you :
    class MyModel extends AbstractTableModel {
              private String[] columnNames = {"c1",
    "c2"};
    public Object[][] data ={{Boolean.valueOf(true),"c1d1"}};
         public int getColumnCount() {
         //System.out.println("Calling getColumnCount");
         return columnNames.length;
    public int getRowCount() {
    //System.out.println("Calling row count");
    return data.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
    return data[row][col];
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    * Don't need to implement this method unless your table's
    * editable.
    public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    return true;
    * Don't need to implement this method unless your table's
    * data can change.
    public void setValueAt(Object value, int row, int col) {
    data[row][col] = value;
    fireTableCellUpdated(row, col);

  • Display data in JTable

    I am trying to display data from database into the JTable swing component. I can see the table and the heading coming from the vector. I cannot see why the data from the databse table is not loaded on to the Jtable. I just get a table with 6 rows blank.
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    public class dataTable extends JApplet
    String dbdriver="jdbc:oracle:thin:@ds1.ctateu.edu:1521:wpac";
    String dbuser="system";
    String dbpass="pass";
    Container c;
    JScrollPane jsp;
    JTable table;
    int v,h;
    Connection connection;
    Statement stmt;
    ResultSet rs;
    String param_start,param_end, param_disp_start, param_disp_end,param_shortdesc, param_longdesc;
    public void init()
    c= getContentPane();
    c.setLayout (new BorderLayout());
    v=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
    h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
    Vector heading = new Vector();
    heading.addElement("Event Start Date");
    heading.addElement("Event End Date");
    heading.addElement("Display Start Date");
    heading.addElement("Display End Date");
    heading.addElement("Short Description");
    heading.addElement("Long Description");
    Vector data = new Vector();
    try
    Class.forName("oracle.jdbc.driver.OracleDriver");
    connection=DriverManager.getConnection(dbdriver,dbuser,dbpass);
    stmt=connection.createStatement();
    rs= stmt.executeQuery("select * from univevents");
    while(rs.next())
    param_start = rs.getString("start_date");
    param_end = rs.getString("end_date");
    param_disp_start = rs.getString("display_start");
    param_disp_end =rs.getString("display_end");
    param_shortdesc = rs.getString("short_desc");
    param_longdesc = rs.getString("long_desc");
    catch (Exception e)
    //JOptionPane.showMessageDialogue("Exception: "+e.getMessage());
    data.addElement(param_start);
    data.addElement(param_end);
    data.addElement(param_disp_start);
    data.addElement(param_disp_end);
    data.addElement(param_shortdesc);
    data.addElement(param_longdesc);
    table = new JTable(data, heading);
    jsp = new JScrollPane(table,v,h);
    //Add scrollpane to container
    c.add("Center",jsp);
    }//init
    }//JApplet

    Your data vector should be a Vector of Vectors.
    I think you need to change your loop to look something like this:
    while(rs.next())
        Vector row = new Vector();
        row.addElement( rs.getString("start_date") );
        row.addElement( rs.getString("end_date") );
        row.addElement( rs.getString("display_start") );
        row.addElement( rs.getString("display_end") );
        row.addElement( rs.getString("short_desc") );
        row.addElement( rs.getString("long_desc") );
        data.addElement( row );
    } Then remove your data.addElement() statements found outside the loop.

Maybe you are looking for