カスタムJLayeredPaneを使用しています。JLayeredPaneのさまざまなレイヤーに描画する必要のあるシェイプがいくつかあります。
これをテストするために、JPanelを作成し、そのグラフィックスを尋ねます。次に、そのJPanel(グラフィックの準備)にテスト長方形を描画し、JLayeredPaneのpaintComponentメソッドで最終的にすべてを描画します。しかし、これは失敗します(NullPointerException)。
public class MyCustomPanel extends JLayeredPane {
// test
JPanel testpane;
Graphics g2;
// test
// constructor
public MyCustomPanel() {
testpane = new JPanel();
this.add(testpane, new Integer(14));
g2 = testpane.getGraphics();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g2.drawRect(10, 10, 300, 300);
}
}
// run:
//Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
// at view.MyCustomPanel.paintComponent(MyCustomPanel.java:65)
JLayeredPane内からそのようなJPanelを利用できないのはなぜですか?paintComponentメソッド内からJLayeredPaneに直接描画できますが、これはJLayeredPaneのデフォルトのパネルにあります。JLayeredPaneに追加されたいくつかのレイヤーを作成して描画する必要があります。
私は何が間違っているのですか?:s