I have a jButton and when it is clicked currently I can select multiple rows and I am able to delete all of them. I am trying to make a message pop up if no row is selected to warn the user. I tried different things, but I couldn't manage it in the end unfortunately.
private void silButtonActionPerformed(java.awt.event.ActionEvent evt) {
try {
int[] selectedItems = jTable2.getSelectedRows();
for (int i = 0; i < selectedItems.length; i++) {
String cell = (jTable2.getModel().getValueAt(selectedItems[i], 0)).toString();
System.out.println(cell);
String query="DELETE FROM Musteriler WHERE id="+cell+"";
PreparedStatement pst = connection.prepareStatement(query);
int rs = pst.executeUpdate();
}
loadTable();
cleanFields();
} catch (Exception e) {
System.out.println(e);
}
}
Simply just test that selectedItems length is zero or not:
if(selectedItems == null || selectedItems.length() < 1) {
showPopup();
}
API reference:
public int[] getSelectedColumns​()
Returns:
an array of integers containing the indices of all selected columns, or an empty array if no column is selected.
Basically you should check if the selectedItems is empty and show your modal dialog.
Related
I have a JTable which has 2 columns
column 0 username
column 1 password.
for the password column it will be encrypted to SHA256.
Basically what I want to achieve is it will update all the rows in my password column to SHA256 that I have edited after my button is pressed.
so..
I have a RowData class, this will store the text being edited and the position of the text
being edited(rows,columns).
public class RowData {
int rows = 0, columns = 0;
String text = " ";
public RowData(String text,int rows, int columns) {
setEditedRows(rows);
setEditedColumns(columns);
setEditedText(text);
}
public int getEditedRows() {
return rows;
}
public int getEditedColumns() {
return columns;
}
public String getEditedText() {
return text;
}
public void setEditedRows(int rows) {
this.rows = rows;
}
public void setEditedColumns(int columns) {
this.columns = columns;
}
public void setEditedText(String text) {
this.text = text;
}
}
I wrote a TableModelListener.. I have an List to store the text and the rows and columns
after the table has changed
table.getModel().addTableModelListener(new TableModelListener() {
#Override
public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
int column = e.getColumn();
TableModel model = (TableModel) e.getSource();
//System.out.println(model.getValueAt(row, column));
if(column == 1) {
String data = (String) model.getValueAt(row, column);
System.out.println(data);
dataList.add(new RowData(data,row,column));
}
}
});
In my button I loop through the list and retrieve the rows, and columns and text
and set the password to SHA256 to the JTable.
updateBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
if (table.getCellEditor() != null) {
table.getCellEditor().stopCellEditing();
for(int i = 0; i < dataList.size(); i++) {
String text = dataList.get(i).getEditedText();
int rows = dataList.get(i).getEditedRows();
int columns = dataList.get(i).getEditedColumns();
//System.out.println(dataList.get(i).getEditedText() + " " + dataList.get(i).getEditedRows() + dataList.get(i).getEditedColumns());
table.setValueAt(convertPassword.convertToSHA256(text), rows ,columns);
}
}
}
});
The result I get is I will keep printing the password endlessly in my console.
So I think that my logic is wrong and needed to be corrected.
table.setValueAt(convertPassword.convertToSHA256(text), rows ,columns);
When you change the TableModel the TableModelListener will be invoked again. The TableModelListener is invoked whether you change the data by using the JTable or by updating the TableModel directly.
The solution would be to remove the TableModelListener when you click on your button, at the start of your ActionListener. You would then need to add the TableModelListener back to the TableModel at the end of the code in case the user make further changes.
Another solution is to have 3 columns in the TableModel, username, password and sha256Password. Then you can use the JTable to display only the first two columns. See the removeColumn() method of JTable. Then your conversion code would update the TableModel using:
table.getModel().setValueAt(value, row, 2);
Now the code in your TableModel will be invoked, but because you check for updates to column 1, nothing will happen when you update column 2.
Then when you save the data you save the data from the TableModel.
Edit:
I must click into another cell before I can press my button to edit.
You need to stop the cell editing. See Table Stop Editing for a couple of solutions.
I have a button click event on which i am getting a column value, if a Table row is selected. But if i don't select the row and click the button i get the error: java.lang.ArrayIndexOutOfBoundsException:-1 my question is how can i check to see if a row has been selected pseudocode: if(Row == selected) { execute }
java code i have:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try
{
int row = Table.getSelectedRow();
String Table_click = (Table.getModel().getValueAt(row, 0).toString());
//... implementation hire
} catch (Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
Thank you for your help.
Stop and think logically about your problem before you're tempted to post. Take a break from coding if you need to -- once you take a break, the solution to the problem often presents itself in short order.
int row = Table.getSelectedRow();
if(row == -1)
{
// No row selected
// Show error message
}
else
{
String Table_click = (Table.getModel().getValueAt(row, 0).toString());
// do whatever you need to do with the data from the row
}
When no row is selected, getSelectedRow() returns -1.
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try {
int row = Table.getSelectedRow();
if (row > -1) {
String Table_click = (Table.getModel().getValueAt(row, 0).toString());
//... implementation here
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
if row > -1 then you know a row has been selected.
see: http://docs.oracle.com/javase/7/docs/api/javax/swing/JTable.html#getSelectedRow()
How to prevent duplicate entries in JTable?
I want to stop enter duplicate data in table. I tried given below cord. But it is not working. My first column name is item id. So I used jtable.getValueAt(i, 1). It that wrong.
public void lordTable(JTable jtable, JTextField txtItemID, JTextField txtName, JTextField txtQty, JTextField txtUp) {
String s = "";
boolean exists = false;
for (int i = 0; i < jtable.getRowCount(); i++) {
s = jtable.getValueAt(i, 1).toString().trim();
if (txtItemID.getText().equals("")) {
JOptionPane.showMessageDialog(null, "Enter Invoice Details First");
} else {
if (txtItemID.getText().equals(s)) {
exists = true;
break;
}
}
}
if (!exists) {
DefaultTableModel dd = (DefaultTableModel) jtable.getModel();
Vector v = new Vector();
v.add(txtItemID.getText());
v.add(txtName.getText());
v.add(txtQty.getText());
v.add(txtUp.getText());
Double val = (Double.parseDouble(txtUp.getText())) * (Double.parseDouble(txtQty.getText()));
v.add(val);
dd.addRow(v);
} else {
JOptionPane.showMessageDialog(null, "data already exist.");
}
}
Access first column in a table with zero, that is: getValueAt(row, 0).
i have create student table like following fields Stuid, studname, mark1,mark2 in Mysql Database. and also create a table using JFrame( source,design) after that i wrote the following code in source side, then drag the table from the Swing controls.
public void DbConnection(){
try
{
Class.forName("com.mysql.jdbc.Driver");//Connection establishment to the database
String username = "root";
String password = "root";
String Database = "jdbc:mysql://localhost:3306/project";
Conn = DriverManager.getConnection( Database, username, password );
System.out.println("*** Connect to the database ***");
String Query = "Select * from StudentMaster";
Statement smnt = Conn.createStatement();
ResultSet results = smnt.executeQuery( Query );
ResultSetMetaData metaDt = results.getMetaData();
System.out.println(metaDt);
int cols = metaDt.getColumnCount();
for(int i=1;i<cols;i++){
columnNames.addElement (metaDt.getColumnName(i));
}
while(results.next()){
Vector row= new Vector(cols);
for(int i=1;i<=cols;i++){
row.addElement(results.getObject(i));
}
data.addElement(row);
}
results.close();
smnt.close();
Conn.close(); //Close Connection to the database
}
catch(Exception e)
{
System.out.println(e);
}
}
it's connecting with Mysql Database, but it's not showing the DBtable value in Jframe Table. how i can get the value in table(Jframe table control) without creating a code for table. if i double click on table i don't know where i write table code.
If you are using NetBeans it is easy
Step 1
right click on javaApplication in project window
Select New > Others > Persistence ->(Right Side) Entity Classes From Database [Select]
Click Next
Now Select Database Connection from ComboBox and Add database table you want to bind with jTable from 'Available Tables' listbox to 'Selected tables' listbox
Finish
Here you made a class which you can bind with your jTable
Step 2
Right Click on your jTable
Select Binding
Click on elements [it will open 'Bind jTable.element' window]
There click on 'Import Data from Form' named Button
Select Database and Table from given ComboBoxes and click OK
Now There you can see two list boxes named as 'Available' and 'Selected' in Selected List Box there you can see all attributes of your database table listed.
If you want to remove any attribute from this just select that and click '<<' button
Re Arrange attributes using 'up' and 'down' buttons
Click OK now you can see your jTable bound With database
Finished
This is an easy way to achieve your homework, by creating a reusable TableModel able to display content of any ResultSet:
public class MyModel extends AbstractTableModel {
String[] headers = {};
ArrayList<String[]> rows;
public MyModel() {
rows = new ArrayList<String[]>();
}
public int getColumnCount() {
return headers.length;
}
public Object getValueAt(int row, int col) {
if (row < 0 || row >= rows.size()) return "N/A";
if (col < 0 || col >= headers.length) return "N/A";
return rows.get(row)[col];
}
public int getRowCount() {
return rows.size();
}
public String getColumnName(int col){
if (col < 0 || col >= headers.length) return "N/A";
return headers[col];
}
public void fill(ResultSet rs) {
//Setting Headers
ResultSetMetaData md = rs.getMetaData();
int cols = md.getColumnCount();
headers = new String[cols];
for(int i = 1; i < cols; i++) {
headers[i - 1] = md.getColumnName(i);
}
// Setting rows
rows.clear();
while(rs.next()) {
String[] row = new String[cols];
for(int i = 1; i < cols; i++) {
row[i - 1] = rs.getString(i);
}
rows.add(row);
}
this.fireTableDataChanged();
}
}
Hope it helps, good luck!
I can tell on button and window is opened.
{
try
{
Class.forName("java.sql.DriverManager");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/project","root","tiger");
sql="select * from (table name)";
Statement st=con.createStatement();
ResultSet rs=st.executeQuery(sql);
jdis.getModel();
}
catch(Exception e)
{JOptionPane.showMessageDialog(null,e.getMessage());}
}
}
I am doing a project in java swing in which I have to use a JTable.
By default jtable can validate the inputs (float,int) by turning into red when wrong input is given.
But I want to validate the empty cell left in the table at the time of save button click.
Here is my code:
public boolean validCheck() {
if (jTable.getCellEditor() != null) {
jTable.getCellEditor().stopCellEditing();
}
for (int i = 0; i < jTable3.getRowCount(); i++) {
for (int j = 0; j < jTable3.getColumnCount(); j++) {
String val = jTable3.getValueAt(row, col).toString();
if (val.trim().length() == 0) {
return false;(joptionpane.showmessagedialog(null,"field empty");)
}
}
}
return true;
}
This code is checking all the rows in the table and displaying the field empty message. I need to check only filled rows(rows which have data) not all the rows in the jtable.
Any suggestions would be helpful.
You need to change your logic to first look if a row had data at all. Then (and only then), take a second pass to validate that all columns in that row are filled.