Allowing user to modify/edit a JTable

i'm new to java and i'm creating a JTable that allows a user to modify the data and the data will be stored in the database that i have created here is my code:
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.*;
import javax.swing.event.*;
import javax.swing.table.TableModel;
public class SelectContacts extends JFrame implements TableModelListener {
private boolean DEBUG = true;
DataBase db = new DataBase();
Connection connection = db.getConnection();
public SelectContacts() {
super("SelectContacts");
DataBase db = new DataBase();
Connection connection = db.getConnection();
ArrayList contactsList =new ArrayList();
String[] columnNames = {"Name",
"Address",
"Gender",
"Email",
"Contact",
"Age"};
String query;
Statement statement;
ResultSet rs;
String personName="";
String address="";
String gender="";
String email="";
String contact="";
String age="";
Contacts s1;
int i=0;
query = "SELECT * FROM Contacts";
try{
statement = connection.createStatement();
rs = statement.executeQuery(query);
while (rs.next()){
     personName = rs.getString("Name");
address = rs.getString("Address");
gender = rs.getString("Gender");
email = rs.getString("Email");
contact = rs.getString("Contact");
age = rs.getString("Age");
s1= new Contacts(personName,address,gender,email,contact,age);
contactsList.add(s1);
i++;      
statement.close();
catch ( SQLException sqlex ) {
sqlex.printStackTrace();
Object[][] data = new Object[6];
int count=0;
while (count<i){
     s1 = (Contacts) contactsList.get(count);
     System.out.println("Name:" + s1.getName());
     System.out.println("Address:" + s1.getAddress());
     System.out.println("Gender:" + s1.getGender());
     System.out.println("Email:" + s1.getEmail());
     System.out.println("Contact No.:" + s1.getContact());
     System.out.println("Age:" + s1.getAge());
     data[count][0] = s1.getName();
     data[count][1] = s1.getAddress();
     data[count][2] = s1.getGender();
     data[count][3] = s1.getEmail();
               data[count][4] = s1.getContact();
               data[count][5] = s1.getAge();
count++;
final JTable table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.getModel().addTableModelListener(this);
//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
//Add the scroll pane to this window.
getContentPane().add(scrollPane, BorderLayout.CENTER);
highlighed
public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
int column = e.getColumn();
TableModel model = (TableModel)e.getSource();
String columnName = model.getColumnName(column);
Object data = model.getValueAt(row, column);
Statement statement;
ResultSet rs;
     String insertString= "Insert into Contacts (Name, Address, Gender, Email, Contact, Age ) "+
          " VALUES ( '"+ data +"')";
          // Do something with the data...
try{
statement = connection.createStatement();
statement.executeUpdate(insertString);
statement.close();
catch ( SQLException sqlex ) {
sqlex.printStackTrace();
     System.out.println("You sucessfully modified! :)");          
highlighted
public static void main(String[] args) {
SelectContacts frame = new SelectContacts();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
//Whenever window gets the focus, let the
//TextFieldDemo set the initial focus.
public void windowActivated(WindowEvent e) {
// demo.setFocus();
frame.pack();
frame.setVisible(true);
i recieved error when i tried to edit 1 of the data "java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Number of query values and destination fields are not the same. i think the problem lies in the highlighted part. pls guide me thanks

i think the problem lies in the highlighted part. pls guide me thanks What highlighted part? When you post code use the [code ]...[code ] tags. Read the "Formatting Help" link when you post a question for more information.
I find it easier to use a PreparedStatement as it delimits a the parameters in your SQL statement for you. Here's a simple example, read the API for more information:
        private static void addData(Connection connection)
            throws Exception
            String sql =
                "INSERT INTO Page " +
                     "(Name," +
                     "Title) " +
                 "VALUES " +
            PreparedStatement stmt = connection.prepareStatement(sql);
            stmt.setString( 1, "Name1" );
            stmt.setString( 2, "Title1" );
            stmt.executeUpdate();
            stmt.setString( 1, "Name2" );
            stmt.setString( 2, "Title2" );
            stmt.executeUpdate();
            stmt.close();

Similar Messages

  • Allow user to access /edit/delete/add specific items in list

    Hi
    I have one custom list.
    every month department head is creating some activity because of which some items are getting added in that list pragmatically.
    like-
    departmentID item1
    item2
    DEPT001 item001
    item002
    DEPT001 item003
    item001
    DEPT002 item004
    item001
    After that User want to edit or delete or add new entries only related to their department only.
    How can allow user to edit/delete or add entries (full control) only related to his department in the same list?
    How can I assign users for this?
    Should I create another list having department id and user mapping?
    please suggest any soln.

    The flow is like,
    User(Dept head/department user)will select department from drop down and clik on button to add some entries against the department.
    once the entries done he just click on save button.
    after some time if department head/department user want to add/edit/delete some entries against his department then he should able to view only his deapartment entries.  
    Also the email is generated to his manager.
    So my question is how should I allow user to view his own entires only which should be available for him to add/edit/delete.?
    If I create one list of department  and on adding the entries against each department I will add departmentID for every entry so that I can filter them by department.
    but how to allow users for those entries? If I added user for each entry and if any department user changed then I have to change his name from all entries for that department.If the entries are more than 50 or 100 then it will be very difficuelt to handle.
    Also for multiple users for single department this is very difficuelt to provide access.
     is there any alternate solution for it?

  • Allowing user to modify default value - is this possible?

    A report needs to be produced with the default value of an input variable (0FISCPER) set to the current fiscal period - this is used to calculate the YTD and Full Year Forecast of the present year. The default is required to allow the user the view the present day information without having to enter the current date manually - i.e. <b>no pop up variables screen</b>.
    The complication occurs when it is required for the user to be able to modify the input variable to view historical data. Is it possible for the end user to adapt the current default (i.e. the current month) to a month of his/her choice?

    Thanks all - I've been experimenting a bit over the past few days with this. This is my situation so far:
    The Year-to-Date and Forecast variables take in 0F_FPER as its input - 0F_FPER is a user entry variable.
    There is a user exit variable which exists in the system which returns the current fiscal period called 0FPER. I need this variable to be the YTD and Forecast default inputs <i>without the variables entry screen popping up</i>.
    Once the user is in the report, it is required to be possible for them to enter a date (it may be in the previous year) to allow them to view historical data.
    <u>What I am thinking about doing is creating new YTD and Forecast variables that will take 0FPER in as an input.</u>
    However, 0FPER is hardcoded to return the current fiscal year. <b>Is it therefore possible to allow the user to input another value into 0FPER? Would this not conflict with the coding?</b>

  • How to allow user to modify his own data with a Portal Form

    Hi,
    I have a form (Master-Detail) to update a user-profile (Master) and the user's skills (Detail).
    How can I make sure, that a user can only modify his own profile - assuming the master table has an attribute containing the users loginname for Portal?
    thanks!
    bye Stephan...

    Yes, along with the default value of wwctx_api.get_user, you also need to specify the default value type. In this case it should be Expression returning Varchar2.

  • How to protect Excel cells while allowing VBA to modify them?

    I want to allow users to modify inputs in some Unlocked cells and have the other cells update accordingly. I also want to prevent users from clobbering those other cells, so those are Locked.
    Protect Sheet allows ordinary formulas in Locked cells to execute but, by default, prevents VBA functions from executing when their input cells are modified. So, after consulting the
    Excel 2013 developer reference's descriptions of the Worksheet.Protect method and
    Worksheet object, I added these statements to my initialization routine:
    Worksheets(1).Activate
    ActiveSheet.Protect "", UserInterfaceOnly = True
    The 2nd statement enables Protect Sheet with a null password successfully, but the UserInterfaceOnly setting isn't having the effect I expected, i.e., allowing the VBA functions to execute when their input cells are changed. (I've noticed it seems to enable
    the Allow Users to Edit Objects protection option.)
    I also tried := True, but that doesn't help.

    The function fails because you cannot change characteristics of a chart in a worksheet function. A worksheet function can only return a value to the cell that contains the formula.
    You can use the Worksheet_Change event to modify the chart instead. The function can be simplified to
    Function Show_RGB(Y, u, v, Swatch) As Variant
    Dim R As Single, G As Single, B As Single
    On Error GoTo ErrHandler
    R = R_from_Yuv(Y, u, v)
    G = G_from_Yuv(Y, u, v)
    B = B_from_Yuv(Y, u, v)
    Show_RGB = Array(R, G, B) ' Allow <0 and >255 in spreadsheet
    ExitHandler:
    Exit Function
    ErrHandler:
    MsgBox Err.Description, vbExclamation
    Resume ExitHandler
    End Function
    The Worksheet_Change event procedure in the worksheet module:
    Private Sub Worksheet_Change(ByVal Target As Range)
    Dim R As Single, G As Single, B As Single, Swatch As Integer
    Dim rng As Range
    On Error GoTo ErrHandler
    If Not Intersect(Range("B3:D14"), Target) Is Nothing Then
    Worksheets(1).Unprotect
    For Each rng In Intersect(Range("B3:D14"), Target)
    R = Cells(rng.Row, 5)
    G = Cells(rng.Row, 6)
    B = Cells(rng.Row, 7)
    Swatch = rng.Row - 2
    R = WorksheetFunction.Max(0, (WorksheetFunction.Min(255, R))) ' ...avoid runtime error when changing displayed color
    G = WorksheetFunction.Max(0, (WorksheetFunction.Min(255, G)))
    B = WorksheetFunction.Max(0, (WorksheetFunction.Min(255, B)))
    With Worksheets(1).ChartObjects(6).Chart.SeriesCollection(1)
    .Points(Swatch).MarkerBackgroundColor = RGB(R, G, B)
    .DataLabels(Swatch).Font.Color = RGB(R, G, B)
    End With
    Next rng
    End If
    ExitHandler:
    Worksheets(1).Protect
    Exit Sub
    ErrHandler:
    MsgBox Err.Description, vbExclamation
    Resume ExitHandler
    End Sub
    See
    https://www.dropbox.com/s/nylonrp0y86lq1c/FAA%20palette%20designer%20Beta%2002.xlsm?dl=1
    Regards, Hans Vogelaar (http://www.eileenslounge.com)

  • Copy select value in the textfield from LOV and allow user to edit it

    Hi,
    I have a datablock with 20 records and each record has comments (say field_comments) fields. I would like to allow user to choose predefined comments populated from LOV (say lov_comments) and to append some extra comments after they choose the value from LOV.
    I have created a LOV and added Return type “field_comments” in the column mapping properties. When user clicks on a button, LOV opens up. They select the value from the LOV and the value goes to “field_comment” field. The problem with this approach, user can’t add their comment after selecting from LOV.
    I tried this way too. I created another non-visible textbox (say dummy). In the LOV, I added “dummy” field as returntype. In the dummy field, I have created “POST-CHANGE” trigger which basically says :block. field_comments = :block. Dummy.
    But, the user has to click on other field to view the selected value from the LOV. The values in the “field_comments” is not updated as soon as user click on “OK” button in the LOV.
    I would appreciate it if somebody could give me some input and help to solve my issue. Thank you for your help.
    Thank.

    Well, I tried exactly what you posted and it allowed me to SELECT from LOV and then CHANGE/APPEND new text in front of returned value in the field. It saved to the database and queried without any problems.
    Is your item allowed to INSERT/UPDATE ? If not, then set "Update/Insert Allowed" properties to Yes and attach your LOV to the item and set "Validate from list" to No.
    You may also see if you have any validation being performed on WHEN-VALIDATE-ITEM or POST-CHANGE trigger which will fail since you are editing the values populated from LOV.
    Hope it helps!

  • Allow user to edit their own Address Book server entry

    Hiya.
    I'm looking for a way to let users edit their own information in the Address Book Server/Open directory. I've made sure the main group for users is in the AB Read-Write Groups group in WGM.
    I've even checked the box in Server Admin that says "Allow users to edit their own contact information", but after adding the account to an address book client and authenticating as a user (For example, myself), I can't edit my own contact info anywhere that will push to the server.
    Is there any way to do this?
    Thanks!

    You'd need to write a php script or something to interface with applescript…

  • Adding a blank row to a JTable when a user begins to edit a current row

    Hi, this may be a daft question, but I've been looking through the forum and didnt find anything that really helped me. So I'm posting this in the hope someone will be a ble to point me in the right direction.
    In my current application I have a JTable. It currently contains a single emptry row. What I wish to happen is when a user begins to edit that empty row a new blank row is added to the bottom of the table.
    I'm using a custom table model, as there maybe data loaded from a Oracle database at a later date and have included an "addRow()" method which will add the blank row.
    What i'm struggling with is a way to detect when the user has started to edit the blank row and so when to call my "addRow()" method.
    I tried experimenting with propertyChange listeners but they didnt seem effective. Could someone please provide me with either a solution or a pointer in the right direction.
    Thanks for your help

    What I wish to happen is when a user begins to edit that empty row a new blank row is added to the bottom of the table.Well a user could start to edit the last row, but then they could use the escape key to cancel the cell editing. So I would only add the empty row once a cell has actually been updated.
    For this I would use a TableModelListener. The listener will only fire when the data in a cell is changed. So once the event is received you simply check if the row of the edited cell is the last row of the table.

  • Anyway to Restrict Editing and Allow Users to Highlight/Bold?

    Hello Everyone, 
    I was wondering if there was a way that I could restrict editing on my 2013 MS Word document but allow users to highlight and bold the text. I have looked up many forums and have not found a thing! 
    Thank you, 
    Kimmi131

    Unfortunately, there is no way to apply true highlighting in a protected document. But note that you can assign a keyboard shortcut to apply your custom character style, which simplifies the task.
    Also, character styles are applied on top of the current paragraph style, so you only need one. Hmm, if you need multiple highlighting colors, then you may have to create more styles, yes.
    Stefan Blom, Microsoft Word MVP

  • Ignoring editing in JTable

    Hello,
    I've got a JTable that reflects data in an xml file that is diaplaed as a JTree.
    I've allowed editing of certain columns in the JTable, but want to ignore a users edits if they do not accord with the xml schema. I can ignore the changes so that the underlying model is not changed, but I cannot get the table to ignore the changes and display what was there previous to editing. Can anyone help with this.
    Also, if the user double clicks in the table cell and then clicks on a different node in the tree, the table does not change to reflect the selected tree node. I've got an appropriate treeEventListener and it works fine when then user has not edited, but when they do the table does not update. Any help with thei would be great as well.
    Thanks
    Simon Hall

    In your tablemodel isCellEditable(int row,int column) method set the cells that you don't want the user to edit to return false. Example:public boolean isCellEditable(int Row, int Column)
       if(row == 10 && column == 2)
           return false;
        return true;
    }the cell at row 10 and column 2 would not allow editing on the JTable.
    Hope this helps
    Justin

  • No edit with JTable ?

    Hi All!
    How can I NOT allow user edit in JTable's cell ???
    Which method to use or the way to do that!
    Thank for you help!
    Long Ng

    In your abstract table model return false from
    public boolean isCellEditable(int row, int col) {return false;}
    rykk

  • How to allow users to mount a Samba shares on a WXP

    Through lots of reading I've managed to get an understanding of how to mount SMB shares at bootup by placing the proper edits in /etc/fstab. While having the shares of the server, running Contribs.org SME Server 6.01 (recently known as Mitel SME Server) and acting as a samba server, being mounted at startup is perfect since the server is always on. This is not the best idea for the XP workstation since it isn't always on. Here is a copy of my present fstab file with x's replacing the passwords.
    fstab               [B---]  0 L:[  1+19  20/ 21] *(1085/1086b)= .  10 0x0A
    # /etc/fstab: static file system information
    # <file system>        <dir>         <type>    <options>          <dump> <pass>
    none                   /proc         proc      defaults            0      0
    none                   /dev/pts      devpts    defaults            0      0
    none                   /dev/shm      tmpfs     defaults            0      0
    tmpfs                  /tmp          tmpfs     defaults            0      0
    sysfs                  /sys          sysfs     defaults            0      0
    usbdevfs               /proc/bus/usb usbdevfs  defaults            0      0
    /dev/cdroms/cdrom0     /mnt/cd   iso9660   ro,user,noauto,unhide   0      0
    /dev/cdroms/cdrom0     /mnt/dvd  udf       ro,user,noauto,unhide   0      0
    /dev/floppy/0          /mnt/fl   vfat      user,noauto,unhide      0      0
    //192.168.2.2/stuff    /mnt/silicon2 smbfs username=kingnubian,password=xxxxxxx,user
    //192.168.2.105/e-smith   /mnt/silicon1 smbfs username=kingnubian,password=xxxxxxx,users,noauto
    /dev/discs/disc0/part5 swap swap defaults 0 0
    /dev/discs/disc0/part1 / xfs defaults 0 1
    I would like users with an account on the Linux box to mount the remote share on the XP box without needing to SU and consequently need the root password. When trying now to mount "e-smith" (The share on the XP box) as a user using "mount /mnt/silicon1" I get a message about needing to be SU.

    To allow users to mount smb shares you need to make smbmnt suid:
    # chmod +s /usr/bin/smbmnt
    Note however that the user needs to own the directory used as mountpoint. So I don't know how to make 'mount /mnt/silicon1' in your setup work for all users.
    For the users to be able to unmount the smb shares as well you need:
    # chmod +s /usr/bin/smbumount
    Now users can do 'smbmount //server/share mountpoint -o username=whatever' or simply 'mount mountpoint' if the details are specified in fstab. To unmount root can do 'umount mountpoint' or users can do 'smbumount mountpoint'.
    Don't confuse smbmount with smbmnt - the first is the command you use to mount shares manually, the second is the one that should be suid and is used both by smbmount and by mount -t smb.
    Hope this helps.
    -bogomipz

  • Efficiently identify modified values in JTable

    Hi
    I have a table with about 20 columns and 800 rows,
    It was read only , now i have open this table for editing.
    The user will update cells,and then click update database which will update those cells in database,
    is there a efficient way to do this, or do i have to keep old values, and then read all table to compare it with old values to find out which are modified
    Is there a row or cell listener which i can use to keep track of cells or rows which where modified,
    This should be smart enough to differentiate between just a click and double click for the user to modify this value.
    Any ideas or code would help
    Ashish

    One technique is to override the setValueAt( ) method of your TableModel and update the database instantly when the value changes. (Unless this is not the requirement)
    Updates to a database record can take just a few seconds so this shouldn't hamper performance. However, you can just as well spawn a new thread and run the update from there.
    ICE

  • I am looking for a way or a PDF annotator app to use in a tablet that don't allow deletion as I edit.

    Hi All, I am looking for a way or a PDF annotator app to use in a tablet that don't allow deletion as I edit. I need to use in a controlled process that don't allow user to delete or erase edits once a mistake is made or a rewrite is needed. Thank you

    See How to call Adobe Acrobat 9 APIs to OCR the PDFs through .NET reply 4.

  • FCH6-allow user to chng.check info for manual check-n not for auto chekf110

    Hi Gurus....
    T'Code FCH6 will allow user to change check info if the check is created manually. But it will not allow check info to be changed if the check is generated from F110. Is there  any mean to protect check info from being changed no matter it is manual or auto check (F110)?
    FCH6 is used for bank reconcilation. user need to key in encashment date but not to allow to modify other details e.g. amount, name,....but found for manual check, it allows users to do it so...
    Is there any way to restrict the above....
    Thanks n Regards
    N Sathish Kumar

    HI,
    The way to restrict the users from changeing the data or restricted access to certain screens or fields or t-codes can be done through Authorization Objects.  Approach your Basis guy to create one for you and you assign this Auth. Object in the user roles. Provide the Basis guy with the fields that you want to restrict. I think this is the only way to restrict the access to certain fields in a screen.
    uset this link to understand more on Aurth. Objects
    http://help.sap.com/erp2005_ehp_02/helpdata/en/95/1632e5ba9511d29e310000e839cd96/frameset.htm
    Thanks
    VK

Maybe you are looking for