How to set a value in a particular JTable cell with Java?


Let’s say initially our table is the following with a specific cell [2,1] with value “Kane” −

The following is an example to set a new value to the above table. Here, we will update the cell [2,1] −

table.setValueAt("Guptill", 2, 1);

Let us see the complete example −

Example

package my;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.border.TitledBorder;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame();
      JPanel panel = new JPanel();
      panel.setBorder(BorderFactory.createTitledBorder(
      BorderFactory.createEtchedBorder(), "ODI Rankings", TitledBorder.CENTER,
      TitledBorder.TOP));
      String[][] rec = {
         { "1", "Steve", "AUS" },
         { "2", "Virat", "IND" },
         { "3", "Kane", "NZ" },
         { "4", "David", "AUS" },
         { "5", "Ben", "ENG" },
         { "6", "Eion", "ENG" },
      };
      String[] header = { "Rank", "Player", "Country" };
      JTable table = new JTable(rec, header);
      table.setShowHorizontalLines(true);
      table.setGridColor(Color.orange);
      table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
      table.setValueAt("Guptill", 2, 1);
      panel.add(new JScrollPane(table));
      frame.add(panel);
      frame.setSize(550, 400);
      frame.setVisible(true);
   }
}

The output is as follows with the updated value “Guptill” in the cell [2,1]. We initialized that particular table cell with value “Kane”, but using the setValueAt() method, we have updated it successfully with “Guptill” as shown below −

Updated on: 30-Jul-2019

864 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements