Java 为什么随机矩形是I';你创造了没有出现在我的游戏中?

Java 为什么随机矩形是I';你创造了没有出现在我的游戏中?,java,user-interface,timer,drawrectangle,Java,User Interface,Timer,Drawrectangle,我是gui java新手,我一直在尝试重新创建名为“jump it”()的游戏,目前我正在制作随机矩形,让我的角色在上面跳跃。然而,我运行了我的代码,没有出现错误,但是我创建的矩形没有显示出来。我在下面附上了我的代码,对此我有点抱歉 import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.util.Random; import java.util.TimerTask; class GuiGame

我是gui java新手,我一直在尝试重新创建名为“jump it”()的游戏,目前我正在制作随机矩形,让我的角色在上面跳跃。然而,我运行了我的代码,没有出现错误,但是我创建的矩形没有显示出来。我在下面附上了我的代码,对此我有点抱歉

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.Random;
import java.util.TimerTask;

class GuiGame{
 public static void main(String args[]) {
    JFrame f = new JFrame("RUN - Christine & Esther"); //title of frame
    Container cont = f.getContentPane();  // get container - top of the frame
    cont.setLayout(new BorderLayout()); 
    BtnActPanel bp = new BtnActPanel();  // create an object of our game panel
    cont.add(bp, BorderLayout.CENTER );
    f.setVisible(true);
    f.setSize(975,613); //size of frame
 }
}

class Rectangle{
    static Random r = new Random();
    static int upperX = 100;
    static int lowerX = 20;
    static int upperY = 550;
    static int lowerY = 450;
    static int minWidth = 200;
    static int maxWidth = 600;
    static int minHeight = 40;
    static int maxHeight = 140;
    static int  x = 0, y = 0, w = 0, h = 0, check = 0;

    public Rectangle(){
        check++;
        int x = 650 + 50*check;
        int y = r.nextInt(upperY-lowerY + 1) + lowerY; // from 450 to 550
        int w = r.nextInt(maxWidth-minWidth + 1) + minWidth; // from 200 to 600
        int h = r.nextInt(maxHeight - minHeight + 1) + minHeight; // from 40 to 140
    }
    public int getx(){
        return x;
    }
    public int gety(){
        return y;
    }
    public int getw(){
        return w;
    }
    public int geth(){
        return h;
    }
}
class BtnActPanel extends JPanel implements ActionListener{
//variables
   private JButton b1, b2, b3;     
   private JPanel background;
   private JPanel game;
   private Timer t, timer;
   private int x = 0, check1 = 0, index = 0, x1 = 650, count2 = 0,
   y2 = (int)(Math.random()*100)+40, y1 = (int)(Math.random()*100)+450, 
   x2 = (int)(Math.random()*600)+200, xaxis = 0, yaxis = 0, w = 0, h = 0, count = 0;
   private ImageIcon []arrImage;
   private boolean check2;
   private static ImageIcon icon, exitButton, startButton, questionButton, b, instruct, c ;


   public BtnActPanel(){    

      c = new ImageIcon("character.png");   // constructor
      t = new Timer (100,this);
      arrImage = new ImageIcon[2];
      arrImage[0] = new ImageIcon("character.png");
      arrImage[1] = new ImageIcon("character2.png");

      startButton = new ImageIcon("startButton.png");//start button image
      questionButton = new ImageIcon("QuestionButton.png"); //question button image
      exitButton = new ImageIcon("exitButton.png"); //exit button image

      icon = new ImageIcon("Title.jpg");//title image

      b1 = new JButton(questionButton); // creates first button
      //only shows button image with borders
      b1.setOpaque(false);
      b1.setContentAreaFilled(false);
      b1.setBorderPainted(false);
      b1.setFocusPainted(false);

      b2 = new JButton(startButton);// creates second button
      //only shows button image with borders
      b2.setOpaque(false);
      b2.setContentAreaFilled(false);
      b2.setBorderPainted(false);
      b2.setFocusPainted(false);

      b3 = new JButton(exitButton);// creates third button
      //only shows button image with borders
      b3.setOpaque(false);
      b3.setContentAreaFilled(false);
      b3.setBorderPainted(false);
      b3.setFocusPainted(false);

      //adds buttons to code
      this.add(b1);
      this.add(b2);
      this.add(b3);

      b1.addActionListener(this);
      b2.addActionListener(this);
      b3.addActionListener(this);
   }// end of constructor

    public void actionPerformed(ActionEvent e) { //checks which button the user presses and performs actions based off choice
              if(e.getSource() == b1){
                check1 = 2;
                this.remove(b1);
                this.remove(b3);
                repaint();
                instruct = new ImageIcon("Instructions.jpg");
              }
              else if (e.getSource() == b2){
                t.start();
                check1 = 1;
                this.remove(b1);
                this.remove(b2);
                this.remove(b3);
                repaint();
                b = new ImageIcon("toskyline.png");


              }

              else  if (e.getSource() == b3){
                JOptionPane.showMessageDialog(null, "This is an exit button, hope you enjoyed the game! :)", "Exit message",JOptionPane.WARNING_MESSAGE ); //shows exit message
                System.exit(0);//exits program
              } 

              else if (e.getSource() == t){
                  if (index == 0){
                      index = 1;
                      c = arrImage[1];
                  }
                  else{
                      index = 0;
                      c = arrImage[0];
                  }
                if(count%50 == 0 && count >= 50){
                    Rectangle obstacle = new Rectangle();
                    int xaxis = obstacle.getx();
                    int yaxis = obstacle.gety();
                    int w = obstacle.getw();
                    int h = obstacle.geth();
                    xaxis = xaxis - 10;
                    count2 = 1;
                }   
                x = x - 10;
                x1 = x1 - 10;
                repaint();
              }   
    }


    public void paintComponent(Graphics g){//this method draws and paints images and icons based on the user decisions
        super.paintComponent(g);
        if(check1 == 0)[enter image description here][1]
            g.drawImage(icon.getImage(),0,0,null);
        if(check1 == 1){
            g.drawImage(b.getImage(),0,0,null);
            g.setColor(Color.black);
            g.fillRect(x,495, 500, 35);
            g.fillRect(x1, y1, x2, y2);
            count++;
            System.out.println(count);
            if(count2 == 1){
                g.fillRect(xaxis, yaxis, w, h);
                count2 = 0;
            }
            g.drawImage(c.getImage(), 100, 460, null);
        }

        if(check1 == 2)
            g.drawImage(instruct.getImage(),0,0,null);
        b1.setBounds(320, 350, 100, 100);
        b2.setBounds(420, 350, 100, 100);
        b3.setBounds(520, 350, 100, 100);
    }
}//end of class

