• 締切済み

Graphics gra = this.getGraphics( );について

public void drawPhotograph( ) { Graphics gra = this.getGraphics( ); if (image != null) { x = 0; y = 0; gra.drawImage(image,x,y,this); } } この場合、graの値がnullとなり、実行時に、NullPointer Exceptionが起こります。その原因は何なのでしょうか、また回避策はどのようにすればよいでしょうか?

みんなの回答

  • ssr-y6
  • ベストアンサー率71% (5/7)
回答No.3

 ビジュアルコンポーネントのグラフィックコンテキストが有効に取得できるのは、 そのコンポーネットが実際に画面に表示されてからです。 以下の例を実行し、コンソールに表示される文字と画面に表示されるフレームの関係を見てもらえばわかると思います。 対処法としては、キャンバスなどのグラフィックコンテキストは直接取得しないで、 paintなどが渡してくれるものを極力使うように心がけることでしょうか。 import java.awt.*; import java.awt.image.*; import java.awt.event.*; class imagecanvas extends Canvas { private BufferedImage OSI; public imagecanvas() { CreateOffScreenImage(); GetCanvasGraphics(1); setVisible(true); GetCanvasGraphics(2); }; private void CreateOffScreenImage() { OSI = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB); Graphics g = OSI.getGraphics(); g.setColor(Color.GREEN); g.fillRect(0, 0, 100, 100); g.setColor(Color.RED); g.fillOval(0, 0, 100, 100); }; public void GetCanvasGraphics(int n) { try { Thread.sleep(3000); } catch (Exception e) {}; System.out.print(Integer.toString(n) + ":"); System.out.println(this.getGraphics() == null ? "Null" : "Not Null"); }; public void paint(Graphics g) { g.drawImage(OSI, 0, 0, getWidth(), getHeight(), this); }; } public class gratest { public static void main(String args[]) { Frame MF = new Frame("Main Frame"); imagecanvas IC = new imagecanvas(); MF.add(IC, BorderLayout.CENTER); MF.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); }; }); MF.setSize(200, 200); MF.setVisible(true); IC.GetCanvasGraphics(3); System.out.print("End of Main"); }; }

全文を見る
すると、全ての回答が全文表示されます。
  • kacchann
  • ベストアンサー率58% (347/594)
回答No.2

>this.setVisible(true); >としてみましたが、やはり同じでうまくいきません。 PhotographPaneをvisibleにするのではなく、 PhotographPaneが乗っているウインドウ(UremjnFrame)のほうを visibleにしないといけない。 ウインドウがvisibleになった後に、 PhotographPaneのgetGraphics()メソッドを呼ぶと、 うまくいく。

全文を見る
すると、全ての回答が全文表示されます。
  • kacchann
  • ベストアンサー率58% (347/594)
回答No.1

>原因は何なのでしょうか getGraphics()というのは、 ComponentクラスのgetGraphics()のこと、でいいのかな? Component#getGraphics()がnullを返すのは、 たとえば、 (そのコンポーネントが乗っている)ウインドウがpack()されてなかったり、またはvisibleでなかったりした場合・・・だったと思う。 >また回避策はどのようにすればよいでしょうか (そのコンポーネントが乗っている)ウインドウがpack()された後や、visibleになった後で、(そのコンポーネントに対し)getGraphics()を使えばよい。 いちばん簡単でよく使われる方法は、 (そのコンポーネントの)paint()メソッドやpaintComponent()メソッド(※swingコンポーネントの場合)の内部で、getGraphics()を呼ぶ。 一例として、 たとえば、簡単に void paint(Graphics g) { drawPhotograph(); } とかやってみるだけでも、うまくいくような気がする。

urehss
質問者

補足

回答ありがとうございます。質問の説明を補足します。 JFrameを継承したコンポネントUremjnFrameに、いずれも JPanelを継承した、4つのコンポネントを載せています。 そのうちの一つが、photographPaneです。 PhotographPane photographPane = new PhotographPane( ); PhotographPaneクラスの中で this.setBounds(x,y,width,heigth); this.setLayout(null); this.setVisible(true); としてみましたが、やはり同じでうまくいきません。 pack( )の意味と使い方を教えて戴けないでしょうか。 私、いまインターネット通信囲碁対局 烏鷺苑名人 の開発 に着手したところです。よろしくお願いします。

全文を見る
すると、全ての回答が全文表示されます。

関連するQ&A

  • public void paint(Graphics g){

    public void paint(Graphics g){ g.setColor(new Color(ci, ci, ci)); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(Color.WHITE); g.drawString("Canvas表示", 20, 20); g.drawImage(image, x1, y1, this); g.drawImage(image1, x2, y2, this); } public void update(Graphics g){ paint(g); } public void run(){         //while(true)で永久ループ //imageの座標を変更する処理         //repaint();     } スレッドを使ってイメージの座標を変更し、イメージが動くプログラムを作りました。 これだと滑らかに動かないからpaintメソッドをもうひとつ作って 処理するpaintと描画するpaintとにわけたらいいと言われました。 ですがやりかたがわからないので教えてください。

  • マウスクリックで別のスレッドを動かしたい

    うまく動きません、どなたかご教示下さい(文字数が不足です) ===== public class ImgMove3 extends Applet implements Runnable , MouseListener { private int width , height ; private Thread th1 /*, th2*/ ; private boolean bLoopEnd = false ; private int x1 = 30 , y1 = 100 ; // private int x2 = 80 , y2 = 150 ; Image img1 , img2 ; AudioClip sound ; private int vx1 = 3 , vy1 = 2 ; // private int vx2 = 1 , vy2 = 1 ; Dimension d ; public void init() { d = getSize() ; width = d.width ; height = d.height ; this.addMouseListener(this) ; this.addMouseListener(new MyImage3(this)) ; img1 = getImage( getDocumentBase() , "ambulance.jpg" ) ; img2 = getImage( getDocumentBase() , "firecar.jpg" ) ; sound = getAudioClip( getDocumentBase() , "UFO.wav" ) ; } public void mouseEntered( MouseEvent e) { sound.play() ; } public void mouseClicked(MouseEvent e) { } public void start() { if(th1 == null) { th1 = new Thread(this); th1.start(); } } public void stop() { if( th1 != null ) { th1 = null ; } } public void run() { while(bLoopEnd == false) { move() ; repaint() ; try{ Thread.sleep( 10 ) ; } catch (InterruptedException e ) {} } } private void move() { if( x1 >= width - 130 ) { vx1 =- vx1 ; } if( y1 >= height - 110 ) { vy1 =- vy1 ; } if( x1 < 0 ) { vx1 =- vx1 ; } if( y1 < 0 ) { vy1 =- vy1 ; } } public void update( Graphics g1 ) { paint( g1 ) ; } public void paint( Graphics g1 ) { g1.drawImage( img1 , x1 , y1 , this ) ; } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e){ } } //======================================================================= class MyImage3 extends Applet implements Runnable , MouseListener { private int width , height ; private Thread th2 ; private boolean bLoopEnd = false ; private int x2 = 80 , y2 = 150 ; Image img2 ; AudioClip sound ; private int vx2 = 1 , vy2 = 1 ; Dimension d ; Image firecar ; ImgMove3 imv3 ; public MyImage3(ImgMove3 app) { imv3 = app ; imv3.img2 = getImage( getDocumentBase() , "firecar.jpg" ) ; } public void mouseEntered( MouseEvent e) { imv3.sound.play() ; } public void mouseClicked(MouseEvent e) { Graphics g1 =getGraphics(); g1.drawImage( img2 , x2 , y2 , this ) ; imv3.repaint(); } public void start() { if(th2 == null) { th2 = new Thread(this); th2.start(); } } public void stop() { if( th2 != null ) { th2 = null ; } } public void run() { while( th2 != null && bLoopEnd == false) { move() ; imv3.repaint() ; try{ Thread.sleep( 10 ) ; } catch (InterruptedException e ) {} } } private void move() { if( x2 >= width - 130 ) { vx2 =- vx2 ; } if( y2 >= height - 110 ) { vy2 =- vy2 ; } if( x2 < 0 ) { vx2 =- vx2 ; } if( y2 < 0 ) { vy2 =- vy2 ; } x2 += vx2 ; y2 += vy2 ; } public void update( Graphics g1 ) { imv3.paint( g1 ) ; } public void paint( Graphics g1 ) { g1.drawImage( img2 , x2 , y2 , this ) ; } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } }

    • ベストアンサー
    • Java
  • スレッドが動いてくれません。

    ボールを左から右に動かすようなプログラムを組んだのですがスレッドの部分がうまく動いてくれません。プログラムは下のものなのですがどこがいけないのでしょうか。教えてください。 import javax.swing.*; import java.awt.*; public class SampleBall extends JFrame implements Runnable{ SmapleCanvas samplecanvas; Image image=null; Graphics offg=null; int x1,y1=60; public SampleBall(){ super("Ball"); setSize(500,360); setDefaultCloseOperation(EXIT_ON_CLOSE); samplecanvas=new SmapleCanvas(); samplecanvas.setBounds(0,0,500,360); getContentPane().add(samplecanvas); } public static void main(String args[]){ new SampleBall().show(); Thread b1=new Thread(); b1.start(); } public void run(){ try{ x1=40; while(true){ x1=x1+10; if(x1>=500){ x1=10; } samplecanvas.repaint(); } }catch(Exception e){ System.out.println(e); } } class SmapleCanvas extends Canvas{ public void paint(Graphics g){ if(image==null){ image=createImage(500,360); offg=image.getGraphics(); offg.setColor(Color.white); offg.fillRect(0,0,500,360); } else{ offg.setColor(Color.white); offg.fillRect(0,0,500,360); g.drawImage(image,0,0,this); } offg.setColor(Color.blue); offg.fillOval(x1,y1,10,10); g.drawImage(image,0,0,this); } } }

    • ベストアンサー
    • Java
  • 「初心者です」-Xlint: deprecation

    import java.awt.*; import java.applet.*; public class ani_ball extends Applet implements Runnable { Thread th_mvball = null; int X,Y; double x1,y1; double x2,y2; double dx,dy; Graphics g; public void init() { this.setBackground(new Color(150,245,255)); this.X = 250; this.Y = 250; this.setSize(X,Y); this.x1 = this.x2 = this.X/2; this.y1 = this.y2 = this.Y/2; this.dx = 3; this.dy = 2; } public void paint(Graphics g) { g.setColor(Color.red); g.fillOval((int)(this.x2-3),(int)(this.y2-3),6,6); this.x1 = this.x2; this.y1 = this.y2; } public void start() { if(th_mvball == null) { th_mvball = new Thread(this); th_mvball.start(); } } public void run() { while(true) { try { this.move(); this.repaint(); Thread.sleep(10); } catch(InterruptedException e ) { this.stop(); } } } public void move() { if( y2 > Y ) { y2 = 2*Y - y1 - dy; dy = -dy; } else if ( y2 < 0) { y2 = -y1 - dy; dy = -dy; } else if ( x2 > X) { x2 = 2*X - x1 -dx; dx = -dx; } else if ( x2 < 0) { x2 = -x1 - dx; dx = -dx; } if( x2 < 0 ) { x2 = -x2 ; dx = -dx; } else if ( y2 < 0) { y2 = -y2; dy = -dy; } else if ( x2 > X) { x2 = 2*X - x2; dx = -dx; } else if ( y2 > Y) { y2 = 2*Y - y2; dy = -dy; } x2 = x1 + dx; y2 = y1 + dy; } public void stop() { if(th_mvball!=null) { th_mvball stop(); th_mvball=null; } } } ↑のプログラムをコンパイルすると、「-Xlint: deprecation オプションを指定して再コンパイルしてください」とエラーが出ます。 エラーの対処法、またはプログラムの訂正すべき箇所を教えてください。 よろしくお願いします。

    • ベストアンサー
    • Java
  • パネルの絵の差し替え方法

    JBuilderでJavaの開発を勉強しています。 パネルがクリックされるたびに、パネルに張られている絵を差し替えたいのですが最初の2回のクリックではパネルの絵が消えてしまい3回目からのクリックでは問題なく絵は切り替わります。下記のロジックで問題があるのでしょうか? メインフレームのパネルクリックイベントから"public void ChangeImage(int num)"関数を呼びます。 ************************************************* public class New_Panel extends Panel { Image img; Image im_off; Image im_on; //CONSTRUCT public Panel_FD() { im_off = Toolkit.getDefaultToolkit().getImage("OFF.jpg"); im_on = Toolkit.getDefaultToolkit().getImage("ON.jpg");   //初期イメージ img = Toolkit.getDefaultToolkit().getImage("ON.jpg"); } public void paint(Graphics g){ g.drawImage(img, 0, 0, this); } //イメージ変更 public void ChangeImage(int num){ Graphics g; img.flush(); img = this.createImage(100, 40); if (sw == 0) { g = img.getGraphics(); g.drawImage(im_off, 0, 0, this); } else { g = img.getGraphics(); g.drawImage(im_on, 0, 0, this); } //再描画 repaint(); } } *************************************************

    • ベストアンサー
    • Java
  • Graphicsについて

    Graphicsで描かれた線や図形は、ダブルバッファリングを使用しないと、ウィンドウのサイズを変更したり、別のウィンドウで覆ったりすると、描かれたものは消えてしまいます。 そこで今回JPanelを用いて、消えてしまわないようにしたいですが、 JPanel p = new JPanel(); Graphics g = p.getGraphics(); g.drawLine( x, x, y, y); のようにして、を実行すると上記の行為をすると消えてしまいます。JPanelはデフォルトでダブルバッファリングを備えているはずですよね。なぜなのでしょうか? どなたかご教授願います。宜しくお願いします。

    • ベストアンサー
    • Java
  • C#のGraphicsクラスについて(GDI+)

    以下のようにgraphicsクラスをつかった画像の描画をおこないました。 Graphics gr = Graphics.FromImage(mapObj); というふうにからのリソースからGraphicsオブジェクトをつくる方法です。 using System; using System.IO; using System.Windows.Forms; using System.Drawing; using System.Web; using System.Net; using System.Text; using System.Threading; using System.ComponentModel; public class MainClass{ public static void Main(string [] args){ NewForm formObj = new NewForm(); formObj.RenderMethod(); Application .Run(formObj); } } public class NewForm : Form{ public NewForm(){ this.Width = 500; this.Height = 500; } public void RenderMethod(){ Bitmap mapObj = new Bitmap(500,500); Graphics gr = Graphics.FromImage(mapObj); Image imageObj = Image.FromFile("C:\\test.jpg"); gr .DrawImage(imageObj, 0,0,150,150); this.BackgroundImage = mapObj; } } このほかに、フォームコントロールの thisl.CreateGraphics()という メソッドを使っても画像を描画できるとききました。 あるサンプルをみると public class NewForm : Form{ public NewForm(){ this.Width = 500; this.Height = 500; } public void RenderMethod(){ Graphics gr = this.CreateGraphics(); Image imageObj = Image.FromFile("C:\\test.jpg"); gr .DrawImage(imageObj, 0,0,150,150); } } とこのようにthis.CreateGraphics()をつかっていましたが 実際にはこれが描画されないのです。 Graphics gr = Graphics.FromImage(mapObj); というGraphicsクラスの静的メソッドを使う方法ではなく コントロールのCreateGraphicsメソッドをつかって描画するにはどうしたらよいのですか? 識者のかた、ご教授ください。

  • java ダブルバッファリングするがちらつく

    javaでゲームをつくろうかと考えています。 そこで、ダブルバッファリングを実装したのですが、ちらついてしまいます。 いろいろ検索をかけて調べたのですが、これ以上改善が見込めないので 質問します。 以下がソースコードです。 画面がちらつくので、画面のリフレッシュレートが関係しているのかわからず、 しかし、ふつうにjava applet でゲームがあるので、多分どこかが間違っていると思います。 ご指摘をお願いします。 import java.applet.Applet; import java.awt.*; import java.awt.event.*; import java.net.URL; /*<applet code="applet01" width="320" height="480"></applet>*/ public class applet01 extends Applet implements KeyListener, Runnable { String text = ""; Image image; int x = 100, y = 100; KeyInput key; Image image弾; Bullet bullet; int flag_x = 1; Image backbuffer; Graphics ct; Dimension dim; // 初期化 public void init() { // image = getImage( getDocumentBase(), "test.jpg" ); image = getImage( getCodeBase(), "test.jpg" ); image弾 = getImage( getCodeBase(), "弾.jpg" ); bullet = new Bullet(); key = new KeyInput(); dim = getSize(); backbuffer = createImage( dim.width, dim.height ); ct = backbuffer.getGraphics(); Thread th = new Thread( this ); th.start(); addKeyListener( this ); requestFocus(); } // public void run() { try { while(true) { repaint(); Thread.sleep(1000/60); if( x>640 ) flag_x = 1; if( x<0 ) flag_x = 0; if( 1 == flag_x ) x--; if( 0 == flag_x ) x++; } } catch( Exception err ) { } } // 描画 public void paint( Graphics g ) { ct.setColor( Color.white ); ct.fillRect( 0, 0, dim.width, dim.height ); ct.setColor( Color.red ); ct.fillRect( (dim.width/2)-50 , (dim.height/2)-50, x, y ); // 裏画面に描画 ct.drawString( "画面をクリックしてキーボードで操作できます。", 0, 20 ); ct.drawString( "Hello from Java!", 60, 100 ); ct.drawImage( image, x, y, this ); bullet.Draw( ct, this, image弾 ); // 裏画面を表に反映 g.drawImage( backbuffer, 0, 0, this ); } // キーの入力があったとき public void keyTyped( KeyEvent e ) { repaint(); } // キーが押されたとき public void keyPressed( KeyEvent e ) { key.keyPressed( e ); if( key.isPressing( KeyEvent.VK_UP ) ) y = y - 5; if( key.isPressing( KeyEvent.VK_DOWN ) ) y = y + 5; if( key.isPressing( KeyEvent.VK_LEFT ) ) x = x - 5; if( key.isPressing( KeyEvent.VK_RIGHT ) ) x = x + 5; if( KeyEvent.VK_UP == e.getKeyCode() ) y = y - 5; if( KeyEvent.VK_Z == e.getKeyCode() ) { bullet.x = x; bullet.y = y; } repaint(); } // キーが放されたとき public void keyReleased( KeyEvent e ) { key.keyReleased( e ); } }

    • ベストアンサー
    • Java
  • java 初心者です

    javaの勉強しようと思い、ゲームを作ることになったのですが、画像が表示されなくて困っています。 構想としてはメインクラスからフレームクラス(gameFrame)を呼び出し、フレームクラスから画像表示クラス(Layer)を呼び出したいのですが、 Exception in thread "main" java.lang.NullPointerException at Layer.paint(Layer.java:25) at Layer.<init>(Layer.java:17) at gameFrame.newLayer(gameFrame.java:25) at main.main(main.java:9) というエラーが出てうまくいきません。 下記にLayerクラスを載せるのでお願いします。 import java.awt.*; import javax.swing.*; public class Layer extends JPanel{ int x=0; int y=0; private static final long serialVersionUID = 1L; Image image = null; Layer(String img,int X,int Y){ image=roadImage(img); setVisible(true); x=X; y=Y; paint(this.getGraphics()); } public void paint(Graphics g){ System.out.println("ペイント"); System.out.println(image); g.drawImage(image,x,y,this); System.out.println("ペイント終わり"); } static Image roadImage(String path){System.out.println("イメージセット"); if(path == null){ System.out.println("pathはnullです"); } System.out.println("pathは"+path+"です。"); Toolkit kit = Toolkit.getDefaultToolkit(); return kit.getImage(path); } }

  • ウインドウを大きくしてもボールの動きが変わらない

     今晩は、java初心者です。  宜しくお願い致します。  "ComponentListener"でウインドウを"componentResized"してもボールの動く範囲 は変わりません、何故でしょうか。    "componentResized"では確かに"Resized"されたウインドウの大きさをとっていますが、 何故かボールの動きには反映されません。  宜しくお願いします。 ======================================================================================== public class Ball2 extends Applet implements Runnable , ComponentListener { public static final long serialVersionUID = 1L ; int width , height ; Thread thread ; boolean  LoopFlag = false  ; int x = 30 , y = 100 ; Image  offScreen ; Graphics screen ; int vx = 2 , vy = 2 ; public void init() { width = getSize().width ; height = getSize().height ; thread = new Thread( this ); thread.start(); offScreen = createImage( width, height ) ; screen = offScreen.getGraphics() ; addComponentListener(this) ; } public void componentResized( ComponentEvent e ) { width = getSize().width ; height = getSize().height ; } public void run() { while( LoopFlag == false ) { move() ; repaint() ; try { Thread.sleep( 10 ) ; } catch ( InterruptedException e ) {} } } private void move() { if( x >= width - 50 ) { vx =- vx ; } if( y >= height - 50 ) { vy =- vy ; } if( x < 0 ) { vx =- vx ; } if( y < 0 ) { vy =-vy ; } x += vx; y += vy; } public void update( Graphics g) { paint(g) ; } public void paint( Graphics g) { screen.clearRect( 0 , 0 , width , height ) ; screen.setColor( Color.blue ) ; screen.fillOval( x , y , 50 , 50 ) ; g.drawImage( offScreen , 0 , 0 , this ) ; } public void destroy() { LoopFlag = true ; } public void componentHidden( ComponentEvent e ){} public void componentMoved( ComponentEvent e ){} public void componentShown( ComponentEvent e ){} }

    • ベストアンサー
    • Java