2013-07-21 3 views
1

2 개의 JPanel을 공동으로 사용하는 JFrame에서 이상한 문제가 발생했습니다. JFrame을 확장하는 "SlotCheck"라는 클래스가 있습니다. 그리고 JPanel을 확장하는 "슬롯"이라는 클래스가 있습니다. SlotCheck 생성자에서 sl 및 s2라는 2 개의 Slot 인스턴스를 추가합니다. setBounds()를 사용하여 보드의 서로 다른 두 위치에 배치했습니다.Java Jpanel setBounds가 작동하지 않습니다.

sl.setBounds가 작동하고 그것을 나타냅니다. 하지만 s2.setBounds가 작동하지 않으며 (0,0)에 넣습니다. 여기

는 모습입니다 :

enter image description here

내가 그것을 그 않는 이유를 알고 싶어요. 여기

package Try1; 
import java.io.IOException; 
import javax.swing.JFrame; 

public class SlotCheck extends JFrame{ 
    private Slot sl; 
    private Slot s2; 
    public SlotCheck() throws IOException{ 
    sl = new Slot(4,2,SlotType.white); 
    System.out.print(sl.toString()); 
    add(sl); 
    sl.setBounds(100,0,40,300); 
    sl.setVisible(true); 

    s2 = new Slot(6,2,SlotType.black); 
    System.out.print(s2.toString()); 
    add(s2); 
    s2.setBounds(200,0,40,300); 
    s2.setVisible(true); 
    } 

    public static void main(String[]args) throws IOException{ 
    SlotCheck sc = new SlotCheck(); 
    sc.setDefaultCloseOperation(EXIT_ON_CLOSE); 
    sc.setTitle("check of slot"); 
    sc.setVisible(true); 
    sc.setLocation(300, 200); 
    sc.setSize(400,400); 
    } 
} 

그리고

는 슬롯 클래스입니다 :

여기 SlotCheck 클래스입니다

이 가지 긴하지만 난 당신이 이해 바랍니다. 또한 paintComponent 클래스는 코드에서 내려졌고, 중요한 점은 거기에 갈 수 있다고 생각합니다.

package Try1; 

import java.awt.Graphics; 
import java.awt.Image; 
import java.io.File; 
import java.io.IOException; 
import java.util.Stack; 

import javax.imageio.ImageIO; 
import javax.swing.JPanel; 

