来自不同类的调用方法

时间:2012-04-12 00:37:50

标签: java swing jpanel jbutton actionlistener

我有一个需要在屏幕上打印出来的对象的ArrayList。我有一个按钮和一个监听器,它应该在扩展JPanel的类中调用一个方法,该类扩展在MainFrame类中。

这是我想在名为AddOrderPanel的类中调用的方法。

    public void addLCheese(){ 
         BigDecimal price = new BigDecimal("8.99");
         CheesePizza largeCheese = new CheesePizza("Large Cheese/Tomato",price);
         OrderItem laCheese = new OrderItem(largeCheese,1);
         System.out.println(largeCheese.getDescription()+" "+largeCheese.getPrice()+" " +laCheese.testArray());
          JPanel order = new JPanel();
         order.setBackground(Color.blue);
      order.setPreferredSize(new Dimension(800,50));
        add(order,BorderLayout.CENTER);
     revalidate();

}

这是我的听众代码:

        lCheese.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
 AddOrderPanel orderPanel;
              orderPanel.addLCheese();

            }
      }); 

当我尝试它时会返回NullPointerException,想法?

我的面板对象。

 private JFrame myMainFrameObject;
    AddOrderPanel(JFrame theMainFr){  
    myMainFrameObject = theMainFr;
          this.setLayout(new FlowLayout(FlowLayout.RIGHT));
         setBackground(Color.red);
         setPreferredSize(new Dimension(800,0));     
    }

2 个答案:

答案 0 :(得分:1)

在致电orderPanel之前,您没有将orderPanel.addLCheese()分配给任何内容。

答案 1 :(得分:1)

在你的监听器中进行此更改以获取JFrame,然后创建AddOrderPanel的新实例

  lCheese.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e) {
           Component component = (Component) e.getSource();
           JFrame frame = (JFrame) SwingUtilities.getRoot(component);
           AddOrderPanel orderPanel = new AddOrderPanel(frame);
           orderPanel.addLCheese();

        }
  });