java窗口的一个问题,不明白

来源:百度知道 编辑:UC知道 时间:2024/07/01 12:08:24
请看下面的程序
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class why extends JFrame {
JFrame frame2 = new JFrame();
JButton[] button = new JButton[9];
int i;
public why(){};
public void frame(){
frame2.setTitle("Boom!");
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.setSize(400,300);
frame2.setLayout(new GridLayout(3,3));
frame2.setVisible(true);
for(i=0;i<=8;i++){
frame2.add(button[i]=new JButton());
button[i].setBackground(Color.gray);}
}
public static void main(String[] args){
why boom = new why();
//boom.setVisible(true);
boom.frame();
//boom.setVisible(false);
}
}

在main函数里面,屏蔽两条语句和不屏蔽得出的对话框是不一样的。不屏

看一下下面的注释:

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

import javax.swing.JButton;
import javax.swing.JFrame;

public class Why extends JFrame {
JFrame frame2 = new JFrame();
JButton[] button = new JButton[9];
int i;

public Why() {
};

public void frame() {
frame2.setTitle("Boom!");
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.setSize(400, 300);
frame2.setLayout(new GridLayout(3, 3));
frame2.setVisible(true);
for (i = 0; i <= 8; i++) {
frame2.add(button[i] = new JButton());
button[i].setBackground(Color.gray);
}
// 分是少了点,可是问题也简单,setVisible是设置控件可见的,显示之后你再对控件操作的话,不会立即反应的屏幕上,
// 你需要调用repait()来重绘你的控件
// 在这里加frame2.repaint()是一种解决方案,或者你可以把上面的frame2.setVisible(true);放到这来,
// 也可以把这的frame2.setVisible(true)删掉,在main中调用;应该懂了吧?。
frame2.repaint();
}

public s