0

I have these two forms. One contains several buttons. The other contains two tables. On the click of one button the data is saved in a database and is then transferred to the JTable in the other form. I wrote the code through the first form only. But it doesn't work. Here's the code:

int dress1=100;
DefaultTableModel CurrPurchases=(DefaultTableModel) CurrentPurchases.getModel();
double price1=Double.parseDouble(Price1.getText());
int rows=CurrPurchases.getRowCount();
if(rows > 0){
    for (int i = 0; i < rows; i++) {
         CurrPurchases.removeRow(0);
    }
}
try{
    Connection connection=getConnection();
    ResultSet curprs=null;
    Statement buy1stmt=connection.createStatement();
    String Buy1Query1="Update Products set Quantity=Quantity-1 where Product_no=1;";
    String Buy1Query2="Insert into Buy values('"+Pname1.getText()+"',"+price1+");";
    buy1stmt.executeUpdate(Buy1Query1);
    buy1stmt.executeUpdate(Buy1Query2);
    dress1--;
    if(dress1==0){
        JOptionPane.showMessageDialog(null,"Sorry, This Item is Out of Stock!");
    }
    new ShoppingCart().setVisible(true);
    PreparedStatement buy2stmt=connection.prepareStatement("Select * from Buy;");
    curprs=buy2stmt.executeQuery();
    if(curprs.last()){
        CurrPurchases.addRow(new Object[]{curprs.getString(1),curprs.getDouble(2)});
    }
}
catch(Exception ex){
    ex.printStackTrace();
}
finally{}

But this line in specific shows error(I mean underlined with a red line):

DefaultTableModel CurrPurchases=(DefaultTableModel) CurrentPurchases.getModel();

How can I add the data into that table (CurrentPurchases) in the other form? Note: I don't want to add any button to the form, I just want the data to be displayed.

Any help would be appreciated.

8
  • What's exactly the error you're facing? Is an exception? Compiling error? Hard to help you without knowing nothing about this error. Commented Nov 25, 2013 at 15:37
  • Oh sorry! I mean it's underlined with red, it's just a kind of a warning not really an error. Commented Nov 25, 2013 at 15:42
  • What does the IDE say about this line? Why is it complaining? Missing variable? Unknown identifier? Illegal start of expression? Commented Nov 25, 2013 at 15:57
  • It says 'Cannot find symbol'... Commented Nov 25, 2013 at 15:58
  • Then I suspect this import is missing: import javax.swing.table.DefaultTableModel;. Give it a try and let me know how it went :) Commented Nov 25, 2013 at 16:00

1 Answer 1

1

From comments section:

CurrentPurchases.getModel() underlined with red. Actually CurrentPurchases is the name of the jtable in the other form. So what should I do now?

I understand your problem now. You're trying to access a variable defined in a form from another form directly. That's why the compiler is complaining. You'll need to create a public getter to this CurrentPurchases in order to access it from other class. Something like this:

public JTable getCurrentPurchasesTable() {
    return this.CurrentPurchases;
}

Then make this change:

DefaultTableModel CurrPurchases= (DefaultTableModel) otherFormVariable.getCurrentPurchasesTable().getModel();

Of course you'll need a reference to the other form (I called it otherFormVariable in the example) in order to get the table as you wish.


An off-topic tip:


Edit: implementation examples

Well as you're new to Java (welcome to this world :P) I'll give you two possible implementation examples.

First off let's say you have 2 forms as follows:

  • Form1: here is placed your table.
  • Form2: here you can add a new record to your DB and the previous table.

Example 1: Giving public access to Form1's table

The first way is the one you're trying. To make it work in this way you'll need do something like this:

public class Form1 extends JDialog {

    JTable currentPurchases;
    JButton addRecordButton;

    private initComponents() {
        addRecordButton = new JButton("Add record");
        addRecord.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                Form2 form2 = new Form2();
                form2.setForm1(this);
                form2.setVisible(true);
            }
        };
        ... // init the table and other components
    }

    public JTable getCurrentPurchasesTable() {
        return this.currentPurchases;
    }
}

public class Form2 extends JDialog {

    Form1 form1; // this variable will keep reference to a Form1 instance
    JButton saveRecordButton;

    private void initComponents() {
        saveRecordButton = new JButton("Save record");
        saveRecordButton .addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                DefaultTableModel model = (DefaultTableModel) form1.getCurrentPurchasesTable().getModel();
                // add new rocord to the model
            }
        };
        ... // init the other components

    }

    public void setForm1(Form1 f) {
        this.form1 = f;
    }

}

Example 2: Setting a TableModel to Form2

This second way is about setting a TableModel to the Form2 object. This way you don't need public access to your table anymore. It should be something like this:

public class Form1 extends JDialog {

    JTable currentPurchases;
    JButton addRecordButton;

    private initComponents() {
        addRecordButton = new JButton("Add record");
        addRecord.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                Form2 form2 = new Form2();
                form2.setTableModel(currentPurchases.getModel());
                form2.setVisible(true);
            }
        };
        ... // init the table and other components
    }
}

public class Form2 extends JDialog {

    TableModel model; // this variable will keep reference to a TableModel instance
    JButton saveRecordButton;

    private void initComponents() {
        saveRecordButton = new JButton("Save record");
        saveRecordButton .addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                // add new rocord to the model:
                ((DefaultTableModel)model).addRow(...);                    
            }
        };
        ... // init the other components

    }

    public void setTableModel(TableModel m) {
        this.model = m;
    }

}
Sign up to request clarification or add additional context in comments.

4 Comments

I'm sorry, I'm new to this, where should I exactly enter the public getter?
No worries, no need to apologize :) Let's say you have Form1 where your table is placed. There you should add public access to this table. Now you have another class Form2 where you're adding data. So this second one has to mantain a reference to Form1 and then it will be able to call Form1.getCurrentPurchasesTable().getModel();. Let me know if it's clear enough :) @LuluLala
Not sure if I did it in the right way but I just followed your instructions and it shows a warning: non-static method getCurrentPurchasesTable() cannot be referenced from a static context...where should I type that public getter, I mean at which line or page?
@mKorbel my magic ball lost connection for a couple of hours but now I think it's working again :P @LuluLala the new error you're getting is because you don't keep any reference to a Form1 object. Please see updated answer. I've included two examples of implementation. Hope these be helpful and can lead you in the right way :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.