DataDriven testing with TestNG using Apache POI in Selenium WebDriver - selenium-webdriver

I am new to TestNG framework. Please guide how to parameterise the test cases using Apache POI(Excel).
I have a code to read from second row from Excel.
public class spreadData {
private transient Collection data = null;
public spreadData(final InputStream excelInputStream) throws IOException {
this.data = loadFromSpreadsheet(excelInputStream);
}
public Collection getData() {
return data;
}
private Collection loadFromSpreadsheet(final InputStream excelFile)
throws IOException {
HSSFWorkbook workbook = new HSSFWorkbook(excelFile);
data = new ArrayList();
Sheet sheet = workbook.getSheetAt(0);
int numberOfColumns = countNonEmptyColumns(sheet);
List rows = new ArrayList();
List rowData = new ArrayList();
/*for (Row row : sheet) {
if (isEmpty(row)) {
break;
} else {
rowData.clear();
for (int column = 0; column < numberOfColumns; column++) {
Cell cell = row.getCell(column);
rowData.add(objectFrom(workbook, cell));
}
rows.add(rowData.toArray());
}
}*/
int rowStart = 1;
//int rowEnd = Math.max(1400, sheet.getLastRowNum());
for (int rowNum = rowStart; rowNum <= sheet.getLastRowNum(); rowNum++) {
//Row r = sheet.getRow(rowNum);
Row read = sheet.getRow(rowNum);
if (isEmpty(read)) {
break;
} else {
rowData.clear();
for (int column = 0; column < numberOfColumns; column++) {
Cell cell = read.getCell(column);
rowData.add(objectFrom(workbook, cell));
}
rows.add(rowData.toArray());
}
}
return rows;
}
private boolean isEmpty(final Row row) {
Cell firstCell = row.getCell(0);
boolean rowIsEmpty = (firstCell == null)
|| (firstCell.getCellType() == Cell.CELL_TYPE_BLANK);
return rowIsEmpty;
}
/**
* Count the number of columns, using the number of non-empty cells in the
* first row.
*/
private int countNonEmptyColumns(final Sheet sheet) {
Row firstRow = sheet.getRow(0);
return firstEmptyCellPosition(firstRow);
}
private int firstEmptyCellPosition(final Row cells) {
int columnCount = 0;
for (Cell cell : cells) {
if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
break;
}
columnCount++;
}
return columnCount;
}
private Object objectFrom(final HSSFWorkbook workbook, final Cell cell) {
Object cellValue = null;
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
cellValue = cell.getRichStringCellValue().getString();
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
cellValue = getNumericCellValue(cell);
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
cellValue = cell.getBooleanCellValue();
} else if (cell.getCellType() ==Cell.CELL_TYPE_FORMULA) {
cellValue = evaluateCellFormula(workbook, cell);
}
return cellValue;
}
private Object getNumericCellValue(final Cell cell) {
Object cellValue;
if (DateUtil.isCellDateFormatted(cell)) {
cellValue = new Date(cell.getDateCellValue().getTime());
} else {
cellValue = cell.getNumericCellValue();
}
return cellValue;
}
private Object evaluateCellFormula(final HSSFWorkbook workbook, final Cell cell) {
FormulaEvaluator evaluator = workbook.getCreationHelper()
.createFormulaEvaluator();
CellValue cellValue = evaluator.evaluate(cell);
Object result = null;
if (cellValue.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
result = cellValue.getBooleanValue();
} else if (cellValue.getCellType() == Cell.CELL_TYPE_NUMERIC) {
result = cellValue.getNumberValue();
} else if (cellValue.getCellType() == Cell.CELL_TYPE_STRING) {
result = cellValue.getStringValue();
}
return result;
}
}
My question is how to parameterise the test cases using TestNG? means by using #DataProvider TestNG annotation.
Kindly help me with a sample code or explanation.

I'm not sure which set of data you want...but here's how a dataProvider works:
Say I have a test that takes a String and then an int like this:
#Test(dataProvider = "excelData")
public void executeTest(String name, int value){}
My data provider would look something like this:
#DataProvider(name = "excelData")
public Object[][] data(){
return new Object[][]{
{"Test",1},
{"More Testing",7},
{"Last Test",-5}}
}
The test will be run 3 times, with each row of the array is the set of data that is to be passed in. You will need to convert your excel data into such a format.
Note, you can also return an Iterator<Object[]> if you prefer.

Related

My unity save system doesn't save integer array

