2016-10-16 99 views
1

我有2個類:GameOfLife()和PanelGrid。在創建panelgrid的新對象時,不會調用(覆蓋的)方法paintComponent。將「repaint()」放在構造函數中也不起作用。未由構造函數調用paintcomponent或創建對象時

import java.util.Scanner; 
import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 
import java.io.*; 

class GameOfLife { 
    JFrame frame = new JFrame("Game of life"); 
    PanelGrid panelGrid; 

    void buildIt() { 
     frame.setSize(600, 600); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setVisible(true); 
     frame.add(buttonStart, BorderLayout.SOUTH); 
     frame.add(buttonStop, BorderLayout.NORTH); 
     panelGrid = new PanelGrid(); 
     panelGrid.setOpaque(true); 
     frame.add(panelGrid); 
    } 

    public static void main(String[] args) { 
     new GameOfLife().buildIt(); 
    } 
} 

class PanelGrid extends JPanel implements ActionListener { 
    Timer timer; 
    int delay; 
    JLabel label; 
    int height; // get length from the file 
    int width; //get width of array from the file 

    //constructor 
    public PanelGrid() { 
     delay = 1000; 
     timer = new Timer(delay, this); 
     width = 4; 
     height = 5; 
     //if there exists a file with an initial configuration, initial[][], width and height are updated. 
     //if not, the default array is used 
     readInitial(); 
     //repaint(); putting repaint() here din't make a difference. 
    } 

    @Override 
    public void paintComponent(Graphics g) { 
     System.out.println("if you read this, the method is called"); 
    super.paintComponent(g); //erases panel content 
    this.setLayout(new GridLayout(width, height)); 
    for (int r = 0; r < height; r++) { 
     for (int c = 0; c < width; c++) { 
      JPanel panel = new JPanel(); 
      if (grid[r][c].isAlive() == true) { 
       panel.setBackground(Color.BLACK); 
      } else {      
       panel.setBackground(Color.WHITE); 
      } 
      this.add(panel); 
     } 
    } 
    //the rest of this class I have left out for clarity 
    } 
} 
+1

你的代碼甚至沒有編譯。 PanelGrid類中的動作偵聽器缺失。網格未定義。您不要在paintComponent方法中定義Swing組件。看看我的[John Conway的Java Swing中的生活遊戲](http://java-articles.info/articles/?p=504)文章,看看它是否提供了任何提示。 –

+0

如何設置'frame.setVisible(true);'作爲構造函數中的最後一個語句? –

+0

也......在你的'paintComponent'實現中''JPanel panel = new JPanel();''和'this.add(panel);'這是一個很大的NO-NO。繪畫組件僅*用於繪畫,而不用於構建/添加組件或將其展開。嚴格的繪畫。你必須重新考慮你的策略。此外,如果您需要我們的幫助,這可能有助於更詳細地解釋您嘗試實現的目標。 –

回答

0

我認爲您需要將您的PanelGrid添加到JFrame。如果它不在可見的頂級容器paint()中,因此不會調用paintComponent()。也許。值得一試...

+0

對不起,作爲評論而不是答案(因爲我不知道它是否會起作用) – OffGridAndy

相關問題