没有JFrame的输出?

时间:2012-11-01 19:45:17

标签: java arrays jframe

所以我'试图创建一个tictactoe板,但它并没有出现任何东西。 (有一个主要类,但它只是创建一个" GameBoard")

非常感谢任何帮助,谢谢你。

所以我添加的组件无法相信我忘记了,我一定很累。

然而现在我得到的只是一个红色方块。

    public GameBoard() 
    {

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(0, 0, 195, 215);
        frame.setSize(new Dimension (300, 400));
        int count = 1;
        Rectangle board[][] = new Rectangle[3][3];


        for (int row = 0; row < board.length; row++){
            for (int col = 0; col < board[row].length; col++){
                if (count == 2){

                board[row][col] = new Rectangle(1,1,1,1);
               board[row][col].setBackground(Color.RED);
               frame.add(board[row][col]);
               count--;
            } else {board[row][col] = new Rectangle(1,1,1,1);
                    board[row][col].setBackground(Color.BLACK);
                    frame.add(board[row][col]);
                    count++;
                }
            }}
        frame.pack();
        frame.setVisible(true);
}}

矩形类:

public class Rectangle extends JComponent  {


    public Rectangle(int x, int y, int w, int h)  {
        super();
        setBounds(x, y, w, h);
        setBackground(Color.black);
    }


    public void paint(Graphics g)  {
        g.setColor( getBackground() );
        g.fillRect(0, 0, getWidth()-1, getHeight()-1);
        paintChildren(g);
   }

}

2 个答案:

答案 0 :(得分:1)

逻辑上,您错过了将电路板实际添加到JFrame中的步骤:

frame.add(...);
你的for循环中的

,所以你正在创建JFrame和Rectangles,但从不将矩形添加到你的JFrame。

正如@AmitD指出的那样,JFrame.add()不接受Rectangles,所以你需要编写一个扩展JComponent的类来在其paintComponent()方法中绘制Rectangle。

解决显示问题(仅看到红色):

您需要为JFrame设置布局管理器;我认为GridLayout最适合你的情况:

...
JFrame frame = new JFrame();
frame.setLayout(new GridLayout(3,3));
...

答案 1 :(得分:0)

你创建一个空的JFrame,并创建一堆存储在数组中的矩形,但是你从不在任何地方绘制,所以框架保持空白。

您需要在JComponent上绘制这些矩形(通过覆盖其paintComponent()方法),并将此JComponent添加到框架中。

编辑:正如@whiskeyspider所说,标准的Rectangle类中没有setBackground()方法。因此,如果Rectangle是您的类,并且是JComponent的子类,则需要将Rectangle的实例添加到框架中。