What best data structures to use? [closed] - arrays

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm using C# to rewrite some ColdFusion code.
The CF code looks like this:
An array contains a struct that consists of two sections:
Another struct, which contains header data extracted from a data file.
A 2D array that contains the actual data from each row in the same data file.
In C#, I'm using Dictionary and Jagged Array. See the code below. Are these the best data structures to use?
// Create AllDataArray that contains HeaderAndDataDict.
Dictionary<string, object>[] AllDataArray = new Dictionary<string, object>[1];
// Create HeaderAndData Dictionary.
Dictionary<string, object> HeaderAndDataDict = new Dictionary<string, object>();
// Add HeaderAndDataDict to AllDataArray[0].
AllDataArray[0] = HeaderAndDataDict;
// Create Header Dictionary.
Dictionary<string, string> HeaderDict = new Dictionary<string, string>();
// Populate Header Dictionary
HeaderDict.Add("Create Date", "10/20/2014");
HeaderDict.Add("ABC Rank", "ALL");
HeaderDict.Add("Status", "All");
// Add Header Dictionary to HeaderAndDataDict.
HeaderAndDataDict.Add("Header", HeaderDict);
// Create jagged array.
string[][] DataJaggedArray = new string[2][];
DataJaggedArray[0] = new string[] { "aaaa0", "bbbb0", "cccc0" };
DataJaggedArray[1] = new string[] { "aaaa1", "bbbb1", "cccc1" };
// Add DataJaggedArray to HeaderAndDataDict.
HeaderAndDataDict.Add("Data", DataJaggedArray);
// Display data.
for (int a = 0; a < AllDataArray.Length; a++)
{
Console.WriteLine("AllDataArray = " + a);
foreach (var key1 in HeaderAndDataDict.Keys)
{
Console.WriteLine("key= " + key1);
if (key1.Equals("Header"))
{
var valueHeader = (Dictionary<string, string>)HeaderAndDataDict[key1];
foreach (var key2 in valueHeader.Keys)
{
Console.WriteLine("valueHeader= {0}= {1}", key2, valueHeader[key2]);
}
}
else if (key1.Equals("Data"))
{
var valueData = (string[][])HeaderAndDataDict[key1];
Console.WriteLine("valueData length= " + valueData.Length);
for (int i = 0; i < valueData.Length; i++)
{
for (int j = 0; j < valueData[i].Length; j++)
{
Console.WriteLine("valueData= i= " + i + " j= " + j + " " + valueData[i][j]);
}
}
}
}
} // AllDataArray for loop

Consider using an object-oriented approach to hold your data. This means creating a class that holds the headers and data rows:
public class DataItem
{
private readonly Dictionary<string, string> _headers = new Dictionary<string, string>();
private readonly List<string[]> _rows = new List<string[]>();
public IEnumerable<string> Headers
{
get { return _headers.Keys; }
}
public void AddHeader(string key, string value)
{
_headers.Add(key, value);
}
public string GetHeader(string key)
{
return _headers[key];
}
public string[] GetDataRow(int rowNumber)
{
return _rows[rowNumber];
}
public void AddDataRow(string[] row)
{
_rows.Add(row);
}
public int RowCount
{
get { return _rows.Count; }
}
}
When you have this infrastructure ready, the actual implementation becomes simpler and less error-prone:
//add data
List<DataItem> allData = new List<DataItem>();
var dataItem = new DataItem();
dataItem.AddHeader("Create Date", "10/20/2014");
dataItem.AddHeader("ABC Rank", "ALL");
dataItem.AddHeader("Status", "All");
dataItem.AddDataRow(new [] {"aaaa0", "bbbb0", "cccc0"});
dataItem.AddDataRow(new[] {"aaaa1", "bbbb1", "cccc1"});
allData.Add(dataItem);
//display data
foreach (var item in allData)
{
Console.WriteLine("New item:");
foreach (var header in item.Headers)
{
Console.WriteLine("{0}: {1}", header, item.GetHeader(header));
}
for (int i = 0; i < item.RowCount; i++)
{
var row = item.GetDataRow(i);
for (int j = 0; j < row.Length; j++)
{
Console.WriteLine("Cell ({0}, {1}): {2}", i, j, row[j]);
}
}
}
Additionaly, if you like to, you could move the printing code to within the data item class:
public class DataItem
{
public void Print()
{
Console.WriteLine("New item:");
foreach (var header in Headers)
{
Console.WriteLine("{0}: {1}", header, GetHeader(header));
}
for (int i = 0; i < RowCount; i++)
{
var row = GetDataRow(i);
for (int j = 0; j < row.Length; j++)
{
Console.WriteLine("Cell ({0}, {1}): {2}", i, j, row[j]);
}
}
}
}
Then using it like this:
//display data
foreach (var item in allData)
{
item.Print();
}
This will have the advantage that if you require printing from somewhere else in your program you can do it more easily. This can also work for other things like loading data from a text file, or saving it back.
Update
To access your data using LINQ, here is an example that filters on rows and headers, then sorts the results by the value in the Create Date header.
var query = from item in allData
where item.GetHeader("Status") == "Status 1"
&& item.GetHeader("ABC Rank") == "3"
&& item.GetDataRow(1).Contains("bbbb1")
orderby item.GetHeader("Create Date")
select item;
foreach (var item in query)
item.Print();

