2016-01-20 29 views
0

我开始学习使用JFrame和JPanel。为什么我的代码不工作? 由于某种原因,当我运行它时,JFrame确实打开,但没有网格布局和边框。我开始学习使用JFrame和JPanel。为什么我的代码不工作?

主:

package test; 

import javax.swing.JFrame; 

public class ht { 
public static void main(String[] args) { 


    JFrame frame = new screen(); 
    frame.setSize(600, 600); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setLocationRelativeTo(null); 
    frame.setVisible(true); 
} 
} 

Screen类:

package test; 

import java.awt.Color; 
import java.awt.GridLayout; 

import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.border.LineBorder; 

public class screen extends JFrame { 

/** 
* 
*/ 

private cell[][] arr = new cell[3][3]; 

public screen() 
{ 

    JPanel panel = new JPanel(new GridLayout(3, 3, 0, 0)); 



    for (int i = 0; i < 3; i++) { 
     for (int j = 0; j < 3; j++) { 
      panel.add(arr[i][j] = new cell()); 
     } 
    } 



    panel.setBorder(new LineBorder(Color.black, 1)); 
} 

public class cell extends JPanel{ 

    private String type1; 

    public cell() 
    { 
     type1 = "white"; 
     setBorder(new LineBorder(Color.red,1)); 
    } 
} 
} 

问题是什么?

回答

3

您创建您的JPanel面板,但将其添加到任何内容。您应该将它添加到您的JFrame中以供它显示。

// class name should start with an upper case letter. 
public class Screen extends JFrame { 

    // class name should start with an upper case letter. 
    private Cell[][] arr = new Cell[3][3]; 

    public Screen() { 

     JPanel panel = new JPanel(new GridLayout(3, 3, 0, 0)); 

     for (int i = 0; i < 3; i++) { 
      for (int j = 0; j < 3; j++) { 
       panel.add(arr[i][j] = new Cell()); 
      } 
     } 

     panel.setBorder(new LineBorder(Color.black, 1)); 


     add(panel); // ***** add panel to the JFrame ***** 
    } 
} 
+0

感谢您的帮助! – user3672173

+0

@ user3672173:不客气。 –

+0

@PetterFriberg:我不确定我是否理解你的评论。因为这似乎是一个微不足道的问题,所以我将答案定义为Swing wiki。 –

相关问题