我正在编写此代码,以便它将添加JPanels并在单击时更改背景颜色。运行JFrame类的类中的代码为:

import javax.swing.*;

public class project9Driver {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Project9 w=new Project9();
        w.setVisible(true);
        w.setSize(900, 900);
    }

}


Project9类是:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;

public class Project9 extends JFrame implements MouseListener{
    JPanel panes[]=new JPanel[64];
    public void Project9(){
        JFrame mainFrame=new JFrame();
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container mainBox=mainFrame.getContentPane();
        mainBox.setLayout(new GridLayout(8,8));
        mainBox.addMouseListener(this);
        for(int i=0;i<=63;i++){
            panes[i].setBackground(Color.WHITE);
            mainBox.add(panes[i]);
        }
    }
    public void paint(Graphics g){
        super.paintComponents(g);
    }
    public void mouseClicked(MouseEvent e) {
        for(int i=0;i<=64;i++){
            if(e.getSource()==panes[i]){
                Random xR=new Random();
                Random yR=new Random();
                Random zR=new Random();
                int x=xR.nextInt(255),y=yR.nextInt(255),z=zR.nextInt(255);
                panes[i].setBackground(new Color(x,y,z));
            }
        }
    }


}


每当我尝试运行该程序时,它就会带有一个空的GUI窗口。我想念什么?

最佳答案

第一个问题是您正在使用构造函数Project9 w=new Project9();
在Project9类中,您正在定义方法public void Project9(){,则应删除void关键字。

public Project9(){
    //JFrame mainFrame=new JFrame(); delete this.
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container mainBox= this.getContentPane();

09-26 04:20