如何在此类中使用公共变量和方法?

时间:2018-05-21 04:27:54

标签: java swing methods jpanel awt

以下代码创建了12个面板,每个面板上都有一个标签和一个按钮。

public MainFormWithPanel() {
    InventoryFileReader reader = new InventoryFileReader();
    ArrayList<Car> cars = reader.getAllCars();

    setLayout(new GridLayout(0,4));//set rows to zero so it fills rows first

    for(int i = 0; i < cars.size(); i++){
    InventoryItemPanel panel = new InventoryItemPanel();
    panel.setLabel(cars.get(i).getYear(), cars.get(i).getMake(), 
           cars.get(i).getModel(),cars.get(i).getMiles(), cars.get(i).getPrice());
    add(panel);
    }

    pack();

    initComponents();
}

以下类保存我上面使用的setLabel方法,但它不会返回我从汽车传递的值。

public class InventoryItemPanel extends JPanel{
public int year;
public String make;
public String model;
public int miles;
public int price;



JLabel label = setLabel(year, make, model, miles, price);
Button button = new Button("View More Details");

public InventoryItemPanel(){
    setLayout(new GridLayout(2,1));
    add(label);
    add(button);


}

public JLabel setLabel(int year, String make, String model, int miles, int price){
    Locale locale = new Locale("en", "US");
    NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);     
    return new JLabel("<html>"+ year + " " + make + 
                " " + model + "<br> " +  + miles
                + " miles" + "<br>" +  formatter.format(price)+"</html>");
}
}

代码的输出是:

0 null null
0 miles
$0.00

当实际输出应为:

2012 Toyota Corolla

70000 Miles

$12,000.00

我应该如何在MainFormWithPanel类的InventoryItemPanel类中实现setLabel方法?

1 个答案:

答案 0 :(得分:1)

尝试修改该行:

    add(panel);

MainFormWithPanel中:

    add(panel.setLabel(cars.get(i).getYear(), cars.get(i).getMake(), 
       cars.get(i).getModel(),cars.get(i).getMiles(), cars.get(i).getPrice()));