Java - delete selected row from tablemodel - java

I need delete deleted row from my arraylist...
private GuiIO guiIO;
private DefaultTableModel tableModel;
private List<Book> zoz;
public MyGui() {
initComponents();
this.setLocationRelativeTo(this.getRootPane());
this.guiIO = new GuiIO();
tableModel = new DefaultTableModel(new String[]{"Znacka", "Model", "Najazdene", "Rok vyroby", "Vykon", "Cena"}, 0);
this.tblTabulka.setModel(tableModel);
this.tblTabulka.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
tblTabulka.setAutoCreateRowSorter(true);
TableRowSorter rowSorter = new TableRowSorter(tableModel);
zoz = guiIO.getAllBook();
}
my function for delete row from model:
private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {
final int sectedRowIndex = this.tblTabulka.getSelectedRow();
this.tableModel.removeRow(sectedRowIndex);
zoz = guiIO.getAllBook();
}
public List getAllBook() {
List all_book = new ArrayList<Book>();
for (Containerable item = this.book.getFirst();
item!=null;
item = this.book.getNext())
all_book.add(item);
return all_book;
}
but i need delete it from my private List zoz;
how can i do it?

I need delete it from my private List zoz?
zoz.remove(sectedRowIndex); // if table is not sortable
Note:
Do not initialize the list again after deleting the selected row.
DefaultTableModel is not populating from the list
put a check tblTabulka.getSelectedRow() != -1 before deleting the row whether row is selected or not?
Use Map instead of List something like
Map<String,Book> books = new HashMap<String,Book>();
where you can make isbn or id as key.
Sample code:
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// check for selected row first
if (tblTabulka.getSelectedRow() != -1) {
// get value of first cell of selected row
String isbn= (String)tableModel.getValueAt(tblTabulka.getSelectedRow(), 0);
books.remove(isbn);
// remove from the model also
model.removeRow(tblTabulka.getSelectedRow());
}
}
});

Related

Adding JComboBox to JTable: ComboBoxes in different rows are not independent

I have a table with a combobox where the user can select a country. I have the problem, that comboBoxes in each row are not independent of each other. When I select an item in row A and then click on the comboBox in row B, the ComboBox B are automatically set to the same value as comboBox A.
Code:
DefaultTableModel model = new DefaultTableModel();
//Creating the Headers
ArrayList<Adress> adressList = customer.getAdressList();
//customer.getAdressList() is an ArrayList, which has been populated from SQL
model.addColumn("ID");
model.addColumn("Country");
//Iterate through Adresses of current Customer and fill JTable
for(Iterator<Adress> iterator = adressList.iterator(); iterator.hasNext();){
Adress adress = iterator.next();
Object[] data = new Object[2];
data[0] = adress.getID();
data[1] = adress.getCountry();
model.addRow(data);
}
//Populate combobox with values from an enum
JComboBox country_comboBox = new JComboBox(CountryEnum.values());
// Set Model, Renderer and Editor
table.setModel(model);
table.getColumnModel().getColumn(1).setCellRenderer(new JComboBoxCountryRenderer(country_comboBox));
table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(country_comboBox));
and the Renderer:
public class JComboBoxCountryRenderer extends JComboBox implements TableCellRenderer{
CountryEnum country;
public JComboBoxCountryRenderer(JComboBox comboBox) {
if (comboBox != null) {
this.setModel(comboBox.getModel());
this.setSelectedIndex(comboBox.getSelectedIndex());
}
}
#Override
public Component getTableCellRendererComponent(JTable arg0, Object value, boolean arg2, boolean arg3, int arg4,
int arg5) {
if (value instanceof CountryEnum) {
this.setSelectedItem((CountryEnum) value);
}
return this;
}
}
You use JCombobox as the renderer, try using as an editor instead...
See this example from Oracle.

Is there a way to put an ArrayList into a JTable where each line is the next index of the ArrayList?

I have many different array lists. I want each index to be a new row in the JTable but I'm not sure how to do that. I made a for loop but it is not working.
Is there even a way to populate a JTable with an array list and not an array?
public TableCreator() {
super(new GridLayout(1,0));
String[] columnNames = {"Item Type",
"Description",
"Size",
"Price"};
// for(int i=0; i<ShoppingFunctions.cartType.size(); i++){
for(int i=0; i<GUI.size.size(); i++){//FIX!!!!
item = ShoppingFunctions.cartType.get(i)+"\n";
described = GUI.describe[GUI.imageNum];
sizes = GUI.size.get(i);
price = ShoppingFunctions.cartPrice.get(i)+"\n";
}//end of for
Object[][] data = {{item, described, sizes, price}};
final JTable table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
if (DEBUG){
table.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
printDebugData(table);
}//end of method
});//end of listener
}//end of if
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
}//end of method
The simple answer is to create your own, based on something like AbstractTableModel
For example...
public abstract class AbstractGenericTableModel<R> extends AbstractTableModel {
protected ArrayList<R> rows;
protected List columnIdentifiers;
public AbstractGenericTableModel() {
this(0, 0);
}
public AbstractGenericTableModel(int rowCount, int columnCount) {
this(new ArrayList(columnCount), rowCount);
}
public AbstractGenericTableModel(List columnNames, int rowCount) {
setData(new ArrayList<>(rowCount), columnNames);
}
public AbstractGenericTableModel(List<R> data, List columnNames) {
setData(data, columnNames);
}
public List<R> getRowData() {
return rows;
}
private List nonNullVector(List v) {
return (v != null) ? v : new ArrayList();
}
public void setData(List<R> data, List columnIdentifiers) {
this.rows = new ArrayList<>(nonNullVector(data));
this.columnIdentifiers = nonNullVector(columnIdentifiers);
fireTableStructureChanged();
}
public void addRow(R rowData) {
insertRow(getRowCount(), rowData);
}
public void insertRow(int row, R rowData) {
rows.add(row, rowData);
fireTableRowsInserted(row, row);
}
/**
* Removes the row at <code>row</code> from the model. Notification of the row being removed will be sent to all the listeners.
*
* #param row the row index of the row to be removed
* #exception ArrayIndexOutOfBoundsException if the row was invalid
*/
public void removeRow(int row) {
rows.remove(row);
fireTableRowsDeleted(row, row);
}
public void setColumnIdentifiers(List columnIdentifiers) {
setData(rows, columnIdentifiers);
}
#Override
public int getRowCount() {
return rows.size();
}
#Override
public int getColumnCount() {
return columnIdentifiers.size();
}
#Override
public String getColumnName(int column) {
Object id = null;
// This test is to cover the case when
// getColumnCount has been subclassed by mistake ...
if (column < columnIdentifiers.size() && (column >= 0)) {
id = columnIdentifiers.get(column);
}
return (id == null) ? super.getColumnName(column)
: id.toString();
}
}
public class ArrayListTableModel extends AbstractGenericTableModel<ArrayList> {
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
List<ArrayList> rows = getRowData();
return rows.get(rowIndex).get(columnIndex);
}
}
This creates two classes, an "abstract generics" based model, which allows you to specify the physical data which backs a row and a ArrayListTableModel which allows you to use a ArrayList for the individual data.
What this assumes though, is each row has the same number of elements, but it makes no checks
I suggest you have a closer look at How to Use Tables for more details
You can use the List Table Model. It will support rows of data stored in an ArrayList, Vector or any other class that implements the List interface.
The ListTableModel is also based on a generic TableModel that allows you to add Objects to a row in the model. There are many row based methods that allow easy usage of the model
The ListTableModel provides methods that allow you to easily customize the model:
setColumnClass – specify the class of individual columns so the proper renderer/editor can be used by the table.
setModelEditable – specify editable property for the entire model.
setColumnEditable – specify editable property at a column level. This property will have preference over the model editable property.
The other option is to iterate through the ArrayList and copy each row of data to a Vector and then add the Vector to the DefaultTableModel using the addRow(...) method.

Garbage value in jtable after adding row dynamically

I have JTable which has few columns.In that I have JComboBox. At program start I want them to be empty.I have one JButton on click action of button i have the code to add row dynamically in table.
But after adding the row i get garbage value in the cell having JComboBox. As shown in below figure :
And here is the code :
Code to add JComboBox in table
// Create columns names
String columnNames[] = { "Item", "Sun Item", "Required Quantity","Price","Gross Amount" };
// Create some data
final String dataValues[][] =
{
{ "", "", "","","", },
};
tableModel = new DefaultTableModel(dataValues, columnNames);
// Create a new table instance
table = new JTable( tableModel );
updateItemCombo();
TableColumn itemColumn = table.getColumnModel().getColumn(0);
itemColumn.setCellEditor(new DefaultCellEditor(comboItem));
public void updateItemCombo(){
Vector<String> s = new Vector<String>();
try{
setConnectin();
String str = "select * from ItemTable";
stmt = conn.createStatement();
rs = stmt.executeQuery(str);
while(rs.next())
{
String nm = rs.getString("Item_Name");
s.add(nm);
}
conn.close();
}catch(Exception e2){
e2.printStackTrace();
}
DefaultComboBoxModel<String> modelData = new DefaultComboBoxModel<String>(s);
comboItem.setModel(modelData);
}
Code to add row dynamically on button click :
btnAddOrder.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
tableModel.addRow(dataValues);
tableModel.fireTableDataChanged();
}
});
What should i do to remove this garbage value from table? Please help
The addRow(...) method takes a 1-Dimensional array as a parameter. You are attempting to add a 2-Dimensional array.
Also, do not use:
tableModel.fireTableDataChanged();
it is the job of the TableModel to invoke the appropriate fireXXX() method, which by the way in this case would be fireTableRowsInserted(...).

have problems in Linking multiple JComboBox in JTable one time

I got a quite tricky problem when I do some code on JTable
I need to add one line In JTable when I click "Add" button, and I want one of the columns to render
as a JComboBox
the problem is that when I only add one line, it works fine.
but when I add multiple lines a time, no matter which combobox I choose item from, It will always trigger the last comboBox's event(seems always the same combobox since I have printed the hashcode of jComboBox in MyComboxActionListener class. it's the same).
why is that happens , I can't figure it out. Since It's totally a new comboBox and a new listener when I add one line.
Following is the code.
Thanks in advance.
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
ProducedProcedure_new addedProducedProcedure = new ProducedProcedure_new(); // the new item
componentProcedureTableModel.getWorks().add(addedProducedProcedure); //add one line to the table
componentProcedureTableModel.fireTableRowsInserted(componentProcedureTableModel.getRowCount()-1, componentProcedureTableModel.getRowCount()-1);
jTable1.changeSelection(componentProcedureTableModel.getRowCount()-1,0, false, false);
List<String> procedureNames = produceCardManager.getProcedureNames(componentIdTextField.getText().trim(),false); //get the items added to combobox
renderColumnAsCombox(1,procedureNames,addedProducedProcedure); //-------------------------------------------
}
void renderColumnAsCombox(int columnIndex , List<String> items,ProducedProcedure_new producedProcedure) {
TableColumn col = jTable1.getColumnModel().getColumn(columnIndex);
JComboBox comboBox = new JComboBox();
for(String item : items) {
comboBox.addItem(item);
}
MyComboxActionListener myComboxActionListener = new MyComboxActionListener(columnIndex,comboBox,producedProcedure);
comboBox.addActionListener(myComboxActionListener);
col.setCellEditor(new DefaultCellEditor(comboBox));
}
class MyComboxActionListener implements ActionListener { // listen for the select event of the combobox
private JComboBox jComboBox;
private ProducedProcedure_new producedProcedure;
private int columnIndex;
public MyComboxActionListener(int columnIndex,JComboBox jComboBox,ProducedProcedure_new producedProcedure) {
this.columnIndex = columnIndex;
this.jComboBox = jComboBox;
this.producedProcedure = producedProcedure;
}
#Override
public void actionPerformed(ActionEvent e) {
String selectedItem = (String)jComboBox.getSelectedItem();
producedProcedure.getProcedure().setProcedureName(selectedItem);
producedProcedure.getProcedure().setProcedureId(String.valueOf(produceCardManager.getProcedureId(selectedItem)));
producedProcedure.getProcedure().setFactor(produceCardManager.getProcedureFactor(selectedItem)); //automately update the factor
((ComponentProcedureTableModel_new)jTable1.getModel()).fireTableDataChanged();
}
}

