繁体   English   中英

JPanel未显示在JFrame中

[英]Jpanel not showing in JFrame

我正在编写此代码,以便它将添加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是一个Frame,并且您正在Project9内创建另一个Frame,并且没有显示它,正因为如此,只有Project9(w)绘制在屏幕上,但是它没有任何内容。

您必须使用“ this”而不是另一个框架。

public class Project9 extends JFrame implements MouseListener{        
    JPanel panes[]=new JPanel[64];
    public void Project9(){
        //JFrame mainFrame=new JFrame(); delete this.
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container mainBox= this.getContentPane();

三个答案都指出您的代码存在不同的问题。

您应该从一个正确的工作示例开始。 Swing教程“ 使用顶级容器 ”中的TopLevelDemo.java代码将向您展示基础知识以及创建GUI组件的正确方法。

您甚至不应该扩展JFrame。 在事件调度线程上创建所有组件非常重要,这就是为什么在本教程中使用invokeLater()代码的原因。

使用该教程获取使用所有Swing组件的示例。 其他示例将向您展示如何为更复杂的GUI扩展JPanel。 您不需要扩展JFrame。

我注意到的原始问题是:

public void paint(Graphics g){
    super.paintComponents(g);
}

不要重写paint()方法。 没有理由这样做!

paint()方法用于绘画,您没有进行任何自定义绘画。

第一个问题是您正在使用构造函数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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM