IEssGridView.getData.getDataCellAttributes(int row, int column) returns 0
I am retrieving cells containing values. In trying to figure out whether the cell is a READ_WRITE or a READ_ONLY cell, I called the getDataCellAttributes method for the cells in question. They all return zero attribute values.I printed out the values of DATA_CELL_ATTRIB_READ_WRITE (2) and DATA_CELL_ATTRIB_READ_ONLY (1). Presumably a non-zero value should be returned by this call. What am I doing wrong?Nils
Try this:IEssDataCell dataCell = (EssDataCell)grid.getCell(i,j);if (dataCell.getAccessMode()==IEssDataCell.EEssAccessMode.READ_WRITE) {..} else {..}
Similar Messages
-
JTable: Selecting rows in columns independently
Dear all,
I have a JTable with two columns. I want the user to be able to select cells in columns independently. At present, the entire row gets marked as selected. Is it possible at all to, for instance, select row1 1 to 3 in column 1 and rows 4 to 5 in column 2? If so, where's the switch? Thanks a lot in advance!
Cheers,
MartinAre you trying to use a seperate table for each column.
Thats not a good idear.
Here is what you have to do.
1. Create a sub class of JTable
2. You will have to redefine how the selection is done so. You will need some sort of a collection to store the list of selected cells indexes
2.1 Selecting a cell is simply adding the coordinations of the cell to the selection
2.2 de selecting is just removing it from the collection.
2.3 Here is what you have to override
setColumnSelectionInterval()
setColumnSelectionInterval()
changeSelection()
selectAll()
getSelectedColumns()
getSelectedColumn()
getSelectedRows()
getSelectedRow() You migh also need few new methods such as
setCellSelected(int row, int column, boolean selected);
boolean isCellSelected(int row, int column);
clearSelection();
int[][] getSelectedCells();You will have to implement the above in terms of your new data structure.
3. Handle mouse events.
Ex:- when user cicks on a cell if it is already selected it should be deselected (see 2.2)
other wise current selected should be cleared and the clicked cell should be selected
if your has pressed CTRL key while clicking the the cell should be selected without deselecting the old selection.
---you can use above using a MouseListener
When the user hold down a button and move the mouse accross multiple cell those need to be selected.
--- You will need a MouseMotionListener for this
You might also need to allow selection using key bord. You can do that using a KeyListener
4. Displaying the selection
You have to make sure only the selected cells are high lighted on the table.
You can do this using a simple trick.
(Just override getCellEditor(int row, int column) and getCellRenderer(int row, int column) )
Here is what you should do in getCellRenderer(int row, int column)
public TableCellRenderer getCellRenderer(int row, int column)
TableCellRenderer realRenderer = super.getCellRenderer(int row, int);
return new WrapperRenderer(realRenderer,selectedCellsCollection.isCellSelected(row,column));
static class WrapperRenderer implements TableCellRenderer{
TableCellRenderer realRenderer;
boolean selected;
public WrapperRenderer(TableCellRenderer realRenderer, boolean selected){
this.realRenderer = realRenderer;
this.selected = selected;
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column){
return realRenderer.getTableCellRendererComponent(table,value,selected,hasFocus,row,column);
}What the above code does is it simply created wrapper for the Renderer and when generating the rendering component it replaces the isSeleted flag with our on selected flag
and the original renderer taken from the super class will do the rest.
You will have to do the same with the TableCellEditor.
By the way dont use above code as it is becouse the getCellRenderer method create a new instance of WrapperRenderer every time.
If the table has 10000 cells above will create 10000 instances. So you should refine above code.
5. Finnaly.
Every time the selection is changes you should make the table rerender the respective cells in or der to make the changes visible.
I'll leave that part for you to figure out.
A Final word
When implementing th above make sure that you do it in the java way of doing it.
For the collection of selected cells write following classes
TableCellSelectionModel // and interface which define what it does
DefaultTableCellSelectionModel //Your own implementation of above interface the table you create should use thisby default
//To communicate the selection changes
TableCellSelectionModelListener
TableCellSelectionModelEventif you read the javadoc about similer classes in ListSelectionModel you will get an idear
But dont make it as complex as ListSelectionModel try to keep the number of methods less than 5.
If you want to make it completly genaric you will have to resolve some issues such as handling changes to the table model.
Ex:- Rows and colums can be added and removed in the TableModle at the run time as a result the row and column indexes of some cells might change
and the TableCellSelectionModel should be updated with those changes.
Even though the todo list is quite long if you plan your implementation properly the code will not be that long.
And more importantly you will learn lots more by trying to implementing this.
Happy Coding :) -
A question about ResultSet.UpdateObject(int column, Object x)
hi, I write some code which use the TableModel to represent the data fetched from MS-ACCESS.
the problem is about the UpdateObject(...) method which is in the implement of the AbstractTableModel method setAtValue(). when transfered OBJECT TYPE is java.lang.String, I can't get the correct result in the JTable view.
my code is as below, could somebody point me out my problem
public class MyTableModel extends AbstractTableModel {
private ResultSet rs ;
private ResultSetMetaData rsmd;
/** Creates a new instance of MyTableModel */
public MyTableModel() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
String url = "jdbc:odbc:CoffeeBreak";
try {
Connection con = DriverManager.getConnection(url,"","");
String strSQL = "SELECT * FROM COFFEES";
Statement pSt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs = pSt.executeQuery(strSQL);
rsmd = rs.getMetaData();
} catch (SQLException ex) {
ex.printStackTrace();
/* table model retrieve the Class type of a column method here*/
public Class getColumnClass(int c){
try {
return Class.forName(rsmd.getColumnClassName(c+1));
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (SQLException ex) {
ex.printStackTrace();
return String.class;
//method of update database and JTable after user edited a table cell
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
try {
int concurrency = rs.getConcurrency();
if(concurrency == 1008){
rs.absolute(rowIndex+1); //the JTable row index is start from 0,so plus 1
rs.updateObject(columnIndex+1, aValue);//the JTable column index is start from 0, so plus 1
rs.updateRow();
} catch (SQLException ex) {
ex.printStackTrace();
}when the column type is about java.lang.String, the cell's result is incorrect, it looks like "[B@1f8f72f" and database can't update.It's me again.
I post the whole class code here
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
* @author qhj
public class MyTableModel extends AbstractTableModel {
/** Creates a new instance of MyTableModel */
private ResultSet rs ;
private ResultSetMetaData rsmd;
private Statement pSt;
private String strSQL;
public MyTableModel() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
String url = "jdbc:odbc:CoffeeBreak";
try {
Connection con = DriverManager.getConnection(url,"","");
strSQL = "SELECT * FROM COFFEES";
pSt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs = pSt.executeQuery(strSQL);
rsmd = rs.getMetaData();
} catch (SQLException ex) {
ex.printStackTrace();
public int getRowCount() {
try {
rs.last();
return rs.getRow();
} catch (SQLException ex) {
ex.printStackTrace();
return 0;
public int getColumnCount() {
try {
return rsmd.getColumnCount();
} catch (SQLException ex) {
ex.printStackTrace();
return 0;
public Object getValueAt(int rowIndex, int columnIndex) {
try {
rs.absolute(rowIndex+1);
return rs.getObject(columnIndex+1);
} catch (SQLException ex) {
ex.printStackTrace();
return null;
public String getColumnName(int column){
try {
return rsmd.getColumnName(column+1);
} catch (SQLException ex) {
ex.printStackTrace();
return "N/A";
public Class getColumnClass(int c){
try {
return Class.forName(rsmd.getColumnClassName(c+1));
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (SQLException ex) {
ex.printStackTrace();
return String.class;
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
return true;
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
try {
int concurrency = rs.getConcurrency();
if(concurrency == 1008){
rs.absolute(rowIndex+1);
rs.updateObject(columnIndex+1, aValue);
//rs.updateRow();
//rs = pSt.executeQuery(strSQL);
} catch (SQLException ex) {
ex.printStackTrace();
fireTableDataChanged();
} -
Obiee 11g Administrator: Dividing an INT with an INT column results in INT
OBIEE 11.1.1.7.1
I have developed a formula column in BMM. The column is based on dividing an INT column with another INT column.
The formula column picks automatically the type as INT and when I developed a report on this column it shows integer values instead of decimal.
Dividing Profit by Cost (both integers) should give an index which is a decimal value. How to come up with that?Multiply with 1.0 to see decimal values
ex: (a*1.0)/b
or else try data format in report
if helps mark -
Search row and column for return value
Dear Sir/Madam,
I have a problem for searching spreadsheet and hope you can help me out a bit. Im pretty new to Labview and Im currently using Labview 8.0. My task is to search the spreadsheet I have attached in row and column-wise, then return the corresponding value out. I had an attempt in doing this as you can see from the vi that i have attached. I try inputting the 'read from measurement file' into an array and using delete, index and search array I will be able to find the index value for the relevant row and column that i searched for by inputting them into an index array with the orginal array from the 'read from measurement file'.
So ultimately, when i enter a row value of 0.5 and a column value of 0.3, my output will be 1.688.
I can't see any mistakes in my logic but I getting really strange results, like I can read my data has been entered into an array but when i try deleting the first column and put it into another array, the orginal array with nothing deleted is outputted hence making my search to give out -1 value. So could you take a look please and give me any suggestion that can solve my problem or enhance the code a bit. Thank you for your time.
Best Regards,
Coato
P.s for some reason i can't attached the .lvm file of my data hence i have attached the excel version but i think you need to convert it back to .lvm for the 'read from measurement file' function to work.
Attachments:
Backswing compensation.csv 10 KB
Backswing comnpensation2.vi 109 KBYour VI makes absolutely no sense to me, but maybe I don't understand what you are trying to do.
You seem to have dynamic data with 6 signals and 48 points/channel. Now you reshape this into an array of dynamic data with 4x13 elements from which you slice out one row or column, resp. "delete from array" is NOT the correct tool to do this, use "Index array" with one index unwired to get a row or column as 1D array.
So you end up with two 1D arrays of dynamic data that you search for DBL. It is difficult to understand how you want to search for an array element that corresponds to a scalar DBL value of 0.1. Your array elements are NOT DBLs but dynamic data, each containing many signals!
There are two elements on all your data that are "3", the rest are zero. You will never find anything that is 0.1.
Maybe you can convert your original dynamic data to a 2D array with "rows are signals" using "convert from dynamic data", then operate on the 2D array.
Coato wrote:
So ultimately, when i enter a row value of 0.5 and a column value of 0.3, my output will be 1.688.
Sorry, Please explain.
Please make a VI containing a simple 2D aray as diagram constant that contains e.g. 5x5 typical values. Let us know what kind of result you expect from your algorithm..
LabVIEW Champion . Do more with less code and in less time . -
Hi Guys,
I have to add a new Big INT column to existing table in production, which holds 700 million records and would like to know the impact?
I have been tolled by one of my colleagues that last time they tried adding a column to same table during working hour and it locked out the table and impacted the users.
Please suggest/share If any one had similar experience.
Thanks Shiven:) If Answer is Helpful, Please VoteIf you add a new column to a table using an ALTER TABLE ADD command and specify that the new column allows NULLs and you do not define a default value, then it will take a table lock. However, once it gets the table lock, it will essentially run instantly
and then free the table lock. That will add this new column as the last column in the table, for example
ALTER MyTable ADD MyNewColumn bigint NULL;
But if you your change adds a new column with a default value, or you do something like using table designer to add the new column in the middle of the current list of columns, then SQL will have to rewrite the table. So it will get a table lock, rewrite
the whole table and then free the table lock. That will take a considerable amount of time and the table lock will be held for that whole period of time.
But, no matter how you make the change, if at all possible, I would not alter a table schema on a production database during working hours. Do it when nothing else is going on.
Tom -
Can i search multiple sheets in a document for text in column a to return the entire row if column a matches in a
separate sheet?Thank you, Barry. That was helpful, and am hopeful that what I want to do is possible.
I am creating a spreadsheet that currently has 20 sheets, of which certain sheets have more than one table. I will be adding more sheets. I would like to return results for all occurences of the search string. Preferably into a seperate spreadsheet. It would be perfect if that seperate sheet updated whenever I update information in the first spreadsheet. To give an example:
Sheet: baskets
Tables: straw
wire
Sheet: barware
Tables: glasses
decanters
coasters
My tables all have the same titiels:
Vendor Description Cost Selling Price
Since I will have upwards of 100 sheets, with multiple tables, and most of my vendors will fit into multiple sheet categories, it would be helpful if I could also see what my order will be from each vendor, not just who I will be ordering each item from. How would I do that?
I hope I conveyed that properly.
Thank you in advance for your help,
Rana -
Composite Studio - return row number column
Hi, I’m trying to include a row number column in my result set in Composite Studio (SQL Scratchpad), however I’m getting various error messages such as the below. Is there any way to add a row number?
An internal error has occurred.
Cause: analytical function ROW_NUMBER is not supported natively.
com.compositesw.cdms.webapi.WebapiException: An internal error has occurred.
Cause: analytical function ROW_NUMBER is not supported natively.
analytical function ROW_NUMBER is not supported natively.
at com.compositesw.cdms.webapi.PrefetchCursor$LoadPipeThread.run(PrefetchCursor.java:273)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Caused by: analytical function ROW_NUMBER is not supported natively.
at com.compositesw.server.qe.QueryResult.next(SourceFile:311)
at com.compositesw.cdms.webapi.PrefetchCursor$LoadPipeThread.run(PrefetchCursor.java:253)
... 3 more
Caused by: java.lang.IllegalArgumentException: analytical function ROW_NUMBER is not supported natively.
at com.compositesw.server.qe.physical.util.FunctionExecutor.initialize(SourceFile:232)
at com.compositesw.server.qe.physical.util.FunctionExecutor.next(SourceFile:379)
at com.compositesw.server.qe.physical.operator.FunctionNode.next(SourceFile:197)
at com.compositesw.server.qe.topology.SelectPTree.nextInternal(SourceFile:399)
at com.compositesw.server.qe.topology.SelectPTree.next(SourceFile:378)
at com.compositesw.server.qe.QueryResult.next(SourceFile:295)
... 4 more
at com.compositesw.cdms.webapi.WebapiException_SOAPSerializer.doDeserialize(WebapiException_SOAPSerializer.java:58)
at com.sun.xml.rpc.encoding.ObjectSerializerBase.deserialize(ObjectSerializerBase.java:209)
at com.sun.xml.rpc.encoding.ReferenceableSerializerImpl.deserialize(ReferenceableSerializerImpl.java:172)
at com.compositesw.cdms.webapi.service.WMetaDataSvc_dataset_fetch_Fault_SOAPSerializer.deserializeDetail(WMetaDataSvc_dataset_fetch_Fault_SOAPSerializer.java:54)
at com.sun.xml.rpc.encoding.SOAPFaultInfoSerializer.doDeserialize(SOAPFaultInfoSerializer.java:151)
at com.sun.xml.rpc.encoding.ObjectSerializerBase.deserialize(ObjectSerializerBase.java:209)
at com.sun.xml.rpc.encoding.ReferenceableSerializerImpl.deserialize(ReferenceableSerializerImpl.java:172)
at com.compositesw.cdms.webapi.service.WMetaDataSvc_Stub._readBodyFaultElement(WMetaDataSvc_Stub.java:23530)
at com.sun.xml.rpc.client.StreamingSender._send(StreamingSender.java:238)
at com.compositesw.cdms.webapi.service.WMetaDataSvc_Stub.dataset_fetch(WMetaDataSvc_Stub.java:14247)
at com.compositesw.cdms.webapi.WDataset$FetcherThread.run(WDataset.java:273)
Version Information: Studio 6.2.5.00.32 (hotfix), Build ID 131217-101258-0800-72550, Server 6.2.5.00.32 (hotfix)Hi Tom,
I think you intended your question for the other DV community here: https://supportforums.cisco.com/community/12298251/cisco-data-virtualization
Although our parser allows the syntax of these analytic functions such as ROW_NUMBER to be submitted to us from a client, our query engine is not capable of processing it locally.
It is up to the user to ensure the resulting query plan will push the sql containing that function down to the external db (ie; oracle) to be processed there instead. Creating the query from inside a view will provide the ability to see the resulting query plan.
Which customer (company) are you with? If you need further assistance, I recommend you log a support case with Cisco.
Thank you,
Brad -
JTable about selection mode, setting a Color to rows and column.
I need an application with a table containing Double and String data. When the table is shown the Double data must be shown as selected. I need a special kind of selection mode similar to MULTIPLE_INTERVAL_SELECTION but it must be a mode as if CONTROL was pressed when the user left clicks the table so he or she can select and deselect columns without deselecting those wich have been selected previously... Besides I need to paint columns and rows only if they have certain conditions. This is an example of what I have done so far... The selection mode is what is really important.
UsingJTable.java
package mytables;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.TableColumn;
public class UsingJTable extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel panel = null;
private JTable table = null;
private JButton[] buttonArray = null;
private JPanel buttonsPanel = null;
public UsingJTable() {
panel = new JPanel();
table = new JTable( new MyOwnTableModel() );
JScrollPane sPane = new JScrollPane( table );
sPane.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
sPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED );
panel.setOpaque( true );
panel.add( sPane );
buttonsPanel = new JPanel();
buttonsPanel.setLayout( new FlowLayout() );
buttonArray = new JButton[ 5 ];
for( int i = 0; i < buttonArray.length; i++ ) {
buttonArray[ i ] = new JButton( "columna " + i );
buttonArray[ i ].addActionListener( new ColumnListener( i ) );
buttonsPanel.add( buttonArray[ i ] );
table.setRowSelectionAllowed( false );
table.setColumnSelectionAllowed( true );
ListSelectionModel csm = table.getColumnModel().getSelectionModel();
csm.setSelectionInterval( 0, table.getColumnCount() );
csm.removeSelectionInterval( 0, table.getColumnCount() - 3 );
csm.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
this.setTitle( "Using JTable" );
this.getContentPane().add( panel );
this.getContentPane().add( buttonsPanel, BorderLayout.SOUTH );
this.setSize( 500, 500);
this.setVisible( true );
this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
class ColumnListener implements ActionListener {
private boolean pressed = false;
private int column = 0;
public ColumnListener( int col) {
this.setColumn( col );
public void actionPerformed(ActionEvent e) {
TableColumn tColumn = table.getColumnModel().getColumn( column );
Color c;
if ( !pressed )
c = Color.YELLOW;
else
c = Color.WHITE;
table.setVisible( false );
tColumn.setCellRenderer( new MyCellRenderer( c ) );
table.setVisible( true );
pressed = !pressed;
public int getColumn() {
return column;
public void setColumn(int column) {
this.column = column;
public static void main( String args[] )
new UsingJTable();
} MyOwnTableModel.java
package mytables;
import javax.swing.table.AbstractTableModel;
public class MyOwnTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private Object data[][] = null;
private String columnNames[] = null;
private int rowCount = 0;
private int columnCount = 0;
public MyOwnTableModel() {
initData();
initColumnNames();
this.setRowCount( data.length );
this.setColumnCount( columnNames.length );
public int getColumnCount() {
return columnCount;
public int getRowCount() {
return rowCount;
public Object getValueAt(int r, int c) {
return data[ r ][ c ];
private void initData() {
data = new Object[4][5];
data[ 0 ][ 0 ] = new String("Hern�n");
data[ 0 ][ 1 ] = new String("Amaya");
data[ 0 ][ 2 ] = new Integer( 23 );
data[ 0 ][ 3 ] = new Double( 61.5 );
data[ 0 ][ 4 ] = new Double( 1.71 );
data[ 1 ][ 0 ] = new String("Mariana");
data[ 1 ][ 1 ] = new String("Amaya");
data[ 1 ][ 2 ] = new Integer( 25 );
data[ 2 ][ 3 ] = new Double( 75 );
data[ 2 ][ 4 ] = new Double( 1.65 );
data[ 2 ][ 0 ] = new String("Nicol�s");
data[ 2 ][ 1 ] = new String("Coniglio");
data[ 2 ][ 2 ] = new Integer( 23 );
data[ 2 ][ 3 ] = new Double( 88.5 );
data[ 2 ][ 4 ] = new Double( 7.85 );
data[ 3 ][ 0 ] = new String("Juan Pablo");
data[ 3 ][ 1 ] = new String("Garribia");
data[ 3 ][ 2 ] = new Integer( 24 );
data[ 3 ][ 3 ] = new Double( 70.2 );
data[ 3 ][ 4 ] = new Double( 1.76 );
private void initColumnNames() {
columnNames = new String[ 5 ];
columnNames[ 0 ] = "Nombre";
columnNames[ 1 ] = "Apellido";
columnNames[ 2 ] = "Edad";
columnNames[ 3 ] = "Peso";
columnNames[ 4 ] = "Altura";
public String[] getColumnNames() {
return columnNames;
public void setColumnNames(String[] columnNames) {
this.columnNames = columnNames;
public Object[][] getData() {
return data;
public void setData(Object[][] data) {
this.data = data;
public void setColumnCount(int columnCount) {
this.columnCount = columnCount;
public void setRowCount(int rowCount) {
this.rowCount = rowCount;
public Class getColumnClass(int c) {
return data[0][c].getClass();
public String getColumnName(int c) {
return columnNames[ c ];
} MycellRenderer.java
package mytables;
import java.awt.Color;
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
public class MyCellRenderer extends DefaultTableCellRenderer {
private static final long serialVersionUID = 1L;
private Color cellColor = null;
public MyCellRenderer( Color c )
setCellColor( c );
public Component getTableCellRendererComponent
(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
// Obtains default cell settings
Component cell = super.getTableCellRendererComponent ( table, value, isSelected, hasFocus, row, column);
cell.setBackground( getCellColor());
return cell;
public Color getCellColor() {
return cellColor;
public void setCellColor(Color cellColor) {
this.cellColor = cellColor;
}Interesting concept! This is what I have tried and it works, but in the application I need the user to deselect the columns he wants only by left clicking on them... This is the main idea: there will be lots of columns (String and Double data). The user must deselect the Double columns he or she does not want to be processed... Maybe with a boolean array that changes it state if a user left clicks a column... but I suppose this method is called only once to initialize the table, isn't it? Thanks.
<code>
table = new JTable( new MyOwnTableModel() ) {
public boolean isCellSelected(int row, int column) {
MyOwnTableModel model = (MyOwnTableModel) this.getModel();
if( model.getColumnClass( column ) == Double.class )
return true;
return false;
</code> -
JTable fixed Row and Column in the same window
Hi
Could anyone tip me how to make fixed row and column in the same table(s).
I know how to make column fixed and row, tried to combine them but it didnt look pretty.
Can anyone give me a tip?
Thanks! :)Got it to work!
heres the kod.. nothing beautiful, didnt clean it up.
* NewClass.java
* Created on den 29 november 2007, 12:51
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
package tablevectortest;
* @author Sockan
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
public class FixedRowCol extends JFrame {
Object[][] data;
Object[] column;
JTable fixedTable,table,fixedColTable,fixedTopmodelTable;
private int FIXED_NUM = 16;
public FixedRowCol() {
super( "Fixed Row Example" );
data = new Object[][]{
{ "","A","A","A","",""},
{ "a","b","","","",""},
{ "a","","c","","",""},
{ "","","","d","",""},
{ "","","","","e",""},
{ "","","","","","f"},
{ "","b","","","",""},
{ "","","c","","",""},
{ "","","","d","",""},
{ "","","","","e",""},
{ "","b","","","",""},
{ "","","c","","",""},
{ "","","","d","",""},
{ "","","","","e",""},
{ "","","","","","f"},
{ "I","","W","G","A",""}};
column = new Object[]{"A","B","C","D","E","F"};
AbstractTableModel fixedColModel = new AbstractTableModel() {
public int getColumnCount() {
return 1;
public int getRowCount() {
return data.length;
public String getColumnName(int col) {
return (String) column[col];
public Object getValueAt(int row, int col) {
return data[row][col];
public boolean CellEditable(int row, int col) {
return true;
AbstractTableModel model = new AbstractTableModel() {
public int getColumnCount() { return column.length-2; }
public int getRowCount() { return data.length - FIXED_NUM; }
public String getColumnName(int col) {
return (String)column[col+1];
public Object getValueAt(int row, int col) {
return data[row][col+1];
public void setValueAt(Object obj, int row, int col) {
data[row][col+1] = obj;
public boolean CellEditable(int row, int col) {
return true;
AbstractTableModel fixedTopModel = new AbstractTableModel() {
public int getColumnCount() { return 1; }
public int getRowCount() { return data.length - FIXED_NUM; }
public String getColumnName(int col) {
return (String)column[col];
public Object getValueAt(int row, int col) {
return data[row][col];
public void setValueAt(Object obj, int row, int col) {
data[row][col] = obj;
public boolean CellEditable(int row, int col) {
return true;
AbstractTableModel fixedModel = new AbstractTableModel() {
public int getColumnCount() { return column.length-2; }
public int getRowCount() { return FIXED_NUM; }
public Object getValueAt(int row, int col) {
return data[row + (data.length - FIXED_NUM)][col+1];
table = new JTable( model );
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
fixedTable = new JTable( fixedModel );
fixedTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
fixedTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
fixedColTable= new JTable(fixedColModel);
fixedColTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
fixedColTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
fixedTopmodelTable = new JTable(fixedTopModel);
fixedTopmodelTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
fixedTopmodelTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll = new JScrollPane( table );
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JScrollPane fixedScroll = new JScrollPane( fixedTable ) {
public void setColumnHeaderView(Component view) {}
fixedScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
fixedScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
JScrollBar bar = scroll.getVerticalScrollBar();
JScrollBar dummyBar = new JScrollBar() {
public void paint(Graphics g) {}
dummyBar.setPreferredSize(bar.getPreferredSize());
scroll.setVerticalScrollBar(dummyBar);
final JScrollBar bar1 = scroll.getHorizontalScrollBar();
JScrollBar bar2 = fixedScroll.getHorizontalScrollBar();
bar2.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
bar1.setValue(e.getValue());
JViewport viewport = new JViewport();
viewport.setView(fixedColTable);
viewport.setPreferredSize(fixedColTable.getPreferredSize());
fixedScroll.setRowHeaderView(viewport);
fixedScroll.setCorner(JScrollPane.UPPER_LEFT_CORNER, fixedColTable
.getTableHeader());
JViewport viewport2 = new JViewport();
viewport2.setView(fixedTopmodelTable);
viewport2.setPreferredSize(fixedTopmodelTable.getPreferredSize());
scroll.setRowHeaderView(viewport2);
scroll.setCorner(JScrollPane.UPPER_LEFT_CORNER, fixedTopmodelTable
.getTableHeader());
scroll.setPreferredSize(new Dimension(600, 19));
fixedScroll.setPreferredSize(new Dimension(600, 100));
getContentPane().add( scroll, BorderLayout.NORTH);
getContentPane().add(fixedScroll, BorderLayout.CENTER);
public static void main(String[] args) {
FixedRowCol frame = new FixedRowCol();
frame.addWindowListener( new WindowAdapter() {
public void windowClosing( WindowEvent e ) {
System.exit(0);
frame.pack();
frame.setVisible(true);
} -
How do I select the end of a row or column in Numbers?
I am trying to select to the end of a column in Numbers. In Excel, I simply hold down the shift+command+arrow keys and I can select the entire row or column int he arrow direction. How do I do this in Numbers?
Here two other scripts :
Select-to-top and select-to-left.
Both of them take care of possible headers.
--{code}
--[SCRIPT select-to-top]
Enregistrer le script en tant que Script : select-to-top.scpt
déplacer le fichier ainsi créé dans le dossier
<VolumeDeDémarrage>:Utilisateurs:<votreCompte>:Bibliothèque:Scripts:Applications :Numbers:
Il vous faudra peut-être créer le dossier Numbers et peut-être même le dossier Applications.
Sélectionner une ou plusieurs cellules d'une ligne dans une table de Numbers
Aller au menu Scripts , choisir Numbers puis choisir “select-to-top”
Il étendra la sélection jusqu'à la première ligne standard de la colonne (ne sélectionne pas les rangs d’en tête).
Bien entendu, ce script sera plus intéressant si vous le dotez d'un raccourci clavier à l’aide, par exemple, de FastScripts.
--=====
L’aide du Finder explique:
L’Utilitaire AppleScript permet d’activer le Menu des scripts :
Ouvrez l’Utilitaire AppleScript situé dans le dossier Applications/AppleScript.
Cochez la case “Afficher le menu des scripts dans la barre de menus”.
Sous 10.6.x,
aller dans le panneau “Général” du dialogue Préférences de l’Éditeur Applescript
puis cocher la case “Afficher le menu des scripts dans la barre des menus”.
--=====
Save the script as a Script: select-to-top.scpt
Move the newly created file into the folder:
<startup Volume>:Users:<yourAccount>:Library:Scripts:Applications:Numbers:
Maybe you would have to create the folder Numbers and even the folder Applications by yourself.
Select one or several cells in a row of a Numbers table.
Go to the Scripts Menu, choose Numbers, then choose “select-to-top”
It will expand the selection to the first standard row of the table (minus header rows).
Of course, it would be more useful if you attach a shortcut thanks to a tool like FastScripts.
--=====
The Finder’s Help explains:
To make the Script menu appear:
Open the AppleScript utility located in Applications/AppleScript.
Select the “Show Script Menu in menu bar” checkbox.
Under 10.6.x,
go to the General panel of AppleScript Editor’s Preferences dialog box
and check the “Show Script menu in menu bar” option.
--=====
Yvan KOENIG (VALLAURIS, France)
2012/02/09
--=====
on run
my activateGUIscripting()
set {dName, sName, tName, rowNum1, colNum1, rowNum2, colNum2} to my get_SelParams()
tell application "Numbers" to tell document dName to tell sheet sName to tell table tName
set count_HeaderRows to my countXers("Numbers", "R")
set selection range to range ((name of cell (1 + count_HeaderRows) of column colNum1) & " : " & (name of cell rowNum1 of column colNum2))
end tell
end run
--=====
set { dName, sName, tName, rowNum1, colNum1, rowNum2, colNum2} to my get_SelParams()
tell application "Numbers" to tell document dName to tell sheet sName to tell table tName
on get_SelParams()
local d_Name, s_Name, t_Name, row_Num1, col_Num1, row_Num2, col_Num2
tell application "Numbers" to tell document 1
set d_Name to its name
set s_Name to ""
repeat with i from 1 to the count of sheets
tell sheet i to set maybe to the count of (tables whose selection range is not missing value)
if maybe is not 0 then
set s_Name to name of sheet i
exit repeat
end if -- maybe is not 0
end repeat
if s_Name is "" then
if my parleAnglais() then
error "No sheet has a selected table embedding at least one selected cell !"
else
error "Aucune feuille ne contient une table ayant au moins une cellule sélectionnée !"
end if
end if
tell sheet s_Name to tell (first table where selection range is not missing value)
tell selection range
set {top_left, bottom_right} to {name of first cell, name of last cell}
end tell
set t_Name to its name
tell cell top_left to set {row_Num1, col_Num1} to {address of its row, address of its column}
if top_left is bottom_right then
set {row_Num2, col_Num2} to {row_Num1, col_Num1}
else
tell cell bottom_right to set {row_Num2, col_Num2} to {address of its row, address of its column}
end if
end tell -- sheet…
return {d_Name, s_Name, t_Name, row_Num1, col_Num1, row_Num2, col_Num2}
end tell -- Numbers
end get_SelParams
--=====
on parleAnglais()
local z
try
tell application "Numbers" to set z to localized string "Cancel"
on error
set z to "Cancel"
end try
return (z is not "Annuler")
end parleAnglais
--=====
on activateGUIscripting()
(* to be sure than GUI scripting will be active *)
tell application "System Events"
if not (UI elements enabled) then set (UI elements enabled) to true
end tell
end activateGUIscripting
--=====
set count_Row_Headers to my countXers("Numbers","R")
set count_Column_Headers to my countXers("Numbers","C")
set count_Footers to my countXers("Numbers","F")
set count_Row_Headers to my countXers("Pages","R")
set count_Column_Headers to my countXers("Pages","C")
set count_Footers to my countXers("Pages","F")
on countXers(theApp, what)
local mt, mi, mm, ms
if theApp is "Numbers" then
set mt to 6 (* Table *)
if "Row" starts with what then
set mi to 10
else if "Column" starts with what then
set mi to 11
else if "Footer" starts with what then
set mi to 14
else
if my parleAnglais() then
error "“" & what & "” isn’t a valid parameter !"
else
error "« " & what & " » n’est pas un paramètre géré !"
end if -- parleAnglais
end if -- "Row"…
else if theApp is "Pages" then
set {mt, mi} to {6, 4} (* Format, Table *)
if "Row" starts with what then
set mm to 13
else if "Column" starts with what then
set mm to 14
else if "Footer" starts with what then
set mm to 15
else
if my parleAnglais() then
error "“" & what & "” isn’t a valid parameter !"
else
error "« " & what & " » n’est pas un paramètre géré !"
end if -- parleAnglais
end if -- "Row"…
else
if my parleAnglais() then
error "The application “" & theApp & "” isn’t driven by this script !"
else
error "L’application « " & theApp & " » n’est pas gérée par ce script !"
end if -- parleAnglais
end if -- theApp…
activate application theApp
tell application "System Events" to tell process theApp to tell menu bar 1 to tell menu bar item mt to tell menu 1 to tell menu item mi to tell menu 1
if theApp is "Numbers" then
Here we are in Numbers *)
repeat with ms from 1 to 6
try
(get value of attribute "AXMenuItemMarkChar" of menu item ms) = "✓"
exit repeat
end try
end repeat
else
Here we are in Pages *)
tell menu item mm to tell menu 1
repeat with ms from 1 to 6
try
(get value of attribute "AXMenuItemMarkChar" of menu item ms) = "✓"
exit repeat
end try
end repeat
end tell -- menu item mm
end if -- theApp is …
end tell -- System Events…
return ms - 1
end countXers
--=====
--[/SCRIPT]
--{code}
--{code}
--[SCRIPT select-to-left]
Enregistrer le script en tant que Script : select-to-left.scpt
déplacer le fichier ainsi créé dans le dossier
<VolumeDeDémarrage>:Utilisateurs:<votreCompte>:Bibliothèque:Scripts:Applications :Numbers:
Il vous faudra peut-être créer le dossier Numbers et peut-être même le dossier Applications.
Sélectionner une ou plusieurs cellules d'une colonne dans une table de Numbers
Aller au menu Scripts , choisir Numbers puis choisir “select-to-left”
Il étendra la sélection jusqu'à la première colonne standard de la table (ne sélectionne pas les colonnes d’en tête).
Bien entendu, ce script sera plus intéressant si vous le dotez d'un raccourci clavier à l’aide, par exemple, de FastScripts.
--=====
L’aide du Finder explique:
L’Utilitaire AppleScript permet d’activer le Menu des scripts :
Ouvrez l’Utilitaire AppleScript situé dans le dossier Applications/AppleScript.
Cochez la case “Afficher le menu des scripts dans la barre de menus”.
Sous 10.6.x,
aller dans le panneau “Général” du dialogue Préférences de l’Éditeur Applescript
puis cocher la case “Afficher le menu des scripts dans la barre des menus”.
--=====
Save the script as a Script: select-to-left.scpt
Move the newly created file into the folder:
<startup Volume>:Users:<yourAccount>:Library:Scripts:Applications:Numbers:
Maybe you would have to create the folder Numbers and even the folder Applications by yourself.
Select one or several cells in a column of a Numbers table.
Go to the Scripts Menu, choose Numbers, then choose “select-to-left”
It will expand the selection to the first standard colomn of the table (minus fheader columns).
Of course, it would be more useful if you attach a shortcut thanks to a tool like FastScripts.
--=====
The Finder’s Help explains:
To make the Script menu appear:
Open the AppleScript utility located in Applications/AppleScript.
Select the “Show Script Menu in menu bar” checkbox.
Under 10.6.x,
go to the General panel of AppleScript Editor’s Preferences dialog box
and check the “Show Script menu in menu bar” option.
--=====
Yvan KOENIG (VALLAURIS, France)
2012/02/09
--=====
on run
my activateGUIscripting()
set {dName, sName, tName, rowNum1, colNum1, rowNum2, colNum2} to my get_SelParams()
tell application "Numbers" to tell document dName to tell sheet sName to tell table tName
set count_ColHeaders to my countXers("Numbers", "C")
set selection range to range ((name of cell (1 + count_ColHeaders) of row rowNum1) & " : " & (name of cell colNum1 of row rowNum2))
end tell
end run
--=====
set { dName, sName, tName, rowNum1, colNum1, rowNum2, colNum2} to my get_SelParams()
tell application "Numbers" to tell document dName to tell sheet sName to tell table tName
on get_SelParams()
local d_Name, s_Name, t_Name, row_Num1, col_Num1, row_Num2, col_Num2
tell application "Numbers" to tell document 1
set d_Name to its name
set s_Name to ""
repeat with i from 1 to the count of sheets
tell sheet i to set maybe to the count of (tables whose selection range is not missing value)
if maybe is not 0 then
set s_Name to name of sheet i
exit repeat
end if -- maybe is not 0
end repeat
if s_Name is "" then
if my parleAnglais() then
error "No sheet has a selected table embedding at least one selected cell !"
else
error "Aucune feuille ne contient une table ayant au moins une cellule sélectionnée !"
end if
end if
tell sheet s_Name to tell (first table where selection range is not missing value)
tell selection range
set {top_left, left_right} to {name of first cell, name of last cell}
end tell
set t_Name to its name
tell cell top_left to set {row_Num1, col_Num1} to {address of its row, address of its column}
if top_left is left_right then
set {row_Num2, col_Num2} to {row_Num1, col_Num1}
else
tell cell left_right to set {row_Num2, col_Num2} to {address of its row, address of its column}
end if
end tell -- sheet…
return {d_Name, s_Name, t_Name, row_Num1, col_Num1, row_Num2, col_Num2}
end tell -- Numbers
end get_SelParams
--=====
on parleAnglais()
local z
try
tell application "Numbers" to set z to localized string "Cancel"
on error
set z to "Cancel"
end try
return (z is not "Annuler")
end parleAnglais
--=====
on activateGUIscripting()
(* to be sure than GUI scripting will be active *)
tell application "System Events"
if not (UI elements enabled -
Problem in Row and column.
Hi all,
This is the output for this snippet.
one Two ---> Column header
A B -->Row datas.
C D
E F
I am missing "G" in the above table.
What should i to get the output like this?
one Two ---> Column header
A B -->Row datas.
C D
E F
G
File: DataFileTable .java
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.util.*;
public class DataFileTable extends JPanel {
public DataFileTable() {
JTable table;
DataFileTableModel model;
Font f;
f = new Font("SanSerif",Font.PLAIN,24);
setFont(f);
setLayout(new BorderLayout());
model = new DataFileTableModel();
table = new JTable();
table.setModel(model);
table.createDefaultColumnsFromModel();
JScrollPane scrollpane = new JScrollPane(table);
add(scrollpane);
public Dimension getPreferredSize(){
return new Dimension(400, 300);
public static void main(String s[]) {
JFrame frame = new JFrame("Data File Table");
DataFileTable panel;
panel = new DataFileTable();
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setForeground(Color.black);
frame.setBackground(Color.lightGray);
frame.getContentPane().add(panel,"Center");
frame.setSize(panel.getPreferredSize());
frame.setVisible(true);
frame.addWindowListener(new WindowCloser());
class WindowCloser extends WindowAdapter {
public void windowClosing(WindowEvent e) {
Window win = e.getWindow();
win.setVisible(false);
System.exit(0);
File:DataFileTableModel.java
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.io.*;
import java.util.*;
public class DataFileTableModel extends AbstractTableModel {
protected Vector data;
protected Vector columnNames ;
public DataFileTableModel(){
initVectors();
public void initVectors() {
String aLine ;
data = new Vector();
columnNames = new Vector();
columnNames.addElement("one");
columnNames.addElement("two");
data.addElement("A");
data.addElement("B");
data.addElement("C");
data.addElement("D");
data.addElement("E");
data.addElement("F");
data.addElement("G");
public int getRowCount() {
return data.size() / getColumnCount();
public int getColumnCount(){
return columnNames.size();
public String getColumnName(int columnIndex) {
String colName = "";
if (columnIndex <= getColumnCount())
colName = (String)columnNames.elementAt(columnIndex);
return colName;
public Class getColumnClass(int columnIndex){
return String.class;
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
public Object getValueAt(int rowIndex, int columnIndex) {
return (String)data.elementAt( (rowIndex * getColumnCount()) + columnIndex);
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
return;
}Here I would guess your problem is with
public Object getValueAt(int rowIndex, int columnIndex) {
return (String)data.elementAt( (rowIndex * getColumnCount()) + columnIndex);
}Even though you only have seven items in your data Vector, the table will
still try to populate all the cells in the number of rows you have. So, you
need to check if the index is greater than the Vector size and return an
empty string in that case. Something like
public Object getValueAt(int rowIndex, int columnIndex) {
int index = rowIndex * getColumnCount() + columnIndex;
return index < data.size() ? data.elementAt( index ) : "";
} -
Summing the Rows and Columns in an Array
I am importing a 2-dimensional array of integers.(which is held in a 2-dimensional array)
I need to store the row sums and column sums in separate 1-dimensional arrays.
I can get the integers in and print out a list along with the grand total(sum of all).
But, how do I pass each row's and each column's value in to my sumRow and sumCol methods to get the sum for each row and each column?
Can I do the row and column summing in the same "for" statement where I calculate the "grand total"? Or am I making this more difficult than it is?
Would appreciate any help.
This is what I have so far:
import java.awt.Graphics;
import java.applet.Applet;
public class TwoWayTable extends Applet {
int numRows;
int numCols;
int [] [] cell;
int [] rowSum;
int [] colSum;
int grandTotal;
public TwoWayTable(int [][] data){
grandTotal = 0;
cell = new int [data.length][data.length];
for(int i = 0; i < data.length; i++)
for(int j = 0; j < data.length; j++){
cell[i][j] = data[i][j];
grandTotal += cell[i][j];
System.out.println(cell[i][j]);
System.out.println(grandTotal);
public int sumRow(int [] data2){
int rowaccumulator=0;
rowSum = new int[data2.length];
for(int numRows = 0; numRows < rowSum.length; numRows++){
rowaccumulator += rowaccumulator + rowSum[numRows];
return(rowaccumulator);
public int sumCol(int [] data3){
int colaccumulator = 0;
colSum = new int[data3.length];
for(int numCols = 0; numCols < colSum.length; numCols++){
colaccumulator += colaccumulator + colSum[numCols];
return(colaccumulator);Thanks for your input.
I'll make the changes that you suggest.(after this)
My output prints:
4 6 3 8 21
9 1 5 3 18
13 7 8 11 39
numbers are right, but I need to format the table
the output needs to look like this:
int int int int | rowsum
int int int int | rowsum
colsum colsum colsum colsum | total
How do I do this?
I have no idea?
I'm supposed to call a "void setMargins( )" method to line this up, without
using the exotic formatting in the IO library.
I'm also supposed to use "public String toString( )"
This is what I have so far:
import java.awt.Graphics;
import java.applet.Applet;
public class TwoWayTable extends Applet {
int numRows;
int numCols;
int [] [] cell;
int [] rowSum;
int [] colSum;
int grandTotal;
public TwoWayTable(int [][] data){
cell = new int [data.length][data.length];
for(int i = 0; i < data.length; i++){
for(int j = 0; j < data.length; j++){
cell[i][j] = data[i][j];
calcTotals(cell);
for(int i = 0; i < cell.length; ++i){
for(int j = 0; j < cell.length; ++j){
System.out.print(cell[i][j] + " ");
System.out.println(rowSum[i] + " ");
for(int j = 0; j < cell.length-1; ++j){
System.out.print(colSum[j] + " ");
System.out.println(colSum[cell.length-1] + " " + (grandTotal));
public void calcTotals(int [][] data2){
grandTotal = 0;
rowSum = new int[data2.length];
colSum = new int[data2.length];
for(int numRows = 0; numRows < data2.length; numRows++){
for(int numCols = 0; numCols < data2.length; numCols++){
grandTotal += data2[numRows][numCols];
rowSum[numRows] += data2[numRows][numCols];
colSum[numCols] += data2[numRows][numCols]; -
Hi,
I have a file where fields are wrapped with ".
=========== file sample
"asdsa","asdsadasdas","1123"
"asdsa","asdsadasdas","1123"
"asdsa","asdsadasdas","1123"
"asdsa","asdsadasdas","1123"
==========
I am having a .net method to remove the wrap characters and write out a file without wrap characters.
======================
asdsa,asdsadasdas,1123
asdsa,asdsadasdas,1123
asdsa,asdsadasdas,1123
asdsa,asdsadasdas,1123
======================
the .net code is here.
========================================
public static string RemoveCharacter(string sFileName, char cRemoveChar)
object objLock = new object();
//VirtualStream objInputStream = null;
//VirtualStream objOutStream = null;
FileStream objInputFile = null, objOutFile = null;
lock(objLock)
try
objInputFile = new FileStream(sFileName, FileMode.Open);
//objInputStream = new VirtualStream(objInputFile);
objOutFile = new FileStream(sFileName.Substring(0, sFileName.LastIndexOf('\\')) + "\\" + Guid.NewGuid().ToString(), FileMode.Create);
//objOutStream = new VirtualStream(objOutFile);
int nByteRead;
while ((nByteRead = objInputFile.ReadByte()) != -1)
if (nByteRead != (int)cRemoveChar)
objOutFile.WriteByte((byte)nByteRead);
finally
objInputFile.Close();
objOutFile.Close();
return sFileName.Substring(0, sFileName.LastIndexOf('\\')) + "\\" + Guid.NewGuid().ToString();
==================================
however when I run the bulk load utility I get the error
=======================================
Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 3 (NumberOfMultipleMatches).
==========================================
the bulk insert statement is as follows
=========================================
BULK INSERT Temp
FROM '<file name>' WITH
FIELDTERMINATOR = ','
, KEEPNULLS
==========================================
Does anybody know what is happening and what needs to be done ?
PLEASE HELP
Thanks in advance
VikramTo load that file with BULK INSERT, use this format file:
9.0
4
1 SQLCHAR 0 0 "\"" 0 "" ""
2 SQLCHAR 0 0 "\",\"" 1 col1 Latin1_General_CI_AS
3 SQLCHAR 0 0 "\",\"" 2 col2 Latin1_General_CI_AS
4 SQLCHAR 0 0 "\"\r\n" 3 col3 Latin1_General_CI_AS
Note that the format file defines four fields while the fileonly seems to have three. The format file defines an empty field before the first quote.
Or, since you already have a .NET program, use a stored procedure with table-valued parameter instead. I have an example of how to do this here:
http://www.sommarskog.se/arrays-in-sql-2008.html
Erland Sommarskog, SQL Server MVP, [email protected] -
JTable Problem (table does not show rows and columns)
Hi All,
What the table is suppose to do.
- Load information from a database
- put all the values in the first column
- in the second column put combobox (cell editor with numbers 1-12)
- the 3rd column put another combobox for something else
- the 4th column uses checkbox as an edit
The number of rows of the table should be equal to the number of
record from
the database. If not given it default to 20 (poor but ok for this)
The number of columns is 4.
But the table does not show any rows or
column when I put it inside a
JScrollPane (Otherwise it works).
Please help,
thanks in advance.
public class SubjectTable extends JTable {
* Comment for <code>serialVersionUID</code>
private static final long serialVersionUID = 1L;
/** combo for the list of classes */
protected JComboBox classCombo;
/** combo for the list of subjects */
protected JComboBox subjectsCombo;
/** combo for the list of grade */
protected JComboBox gradeCombo;
boolean canResize = false;
boolean canReorder = false;
boolean canSelectRow = false;
boolean canSelectCell = true;
boolean canSelectColumn = true;
// the row height of the table
int rowHeight = 22;
// the height of the table
int height = 200;
// the width of the table
int width = 300;
// the size of the table
Dimension size;
* Parameterless constructor. Class the one of the other constructors
to
* create a table with the a new <code>SubjectTableModel</code>.
public SubjectTable() {
this(new SubjectTableModel());
* Copy constructor to create the table with the given
* <code>SubjectTableModel</code>
* @param tableModel -
* the <code>SubjectTableModel</code> with which to
initialise
* the table.
SubjectTable(SubjectTableModel tableModel) {
setModel(tableModel);
setupTable();
* Function to setup the table's functionality
private void setupTable() {
clear();
// set the row hieght
this.setRowHeight(this.rowHeight);
// set the font size to 12
//TODO this.setFont(Settings.getDefaultFont());
// disble reordering of columns
this.getTableHeader().setReorderingAllowed(this.canReorder);
// disble resing of columns
this.getTableHeader().setResizingAllowed(this.canResize);
// enable the horizontal scrollbar
this.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
// disable row selection
setRowSelectionAllowed(this.canSelectRow);
// disable column selection
setColumnSelectionAllowed(this.canSelectColumn);
// enable cell selection
setCellSelectionEnabled(this.canSelectCell);
setPreferredScrollableViewportSize(getSize());
TableColumn columns = null;
int cols = getColumnCount();
for (int col = 0; col < cols; col++) {
columns = getColumnModel().getColumn(col);
switch (col) {
case 0:// subject name column
columns.setPreferredWidth(130);
break;
case 1:// grade column
columns.setPreferredWidth(60);
break;
case 2:// class room column
columns.setPreferredWidth(120);
break;
case 3:// select column
columns.setPreferredWidth(65);
break;
} // end switch
}// end for
// set up the cell editors
doGradeColumn();
doClassColumn();
//doSubjectColumn();
* Function to clear the table selection. This selection is different
to
* <code>javax.swing.JTable#clearSelection()</code>. It clears the
user
* input
public void clear() {
for (int row = 0; row < getRowCount(); row++) {
for (int col = 0; col < getColumnCount(); col++) {
if (getColumnName(getColumnCount() - 1).equals("Select")) {
setValueAt(new Boolean(false), row, getColumnCount() - 1);
}// if
}// for col
}// for row
* Function to set the cell renderer for the subjects column. It uses
a
* combobox as a cell editor in the teacher's subjects table.
public void doSubjectColumn() {
TableColumn nameColumn = getColumnModel().getColumn(0);
nameColumn.setCellEditor(new DefaultCellEditor(getSubjectsCombo()));
// set up the celll renderer
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for drop down list");
nameColumn.setCellRenderer(renderer);
// Set up tool tip for the sport column header.
TableCellRenderer headerRenderer = nameColumn.getHeaderRenderer();
if (headerRenderer instanceof DefaultTableCellRenderer) {
((DefaultTableCellRenderer) headerRenderer)
.setToolTipText("Click the Name to see a list of choices");
}// end doSubjectsColumn----------------------------------------------
/** Function to set up the grade combo box. */
public void doGradeColumn() {
TableColumn gradeColumn = getColumnModel().getColumn(1);
gradeColumn.setCellEditor(new DefaultCellEditor(getGradeCombo()));
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for drop down list");
gradeColumn.setCellRenderer(renderer);
// Set up tool tip for the sport column header.
TableCellRenderer headerRenderer = gradeColumn.getHeaderRenderer();
if (headerRenderer instanceof DefaultTableCellRenderer) {
((DefaultTableCellRenderer) headerRenderer)
.setToolTipText("Click the Grade to see a list of choices");
}// end doGradeColumn-------------------------------------------------
* Function to setup the Class room Column of the subjects
public void doClassColumn() {
// set the column for the classroom
TableColumn classColumn = getColumnModel().getColumn(2);
classColumn.setCellEditor(new DefaultCellEditor(getClassCombo()));
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for drop down list");
classColumn.setCellRenderer(renderer);
// Set up tool tip for the sport column header.
TableCellRenderer headerRenderer = classColumn.getHeaderRenderer();
if (headerRenderer instanceof DefaultTableCellRenderer) {
((DefaultTableCellRenderer) headerRenderer)
.setToolTipText("Click the Class to see a list of choices");
}// end doClassColumn--------------------------------------------------
* Function to get the size of the table
* @return Returns the size.
public Dimension getSize() {
if (this.size == null) {
this.size = new Dimension(this.height, this.width);
return this.size;
* Function to set the size of the table
* @param dim
* The size to set.
public void setSize(Dimension dim) {
if (dim != null) {
this.size = dim;
return;
* Function to create/setup the class room comboBox. If the comboBox
is
* <code>null</code> a nwew one is created else the functon returns
the
* function that was returned initially.
* @return Returns the classCombo.
private JComboBox getClassCombo() {
if (this.classCombo == null) {
this.classCombo = new JComboBox();
// fill up the class name combo
ArrayList classRooms = new ArrayList();
try {
//TODO classRooms = Settings.getDatabase().getClassRooms();
for (int i = 0; i < 10; i++) {
String string = new String("Class");
string += i;
if (!classRooms.isEmpty()) {
classRooms.trimToSize();
for (int i = 0; i < classRooms.size(); i++) {
this.classCombo.addItem(classRooms.get(i));
} catch (Exception e) {
e.printStackTrace();
return this.classCombo;
* Function to create/setup the subjects comboBox. If the comboBox is
* <code>null</code> a nwew one is created else the functon returns
the
* function that was returned initially.
* @return Returns the subjectsCombo.
private JComboBox getSubjectsCombo() {
if (this.subjectsCombo == null) {
this.subjectsCombo = new JComboBox();
try {
ArrayList subjects = loadSubjectsFromDatabase();
if (!subjects.isEmpty()) {
Iterator iterator = subjects.iterator();
while (iterator.hasNext()) {
// create a new subject instance
//TODO Subject subct = new Subject();
// typecast to subject
//TODO subct = (Subject) iterator.next();
String name = (String) iterator.next();
// add this subject to the comboBox
//TODO this.subjectsCombo.addItem(subct.getName());
subjectsCombo.addItem(name);
}// end while
}// end if
else {
JOptionPane.showMessageDialog(SubjectTable.this,
"Subjects List Could Not Be Filled");
System.out.println("Subjects List Could Not Be Filled");
} catch (Exception e) {
e.printStackTrace();
return this.subjectsCombo;
* Function to load subjects from the <code>Database</code>
* @return Returns the subjects.
private ArrayList loadSubjectsFromDatabase() {
// list of all the subject that the school does
ArrayList subjects = new ArrayList();
try {
//TODO to be removed later on
for (int i = 0; i < 10; i++) {
String string = new String("Subject");
string += i;
subjects.add(i, string);
// set the school subjects
//TODO subjects = Settings.getDatabase().loadAllSubjects();
} catch (Exception e1) {
e1.printStackTrace();
return subjects;
* Function to create/setup the grade comboBox. If the comboBox is
* <code>null</code> a nwew one is created else the functon returns
the
* function that was returned initially.
* @return Returns the gradeCombo.
private JComboBox getGradeCombo() {
if (this.gradeCombo == null) {
this.gradeCombo = new JComboBox();
// fill with grade 1 to 12
for (int i = 12; i > 0; i--) {
this.gradeCombo.addItem(new Integer(i).toString());
return this.gradeCombo;
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(new Plastic3DLookAndFeel());
System.out.println("Look and Feel has been set");
} catch (UnsupportedLookAndFeelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
SubjectTableModel model = new SubjectTableModel();
int cols = model.getColumnCount();
int rows = model.getRowCount();
Object[][] subjects = new Object[rows][cols];
for (int row = 0; row < rows; row++) {
subjects[row][0] = new String("Subjectv ") + row;
}//for
model.setSubjectsList(subjects);
SubjectTable ttest = new SubjectTable(model);
JFrame frame = new JFrame("::Table Example");
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(ttest);
frame.getContentPane().add(scrollPane);
frame.pack();
frame.setVisible(true);
**************************************END
TABLE******************************
----------------------------THE TABLE
MODEL----------------------------------
* Created on 2005/03/21
* SubjectTableModel
package com.school.academic.ui;
import javax.swing.table.AbstractTableModel;
* Class extending the <code>AbstractTableModel</code> for use in
creating the
* <code>Subject</code>s table. In addition to the implemented methods
of
* <code>AbstractTableModel</code> The class creates a model that has
initial
* values - the values have their own <code>getter</code> and
* <code>setter</code> methods - but can still be used for values that
a user
* chooses.
* <p>
* @author Khusta
public class SubjectTableModel extends AbstractTableModel {
* Comment for <code>serialVersionUID</code>
private static final long serialVersionUID = 3257850978324461113L;
/** Column names for the subjects table */
String[] columnNames = { "Subject", "Grade", "Class Room",
"Select" };
/** Array of objects for the subjects table */
Object[][] subjectsList;
private int totalRows = 20;
protected int notEditable = 0;
* Parameterless constructor.
public SubjectTableModel() {
// TODO initialise the list
// add column to the default table model
this.subjectsList = new
Object[getTotalRows()][getColumnNames().length];
* Copy constructor with the <code>subjectList</code> to set
* @param subjects
public SubjectTableModel(Object[][] subjects) {
this(0, null, subjects, 0);
* Copy constructor with the initial number of row for the model
* @param rows -
* the initial rows of the model
* @param cols -
* the initial columns of the model
* @param subjects -
* the initial subjects for the model
* @param edit - the minimum number of columns that must be
uneditable
public SubjectTableModel(int rows, String[] cols, Object[][]
subjects, int edit) {
// set the initial rows
setTotalRows(rows);
// set the column names
setColumnNames(cols);
// set the subjectlist
setSubjectsList(subjects);
//set not editable index
setNotEditable(edit);
* Function to get the total number of columns in the table
* @return int -- the columns in the table
public int getColumnCount() {
if (this.subjectsList == null) {
return 0;
return getColumnNames().length;
* Function to get the total number of rows in the table
* @return int -- the rows in the table
public int getRowCount() {
if (this.subjectsList == null) {
return 0;
return this.subjectsList.length;
* Function to get the name of a column in the table.
* @param col --
* the column to be named
* @return String -- the column in the table
public String getColumnName(int col) {
if (getColumnNames()[col] != null) {
return getColumnNames()[col];
return new String("...");
* Function to get the value of the given row.
* @param row --
* the row of the object.
* @param col --
* the col of the object.
* @return Object -- the value at row, col.
public Object getValueAt(int row, int col) {
return getSubjectsList()[row][col];
* Function to return the data type of the given column.
* @param c --
* the column whose type must be determined.
* @return Class -- the type of the object in this col.
public Class getColumnClass(int c) {
if (getValueAt(0, c) != null) {
return getValueAt(0, c).getClass();
return new String().getClass();
* Function to put a value into a table cell.
* @param value --
* the object that will be put.
* @param row --
* the row that the object will be put.
* @param col --
* the col that the object will be put.
public void setValueAt(Object value, int row, int col) {
* TODO: Have a boolean value to determine whether to clear or
to set.
* if true clear else set.
if (value != null) {
if (getSubjectsList()[0][col] instanceof Integer
&& !(value instanceof Integer)) {
try {
getSubjectsList()[row][col] = new
Integer(value.toString());
fireTableCellUpdated(row, col);
} catch (NumberFormatException e) {
* JOptionPane .showMessageDialog( this., "The \""
+
* getColumnName(col) + "\" column accepts only
values
* between 1 - 12");
return;
System.out.println("Value = " + value.toString());
System.out.println("Column = " + col + " Row = " + row);
// column = Grade or column = Select
switch (col) {
case 2:
try {
// TODO
if (Boolean.getBoolean(value.toString()) == false
&& getValueAt(row, 0) != null
&& getValueAt(row, 1) != null
&& getValueAt(row, 2) != null) {
// subjectsList[row][col + 1] = new
Boolean(true);
System.out.println("2. false - Updated...");
* this.subjectListModel.add(row,
* this.subjectsList[row][0] + new String(" -
") +
* this.subjectsList[row][2]);
} catch (ArrayIndexOutOfBoundsException exception) {
exception.printStackTrace();
break;
case 3:
if (Boolean.getBoolean(value.toString()) == false
&& getValueAt(row, 0) != null
&& getValueAt(row, 1) != null
&& getValueAt(row, 2) != null) {
System.out.println("3. If - Added...");
getSubjectsList()[row][3] = new Boolean(true);
this.subjectListModel.addElement(this.subjectsList[row][0] +
* new String(" - ") + this.subjectsList[row][2]);
// subjectListModel.remove(row);
fireTableCellUpdated(row, col);
fireTableDataChanged();
// this.doDeleteSubject();
} else if (Boolean.getBoolean(value.toString()) ==
true
&& getValueAt(row, 0) != null
&& getValueAt(row, 1) != null
&& getValueAt(row, 2) != null) {
setValueAt("", row, col - 1);
setValueAt("", row, col - 2);
setValueAt("", row, col - 3);
System.out.println("3. Else - Cleared...");
// this.subjectListModel.remove(row);
break;
default:
break;
}// end switch
getSubjectsList()[row][col] = value;
fireTableCellUpdated(row, col);
fireTableDataChanged();
}// end if
}// end
* Function to enable edition for all the columns in the table
* @param row --
* the row that must be enabled.
* @param col --
* the col that must be enabled.
* @return boolean -- indicate whether this cell is editble or
not.
public boolean isCellEditable(int row, int col) {
if (row >= 0
&& (col >= 0 && col <= getNotEditable())) {
return false;
return true;
* Function to get the column names for the model
* @return Returns the columnNames.
public String[] getColumnNames() {
return this.columnNames;
* Function to set the column names for the model
* @param cols
* The columnNames to set.
public void setColumnNames(String[] cols) {
// if the column names are null the default columns are used
if (cols != null) {
this.columnNames = cols;
* Function to get the rows of subjects for the model
* @return Returns the subjectsList.
public Object[][] getSubjectsList() {
if (this.subjectsList == null) {
this.subjectsList = new
Object[getTotalRows()][getColumnNames().length];
return this.subjectsList;
* Function to set the subjects list for the model
* @param subjects
* The subjectsList to set.
public void setSubjectsList(Object[][] subjects) {
// if the subject list is null create a new one
// using default values
if (subjects == null) {
this.subjectsList = new
Object[getTotalRows()][getColumnNames().length];
return;
this.subjectsList = subjects;
* Function to get the total number of rows for the model. <b>NB:
</b> This
* is different to <code>
getRowCount()</code>.<code>totalRows</code>
* is the initial amount of rows that the model must have before
data can be
* added.
* @return Returns the totalRows.
* @see #setTotalRows(int)
public int getTotalRows() {
return this.totalRows;
* Function to set the total rows for the model.
* @param rows
* The totalRows to set.
* @see #getTotalRows()
public void setTotalRows(int rows) {
// if the rows are less than 0 the defaultRows are used
// set getTotalRows
if (rows > 0) {
this.totalRows = rows;
* Function to get the number of columns that is not editble
* @return Returns the notEditable.
public int getNotEditable() {
return this.notEditable;
* Function to set the number of columns that is not editable
* @param notEdit The notEditable to set.
public void setNotEditable(int notEdit) {
if (notEdit < 0) {
notEdit = 0;
this.notEditable = notEdit;
----------------------------END TABLE MODEL----------------------------------I hope you don't expect us to read hundreds of lines of unformatted code? Use the "formatting tags" when you post.
Why are you creating your own TableModel? It looks to me like the DefaultTableModel will store you data. Learn how to use JTable with its DefaultTableModel first. Then if you determine that DefaultTableModel doesn't provide the required functionality you can write your own model.
Maybe you are looking for
-
How do I transfer books from IBook on my Ipad to my laptop
I am trying to transfer IBooks to my Laptop - can anyone help
-
I have an Samsung 930b 19" connected to my mac-mini via the mac-mini's DVI to VGA converter. Previously I had a CRT connected to the Macmini and the text was clearer. The text is blurry now with the LCD. I've tried many resolutions and the text still
-
Urgent with step by step example
Hi I was trying to create the given example(Step by step example) from the pdf document(OracleBPM-Tutorial_10.3.pdf) on Page 36 step 12 mentioned as below. My question is Do we expand Expense Report Process or Scren Flow when creating Instance report
-
Hide report path in oracle form 10g (10.1.2.0.2)
Dear all, I m oracle form 10g (10.1.2.0.2) ,when i run report through form using paramform='yes' then parameter form open with path and userid/pass please help me how to hide this path
-
why is th uploading process not working? i am trying to convert a pdf into a word doc