In my last post I shared about how to assign two different JTextField in two different JTable Column cells. Today I am sharing with you another important part of JTable cell validation where I have tried to show you about how to make first column of JTable cells take only Char or string input and also at the same time how to make the cells second column take int (integer ) input from the users. To implement this validation process I have assigned two different JTextField in two different JTable Cell Column. Just Copy the following code and Run it in your pc.
Here is the code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
class JtableCellValidation extends JFrame
{
private JPanel topPanel;
private JTable table;
private JScrollPane scrollPane;
private String[] columnNames=new String[3];
private String[][] dataValues=new String[3][3];
JTextField textBox=new JTextField();
JTextField textBox1=new JTextField();
public JtableCellValidation()
{
setTitle(“Two JTextFied In Two JTable Column”);
setSize(300,300);
setDefaultCloseOperation (EXIT_ON_CLOSE);
topPanel=new JPanel();
topPanel.setLayout(new BorderLayout());
getContentPane().add(topPanel);
columnNames=new String[] {“Column 1″ ,”Column 2”, “Column 3”};
dataValues=new String[][]
{
{“a”,”2″,”3″},
{“b”,”5″,”6″},
{“c”,”8″,”9″}
};
TableModel model=new myTableModel();
table=new JTable();
table.setRowHeight(50);
table.setModel(model);
TableColumn soprtColumn=table.getColumnModel().getColumn(1);
soprtColumn.setCellEditor(new DefaultCellEditor (textBox));
TableColumn soprtColumn1=table.getColumnModel().getColumn(0);
soprtColumn1.setCellEditor(new DefaultCellEditor (textBox1));
table.setCellSelectionEnabled(true);
scrollPane=new JScrollPane(table);
topPanel.add(scrollPane,BorderLayout.CENTER);
textBox.addKeyListener(new KeyAdapter()
{
public void keyTyped(KeyEvent e)
{
if(!Character.isDigit(e.getKeyChar()) && e.getKeyChar() !=KeyEvent.VK_BACK_SPACE)
{
textBox.setEditable(false);
textBox.setBackground(Color.WHITE);
}
else
{
textBox.setEditable(true);
}
}
});
textBox1.addKeyListener(new KeyAdapter()
{
public void keyTyped(KeyEvent ex)
{
if(Character.isDigit(ex.getKeyChar()) && ex.getKeyChar() !=KeyEvent.VK_BACK_SPACE)
{
textBox1.setEditable(false);
textBox1.setBackground(Color.WHITE);
}
else
{
textBox1.setEditable(true);
}
}
});
table.addMouseListener(new java.awt.event.MouseAdapter()
{
public void mouseClicked(java.awt.event.MouseEvent e)
{
}
});
}
public class myTableModel extends DefaultTableModel
{
myTableModel()
{
super(dataValues,columnNames);
}
public boolean isCellEditable(int row,int cols)
{
return true;
}
}
public static void main(String args[])
{
JtableCellValidation x=new JtableCellValidation();
x.setVisible(true);
}
}