Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 272
  • Last Modified:

For Loop

can anyone please change this to a for loop

JPanel tPanel = new JPanel(new GridBagLayout());
tPanel.setBackground(Color.magenta);

GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;

tPanel.add(new JTextField(20),gbc);
gbc.gridx = 1;
gbc.gridy = 0;
tPanel.add(new JLabel("TITLE"),gbc);
gbc.gridx = 0;
gbc.gridy++;
tPanel.add(new JTextField(20),gbc);
gbc.gridx = 1;
tPanel.add(new JLabel("AUTHOR"),gbc);
gbc.gridx = 0;
gbc.gridy++;
tPanel.add(new JTextField(20),gbc);
gbc.gridx = 1;
tPanel.add(new JLabel("PUBLISHER"),gbc);
gbc.gridx = 0;
gbc.gridy++;
tPanel.add(new JTextField(20),gbc);
gbc.gridx = 1;
tPanel.add(new JLabel("YEAR"),gbc);
gbc.gridx = 0;
gbc.gridy++;
tPanel.add(new JTextField(20),gbc);
gbc.gridx = 1;
tPanel.add(new JLabel("ISBN"),gbc);
gbc.gridx = 0;
gbc.gridy++;
tPanel.add(new JTextField(20),gbc);
gbc.gridx = 1;
tPanel.add(new JLabel("CATEGORY"),gbc);
gbc.gridx = 0;
gbc.gridy++;
tPanel.add(new JTextField(20),gbc);
gbc.gridx = 1;
tPanel.add(new JLabel("NUMBER"),gbc);
gbc.gridx = 0;
gbc.gridy++;
tPanel.add(new JTextField(20),gbc);
gbc.gridx = 1;
tPanel.add(new JLabel("UNIT PRICE"),gbc);
gbc.gridx = 0;
gbc.gridy++;

0
lucinda77
Asked:
lucinda77
1 Solution
 
Hammadian2Commented:
dont what's your language
however
make an array of objects containning:
JTextField(20), JLabel("TITLE"), JTextField(20),JLabel("AUTHOR"),....

Then make ur for loop something like this:
for i = 1 to ArrayCount
      if (i mod 2) = 1 then gbc.gridx = 1 else gbc.gridx = 0
      gbc.gridy++;            
      tPanel.add(Objects[i],gbc);
Next


however, this kind of loop is really USELESS, no problem with repeating the code in such a case
0
 
adambuttCommented:
Since each lable has a different name, it really woulden't be worth it.  However, the text fields could be simplified to:

gbc.gridx = 0;
for(int i=0; i<8; i++)
{
gbc.gridy = i;
tPanel.add(new JTextField(20),gbc);
}

But, again, since you already have to put each lable on its own line, it isen't worth it.  You will save processor cycles just leaving it as it is.
0
 
SkonenCommented:
If you want to take care of gbc.gridx in the same loop use the modulus operator:


for(int i=0; i<8; i++) {
     gbc.gridx = (i+1) % 2;
     gbc.gridy = i;
     tPanel.add(new JTextField(20),gbc);
}
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now