2017-06-08 57 views
0

在我的計劃,我有以下代碼:的Java的drawImage()不拉絲

package io.github.AdmiralSbs.DiceWars; 

import javax.imageio.ImageIO; 
import javax.swing.*; 

import java.awt.*; 
import java.awt.image.BufferedImage; 
import java.io.*; 
import java.util.Scanner; 

public class HexDisplay extends JPanel { 
    private static final long serialVersionUID = 1L; 
    public static final int SIZE = 200; 
    private int height; 
    private int width; 
    private Hex[][] hex; 
    private BufferedImage myImage; 
    private Graphics drawer; 

    public HexDisplay(File f) throws IOException { 
     Scanner key = new Scanner(f); 
     int[] temp = commaSplit(key.nextLine()); 
     height = temp[0]; 
     width = temp[1]; 
     hex = new Hex[width][height]; 
     for (int w = 0; w < width; w++) { 
      for (int h = 0; h < height; h++) { 
       //temp = commaSplit(key.nextLine()); 
       if (h % 2 == 0) 
        hex[w][h] = new Hex((int) (SIZE * (w + 0.5)), 
          (int) (SIZE * (h + 0.5)), SIZE); 
       else 
        hex[w][h] = new Hex((int) (SIZE * (w + 1.5)), 
          (int) (SIZE * (h + 0.5)), SIZE); 
       System.out.println(hex[w][h].getX() + " " + hex[w][h].getY()); 
      } 
     } 
     key.close(); 
     starting(); 
     ImageIO.write(myImage, "jpg", new File("outPic.jpg")); 
    } 

    public void starting() { 
     setPreferredSize(new Dimension(400,400)); 
     setLayout(new FlowLayout()); 
     myImage = new BufferedImage(400, 400, BufferedImage.TYPE_INT_RGB); 
     drawer = myImage.getGraphics(); 
     drawer.setColor(Color.BLUE); 
     drawer.fillRect(0, 0, 400, 400); 
     drawStuff(drawer); 
     repaint(); 
    } 

    public int[] commaSplit(String s) { 
     String[] str = s.split(","); 
     int[] ret = new int[str.length]; 
     for (int i = 0; i < str.length; i++) { 
      ret[i] = Integer.parseInt(str[i]); 
     } 
     return ret; 
    } 

    public void paintComponents(Graphics g) { 
     g.drawImage(myImage, 0, 0, this); 
     System.out.println("Painted"); 
    } 

    public void drawStuff(Graphics g) { 
     for (int w = 0; w < width; w++) { 
      for (int h = 0; h < height; h++) { 
       hex[w][h].draw(g); 
      } 
     } 
     System.out.println("Drew"); 
     revalidate(); 
     repaint(); 
     paintComponents(g); 
    } 
} 

我會希望發生的是包含此JPanel的顯示圖像的幀,但事實並非如此。所有System.out.println()方法都按預期方式調用,並且我可以將該圖像另存爲.jpg文件。但是,圖像不顯示在GUI中。可以做什麼?

+2

對於風俗畫的第一線,考慮調用'paintComponent',而不是'paintComponents'。 – Berger

+0

你的'starting()'從哪裏調用? –

+0

開始()從構造函數 –

回答

4

你有一個錯字:

//      v 
public void paintComponents(Graphics g) { 

應該paintComponent

,並應包含超方法的調用:

super.paintComponent(g); 

如方法

+1

調用OP也應該使用@Override註釋來防止在將來。 –

+0

@SteveSmith我的回答最初表示,但Berger指出,['paintComponents'](http://docs.oracle.com/javase/8/docs/api/java/awt/Container.html#paintComponents -java.awt.Graphics-)實際上是一種存在的方法。 (我從來沒有注意到它,我猜它必須是一個較老的AWT方法,因爲Swing組件通常使用'paintChildren'來達到這個目的。) – Radiodef

+0

我所在的計算機不允許使用註釋,很糟糕 –