1

我想知道如何更改此代码块以能够具有从(红色->黑色->绿色->黑色->蓝色->黑色->红色)切换的动态变化的背景颜色,并且循环再次开始. 背景颜色应在每个刻度上不断变化。现在我有一个渲染方法,它将在循环中连续运行,我想知道是否有人能够改变它,以便它也包括这种动态颜色变化。

private void render() {
        BufferStrategy bs = this.getBufferStrategy();
        if (bs == null) {
            this.createBufferStrategy(3);
            return;
        }

        Graphics g = bs.getDrawGraphics();
        g.setColor(Color.black);
        g.fillRect(0, 0, WIDTH, HEIGHT);


        g.dispose();
        bs.show();
    }
4

1 回答 1

0

Hello and welcome to SO!

You are not using swing right. You should be doing all your rendering in paintComponent, which gets automatically called when needed. However paintComponent on JFrame doesn't do anything, as the JFrame contains a ContentPane (JFrame.getContentPane) and that is the background you want to change. Changing the background of the contentpane should be as simple as

myJFrame.getContentPane().setBackground(newColor);

However not all (J)Components paint their background (JLabel for one), so you may need to create a JPanel and use myJFrame.setContentPane(...); before the code above

Note: To get swing to be single-threaded (as it should be) use SwingUtilities.invokeLater(...) to create/modify Swing classes.

Note 2: Looping in swing should be done using javax.swing.Timer. You don't need a loop though: Set the new background in your click listener, and then call repaint

于 2020-04-20T11:27:26.350 回答