JPanel的repaint调用时应该是先自调用update(),再调用paint()
为什么我每次画的时候没有清空,而是新添画了一个
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
class Show extends JPanel{
ArrayList price;
static int w=500;
static int h=400;
public Show(ArrayList al){
price=al;
this.setSize(600,500);
}
public void setPrice(ArrayList al){
price=al;
}
public void paint(Graphics g){
if(price.size()>=2){
int[] x=new int[price.size()];
int[] y=new int[price.size()];

int mw=500/x.length;
for(int i=0;i<x.length;i++){
x[i]=w-i*mw;
y[i]=400-Integer.parseInt(price.get(i).toString());
}
g.fillOval(x[x.length-1]+50, y[x.length-1]+100, 10, 10);
/*for(int i=0;i<x.length;i++){
//g.fillOval(x[i]+50, y[i]+100, 3, 3);
}
for(int i=0;i<x.length-1;i++){
//g.drawLine(x[i]+50, y[i]+100, x[i+1]+50, y[i+1]+100);
}*/
}
}
}public class GuPiao extends JFrame implements Runnable,ActionListener{
public ArrayList price=new ArrayList();
public Show panel=new Show(price);;
JButton btn;
public GuPiao(){
btn=new JButton("a");
btn.setBounds(500,300, 35, 25);
//price.add(new Integer(200));
Container c = this.getContentPane();
//c.setBounds(50, 50, 600, 500);
c.setLayout(null);
c.add(panel);
c.add(btn);
btn.addActionListener(this);
this.setSize(650, 400);
this.setLocation((Toolkit.getDefaultToolkit().getScreenSize().width - this.getSize().width) / 2, (Toolkit.getDefaultToolkit().getScreenSize().height - this.getSize().height) / 2);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e){
int p=(int)(Math.random()*100)+300;
price.add(new Integer(p));
panel.setPrice(price);
panel.repaint();
}
public void run(){
try{
for(int i=0;i<50;i++){
int p=(int)(Math.random()*100)+300;
System.out.println(p);
price.add(new Integer(p));
panel.setPrice(price);
this.panel.repaint();
Thread.sleep(1000);
}
}catch(Exception e){
System.out.println(e);
}
}
public static void main(String[] args){
GuPiao gp=new GuPiao();
//g.setPrice();
//Thread t=new Thread(gp);
//t.start();
}
}