java jpanel调用构造函数的时候就开始执行repaint,Swing:为什么repaint()并没有调用paintComponent方法,该如何解决...

这个博客展示了如何使用Java Swing库创建一个简单的动画,通过一个`MyThread`类更新小球的位置,并调用`repaint()`方法来重绘组件。然而,作者遇到问题,即调用`repaint()`并未触发`paintComponent()`方法的执行。
摘要由CSDN通过智能技术生成

Java codepackage org.net;

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

import java.awt.geom.Ellipse2D;

public class BallFrame extends JFrame{

JPanel downPanel;

JButton startButton;

MyPanel upPanel;

Ellipse2D.Double d1 ;

Ellipse2D.Double d2 ;

long t;

long begin;

double x;

double y;

public BallFrame(){

setSize(300,400);

downPanel = new JPanel();

startButton = new JButton("start");

startButton.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent event){

MyThread t = new MyThread();

begin = System.currentTimeMillis();

t.start();

}

});

downPanel.add(startButton);

add(downPanel,BorderLayout.SOUTH);

upPanel = new MyPanel();

d1 = new Ellipse2D.Double(0,0,15,15);

d2 = new Ellipse2D.Double(0,0,15,15);

upPanel.addBall(d1,d2);

}

public static void main(String[] args) {

BallFrame f = new BallFrame();

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setVisible(true);

}

class MyPanel extends JPanel{

Ellipse2D.Double d1 ;

Ellipse2D.Double d2 ;

public void paintComponent(Graphics g){ //???没有被调用

super.paintComponent(g);

System.out.println("===进入paint方法===");

Graphics2D g2 = (Graphics2D)g;

g2.fill(d1);

g2.fill(d2);

}

public void addBall(Ellipse2D.Double d1,Ellipse2D.Double d2){

this.d1 = d1;

this.d2 = d2;

}

}

class MyThread extends Thread{

public void run(){

for(int i=0;i<1000;i++){

t = (System.currentTimeMillis()-begin)/1000;

x = 26*t;

y = 0.5 * 9.8 * Math.pow(t, 2);

System.out.println(x+":"+y);

repaint(); //????为什么调用repaint方法不能进入paintComponent方法呢?

try{

Thread.sleep(100);

}

catch(Exception e){

}

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值