How to get first row value from JTable - java

My question is that how to get first row value of jTable and display it in a textfield, but when ever the first row value changes, the value in the text field should change.

First off - your table has a TableModel.
You can access by calling
TableModel tm = table.getModel();
That TableModel has a method getValueAt(int row, int column) - use this to collect data from your first row (index 0).
The TableModel further allows for a TableModelListener to be added. That TableModelListener in turn receives TableModelEvents.
Use the event data to figure out if the first row was affected by your change and then apply the changed data to your textField:
public void tableModelChanged(TableModelEvent te) {
if(te.getFirstRow() == 0) { //First Row changed
//Receive Data and update TextField Here
}
}

Without knowing your specific case, I think this sounds like an application for using a TableCellListener, which will keep track of changes in your cell. Your jTable will fire a PropertyChangeEvent which is used by the listener. You might take a look at here and the code provided there to get the idea. Hope this helps in any way.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
node n=new node(Integer.parseInt(push.getText()));
q.push(n);
model=(DefaultTableModel) jTable1.getModel();
model.addRow(new Object[]{n.getele()});
push.setText(null);
}

Here is the code for my jtable, how do I get to the value of first row to the text field?
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
node n=new node(Integer.parseInt(push.getText()));
q.push(n);
model=(DefaultTableModel) jTable1.getModel();
model.addRow(new Object[]{n.getele()});
push.setText(null);
}

Related

Java: Refreshing my jTable after data updates in child jDialog

I've investigated lots of different questions and answers around this, but can't find one that seems to work.
I'm new to Java, but have experience in a variety of different languages and, so far (in context to what I'm experimenting with), it's feeling a bit like VBA except with having to build up the actions/functions that you feel should be already there. This is, I expect, just down to my own inexperience though.
I'm using Netbeans IDE 8.2 with Java Runtime 1.80.
I have created jFrame that contains a jTable. The jTable is built with data like so:
public void showTasks(Boolean removeID) {
ArrayList<Tasks> list = tasksList("SELECT * FROM tasks");
JTable table = jTable1;
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
Object[] row = new Object[4];
for(int i=0;i<list.size();i++) {
row[0]=list.get(i).getId();
row[1]=list.get(i).getName();
row[2]=list.get(i).getDesc();
row[3]=list.get(i).getDate();
model.addRow(row);
}
// Remove the 'id' column from the table view
if(removeID) { table.removeColumn(table.getColumnModel().getColumn(0)); }
}
The background behind this is less relevant, but essentially tasksList is a function that applies the query to an SQL statement, returning an ArrayList. I build up my rows with 4 columns, then remove the first column so 'ID' is available but not visible (this final action has been segregated through testing/experimentation).
I have another area of code that opens a jDialog when a row is clicked, in which it is possible to update the MySQL DB.
Problem
I'm trying to throw in a function call so that the table data 'refreshes' when the jDialog is closed. I have temporarily added in a button to the jFrame (where the jTable lives) to test/debug this function.
I can't seem to get this to work, though. The closest I have achieved is to re-call showTasks(false), but this obvious just adds rows with updated data, rather than replacing the dataset. I'm not 100% sure if deleting all the rows, then building them back in is 'best practice'.
As I'm new to Java, and may still be looking at it from a flawed method of thinking, I'm finding it difficult to apply any other examples to that of my own. I also can't seem to find a way to implement fireTableDataChanged().
Surely this is a simple concept I'm over-thinking?
Edit - based on below answer
Is there a reason why something like this would be considered incorrect, if deleting all rows and adding them back in is okay?
public void refreshTasks() {
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
int row_total = model.getRowCount();
for(int i= row_total -1;i>=0;i--) {
model.removeRow(i);
}
showTasks(false);
}
Edit: Button to invoke data update
Now works correctly (if not improperly) with the following:
private DefaultTableModel parentTable; // To store the parent 'Task' table model
public void setStart(int user,DefaultTableModel table) {
this.txt_taskID.setText(Integer.toString(user)); // Converts the ID to a string
addData(user); // Populates the fields
parentTable = table; // Sets parent TableModel to a variable
}
The above code is called from the Parent jFrame when the Dialog is opened, and passes the Table model and the 'ID' of the row I'm looking to edit. The table model is stored in parentTable.
There's also a 'Save' button, and a 'Cancel' button. I'm yet to separate these, and currently 'Save' does just that (SQL update and so on). My 'Cancel' button closes the dialog and refreshes the jTable, as per the below function:
private void btn_CancelActionPerformed(java.awt.event.ActionEvent evt) {
this.setVisible(false); // Hide the dialog
Menu menu = new Menu(); // for accessing the tasksList function
parentTable.setRowCount(0); // Clears the jTable data
// jTable data is then 'rebuilt' using the new data
ArrayList<Tasks> list = menu.tasksList("SELECT * FROM tasks");
Object[] row = new Object[4];
for(int i=0;i<list.size();i++) {
row[0]=list.get(i).getId();
row[1]=list.get(i).getName();
row[2]=list.get(i).getDesc();
row[3]=list.get(i).getDate();
parentTable.addRow(row);
}
}
I'm not 100% sure if deleting all the rows, then building them back in is 'best practice'.
Yes that is probably the best practice.
The only other approach is to create a completely new TableModel and add it to the table using the setModel() method. The problem with this approach is that it will reset any custom renderers/editors you may have set on the table.
The easiest way to remove all the rows from the DefaultTableModel is to just use:
model.setRowCount(0);
I'm not sure how you want to do it but I'm gonna give you simple example for deleting and refreshing JTable maybe it's help you.
This following btnDelete Jbutton added to JFrame for deleting rows from table:
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int rowIndex = table.getSelectedRow();
if(rowIndex > -1) {
int x = (Integer) table.getModel().getValueAt(rowIndex, 0);
if (conn.removeContact(x) == true) { //here add your own code like removeID
model.removeRow(rowIndex);
lblInfo.setText("Contact deleted successfully.");
model.fireTableDataChanged();
} else {
lblInfo.setText("Cannot remove at this time!");
}
}else {
lblInfo.setText("At first you need select a row with single click!");
return;
}
}
});
and these following codes for refreshing table in primitive way :
btnRefresh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int rowCount = model.getRowCount();
for (int i = rowCount - 1; i >= 0; i--) {//remove all rows
model.removeRow(i);
}
lblInfo.setText("Table datas updated successfully.");
for (Person p : conn.readAllContacts()) {//add all row from scratch
model.addRow(new Object[] { p.getId(), p.getName(), p.getLastName(), p.getPhone(), p.getEmail() });
}
}
});

