我在JFrame中有一个JButton,它需要在JFrame中从JPanel调用一个方法。我怎样才能做到这一点?

时间:2017-04-02 03:21:15

标签: graphics oop java

基本上,我在ButtonHandler中处理JButton事件,这是一个名为DrawFrame的JFrame类中的嵌套类。运行时,JButton放在JFrame中,旁边是一个名为DrawPanel的JPanel类。我需要按钮在推送时从JPanel调用方法。我目前从panel.clearLastDrawing()和panel.clearDrawing()获得nullPointerException。非常感谢任何帮助,谢谢。

public class DrawFrame extends JFrame {

    public static DrawPanel panel;

    public DrawFrame(){
        BorderLayout borderLayout = new BorderLayout();
        FlowLayout flowLayout = new FlowLayout();
        setLayout(borderLayout);

        JButton undoShape = new JButton("Undo");
        JButton clearAllShapes = new JButton("Clear");
        /*JComboBox colorSelect = new JComboBox();
        JComboBox shapeSelect = new JComboBox();
        JCheckBox shapeFilled = new JCheckBox();*/
        JLabel mouseCoords = new JLabel();

        panel = new DrawPanel(mouseCoords);
        JPanel upperPanel = new JPanel();
        add(panel, BorderLayout.CENTER);
        add(upperPanel, BorderLayout.NORTH);
        upperPanel.setLayout(flowLayout);
        upperPanel.add(undoShape);
        upperPanel.add(clearAllShapes);

        ButtonHandler handler = new ButtonHandler();
        undoShape.addActionListener(handler);
        clearAllShapes.addActionListener(handler);
    }

    public class ButtonHandler implements ActionListener{

            @Override
            public void actionPerformed(ActionEvent e) {
                 if(e.getActionCommand() == "Clear"){
                    panel.clearDrawing();   //is panel not instancianted yet??
                 }
                 else if(e.getActionCommand() == "Undo"){
                    panel.clearLastShape();
                 }
            }   
        }
}

0 个答案:

没有答案