次のコードをご覧ください
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)
助けてください!