They are valid choices.
I don't think there is a "best" solution for all usages
It depends on how you plan to access them (number of read / write operations, thread safety, ...).

Related

How can I save 3-dimension array into file and load later

I'm trying to save the 3D array witch has position data of the blocks with Unity and I can't find out how to save it.
public class Block
{
public Vector3 position;
public short blockType;
public byte facing;
public Block(Vector3 pos, short t, byte f)
{
position = pos;
blockType = t;
facing = f;
}
}
This is the block class which I stored the information about block.
public Block[,,] WorldBlock = new Block[100, 10, 100];
This is the array I want to save and it has 100000 blocks in it.
There are many ways how to approach this.
One way would e.g. be Newtonsoft JSON (comes as a package via the PackageManager and even pre-installed in latest Unity versions)
using Newtonsoft.Json;
....
public Block[,,] WorldBlock = new Block[100, 10, 100];
private string filePath => Path.Combine(Application.persistentDataPath, "example.json");
private void Save()
{
var json = JsonConvert.SerializeObject(WorldBlock);
File.WriteAllText(filePath, json);
}
private void Load()
{
if (File.Exists(filePath))
{
var json = File.ReadAllText(filePath);
WorldBlock = JsonConvert.DeserializeObject<Block[,,]>(json);
}
var block = WorldBlock[1, 2, 3];
Debug.Log($"{block.position} - {block.blockType} - {block.facing}");
}
Or - since JSON wastes a lot of character space for your use case - you could also implement you own binary serialization e.g. usingBinaryReader and BinaryWriter
in something like e.g.
[Serializable]
public class Block
{
public Vector3 position;
public short blockType;
public byte facing;
public Block(Vector3 pos, short t, byte f)
{
position = pos;
blockType = t;
facing = f;
}
public void Serialize(BinaryWriter writer)
{
writer.Write(position.x);
writer.Write(position.y);
writer.Write(position.z);
writer.Write(blockType);
writer.Write(facing);
}
public void Deserialize(BinaryReader reader)
{
position. x = reader.ReadSingle();
position. y = reader.ReadSingle();
position. z = reader.ReadSingle();
blockType = reader.ReadInt16();
facing = reader.ReadByte();
}
}
and then do
private void Save()
{
using (var stream = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.Write))
{
using (var writer = new BinaryWriter(stream))
{
// first store the size of each dimension
for (var i = 0; i < WorldBlock.Rank; i++)
{
writer.Write(WorldBlock.GetLength(i));
}
// then serialize all blocks
for (var i = 0; i < WorldBlock.GetLength(0); i++)
{
for (var j = 0; j < WorldBlock.GetLength(1); j++)
{
for (var k = 0; k < WorldBlock.GetLength(2); k++)
{
var block = WorldBlock[i, j, k];
block.Serialize(writer);
}
}
}
}
}
}
private void Load()
{
if (File.Exists(filePath))
{
using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
{
using (var reader = new BinaryReader(stream))
{
// first get th size of each dimension
var x = reader.ReadInt32();
var y = reader.ReadInt32();
var z = reader.ReadInt32();
WorldBlock = new Block[x, y, z];
// then deserialize all blocks
for (var i = 0; i < WorldBlock.GetLength(0); i++)
{
for (var j = 0; j < WorldBlock.GetLength(1); j++)
{
for (var k = 0; k < WorldBlock.GetLength(2); k++)
{
var block = new Block();
block.Deserialize(reader);
WorldBlock[i, j, k] = block;
}
}
}
}
}
}
var exampleBlock = WorldBlock[1, 2, 3];
Debug.Log($"{exampleBlock.position} - {exampleBlock.blockType} - {exampleBlock.facing}");
}

