简体   繁体   English

将自定义JPanel添加到JFrame之后的repaint方法

[英]repaint method after add custom JPanel to JFrame

I have this code, but JPanel repaint method does not work. 我有这段代码,但是JPanel重绘方法不起作用。 If I do that after add it to JFrame class I debug it and it does not recall paintComponent . 如果在将其添加到JFrame类之后执行此操作,则将对其进行调试,并且它不会调用paintComponent

Why is that so? 为什么会这样?

package trial;

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;


class jp extends JPanel
{
     int i=0;

     {
        setBackground(Color.RED);
     }

     @Override
     protected void paintComponent(Graphics g)
     { 
        super.paintComponent(g);
        Color[] c={Color.red,Color.green};
        //To change body of generated methods, choose Tools | Templates.
        g.drawLine(i, i, i+100, i+100);
        i+=50;
     }
}

public class Trial extends JFrame{

   public static void main(String[] args) {
       Trial f=new Trial();
       jp a;
       a=new jp(); 
       System.out.println(a.i);
       f.add(a);
       f.setVisible(true);
       f.setSize(500, 500);
       f.setDefaultCloseOperation(3);

       a.repaint();

   }
}

[UPDATE] to fit the question better: A call to repaint() places a PaintEvent into the Event Queue . [更新]更适合这个问题:调用repaint()会将PaintEvent放入事件队列 This PaintEvent will be handled by another thread, the Event Dispatching Thread . PaintEvent将由另一个线程( 事件调度线程)处理

In short: the paintComponent() is called in another thread as your main method. 简而言之: paintComponent()在另一个线程中作为您的主要方法被调用。

[/UPDATE] [/更新]

I am not sure what you're trying to achive but try this at the end of your main method: 我不确定您要达到的目标,但是请在main方法的末尾尝试一下:

    try {
        while (true) {
            Thread.sleep(1000);
            a.repaint();
        }
    } catch (InterruptedException e) {
    }

Is a moving line like this what you're expecting? 您所期望的移动路线是这样吗? The reason why this is working: As far as I recall, Java Swing may collapse multiple repaint requests that are enqueued in the Event Dispatching Thread into a single paint request - which is probably what you experienced. 之所以起作用,是因为:据我所知,Java Swing可能会将事件调度线程中排队的多个重新绘制请求折叠成一个绘制请求-这可能是您遇到的。 In my example above, waiting 1 second is enough to get distinct repaints. 在上面的示例中,等待1秒钟足以获得独特的重绘效果。

Nevertheless I strongly advise you not to use my (or your) code . 不过,我强烈建议您不要使用我(或您的)代码 Reason: The value of i depends on the number of calls to paintComponent - which can vary. 原因: i的值取决于对paintComponent的调用次数-可以变化。 For example, pull at a corner to resize the window - repaint maybe gets called dozens of times then! 例如,在某个角落拉动以调整窗口大小-那么重新绘制可能会被调用数十次!

Perhaps you want a javax.swing.Timer to periodically update the value of i and then trigger a repaint? 也许您希望javax.swing.Timer定期更新i的值,然后触发重新绘制?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM