【发布时间】:2017-11-12 04:37:33
【问题描述】:
好的,所以我正在做一个学校项目(小动画),我目前正在尝试下雨。我不确定如何使用 JPanel 绘制单个“水滴”。到目前为止我的代码:
主类:
public class RainPanel extends JPanel {
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
new RainPanel();
}
private final int WIDTH = 800, HEIGHT = 800;
Drop drop;
public RainPanel() {
init();
}
public void init() {
JFrame frame = new JFrame("Rain");
JPanel drop = new Drop();
frame.setVisible(true);
frame.setSize(WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.add(drop);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
drop.paint(g);
}
删除类:
public class Drop extends JPanel implements ActionListener{
private static final long serialVersionUID = 1L;
int x,y;
int yVel = 2;
Timer t = new Timer(5, this);
Random r = new Random();
ArrayList<Drop> DropArray;
public Drop() {
x = r.nextInt(800);
y = r.nextInt(800);
t.start();
}
public void paint(Graphics g) {
super.paintComponent(g);
DropArray = new ArrayList<>(100);
for (int i = 0; i < DropArray.size(); i++) {
DropArray.add(new Drop());
}
g.setColor(Color.BLUE);
g.fillRect(x, y, 3, 15);
}
public void update() {
y += yVel;
if (y > 800)
y = r.nextInt(800);
}
@Override
public void actionPerformed(ActionEvent e) {
update();
repaint();
}
我知道您现在是否会感到畏缩(我对图形编码还很陌生,而且对 Java 本身很熟悉)。我目前正在绘制的只是一个雨滴。任何建议表示赞赏。
【问题讨论】:
-
不要从
paint内部调用super.paintComponent,覆盖paintComponent代替 -
你不应该在
paint里面更新DropArray,这应该在其他地方完成,比如构造函数 -
根据你的例子,
Drop不应该是一个组件 -
如果我不应该使用
Drop作为组件,那应该是什么?顺便感谢您的回复。
标签: java swing graphics jpanel paintcomponent