关于JPanel的repaint问题

steven138 2008-02-17 09:06:44
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();
}
}
...全文
504 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
tianyuansky 2010-05-12
  • 打赏
  • 举报
回复
好老的问题,让我来解释你几年来的疑惑吧
答案就是。。。。
因为你没有铺垫一个背景
原有的图像保留在了面板上
只要你在面板的绘制区域填充一个背景色
每次重绘的时候
用背景色盖住之前绘制的遗留
然后就能显示新的,而不是添加新的了
rain_night 2008-02-17
  • 打赏
  • 举报
回复
楼主说的repaint调用时应该是先自调用update(),再调用paint() 好像见过,不是很清楚了
不过楼主可以把Container c该为GuPiao类的字段,然后再把actionPerformed中该为c.repaint()试下,应该没问题

62,630

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