2016-12-25 1 views
1

작은 타워 방어 게임 과 색상을 만들려고하는데 색상이 작동하지 않는 이유는 여기에 rects 그래픽을 그리는 방법입니다.graphics.setColor (color); 작동하지 않음

public static void fill(GridLocation loc, Color c){ 
    Main.frame.getGraphics().setColor(c); 
    Main.frame.getGraphics().fillRect(loc.toFrameLocation().x, loc.toFrameLocation().y, 20, 20); 
    Main.frame.getGraphics().dispose(); 
} 

과이 내가 내 문제를 JFrame의

public static void main(String[] args) { 
    frame = new JFrame("Tower defense"); 
    frame.setSize(1000, 700); 
    frame.setVisible(true); 
    frame.setLayout(null); 
    frame.setLocationRelativeTo(null); 
    frame.setResizable(false); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    while (frame.isVisible()){ 
     Grid.fill(new GridLocation(1,1), new Color(1F,0F,0F)); 
     Grid.fill(new GridLocation(2,1), Color.gray); 
     Grid.drawGrid(); 
     Grid.fill(new GridLocation(3,1), Color.green); 
    } 
} 

를 생성/호출하는 방법입니다 : 사각형은 항상 검은 색?

+1

이이를 달성 할 수 없습니다. [튜토리얼] (https://docs.oracle.com/javase/tutorial/uiswing/painting/)을 읽으십시오. – user1803551

+2

1. JPanel의 paintComponent 메소드를 그립니다. 2. 'while (true)'루프가 아닌 스윙 타이머를 사용하십시오. 3. 해당 Timer 내에서 도면 JPanel의 상태를 변경하고 (필드 변경) repaint()를 호출합니다. 그런 다음 paintComponent 메소드가 필드를 사용하여 그리는 방법을 알려줍니다. 5. 오버 라이드 내에서 수퍼 페인팅 메서드를 호출하는 것을 잊지 마십시오. –

+0

@DontKnowMuchButGettingBetter, user1803551 고마워 이제 작동합니다! – Rof

답변

3

그래픽 컨텍스트를 얻기 위해 구성 요소에서 getGraphics()을 사용하면 이렇게 얻은 그래픽이 유지되지 않습니다. 예를 들어 아래 코드에서 버튼을 누르면 파란색 직사각형이 나타나지만 GUI를 최소화하고 나중에 크기를 조정하면 사라지는 것을 볼 수 있습니다.

또한, 내 의견에 따라 : JPanel과의의 paintComponent 방법에

  1. 립니다.
  2. 스윙 타이머를 while (true) 루프가 아닌 루프를 사용하십시오.
  3. 해당 Timer 내에서 도면 JPanel의 상태를 변경하고 (필드 변경) repaint()를 호출하십시오.
  4. 그런 다음 paintComponent 메소드에서 필드를 사용하여 그리는 방법을 지정하십시오.
  5. 오버라이드 내에서 수퍼 페인팅 메서드를 호출하는 것을 잊지 마십시오. 예를 들어

:

import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.Graphics; 
import java.awt.event.ActionEvent; 
import javax.swing.*; 

@SuppressWarnings("serial") 
public class UnstableStableGraphics extends JPanel { 
    private static final int PREF_W = 800; 
    private static final int PREF_H = 400; 
    private static final int GAP = 20; 

    public UnstableStableGraphics() { 
     add(new JButton(new DrawBlueRectAction())); 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     g.setColor(Color.RED); 
     int w = PREF_W/2 - 2 * GAP; 
     int h = PREF_H - 2 * GAP; 
     g.fillRect(GAP, GAP, w, h);  
    } 

    @Override 
    public Dimension getPreferredSize() { 
     return new Dimension(PREF_W, PREF_H); 
    } 

    private class DrawBlueRectAction extends AbstractAction { 
     public DrawBlueRectAction() { 
      super("Draw Unstable Blue Rectangle"); 
     } 

     @Override 
     public void actionPerformed(ActionEvent arg0) { 
      Graphics g = getGraphics(); 
      g.setColor(Color.BLUE); 
      int x = PREF_W/2 + GAP; 
      int w = PREF_W/2 - 2 * GAP; 
      int h = PREF_H - 2 * GAP; 
      g.fillRect(x, GAP, w, h); 
      g.dispose(); 
     } 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(() -> createAndShowGui()); 
    } 

    private static void createAndShowGui() { 
     UnstableStableGraphics mainPanel = new UnstableStableGraphics(); 
     JFrame frame = new JFrame("UnstableStableGraphics"); 
     frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
     frame.add(mainPanel); 
     frame.pack(); 
     frame.setLocationByPlatform(true); 
     frame.setVisible(true); 
    } 
} 

은 당신이 그래픽 처분으로 (이 BufferedImage의 호출 getGraphics()를 통해 얻은 그래픽 객체를 사용하여 완벽하게 괜찮라고 할 때에, 오브젝트 데 완료되면 자원을 보존), 그 이미지를 paintComponent 메소드에 표시 할 수 있으며, 종종 백그라운드 이미지로 표시됩니다. 그러나 일반적으로 BufferedImage에서 createGraphics()이라고 부르는 것은 Graphics 객체가 아니라 더 강력한 Graphics2D 객체를 반환하기 때문입니다. 배경 이미지, 스프라이트 이미지와 스윙 타이머의 사용을 포함 예를 들어

는 :

import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.Image; 
import java.awt.RenderingHints; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.image.BufferedImage; 

import javax.swing.*; 

@SuppressWarnings("serial") 
public class BackgroundExample extends JPanel { 
    private static final int PREF_W = 600; 
    private static final int PREF_H = PREF_W; 
    private static final int SPRITE_W = 20; 
    private static final Color SPRITE_COLOR = Color.RED; 
    private static final int TIMER_DELAY = 20; 
    private Image background = null; 
    private Image sprite = null; 
    private int spriteX = 0; 
    private int spriteY = 0; 

    public BackgroundExample() { 
     background = createBackground(); 
     sprite = createSprite(); 

     new Timer(TIMER_DELAY, new TimerListener()).start(); 
    } 

    private Image createSprite() { 
     BufferedImage img = new BufferedImage(SPRITE_W, SPRITE_W, BufferedImage.TYPE_INT_ARGB); 
     Graphics2D g2 = img.createGraphics(); 
     g2.setColor(SPRITE_COLOR); 
     g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 
     int x = 1; 
     int y = 1; 
     int width = SPRITE_W -2; 
     int height = SPRITE_W - 2; 
     g2.fillOval(x, y, width, height); 
     g2.dispose(); 
     return img; 
    } 

    private Image createBackground() { 
     BufferedImage img = new BufferedImage(PREF_W, PREF_H, BufferedImage.TYPE_INT_ARGB); 
     Graphics2D g2 = img.createGraphics(); 
     g2.setColor(Color.GREEN); 
     g2.fillRect(0, 0, PREF_W, PREF_H); 
     g2.setColor(Color.GRAY); 
     int x = 0; 
     int y = 0; 
     g2.fillRect(x, y, 2 * SPRITE_W, 2 * SPRITE_W); 
     x = PREF_W - 2 * SPRITE_W; 
     g2.fillRect(x, y, 2 * SPRITE_W, 2 * SPRITE_W); 
     y = PREF_H - 2 * SPRITE_W; 
     g2.fillRect(x, y, 2 * SPRITE_W, 2 * SPRITE_W); 
     x = 0; 
     g2.fillRect(x, y, 2 * SPRITE_W, 2 * SPRITE_W); 
     g2.dispose(); 
     return img; 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     if (background != null) { 
      g.drawImage(background, 0, 0, this); 
     } 
     if (sprite != null) { 
      g.drawImage(sprite, spriteX, spriteY, this); 
     } 
    } 

    @Override 
    public Dimension getPreferredSize() { 
     if (isPreferredSizeSet()) { 
      return super.getPreferredSize(); 
     } else { 
      return new Dimension(PREF_W, PREF_H); 
     } 
    } 

    private class TimerListener implements ActionListener { 
     @Override 
     public void actionPerformed(ActionEvent e) { 
      spriteX++; 
      spriteY++; 
      repaint(); 
     } 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(() -> createAndShowGui()); 
    } 

    private static void createAndShowGui() { 
     BackgroundExample mainPanel = new BackgroundExample(); 
     JFrame frame = new JFrame("BackgroundExample"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.add(mainPanel); 
     frame.pack(); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
    } 
} 
+0

나는이 대답에 많은 힘을 쏟기 때문에 upvoted. –

+0

@PeterRader : thanks –

+0

[해결 방법 수락] (http://meta.stackexchange.com/a/5235/155831)을 통해 다른 사람들이 문제를 해결할 수 있음을 보여주십시오. 오, 당신 프로필에서 볼 수 있듯이 일반적으로 ** 귀하의 질문에 대한 대답을 수락합니다. 잘 하셨어요, :) –