I don't get any errors but my script doesn't load or possibly save my array...
here's the first script
[System.Serializable]
public class PlayerData
{
public float health;
public float thirst;
public float hunger;
public float oxygen;
public float[] position;
public int[] inventoryIDs;
public PlayerData (Health healthO, SaveLoad saveload)
{
//Save int items
health = healthO.health;
thirst = healthO.thirst;
hunger = healthO.hunger;
oxygen = healthO.oxygen;
//set and save location array
position = new float[3];
position[0] = healthO.transform.position.x;
position[1] = healthO.transform.position.y;
position[2] = healthO.transform.position.z;
//set and save inventory IDs
inventoryIDs = new int[50];
for(int i = 0; i < 50; i++)
{
inventoryIDs[i] = saveload.IDs[i];
}
}
}
here's the next
public class SaveLoad : MonoBehaviour
{
public GameObject player;
public int[] IDs;
public GameObject[] objects;
Inventory inventory;
Health health;
void Start()
{
IDs = new int[50];
objects = new GameObject[50];
inventory = player.GetComponent<Inventory>();
health = player.GetComponent<Health>();
}
void Update()
{
//Add IDs
for (int i = 0; i < 50; i++)
{
IDs[i] = inventory.slot[i].GetComponent<Slot>().ID;
}
//debug save load test
if (Input.GetKeyDown(KeyCode.Z))
{
SaveP();
}
if (Input.GetKeyDown(KeyCode.X))
{
LoadP();
}
}
public void SaveP()
{
SaveSystem.SavePlayer(health, this);
}
public void LoadP()
{
PlayerData data = SaveSystem.LoadPlayer();
//load stats
health.thirst = data.thirst;
health.hunger = data.hunger;
health.health = data.health;
health.oxygen = data.oxygen;
//Load position
Vector3 position;
position.x = data.position[0];
position.y = data.position[1];
position.z = data.position[2];
player.transform.position = position;
//load IDs
for (int i = 0; i < 50; i++)
{
IDs[i] = data.inventoryIDs[i];
}
//Load Items
for (int i = 0; i < 50; i++)
{
if(objects[IDs[i]] != null)
{
GameObject itemObject = (GameObject)Instantiate(objects[IDs[i]], new Vector3(0, 0, 0), Quaternion.identity);
Item item = itemObject.GetComponent<Item>();
inventory.AddItem(itemObject, item.ID, item.type, item.name, item.description, item.icon);
} else
{
return;
}
}
}
}
Here's the last script
public static class SaveSystem
{
public static string fileName = "FileSave.bin";
public static void SavePlayer(Health health, SaveLoad SL)
{
//Create formatter
BinaryFormatter bf = new BinaryFormatter();
// Create file stream
FileStream file = File.Create(GetFullPath());
//Save data
PlayerData data = new PlayerData(health, SL);
bf.Serialize(file, data);
//Close stream
file.Close();
}
public static PlayerData LoadPlayer()
{
if (SaveExists())
{
try
{
//Create formatter
BinaryFormatter bf = new BinaryFormatter();
//Create file stream
FileStream file = File.Open(GetFullPath(), FileMode.Open);
//Load data
PlayerData pd = (PlayerData)bf.Deserialize(file);
//close stream
file.Close();
//return data
return pd;
}
catch (SerializationException)
{
Debug.Log("Failed to load file at: " + GetFullPath());
}
}
return null;
}
private static bool SaveExists()
{
return File.Exists(GetFullPath());
}
private static string GetFullPath()
{
return Application.persistentDataPath + "/" + fileName;
}
}
there are all connected with the save load script loading and saving the variables into the player and items to the inventory sots. the inventory IDs array isn't saving or loading

Unblock row editing on WPF DataGrid

