2011-09-22 125 views
3

我試圖在81個窗口中顯示一個解決的數獨拼圖。我這樣做:爲什麼我的JFrame不顯示?

import java.awt.GridLayout; 
import java.awt.*; 

import javax.swing.JFrame; 
import javax.swing.JLabel; 


public class GraphicSolver extends JFrame { 

GraphicSolver(int[][] spelplan) { 

    Panel panel = new Panel(new GridLayout(9,9)); 

    for(int i=9;i<9;i++){ 
     for(int x=0;x<9;x++){ 
      panel.add(new JLabel(""+spelplan[i][x])); 
     } 
    } 

    Frame frame = new Frame(); 
    frame.add(panel); 


    frame.setVisible(true); 

} 
} 

但是,它只給了我一個沒有任何數字的空窗口。如果有人能指出我朝着正確的方向,我會很高興。

+1

你能也張貼啓動代碼和顯示的JFrame(main方法或類似的東西) –

+1

不要混用的Swing和AWT組件! –

回答

7

外環應從零開始:

for(int i=0;i<9;i++){ 
+0

哦,簡單的愚蠢的錯誤,感謝您指出!我接受這個答案,因爲這是打破這個計劃的主要原因。 –

+0

很高興幫助;也考慮你發現有幫助的投票相關答案。 – trashgod

+0

參見['CellTest'](http://stackoverflow.com/questions/4148336/jformattedtextfield-is-not-properly-cleared/4151403#4151403)。 – trashgod

4

嘗試調用frame.pack(),這將在計算面板的正確尺寸後,將所有組件打包到要顯示的框架中。另外,按照@trashgod建議的解決方法,上面的解決方案將解決沒有添加面板的事實,並且@Ashkan Aryan的修復會使您的代碼更加合理(儘管它應該在沒有它的情況下工作,但是沒有任何意義從JFrame繼承)。

下面的代碼爲我工作:

GraphicSolver(int[][] spelplan) { 
    Panel panel = new Panel(new GridLayout(9,9)); 

    for(int i=0;i<9;i++){ 
     for(int x=0;x<9;x++){ 
      panel.add(new JLabel(""+spelplan[i][x])); 
     } 
    } 

    this.add(panel); 
    this.pack(); 
    this.setVisible(true); 
} 
4

你似乎有兩個框架。 1是JFrame(類GrpahicSolver本身),另一個是你在其中創建的框架。

我建議你用this.addPanel()替換frame.addPanel(),它應該工作。

4

Graphic Solver

import java.awt.GridLayout; 
import javax.swing.*; 

public class GraphicSolver { 

    GraphicSolver(int[][] spelplan) { 
     // presumes each array 'row' is the same length 
     JPanel panel = new JPanel(new GridLayout(
      spelplan.length, 
      spelplan[0].length, 
      8, 
      4)); 

     for(int i=0;i<spelplan.length;i++){ 
      for(int x=0;x<spelplan[i].length;x++){ 
       panel.add(new JLabel(""+spelplan[i][x])); 
      } 
     } 

     JFrame frame = new JFrame(); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.add(panel); 
     frame.pack(); 

     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       int[][] plan = new int[4][7]; 
       for (int x=0; x<plan.length; x++) { 
        for (int y=0; y<plan[x].length; y++) { 
         plan[x][y] = (x*10)+y; 
        } 
       } 
       new GraphicSolver(plan); 
      } 
     }); 
    } 
} 
+1

非常好sscce我的+1 – mKorbel

+1

+1間距;面板上的匹配空白邊框補充了效果。 – trashgod

+0

@trashgod我打算添加一個邊框,但那是兩行更多的代碼,我決定在那裏停下來。 –