I have one table where it shows some data from sql server and when I click it it also shows data on text fields that gets it directly from the table. But once I click one row on the table it remains clicked until the frame is closed. How can I disable it? Heres my code on click event.
int rowIndex;
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {
rowIndex = jTable1.getSelectedRow();
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
if(model.getValueAt(rowIndex, 3).toString().equals("Mashkull "))
{
jRadioButton1_mashkull1.setSelected(true);
jRadioButton2_femer1.setSelected(false);
} else {
jRadioButton2_femer1.setSelected(true);
jRadioButton1_mashkull1.setSelected(false);
}
jTextField1_id1.setText(model.getValueAt(rowIndex, 0).toString());
jTextField1_emri1.setText(model.getValueAt(rowIndex, 1).toString());
jTextField1_mbiemri2.setText(model.getValueAt(rowIndex, 2).toString());
jTextField1_nrtel1.setText(model.getValueAt(rowIndex, 5).toString());
jTextArea1_adresa1.setText(model.getValueAt(rowIndex, 6).toString());
Date bdate;
try {
bdate= new SimpleDateFormat("yyyy-MM-dd").parse(model.getValueAt(rowIndex, 4).toString());
jDateChooser1_data1.setDate(bdate);
} catch (ParseException ex) {
Logger.getLogger(kontrollostudentet.class.getName()).log(Level.SEVERE, null, ex);
}
}
You can make a call to clearSelection() right after getting the row index.
public void clearSelection()
Deselects all selected columns and rows.
Related
How can I remove a row from database using Mysql database using JTable. What I'm trying to do is when user select the row and click delete button I want to delete that row from data base.
private void deleteItemBtn1ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel) jTable2.getModel();
try{
if(jTable2.getSelectedRowCount()== 1){
int SelectedRowIndex = jTable2.getSelectedRow();
int row = jTable2.getSelectedRow();
String eve = model.getValueAt(row, 4).toString();
expenseDAO.deleteRow(eve);
model.removeRow(SelectedRowIndex);
}else{
if(jTable2.getRowCount()==0){
JOptionPane.showMessageDialog(this,"Table is Empty");
}else{
JOptionPane.showMessageDialog(this,"Please slelect s ingle row for Delete");
}
}
}catch(Exception ex){
JOptionPane.showMessageDialog(null, ex);
}
}
This is my deleteRow method :
public void deleteRow(String value){
String query = "DELETE FROM expense WHERE ex_id ="+value;
Statement st;
try {
st = con.createStatement();
st.executeQuery(query);
} catch (SQLException ex) {
Logger.getLogger(ExpenseDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
This code not working.
I want to update my table right after clicking on a diffrent item in combobox. After adding actionPerformed combobox shows only the first item and the arrow doesn't work. I'm updating my table after selecting a diffrent item and clicking a button. Action perform in a button does work. Am I using the actionPerformed incorrectly?
Here is a code how I add items to a combobox.
private void fillComboBox() {
try {
DatabaseMetaData meta = (DatabaseMetaData) conn.getMetaData();
rs = meta.getTables("db", null, null, new String[] {
"TABLE"
});
while (rs.next()) {
ComboBox.addItem(rs.getString("TABLE_NAME"));
}
} catch(Exception e) {
JOptionPane.showMessageDialog(null,e);
}
}
Here is how I fill the table.
private void fillTable()
{
String selectedValue = ComboBox.getSelectedItem().toString();
String sql = "Select * from "+selectedValue;
Statement stmt;
try {
stmt = conn.createStatement(rs.TYPE_SCROLL_INSENSITIVE,rs.CONCUR_UPDATABLE);
rs = stmt.executeQuery(sql);
Table.setModel(DbUtils.resultSetToTableModel(rs));
} catch (SQLException ex) {
Logger.getLogger(Welcome.class.getName()).log(Level.SEVERE, null, ex);
}
}
And after clicking a button, I update the table
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
fillTable();
}
Works fine, but I would like to update the table right after clicking on a new item in combobox.
Edit: I fixed it by adding fillComboBox() after fillTable(). But now I have two first items in combobox even after removeAll(). How do I fix it?
public Welcome() {
initComponents();
conn = MySqlConnect.ConnectDB();
fillComboBox();
fillTable();
ComboBox.removeAll();
fillComboBox();
repaint();
}
I always change contents of a ComboBox dynamically by using the underlying Model, not through the actual ComboBox. After your GUI is already shown, I think this matters ... using the model, not the JComboBox itself.
...
final var model = new DefaultComboBoxModel<String>();
while (rs.next()) {
model.addElement(rs.getString("TABLE_NAME"));
}
...
ComboBox.setModel(model);
Why my JTable row is not selected at first click? It is selected every time after first click. What is the problem?
I need to get all the values from the row which is clicked. Here is my code. It works well from second click.
private void tblAccountInfoMouseReleased(java.awt.event.MouseEvent evt) {
try {
DefaultTableModel model = (DefaultTableModel) tblAccountInfo.getModel();
txtUserName.setText(model.getValueAt(tblAccountInfo.getSelectedRow(), 0).toString());
try {
txtPassword.setText(model.getValueAt(tblAccountInfo.getSelectedRow(), 1).toString());
} catch (NullPointerException npe) {
}
try {
txtType.setText(model.getValueAt(tblAccountInfo.getSelectedRow(), 2).toString());
} catch (NullPointerException npe) {
}
try {
txtUrl.setText(model.getValueAt(tblAccountInfo.getSelectedRow(), 3).toString());
} catch (NullPointerException npe) {
}
updateId = tblAccountInfo.getSelectedRow();
btnSave.setEnabled(false);
btnUpdate.setEnabled(true);
btnDelete.setEnabled(true);
} catch (ArrayIndexOutOfBoundsException aiobe) {
aiobe.printStackTrace();
}
}
I'm populating JTable from access database. when running the code for the first time, table loads perfectly. Then adding new records to database from JDialog. What I was trying to do is to call loadData() method when JDialog is closed, but table is not updating.
This is my loadData() method:
private void loadData() {
System.out.println("sssss");
final String [] columnNames={"Seq", "First Name", "Last Name","Num1","Num2","Num3"};
connectDb();
data = new Object[rows][columns];
int row = 0;
try {
while(rs.next()){
for(int col = 0 ; col<columns; col++ ){
if(col==0)
data[row][col]=rs.getString("contact_seq");
if(col==1)
data[row][col]=rs.getString("contact_fname");
if(col==2)
data[row][col]=rs.getString("contact_lname");
if(col==3)
data[row][col]=rs.getString("contact_num1");
if(col==4)
data[row][col]=rs.getString("contact_num2");
if(col==5)
data[row][col]=rs.getString("contact_num3");
}
row++;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
model = new DefaultTableModel(data, columnNames){
/**
*
*/
private static final long serialVersionUID = 1L;
public boolean isCellEditable(int row, int column)
{
return false;
}
};
table = new JTable(model);
}`
this how I call loadData method when closing the JDialog.
JMenuItem mntmNew = new JMenuItem("New Contact");
mntmNew.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addData gui = new addData(viewData.this,rs);
gui.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
gui.setVisible(true);
gui.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e){
loadData();
}
});
}
});
mnFile.add(mntmNew);
My database is updated when adding the records but Jtable is not refreshed.
Here:
private void loadData() {
...
table = new JTable(model); // don't re-create the table here
}
Don't re-create the table but update its model instead, either by setting a new table model or by clearing and re-filling the current one:
private void loadData() {
...
table.setModel(model);
// Of course, table should have been initialized
// and placed first, and only once!
}
See examples here (includes SwingWorker to make database calls in a background thread), here and here. Please have a look to those answers, there are explanations to make the point clear.
This worked for me:
if (model.getRowCount() > 0) {
for (int i = model.getRowCount() - 1; i > -1; i--) {
model.removeRow(i);
}
}
setTablevalue();
I removed all the rows from the JTable and again called the setTableValue method to re-populate the table.
This is a shot in the dark, but maybe this will work?:
public void windowClosed(WindowEvent e) {
loadData();
// Add this line:
table.repaint();
}
If I understand what is going on, the underlying database is getting updated but the JTable component is not showing the updates. My guess is that you just have to call the repaint() method so that the JTable gets updated as well.
I have jFrame2 which contains jTable with 4 columns (the jTable taking data from table in database which contain 20 columns)
Also I have jFrame1 which I have used it to fill database.
What I want to do that when I select row in jTable and click jButton, it must open jframe1 showing all data for that row.
i will clear what i want in points
*i want open jframe1 from jframe2 via jbutton(this task is done and this is the code)
public void actionPerformed(ActionEvent e) {
if(e.getSource()==jButton2){
jframe2 regFace =new jframe2();
regFace.setVisible(true);
}}
*once jframe1 opened by jbutton in jframe2 it must show in it fields all data of selected row in jframe2>>this point mean
........-sql query executed once jfram1 opened by Jbutton in jframe2
.........-showing data in jtextfield taking from database by query i mentioned in line above (this task is done and this is the code but not completed)
try {
dbconnect = new myDbConnection();
ResultSet resultSet =null;
resultSet = dbconnect.excuteQuery("SELECT id, area,location, status1 FROM pledges where id='17'");
while (resultSet.next()){
id.setText(resultSet.getString(1));
area.setText(resultSet.getString(2));
location.setText(resultSet.getString(3));
status.setText(resultSet.getString(4));
// i = Long.parseLong(rs1.getString(1));
}
*in brief i want understand jframe1 that please if you opened by jframe2 execute a query and fill text fields by that query
*this is picture would clear better
here
It sounds like the part you are having trouble with is how to get the selected data from the table into the fields in jframe1.
A lot of this depends on the TableModel that is used in your JTable. Assuming you just used a DefaultTableModel, you can get the selected row data like this:
#Override
public void actionPerformed(ActionEvent e) {
int viewRow = myJTable.getSelectedRow();
int modelRow = myJTable.convertRowIndexToModel(viewRow);
DefaultTableModel model = (DefaultTableModel) myJTable.getModel();
// You will get a compiler warning on the following line, but there's not much you can do about it beside suppress it
Vector<Object> rowVector = (Vector<Object>) model.getDataVector().get(modelRow);
jframe2 regFace =new jframe2();
regFace.setSelectedRow(rowVector);
regFace.setVisible(true);
}
And you would have the following method in your jframe2 class:
public void setSelectedRow(Vector<Object> row ) {
id.setText(row.get(0).toString());
area.setText(row.get(1).toString());
location.setText(row.get(2).toString());
status.setText(row.get(3).toString());
// continue for all columns
}
before i put the answer i would thank #wolfcastle such a nice person.He almost answer the question and i'm just modify it to adapt it with sql query and database.
this is the code for jfrme2
public void actionPerformed(ActionEvent e) {
if(e.getSource()==jButton2){
int viewRow = jTable1.getSelectedRow();
int modelRow = jTable1.convertRowIndexToModel(viewRow);
Object oc= jTable1.getModel().getValueAt(modelRow, 0);
String vv=oc.toString();
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
jframe1 regFace =new jframe1();
try {
regFace.setSelectedRow(vv);
} catch (SQLException ex) {
Logger.getLogger(showp1.class.getName()).log(Level.SEVERE, null, ex);
}
regFace.setVisible(true);
}
}
and the the code for jframe1
public void setSelectedRow(String row ) throws SQLException {
dbconnect = new myDbConnection();
ResultSet resultSet =null;
System.out.print(row);
resultSet = dbconnect.excuteQuery("SELECT id, area,location, status1 ,date1,insname,oname,bname,street,junction,INSPSITION,recname1 FROM pledges where id='"+row+"'");
while (resultSet.next()){
id.setText(resultSet.getString(1));
area.setText(resultSet.getString(2));
location.setText(resultSet.getString(3));
status.setText(resultSet.getString(4));
date.setText(resultSet.getString(5));
insname.setText(resultSet.getString(6));
oname.setText(resultSet.getString(7));
bname.setText(resultSet.getString(8));
street.setText(resultSet.getString(9));
junction.setText(resultSet.getString(10));
insposition.setText(resultSet.getString(11));
recname.setText(resultSet.getString(12));
}
}