有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

正在运行但未显示的swing Java组件

因此,我只想在屏幕的随机部分绘制一个正方形作为custonJComponent

public void paintComponent(Graphics g){
    Graphics2D g2d = (Graphics2D) g;
    if( this.good ){
        g2d.setColor(Color.green);
    }
    else{
        g2d.setColor(Color.red);
    }
    g2d.fillRect(this.x, this.y, this.w, this.h);
    System.out.println("painting");
}

下面是通过repaint()调用绘画的方法

private void stateChange(){
        
    double rand = Math.random();
        
    if (rand < 0.5){
        this.good = !this.good;
    }
    setLocation(this.x,this.y);
    repaint();
}

this.xthis.y不断变化,但我知道这是可行的。当我运行代码时,它会在应该打印的地方打印^{,但没有显示任何内容。我做错什么了吗

额外代码:

下面是我为让它出现而写的:

\\in JComponent constructore
setOpaque(true);
setVisible(true);
setSize(this.w,this.h);

共 (2) 个答案

  1. # 1 楼答案

    我的猜测是:您有一个while(true)循环来连接Swing事件线程,因此当您更改状态时,GUI无法重新绘制自身以显示它正在发生。或者您的JComponent的大小非常小,太小,无法显示图像

    对于一个不只是猜测的答案,你需要问一个更完整的问题,并附上相关的代码

    请注意paintComponent(...)方法重写缺少对super方法的调用

    注意:您可以通过在paintComponent中添加getSize()方法来测试JComponent的大小:

    public void paintComponent(Graphics g){
        super.paintComponent(g);  // **** don't forget this.
        Graphics2D g2d = (Graphics2D) g;
        if( this.good ){
            g2d.setColor(Color.green);
        }
        else{
            g2d.setColor(Color.red);
        }
        g2d.fillRect(this.x, this.y, this.w, this.h);
    
        // TODO: ***** delete this lines
        System.out.println("painting");
        System.out.println(getSize());  // **** add this***
    }
    

    注意:您应该而不是调用组件上的setSize(...)。这通常是误导性的,因为布局管理者经常忽略它

  2. # 2 楼答案

    根据您提供的示例代码,问题在于您实际上正在绘制组件可视空间边界的外侧

    绘制时,Graphics上下文的左上角是0x0,Swing已经根据组件的位置转换了Graphics上下文,因此

    g2d.fillRect(this.x, this.y, this.w, this.h);
    

    实际上(可能)在零部件的可视区域之外进行绘制。例如,如果x位置为10y位置为10,但高度和宽度仅为1010,则在位置10x10处进行绘制,这将超出组件的可视空间,相反,您应该尝试以下操作

    g2d.fillRect(0, 0, this.w, this.h);
    

    或者,根据您的示例代码

    public void paintComponent(Graphics g){
        Graphics2D g2d = (Graphics2D) g;
        if( this.good ){
            g2d.setColor(Color.green);
        }
        else{
            g2d.setColor(Color.red);
        }
        super.paintComponent(g2d);
    }
    

    相反