为什么每次最小化窗口时,Java程序都会刷新?

为什么每次最小化窗口时,Java程序都会刷新?,java,swing,Java,Swing,我正在制作一个palace游戏,以便更好地理解Java编程。虽然我遇到了一个问题,每次最小化屏幕时,选择卡图像的变量都会不断刷新。例如,我的随机化函数使变量根据一个数字选择一张卡片,然后显示它,但每次我最小化页面并再次打开它时,它都会改变。我试图寻找我的问题的答案,但找不到。我所做的代码在我问的前一个问题中我的问题是如何阻止每次最小化页面时刷新变量? 编辑:我刚刚意识到,如果有帮助的话,每次我用光标移动窗口时,它也会改变。 这是我的随机化功能: public void randomizer()

我正在制作一个palace游戏,以便更好地理解Java编程。虽然我遇到了一个问题,每次最小化屏幕时,选择卡图像的变量都会不断刷新。例如,我的随机化函数使变量根据一个数字选择一张卡片,然后显示它,但每次我最小化页面并再次打开它时,它都会改变。我试图寻找我的问题的答案,但找不到。我所做的代码在我问的前一个问题中我的问题是如何阻止每次最小化页面时刷新变量?

编辑:我刚刚意识到,如果有帮助的话,每次我用光标移动窗口时,它也会改变。

这是我的随机化功能:

public void randomizer() {
        Random rand = new Random();
        int rand_int1 = rand.nextInt(15-1)+1;
        System.out.print(rand_int1);
        if (rand_int1 == 1) {
            setVariables(aceClover);

        }else if (rand_int1 == 2) {
            setVariables(twoClover);
        }else if (rand_int1 == 3) {
            setVariables(threeClover);
        }else if (rand_int1 == 4) {
            setVariables(fourClover);
        }else if (rand_int1 == 5) {
            setVariables(fiveClover);   
        }else if (rand_int1 == 6) {
            setVariables(sixClover);
        }else if (rand_int1 == 7) {
            setVariables(sevenClover);
        }else if (rand_int1 == 8) {
            setVariables(eightClover);
        }else if (rand_int1 == 9) {
            setVariables(nineClover);
        }else if (rand_int1 == 10) {
            setVariables(tenClover);
        }else if (rand_int1 == 11) {
            setVariables(jackClover);
        }else if (rand_int1 == 12) {
            setVariables(queenClover);
        }else if (rand_int1 == 13) {
            setVariables(kingClover);
        }else {
            System.out.println("Couldn't return any Cards!");
        }
    }
如果您需要此问题中的其余代码:


它确实有一些小改动,因为我修复了以前的问题。我所做的只是创建一个新类,将这些变量的创建移到该类中,并将它们从以前的类中删除。

因为您正在从paint方法中调用随机化器,并且每当gui最小化和恢复时,都会调用该方法,或者任何时候调整大小

解决方案:不要这样做,在绘制方法中没有任何程序逻辑,而是只有绘制代码

相反:

  • 从只调用一次的类构造函数进行调用
此外:

  • 不要扩展组件而是JPanel(不要混合AWT和Swing组件)
  • 在JPanel的paintComponent方法中绘制
  • 如果要覆盖绘制,请在覆盖
    super.paint(g)
    中调用super的绘制方法;如果要覆盖paintComponent,请在覆盖
    super.paintComponent(g)
    中调用super的绘制方法。这允许进行“内务管理”绘制,包括删除“脏”像素

感谢您的快速回复!这是因为您正在调用
accessor.randomizer()绘制方法中的code>。
package MainClasses;
import java.awt.*;
import java.io.*;
import java.util.Random;

import javax.imageio.ImageIO;

public class DrawBoard extends Component{
    AllCards accessor = new AllCards();
    public void paint(Graphics g) { // function to draw onto the window
    Graphics2D g1 = (Graphics2D)g; // the component being used to access and write to the window
    g1.clearRect(0, 0, getWidth(), getHeight()); // clears rectangle every frame
    g1.setBackground(Color.green); // sets background color
    accessor.randomizer();
    g1.drawImage(accessor.imageExtract, 100, 100, null);
    }   
}