请看下面的代码
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)
请帮忙!