我用你的射程做了一个演示

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class Demo extends JPanel implements ActionListener {
    final static int height = 800;
    final static int width = 800;
    final static String title = "title";
    JFrame frame = new JFrame("default title");
    Timer timer;
    static Random r = new Random();
    static int upperX = 100;
    static int lowerX = 20;
    static int upperY = 550;
    static int lowerY = 450;
    static int minWidth = 200;
    static int maxWidth = 600;
    static int minHeight = 40;
    static int maxHeight = 140;
    List<MyRectangle> rectangles = new ArrayList<>();

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

    public Demo() {
        frame.setDefaultCloseOperation(
                JFrame.EXIT_ON_CLOSE);
        frame.add(this);
        frame.setPreferredSize(
                new Dimension(width, height));
        setBackground(Color.WHITE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public void start() {
        timer = new Timer(0, this);
        timer.setDelay(1000);
        timer.start();
    }

    public void actionPerformed(ActionEvent ae) {
        rectangles.add(createRectangle());
        repaint();
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g.create();
        g2d.setRenderingHint(
                RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        for (MyRectangle r : rectangles) {
            g2d.setColor(Color.black);
            g2d.drawRect(r.x, r.y, r.width, r.height);
            g2d.setColor(r.color);
            g2d.fillRect(r.x+1, r.y+1, r.width-1,r.height-1);
        }
        g2d.dispose();

    }

    Color[] colors = {Color.RED, Color.BLUE, Color.GREEN, Color.ORANGE, Color.GRAY};
    int color = 0;
    public MyRectangle createRectangle() {
        int y = r.nextInt(upperY - lowerY + 1) + lowerY; // from 450 to 550
        int w = r.nextInt(maxWidth - minWidth + 1)
                + minWidth; // from 200 to 600
        int h = r.nextInt(maxHeight - minHeight + 1)
                + minHeight; // from 40 to 140
        int x = r.nextInt(upperX - lowerX + 1) + lowerX;
        Color c = colors[color++ % colors.length];
        return new MyRectangle(c, x, y, w, h);
    }

    class MyRectangle extends Rectangle {
       Color color; 
       MyRectangle(Color c, int x, int y, int w, int h) {
           super(x, y, w, h);
           this.color = c;
       }
    }

}
导入java.awt.Color;
导入java.awt.Dimension;
导入java.awt.Graphics;
导入java.awt.Graphics2D;
导入java.awt.Rectangle;
导入java.awt.RenderingHints;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.util.ArrayList;
导入java.util.List;
导入java.util.Random;
导入javax.swing.JFrame;
导入javax.swing.JPanel;
导入javax.swing.SwingUtilities;
导入javax.swing.Timer;
公共类演示扩展JPanel实现ActionListener{
最终静态内部高度=800;
最终静态整数宽度=800;
最终静态字符串title=“title”;
JFrame=新JFrame(“默认标题”);
定时器;
静态随机r=新随机();
静态整数x=100;
静态int-lowerX=20;
静态整数y=550;
静态int-lowerY=450;
静态int最小宽度=200;
静态int maxWidth=600;
静态最小高度=40;
静态整数最大高度=140;
列表矩形=新的ArrayList();
公共静态void main(字符串[]args){
猪肠
.invokeLater(()->new Demo().start());
}
公共演示(){
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
框架。添加(此);
frame.setPreferredSize(
新尺寸(宽度、高度);
挫折地面(颜色:白色);
frame.pack();
frame.setLocationRelativeTo(空);
frame.setVisible(true);
}
公开作废开始(){
计时器=新计时器(0,此);
定时器设置延迟(1000);
timer.start();
}
已执行的公共无效行动(行动事件ae){
添加(createRectangle());
重新油漆();
}
公共组件(图形g){
超级组件(g);
Graphics2D g2d=(Graphics2D)g.create();
g2d.setRenderingHint(
RenderingHists.KEY\u抗锯齿,
RenderingHints.VALUE_ANTIALIAS_ON);
用于(My矩形r:矩形){
g2d.setColor(Color.black);
g2d.drawRect(r.x、r.y、r.width、r.height);
g2d.setColor(r.color);
g2d.fillRect(r.x+1,r.y+1,r.width-1,r.height-1);
}
g2d.dispose();
}
Color[]colors={Color.RED,Color.BLUE,Color.GREEN,Color.橙色,Color.GRAY};
int color=0;
公共MyRectangle createRectangle(){
int y=r.nextInt(upperY-lowerY+1)+lowerY;//从450到550
int w=r.nextInt(最大宽度-最小宽度+1)
+minWidth;//从200到600
int h=r.nextInt(最大高度-最小高度+1)
+最小高度;//从40到140
int x=r.nextInt(上x-下x+1)+下x;
颜色c=颜色[Color++%colors.length];
返回新的MyRectangle(c,x,y,w,h);
}
类MyRectangle扩展了Rectangle{
颜色;
MyRectangle(颜色c、整数x、整数y、整数w、整数h){
super(x,y,w,h);
这个颜色=c;
}
}
}

这扩展了JDK类矩形,并向子类添加了一个颜色字段。它每秒显示一个新的矩形。

程序缺少部分,因此无法编译。请提供一个演示该问题的示例。不要在
paintComponent
中进行任何
setBounds
,因为这是一种糟糕的技术。非常感谢!您的代码中有一部分我并不完全理解,如果您不介意的话,paint component方法会让我感到困惑,您能向我解释一下这一部分吗?
super.paintComponent()
调用重写版本进行默认绘制。如果我不这样做,一些事情,比如
setBackground
将不起作用。“抗锯齿”通过平均边缘像素使对象看起来更平滑。如果你画了一个圆或对角线,并尝试了它与不带你可以看到的差异。绘制矩形我只需将颜色设置为
黑色
,然后
绘制一个矩形以获得一个
黑色
边框。然后,当我填充矩形时,我将x和y增加1个像素,并将宽度和高度减少1个像素,这样我就不会覆盖刚刚创建的边框。