While designing or preparing software you may face problem to check JTable cell is empty or not while entering JTable data in Database. Another thing may happen, suppose you are trying to validate your JTable cell empty or not but it is taking space or null entry as a string and your empty cell validation may not work. Here I am sharing you a little but useful technique by which you will be able to check your empty JTable cell and also if you enter space in the JTable cell it will catch this cell as empty and will show error. Just run the given program and check how it works.
Here is the Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
class ButtonBelowTable extends JFrame
{
private JPanel topPanel;
private JTable table;
public JScrollPane scrollPane;
public JScrollPane scrollPane1;
private String[] columnNames=new String[3];
private String[][] dataValues=new String[3][3];
JButton button=new JButton(“Click Here”);
public ButtonBelowTable()
{
setTitle(“Button Below the Table”);
setSize(320,300);
setDefaultCloseOperation (EXIT_ON_CLOSE);
button.setBounds(75,200,90,30);
columnNames=new String[] {“Column 1″ ,”Column 2”, “Column 3”};
dataValues=new String[][]
{
{“a”,”2″,” 1″},
{“b”,”5″,” 5″},
{“c”,”8″,” 7″}
};
topPanel=new JPanel();
topPanel.setLayout(null);
getContentPane().add(topPanel);
table=new JTable();
TableModel model=new myTableModel();
table.setModel(model);
scrollPane=new JScrollPane(table);
scrollPane.setSize(300,200);
scrollPane1=new JScrollPane(button);
scrollPane1.setSize(90,30);
scrollPane1.setBounds(75,200,150,30);
topPanel.add(scrollPane);
topPanel.add(scrollPane1);
button.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if(vaidCheck())
{
JOptionPane.showMessageDialog(null,” Great !! Field is filled up”);
}
else
{
JOptionPane.showMessageDialog(null,”Field is empty”);
}
}
}
);
}
public boolean vaidCheck()
{
if(table.getCellEditor()!=null){
table.getCellEditor().stopCellEditing();
}
for(int i=0;i< table.getRowCount();i++)
{
for (int j=0;j<table.getColumnCount();j++)
{
String om=table.getValueAt(i,j).toString();
System.out.println(“\n Value =”+om+ ” and Length :”+om.length());
if(om.trim().length()==0)
{
return false;
}
}
}
return true;
}
public class myTableModel extends DefaultTableModel
{
myTableModel()
{
super(dataValues,columnNames);
}
public boolean isCellEditable(int row,int cols)
{
return true;
}
}
public static void main(String args[])
{
ButtonBelowTable x=new ButtonBelowTable();
x.setVisible(true);
}
}