nani
nani

Reputation: 399

How to add JTextField to JPanel into specific position by using variable

I need to append the row together with its component in JPanel as user click ADD button. So I want to add the component which is the JTextField into the JPanel by placing them into specific position.

As the column is always be the same number, I just need to increase the row number. So here is the current codes I tried so far.

int startRow = 3;
int row = startRow + 2;

textField_1 = new JTextField();
panel_1.add(textField_1, "3, row");//having error in this line
textField_1.setColumns(10); 

startRow = row; 

I having error at that particular line above. It seems like eclipse did not read row as an integer.

Upvotes: 0

Views: 177

Answers (2)

A.K.
A.K.

Reputation: 2322

textField_1 = new JTextField();
textField_1.setColumns(10); 
panel_1.add(textField_1);

If you are using Default Layout .add() only takes 1 parameter and If you are use GridBagLayout and BorderLayout then .add()tahe 2 Parameter one is component and other is Position

Upvotes: 0

Jake Stanger
Jake Stanger

Reputation: 449

I take it you're fairly new to the world of Java.

Firstly, change the line with the error to be:

panel_1.add(textField_1);

.add() only takes 1 parameter (as far as you need to know at the moment) and you must position the component after adding it. This is done using a layout manager.

http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

I suggest you have a read of that article, and look at some of the demos. I hope this helps.

On a sidenote, I would use better names for your components to make them easier to locate. It's not too important at the moment, but when you make larger applications you rely a lot on your IDEs autocomplete, and it helps knowing what things are called. It tends to be a good idea to start with an abbreviated version of the component type, followed by it's purpose - If you had a button to exit call it btnExit.

Upvotes: 2

Related Questions