I have a master/detail form with a JTable on top, and all the JTextFields corresponding below in the JPanel. I'm trying to make a search in the JTable, so that when the correct row gets picked, all the JTextFields can be filled with the column values. I don't know how can I call the rows programmatically to do so. How would it be done?
This is the code I'm using to do the search:
int rows = (masterTable.getModel()).getRowCount();
final int colCedula = 1; //columna de la CEDULA
final int colRuc = 11; //columna de RUC
String value = null ;
for(int i=0; i
value = (String) (masterTable.getModel()).getValueAt(i, colCedula);
if (value.equals(this.txt_BuscaCliente.getText())) {
//CODE FOR FILLING JTEXTFIELDS
}
If the search finds the column value and stops the loop, could I just write in the //CODE section masterTable.getSelectedRow() and then fill all the JTextFields with its column values???
Also, how is it done to have the row selected highlighted, programatically? Let's say, after my search finds the column value, to have that row highlighted in the JTable
I'd start with the example in the tutorial article How to Use Tables: User Selections in order to understand list selection events. Given a SINGLE_SELECTION model, you won't have to search; just fill in the text fields from the selected row. Alternatively, you can make the cells editable in your table model, and you won't have to copy them at all.
Addendum:
Also, how is it done to have the row selected highlighted, programatically?
Instead of searching, let your implementation of ListSelectionListener tell you what selection has been made by the user. In the example cited, modify the RowListener as shown below to iterate through the columns in the selected row.
private class RowListener implements ListSelectionListener {
#Override
public void valueChanged(ListSelectionEvent event) {
if (!event.getValueIsAdjusting()) {
for (int c : table.getSelectedRows()) {
int row = table.convertRowIndexToModel(c);
TableModel model = table.getModel();
for (int col = 0; col < model.getRowCount(); col++) {
System.out.println(model.getValueAt(row, col));
}
System.out.println();
}
}
}
}
Related
I am trying to select an entire row from the jtable. The first time, entire row is getting selected, but from the next time, only few cells are getting selected though entire row data is obtained.
Code:
jDelete.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(!jtable.getSelectionModel().getValueIsAdjusting())
deleteRow(jtable.getSelectedRow());
}
});
jtable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if(!e.getValueIsAdjusting()){
jtable.setRowSelectionAllowed(true);
String[] arr = new String[9];
int row = jtable.getSelectedRow();
if(row!=-1){
for(int i=0;i<9;i++){
arr[i] = (String) jtable.getValueAt(row, i);
}
jId.setText(arr[0]);
jName.setText(arr[1]);
jTime.setSelectedItem(arr[2]);
jMail.setText(arr[3]);
jMobile.setText(arr[4]);
jCourse.setSelectedItem(arr[5]);
jFee.setText(arr[6]);
jPaid.setText(arr[7]);
jBalance.setText(arr[8]);
}
}
}
});
When I try to select the row and delete it, first time it is deleting properly. From the next time, when I click on a row, few cells are shown as selected but the entire row is obtained. How to make it to display as the entire row selected?
The first time : The entire is row selected properly.
[![enter image description here][1]][1]
The second time : The entire row is not selected entirely.
[![enter image description here][1]][1]
The entire code is posted here :
https://ideone.com/7EJiRQ
jtable.setRowSelectionAllowed(true);
Don't set this property in the selection listener. This is the default behaviour when the table is created. So the above code is not needed.
public void actionPerformed(ActionEvent e) {
if(!jtable.getSelectionModel().getValueIsAdjusting())
deleteRow(jtable.getSelectedRow());
Why are you checking the selection model in the ActionListener. There is no need to do this. The row will already be selected when the button is clicked.
However the code should be something like:
int row = jtable.getSelectedRow();
if (row != -1)
deleteRow( row );
This will make sure a row is selected before attempting to delete it.
Hi I have a problem with separate data in jTable.
My jTable:
When I click to Second button, so I have two data in jTable.
It's correct but when I click to First button again I get same jTable that as jTable in Second button.
This is my code:
DefaultTableModel model = new DefaultTableModel();
model = (DefaultTableModel) jTable1.getModel();
for(int i = 0; i < jTable1.getRowCount(); i++)
{
if(jTable1.getValueAt(i, 0) == Boolean.FALSE)
{
model.removeRow(i);
}
}
jTable2.setModel(model);
But it doesn't work. Is there anyone who tells me why ?
But it doesn't work. Is there anyone who tells me why ?
When you remove, for example, row 0, then all the rows shift down by one, but the value of "I" keeps increasing by one so you will "skip" rows every time you remove a row.
The solution is to start on the last row and decrement "I":
for(int i = jTable.getRowCount() - 1; i >=0; I--)
It's not a problem.
Yes it is. You posted example only works because you selected every other row in the table. Try selecting the first two rows and see what happens. Have said that, this is not the real solution to your problem, because you should NOT be removing data from the first TableModel.
It's correct but when I click to First button again I get same jTable that as jTable in Second button.
The problem is that you can't delete the data from the first TableModel. You need to create a new TableModel and then "copy" the data from the first TableModel to the second TableModel.
As a beginner,i am creating a jtable with some functionalities like adding and removing contents. I would like to know how to make a rename functionality to my application that on selecting this menu should highlight all the contents of the cell as in an editing mode. Thanks in advance
Continuing from your previous post.... Did you want something like below, when when you hit edit in the context menu, you can edit in some popup window?
→
You pretty much already have to tools for this functionality (in your code). For the new Action, you simply need to show a JOptionPane input dialog with the value of the selected cell. The return input of the JOptionPane will be the value you set back to the table. Something like. Keep in mind though, depending on the type of data, you may want to do some logical parsing or conversion. Below I just take the value as a String.
class EditCellAction extends AbstractAction {
private JTable table;
public EditCellAction(JTable table) {
putValue(NAME, "Edit");
this.table = table;
}
#Override
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
int col = table.getSelectedColumn();
String newValue = JOptionPane.showInputDialog(table,
"Enter a new value:", table.getValueAt(row, col));
((DefaultTableModel) table.getModel()).setValueAt(
newValue, row, col);
}
}
If you don't want the popup, and just want to programmatically start the cell editing, you can simple use table.editCellAt(row, col) to start the editing, and use the underlying text field of the cell editor to select the field contents. Something like below (tested and works)
#Override
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
int col = table.getSelectedColumn();
table.editCellAt(row, col);
JTextField field = (JTextField) ((DefaultCellEditor) table
.getCellEditor()).getComponent();
field.requestFocus();
field.setSelectionStart(0);
int endSelection =
(!field.getText().isEmpty()) ? field.getText().length() -1 : 0;
field.setSelectionEnd(endSelection);
}
Keep in mind though, if the cell is editable, the user can just double click the cell to edit it. I guess this adds some more functionality
I want to search data from JTable when data found then I want to highlight table row. This code is work properly search record but I don't know what I do for highlight the row.
String target = jTextField1.getText();
for(int row = 0; row < jTable1.getRowCount(); row++)
for(int col = 0; col < jTable1.getColumnCount(); col++)
{
String next = (String)jTable1.getValueAt(row, col);
if(next.equals(target))
{
System.out.println("found");// here what change for highlight row.
}
}
The answer depends on your idea of "highlighting"
You could use JTable#addRowSelection to highlight a row using the default selection
Or, you could setup your cell renders to apply additional highlighting support via an additional lookup to determine if the cell/row should be highlighted
Or, you could use the inbuilt filtering capabilities of the JTable to filter out unwanted content
See How to use tables for more details
Or, you could use the highlighting support from the SwingLabs, SwingX librRies
We can achieve that with a custom JLabel and TableCellRenderer.
Following example does the highlighting on the found (filtered) rows in JTable. The rows are filtered via RowFilter:
http://www.logicbig.com/tutorials/core-java-tutorial/swing/jtable-row-filter-highlighting/
else if(e.getSource()==field){
int z;
for(z = 0;z<table.getRowCount();z++){
if(Integer.parseInt(field.getText()) == Integer.parseInt((String)table.getValueAt(z, 1))){
break;
}
}
table.setRowSelectionInterval(z, z);
}
i had the same problem and this was how i went about it.
I have a JTable. I want to know which row and column are selected when the user presses Enter. How can I get this information?
Implmenent a TableModelListener. The TableModelEvent from the tableChanged() method will tell you what row and column was the source of the change.
All Swing components use Actions to handle key strokes. The default Action for the Enter key is to move the cell selection down one row. If you want to change this behaviour then you need to replace the default Action with a custom Action.
Check out Key Bindings for a simple explanation on how to replace an Action.
Add this to your table. Have two int globals for rowClicked and colClicked. Should be good to go
table.addMouseListener(new MouseAdapter(){
public void mouseReleased(MouseEvent e)
{
rowClicked = rowAtPoint(e.getPoint());
colClicked = columnAtPoint(e.getPoint());
}
public void mouseClicked(MouseEvent e)
{
rowClicked = rowAtPoint(e.getPoint());
colClicked = columnAtPoint(e.getPoint());
}
});
If you talking about using the keyboard to register the event, you must find the selected cell, then add a KeyListener to it. You can use the following code to find the selected cell. Note that it really depends on the cell selection mode.
public void getSelectedCells()
{
if (getColumnSelectionAllowed() && ! getRowSelectionAllowed())
{
// Column selection is enabled
// Get the indices of the selected columns
int[] vColIndices = getSelectedColumns();
}
else if (!getColumnSelectionAllowed() && getRowSelectionAllowed())
{
// Row selection is enabled
// Get the indices of the selected rows
int[] rowIndices = getSelectedRows();
}
else if (getCellSelectionEnabled())
{
// Individual cell selection is enabled
// In SINGLE_SELECTION mode, the selected cell can be retrieved using
setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
int rowIndex = getSelectedRow();
int colIndex = getSelectedColumn();
// In the other modes, the set of selected cells can be retrieved using
setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
// Get the min and max ranges of selected cells
int rowIndexStart = getSelectedRow();
int rowIndexEnd = getSelectionModel().getMaxSelectionIndex();
int colIndexStart = getSelectedColumn();
int colIndexEnd = getColumnModel().getSelectionModel().getMaxSelectionIndex();
// Check each cell in the range
for (int r = rowIndexStart; r < = rowIndexEnd; r++)
{
for (int c = colIndexStart; c < = colIndexEnd; c++)
{
if (isCellSelected(r, c))
{
// cell is selected
}
}
}
}
}