I want to print only selected rows in a JTable.
My approach is to make a new TableModel, copy the selected rows there, add the tableModel to a new JTable and then print this new Table.
My Problem: It doesnt work as expected, I just see a black line with the height of the rows, if i select lesser rows the line is smaller) but no content. But the content is in the table model, i can see it when i do system.out...
this is my code:
QueryTableModel tempModel = new QueryTableModel(String[] tableheaders);
JTable tempTable = new JTable();
for(int i : table.getSelectedRows())
tempModel.addRow(((QueryTableModel)table.getModel()).getRowAt(i));
System.out.println(tempModel.getRowCount());
tempTable.setModel(tempModel);
tempTable.print(JTable.PrintMode.FIT_WIDTH, header, null);
Related
I have a table where you can select specific cells.
When you select row 1 and 2 for first column by using Ctrl-click, and then you remove selection on one of the rows, the other row also get de-selected:
public static void main(String[] args)
{
JFrame jf = new JFrame("Test");
JTable table = new JTable();
table.setCellSelectionEnabled(true);
DefaultTableModel tm = new DefaultTableModel(new Object[][]{new Object[]{1,"A"},new Object[]{2, "B"},new Object[]{3, "C"}}, new Object[]{"Test", "Test2"});
table.setModel(tm);
jf.setSize(300, 400);
jf.getContentPane().add(table);
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jf.setLocationRelativeTo(null);
jf.setVisible(true);
}
Ctrl + Click on Test/2:
I expected:
From what i understand of the Swing code, the problem is that the column selection model has a code that does something like: if col = 0 selected, remove selection altogether. So when the table re-rendered, there's no column selection and whole selection gets cleared.
Is there a way to prevent whole deselection without recoding the whole DefaultSelectionModel?
I solved it by keeping track of the last selected column and having a selection listener that checks if selected row count is > 0, then select the lastly selected column, not perfect mayhaps but it seems to work fine
I've created a JTable using following way. This table has 5 columns and 4 rows.
All 4 rows are empty in this status.
String[] columns = {"Emplotee ID","Name","Address","City","Salary"};
//Table that already have 4 empty rows
DefaultTableModel model = new DefaultTableModel(columns,4);
JTable detail = new JTable(model);
JScrollPane scroll = new JScrollPane(detail);
Now I want to add values into those empty rows using String array.
The GUI of this program has 5 JTextFields to get user input. When I enter values into JTextFileds and click Add button, all JTextFiled values get by String array named values.
String[] values = new String[6];
//When click addButton all textFiled data should go into table
addButton.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent evt){
values[0] = idField.getText(); //get JTextFields data into array
values[1] = nameField.getText();
values[2] = addressField.getText();
values[3] = cityField.getText();
values[4] = salaryField.getText();
//What now?
}
});
I know I can use this to add new row into the table. But this is not the feature what I want.
DefaultTableModel newModel = (DefaultTableModel)detail.getModel();
newModel.addRow(values);
Set contents of an existing table row with:
int row;
....
// make sure row is set to index of the table row
// you want to populate
for (int c=0; c<values.length; ++c)
detail.setValueAt(values[c], row, c);
TableModel also has setValueAt method, if you prefer.
I have a JFrame Form which has JTextFields, JCombobox etc. and I am able to receive those values to variables and now I want to add the received data to JTable in new row when user clicks Add or something like that.
I have created JTable using net-beans the problem is what would be the code to add data from those variable to the rows of table. A basic example would be appreciated. I have tried numerous example and have added the code to ActionListener of the JButton but nothing Happens.
The Examples I tried are. How to add row in JTable? and How to add rows to JTable with AbstractTableModel method?
Any Help would be appreciated.
Peeskillet's lame tutorial for working with JTables in Netbeans GUI Builder
Set the table column headers
Highglight the table in the design view then go to properties pane on the very right. Should be a tab that says "Properties". Make sure to highlight the table and not the scroll pane surrounding it, or the next step wont work
Click on the ... button to the right of the property model. A dialog should appear.
Set rows to 0, set the number of columns you want, and their names.
Add a button to the frame somwhere,. This button will be clicked when the user is ready to submit a row
Right-click on the button and select Events -> Action -> actionPerformed
You should see code like the following auto-generated
private void jButton1ActionPerformed(java.awt.event.ActionEvent) {}
The jTable1 will have a DefaultTableModel. You can add rows to the model with your data
private void jButton1ActionPerformed(java.awt.event.ActionEvent) {
String data1 = something1.getSomething();
String data2 = something2.getSomething();
String data3 = something3.getSomething();
String data4 = something4.getSomething();
Object[] row = { data1, data2, data3, data4 };
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.addRow(row);
// clear the entries.
}
So for every set of data like from a couple text fields, a combo box, and a check box, you can gather that data each time the button is pressed and add it as a row to the model.
you can use this code as template please customize it as per your requirement.
DefaultTableModel model = new DefaultTableModel();
List<String> list = new ArrayList<String>();
list.add(textField.getText());
list.add(comboBox.getSelectedItem());
model.addRow(list.toArray());
table.setModel(model);
here DefaultTableModel is used to add rows in JTable,
you can get more info here.
String[] tblHead={"Item Name","Price","Qty","Discount"};
DefaultTableModel dtm=new DefaultTableModel(tblHead,0);
JTable tbl=new JTable(dtm);
String[] item={"A","B","C","D"};
dtm.addRow(item);
Here;this is the solution.
I have a JTable and any single row in it has associated a different tooltip when mouse hover a row. I have created a "filter" for this table; when it is applied it perfectly hides the rows need to be hidden but when I hover the mouse on the filtered rows, looks like the tooltip is referring to the row that occupied the same row position of the new current row.
For example:
Table
ROW 1 -> tooltip 1
ROW 2 -> tooltip 2
Apply Filter to Table:
ROW 2 -> tooltip 1
So ROW 2 is displaying the tooltip 1 instead of 2.
TableRowSorter<TableModel> sorter = (TableRowSorter<TableModel>) table.getRowSorter();
sorter.setRowFilter(RowFilter.regexFilter(text));
My table that extends JTable has:
#Override
public String getToolTipText(MouseEvent e) {
final int rowIndex = rowAtPoint(e.getPoint());
TableModel model = getModel();
// take the value from the first column of the selected row
String tip = (String) getModel().getValueAt(rowIndex, 0));
return tip;
}
So it looks like using the model is not (quite obvious) updated respect to the filter. I tried using TableModel model = getRowSorter().getModel() too but without any luck.
How can I point to a correct "filtered model" to retrieve the correct row position?
UPDATE:
I have replaced the "rowIndex" code like this:
final int rowIndex = convertRowIndexToModel(rowAtPoint(e.getPoint()));
It partially solves the problem, but when some rows are added dynamically to the table with the filter applied and I hover new rows I get the exception (with relative API description):
IndexOutOfBoundsException -> if sorting is enabled and passed an index outside the range of the JTable as determined by the method getRowCount
You need to convert the views row index to the model's row index
Have a look at JTable#convertRowIndexToModel
You should not override that JTable#getToolTipText method. Just set the tooltip-text on the component returned by your renderer. The JTable will pick it up automatically. You can see this in the implementation of the getTooltipText method of the JTable
I have a table where my columns expand dynamically. Initially I set my table model to have 5 columns since basic information has 5 columns. Among the 5 columns column 2 and 3 are buttons (actually they are hyperlinks in a form of a button) which means that I have set column 2 and 3 to have its own renderer and editor.
table.getColumnModel().getColumn(2).setCellRender(new MyCellRender());
table.getColumnModel().getColumn(2).setCellEditor(new MyCellEditor(table));
//more code for column 3 initializatation
My problem is there are times that a row might have more than 5 colums so I check it by adding new columns everytime I need to add more columns in the model. I use
model.addColumn("ColumnName");
to add new columns. The problem is everytime I add new rows that is greater then the initial row my renderers and editors on column 2 and 3 are reset/gone and are rendered as default. What do I need so that column 2 and column 3 remains. BTW Column 2 and 3 are the only columns that are always rendered as buttons.
You can try to override createDefaultColumnsFromModel in JTable and set your special editors/renderers again. As you modify the model the JTable will re-create the columnModel if getAutoCreateColumnsFromModel is true. As you add new column I think you need this to remain true.
public void createDefaultColumnsFromModel() {
super.createDefaultColumnsFromModel();
getColumnModel().getColumn(2).setCellRender(new MyCellRender());
getColumnModel().getColumn(2).setCellEditor(new MyCellEditor(this));
}
To initially create the table you can use:
JTable table = new JTable(model);
table.setAutoCreateColumnsFromModel( false );
table.getColumnModel().getColumn(2).setCellRender(new MyCellRender());
table.getColumnModel().getColumn(2).setCellEditor(new MyCellEditor(table));
The TableColumnModel and TableColumns will be created automatically.
Now, if you want to add another column, because TableColumns are not automatically created from the model you won't lose your custom renderer/editor but now you need to create the TableColumns manually:
String columnName = "Column X";
model.addColumn( columnName );
// AutoCreate is turned off so create table column here
TableColumn column = new TableColumn( table.getColumnCount() );
column.setHeaderValue( columnNamer );
table.addColumn( column );