I have read one of the question in this website. and since I had the same problem with the one who asked the same question as mine, I want to do a follow up question. HOW DO YOU PUT THIS INTO CODE:
Ask the master table what its selected row is (getSelectedRow()).
Convert this view row index to a model row index (convertRowIndexToModel()).
Ask the model for the data at this index, ands extract the ID of the data. The model should be a class that you wrote, extending AbstractTableModel.
Then get the data to display in the three sub-tables from this ID, and change the model (or the data contained in the model) of these three tables.
Thanks in advance. i am quite having a hard time in this part of my program. since i only know about
tablePersonalProperty.setModel(DbUtils.resultSetToTableModel(rs));
when displaying all the items from the table. what i need is to DISPLAY the items with the same id from what i have chosen from the main table...
Before we can help you write code, we need more information.
Do your tables both have exactly the same columns?
Are you using your own custom data model already? If not, then you probably need to try that on your own. I can't write this for you since I don't know what you need to include in your model. If you are using netbeans, then you can use the form designer to help you write the table model. Just look at the properties of the JTable after you add it to the JFrame of JPanel. I ended up creating my own anyway, but the code that Netbeans generated helped get me started.
This sample code will help you to do what you are looking for, it show how to move table row from one table to another in a click event in rows,
public class InsertRows{
public static void main(String[] args) {
new InsertRows();
}
public InsertRows(){
final JTable table, table2;
final DefaultTableModel model, model2;
JFrame frame = new JFrame("Inserting rows in the table!");
String data[][] = {{"Vinod","100"},{"Raju","200"},{"Ranju","300"}};
String col[] = {"Name","code"};
Object[][] selrowData = {};
model = new DefaultTableModel(data,col);
model2 = new DefaultTableModel(selrowData,col);
GridLayout gl = new GridLayout(2,1);
table = new JTable(model);
table2 = new JTable(model2);
//Insert first position
model.insertRow(0,new Object[]{"Ranjan","50"});
//Insert 4 position
model.insertRow(3,new Object[]{"Amar","600"});
//Insert last position
model.insertRow(table.getRowCount(),new Object[]{"Sushil","600"});
ListSelectionModel cellSelectionModel = table.getSelectionModel();
cellSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
cellSelectionModel.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
String selectedData = null;
String selectedData2 = null;
Object[][] val = {};
int selectedRow = table.getSelectedRow();
int selectedColumns = table.getColumnCount();
model2.insertRow(0,new Object[]{(String) table.getValueAt(selectedRow, selectedColumns-selectedColumns),(String) table.getValueAt(selectedRow, selectedColumns-1) });
}
});
frame.setLayout(gl);
frame.add(new JScrollPane(table));
frame.add(new JScrollPane(table2));
frame.setSize(600,600);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Related
Today I did a simple student / course selection database.
Everything works fine so far.
Now I want to implement a graphical representation. I decided to use a JTable (wahltabelle) where each column is a course and each row a student.
There a different ways how a student can visit a course. That’s why I want a Combobox in each cell. The currently selected value represents the student’s current selection and can be changed by the course manager.
The values are loaded and stored from / to a database.
Unfortunately I didn’t find out how to represent an individual combobox in each cell of a table. Therefore I currently have a String representation of my comboboxes.
I know that I can easily change the default cell editor for a complete column. But unfortunately I’m not sure how to do that for a individual cell.
Do I have to write my own cellRenderer?
public void addWahldata(List<Fach> faecher)
{
Vector head = new Vector<>();
head.add("");
for(Fach aktuell : faecher)
{
head.add(aktuell.getBezeichner());
}
Vector data = new Vector<>();
wahltabelle.setModel(new DefaultTableModel(data, head));
Vector rowx = new Vector<>();
rowx.add("");
JComboBox temp= null;
for (int i=1; i<wahltabelle.getColumnCount(); i++)
{
JComboBox cb = new AbiMoeglichkeitenGetter().getAbiMoeglichkeiten(wahltabelle.getColumnName(i));
temp = cb;
rowx.add(cb);
}
data.add(rowx);
wahltabelle.setModel(new DefaultTableModel(data, head));
}
Thanks for any explanation.
Let's say I have this JTable:
private JScrollPane scrollPane1;
private JTable table;
private DefaultTableModel model;
DefaultTableModel model = new DefaultTableModel();
model.addColumn("Item");
model.addColumn("ID");
model.addColumn("Price");
model.addColumn("Category");
this.scrollPane1 = new JScrollPane();
this.scrollPane1.setBounds(33, 518, 604, 300);
this.contentPane.add(this.scrollPane1);
table = new JTable(model);
this.scrollPane1.setViewportView(table);
I have an Item class, so when I create a new instance of Item, I add the items info to the JTable:
Item item = new Item("Shovel", 1, 123, "Tools");
model.addRow(new Object[]{item.getItem(), item.getID(), item.getPrice(), item.getCategory()});
So far so good.
But if I update the Item, for example change the price from 5 to 10, it is not updated in the JTable. So if I for example do:
item.setPrice(10);
It doesnt update in the JTable. I've tried calling model.fireTableDataChanged(); and table.repaint(); but none of them works. It seems like the value in the cell is not associated with the objects value? How would I do this? (First time working with JTables).
Any suggestions? Don't be bothered by the lack of methods etc., I just put this together quickly for this post.
EDIT: My Item objects are stored in a HashMap.
Actually, you are not modifying any cell in the table, the item object is not associated with your table directly, your making a now values in the table by using the same values from the item object.
what you has to do is to update the cell itself then by overriding the below method from AbstractTableModel class:
#Override
public void setValueAt(Object value, int row, int col) { //
Then call
model.fireTableDataChanged();
I have a JTable whose cells are editable. However if i edit a cell and refresh the table. The changes are not saved. This is how i have defined the table:
String [] columnNames = {"Application number",
"Name",
"date",
"fileLoc",
"Country"};
//Data for the table
String [][] data = table.tableArray;//tableArray is an array of array of strings.
TableModel model = new DefaultTableModel(data, columnNames);
JTable mainTable = new JTable(model);
model.isCellEditable(data.length,columnNames.length);
contentPane.add(new JScrollPane (mainTable));
I've had a look online but can't seem to find any advice on saving the changes made to a cell. Any help would be very welcome!
I guess i'm not refreshing the table as such. I use frame.dispose()
and then create a new frame with the table in.
then you lost all changes made in the current DefaultTableModel
don't top create a new JFrame with a new DefaultTableModel and a new JTable
all changes from TableCellEditor are changes dispayed in JTables view
JTable (with its model) is prepared for this job, don't to reacreate these Objects on runtime
DefaultTableModel has implemented all notifiers, there no needed to override any others events, nor to fireXxxXxx() programatically, but those events are required for AbstractTableModel
define add this code line for your JTablemainTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
DefaultTableModel respesenting your required 2D array
I try to add header row to my JTable and next put table on panel.
This is my sample code :
Map <String, Float> tmpCart = new HashMap<String , Float>();
MainPanel.removeAll();
MainPanel.repaint();
tmpCart = cart.GetMap();
DefaultTableModel tab = new DefaultTableModel();
tab.setColumnIdentifiers(new String[] {"Name", "Price"});
for (String key : tmpCart.keySet())
tab.addRow(new Object[] {key, tmpCart.get(key)});
JTable jTab = new JTable(tab);
jTab.setBounds(10, 10, 200, 200);
jTab.setBackground(Color.orange);
jTab.setRowHeight(25);
JScrollPane pan =new JScrollPane(jTab);
MainPanel.add(pan);
// MainPanel.add(jTab);
// pan.repaint();
How do I write it properly?
//answer
I try create JTable dynamically, after push button, I want get data from Hashtable, create table and put this table on panel.
First step is remove all components from panel, and next create JTable using data from Hashmap`
full function:
private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {
Map <String, Float> tmpCart = new HashMap<String , Float>();
MainPanel.removeAll();
MainPanel.repaint();
tmpCart = cart.GetMap();
DefaultTableModel tab = new DefaultTableModel();
tab.setColumnIdentifiers(new String[] {"Name", "Price"});
for (String key : tmpCart.keySet())
tab.addRow(new Object[] {key, tmpCart.get(key)});
JTable jTab = new JTable(tab);
jTab.setBounds(10, 10, 200, 200);
jTab.setBackground(Color.orange);
jTab.setRowHeight(25);
// MainPanel.add(pan);
MainPanel.add(jTab);
}
This code works, create table and put it on panel, but doesn't set first row with column names ( text : "Names" and "Price").
Can't tell exactly what you are doing from the code sample.
If you are trying to dynamically update a table on a visible GUI, then there is not need to create a new table, just reset the TableModel.
table.setModel( model );
If you need more help then post your SSCCE that demonstrates the problem.
Edit:
First step is remove all components from panel,
Why are your removing components from the panel?
If you need to "swap" panels, then use a CardLayout.
If you need to "refresh" existing components, then just reset the model as explained above.
// MainPanel.add(pan);
MainPanel.add(jTab);
The scrollPane should be added to the GUI, not the table.
The table header is another component that only gets added automatically when the table is inside a JScrollPane. Your best bet is to create a JScrollPane via
new JScrollPane(table)
and add that to your MainPanel.
The other option is to added the header directly wherever you want it, and for that you can do:
panel.add(table.getTableHeader())
Try putting it into a JScrollPane.
I have a JTable with many strings in it. I have created a textbox for user entry, above the table. I want a row filter which can remove the rows having strings entered by the user in the text box. Please help me out for this.
from here:
sorting and filtering
In the following example code, you
explicitly create a sorter object so
you can later use it to specify a
filter:
MyTableModel model = new MyTableModel();
sorter = new TableRowSorter<MyTableModel>(model);
table = new JTable(model);
table.setRowSorter(sorter);
Then you filter based on the current
value of a text field:
private void newFilter() {
RowFilter<MyTableModel, Object> rf = null;
//If current expression doesn't parse, don't update.
try {
rf = RowFilter.regexFilter(filterText.getText(),0);
} catch (java.util.regex.PatternSyntaxException e) {
return;
}
sorter.setRowFilter(rf);
}
This few line solution seems to work:
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt)
{
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(((DefaultTableModel) jTable1.getModel()));
sorter.setRowFilter(RowFilter.regexFilter(jTextField1.getText()));
jTable1.setRowSorter(sorter);
}
You can use JTable.setAutoCreateRowSorter which will use the default row sorter/filter of the JTable
To pick up the comment from kd304, you could use GlazedLists. There you'll use a FilterList as the input for your JTable, and the FilterList will take care of the rest.