首页 > 解决方案 > 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.

标签: javaswingcompiler-errorsjpaneltitled-border

解决方案


JPanel#setBorder方法具有void返回类型,这意味着在调用该方法时它不返回任何值。

但是JPanel#add方法需要一个值才能调用,它会给出编译错误,因为 setBorder 是无效的。

你可以简单地通过这个来解决这个问题。

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

推荐阅读