如何用表声明JFrame按钮

时间:2014-07-12 00:14:50

标签: java swing jframe jbutton

我创建了一个从JFrame扩展的类,它有一个按钮表。在类构造函数中,我将按钮添加到面板中,但是当我运行main时没有任何反应,我只看到一个空框架。所以你能帮我找到问题吗? 这是代码:

public class Tita extends JFrame {
    JButton ff[][] = new JButton[3][3];
    int i = 0, j = 0;

    public static void main(String[] args) { 
        Tita oo = new Tita();
    }

    public Tita() {
        super("Newframe"); 
        setVisible(true);
        for(i = 0; i < 3; i++) {
            for(j = 0; j < 3; j++) {
                ff[i][j].setText("sss");
                this.getContentPane().add(ff[i][i]);
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

发生的事情是,您还没有初始化任何JButton,当您添加getContentPane().add(ff[i][i]);按钮时,它应该是getContentPane().add(ff[i][j]);

import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;



public class Tita extends JFrame {
    JButton ff[][] = new JButton[3][3];
    int i = 0, j = 0;

    public static void main(String[] args) { 
        Tita oo = new Tita();
    }

    public Tita() {
        super("Newframe"); 
        setVisible(true);
        setLocationRelativeTo(null);
        setSize(new Dimension(300, 400));
        setLayout(new GridLayout(3, 0));
        for(i = 0; i < 3; i++) {
            for(j = 0; j < 3; j++) {
                ff[i][j] = new JButton("SSS");
                ff[i][j].setSize(30, 10);
                getContentPane().add(ff[i][j],i);
            }
        }
    }
}