Unity - Adding multiple array parameters in method (for adding multiple items)

I'm trying to achieve a method that I can call to create multiple items
This is the method I'm trying to get it to work
public void AddMultipleItems(string[] itemKey, int[] amount)
{
for (int i = 0; i < itemKey.Length; i++)
{
Item item;
item = ItemCollection[itemKey[i]];
for (int x = 0; x < amount.Length; x++)
{
if (inventory.CanAddItem(item, amount[x]) == true)
{
inventory.AddItem(item.GetCopy());
}
else if (inventory.CanAddItem(item, amount[x]) == false)
{
Debug.Log("Inventory Full");
break;
}
}
}
}
And then this method will be called to add in items like this:
itemDB.AddMultipleItems(new string[] { "Boots", "Gold Coin", "Apple" }, new int[] {1, 2, 3 });
Result: I get 3 Boots, 3 Gold coin and 3 Apple. when I should be getting 1 Boots, 2 Gold Coin & 3 Apples,
I've done a similar Method like this except it doesn't require array parameters and it works perfectly:
public void AddItems(string itemKey, int amount)
{
//First check if entered itemKey parameter exists in ItemCollection Dictionary
if (ItemCollection.ContainsKey(itemKey))
{
Item item;
item = ItemCollection[itemKey];
if (item != null)
{
//check if we can add the item and the amount of it
if (inventory.CanAddItem(item, amount))
{
//loop through the total amount
for (int i = 0; i < amount; i++)
{
//add the item
inventory.AddItem(item.GetCopy());
}
Debug.Log(itemKey + " Added Successfully!");
}
else
{
Debug.Log("Not enough space in Inventory");
}
}
else
{
Debug.Log("Null Item");
}
}
else
{
Debug.Log(itemKey + " does not exist in ItemDatabase's Dictionary");
}
}
So basically another way of looking at it is how can I turn the AddItems(string itemKey, int amount) into AddItems(string[] itemKey, int[] amount). its the for loop, foreach loop and arrays that are kinda tripping me over since I'm not very good at those.
Appreciate any help, Thank you!
For every item you are iterating over the entire amount array which has 3 entries. I would actually expect that for each item you get 1+2+3 = 6 items added.
Wouldn't you rather want to only get the amount to add from the one entry in amount with the same index as the given itemKey: amount[i]
public void AddMultipleItems(string[] itemKey, int[] amount)
{
for (int i = 0; i < itemKey.Length; i++)
{
Item item;
item = ItemCollection[itemKey[i]];
if (inventory.CanAddItem(item, amount[i]))
{
inventory.AddItem(item.GetCopy());
}
else // your if condition here was redundant
{
Debug.Log("Inventory Full");
}
}
}
In general you already have a method for adding a single item so I wouldn't re-implement that for multiple ones but rather call it from the loop like
public void AddMultipleItems(string[] itemKey, int[] amount)
{
for (int i = 0; i < itemKey.Length; i++)
{
// Instead of re-implement rather call your existing method
// and treat each value pair as if ti was a single add call
AddItems(itemKey[i], amount[i]);
}
}
Then passing in two separate arrays is pretty error prone and hard to maintain. I would probably rather pass in a Dictionary<string, int> like e.g.
public void AddMultipleItems(Dictionary<string, int> itemsToAdd)
{
foreach (var kvp in itemsToAdd)
{
AddItems(kvp.Key, kvp.Value);
}
}
and then call it like
itemDB.AddMultipleItems(new Dictionary<string, int>{ {"Boots", 1}, {"Gold Coin", 2}, {"Apple", 3}});

