Copying (some columns of) a JTable to a new JTable - java

I have a JTable displayed in a frame. This table must remain unmodified for
later processing. At some point I want to show a column reduced version of this
table in a dialog. So I make a copy of the original table in creating a new
TableModel and TableColumnModel, thereby skipping the columns not needed.
Everything is fine until the dialog is set to visible. Then I run into an
endless error loop, starting with an "ArrayIndexOutOfBoundsException: 3 >= 2".
If 3 is the index to a table row, then it's indeed too large.
As the reduced table has only two columns, a column index of 2 would already exceed. Checking the columns with
getColumnCount() shows that the values are ok.
I suspect my copyTable method to be the culprit, but have no idea where the 3
index is coming from.
Instead of filling the rows of the table's model one by one, I succeeded using DefaultTableModel.addColumn(Object columnName, Object[] columnData) as suggested here. Then, however, I lose the columns' width information. Hence I would still like to know my fault in the current code.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class CopyTable extends JFrame {
public static final long serialVersionUID = 100L;
public CopyTable() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JTable table= createTable();
JScrollPane scroll= new JScrollPane(table);
add(scroll, BorderLayout.CENTER);
JButton b= new JButton("Show dialog");
b.addActionListener(e -> createAndShowDialog(table));
add(b, BorderLayout.SOUTH);
setSize(table.getColumnModel().getTotalColumnWidth()+11, 240);
setVisible(true);
}
static public void main(String args[]) {
EventQueue.invokeLater(CopyTable::new);
}
// #param columns Indices of columns to be copied into the new table.
public JTable copyTable(JTable table, int... columns) {
DefaultTableModel tblModel= new DefaultTableModel(0, columns.length);
DefaultTableModel oldModel= (DefaultTableModel)table.getModel();
Object[] row= new Object[columns.length];
int iRow= 0;
while (iRow<oldModel.getRowCount()) {
for (int i=0; i<columns.length; i++) {
row[i]= oldModel.getValueAt(iRow, columns[i]);
}
tblModel.addRow(row);
iRow++;
}
DefaultTableColumnModel colModel= new DefaultTableColumnModel();
DefaultTableColumnModel oldColModel=
(DefaultTableColumnModel)table.getColumnModel();
for (int i=0; i<columns.length; i++) {
colModel.addColumn(oldColModel.getColumn(columns[i]));
/* Creating a new column didn't help.
TableColumn tc= new TableColumn();
tc= oldColModel.getColumn(columns[i]);
colModel.addColumn(tc);
*/
}
return new JTable(tblModel, colModel);
}
private void createAndShowDialog(JTable table) {
JTable tbl = copyTable(table, 0, 3); // Copy only columns 0 and 3.
JOptionPane.showMessageDialog(this, ""+tbl.getModel().getRowCount()+", "+
tbl.getModel().getColumnCount()+", "+
tbl.getColumnModel().getColumnCount(),
"Checking row/column count",
JOptionPane.INFORMATION_MESSAGE);
JDialog dlg= new JDialog(this, "Reduced table", true);
dlg.setLocationRelativeTo(this);
JScrollPane scroll = new JScrollPane(tbl);
dlg.add(scroll, BorderLayout.CENTER);
dlg.pack();
dlg.setVisible(true);
}
private JTable createTable() {
String headers[] = {"Fruit", "Colour", "Count", "Price"};
Object data[][] = {
{"Apple", "Green", 6, .3},
{"Banana", "Yellow", 3, .4},
{"Cherry", "Red", 10, 1.1}
};
DefaultTableModel model = new DefaultTableModel(data, headers) {
public Class<?> getColumnClass(int column) {
Class<?> returnValue;
if (column>=0 && column<getColumnCount() && getValueAt(0,column)!=null)
returnValue= getValueAt(0, column).getClass();
else
returnValue= Object.class;
return returnValue;
}
};
JTable tbl= new JTable(model);
TableColumnModel tcm= tbl.getColumnModel();
int[] width= new int[] {60, 50, 40, 40};
for (int i=0; i<headers.length; i++) {
tcm.getColumn(i).setPreferredWidth(width[i]);
tcm.getColumn(i).setWidth(width[i]);
}
return tbl;
}
}
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 3 >= 2
at java.base/java.util.Vector.elementAt(Vector.java:466)
at java.desktop/javax.swing.table.DefaultTableModel.getValueAt(DefaultTableModel.java:661)
at java.desktop/javax.swing.JTable.getValueAt(JTable.java:2763)
at java.desktop/javax.swing.JTable.prepareRenderer(JTable.java:5780)
at java.desktop/javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:2207)
at java.desktop/javax.swing.plaf.basic.BasicTableUI.paintCells(BasicTableUI.java:2109)
at java.desktop/javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:1905)
at java.desktop/javax.swing.plaf.ComponentUI.update(ComponentUI.java:161)
at java.desktop/javax.swing.JComponent.paintComponent(JComponent.java:852)
java 18

