开发者

Background appears black not cyan when using JFrame and Canvas

开发者 https://www.devze.com 2023-03-20 08:13 出处:网络
Hello I am making a program that creates a multi-flashing block on a cyan background in Java. I am using JFrames and Canvas but for some reason even if I specify for the color to be cyan it makes my b

Hello I am making a program that creates a multi-flashing block on a cyan background in Java. I am using JFrames and Canvas but for some reason even if I specify for the color to be cyan it makes my background black. However the keylistener if blocks fill in the space with cyan if you move the box. Below is the code which I think is relevant to the problem. Any help would be greatly appreciated and thank you for reading this.(Note this is probably bad syntax and coding, but my theory is to make the code work before prettying it up.)

  GraphicsEnvironment ge =
    GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();

// Create off-screen drawing surface
BufferedImage bi = gc.createCompatibleImage( 640, 480 );

// Objects needed for rendering...


Graphics graphics = null;
Graphics2D g2d = null;

//Why isn't the background color cyan? (It's black)
Color background = Color.C开发者_StackOverflow社区YAN;
Random rand = new Random();

//The x and y positions are randomly generated as are the length and width
int x = rand.nextInt(640 / 2), y = rand.nextInt(640 / 2);
int w = rand.nextInt( 640/2 );
int h = rand.nextInt( 480/2 );





//To Do: Infinite loops suck, make a death variable
while( true ) {
    try {
    // clear back buffer...      

    g2d = bi.createGraphics();
    g2d.setColor(Color.CYAN);
    g2d.fillRect( -1000, 1000, 1000, 1000 );

    // draw the rectangle...
      int r = rand.nextInt(256);
      int g = rand.nextInt(256);
      int b = rand.nextInt(256);
      g2d.setColor(new Color(r, g, b));
      g2d.fillRect( x, y, w, h );

    //Get the newly drawn rectangles and flip
    graphics = buffer.getDrawGraphics();
    graphics.drawImage(bi, x, y, canvas);


I'm not sure I completely understand what you are trying to do. If you are trying to make the JFrame cyan colored with a canvas in it this is what I did:

import java.awt.Canvas;
import java.awt.Color;
import javax.swing.JFrame;

public class test {
    static JFrame frame;
    static Canvas canvas;

    public static void main(String[] args){
        frame  = new JFrame();
        canvas = new Canvas();

        canvas.setBackground(Color.cyan);
        frame.getContentPane().add(canvas);
        frame.setVisible(true);
    }
}

I'm pretty sure that's not you want actually.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号