How to update the view of JTable after adding a new row?

This is my TableModel, I have extended AbstractTableModel
class CustomTableModel extends AbstractTableModel
{
String[] columnNames = {"Name","Contact","eMail","Address","City","Pin","State","Type","ID"};
Vector<String[]> data = new Vector<String[]>();
CustomTableModel()
{
try
{
//Using JDBC connection//
while(rs.next())
{
String[] s=new String[9];
s[0]=rs.getString(1);
//System.out.println(s[0]);
s[1]=rs.getString(2);
s[2]=rs.getString(3);
s[3]=rs.getString(4);
s[4]=rs.getString(5);
s[5]=rs.getString(6);
s[6]=rs.getString(7);
s[7]=rs.getString(8);
s[8]=rs.getString(9);
data.add(s);
}
}
catch(Exception e)
{
System.out.println("the exception is :"+e.toString());
}
}
public int getColumnCount() {
int columnCount = columnNames.length;
return columnCount;
}
public int getRowCount() {
int rowCount = data.size();
return rowCount;
}
public Object getValueAt(int rowIndex, int columnIndex) {
return data.get(rowIndex)[columnIndex];
}
public String getColumnName(int column) {
return columnNames[column];
}
public void removeRow(int r)
{
for(int i=0;i<data.size();i++)
{
String[] s = (String[])data.get(i);
if(s[0]==getValueAt(r,0))
{
try
{
//using JDBC connections to delete the data from DB//
//also removing the value from data and also updating the view//
data.remove(data.get(i));
fireTableRowsDeleted(r, r);
}
catch (Exception e)
{
System.out.println(e.toString());
}
break;
}
}
}
//I am using the following code to update the view but it doesnot work//
public void addRow(String[] a)
{
data.add(a);
fireTableRowsInserted(data.size() - 1, data.size() - 1);
}
}
I have a table class which extends CustomTableModel .
class table extends CustomTableModel
{
final JButton editButton = new JButton("Edit");
final JButton deleteButton = new JButton("Delete");
final JTable mytable = new JTable(new CustomTableModel());
.
.
.
}
I have a add button , and in its action listener i use the following code to pass the values that i wanted to add.
String[] a = {"a","b","c","d","e","f","g","h","i"};
table myTableObj = new table();
myTableObj.addRow(a);
Pls let me know where i am going wrong . Thanks
Pls let me know where i am going wrong . Thanks
String[] a = {"a","b","c","d","e","f","g","h","i"};
table myTableObj = new table();
myTableObj.addRow(a);
code lines talking about
create a new row
create a new JTable
row is added to a new JTable
result is that a new JTable is never added to visible Swing GUI
don't do that, why is a new JTable recreated on every JButtons event
add String[] a... to the CustomTableModel directly
for better help sooner post an SSCCE, short, runnable, compilable
The table class makes no sense. It is supposed to be a TableModel that shoud be set into a JTable. Instead you have JTable declared as a field inside this table class (which should be Table btw according to Java naming convention). The result is that when constructing a new table object, a JTable is constructed inside it with another CustomTableModel inside. So the tableModel you are adding rows into is not the tableModel actually used by your JTable.
You can also use the myCustomTable.fireTableStructureChanged();

Categories