【发布时间】:2016-06-20 15:35:18
【问题描述】:
单击框架面板时,我无法生成多个椭圆形。我想要的是它会生成许多椭圆形并且这些形状会向下移动。要求之一是使用两个多线程。但是在我的情况下,我创建的程序是,它只会生成一个椭圆形,并且位置是随机变化的。谁能帮我一个这个。
package ovalrandomcolors;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.List;
import java.awt.Shape;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.Collections;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class OvalRandomColors extends JPanel{
private int ovalX = 50;
private int ovalY =50;
private int ovalPositionX = 250;
private int ovalPositionY = 250;
private Color color = Color.YELLOW;
public OvalRandomColors(){
setBackground(Color.DARK_GRAY);
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(color);
g.fillOval(ovalPositionX, ovalPositionY, ovalX, ovalY);
g.setColor(color);
g.fillOval(ovalPositionX, ovalPositionY, ovalX, ovalY);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
JFrame frame = new JFrame();
final OvalRandomColors oval = new OvalRandomColors();
oval.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e){
OvalWithThreading firstThread = new OvalWithThreading(oval);
OvalWithThreading secondThread = new OvalWithThreading(oval);
Thread first = new Thread(firstThread);
Thread second = new Thread(secondThread);
second.start();
first.start();
}
});
frame.add(oval);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,700);
frame.setVisible(true);
}
});
}
public void updateOval(){
int r = (int)(Math.random() * 255);
int g = (int) (Math.random() * 255);
int b = (int)(Math.random() * 255);
color = new Color(r,g,b);
ovalPositionX = (int)(Math.random() * 78);
ovalPositionY = (int) (Math.random() * 245);
animateOval();
repaint();
}
public void animateOval(){
// ovalPositionX += 30;
ovalPositionY += 30;
}
public static class OvalWithThreading implements Runnable{
private final OvalRandomColors ovalShape;
public OvalWithThreading(OvalRandomColors oS){
this.ovalShape = oS;
}
@Override
public void run() {
for(;;){
ovalShape.updateOval();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(OvalRandomColors.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
【问题讨论】:
-
您需要某种
List,您可以在其中添加新的矩形并从中移动和绘制。一般来说,SwingTimer比使用Thread更好,因为 Swing 不是线程安全的 -
@MadProgrammer 我也读过。但是,要求之一是现在使用线程。能否请您举例说明如何实现列表?
标签: java multithreading swing awt