I have validation in DataGrid. I am copying and trying to paste multiple rows. But if there is a validation error in one of the rows on insertion, the validation will will be called in and disable editing of the other rows, therefore next rows will not be inserted.
My ValidationRule:
public class MyValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
MyModel myModel = (value as BindingGroup).Items[0] as MyModel ;
if (myModel.Top > myModel.Bottom)
{
return new ValidationResult(false, "Error!");
}
return new ValidationResult(true,null);
}
}
XAML:
<DataGrid.RowValidationRules>
<MyValidationRule ValidationStep="UpdatedValue"/>
<DataGrid.RowValidationRules>
The paste code:
protected virtual void OnExecutedPaste(object target, ExecutedRoutedEventArgs args)
{
if (ExecutePasteEvent != null)
{
ExecutePasteEvent(target, args);
if (args.Handled)
{
return;
}
}
List<string[]> clipboardData = Clipboard
Helper2.ParseClipboardData();
int minRowIndex = Items.Count;
int maxRowIndex = Items.Count;
int minColumn = 0;
if (SelectedCells.Any())
{
minRowIndex = SelectedCells.Min(g=> Items.IndexOf(g.Item));
maxRowIndex = Items.Count;
minColumn = SelectedCells.Min(g=> g.Column.DisplayIndex);
}
int minColumnDisplayIndex = (SelectionUnit != DataGridSelectionUnit.FullRow) ? minColumn : 0;
int maxColumnDisplayIndex = Columns.Count - 1;
int rowDataIndex = 0;
List<Tuple<int, int>> cellsToSelect = new List<Tuple<int, int>>();
for (int i = minRowIndex; i <= maxRowIndex && rowDataIndex < clipboardData.Count; i++, rowDataIndex++)
{
if (i == maxRowIndex)
{
if (!CanUserPasteToNewRows)
continue;
ICollectionView cv = CollectionViewSource.GetDefaultView(Items);
IEditableCollectionView iecv = cv as IEditableCollectionView;
if (iecv != null)
{
if (minRowIndex + clipboardData.Count > Items.Count)
{
iecv.AddNew();
if (rowDataIndex < clipboardData.Count)
{
maxRowIndex = Items.Count;
}
}
}
}
if (i < Items.Count)
{
CurrentItem = Items[i];
BeginEditCommand.Execute(null, this);
int clipboardColumnIndex = 0;
for (int j = minColumnDisplayIndex; clipboardColumnIndex < clipboardData[rowDataIndex].Length; j++, clipboardColumnIndex++)
{
DataGridColumn column = null;
foreach (DataGridColumn columnIter in this.Columns)
{
if (columnIter.DisplayIndex == j)
{
column = columnIter;
break;
}
}
column?.OnPastingCellClipboardContent(Items[i], clipboardData[rowDataIndex][clipboardColumnIndex]);
cellsToSelect.Add(new Tuple<int, int>(i, j));
}
CommitEditCommand.Execute(this, this);
}
}
UnselectAll();
UnselectAllCells();
if (Items.Count < 1)
return;
CurrentItem = Items[minRowIndex];
if (SelectionUnit == DataGridSelectionUnit.FullRow)
{
SelectedItem = Items[minRowIndex];
}
else if (SelectionUnit == DataGridSelectionUnit.CellOrRowHeader || SelectionUnit == DataGridSelectionUnit.Cell)
{
foreach(var c in cellsToSelect)
{
if(Columns.Count < c.Item1 && Columns.Count < c.Item2)
SelectedCells.Add(new DataGridCellInfo(Items[c.Item1], Columns[c.Item2]));
}
}
}
And ClipboardHelper.ParseClipboardData(); will return a list of strings for example: {"row1", "value1", "value2"},{"row2", "value1", "value2"}.
How to paste all copied rows?
And I need to allow editing of all rows with errors, and not the last one.

Codename One Table binded to a List of Property Objects to show and modify a database table

This question is specific for Codename One and it's about if my following code is a good-code or if there are better strategies.
This is my use case:
with a REST request, I get a database table as a list of DAOs (each DAO is row) serialized by JSON;
the client has a ServerAPI class with a method that returns the server response as List<SportTypeDAO>;
each SportTypeDAO is implemented as a PropertyBusinessObject;
I want to show a Form with a Table object that allows the user the view all the table and to modify some fields (and to add rows, but I didn't implemented this yet);
the Table will be serialized as JSON to send the modified table to the server.
The problems:
a Property can be easily binded to a TextField or to a InputComponent, but I don't know any default easy way to bind a PropertyBusinessObject to a row of a Table... or even to bind a List<PropertyBusinessObject> to a Table;
the Table uses internally a createCell method that uses the data passed to the TableModel to create each cell as Label or TextField (according to the fact that the cell is editable or not), so I cannot directly insert in the table TextFields binded to Properties.
I tried to solve the problem in the following way... but there is a lot of code for an easy conceptual task (bind a List<PropertyBusinessObject> to a Table)... is there any better approch? I have to do the same task for a lot of tables, and I'm worried to find a good solution that can be generalized as most as possible.
public class FormSportType extends BaseForm {
private static List<SportTypeDAO> listToShow = null;
public FormSportType() {
super("FormSportType", BoxLayout.y());
fillForm();
}
public FormSportType(Form backForm) {
super("FormSportType", BoxLayout.y());
addBackCommand(backForm);
fillForm();
}
private void fillForm() {
add(new Label("FormSportType"));
UiBinding uib = new UiBinding();
if (listToShow == null) {
listToShow = serverAPI.readSportType();
}
int rows = listToShow.size();
int colums = 5;
Object[][] dataArray = new Object[rows][colums];
for (int row = 0; row < rows; row++) {
for (int column = 0; column < colums; column++) {
String cell = "";
switch (column) {
case 0:
cell = listToShow.get(row).keyword.get();
break;
case 1:
cell = listToShow.get(row).text_IT.get();
break;
case 2:
cell = listToShow.get(row).text_EN.get();
break;
case 3:
cell = listToShow.get(row).position.get().toString();
break;
case 4:
cell = listToShow.get(row).dbAction.get().toString();
break;
}
dataArray[row][column] = cell;
}
}
TableModel model = new DefaultTableModel(new String[]{"Keyword", "Text_IT", "Text_EN", "Position", "DbAction"}, dataArray) {
#Override
public boolean isCellEditable(int row, int col) {
return (row > -1 && col != 0 && col != 4);
}
#Override
public void setValueAt(int row, int column, Object o) {
if (DEBUG) {
Log.p("Executing setValueAt \"" + o + "\" at row " + row + ", column " + column);
}
super.setValueAt(row, column, o);
try {
String value;
if (o instanceof String) {
value = (String) o;
} else if (o instanceof Integer) {
Integer num = (Integer) o;
value = num.toString();
} else {
if (DEBUG) {
Log.p("ERROR in setValueAt row " + row + ", column " + column + " because wrong object class");
}
throw new IllegalArgumentException("Object o is not a String or an Integer");
}
switch (column) {
case 0:
listToShow.get(row).keyword.set(value);
break;
case 1:
listToShow.get(row).text_IT.set(value);
break;
case 2:
listToShow.get(row).text_EN.set(value);
break;
case 3:
listToShow.get(row).position.set(Integer.valueOf(value));
break;
case 4:
listToShow.get(row).dbAction.set(Integer.valueOf(value));
break;
default:
if (DEBUG) {
Log.p("ERROR in setValueAt row " + row + ", column " + column + ", because wrong column number");
}
}
} catch (Exception ex) {
if (DEBUG) {
Log.p("ERROR in setValueAt row " + row + ", column " + column);
Log.e(ex);
}
}
if (DEBUG) {
List<Map<String, Object>> listMaps = new LinkedList<>();
for (SportTypeDAO dao : listToShow) {
listMaps.add(dao.getPropertyIndex().toMapRepresentation());
}
Map<String, List<Map<String, Object>>> toConvert = new HashMap<>();
toConvert.put("root", listMaps);
Log.p("--- New JSON content:\n" + JSONParser.mapToJson(toConvert));
}
}
#Override
public Object getValueAt(int row, int column) {
// if(DEBUG) Log.p("Executing getValueAt row " + row + ", column " + column);
try {
switch (column) {
case 0:
return listToShow.get(row).keyword.get();
case 1:
return listToShow.get(row).text_IT.get();
case 2:
return listToShow.get(row).text_EN.get();
case 3:
return listToShow.get(row).position.get();
case 4:
return listToShow.get(row).dbAction.get();
default:
if (DEBUG) {
Log.p("ERROR: cannot get value at row " + row + ", column: " + column);
}
return "";
}
} catch (Exception err) {
if (DEBUG) {
Log.p("ERROR: cannot get value at row " + row + ", column: " + column);
Log.e(err);
}
return "";
}
}
};
Table table = new Table(model) {
#Override
protected Component createCell(Object value, int row, int column, boolean editable) {
Component cell = super.createCell(value, row, column, editable);
if (row > -1) {
cell.setUIID("TableCell");
}
if (row > -1 && row % 2 == 0) {
// pinstripe effect
cell.getAllStyles().setBgColor(0xeeeeee);
cell.getAllStyles().setBgTransparency(255);
}
return cell;
}
#Override
protected TableLayout.Constraint createCellConstraint(Object value, int row, int column) {
TableLayout.Constraint con = super.createCellConstraint(value, row, column);
con.setWidthPercentage(100 / model.getColumnCount());
return con;
}
};
table.setSortSupported(true);
try {
table.sort(3, false); // order by position
if (DEBUG) {
Log.p("table.sort executed successfully");
}
} catch (Exception ex) {
if (DEBUG) {
Log.p("ERROR: cannot order table, maybe there are null values");
Log.e(ex);
}
}
add(table);
}
}
Right now we don't have a property list to table bind. I tried a stab on this and I think this is pretty easy. I'll add this to the next update but you should already be able to use this:
/**
* Implements table model binding, this is implemented as a class to allow
* additional features such as adding/removing rows
*/
public class BoundTableModel implements TableModel {
private List<PropertyBusinessObject> objects;
private PropertyBusinessObject prototype;
private Set<String> exclude = new HashSet<String>();
private PropertyBase[] columnOrder;
private Set<String> uneditable = new HashSet<String>();
private EventDispatcher listeners = new EventDispatcher();
/**
* Creates a table model with the business objects
* #param objects the objects of the model
* #param prototype the type by which we determine the structure of the table
*/
public BoundTableModel(List<PropertyBusinessObject> objects,
PropertyBusinessObject prototype) {
this.objects = objects;
}
/**
* The properties that are ignored
* #param b the property to ignore
*/
public void excludeProperty(PropertyBase b) {
exclude.add(b.getName());
}
/**
* Sets the order of the columns explicitly
* #param columnOrder the order of the columns based on the prototype
*/
public void setColumnOrder(PropertyBase... columnOrder) {
this.columnOrder = columnOrder;
}
/**
* Makes the property editable or uneditable
* #param pb the property base
* #param editable true for editable (the default)
*/
public void setEditable(PropertyBase pb, boolean editable) {
if(editable) {
uneditable.remove(pb.getName());
} else {
uneditable.add(pb.getName());
}
}
/**
* {#inheritDoc}
*/
#Override
public int getRowCount() {
return objects.size();
}
/**
* Adds a new business object to the table
* #param index the index of the addition
* #param b the business object
*/
public void addRow(int index, PropertyBusinessObject b) {
objects.add(index, b);
for(int col = 0 ; col < getColumnCount() ; col++) {
listeners.fireDataChangeEvent(col, index);
}
}
/**
* Removes the row at the given index
* #param index the position in the table
*/
public void removeRow(int index) {
objects.remove(index);
listeners.fireDataChangeEvent(Integer.MIN_VALUE, Integer.MIN_VALUE);
}
/**
* {#inheritDoc}
*/
#Override
public int getColumnCount() {
if(columnOrder != null) {
return columnOrder.length;
}
return prototype.getPropertyIndex().getSize() - exclude.size();
}
#Override
public String getColumnName(int i) {
if(columnOrder != null) {
return columnOrder[i].getLabel();
}
return prototype.getPropertyIndex().get(i).getName();
}
#Override
public boolean isCellEditable(int row, int column) {
return !uneditable.contains(prototype.getPropertyIndex().get(column).getName());
}
#Override
public Object getValueAt(int row, int column) {
PropertyBusinessObject pb = objects.get(row);
String n;
if(columnOrder != null) {
n = columnOrder[column].getName();
} else {
n = pb.getPropertyIndex().get(column).getName();
}
return pb.getPropertyIndex().get(n).get();
}
#Override
public void setValueAt(int row, int column, Object o) {
PropertyBusinessObject pb = objects.get(row);
String n;
if(columnOrder != null) {
n = columnOrder[column].getName();
} else {
n = pb.getPropertyIndex().get(column).getName();
}
pb.getPropertyIndex().get(n).setImpl(o);
listeners.fireDataChangeEvent(column, row);
}
#Override
public void addDataChangeListener(DataChangedListener d) {
listeners.addListener(d);
}
#Override
public void removeDataChangeListener(DataChangedListener d) {
listeners.removeListener(d);
}
}

How do i get Object index in an array

I have seen many threads about this but my problem doesn't solved. This may be a simple way but i have no idea...
I'm trying to get Objects indices in an array like so :
var test:Array = new Array();
for (var row:Number = 0; row < 2; row++) {
test[row] = [];
for (var column:Number = 0; column < 3; column++) {
test[row][column].addEventListener(MouseEvent.CLICK, objClicked);
test[row][column] = new ballShape(column, column, row);
addChild(test[row][column]);
}
}
function objClicked(evt:MouseEvent):void {
// Here must return Object index in array
}
P.S :
I can get items index in int array, but i don't know about objects.
Any ideas would be appreciated.
Edit :
ballShape.as
package {
import flash.display.Graphics;
import flash.display.Sprite;
import flash.events.MouseEvent;
import fl.motion.Color;
public class ballShape extends Sprite {
private var shapeId:uint;
private var currentPosition:uint;
private var arrayPosition:uint;
private var color:Number;
public function ballShape(Id:uint, currPos:uint, arrPos:uint) {
setId(Id);
setArrayPos(arrPos);
setCurrentPos(currPos);
//trace("Array : " + arrPos);
//trace("Curr : " + currPos);
if (arrPos == 0) {
var posX:uint = 60;
} else {
var posX:uint = (arrPos + 1) * 60;
}
if (currPos == 0) {
var posY:uint = 42;
} else {
var posY:uint = (currPos + 1) * 42;
}
if (arrPos == 0) {
color = 0xFF0000;
} else {
color = 0x00FF00;
}
graphics.beginFill(color, 1.0);
graphics.drawCircle(posX, posY, 20);
graphics.endFill();
this.addEventListener(MouseEvent.CLICK, Clicked);
}
public function setId(Id:uint):void {
shapeId = Id;
}
public function getId():uint {
return shapeId;
}
public function Clicked(evt:MouseEvent):void {
//return getId();
trace("Ball id is " + getId());
trace("Array id is " + getArrayPos());
trace("PositionInArray id is " + getCurrentPos());
//return arrayPosition;
}
public function setCurrentPos(Pos:uint):void {
currentPosition = Pos;
}
public function getCurrentPos():uint {
return currentPosition;
trace(currentPosition);
}
public function setArrayPos(arrayPos:uint):void {
arrayPosition = arrayPos;
}
public function getArrayPos():uint {
return arrayPosition;
trace(arrayPosition);
}
public function addBead(arrayId, currPos):void {
}
}
}
I would suggest adding row and column as public variables in your ballShape class.
That way you can get them like this:
function objClicked(evt:MouseEvent):void {
trace(ballShape(evt.target).getCurrentPos(), ballShape(evt.target).getArrayPos());
}
Maybe turn this two lines around:
test[row][column].addEventListener(MouseEvent.CLICK, objClicked);
test[row][column] = new ballShape(column, column, row);
to be :
test[row][column] = new ballShape(column, column, row);
test[row][column].addEventListener(MouseEvent.CLICK, objClicked);
Try something like:
protected function objClicked(e:MouseEvent):void {
for (var row: int=0; row < test.length; row++) {
var column:int = (test[row] as Array).indexOf(e.currentTarget);//use currentTarget so you don't try to match on internal Interactive Objects!
if (column>-1) {
trace(row, column);
return;//or break, if you need to do something else below this loop
}
}
}

database in Jtable and add jcheckbox in last column of all rows

since I am beginner, Jtable concept has made my brain rack a lot. with difficult i have maganaged to read a database and add it to jtable CODE given below. but am stuck as how to ADD A JCHECKBOX IN THE LAST COLUMN OF THE SAME TABLE.
public class ttt extends JFrame{
ResultSet rs;
int colcount;
String[] headers;
Connection con;
Statement st;
ttt(){
final Vector columnNames = new Vector();
final Vector data = new Vector();
JPanel panel=new JPanel();
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Driver loaded");
// Establish a connection
con= DriverManager.getConnection
("jdbc:odbc:ysr");
System.out.println("Database connecteddddd");
// Create a statement
st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT
Block_Name,Panchayat_Name,Village_Name," +
" Habitation_Name,Scheme_Name,Sanction_Amount FROM
ysr2011 where Habitation_Name= '10th mile' ");
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement( md.getColumnName(i) );
}
while (rs.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
}
catch(Exception e){}
JTable table = new JTable(data, columnNames);
JScrollPane scrollPane = new JScrollPane(table);
panel.add(scrollPane);
add(panel);
}
public static void main(String arg[])
{
try
{
ttt frame=new ttt();
frame.setSize(550,200);
frame.setVisible(true);
}
catch(Exception e)
{}
}
}
ANY HELP IS REALLY A WELCOME GESTURE. THANKING IN ADVANCE.
You would add the check box here:
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement( md.getColumnName(i) );
}
columnNames.addElement("Check Box");
while (rs.next()) {
Vector row = new Vector(columns + 1);
for (int i = 1; i <= columns; i++) {
row.addElement( rs.getObject(i) );
}
row.addElement(new JCheckBox());
data.addElement( row );
}
Use your own column title. You're also going to have to define the check boxes more completely because eventually you're going to add tests for the isSelected method.

Resources