There is no need to copy the TableModel (they are shareable by design) - all you need is a new TableColumnModel containing clones of the original: note that the relevant coordinate system is the model index.
Example:
TableColumnModel sourceColumnModel = sourceTable.getColumnModel();
DefaultTableColumnModel reducedColumnModel = new DefaultTableColumnModel();
for (int i = 0; i < sourceColumnModel.getColumnCount(); i++) {
TableColumn sourceColumn = sourceColumnModel.getColumn(i);
int modelIndex = sourceColumn.getModelIndex();
if (modelIndex % 2 == 0) { // replace with your condition
TableColumn column = new TableColumn(modelIndex, sourceColumn.getPreferredWidth());
column.setHeaderValue(sourceColumn.getHeaderValue());
reducedColumnModel.addColumn(column);
}
}
JTable reducedTable = new JTable(sourceTable.getModel(), reducedColumnModel);

#g00se
Your solution works. Thank you. The only drawback is that removing columns from the TableColumnModel doesn't remove them from the TableModel. So I added the following to your code
int icnt= oldModel.getRowCount();
for (int j=0; j<icnt; j++) {
Vector<?> vec= (Vector<?>)data.get(j);
for (int i=columns.length-1; i>=0; i--) {
vec.removeElementAt(columns[i]);
}
data.setElementAt(vec, j);
}
((DefaultTableModel)result.getModel()).setDataVector(data, headers);
return result;
But due to lack of Generics knowledge, I cannot make the code compile. Still an idea for that?
Just copying/creating a new model would avoid any removal. So I am still curious as for my original error.
Edit
----------------------------------------------------------
Generics:
Vector<Vector<Object>> data = ...
...
Vector<Object> vec= data.get(j);
----------------------------------------------------------
Finally I got my original version to work. colModel.addColumn(oldColModel.getColumn(columns[i])); passes only a reference of the column. But one has to create a new instance for each column in the new table.
// #param columns Indices of columns to be copied into the new table.
public JTable copyTable(JTable table, int... columns) {
DefaultTableModel oldModel= (DefaultTableModel)table.getModel();
DefaultTableModel tblModel= new DefaultTableModel(0, columns.length) {
public Class<?> getColumnClass(int column) {
Class<?> returnValue;
if (column>=0 && column<getColumnCount() && getValueAt(0,column)!=null)
returnValue= getValueAt(0, column).getClass();
else
returnValue= Object.class;
return returnValue;
}
};
Object[] row= new Object[columns.length];
int icnt= oldModel.getRowCount();
for (int i=0; i<icnt; i++) {
for (int j=0; j<columns.length; j++) {
row[j]= oldModel.getValueAt(i, columns[j]);
}
tblModel.addRow(row);
}
DefaultTableColumnModel oldColModel=
(DefaultTableColumnModel)table.getColumnModel();
DefaultTableColumnModel colModel= new DefaultTableColumnModel();
for (int i=0; i<columns.length; i++) {
// colModel.addColumn(oldColModel.getColumn(columns[i])); // Endless err loop
TableColumn tc= oldColModel.getColumn(columns[i]);
TableColumn tcNew= new TableColumn(i, tc.getPreferredWidth(),
tc.getCellRenderer(), tc.getCellEditor());
tcNew.setHeaderValue(tc.getHeaderValue());
colModel.addColumn(tcNew);
}
return new JTable(tblModel, colModel);
}
private void createAndShowDialog(JTable table) {
JTable tbl = copyTable(table, 0, 1, 3); // Copy only columns 0, 1 and 3.
JDialog dlg= new JDialog(this, "Reduced table", true);
JScrollPane scroll = new JScrollPane(tbl);
scroll.setPreferredSize(
new Dimension(tbl.getColumnModel().getTotalColumnWidth(), 80));
dlg.add(scroll, BorderLayout.CENTER);
dlg.pack();
dlg.setLocationRelativeTo(this);
dlg.setVisible(true);
}

