为什么这段代码有错误?

时间:2017-04-19 05:46:02

标签: java swing graphics nullpointerexception awt

我的代码是

import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

@SuppressWarnings("serial")
public class point extends JFrame {

private JPanel contentPane;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                point frame = new point();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public point() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setType(Type.UTILITY);
    getContentPane().setLayout(null);

    JPanel panel = new JPanel();
    panel.setBounds(0, 0, 300, 300);
    getContentPane().add(panel);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(200, 200, 450, 300);
    contentPane = new JPanel();

    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    Graphics g = panel.getGraphics();

    g.drawLine(10, 10, 20, 20); 

}
}

在g.drawLine或其他绘图中我有错误但是eclipse note在代码中有错误 我的错误是:

> java.lang.NullPointerException
    at org.eclipse.wb.swing.point.<init>(point.java:54)
    at org.eclipse.wb.swing.point$1.run(point.java:20)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$500(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

感谢您的帮助

我只需要在面板中绘制任何东西 我的IDE是eclipse并使用WindowsBuilder和My IDE在代码中没有出错 我尝试其他图形绘制,但也有错误

0 个答案:

没有答案