Get the value of a specific cell of JTable with mouse clicking

I have a JTable and Given such codes:
jTable.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
System.out.println(jTable.getRowCount());
System.out.println(jTable.getModel().getValueAt(jTable.getRowCount(), 0));
}
});
If I click on a certain row, like in the picture above, I clicked the second row, how can I get that row's content?(How to get the Canada)?
Personally, I use the Mouse Clicked event. You could try something like this inside your event method:
private void myTableMouseClicked(java.awt.event.MouseEvent evt) {
int row = this.myTable.getSelectedRow();
int column = this.myTable.getSelectedColumn();
this.myTable.getValueAt(selectedRow, selectedColumn);
}
Be aware that the getValueAt method returns an Object. You probably will need to cast the Object returned into the object it is supposed to be. And also you could have a global variable that's going to have the value returned by getValueAt for using it as you need.
I hope it helps.

JTable - How to force user to select exactly one row

I have to implement a JTable in which exactly one row has to be selected (always). Empty selection is not allowed. I'm selecting the first row during initialization:
table.setRowSelectionInterval(0, 0);
additionally, I'm using
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
But user can still deselect one row using CLick + Ctrl.
What is the easiest way ensure, that one (exaclty) row is always selected in the table ?
If you have a JTable instance created, just use:
jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Now, you could add MouseListeners, SelectionListeners, KeyListeners and key bindings to try and solve this is issue. Or, you could go to the heart of the problem.
The ListSelectionModel is responsible for managing the selection details.
You could simply supply your own ListSelectionModel for the row selection
public class ForcedListSelectionModel extends DefaultListSelectionModel {
public ForcedListSelectionModel () {
setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
#Override
public void clearSelection() {
}
#Override
public void removeSelectionInterval(int index0, int index1) {
}
}
And simply set it to your table...
table.setSelectionModel(new ForcedListSelectionModel());
What is the easiest way ensure, that one (exaclty) row is always
selected in the table ?
there are three (basically) selection types
JTable.setRowSelectionAllowed(boolean);
JTable.setColumnSelectionAllowed(boolean);
JTable.setCellSelectionAllowed(boolean);
edit
works for me too
int row = table.getSelectedRow();
if ((row > -1)) {
table.setRowSelectionInterval(row, row);
}
}
I would use the JTable#setRowSelectionAllowed as it will ensure that a row can be selected.
This code changes it right back to the desired index and it gives the appearance to the user that it never updates.
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
table.setRowSelectionInterval(0,0);
}
);
First do
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setRowSelectionInterval(0, 0);
then set ListSelectionModel

