Its been awhile since I have toyed around with java, so I'm a bit rusty. But decided to mess with it today.

I have a jPanel that I will be adding objects to, but I want to add the in a new row each time a button is clicked. Anyways the problem is, every time I click the button it resets my integer which I increment.

Here is the snipper:

int row = 0;
        row++;

         //constraints
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = row;
        gridBagConstraints.anchor = GridBagConstraints.NORTHWEST;
        gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;

        //add object to panel
        jPanel1.add(object, gridBagConstraints);

Basically since I set int row = 0 it resets it to 0 every time I click the button.

Anyone able to offer a quick solution?

Its been awhile since I have toyed around with java, so I'm a bit rusty. But decided to mess with it today.

I have a jPanel that I will be adding objects to, but I want to add the in a new row each time a button is clicked. Anyways the problem is, every time I click the button it resets my integer which I increment.

Here is the snipper:

int row = 0;
        row++;

         //constraints
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = row;
        gridBagConstraints.anchor = GridBagConstraints.NORTHWEST;
        gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;

        //add object to panel
        jPanel1.add(object, gridBagConstraints);

Basically since I set int row = 0 it resets it to 0 every time I click the button.

Anyone able to offer a quick solution?

Well, not seeing the rest of the code, it's speculation, but I imagine you want to make the row variable a global class variable rather than a local variable, initialize it to 0 ONCE in your constructor or something, then when the button is pressed, it's no longer set to 0 every time and is incremented (I assume this snippet is in actionPerformed?).

Apologies, yes it is actionperformed.

Yeah making it a global class variable should work, I suppose I just thought there might be a way to do it inside the actionperformed.

Nonetheless, it gets the job done. Thanks for the response Vernon

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.