AS3 - Auto refreshing display after updating array

So, basically I'm reinventing the wheel by trying to make a sort of spreadsheet in flash for tracking member growth in a game. In this one section I'm adding member names to an array and then placing the names into dynamically created tiles with text fields attached to display the name.
I have a save button which saves the array, and if I save, close, and reopen, then I can see the members I have added. However, I would like it to refresh the stage as soon as the array is changed to reflect the changes made (update the spreadsheet). I will also be adding and removing other tiles dynamically, but I can extrapolate the solution to this problem to all of those later.
Here's the code I have to add members and create the display:
public var mainArray:Array = new Array;
public var i1:Number = 0;
public var memberBox:MovieClip = new MovieClip();
public var MAX_ROWS = 0;
public var MAX_COLS = 0;
public function Tracker() {
MAX_COLS = mainArray.length - 1;
addBtn.addEventListener(MouseEvent.CLICK, addFun); //atchaed to button on stage
public function addFun($e:MouseEvent):void{
mainArray[i1] = [];
mainArray[i1][0] = addNameTxt.text //attached to textfield on stage
i1++;
loadMembers();
public function loadMembers():void{
var multiDimensionalArray:Array = new Array();
//initalize the arrays
for (var row = 0; row <= MAX_ROWS; row++)
{
var boolArray:Array = new Array();
for (var col = 0; col <= MAX_COLS; col++){
boolArray.push(false);
}
multiDimensionalArray.push(boolArray);
}
//now we can set the values of the array as usual
for (var row = 0; row <= MAX_ROWS; row++)
{
for (var col = 0; col <= MAX_COLS; col++){
multiDimensionalArray.push(1); ;
}
}
//create a column of tiles based on mainArray length with a textfield attached to each
buildLevel(multiDimensionalArray);
}
public function buildLevel(s:Array){
var txtArray:Array = new Array();
memberBox.name = "tileHolder";
for(var i=0; i < MAX_ROWS + 1; i++){
for(var o=0; o < MAX_COLS + 1; o++){
var currentTile:MemberBox = new MemberBox();
currentTile.x = i*150;
currentTile.y = o*25;
currentTile.name = "b"+o;
memberBox.addChild(currentTile);
//currentTile.gotoAndStop(int(s[o][i]));
var memberTxt:TextField=new TextField();
currentTile.addChild(memberTxt);
memberTxt.width = 150;
memberTxt.height = 25;
txtArray[o] = memberTxt;
txtArray[o].text = mainArray[o][0];
}
}
memberBox.x = 60;
memberBox.y = 170;
addChild(memberBox);
}
}
The ideal solution would be to attach event listeners to the Array, however, Arrays don't fire events.
Solution #1: Managed Updates
Rather than allowing any piece of code to modify your array directly, write a function that handles updating your array. This way, you can know when to update the display at the same time.
public var mainArray:Array = new Array;
public var i1:Number = 0;
public var memberBox:MovieClip = new MovieClip();
public var MAX_ROWS = 0;
public var MAX_COLS = 0;
public function Tracker() {
MAX_COLS = mainArray.length - 1;
addBtn.addEventListener(MouseEvent.CLICK, addFun); //attached to button on stage
public function addFun(e:MouseEvent):void {
mainArray[i1] = [];
mainArray[i1][0] = addNameTxt.text //attached to textfield on stage
i1++;
loadMembers();
}
public function loadMembers():void {
var multiDimensionalArray:Array = new Array();
//initalize the arrays
for (var row = 0; row <= MAX_ROWS; row++) {
var boolArray:Array = new Array();
for (var col = 0; col <= MAX_COLS; col++) {
boolArray.push(false);
}
multiDimensionalArray.push(boolArray);
}
//now we can set the values of the array as usual
for (var row = 0; row <= MAX_ROWS; row++) {
for (var col = 0; col <= MAX_COLS; col++) {
multiDimensionalArray.push(1); ;
}
}
//create a column of tiles based on mainArray length with a textfield attached to each
buildLevel(multiDimensionalArray);
}
public function buildLevel(s:Array) {
var txtArray:Array = new Array();
memberBox.name = "tileHolder";
for (var i:int = 0; i < MAX_ROWS + 1; i++) {
for(var o=0; o < MAX_COLS + 1; o++) {
var currentTile:MemberBox = new MemberBox();
currentTile.name = i + "_" + o;
currentTile.x = i*150;
currentTile.y = o*25;
memberBox.addChild(currentTile);
//currentTile.gotoAndStop(int(s[o][i]));
var memberTxt:TextField=new TextField();
currentTile.addChild(memberTxt);
memberTxt.width = 150;
memberTxt.height = 25;
txtArray[o] = memberTxt;
txtArray[o].text = mainArray[o][0];
}
}
memberBox.x = 60;
memberBox.y = 170;
addChild(memberBox);
}
public function modifyArray(row:int, col:int, value:*):void {
// Update our array.
mainArray[row][col] = value;
// Update our tile.
var tile:MemberBox = memberBox.getChildByName(row + "_" + col);
tile.getChildAt(0).text = value;
}
}
When you actually modified your array, you'd do that with your function, rather than a direct mainArray[o][i] approach.
// Instead of this
mainArray[o][i] = "foo";
// You'd do this
modifyArray(o, i, "foo");
Update: I'm not sure how better to explain this, so I've posted working example that you can view. It contains the class, and the document code, the fla, and the swf with working updates to the spreadsheet. Let me know if that resolves the issue: SpreadSheet Test # Dropbox
Solution #2: Poll for Changes
Hold two versions of your array in memory. The first is the one you're actively editing, the second is an untouched duplicate to compare against the first. Every so often (once per second?) you iterate over the entire dataset and look for differences. When one is found, update the duplicate array and the displayed spreadsheet.
Here's an example of how you'd do that:
import flash.utils.*;
var last:Number = flash.utils.getTimer();
this.addEventListener("enterFrame", checkData);
var foo:Array = ["a", "b", "c"];
var fooBackup:Array = [];
function update():void {
var txt:TextField;
for (var i:int = 0; i < foo.length; i++) {
// If we don't have a representation of this index, create one.
if (!this.getChildByName("tile"+i)) {
txt = new TextField();
txt.name = "tile" + i;
txt.text = foo[i];
this[txt.name] = txt;
addChild(txt);
txt.y = i * 20;
}
// Update the data if inconsistent.
txt = this.getChildByName("tile"+i) as TextField;
if (fooBackup.hasOwnProperty(i) == false || foo[i] != fooBackup[i]) {
fooBackup[i] = foo[i]
txt.text = foo[i];
trace("Index " + i + " changed. Updated backup, and display.");
}
}
}
function checkData(e:Event):void {
var now:Number = flash.utils.getTimer();
// If the last time we checked is greater than a second, run the check again.
if (now - last > 1000) {
// Update last checked index;
last += 1000;
// For the sake of argument, let's randomly change an index to a random value.
foo[random(0, foo.length-1)] = random(-1000, 1000);
update();
}
}
function random(low:Number=0, high:Number=1):Number {
/* Returns a random number between the low and high values given. */
return Math.floor(Math.random() * (1+high-low)) + low;
}
Solution #3: Roll your own Array
As outlined by Adobe's Extending the Array class, you can subclass Arrays and from there add your own event dispatches when you add/remove entries. This is the more adventurous solution, and (in my humble opinion) the best as it maintains code consistency, while giving broad and efficient powers.

DataDriven testing with TestNG using Apache POI in 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.

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