簡體   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