2011-09-22 131 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我打算添加一个边框,但那是两行更多的代码,我决定在那里停下来。 –