I can't say I know quite why you get that exception, but this is a possible problem-free alternative, involving cloning the table then removing unwanted columns. This is based on the intuitive ascending ordering of required columns. Obviously the logic could be made easier by passing an array of columns to be removed rather than retained.
// #param columns Indices of columns to be copied into the new table.
public JTable copyTable(JTable table, int... columns) {
DefaultTableModel oldModel = (DefaultTableModel) table.getModel();
#SuppressWarnings("unchecked")
Vector<? extends Vector> data = (Vector<? extends Vector>) oldModel.getDataVector().clone();
Vector<Object> headers = new Vector<>();
TableColumnModel cmSource = table.getColumnModel();
for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) {
headers.add(cmSource.getColumn(i).getIdentifier());
}
JTable result = new JTable(data, headers);
TableColumnModel cmTarget = result.getColumnModel();
Set<Integer> columnsToCopy = new HashSet<>();
for (int i = columns.length; --i >= 0;) {
columnsToCopy.add(columns[i]);
}
for (int i = cmTarget.getColumnCount(); --i >= 0;) {
if (!columnsToCopy.contains(i)) {
cmTarget.removeColumn(cmTarget.getColumn(i));
}
}
return result;
}

Related

How to duplicate or copy data on my first Jframe table to second jframe table?

My problem is this. I have a table on my first JFrame and now I want the data on my first table to be duplicated on the table of my second JFrame. I'm using GUI, I have 2 JFrames, both JFrames have tables and i want both tables to display same data.
I have come up to this solution but I don't know how to set the data on my second table.
This is the code:
public Object[][] getTableData (JTable table) {
TableModel dtm = table.getModel();
int nRow = dtm.getRowCount(), nCol = dtm.getColumnCount();
Object[][] tableData = new Object[nRow][nCol];
for (int i = 0 ; i < nRow ; i++)`enter code here`
for (int j = 0 ; j < nCol ; j++)
tableData[i][j] = dtm.getValueAt(i,j);
return tableData;
}
How do I solve the problem?
To make it more clear. ill attach photo
this is my first JFrame Photo
this is my second JFrame
my second jframe is just a summary of what is being entered in first JFrame. that is the reason why i use 2 JFrames.
i have 2 JFrame forms. in First JFrame Form i have this Code, i tried to modify the code above a bit.
public Object[][] getEquipTableData () {
TableModel dtm = equipmentBorrowTable.getModel();
int nRow = dtm.getRowCount(), nCol = dtm.getColumnCount();
tableDataE = new Object[nRow][nCol];
for (int i = 0 ; i < nRow ; i++)
for (int j = 0 ; j < nCol ; j++)
tableDataE[i][j] = dtm.getValueAt(i,j);
return tableDataE;
}
and then at the second JFrame i have this partof code
public StudentSumarry() {
StudentModeDashboard SMD = new StudentModeDashboard();
String[] columnNames = {"Employee 1", "Employee 2", "Employee 3", "Employee 4"};
Object[][] firstTableData = SMD.getEquipTableData();
initComponents();
equipmentBorrowTable2.setModel(new DefaultTableModel(firstTableData, columnNames));
}
i instantiate my JFrame1 on JFrame2 to use the method getEquipTableData() on JFrame1. IDK if what im doing is right.
First and foremost take some time to read if multiple JFrames is good or bad practice.
Secondly, you can change the TableModel of the second JTable, by using setModel() method passing a DefaultTableModel. The getTableData method you have created seems to be ok in order to achieve something like this.
Object[][] firstTableData = getTableData(firstTable);
secondJTable.setModel(new DefaultTableModel(firstTableData, columnNames));
(After some comments taking place):
SSCCE:
public class JTables {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Frame 1");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTable table = new JTable(randomData(), new String[] { "FirstTableCol1", "FirstTableCol2" });
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(table));
JFrame frame2 = new JFrame("Frame 2");
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTable table2 = new JTable(randomData(), new String[] { "SecondTableCol1", "SecondTableCol2" });
frame2.setLayout(new BorderLayout());
frame2.add(new JScrollPane(table2));
JButton button = new JButton("copy");
button.addActionListener(e -> {
Object[][] data = getTableData(table);
table2.setModel(new DefaultTableModel(data, new String[] { "SecondTableCol1", "SecondTableCol2" }));
});
frame.add(button, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
frame2.pack();
frame2.setVisible(true);
});
}
private static Object[][] randomData() {
Object arr[][] = new Object[5][2];
for (int i = 0; i < arr.length; i++) {
arr[i][0] = String.valueOf((int) (Math.random() * 10000));
arr[i][1] = String.valueOf((int) (Math.random() * 10000));
}
return arr;
}
public static Object[][] getTableData(JTable table) {
TableModel dtm = table.getModel();
int nRow = dtm.getRowCount(), nCol = dtm.getColumnCount();
Object[][] tableData = new Object[nRow][nCol];
for (int i = 0; i < nRow; i++)
for (int j = 0; j < nCol; j++)
tableData[i][j] = dtm.getValueAt(i, j);
return tableData;
}
}

