Ghadeer M
Ghadeer M

Reputation: 3

Creating JPanels with a titled border in a for loop from user input

I want to create a for loop that creates JPanel containers with titled headers. the number of iterations depends on the user input from previous interfaces.

int noofpara=Integer.parseInt(data[6]);

for(int i=1;i<=noofpara;i++){
    jPanel1.add(new JPanel().setBorder(new TitledBorder("Perimeter"+i)));       
}

The noofpara is the number of perimeters the user chose according to that the for loop should create panels with the titled border with the number of perimeters. the error appears at the jpanel1.add... where it says void type not allowed.

Upvotes: 0

Views: 44

Answers (2)

friendlyBug
friendlyBug

Reputation: 598

JPanel#setBorder method has void return type, which mean it doesn't return any value when that method invoked.

But JPanel#add method need a value in order to invoked, it gives compilation error since setBorder is void.

You can simply fix this by this.

JPanel childPanel = new JPanel();
childPanel.setBorder(new TitledBorder("Perimeter" + i));
jPanel1.add(childPanel);

Upvotes: 1

Super Shark
Super Shark

Reputation: 376

You have to make new panel and add.

for (int i = 1; i <= noofpara; i++) {
    JPanel innerPane = new JPanel();
    innerPane.setBorder(new TitledBorder("Perimeter" + i));
    jPanel1.add(innerPane);
}

Upvotes: 0

Related Questions