2014-06-18 2 views
-1

많은 이미지를 칠할 클래스 MenuScreen이 있습니다. (순간에 4 당신에게 많은하지 않을 수 있지만, 그것은 나에게])BufferedImage가 때때로 렌더링되지 않습니다.

하나만 상관없이, 때로는 그들이 어떤 반 렌더링 무엇을 렌더링하지 않으며, 다른 시간들이 완전히 렌더링,

때때로 그들은 여기

이 는 는

사람은 이런 이유를 이해하는 데 도움이 수

public List<BufferedImage> im; 

public MenuScreen() { 
    setTitle("ALevelUp 0.0.1 Alpha"); 

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    initImages(); 
    JPanel p = new JPanel(new GridLayout(1, 1)); 

    p.add(new JLabel(new ImageIcon(im.get(0)))); 

    add(p); 
    setSize(766, 500); 
    setLocationRelativeTo(null); 
    setVisible(true); 
    System.err.println(getHeight() + "," + getWidth()); 

    Graphics2D g = (Graphics2D) im.get(0).getGraphics(); 
    draw(g); 
} 

public final void initImages() { 
    im = a.init(); 
} 

public final void draw(Graphics2D g) { 
    BufferedImage s1 = im.get(1); 
    Graphics2D s1g = (Graphics2D) s1.getGraphics(); 
    s1g.setFont(scale(a.getFont(), s1g, "Slot 1", s1)); 
    s1g.setColor(Color.black); 
    s1g.drawString("Slot 1", s1.getWidth()/2 - 23, s1.getHeight()/2 + 7); 
    g.drawImage(s1, (getWidth()/2) - (s1.getWidth()/2) - 21, 
      47, rootPane); 
    s1g.setColor(new Color(253, 198, 147)); 
    s1g.fillRect(106, 20, 100, 20); 
    s1g.setColor(Color.black); 
    s1g.drawString("Slot 2", s1.getWidth()/2 - 23, s1.getHeight()/2 + 7); 
    g.drawImage(s1, getWidth()/2 - s1.getWidth()/2 - 21, 179, rootPane); 
    s1g.setColor(new Color(253, 198, 147)); 
    s1g.fillRect(106, 20, 100, 20); 
    s1g.setColor(Color.black); 
    s1g.drawString("Slot 3", s1.getWidth()/2 - 23, s1.getHeight()/2 + 7); 
    g.drawImage(s1, getWidth()/2 - s1.getWidth()/2 - 21, 311, rootPane); 
} 

public Font scale(Font f, Graphics g, String text, BufferedImage img) { 
    float ntry = 20.0f; 
    Font font = null; 

    while (2 < 3) { 
     font = f.deriveFont(ntry); 
     FontMetrics fm = g.getFontMetrics(font); 
     int width = fm.stringWidth(text); 
     if (width < img.getWidth()) { 
      return font; 
     } 
    } 
} 
무엇을 나는 그것을 해결하기 위해 할 수있는 내 코드

모두는 (주 하나는 여전히 렌더링)로 렌더링하지?

편집 : 당신이 그들을 필요로하는 경우 여기, 이미지 리소스 위치 :
The Main Screen
The Slot Panels
How it looks when it works

+2

곧 도움을받을 수없는 경우, 작성 및 게시 생각해 보자 [, 최소를 완료하고 검증 가능한 예제 프로그램 (http://stackoverflow.com/help/mcve) 당신이에 코드를 응축 곳 여전히 컴파일되고 실행되는 가장 작은 비트는 외부 종속성 (예 : 데이터베이스에 연결해야 함)이 없으며 문제와 관련이없는 추가 코드가 없지만 여전히 문제를 보여줍니다. 이미지를 사용해야하는 경우 온라인에서 이미지를 사용할 수 있는지 확인하십시오. –

+2

및 무엇이든 읽기 전에 [Oracle trail 2D Graphics] (http://docs.oracle.com/javase/tutorial/2d/index.html) – mKorbel

+0

getGraphics를 사용하지 마십시오. Swing에서 페인팅이 수행되는 방식이 아닙니다. – MadProgrammer

답변

4

나는 일을 뭔가를 얻을 수있는 대부분의 코드를 수정했다. 나는 이것이 당신이 원하는 것이라고 생각하고 있습니다.

enter image description here

는 여기에 내가 변경 한 내용입니다.

  1. 은 내가 Event Dispatch thread에 스윙 구성 요소를 넣어 SwingUtilities의 invokeLater라는 주요 방법을 추가했습니다.

  2. 코드를 DrawImage, DrawingPanel 및 Snippet의 3 가지 클래스로 나눕니다. DrawImage는 4 개의 이미지를 만듭니다. DrawingPanel은 4 개의 이미지를 JPanel에 그립니다. 스 니펫은 JFrame을 만들고 JFrame에 드로잉 패널을 추가합니다.

  3. 드로잉 패널의 크기를 4 슬롯으로 유지하도록 정의했습니다. JFrame이 드로잉 패널을 잡는 데 적당한 크기가되도록 JFrame을 포장했습니다.

  4. 나는 paintComponent 메서드를 오버라이드하여 이미지 목록에서 네 개의 이미지를 그립니다. 이러한 이미지는 이미 DrawImage 클래스에서 만들어졌습니다. super.paintComponent를 호출하여 모든 Swing 하위 구성 요소가 올바르게 그려 졌는지 확인합니다.

  5. 스윙 GUI를 만들기 전에 이미지를 만들었습니다.

  6. 내가 만든 방법을 사용하여 centerString 이미지의 가운데에 텍스트를 넣었습니다. 규모 방법 만 남겼습니다.

다음은 수정 된 코드입니다. 당신과는 달리, 그것은 실행 가능합니다.

package snippet; 

import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.Font; 
import java.awt.FontMetrics; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.Rectangle; 
import java.awt.font.FontRenderContext; 
import java.awt.geom.Rectangle2D; 
import java.awt.image.BufferedImage; 
import java.util.ArrayList; 
import java.util.List; 

import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.SwingUtilities; 

public class Snippet implements Runnable { 

    private JFrame frame; 

    private List<BufferedImage> imageList; 

    public Snippet() { 
     imageList = new ArrayList<BufferedImage>(); 
     new DrawImage().createImages(); 
    } 

    @Override 
    public void run() { 
     frame = new JFrame(); 
     frame.setTitle("ALevelUp 0.0.1 Alpha"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     DrawingPanel p = new DrawingPanel(); 
     frame.add(p); 

     frame.pack(); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 

     System.out.println(frame.getHeight() + "," + frame.getWidth()); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Snippet()); 
    } 

    public class DrawingPanel extends JPanel { 

     private static final long serialVersionUID = 
       2535522354552193273L; 

     public DrawingPanel() { 
      this.setPreferredSize(new Dimension(550, 350)); 
     } 

     @Override 
     protected void paintComponent(Graphics g) { 
      super.paintComponent(g); 

      int x = 50; 
      int y = 50; 

      for (int i = 0; i < 2; i++) { 
       BufferedImage image = null; 
       for (int j = 0; j < 2; j++) { 
        image = imageList.get(i * 2 + j); 
        g.drawImage(image, x, y, this); 
        x += image.getWidth() + 50; 
       } 
       x = 50; 
       y += image.getHeight() + 50; 
      } 
     } 
    } 

    public class DrawImage { 

     public void createImages() { 
      imageList.add(createImage("Slot 1")); 
      imageList.add(createImage("Slot 2")); 
      imageList.add(createImage("Slot 3")); 
      imageList.add(createImage("Slot 4")); 
     } 

     private BufferedImage createImage(String text) { 
      Rectangle r = new Rectangle(0, 0, 200, 100); 
      BufferedImage image = new BufferedImage(r.width, r.height, 
        BufferedImage.TYPE_INT_RGB); 

      Graphics2D g = (Graphics2D) image.getGraphics(); 
      Font font = g.getFont(); 
      g.setFont(scale(font, g, text, image)); 
      g.setColor(Color.BLACK); 
      g.fillRect(0, 0, image.getWidth(), image.getHeight()); 
      g.setColor(Color.YELLOW); 
      centerString(g, r, text, font); 
      g.dispose(); 

      return image; 
     } 

     private Font scale(Font f, Graphics g, String text, 
       BufferedImage img) { 
      float ntry = 20.0f; 
      Font font = null; 

      while (2 < 3) { 
       font = f.deriveFont(ntry); 
       FontMetrics fm = g.getFontMetrics(font); 
       int width = fm.stringWidth(text); 
       if (width < img.getWidth()) { 
        return font; 
       } 
      } 
     } 

     /** 
     * This method centers a <code>String</code> in 
     * a bounding <code>Rectangle</code>. 
     * @param g - The <code>Graphics</code> instance. 
     * @param r - The bounding <code>Rectangle</code>. 
     * @param s - The <code>String</code> to center in the 
     * bounding rectangle. 
     * @param font - The display font of the <code>String</code> 
     * 
     * @see java.awt.Graphics 
     * @see java.awt.Rectangle 
     * @see java.lang.String 
     */ 
     private void centerString(Graphics g, Rectangle r, String s, 
       Font font) { 
      FontRenderContext frc = 
        new FontRenderContext(null, true, true); 

      Rectangle2D r2D = font.getStringBounds(s, frc); 
      int rWidth = (int) Math.round(r2D.getWidth()); 
      int rHeight = (int) Math.round(r2D.getHeight()); 
      int rX = (int) Math.round(r2D.getX()); 
      int rY = (int) Math.round(r2D.getY()); 

      int a = (r.width/2) - (rWidth/2) - rX; 
      int b = (r.height/2) - (rHeight/2) - rY; 

      g.setFont(font); 
      g.drawString(s, r.x + a, r.y + b); 
     } 

    } 

} 
+0

좋은 예가 있습니다 .... – Braj

관련 문제