I want to remove a Selected row from a table in java.
The event should be performed on button click.
I will be thank full if someone helps...
For example there is a table named sub_table with 3 columns i.e sub_id, sub_name,class.
when I select one of the rows from that table and click delete button that particular row should be deleted..
It's very simple.
Add ActionListener on button.
Remove selected row from the model attached to table.
Sample code: (table having 2 columns)
Object[][] data = { { "1", "Book1" }, { "2", "Book2" }, { "3", "Book3" },
{ "4", "Book4" } };
String[] columnNames = { "ID", "Name" };
final DefaultTableModel model = new DefaultTableModel(data, columnNames);
final JTable table = new JTable(model);
table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
JButton button = new JButton("delete");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// check for selected row first
if (table.getSelectedRow() != -1) {
// remove selected row from the model
model.removeRow(table.getSelectedRow());
}
}
});
Related
On load, my JTable has 2 columns - . So its a string in the first column and a checkbox in the second column. When I click on the checkbox tableChanged is fired and I can print the row data that was selected.
I need to change the table data when user selects a new category in the dropdown.
When the table data is updated, and I click on the checkbox the tableChanged is no longer fired.
This is what I have:
This is how I am updating the table data:
comboBox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String t = (String) comboBox.getSelectedItem();
if (t.equals("survey2")) {
String[] columnNames = { "Volume Name", "Select" };
Object[][] data = { { "pt1", false }, { "pt2", false },
{ "pt3", false }, { "pt4", false },
};
model = new DefaultTableModel(data, columnNames);
table.setModel(model);
}
}
});
This is my tableChanged:
table.getModel().addTableModelListener(new TableModelListener() {
#Override
public void tableChanged(TableModelEvent e) {
if ((Boolean)table.getModel().getValueAt(table.getSelectedRow(), 1)) {
System.out.println(">\t"
+ table.getValueAt(table.getSelectedRow(), 0));
} else {
System.out.println(">\t"
+ table.getValueAt(table.getSelectedRow(), 0));
}
}
});
I do not understand why the event is not fired after updating the model. Am I updating the table incorrectly?
You area creating a new TableModel but you added the ChangeListener to the old TableModel.
Don't create a new TableModel!
You can clear the data by using setRowCount(0).
The you can add the new data back to the DefaultTableModel by using:
the setDataVector(...) method, or
by adding data back to the model one row at a time using the addRow(...) method.
So there is no need to create a new TableModel. If you want to create a new TableModel then you also need to add your ChangeListener to this new model.
I'm trying to implement a checkbox interface which allows a user to show/hide columns in a JTable, but when I remove the column, the column seems to move position and there is no way of knowing 100% where the columns are. The table is built with this code:
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
String[] columnNames = {"Artist","Track","Album","Genre","Year","Filetype"};
for (String column : columnNames) {
model.addColumn(column);
}
table.createDefaultColumnsFromModel();
table.getTableHeader().setReorderingAllowed(false);
Here's the code I have for implementing the checkbox listeners:
if (e.getSource() == artist) {
if (!artist.isSelected()) {
table.removeColumn(table.getColumnModel().getColumn(0));
} else {
table.addColumn(table.getColumnModel().getColumn(0));
}
}
if (e.getSource() == trackName) {
if (!trackName.isSelected()) {
table.removeColumn(table.getColumnModel().getColumn(1));
} else {
table.addColumn(table.getColumnModel().getColumn(1));
}
}
/* etc */
You can to use the Table Column Manager.
It will manager the hiding/showing of the table columns for you.
I am having a main class which controls all the application, including the displaying of all the panels. The method to display the main application panel is:
private void displayMainApplicationPanel() {
String[] columnNames = { "Media ID", "Title", "Pricipal Actors", "Type", "Duration", "Launch Date", "Price",
"Status" };
ResultSet resultSet = databaseLogicController.showMediaInfo();
String[][] data = parseMediaResultSet(resultSet, 8);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
graphicController.showMainApplicationPanel(data, columnNames);
addMainApplicationPanelSearchButtonActionListener();
addMainApplicationPanelSearchTextFieldKeyListener();
addMainApplicationPanelShowMyIdButtonActionListener();
addMainApplicationPanelBorrowMediaButtonActionListener();
addMainApplicationPanelMakeInternetRezervationButtonActionListener();
addMainApplicationPanelShowVHSInformationButtonActionListener();
addMainApplicationPanelShowDVDInformationButtonActionListener();
addMainApplicationPanelShowInternetRezervationsActionListener();
addMainApplicationPanelShowClientsInformationButtonActionListener();
addMainApplicationPanelInsertClientButtonActionListener();
addMainApplicationPanelInsertMovieButtonActionListener();
addMainApplicationPanelInsertVHSButtonActionListener();
addMainApplicationPanelInsertDVDButtonActionListener();
}
});
}
On that main panel, I have a table which shows all the current medias. I want to be able to update that table via a search function.
The code for the search button action listener is:
private void addMainApplicationPanelSearchButtonActionListener() {
graphicController.getMainApplicationPanel().addSearchButtonActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String[] columnNames = { "Media ID", "Title", "Pricipal Actors", "Type", "Duration", "Launch Date", "Price",
"Status" };
String title = graphicController.getMainApplicationPanel().getSearchTextField().getText();
ResultSet resultSet = databaseLogicController.showParticularMediaInfo(title);
String[][] data = parseMediaResultSet(resultSet, 8);
graphicController.getMainApplicationPanel().setMediaTable(new JTable(data, columnNames));
graphicController.getMainApplicationPanel().repaint();
graphicController.getMainApplicationPanel().revalidate();
graphicController.getMainFrame().repaint();
graphicController.getMainFrame().revalidate();
}
});
}
Now, I create a new table in the action listener based on the search criteria and set it in the main application panel, followed by calls to repaint and revalidate on both the main frame and the main panel. Why isn't the new table shown?
Now, I create a new table in the action listener based on the search criteria
Don't create a new table. The easiest approach is to update the existing table with a new TableModel:
table.setModel(...);
I don't recommand you using this line
graphicController.getMainApplicationPanel().setMediaTable(new JTable(data, columnNames));
You can better get that table then ((DefaultTableModel)myTable.getModel()).setRowCount(0); and ((DefaultTableModel)myTable.getModel()).addRow(new Object[]{data1, data2, ...});
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(...).
I'm trying to use a JTable in order to update users in a Java SWING application, currently when I edit a cell the results of the edit can only be obtained if I click a different cell thus firing the tableModelListener. I want to be able to get these changed values on a button event without clicking other cells.
My table definitions:
DefaultTableModel tableModel = new DefaultTableModel();
table = new JTable(tableModel);
tableModel.addColumn("Key");
tableModel.addColumn("Value");
if (PatientView.getSelected() != null){
tableModel.addRow(new Object[]{"Name", PatientView.getSelected().getName()});
tableModel.addRow(new Object[]{"Age", PatientView.getSelected().getAge()});
tableModel.addRow(new Object[]{"Height", PatientView.getSelected().getHeight()});
tableModel.addRow(new Object[]{"Weight", PatientView.getSelected().getWeight()});
tableModel.addRow(new Object[]{"BMI", PatientView.getSelected().getCalculatedBMI()});
}
Table Listener
tableModel.addTableModelListener(new TableModelListener(){
#Override
public void tableChanged(TableModelEvent arg0) {
int row = arg0.getFirstRow();
int column = arg0.getColumn();
Object data = tableModel.getValueAt(0, 1);
System.out.println(data);
}
});
Button Action Listener
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Vector data = tableModel.getDataVector();
System.out.println(table.getValueAt(0, 1));
System.out.println(data);
}
});
I want to be able to get these changed values on a button event without clicking other cells.
See Table Stop Editing.