2012-07-19 3 views
6

동일한 jlabel 저장 이미지를 gridlayout 패널에 두 번로드하려고 시도하지만 이미지 인스턴스 두 개를 만드는 대신 이미지를 한 번만 이동 한 다음 이동합니다.JLabel 이미지 배열

조각 배열의 동일한 JLabel 위치를 boardLabels 배열의 둘 이상의 JLabel에 어떻게 저장할 수 있습니까?

감사합니다 :) ImageIcons를 사용하여,하지만 난 다음 제거 JLabels를 다시로드해야합니다 보드를 업데이트 할 수 있기 때문에이를 방지하고자 할 때이

boardLabels[0] = new JLabel(pieces[1]); 
    boardLabels[1] = new JLabel(pieces[1]); 

작동

public static JPanel boardPanel = new JPanel(new GridLayout(4, 0)); 
public static JLabel pieces[] = new JLabel[2]; 
private static JLabel[] boardLabels = new JLabel[4]; 

public MainFrame() { 
    pieces[0] = new JLabel(new ImageIcon(System.getProperty("user.dir") + "/images/piece1.png")); 
    pieces[1] = new JLabel(new ImageIcon(System.getProperty("user.dir") + "/images/piece2.png")); 

    this.add(boardPanel); 
    displayGUIboard(); 
} 


public static void displayGUIboard() { 

    //ERROR - the label in pieces[0] is not copied into both boardLabels [0] and [1] 
    boardLabels[0] = pieces[0]; 
    boardLabels[1] = pieces[0]; 

    boardPanel.add(boardLabels[0]); 
    boardPanel.add(boardLabels[1]); 
} 

public static void main(String[] args) { 
    MainFrame frame = new MainFrame(); 
    frame.setVisible(true); 
    frame.setSize(600, 600); 
    frame.setLocationRelativeTo(null); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
} 

. 이미로드 된 레이블을 업데이트하는 것을 선호합니다.

편집 ... 나는 전에이 시도하지만 널 포인터 예외가 발생

boardLabels[0].setIcon(pieces[1]); 
    boardLabels[1].setIcon(pieces[1]); 

    boardPanel.add(boardLabels[0]); 
    boardPanel.add(boardLabels[1]); 
+2

enter image description here

*** 매우 *** 깨지기 쉬운 것입니다. 이러한 이미지는 앱에 기본적으로 포함되어 있으므로 Jar에 [임베디드 리소스] (http://stackoverflow.com/tags/embedded-resource/info)로 추가해야합니다. –

답변

9

번보다 더 많은 같은 구성 요소를 추가 할 수 없기 때문에이 작업을 수행하지 마십시오 시각화 된 컨테이너. 여러 개의 JLabel을 사용하는 것이 더 좋지만 같은 것을 사용하도록하십시오. ImageIcon. ImageIcons은 쉽게 번 이상 사용할 수 있습니다

public MainFrame() { 
    pieceIcon[0] = new ImageIcon(System.getProperty("user.dir") + 
     "/images/piece1.png"); 
    pieceIcon[1] = new ImageIcon(System.getProperty("user.dir") + 
     "/images/piece2.png"); 

    this.add(boardPanel); 
    displayGUIboard(); 
} 


public void displayGUIboard() { 
    boardPanel.add(new JLabel(pieceIcon[0]); 
    boardPanel.add(new JLabel(pieceIcon[0]); 
} 

를 제쳐두고 : 당신의 변수 것도 정적 없어야 있습니다. ImageIcons를 사용하는 경우

boardLabels[0] = new JLabel(pieces[1]); 
boardLabels[1] = new JLabel(pieces[1]); 

작동,하지만 난 것이다 보드를 업데이트 할 수 있기 때문에이를 방지하려면 : 최근 편집에 관한 :

편집 JLabel을 제거한 다음 다시로드하십시오. 나는.
없음 당신이 전혀 JLabels을 변경할 필요가 없습니다

솔루션 ". 다만 이미로드 된 라벨을 업데이트하는 것을 선호하지 그들이 어디 JLabels을 유지하지만, 단순히 그들이 보유하고있는 아이콘을 교환 할 것 JLabel의 setIcon(...) 방법을 사용하여.

또한 편집
, 객체와 변수를 혼동하지 마십시오. 모두 동일한 JLabel의 객체를 참조하는 경우는, JLabel의 변수의 무리를 만들 경우에도 할 수 없습니다 JLabel 객체를 추가하십시오. 용기에 한 번 이상.

편집 당신의 상태 :

코드 게임에 대한 표시 기능의 일부입니다.정수의 배열은 해석되는 보드를 나타낼 것이지만 위의 코드에서는 그렇지 않습니다. 올바른 Jlabel 이미지는 보드의 GUI를 표시하는 격자 레이아웃 패널에 배치됩니다. 나는 잘 작동하도록 표시 코드를 얻었지만 내 현재 버전에서는 보드에서 jlabels를 제거한 다음 새 JLabel (조각 ...)을 만듭니다 ...하지만 제거하는 대신 정수 배열에서 자체를 업데이트하는 것이 좋습니다. 레이블을 읽고 배열을 읽은 다음 레이블을 다시 만듭니다.

그래서 GridLayout을 사용하는 JPanel을 만들고 변경되지 않은 JLabel로 채 웁니다. 그런 다음 int 배열이 보유한 값을 기반으로 JLabel이 보유한 아이콘을 변경하십시오. 이 프로세스를 단순화하고 자동화하는 메소드를 작성할 수 있습니다. 대한

편집 :

편집은 내가 전에이 시도하지만 널 포인터 예외가 발생합니다.

그러면 NPE와 마찬가지로 이것을 해결하십시오. 어떤 라인이 NPE를 던 졌는지 확인하고, 라인의 변수를 확인하고, 적어도 하나는 null이며, 사용하기 전에 변수를 초기화하도록 수정하십시오.

편집 예를 들어
는 : GUI를 그리드 보여줍니다

import java.awt.Color; 
import java.awt.Graphics; 
import java.awt.GridLayout; 
import java.awt.image.BufferedImage; 

import javax.swing.*; 

@SuppressWarnings("serial") 
public class GridExample extends JPanel { 
    public static final int[][] MAP = { 
     {1, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2}, 
     {1, 1, 0, 0, 2, 2, 2, 2, 2, 2, 2}, 
     {1, 1, 1, 0, 2, 2, 2, 2, 2, 2, 2}, 
     {1, 1, 1, 0, 0, 2, 2, 2, 2, 2, 2}, 
     {1, 1, 1, 1, 0, 2, 2, 2, 2, 2, 2}, 
     {1, 1, 1, 0, 0, 0, 2, 2, 2, 2, 2}, 
     {1, 1, 0, 0, 0, 2, 2, 2, 2, 2, 2}, 
     {1, 1, 1, 0, 0, 0, 2, 2, 2, 2, 2}, 
     {1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2}, 
     {1, 1, 1, 1, 1, 0, 0, 0, 2, 2, 2}, 
     {1, 1, 1, 1, 1, 1, 0, 0, 0, 2, 2} 
    }; 

    public static final Color[] COLORS = {}; 
    private JLabel[][] labelGrid = new JLabel[MAP.length][MAP[0].length]; 

    public GridExample() { 
     setLayout(new GridLayout(MAP.length, MAP[0].length)); 
     for (int r = 0; r < labelGrid.length; r++) { 
     for (int c = 0; c < labelGrid[r].length; c++) { 
      labelGrid[r][c] = new JLabel(); 
      labelGrid[r][c].setIcon(Ground.getGround(MAP[r][c]).getIcon()); 
      add(labelGrid[r][c]);    
     } 
     } 
    } 

    private static void createAndShowGui() { 
     GridExample mainPanel = new GridExample(); 

     JFrame frame = new JFrame("GridExample"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.getContentPane().add(mainPanel); 
     frame.pack(); 
     frame.setLocationByPlatform(true); 
     frame.setVisible(true); 
    } 

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

enum Ground { 
    DIRT(0, new Color(205,133, 63)), GRASS(1, new Color(0, 107, 60)), 
    WATER(2, new Color(29, 172, 214)); 
    private int value; 
    private Color color; 
    private Icon icon; 

    private Ground(int value, Color color) { 
     this.value = value; 
     this.color = color; 

     icon = createIcon(color); 
    } 

    private Icon createIcon(Color color) { 
     int width = 24; // how to use const in enum? 
     BufferedImage img = new BufferedImage(width, width, BufferedImage.TYPE_INT_ARGB); 
     Graphics g = img.getGraphics(); 
     g.setColor(color); 
     g.fillRect(0, 0, width, width); 
     g.dispose(); 
     return new ImageIcon(img); 
    } 

    public int getValue() { 
     return value; 
    } 

    public Color getColor() { 
     return color; 
    } 

    public Icon getIcon() { 
     return icon; 
    } 

    public static Ground getGround(int value) { 
     for (Ground ground : Ground.values()) { 
     if (ground.getValue() == value) { 
      return ground; 
     } 
     } 
     return null; 
    } 

} 

: 비교를 위해
enter image description here

+0

boardLabel 배열에 여러 개의 JLabel을 만들었지 만 조각 배열의 Jlabels를 두 번 추가 할 수 없으므로 조각 배열에서 같은 JLabel로 할당되지 않습니다. – user1334130

+0

하하! 같은 것을 게시했습니다. – user1334130

+0

JLabels의 설정 양을 업데이트하는 것은 불가능합니다. 모든 JLabels가 작동하지 않는 동일한 객체를 가리키기 때문입니다. – user1334130

10

을, 나는 HFOE의 example 너무 @ 다시 고려했습니다 Ground implements Icon 및 색인을 그 배열은 values()에 의해 반환됩니다. value은 구현 세부 정보이므로 int[][] MAPGround[][] MAP이 될 수 있습니다.

업데이트 :이 변형은 Ground[][] MAP을 나타내며 TexturePaint을 추가합니다. 은`user.dir`에 상대 경로에서 응용 프로그램 자원을 확보

import java.awt.Color; 
import java.awt.Component; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.GridLayout; 
import java.awt.TexturePaint; 
import java.awt.geom.Rectangle2D; 
import java.awt.image.BufferedImage; 
import java.util.Random; 
import javax.swing.*; 

/** @see https://stackoverflow.com/a/11556441/230513 */ 
public class GridExample extends JPanel { 

    public static final Ground[][] MAP = { 
     {Ground.GRASS, Ground.GRASS, Ground.DIRT, Ground.WATER, Ground.WATER}, 
     {Ground.GRASS, Ground.DIRT, Ground.CITY, Ground.WATER, Ground.WATER}, 
     {Ground.GRASS, Ground.DIRT, Ground.CITY, Ground.WATER, Ground.WATER}, 
     {Ground.GRASS, Ground.DIRT, Ground.DIRT, Ground.DIRT, Ground.WATER}, 
     {Ground.GRASS, Ground.GRASS, Ground.DIRT, Ground.WATER, Ground.WATER}, 
    }; 
    private JLabel[][] labelGrid = new JLabel[MAP.length][MAP[0].length]; 

    public GridExample() { 
     setLayout(new GridLayout(MAP.length, MAP[0].length)); 
     for (int r = 0; r < labelGrid.length; r++) { 
      for (int c = 0; c < labelGrid[r].length; c++) { 
       labelGrid[r][c] = new JLabel(); 
       labelGrid[r][c].setIcon(MAP[r][c]); 
       add(labelGrid[r][c]); 
      } 
     } 
    } 

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

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       createAndShowGui(); 
      } 
     }); 
    } 
} 

enum Ground implements Icon { 

    DIRT(new Color(205, 133, 63)), GRASS(new Color(0, 107, 60)), 
    WATER(new Color(29, 172, 214)), CITY(Color.lightGray); 
    private static final int SIZE = 42; 
    private Random random = new Random(); 
    private TexturePaint paint; 

    private Ground(Color color) { 
     this.paint = initPaint(color); 
    } 

    private TexturePaint initPaint(Color color) { 
     BufferedImage image = new BufferedImage(
      SIZE, SIZE, BufferedImage.TYPE_INT_ARGB); 
     Rectangle2D.Double rect = new Rectangle2D.Double(0, 0, SIZE, SIZE); 
     for (int row = 0; row < SIZE; row++) { 
      for (int col = 0; col < SIZE; col++) { 
       if (random.nextBoolean()) { 
        image.setRGB(col, row, color.getRGB()); 
       } else { 
        if (random.nextBoolean()) { 
         image.setRGB(col, row, color.darker().getRGB()); 
        } else { 
         image.setRGB(col, row, color.brighter().getRGB()); 
        } 
       } 
      } 
     } 
     return new TexturePaint(image, rect); 
    } 

    @Override 
    public void paintIcon(Component c, Graphics g, int x, int y) { 
     Graphics2D g2d = (Graphics2D) g; 
     g2d.setPaint(paint); 
     g.fillRect(0, 0, SIZE, SIZE); 
    } 

    @Override 
    public int getIconWidth() { 
     return SIZE; 
    } 

    @Override 
    public int getIconHeight() { 
     return SIZE; 
    } 
}