Sometimes in programming while we do our work with JTable cell, we may need to make the JTable cell Such that it will allow or accept only numeric or number type data from users and will not allow any other type of data in that cell. In the following example(Check the picture), I have made the cells of Column-2 such that they will allow only numeric data and it will show a warning message if any character or string type entry is detected. Just Copy the code and run it.
Code Example:
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();
public JtableCellValidation()
{
setTitle(“JTable Cell Validation”);
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[][]
{
{“1″,”2″,”3”},
{“4″,”5″,”6”},
{“7″,”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));
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);
JOptionPane.showMessageDialog(null,”String Type Entry Not Allowed”);
}
else
{
textBox.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);
}
}
OUTPUT:
An individual always prepare the best exciting articles or blog posts. And you also continually seem to take bad/boring elements and also change these straight into exciting/interesting things. Im your target audience for life-long!
LikeLike
How the hell does it work?
LikeLike