Java 将面板添加到框架时获取空指针异常

Java 将面板添加到框架时获取空指针异常,java,swing,user-interface,exception,jpanel,Java,Swing,User Interface,Exception,Jpanel,更新:我试图通过使面板与另一个面板相同的方式来解决问题,但我得到了这个例外 Exception in thread "main" java.lang.NullPointerException at java.awt.Container.addImpl(Container.java:1040) at java.awt.Container.add(Container.java:926) at Plotter.createLayout(Plotter.java:48) at Plotter.<i

更新:我试图通过使面板与另一个面板相同的方式来解决问题,但我得到了这个例外

Exception in thread "main" java.lang.NullPointerException
at java.awt.Container.addImpl(Container.java:1040)
at java.awt.Container.add(Container.java:926)
at Plotter.createLayout(Plotter.java:48)
at Plotter.<init>(Plotter.java:37)
at Plotter.main(Plotter.java:325)
/

import java.util.*;
import java.io.*;
import javax.swing.*;
import javax.swing.Timer;
import java.awt.*;
import java.awt.event.*;


public class Plotter extends JFrame implements ActionListener
{   

private JMenuBar menuBar = new JMenuBar();
private JMenu fileMenu = new JMenu("File");
private JMenuItem openMenuItem = new JMenuItem("Open");
private JMenuItem saveMenuItem = new JMenuItem("Save");
private JMenuItem exitMenuItem = new JMenuItem("Exit");

private JComboBox eqCombo = new JComboBox();
private JButton addButton, removeButton, clearButton , playbutton ;
private Graph graph;
private JPanel userPanel , sliderPanel;
private JSlider slider;
private JTextField field;

public Plotter(double lowX, double highX, double frequency, String file) throws GraphArgumentsException, IOException
{
    super("Plotter");

    createNewGraph(lowX, highX, frequency, file);
    createLayout();
    createsliderpanel();
}

private void createLayout() throws GraphArgumentsException
{
    Container c = getContentPane();
    c.setLayout(new BorderLayout());
    setSize(600,500);
    c.add(graph, BorderLayout.CENTER);
    c.add(userPanel, BorderLayout.NORTH);
    c.add(sliderPanel , BorderLayout.SOUTH);
    createMenuBar();
}



/**
 * Creates a new Graph instance and adds equations from file into Graph
 * @param eqFile file where equations are stored
 * @throws IOException
 */
private void createNewGraph(double minX, double maxX, double freq, String eqFile) throws GraphArgumentsException, IOException
{
    Equation[] eq = null;
    graph = new Graph(minX, maxX, freq);

    eq = readEquationsFromFile(eqFile);

    if (eq != null)
        addEquation(eq);

    graph.setBackground(Color.WHITE);
    userPanel = createUserPanel(eq);
}

private void createMenuBar()
{
    menuBar.add(fileMenu);
    fileMenu.add(openMenuItem);
    fileMenu.add(saveMenuItem);
    fileMenu.addSeparator();
    fileMenu.add(exitMenuItem);
    openMenuItem.addActionListener(this);
    saveMenuItem.addActionListener(this);
    exitMenuItem.addActionListener(this);
    setJMenuBar(menuBar);
}

/**
 * Create user panel at top of the GUI for adding and editing functions
 * @param eq equation list to add into the combo box
 * @return panel containing buttons and an editable combo box
 */
private JPanel createUserPanel(Equation[] eq)
{
    JPanel up = new JPanel(new FlowLayout(FlowLayout.LEFT));
    eqCombo.setEditable(true);

    if (eq != null)
    {
        //Add all equations into the combo box
        for (int i = 0; i < eq.length; i++)
            eqCombo.addItem(eq[i].getPrefix());
    }

    addButton = new JButton("Add");
    removeButton = new JButton("Remove");
    clearButton = new JButton("Clear");

    addButton.addActionListener(this);
    removeButton.addActionListener(this);
    clearButton.addActionListener(this);

    up.add(eqCombo);
    up.add(addButton);
    up.add(removeButton);
    up.add(clearButton);


    return up;





}

// slider panel
private JPanel createsliderpanel()
{
    JPanel down = new JPanel(new FlowLayout(FlowLayout.LEFT));

    playbutton = new JButton("Play");
    slider = new JSlider();
    field = new JTextField();


    down.add(playbutton);
    down.add(slider);
    down.add(field);


    return down;
}



/**
 * Check action lister for button and menu events
 */
public void actionPerformed(ActionEvent e)
{
    if (e.getSource() == addButton)
        addEquation((String)eqCombo.getSelectedItem());
    else if (e.getSource() == removeButton)
        removeEquation(eqCombo.getSelectedIndex());
    else if (e.getSource() == saveMenuItem)
        saveEquationList();
    else if (e.getSource() == openMenuItem)
        loadEquations();
    else if (e.getSource() == clearButton)
        clearEquations();
    else if (e.getSource() == exitMenuItem)
        System.exit(0);
}

/**
 * Save equations to file
 *
 */
private void saveEquationList()
{
    try
    {
        PrintWriter out = new PrintWriter(new FileWriter("myeq.txt"));
        for (int i = 0; i < eqCombo.getItemCount(); i++)
            out.println(eqCombo.getItemAt(i));

        out.close();
    }
    catch (IOException e)
    {
        System.out.println(e);

    }
}


private void clearEquations()
{
    graph.removeAllEquations();
    eqCombo.removeAllItems();
}

/**
 * Load equations from file into graph
 *
 */
private void loadEquations()
{
    String file=null;
    JFileChooser fc = new JFileChooser();

    fc.showOpenDialog(null);
    if (fc.getSelectedFile() != null)
    {
        file = fc.getSelectedFile().getPath();

        try
        {
            Equation[] eq = readEquationsFromFile(file);
            if (eq != null)
            {
                clearEquations();
                addEquation(eq);

                //Restock combo box with new equations
                for (int i = 0; i < eq.length; i++)
                    eqCombo.addItem(eq[i].getPrefix());
            }
        }
        catch (IOException e)
        {
            JOptionPane.showMessageDialog(null, "ERR4: Unable to read or access file", "alert", JOptionPane.ERROR_MESSAGE);
        }
    }
}

/**
 * Add an equation to the Graph
 * @param eq equation
 */
private void addEquation(String eq)
{
    try
    {
        if (eq != null && !eq.equals(""))
        {
            Equation equation = new Equation(eq);
            eqCombo.addItem(eq);
            graph.addEquation(equation);
        }
    }
    catch (EquationSyntaxException e)
    {
        JOptionPane.showMessageDialog(null, "ERR2: Equation is not well-formed", "alert", JOptionPane.ERROR_MESSAGE);
    }
}
/**
 * Add multiple equations to Graph
 * @param eq equation array
 */
private void addEquation(Equation[] eq)
{
    for (int i = 0; i < eq.length; i++)
    {
        graph.addEquation(eq[i]);
    }
}

/**
 * Remove equation from Graph
 * @param index index to remove
 */
private void removeEquation(int index)
{
    if (index >= 0)
    {
        graph.removeEquation(index);
        eqCombo.removeItem(eqCombo.getSelectedItem());
    }
}

/**
 * Read file and extract equations into an array. Any errors on an equation halt the loading of the entire file
 * @param file name of file containing equations
 * @return array of equations
 * @throws IOException
 */
public Equation[] readEquationsFromFile(String file) throws IOException
{
    ArrayList<Equation> eqList = new ArrayList<Equation>(20);

    if (file == null)
        return null;

    String line;
    int lineCount = 1;
    try
    {
        BufferedReader br = new BufferedReader(new FileReader(file));
        while ((line = br.readLine()) != null)
        {
            Equation eq = new Equation(line);
            eqList.add(eq);
            lineCount++;
        }
        br.close();
        return ((Equation[])(eqList.toArray(new Equation[0])));
    }
    catch (EquationSyntaxException e)
    {
        JOptionPane.showMessageDialog(null, "ERR2.1: Equation on line " + lineCount + " is not well-formed", "alert", JOptionPane.ERROR_MESSAGE);
        return null;
    }
}

/**
 * Set up Plotter object and draw the graph.
 * @param args command line arguments for Plotter
 */
public static void main(String[] args)
{
    Scanner s = new Scanner(System.in);
    String eqFile = null;
    try
    {
        ///double minX = Double.parseDouble(args[0]);
    //  double maxX = Double.parseDouble(args[1]);
    //  double frequency = Double.parseDouble(args[2]);
        double minX = -10; 
        double maxX = 10; 
        double frequency = 0.01;

        if (args.length > 3)
            eqFile = args[3];

        Plotter plotterGUI = new Plotter(minX, maxX, frequency, eqFile);
        plotterGUI.setVisible(true);
        plotterGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }
    catch (NumberFormatException e)
    {
        System.out.println("ERR: Invalid arguments");
    }
    catch (GraphArgumentsException e)
    {
        System.out.println(e.getMessage());
    }
    catch (IOException e)
    {
        System.out.print("ERR4: Unable to read or access file");
    }

    }
}
import java.util.*;
导入java.io.*;
导入javax.swing.*;
导入javax.swing.Timer;
导入java.awt.*;
导入java.awt.event.*;
公共类绘图仪扩展JFrame实现ActionListener
{   
private JMenuBar menuBar=new JMenuBar();
私有JMenu fileMenu=新JMenu(“文件”);
私有JMenuItem openMenuItem=新JMenuItem(“打开”);
private JMenuItem saveMenuItem=新的JMenuItem(“保存”);
私有JMenuItem exitMenuItem=新JMenuItem(“退出”);
私有jcombox eqCombo=新jcombox();
私人JButton addButton、removeButton、clearButton、playbutton;
私有图;
专用JPanel用户面板、sliderPanel;
专用滑动滑块;
私有JTextField字段;
公共绘图仪(双低、双高、双频、字符串文件)抛出GraphgumentsException、IOException
{
超级(“绘图仪”);
createNewGraph(低x、高x、频率、文件);
createLayout();
createsliderpanel();
}
私有void createLayout()引发GraphChargementsException
{
容器c=getContentPane();
c、 setLayout(新的BorderLayout());
设置大小(600500);
c、 添加(图形、边框布局、中心);
c、 添加(userPanel,BorderLayout.NORTH);
c、 添加(滑动面板,BorderLayout.SOUTH);
createMenuBar();
}
/**
*创建一个新的图形实例,并将公式从文件添加到图形中
*@param eqFile存储公式的文件
*@抛出异常
*/
私有void createNewGraph(双minX、双maxX、双freq、字符串eqFile)抛出GraphgumentsException、IOException
{
方程[]eq=null;
图形=新图形(minX、maxX、freq);
eq=从文件(eqFile)读取的等式;
如果(等式!=null)
加法(eq);
图.立根背景(颜色.白色);
userPanel=createUserPanel(eq);
}
私有void createMenuBar()
{
菜单栏。添加(文件菜单);
fileMenu.add(openMenuItem);
添加(saveMenuItem);
fileMenu.addSeparator();
fileMenu.add(exitMenuItem);
openMenuItem.addActionListener(此);
saveMenuItem.addActionListener(此);
exitMenuItem.addActionListener(此);
setJMenuBar(菜单栏);
}
/**
*在GUI顶部创建用户面板,用于添加和编辑功能
*@param eq等式列表添加到组合框中
*@包含按钮和可编辑组合框的返回面板
*/
私有JPanel createUserPanel(等式[]等式)
{
JPanel up=newjpanel(newflowlayout(FlowLayout.LEFT));
eqCombo.setEditable(真);
如果(等式!=null)
{
//将所有方程式添加到组合框中
for(int i=0;iimport java.util.*;
import java.io.*;
import javax.swing.*;
import javax.swing.Timer;
import java.awt.*;
import java.awt.event.*;


public class Plotter extends JFrame implements ActionListener
{   

private JMenuBar menuBar = new JMenuBar();
private JMenu fileMenu = new JMenu("File");
private JMenuItem openMenuItem = new JMenuItem("Open");
private JMenuItem saveMenuItem = new JMenuItem("Save");
private JMenuItem exitMenuItem = new JMenuItem("Exit");

private JComboBox eqCombo = new JComboBox();
private JButton addButton, removeButton, clearButton , playbutton ;
private Graph graph;
private JPanel userPanel , sliderPanel;
private JSlider slider;
private JTextField field;

public Plotter(double lowX, double highX, double frequency, String file) throws GraphArgumentsException, IOException
{
    super("Plotter");

    createNewGraph(lowX, highX, frequency, file);
    createLayout();
    createsliderpanel();
}

private void createLayout() throws GraphArgumentsException
{
    Container c = getContentPane();
    c.setLayout(new BorderLayout());
    setSize(600,500);
    c.add(graph, BorderLayout.CENTER);
    c.add(userPanel, BorderLayout.NORTH);
    c.add(sliderPanel , BorderLayout.SOUTH);
    createMenuBar();
}



/**
 * Creates a new Graph instance and adds equations from file into Graph
 * @param eqFile file where equations are stored
 * @throws IOException
 */
private void createNewGraph(double minX, double maxX, double freq, String eqFile) throws GraphArgumentsException, IOException
{
    Equation[] eq = null;
    graph = new Graph(minX, maxX, freq);

    eq = readEquationsFromFile(eqFile);

    if (eq != null)
        addEquation(eq);

    graph.setBackground(Color.WHITE);
    userPanel = createUserPanel(eq);
}

private void createMenuBar()
{
    menuBar.add(fileMenu);
    fileMenu.add(openMenuItem);
    fileMenu.add(saveMenuItem);
    fileMenu.addSeparator();
    fileMenu.add(exitMenuItem);
    openMenuItem.addActionListener(this);
    saveMenuItem.addActionListener(this);
    exitMenuItem.addActionListener(this);
    setJMenuBar(menuBar);
}

/**
 * Create user panel at top of the GUI for adding and editing functions
 * @param eq equation list to add into the combo box
 * @return panel containing buttons and an editable combo box
 */
private JPanel createUserPanel(Equation[] eq)
{
    JPanel up = new JPanel(new FlowLayout(FlowLayout.LEFT));
    eqCombo.setEditable(true);

    if (eq != null)
    {
        //Add all equations into the combo box
        for (int i = 0; i < eq.length; i++)
            eqCombo.addItem(eq[i].getPrefix());
    }

    addButton = new JButton("Add");
    removeButton = new JButton("Remove");
    clearButton = new JButton("Clear");

    addButton.addActionListener(this);
    removeButton.addActionListener(this);
    clearButton.addActionListener(this);

    up.add(eqCombo);
    up.add(addButton);
    up.add(removeButton);
    up.add(clearButton);


    return up;





}

// slider panel
private JPanel createsliderpanel()
{
    JPanel down = new JPanel(new FlowLayout(FlowLayout.LEFT));

    playbutton = new JButton("Play");
    slider = new JSlider();
    field = new JTextField();


    down.add(playbutton);
    down.add(slider);
    down.add(field);


    return down;
}



/**
 * Check action lister for button and menu events
 */
public void actionPerformed(ActionEvent e)
{
    if (e.getSource() == addButton)
        addEquation((String)eqCombo.getSelectedItem());
    else if (e.getSource() == removeButton)
        removeEquation(eqCombo.getSelectedIndex());
    else if (e.getSource() == saveMenuItem)
        saveEquationList();
    else if (e.getSource() == openMenuItem)
        loadEquations();
    else if (e.getSource() == clearButton)
        clearEquations();
    else if (e.getSource() == exitMenuItem)
        System.exit(0);
}

/**
 * Save equations to file
 *
 */
private void saveEquationList()
{
    try
    {
        PrintWriter out = new PrintWriter(new FileWriter("myeq.txt"));
        for (int i = 0; i < eqCombo.getItemCount(); i++)
            out.println(eqCombo.getItemAt(i));

        out.close();
    }
    catch (IOException e)
    {
        System.out.println(e);

    }
}


private void clearEquations()
{
    graph.removeAllEquations();
    eqCombo.removeAllItems();
}

/**
 * Load equations from file into graph
 *
 */
private void loadEquations()
{
    String file=null;
    JFileChooser fc = new JFileChooser();

    fc.showOpenDialog(null);
    if (fc.getSelectedFile() != null)
    {
        file = fc.getSelectedFile().getPath();

        try
        {
            Equation[] eq = readEquationsFromFile(file);
            if (eq != null)
            {
                clearEquations();
                addEquation(eq);

                //Restock combo box with new equations
                for (int i = 0; i < eq.length; i++)
                    eqCombo.addItem(eq[i].getPrefix());
            }
        }
        catch (IOException e)
        {
            JOptionPane.showMessageDialog(null, "ERR4: Unable to read or access file", "alert", JOptionPane.ERROR_MESSAGE);
        }
    }
}

/**
 * Add an equation to the Graph
 * @param eq equation
 */
private void addEquation(String eq)
{
    try
    {
        if (eq != null && !eq.equals(""))
        {
            Equation equation = new Equation(eq);
            eqCombo.addItem(eq);
            graph.addEquation(equation);
        }
    }
    catch (EquationSyntaxException e)
    {
        JOptionPane.showMessageDialog(null, "ERR2: Equation is not well-formed", "alert", JOptionPane.ERROR_MESSAGE);
    }
}
/**
 * Add multiple equations to Graph
 * @param eq equation array
 */
private void addEquation(Equation[] eq)
{
    for (int i = 0; i < eq.length; i++)
    {
        graph.addEquation(eq[i]);
    }
}

/**
 * Remove equation from Graph
 * @param index index to remove
 */
private void removeEquation(int index)
{
    if (index >= 0)
    {
        graph.removeEquation(index);
        eqCombo.removeItem(eqCombo.getSelectedItem());
    }
}

/**
 * Read file and extract equations into an array. Any errors on an equation halt the loading of the entire file
 * @param file name of file containing equations
 * @return array of equations
 * @throws IOException
 */
public Equation[] readEquationsFromFile(String file) throws IOException
{
    ArrayList<Equation> eqList = new ArrayList<Equation>(20);

    if (file == null)
        return null;

    String line;
    int lineCount = 1;
    try
    {
        BufferedReader br = new BufferedReader(new FileReader(file));
        while ((line = br.readLine()) != null)
        {
            Equation eq = new Equation(line);
            eqList.add(eq);
            lineCount++;
        }
        br.close();
        return ((Equation[])(eqList.toArray(new Equation[0])));
    }
    catch (EquationSyntaxException e)
    {
        JOptionPane.showMessageDialog(null, "ERR2.1: Equation on line " + lineCount + " is not well-formed", "alert", JOptionPane.ERROR_MESSAGE);
        return null;
    }
}

/**
 * Set up Plotter object and draw the graph.
 * @param args command line arguments for Plotter
 */
public static void main(String[] args)
{
    Scanner s = new Scanner(System.in);
    String eqFile = null;
    try
    {
        ///double minX = Double.parseDouble(args[0]);
    //  double maxX = Double.parseDouble(args[1]);
    //  double frequency = Double.parseDouble(args[2]);
        double minX = -10; 
        double maxX = 10; 
        double frequency = 0.01;

        if (args.length > 3)
            eqFile = args[3];

        Plotter plotterGUI = new Plotter(minX, maxX, frequency, eqFile);
        plotterGUI.setVisible(true);
        plotterGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }
    catch (NumberFormatException e)
    {
        System.out.println("ERR: Invalid arguments");
    }
    catch (GraphArgumentsException e)
    {
        System.out.println(e.getMessage());
    }
    catch (IOException e)
    {
        System.out.print("ERR4: Unable to read or access file");
    }

    }
}