請看看下面的代碼的Java 2D API:空指針異常
package java2D;
import java.awt.BasicStroke;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.*;
import java.awt.*;
public class Joins extends JFrame
{
private JPanel centerPanel;
public Joins()
{
this.setLayout(new BorderLayout());
this.add(createCenterPanel(),"Center");
this.setSize(200,250);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private JPanel createCenterPanel()
{
centerPanel = new JPanel();
//centerPanel.setLayout(new FlowLayout());
Graphics g = centerPanel.getGraphics();
Graphics2D g2d = (Graphics2D)g;
BasicStroke bs1 = new BasicStroke(8, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL);
g2d.setStroke(bs1);
g2d.drawRect(15, 15, 80, 50);
BasicStroke bs2 = new BasicStroke(8, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
g2d.setStroke(bs2);
g2d.drawRect(125, 15, 80, 50);
BasicStroke bs3 = new BasicStroke(8, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
g2d.setStroke(bs3);
g2d.drawRect(235, 15, 80, 50);
return centerPanel;
}
public static void main(String[]args)
{
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
new Joins();
}
});
}
}
此代碼生成NullPointerException異常。我需要繪製centerPanel
中的圖形。當我開發Swing應用程序時,我通常將JFrame區域分成JPanel數量,而且我也是在這裏完成的,但最終發生了NullPointerException!
以下是錯誤
run:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at java2D.Joins.createCenterPanel(Joins.java:34)
at java2D.Joins.<init>(Joins.java:17)
at java2D.Joins$1.run(Joins.java:55)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:705)
at java.awt.EventQueue.access$000(EventQueue.java:101)
at java.awt.EventQueue$3.run(EventQueue.java:666)
at java.awt.EventQueue$3.run(EventQueue.java:664)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:675)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
BUILD SUCCESSFUL (total time: 6 seconds)
請幫幫忙!
您的堆棧跟蹤添加到這個問題吧。 – Perception 2013-02-19 19:54:53
@Perception:對不起,我加了 – 2013-02-19 19:58:16
哎呀! http://stackoverflow.com/questions/8356111/drawing-on-a-jpanel你真的應該考慮延長JPanel並通過繪製的paintComponent(特別是這個原因)。你正在尋找很多馬車行爲,如果你直接繪製它(重繪等...) – 2013-02-19 20:07:14