How to get cell value of jtable depending on which row is clicked

I am trying to use an update method on my jtable that's connected to the database and would like to fill in the textfields on the form depending on which row the users clicks. I understand I will be needing a getValueAt() method however I am uncertain of how to fill in which row depending on which row the user clicks. I am unable to find anything on Google or anything so any information would be helpful!
private final UrTableModel urTableModel;
private JTable urTable;
...
// 1. Create your table model class that should extends from DefaultTableModel, instantiate it
urTableModel=new UrTableModel();
// 2. creates table
table = TableUtils.createStandardSortableTable(urTableModel);
// 3. customize your table
table.setBackground(Color.WHITE);
table.getTableHeader().setReorderingAllowed(false);
// 4. Add the mouse listner to it
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(final MouseEvent e) {
if (e.getClickCount() == 1) {
final JTable target = (JTable)e.getSource();
final int row = target.getSelectedRow();
final int column = target.getSelectedColumn();
// Cast to ur Object type
final UrObjctInCell urObjctInCell = (UrObjctInCell)target.getValueAt(row, column);
// TODO WHAT U WANT!
}
}
});
Cheers,
You will need to call getValueAt() your table's model to get the values you need. You will also need a listener on the table to listen for selections. So that once a user selects a row you call getValueAt() to get the value for the specific column of data in that row.

Adding CheckBox to DefaultTableModel

I have a DefaultTableModel which is populated with an Object[][] array.
Now I want to add a column with checkBoxes and perform operations accordingly.
When I add the checkbox into the Object[][] array and view it, I get text displayed
'javax.swing.JCheckBox[,0,0,0x0....', how do I get it to show a checkbox and add actions to it?
JTable have default checkbox renderer/editor for boolean values. Just make your TableModel#getColumnClass return Boolean.class for given column.
how do I get it to show a checkbox
See Uhlen's answer
and add actions to it?
Use a TableModelListener. Something like:
public void tableChanged(TableModelEvent e)
{
if (e.getType() == TableModelEvent.UPDATE)
{
int row = e.getFirstRow();
int column = e.getColumn();
if (column == ?)
{
TableModel model = (TableModel)e.getSource();
Boolean value = (Boolean)model.getValueAt(row, column));
if (value.booleanValue())
// add your code here
}
}
}
You could also just get the class, instead of hard coding each return type. Here is an example for the override method :
//create the table
DefaultTableModel tableModel = new DefaultTableModel(data, columnNames)
//override the method
{
public Class<?> getColumnClass(int colIndex) {
return getValueAt(0, colIndex).getClass();
}
Then, when you create the table you initialize it this way:
data[i][12] = new Boolean(false);
which makes the box appear unticked :)
You could use a custom table cell renderer.
See here
http://www.exampledepot.com/egs/javax.swing.table/CustRend.html
No you cannot provide swing component as model object[] array. That should be registered as cell editor on column.
Anyway by default DefaultTableModel supports checkbox as editor for columns under which Boolean class type values are stored.
So, in the array pass Boolean.TRUE/Boolean.FALSE object and set table as editable. Then table automatically renders checkbox for you.
Are you need to register editor for each class type

Categories

Resources