我正在尝试做一个简单的软件来绘制一个矩形和一些行,但是当我尝试在我的 JFrame 中添加我的面板(扩展为 JPanel)时出现意外的java.lang.NullPointerException 。代码是:
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JPanel;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import com.Entity.robot.Map;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class MainWindow {
private JFrame frame;
private JFileChooser fileChooser;
private MapGUI panel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
panel= new MapGUI();
panel.setBounds(200, 100, 500, 250);
frame.getContentPane().add(panel); <---- THE EXCEPTION IS HERE**
frame = new JFrame();
frame.getContentPane().setLayout(null);
frame.setResizable(false);
frame.setBounds(100, 100, 1500, 900);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmOpenMapFrom = new JMenuItem("Open map from...");
mnFile.add(mntmOpenMapFrom);
}
}
class MapGUI extends JPanel {
public MapGUI(){
setPreferredSize(new Dimension(300, 300));
}
public void paint (Graphics g){
g.setColor(Color.white);
g.drawRect(1, 1, 500, 250);
}
}
我该如何解决?