为什么我的 Java 代码可以在 Windows 上运行而不是在 Mac 上运行?

问题描述

这是我的代码。我是初学者学习核心Java。我在 MacBook Air 2017 上编程。在执行“Frame”程序时,代码是完美的,并且运行没有任何错误。就像我必须在一秒钟后逐渐改变窗口的背景。当我在 Windows 上运行它时,它工作得很好。但是当我在 Mac 上运行时,它不会改变任何背景颜色,而是开始改变标题栏的颜色。我需要更改任何设置吗?

import java.awt.*;
class abc extends  Frame
{
    public void paint(Graphics g){
       
        int red,green,blue;
        red = (int) (Math.random()*255);
        green = (int) (Math.random()*255);
        blue = (int) (Math.random()*255);
        Color c1 = new Color(red,blue);
        setBackground(c1);
        try{
            Thread.sleep(1000);
        }
        catch (Exception ae)
        {}
        
    }

    public static void main(String[] args) {
        abc obj1 = new abc();
        obj1.setVisible(true);
        obj1.setSize(500,500);

    }

}

I have added this Youtube link. Please check What Output I'm getting.

解决方法

窗口似乎没有重绘(调整窗口大小时颜色会发生变化,这会触发重绘事件)。这是完全有效的行为,只是碰巧 Windows 自己做到了,而 Mac OS X 没有。

我没有在一些大学作业之外使用 Swing(我使用了其他 UI 框架),但是查看 Javadocs 我会在设置新的背景颜色后尝试其中一种方法:

https://docs.oracle.com/javase/10/docs/api/java/awt/Component.html#repaint()

https://docs.oracle.com/javase/10/docs/api/java/awt/Component.html#revalidate()

编辑:我注意到它是 paint 方法。我不知道到底发生了什么,但 paint 应该只调用一次。可能 sleep 导致程序重新绘制并可能导致在剪辑中看到的奇怪行为。将此代码移至单独的线程。

public class ColorRotator extends Thread {

  final private Frame frame;
  public boolean active = true;

  public ColorRotator (Frame frame) {
    this.frame = frame;
  }

  @Override
  public void run() {
    while (active) {
        int red,green,blue;
        red = (int) (Math.random()*255);
        green = (int) (Math.random()*255);
        blue = (int) (Math.random()*255);
        Color c1 = new Color(red,blue);
        frame.setBackground(c1);
        Thread.sleep(1000);
    }
  }
}