// slot is a defined place on the backgammon board that can hold 
// one type of pieces black or white. 
//there are 24 slots 12 on each side and 6 in each quartor. 
//if a slot holds 2 or more pieces those pieces cannot be eaten. 
public class Slot extends JPanel{ 
    private int slotNumber; 
    private int piecesAmount; 
    private SlotType type; 
    private Stack<WhitePiece> wPieces; 
    private Stack<BlackPiece> bPieces; 
    private Image wPieceImage; 
    private Image bPieceImage; 
    public Slot() throws IOException{ 
    type = SlotType.empty; 
    piecesAmount = 0; 
    setSize(300,40); 
    wPieces = new Stack<WhitePiece>(); 
    bPieces = new Stack<BlackPiece>(); 
    wPieceImage = ImageIO.read(new File("pics/whitePiece.png")); 
    bPieceImage = ImageIO.read(new File("pics/blackPiece.png")); 
} 
    public Slot(int pA, int sN, SlotType t) throws IOException{ 
    if(t != SlotType.empty){ 
     piecesAmount = pA; 
     slotNumber = sN; 
     type = t; 
     wPieces = new Stack<WhitePiece>(); 
     bPieces = new Stack<BlackPiece>(); 
     wPieceImage = ImageIO.read(new File("pics/whitePiece.png")); 
     bPieceImage = ImageIO.read(new File("pics/blackPiece.png")); 
     if(t == SlotType.black){ 
      for(int i=0;i<pA;i++) 
       bPieces.push(new BlackPiece()); 
     }else{ 
      for(int i=0;i<pA;i++) 
       wPieces.push(new WhitePiece()); 
     } 
    } 
    } 
    public SlotType getType(){ 
    return type; 
    } 
    public void setType(SlotType t){ 
    if(piecesAmount == 0) 
    type = t; 
    } 
    public int getPiecesAmount(){ 
    return piecesAmount; 
    } 
    public void setPiecesAmount(int pa) throws IOException{ 
    if(type != SlotType.empty){ 
     piecesAmount = pa; 
     if(type == SlotType.black){ 
     if(pa>bPieces.size()) 
      for(int i=0;i<(pa-bPieces.size());i++) 
       bPieces.push(new BlackPiece()); 
     else 
      if(pa<bPieces.size()) 
       for(int i=0;i<(bPieces.size()-pa);i++) 
        bPieces.pop(); 
    } 
     else{ 
      if(pa>wPieces.size()) 
       for(int i=0;i<(pa-wPieces.size());i++) 
        wPieces.push(new WhitePiece()); 
      else 
       if(pa<wPieces.size()) 
        for(int i=0;i<(wPieces.size()-pa);i++) 
         wPieces.pop(); 
     } 
    }else{ 
     System.out.println("Slot #"+slotNumber+" is Empty Slot"); 
    } 
    } 
    public void decreasePiecesAmount(){ 
    if(type != SlotType.empty){ 
     piecesAmount --; 
     if(type == SlotType.black) 
      bPieces.pop(); 
     else 
      wPieces.pop(); 
    } 
    } 
    public void increasePiecesAmount() throws IOException{ 
    if(type != SlotType.empty){ 
     piecesAmount ++; 
     if(type == SlotType.black) 
      bPieces.push(new BlackPiece()); 
     else 
      wPieces.push(new WhitePiece()); 
    } 
    } 
    public void pushPiece(){ 

    } 
    public void paintComponent(Graphics g){  
    if(type == SlotType.empty){ 
     System.out.println("no type selected slot is empty Slot Number"+slotNumber); 
    }else 
     if(type == SlotType.white){ 
     if(!wPieces.isEmpty()){ 
     try { 
      wPieces.push(new WhitePiece()); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     if(slotNumber <= 11){ 
      for(int i=0;i<piecesAmount;i++){ 
      g.drawImage(wPieceImage, 5, i*30, null); 
      } 
     } 
     else{ 
      for(int i=0;i<piecesAmount;i++){ 
       g.drawImage(wPieceImage, 5,300-(i*30), null); 
      } 
     } 
     }else{ 
      System.out.println("Slot Stack is Empty Slot #"+slotNumber); 
     } 
     }else 
     { 
      if(!bPieces.isEmpty()){ 

      if(slotNumber<=11){ 
      for(int i=0;i<piecesAmount;i++){ 
       g.drawImage(bPieceImage, 5, i*30, 30, 30, null); 
      } 
      }else{ 
       for(int i=0;i<piecesAmount;i++){ 
        g.drawImage(bPieceImage, 5, 300-(i*30), 30, 30, null); 
       } 
      } 
    } 
      else{ 
     System.out.println("Slot Stack is empty Slot #"+slotNumber); 
    } 
} 

} 
protected void setSlotNumber(int sN){ 
    slotNumber = sN; 
} 
public int getSlotNumber(){ 
    return slotNumber; 
} 
public String toString(){ 
return "Slot #"+slotNumber+"\nSlot Type is: "+type.toString()+"\nAmount of pieces is: "+piecesAmount; 
    } 

} 

귀하의 도움을 호소합니다.

+1

호버 크래프트가 이미 제시 한 조언 외에도 이벤트 발송 스레드에서 모든 GUI 작업을 수행해야합니다. 참조 : http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html – kiheru

답변

2
  • setBounds(...)은 null 레이아웃에서만 작동합니다.
  • 그러나 null 레이아웃을 사용하지 마십시오!
  • 사용하지 마시오 setBounds(...)
  • 스윙 레이아웃 관리자에 대해 자세히 알아보고 구성 요소를 놓을 때 무거운 것을 들도록하십시오. 튜토리얼의 링크는 다음과 같습니다. Lesson: Laying Out Components Within a Container
  • paintComponent 메소드 내부에서 super.paintComponent(g);을 호출하는 것을 잊지 마세요. 일반적으로 덮어 쓰기의 첫 번째 행에 있습니다.
+0

링크를 볼 수 없습니다. 지금은 일 수 있습니다.하지만 정확히 어디에 있는지 결정하고 싶습니다. –

+0

@GiladBenYe : 수정 됨 다시 확인해주세요. –

+0

예, 이제 표시됩니다. 하지만 제 경우에는 슬롯이 정확히 어디에 있는지를 결정하고 싶습니다. 나중에 이미지에서 조정해야하기 때문입니다. –

-1

확인 문제가 발견되었습니다. 나는 setLayout (null)을 넣지 않았다.

+0

그래도 작동하지만 레이아웃 관리자를 사용하는 것이 더 좋습니다. 그렇지 않으면 크기 조정 처리 등을 포함한 모든 위치 지정을 수동으로 수행해야합니다. 어느 시점에서 레이아웃 관리자를 작성할 수도 있습니다.그러나 거의 언제나 중첩 된 레이아웃을 사용할 수 있다는 점을 감안할 때 상황에 맞는 것이 있습니다. – kiheru

+0

알 겠어. 을 배울 것이지만 지금은 내 프로그램이 작고 은 레이아웃 관리자를 배우기 시작한 후 더 이상 사용하지 않는다. –

+0

@GiladBenYe : 일반적인 함정에 빠져 있습니다. 단기간에 널 레이아웃을 사용하는 것이 더 쉽지만 장기적으로는 훨씬 어려워집니다. 나는 당신이 엉덩이에서 당신을 물릴 것이기 때문에 널 레이아웃을 사용하지 않기를 강력히 권합니다. 복잡한 GUI를 만든 다음 나중에 GUI의 중앙에 하나 이상의 JRadioButton을 추가해야한다는 것을 알았습니다. null 레이아웃을 사용하면 새 구성 요소에 맞게 * 모든 항목을 수동으로 이동하고 전체 GUI의 크기를 조정해야합니다. 모두 버그의 위험이 있습니다. 레이아웃 관리자를 사용하면 * 한 줄의 코드 만 추가하면됩니다. –

관련 문제