JTable select and deselect not working

I have a problem with my JTable. Firstly I selected some entries in my table. However when I deselect some of them, the table could not understand it.
Example scenario: I select job1 and 2 for the testing after that I change my mind and de-select job2. But in the result I saw job1 job1 and job2 ( job 1 seen 2 times and even though I dis-select job 2 I saw them.) Or after selected all the jobs ( choose all button) I want to deselect all of them (Clear button) when I click clear all the table seems empty. It is good but somehow the background of the program still protect the all old selection. How can I solve this?
Try:
I created the row of my table by read csv file.
public class JobSelectionListPanel extends JPanel {
private static final long serialVersionUID = 5198916547962359735L;
private static JobSelectionListPanel INSTANCE = new JobSelectionListPanel();
public static JobSelectionListPanel getInstance() {
return INSTANCE;
}
private JTable table;
private JButton next, back, btnClear, btnNewButton, btnChooseAll;
private JobList fnnJobList = new JobList();
private JobSelectionListPanel() {
table = new JTable();
JScrollPane scrollPane = new JScrollPane(table);
table.setBorder(new CompoundBorder());
// Read all FNN jobs from file
try {
fnnJobList.readFromFile("rules.csv");
} catch (IOException e1) {
System.out.println("You are not able to read the rules.csv file");
}
// Create ArrayList of JobNames
Object[][] initialData = new Object[fnnJobList.size()][1];
int i = 0;
for (Job jobDes : fnnJobList) {
initialData[i][0] = (Object) jobDes.getJobname();
i++;
}
String[] columnNames = new String[] { "", "Your preferences" };
table.setModel(new DefaultTableModel(initialData, columnNames) {
private static final long serialVersionUID = 1L;
#SuppressWarnings("rawtypes")
Class[] columnTypes = new Class[] { Object.class, Boolean.class };
#SuppressWarnings({ "unchecked", "rawtypes" })
public Class getColumnClass(int columnIndex) {
return columnTypes[columnIndex];
}
});
table.getColumnModel().getColumn(1).setPreferredWidth(80);
table.getColumnModel().getColumn(1).setMinWidth(40);
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
table.setCellSelectionEnabled(true);
I user want to choose all rows then I implemented this.
btnChooseAll = new JButton("Choose all");
btnChooseAll.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultTableModel chooseAllData = (DefaultTableModel) table.getModel();
if (DeviceGroups.DeviceAList.size() == 0 || DeviceGroups.DeviceBList.size() == 0
|| DeviceGroups.DeviceCList.size() == 0 || DeviceGroups.DeviceDList.size() == 0)
JOptionPane.showMessageDialog(null,
"You should choose at least 1 device for each test device to apply this test case", "Invalid OPTION",
JOptionPane.ERROR_MESSAGE);
else
for (int i = 0; i < chooseAllData.getRowCount(); i++) {
for (int j = 1; j < chooseAllData.getColumnCount(); j++) {
chooseAllData.setValueAt(true, i, j);
}
}
}
});
For clear all preferences :
btnClear = new JButton("Clear all");
// Clear button create a model of JTable and delete all the rows of table!!
btnClear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultTableModel clearTableData = (DefaultTableModel) table.getModel();
for (int i = 0; i < clearTableData.getRowCount(); i++) {
for (int j = 1; j < clearTableData.getColumnCount(); j++) {
clearTableData.setValueAt(null, i, j);
}
}
}
});
I see the following problem in your code: mixing up view indexes and model indexes. This is the offending snippet:
for (int i = 0; i < table.getRowCount(); i++) {
if (table.getValueAt(i, 1) != null) {
if (((Boolean) table.getValueAt(i, 1)).booleanValue()) {
String jobName = (((DefaultTableModel) table.getModel()).getValueAt(i, 0).toString());
You are using the i variable to denote view row indices, since you are checking values in this statement: table.getValueAt(i, 1) != null.
But then a bit further you are using i to index the model:
String jobName = ((DefaultTableModel) table.getModel()).getValueAt(i, 0).toString();
If i is to be a view index, you need to convert it to a model index before indexing the model:
String jobName = ((DefaultTableModel) table.getModel()).getValueAt(table.convertRowIndexToModel(i), 0).toString();
Also, when columns would be switched around in the view (ie on screen in your GUI), the following will probably not work as intended:
table.getValueAt(i, 1) != null
You most likely mean to say, get the second column value in the model, not the view. Best rewrite then as
table.getValueAt(i, table.convertColumnIndexToView(1)) != null

Calculate the sum of a column and put it on that jtable

How can I calculate sum of price column in jTable and put sum of them at the end of the jTable. Can you give me a sample code?
public class IncomeReport extends JFrame {
private AccountFacade service = new AccountFacade();
void init() {
String[] columnNames = {"مبلغ", "محل درآمد ", "منبع"};
List list = service.incomeReportFacade();
Object[][] model = new Object[list.size()][];
for (int i = 0; i < list.size(); i++) {
model[i] = (Object[]) list.get(i);
}
JTable table = new JTable(model, columnNames) {
DefaultTableCellRenderer renderRight = new DefaultTableCellRenderer();
{
// initializer block
renderRight.setHorizontalAlignment(SwingConstants.RIGHT);
}
#Override
public TableCellRenderer getCellRenderer(int arg0, int arg1) {
return renderRight;
}
};
Try something like this. Get the model, and use the DefaultTableModel#getValueAt() method.
Jtable table = new Jtable();
DefaultTableModel model = (DefaultTableModel)table.getModel();
double total = 0;
int column = 2; // example
for (int i = 0; i < model.getRowCount(); i++){
total += model.getValueAt(i, column); // getValueAt(row, column)
}
Object[] row = {"", "", total};
model.addRow(row);
If you need a total that is dynamically kept up to date then you will need to either override your TableModel to provide the sum for the final row, or will need to listener for changes to the model and update the last row with the sum.
Customizing your own TableModel would also allow you the ability to make your summary row uneditable so while this might be more work, it provides much more flexibility.

Java Swing JTable: cannot access the values in the table due to incorrect usage/creation of table model

I am just beginning to program using Java Swing. I am not very familiar with each of the many Java Swing Classes, and have ran into a stumbling block regarding the creation of a Table.
I am trying to figure out how to add a table to a Java Swing Program I am making. I have looked at docs.oracle.com to try and figure it out but I am getting an error when I try to access the values of the table. I will include my code to help show what I am currently trying to do and where the error is.
This is my code for making the table and the table model (I think the problem is that my table model is not working correctly):
/*Create the Table Entry*/
columnNames = new String[listoffields.size()+1];
columnNames[0] = "Record Number";
for(int a = 1; a < columnNames.length;a++){
columnNames[a] = listoffields.get(a-1).getTitle();
}
int count = 1;
data = new Object[numrecords][listoffields.size()+1];
for(int a = 0; a < numrecords;a++){
for(int b = 0; b < listoffields.size()+1;b++){
if(b == 0){
data[a][b] = count;
count++;
}
else{
data[a][b] = "";
}
}
}
/* create the table */
JTable table = new JTable(data,columnNames);
table.setCellSelectionEnabled(true);
table.setModel(new AbstractTableModel() {
public String getColumnName(int col) {
return columnNames[col].toString();
}
public int getRowCount() { return data.length; }
public int getColumnCount() { return columnNames.length; }
public Object getValueAt(int row, int col) {
return data[row][col];
}
public boolean isCellEditable(int row, int col) {
return (col >= 1);
}
public void setValueAt(Object value, int row, int col) {
data[row][col] = value;
fireTableCellUpdated(row, col);
}
});
JScrollPane scrollPane = new JScrollPane(table);
table.setFillsViewportHeight(true);
/* addthe table to the JTable tableentry*/
tabelentry.setLayout(new BoxLayout(ProjectFrame.tabelentry, BoxLayout.Y_AXIS));
tabelentry.add(scrollPane);
tabelentry.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
After the table is displayed and I edit the blank values for each cell, I click a submit button that submits the cell. However, the following error is encountered:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0 >= 0
at java.util.Vector.elementAt(Unknown Source)
at javax.swing.table.DefaultTableModel.getValueAt(Unknown Source)
at Client.GUIComponents.ProjectFrame$1.submit(NameOfFile.java:LineNumber)
The error is encountered when trying to submit as follows:
public void submit(){
String recordvalues = ""; //contains a String representation of what I want to submit
for(int a = 0; a < numberoffields;a++){
for(int b = 0; b < numberofrecords;b++){
if(a != 0){ //I want to skip the first column
recordvalues = recordvalues + (String) tabelentry.getModel().getValueAt(b, a) + ","; //The error is at this line in the code
}
}
}
}
I provided my code to give an example of the current problems I am encountering and what I have currently tried. To generalize my question, I am wondering how to correctly write a table model class so that I can access the values at each of the cells in the table. Any assistance would be helpful. Thanks a ton!
My immediate thought is that you're creating two different table models.
JTable table = new JTable(data,columnNames);
table.setCellSelectionEnabled(true);
table.setModel(new AbstractTableModel() {...
new JTable(data,columnNames) is actually creating it's own DefaultTableModel based on the information you are providing it. Try removing the table.setModel(new AbstractTableModel() {... code
The other, associated, problem is, I don't know how data and columnNames are declared.
Have a read through How to Use Tables for more details
Updated
The other problem, as pointed about by Hovercraft, is you adding one table to another and then accessing the wrong model.
The table creation should look more like...
tableEntry = new JTable(data,columnNames);
JScrollPane scrollPane = new JScrollPane(tableEntry );
tableEntry .setFillsViewportHeight(true);
// Don't forget to add the scroll pane to you view !!
Then you submit method should look more like...
public void submit(){
String recordvalues = ""; //contains a String representation of what I want to submit
TableModel model = tableEntry.getModel();
for(int a = 0; a < model.getColumnCount();a++){
for(int b = 0; b < model.getRowCount();b++){
if(a != 0){ //I want to skip the first column
recordvalues = recordvalues + (String) model.getValueAt(b, a) + ","; //The error is at this line in the code
}
}
}
}
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0 >= 0
This exception means that the column size of your table is 0, I think it's because you don't add columns into your TableModel.
Try to create several TableColumn Column = new TableColumn(); then add these columns to your table

how can i create an array of swt TableColumn and assign those TableColumns to one Table?

String[] titles = {"System Code","Domain Name","Organizational Unit","Organization Name"};
for(int i=0; i<titles.length; i++)
{
TableColumn column = new TableColumn(table, SWT.LEFT, i);
column.setText(titles[i]);
column.setWidth(150);
column.setMoveable(true);
column.setResizable(true);
}
this code works for me but i want to have an array of TableColum, like this one
Table table;
TableColumn[] columns;
table = new Table(composite, SWT.NONE);
columns = new TableColumn[noOfColumns];
table.setHeaderVisible(true);
but now you see they are not associated with table. How can i associate all these to columns to table ??
As far as making the columns into an array,
String[] titles = {"System Code","Domain Name","Organizational Unit","Organization Name"};
TableColumn[] columns = new TableColumn[titles.length];
for(int i=0; i<titles.length; i++)
{
TableColumn column = new TableColumn(table, SWT.LEFT, i);
column.setText(titles[i]);
column.setWidth(150);
column.setMoveable(true);
column.setResizable(true);
columns[i] = column;
}
For the second part though, you're trying to get that array into your table?
Are you using javax.swing.table.TableColumn? As it doesnt appear to have setText and setMoveable methods on it. If you are using it, and fixed that in your code, simply add the following code into the for loop (at the end):
tableInstance.addColumn(column);
Or do another iteration afterwards/later on:
for( TableColumn column : columns ) {
tableInstance.addColumn(column);
}
tableInstance if your instance of the JTable class
Here's a full class with all the issues I found fixed up (you wont need all of it, such as the frame declaration, but just to let you see it all):
public class TableTest {
public static void main(String[] args) {
JFrame f = new JFrame();
JTable table = new JTable();
JScrollPane scroll = new JScrollPane(table);
String[] titles = {"System Code","Domain Name","Organizational Unit","Organization Name"};
TableColumn[] columns = new TableColumn[titles.length];
for(int i=0; i<titles.length; i++)
{
TableColumn column = new TableColumn(i);
column.setHeaderValue(titles[i]);
column.setWidth(150);
column.setResizable(true);
columns[i] = column;
table.addColumn(column);//since we add this here, no real point in keeping
//the columns in an array tbh anymore
}
f.add(scroll);
f.setSize(500, 500);
f.setVisible(true);
}
}

Categories

Resources