如何在Java中使用线程创建多个下落的物体?

huangapple go评论107阅读模式
英文:

How to create multiple falling down objects by using threads in java?

问题

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

public class Project3 extends JFrame {
    public Project3() {
        super("Game");
        setSize(600, 600);
        add(new Game(600, 600));
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);
    }

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

    class Square {
        public int squareX;
        public int squareY;
        int squareW = 25;
        int squareH = 25;

        public Square(int X, int Y) {
            this.squareX = X;
            this.squareY = Y;
        }

        public int getSquareX() {
            return squareX;
        }

        public void setSquareX(int X) {
            this.squareX = X;
        }

        public int getSquareY() {
            return squareY;
        }

        public void setSquareY(int Y) {
            this.squareY = Y;
        }
    }

    class Game extends JPanel implements ActionListener, Runnable, MouseListener {
        public int score;
        private java.util.List<Square> shapeList = new ArrayList<>();
        Timer timer = new Timer(10, this);
        private boolean play = true;

        public Game(int w, int h) {
            Dimension d = new Dimension(600, 600);
            setBackground(Color.BLUE);
            add(new Label("SCORE...."), BorderLayout.PAGE_END);
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.YELLOW);
            for (Square s : shapeList) {
                g.fillRect(s.squareX, s.squareY, 25, 25);
            }
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            for (Square k : shapeList) {
                k.setSquareY(k.getSquareY() + 5);
                repaint();
            }
        }

        public void stop() {
            play = false;
        }

        @Override
        public void run() {
            while (play) {
                int randomNumber = (int) (Math.random() * 600) + 1;
                shapeList.add(new Square(randomNumber, 0));

                for (Square k : shapeList) {
                    if (k.getSquareY() == 600) {
                        stop();
                    }
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException ignored) {
                    }
                }
            }
        }

        @Override
        public void mouseClicked(MouseEvent e) {

        }

        @Override
        public void mousePressed(MouseEvent e) {
            int mouseX = e.getX();
            int mouseY = e.getY();
            for (Square s : shapeList) {
                if ((mouseX > s.squareX) && (mouseX < s.squareX + s.squareW) &&
                        (mouseY > s.squareY) && (mouseY < s.squareY + s.squareH)) {
                    shapeList.remove(s);
                    score++;
                }
            }
        }

        @Override
        public void mouseReleased(MouseEvent e) {

        }

        @Override
        public void mouseEntered(MouseEvent e) {

        }

        @Override
        public void mouseExited(MouseEvent e) {

        }
    }
}
英文:

** Here i created only one moving object ,i want to create more objects which falls down and has random X coordinate .i know i should implement runnable and i should create squres then store them in a collection but its really hard for me to merge everything.i also might have done some mistakes btw . Could you help me some ? **

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Random;
public class Project3 extends JFrame {
public Project3(){
super(&quot;Game&quot;);
setSize(600,600);
add(new Game(600,600));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -&gt; new Project3());
}
class Squares{
public int x;
public int y;
public Squares(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
class Game extends JPanel implements ActionListener {
private int score;
private java.util.List&lt;Squares&gt; shapeList=new ArrayList&lt;&gt;();
private boolean play ;
private int X=50;
private int Y=0;
Timer timer=new Timer(10,this);
public Game(int w , int h){
Dimension d = new Dimension(w, h);
setBackground(Color.BLUE);
}
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.fillRect(X,Y,60,60);
timer.start();
}
@Override
public void actionPerformed(ActionEvent e) {
Y=Y+5;
repaint();
if(Y==600){
Random random=new Random();
Y=0;
X=random.nextInt(600-60);
}
}
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class Project3 extends JFrame {
public Project3() {
super(&quot;Game&quot;);
setSize(600, 600);
add(new Game(600,600));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -&gt; new Project3());
}
class Square {
public int squareX;
public int squareY;
int squareW = 25;
int squareH = 25;
public Square(int X, int Y) {
this.squareX = X;
this.squareY = Y;
}
public int getSquareX() {
return squareX;
}
public void setSquareX(int X) {
this.squareX = X;
}
public int getSquareY() {
return squareY;
}
public void setSquareY(int Y) {
this.squareY = Y;
}
}
class Game extends JPanel implements ActionListener ,Runnable,MouseListener {
public int score;
private java.util.List&lt;Square&gt; shapeList = new ArrayList&lt;&gt;();
Timer timer = new Timer(10, this);
private boolean play= true;
public Game(int w, int h) {
Dimension d = new Dimension(600, 600);
setBackground(Color.BLUE);
add(new Label(&quot;SCORE....&quot;),BorderLayout.PAGE_END);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.YELLOW);
for (Square s:shapeList) {
g.fillRect(s.squareX,s.squareY,25,25);
}
}
@Override
public void actionPerformed(ActionEvent e) {
for (Square k : shapeList) {
k.setSquareY(k.getSquareY() + 5);
repaint();
}
}
public void stop() {
play = false;
}
@Override
public void run() {
while(play){
int randomNumber=(int)(Math.random()*600)+1;
shapeList.add(new Square(randomNumber,0));
for (Square k : shapeList) {
if (k.getSquareY()== 600) {
stop();
}try {
Thread.sleep(500);
} catch (InterruptedException ignored) {
}
}
}
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
int mouseX=e.getX();
int mouseY=e.getY();
for (Square s:shapeList){
if ((mouseX &gt; s.squareX) &amp;&amp; (mouseX &lt; s.squareX + s.squareW) &amp;&amp; (mouseY &gt; s.squareY) &amp;&amp; (mouseY &lt; s.squareY + s.squareH)) {
shapeList.remove(s);
score++;
}
}
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
}
}

答案1

得分: 1

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.util.Random;

public class AnimatedSnowFall {

    private JComponent ui = null;

    AnimatedSnowFall() {
        initUI();
    }

    public final void initUI() {
        if (ui != null) {
            return;
        }

        ui = new JPanel(new BorderLayout(4, 4));
        ui.setBorder(new EmptyBorder(4, 4, 4, 4));

        ui.add(new SnowFall());
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = () -> {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception useDefault) {
            }
            AnimatedSnowFall o = new AnimatedSnowFall();

            JFrame f = new JFrame(o.getClass().getSimpleName());
            f.setResizable(false);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setLocationByPlatform(true);

            f.setContentPane(o.getUI());
            f.pack();
            f.setMinimumSize(f.getSize());

            f.setVisible(true);
        };
        SwingUtilities.invokeLater(r);
    }
}

class SnowFall extends JPanel implements ActionListener {

    Dimension prefSize = new Dimension(1600, 900);
    SnowFlake[] farFlakes = new SnowFlake[200];
    SnowFlake[] midFlakes = new SnowFlake[150];
    SnowFlake[] closeFlakes = new SnowFlake[75];
    Color farColor = new Color(100, 100, 255);
    Color midColor = new Color(150, 150, 255);
    Color closeColor = new Color(255, 255, 255);

    SnowFall() {
        setBackground(Color.BLACK);
        for (int ii = 0; ii < farFlakes.length; ii++) {
            farFlakes[ii] = new SnowFlake(prefSize.width, prefSize.height, 2, 4);
        }
        for (int ii = 0; ii < midFlakes.length; ii++) {
            midFlakes[ii] = new SnowFlake(prefSize.width, prefSize.height, 3, 6);
        }
        for (int ii = 0; ii < closeFlakes.length; ii++) {
            closeFlakes[ii] = new SnowFlake(prefSize.width, prefSize.height, 4, 8);
        }
        Timer timer = new Timer(50, this);
        timer.start();
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        g.setColor(farColor);
        for (SnowFlake snowFlake : farFlakes) {
            snowFlake.draw(g);
        }

        g.setColor(midColor);
        for (SnowFlake snowFlake : midFlakes) {
            snowFlake.draw(g);
        }

        g.setColor(closeColor);
        for (SnowFlake snowFlake : closeFlakes) {
            snowFlake.draw(g);
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return prefSize;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        repaint();
    }
}

class SnowFlake {

    int w;
    int h;
    int x;
    int y;
    int size;
    int speed;
    static Random r = new Random();

    SnowFlake(int w, int h, int size, int speed) {
        this.w = w;
        this.h = h;
        x = r.nextInt(w);
        y = r.nextInt(h);
        this.size = size;
        this.speed = speed;
    }

    public void draw(Graphics g) {
        y += speed;
        if (y > h) {
            x = r.nextInt(w);
            y = 0;
        }
        g.fillOval(x, y, size, size);
    }
}
英文:

This code produces three layers of 'snow flakes' which drift towards the bottom of the screen.

Have a look over it, for tips:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.util.Random;
public class AnimatedSnowFall {
private JComponent ui = null;
AnimatedSnowFall() {
initUI();
}
public final void initUI() {
if (ui != null) {
return;
}
ui = new JPanel(new BorderLayout(4, 4));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
ui.add(new SnowFall());
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = () -&gt; {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
AnimatedSnowFall o = new AnimatedSnowFall();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
};
SwingUtilities.invokeLater(r);
}
}
class SnowFall extends JPanel implements ActionListener {
Dimension prefSize = new Dimension(1600, 900);
SnowFlake[] farFlakes = new SnowFlake[200];
SnowFlake[] midFlakes = new SnowFlake[150];
SnowFlake[] closeFlakes = new SnowFlake[75];
Color farColor = new Color(100,100,255);
Color midColor = new Color(150,150,255);
Color closeColor = new Color(255,255,255);
SnowFall() {
setBackground(Color.BLACK);
for (int ii = 0; ii &lt; farFlakes.length; ii++) {
farFlakes[ii] = new SnowFlake(prefSize.width, prefSize.height, 2, 4);
}
for (int ii = 0; ii &lt; midFlakes.length; ii++) {
midFlakes[ii] = new SnowFlake(prefSize.width, prefSize.height, 3, 6);
}
for (int ii = 0; ii &lt; closeFlakes.length; ii++) {
closeFlakes[ii] = new SnowFlake(prefSize.width, prefSize.height, 4, 8);
}
Timer timer = new Timer(50, this);
timer.start();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(farColor);
for (SnowFlake snowFlake : farFlakes) {
snowFlake.draw(g);
}
g.setColor(midColor);
for (SnowFlake snowFlake : midFlakes) {
snowFlake.draw(g);
}
g.setColor(closeColor);
for (SnowFlake snowFlake : closeFlakes) {
snowFlake.draw(g);
}
}
@Override
public Dimension getPreferredSize() {
return prefSize;
}
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
}
class SnowFlake {
int w;
int h;
int x;
int y;
int size;
int speed;
static Random r = new Random();
SnowFlake(int w, int h, int size, int speed) {
this.w = w;
this.h = h;
x = r.nextInt(w);
y = r.nextInt(h);
this.size = size;
this.speed = speed;
}
public void draw(Graphics g) {
y += speed;
if (y &gt; h) {
x = r.nextInt(w);
y = 0;
}
g.fillOval(x, y, size, size);
}
}

huangapple
  • 本文由 发表于 2020年5月29日 17:29:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/62082763.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定