문제

이 프로그램 내에서는 "LifeCell"위젯의 8x8 그리드를 만들어야합니다. 강사는 위젯이 Shape 그래서 나는 계속해서 사용했습니다 GridLayout 수업. 그만큼 GridLayout 클래스는 잘 작동합니다 (확인할 시각적 원조가 없기 때문에 알 수 있듯이) 프로그램의 대상은 사용자가 LifeCell 위젯 중 하나를 클릭하고 '살아있는 상태 사이의 토글을 클릭 할 수있는 게임 게임을하는 것입니다. '또는'죽었다.

내 질문은 세포를 칠하는 데 크게 의존합니다. 내 코드에 문제가 될 수 있지만 100% 확실하지 않습니다.

program2.java

public class Program2 extends JPanel implements ActionListener {
private LifeCell[][] board; // Board of life cells.
private JButton next; // Press for next generation.
private JFrame frame; // The program frame.

public Program2() {
    // The usual boilerplate constructor that pastes the main
    // panel into a frame and displays the frame. It should
    // invoke the "init" method before packing the frame
    frame = new JFrame("LIFECELL!");
    frame.setContentPane(this);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.init();
    frame.pack();
    frame.setVisible(true);
}
    public void init() {
    // Create the user interface on the main panel. Construct
    // the LifeCell widgets, add them to the panel, and store
    // them in the two-dimensional array "board". Create the
    // "next" button that will show the next generation.
    LifeCell[][] board = new LifeCell[8][8];
    this.setPreferredSize(new Dimension(600, 600));
    this.setBackground(Color.white);
    this.setLayout(new GridLayout(8, 8));
    // here is where I initialize the LifeCell widgets
    for (int u = 0; u < 8; u++) {
        for (int r = 0; r < 8; r++) {
            board[u][r] = new LifeCell(board, u, r);
            this.add(board[u][r]);
            this.setVisible(true);

        }
    }

lifecell.java

 public class LifeCell extends JPanel implements MouseListener {
   private LifeCell[][] board; // A reference to the board array.
   private boolean alive;      // Stores the state of the cell.
   private int row, col;       // Position of the cell on the board.
   private int count;          // Stores number of living neighbors.

   public LifeCell(LifeCell[][] b, int r, int c) {
       // Initialize the life cell as dead.  Store the reference
       // to the board array and the board position passed as
       // arguments.  Initialize the neighbor count to zero.
       // Register the cell as listener to its own mouse events.
       this.board = b;
       this.row = r;
       this.col = c;
       this.alive = false;
       this.count = 0;
       addMouseListener(this);
   }   

그리고 여기에 있습니다 paintComponent 방법:

   public void paintComponent(Graphics gr) {
       // Paint the cell.  The cell must be painted differently
       // when alive than when dead, so the user can clearly see
       // the state of the cell.
           Graphics2D g = (Graphics2D) gr;
           super.paintComponent(gr);
           g.setPaint(Color.BLUE);
   }

나는 그것을 고치기 위해 정확한 솔루션이 필요하지 않지만, 나는 그것을 작동 시키려고 노력하고 있습니다.

감사.

편집하다:

나는 더 많은 program2.java 클래스의 세그먼트를 추가했습니다. 내일 다시 확인할 수 있습니다. 나는 잠자리에 들고 있습니다. 모든 도움을 주셔서 감사합니다.

#2 편집 :

8x8로 내 프레임을 채우면 진짜 혼란이 생깁니다. GridLayout 더 나은 단어가 부족한 각 개인 "셀"은 유형입니다. LifeCell. 어떻게 페인트를 칠할 수 있습니까? LifeCell 다른 색상? 그것이 당신에게 전혀 의미가 있다면, 나는 가능한 한 많이 수정하려고 노력할 수 있습니다. 그리고 Camickr, 나는 그 웹 사이트를 볼 것입니다. 감사합니다.

과제를 찾을 수 있습니다 여기 내 질문 및/또는 코드 스 니펫에 관한 모든 혼란을 피하기 위해.

도움이 되었습니까?

해결책

alt text

당신은 올바른 길에 있습니다.

기존 구성 요소 (예 : jpanel, jlabel, jbutton 등)를 사용하려면 구성 요소가 이미하는 일을 존중하는 것이 훨씬 좋습니다.

따라서 귀하의 경우에는 JPANEL을 사용하고 있습니다.이 (및 기타 JComponents)는 background 변경할 수있는 속성. 따라서, 구성 요소를 페인트하려고 시도하는 대신 (지금 당장 실패하고있는) 그 값을 설정하고 페인트 페인트 자체를 두십시오.

셀 상태에 따라 다른 색상을 반환하는 "getLifeColor"를 추가 할 수 있습니다.

   private Color getLifeColor() {
       return this.alive?liveColor:deadColor;
   } 

그런 다음 셀 에이 색상으로 배경을 그리도록하십시오.

  public void paintComponent(Graphics gr) {
       setBackground( getLifeColor() );
       super.paintComponent( gr );
  }

그 후에는 셀의 상태를 살거나 죽은 상태로 설정해야하며 구성 요소는 해당 색상으로 나타납니다.

alt text

여기에 있습니다 짧은 자체가 포함 된 올바른 예 (SSCCE)가 게시 한 코드 + 라이브/데드 컬러 사용량. 나는 당신이 거기에서 계속할 수 있다고 생각합니다.

다른 팁

JPANEL에는 기본 선호 크기 또는 가시 콘텐츠가 없습니다. 눈에 띄는 구성 요소 (예 : jlabel)를 추가하거나 선호하는 크기를 제공해야합니다.

이 외에도 다음과 같이 설정하면 레이아웃이 작동합니다.

JFrame frame = new JFrame();
Container cp = frame.getContentPane();
cp.setLayout(new GridLayout(8, 8));
for (int i = 0; i < 8; i++)
    for (int j = 0; j < 8; j++)
        cp.add(new JLabel(i + "-" + j));
frame.pack();
frame.setVisible(true);

LifeCell에 대한 PaintComponent () 메소드가있는 이유는 무엇입니까? 커스텀 페인팅을 할 필요가 없습니다. 다음을 사용하여 구성 요소의 배경색을 변경할 수 있습니다.

setBackground( Color.BLUE ) 

그 외에 당신의 질문은 나에게 의미가 없습니다. 먼저 당신은 모양 객체를 사용해야한다고 말하지만 코드의 어느 곳에도 모양 객체가 표시되지 않으므로 왜 그것을 언급하여 질문을 혼동 했습니까?

나는 당신의 질문을 정말로 이해하지 못하고 우리는 당신의 코드가 충분하지 않으며 실제 제안을 제공 할만 큼 충분하지 않습니다.

더 많은 도움이 필요한 경우 게시하십시오 SSCCE 문제를 보여줍니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top