简体   繁体   中英

How to stop background graphics in java?

i try to make a simple java game . ıt work fine but i draw a background but i didn't stop square's color , it always change 在此处输入图片说明

i write another class for that and i call it in main but i didn't work it

@SuppressWarnings("serial")

class BackPan extends JFrame{


    private JLayeredPane layers;
    private JPanel down;
    static int width = Board.boardWidth;
    static int height = Board.boardHeight;
    Random rnd = new Random();

    public BackPan(){

           layers = new JLayeredPane();
           rnd =new Random(); 
           down = new JPanel(){
           public void paintComponent(Graphics g){
            Graphics2D g2d = (Graphics2D)g; 
            //***************************************************************
            int low = 50; 
            int high = 255;
            for(int i = 0; i<= width; i+=50){
                g2d.setColor(new Color(rnd.nextInt(high-low)+low,rnd.nextInt(high-low)+low,rnd.nextInt(high-low)+low));             
                g2d.fillRect(i, 50, 50, 50);
                for(int j = 0; j<= height; j += 50 ){
                    g2d.setColor(new Color(rnd.nextInt(high-low)+low,rnd.nextInt(high-low)+low,rnd.nextInt(high-low)+low));
                    g2d.fillRect(i, j, 50, 50);                 
                }
            }
           }
           };
           //****************************************************************
           down.setBounds(0, 0, width, height);
           layers.add(down, new Integer(1));
           getContentPane().add(layers, BorderLayout.CENTER);


    }

}

Better than using a set seed for your randomization, simply fix the random image by one of two ways:

  1. Create an array of colors that you randomize when needed and then use this array when drawing the background
  2. Even better, simply draw your random colors to a BufferedImage and draw that in the paintComponent method. If this needs to be re-randomized, then re-create the image.

For an example of the latter, note that the image re-randomizes only when the button is pressed (by calling the createBackground() method):

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import javax.swing.*;

@SuppressWarnings("serial")
public class ColorSquares extends JPanel {
    public static final int SQR_SIDE = 50;
    public static final int COLUMNS = 20;
    public static final int ROWS = 16;
    private int columns;
    private int rows;
    private int sqrSide;
    private Image backgroundImg;    

    public ColorSquares(int columns, int rows, int sqrSide) {
        this.columns = columns;
        this.rows = rows;
        this.sqrSide = sqrSide;
        backgroundImg = createBackground();
        add(new JButton(new AbstractAction("New Background") {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                backgroundImg = createBackground();
                repaint();
            }
        }));
    }

    public Image createBackground() {
        int w = columns * sqrSide;
        int h = rows * sqrSide;
        BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
        Graphics g = img.getGraphics();
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < columns; c++) {
                float hue = (float) Math.random();
                float saturation = (float) (Math.random() * 0.5 + 0.5);
                float brightness = (float) (Math.random() * 0.5 + 0.5);
                Color randColor = Color.getHSBColor(hue, saturation, brightness);
                g.setColor(randColor);
                int x = c * sqrSide;
                int y = r * sqrSide;
                g.fillRect(x, y, sqrSide, sqrSide);
            }
        }
        g.dispose();
        return img;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (backgroundImg != null) {
            g.drawImage(backgroundImg, 0, 0, this);
        }
    }

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(columns * sqrSide, rows * sqrSide);
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("Colors");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new ColorSquares(COLUMNS, ROWS, SQR_SIDE));
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

An additional benefit of using a BufferedImage is that it's quicker to draw this than as you're doing it.

The simplest solution would be to remember a constant random seed and set it via rnd.setSeed() each time paintComponent is called. For example:

private final static int SEED = 1000;
rnd.setSeed(SEED);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM