JPanel上活动绘图的顶部JTextFields,线程问题

11
有没有人尝试过使用Swing构建一个合适的多缓冲渲染环境,在此之上可以添加Swing用户界面元素
在这种情况下,我在背景上绘制了一个动画的红色矩形。背景不需要每帧更新,因此我将其渲染到BufferedImage中,并仅重新绘制必要的部分以清除矩形的先前位置。请参见下面的完整代码,这扩展了@trashgod在先前的线程中提供的示例,在这里
到目前为止,一切顺利;流畅的动画,低CPU使用率,没有闪烁。
然后我在JPanel中添加了一个JTextField(通过单击屏幕上的任何位置),并通过单击文本框内部对其进行了聚焦。现在在每个光标闪烁时都无法清除矩形的先前位置,请参见下面的图像。
我想知道为什么会发生这种情况(Swing不是线程安全的吗?图像异步绘制?)以及可能解决方案的方向。
这是在Mac OS 10.5,Java 1.6上的情况。 JPanel redraw fail
(来源:arttech.nl)
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Transparency;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;

public class NewTest extends JPanel implements 
    MouseListener, 
    ActionListener, 
    ComponentListener, 
    Runnable 
{

JFrame f;
Insets insets;
private Timer t = new Timer(20, this);
BufferedImage buffer1;
boolean repaintBuffer1 = true;
int initWidth = 640;
int initHeight = 480;
Rectangle rect;

public static void main(String[] args) {
    EventQueue.invokeLater(new NewTest());
}

@Override
public void run() {
    f = new JFrame("NewTest");
    f.addComponentListener(this);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(this);
    f.pack();
    f.setLocationRelativeTo(null);
    f.setVisible(true);
    createBuffers();
    insets = f.getInsets();
    t.start();
}

public NewTest() {
    super(true);
    this.setPreferredSize(new Dimension(initWidth, initHeight));
    this.setLayout(null);
    this.addMouseListener(this);
}

void createBuffers() {
    int width = this.getWidth();
    int height = this.getHeight();

    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice gs = ge.getDefaultScreenDevice();
    GraphicsConfiguration gc = gs.getDefaultConfiguration();

    buffer1 = gc.createCompatibleImage(width, height, Transparency.OPAQUE);        

    repaintBuffer1 = true;
}

@Override
protected void paintComponent(Graphics g) {
    int width = this.getWidth();
    int height = this.getHeight();

    if (repaintBuffer1) {
        Graphics g1 = buffer1.getGraphics();
        g1.clearRect(0, 0, width, height);
        g1.setColor(Color.green);
        g1.drawRect(0, 0, width - 1, height - 1);
        g.drawImage(buffer1, 0, 0, null);
        repaintBuffer1 = false;
    }

    double time = 2* Math.PI * (System.currentTimeMillis() % 5000) / 5000.;
    g.setColor(Color.RED);
    if (rect != null) {
        g.drawImage(buffer1, rect.x, rect.y, rect.x + rect.width, rect.y + rect.height, rect.x, rect.y, rect.x + rect.width, rect.y + rect.height, this);
    }
    rect = new Rectangle((int)(Math.sin(time) * width/3 + width/2 - 20), (int)(Math.cos(time) * height/3 + height/2) - 20, 40, 40);
    g.fillRect(rect.x, rect.y, rect.width, rect.height);
}

@Override
public void actionPerformed(ActionEvent e) {
    this.repaint();
}

@Override
public void componentHidden(ComponentEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void componentMoved(ComponentEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void componentResized(ComponentEvent e) {
    int width = e.getComponent().getWidth() - (insets.left + insets.right);
    int height = e.getComponent().getHeight() - (insets.top + insets.bottom);
    this.setSize(width, height);
    createBuffers();
}

@Override
public void componentShown(ComponentEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseClicked(MouseEvent e) {
    JTextField field = new JTextField("test");
    field.setBounds(new Rectangle(e.getX(), e.getY(), 100, 20));
    this.add(field);
    repaintBuffer1 = true;
}

@Override
public void mouseEntered(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseExited(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mousePressed(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseReleased(MouseEvent arg0) {
    // TODO Auto-generated method stub

}
}
2个回答

18

NewTest 扩展了 JPanel 类,但是因为你不会在每次调用 paintComponent() 时绘制每个像素,所以需要调用超类的方法来擦除旧的绘图:

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    int width = this.getWidth();
    int height = this.getHeight();
    g.setColor(Color.black);
    g.fillRect(0, 0, width, height);
    ...
}

补充:正如您所提到的,在构造函数中设置背景颜色就可以避免在paintComponent()中填充面板,而super.paintComponent()可以使文本字段正确运行。正如您所观察到的,所提出的解决方法是脆弱的。相反,简化代码并根据需要进行优化。例如,您可能不需要插入、额外缓冲区和组件侦听器等复杂性。

补充2:注意,super.paintComponent()调用UI委托的update()方法,“如果其不透明属性为真,则用其背景颜色填充指定的组件。” 您可以使用setOpaque(false)来避免这种情况。

Animation Test

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Transparency;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;

/** @see http://stackoverflow.com/questions/3256941 */
public class AnimationTest extends JPanel implements ActionListener {

    private static final int WIDE = 640;
    private static final int HIGH = 480;
    private static final int RADIUS = 25;
    private static final int FRAMES = 24;
    private final Timer timer = new Timer(20, this);
    private final Rectangle rect = new Rectangle();
    private BufferedImage background;
    private int index;
    private long totalTime;
    private long averageTime;
    private int frameCount;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new AnimationTest().create();
            }
        });
    }

    private void create() {
        JFrame f = new JFrame("AnimationTest");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(this);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
        timer.start();
    }

    public AnimationTest() {
        super(true);
        this.setOpaque(false);
        this.setPreferredSize(new Dimension(WIDE, HIGH));
        this.addMouseListener(new MouseHandler());
        this.addComponentListener(new ComponentHandler());
    }

    @Override
    protected void paintComponent(Graphics g) {
        long start = System.nanoTime();
        super.paintComponent(g);
        int w = this.getWidth();
        int h = this.getHeight();
        g.drawImage(background, 0, 0, this);
        double theta = 2 * Math.PI * index++ / 64;
        g.setColor(Color.blue);
        rect.setRect(
            (int) (Math.sin(theta) * w / 3 + w / 2 - RADIUS),
            (int) (Math.cos(theta) * h / 3 + h / 2 - RADIUS),
            2 * RADIUS, 2 * RADIUS);
        g.fillOval(rect.x, rect.y, rect.width, rect.height);
        g.setColor(Color.white);
        if (frameCount == FRAMES) {
            averageTime = totalTime / FRAMES;
            totalTime = 0; frameCount = 0;
        } else {
            totalTime += System.nanoTime() - start;
            frameCount++;
        }
        String s = String.format("%1$5.3f", averageTime / 1000000d);
        g.drawString(s, 5, 16);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        this.repaint();
    }

    private class MouseHandler extends MouseAdapter {

        @Override
        public void mousePressed(MouseEvent e) {
            super.mousePressed(e);
            JTextField field = new JTextField("test");
            Dimension d = field.getPreferredSize();
            field.setBounds(e.getX(), e.getY(), d.width, d.height);
            add(field);
        }
    }

    private class ComponentHandler extends ComponentAdapter {

        private final GraphicsEnvironment ge =
            GraphicsEnvironment.getLocalGraphicsEnvironment();
        private final GraphicsConfiguration gc =
            ge.getDefaultScreenDevice().getDefaultConfiguration();
        private final Random r = new Random();

        @Override
        public void componentResized(ComponentEvent e) {
            super.componentResized(e);
            int w = getWidth();
            int h = getHeight();
            background = gc.createCompatibleImage(w, h, Transparency.OPAQUE);
            Graphics2D g = background.createGraphics();
            g.clearRect(0, 0, w, h);
            g.setColor(Color.green.darker());
            for (int i = 0; i < 128; i++) {
                g.drawLine(w / 2, h / 2, r.nextInt(w), r.nextInt(h));
            }
            g.dispose();
            System.out.println("Resized to " + w + " x " + h);
        }
    }
}

感谢您的回复。如果您添加了super.paintComponent(g)并运行我提供的测试应用程序,您会发现这不是一个解决方案。JPanel的默认paintComponent方法会清除其背景,这使得重新绘制整个背景图像成为必要,从而大多数情况下破坏了预渲染背景图像的目的。我有一种直觉,只重新绘制必要的区域应该是可能的,但似乎在不同于重绘背景图像的线程中重绘文本字段会导致这些绘图异常。 - Mattijs
关于补充说明:再次感谢您抽出时间深入研究。我意识到您的观点是,如果不使用super.paintComponent(g),自动重绘JTextFields将无法正确地与活动重绘一起工作。尽管如此,使用super.paintComponent(g)意味着每个动画帧都必须重新绘制整个窗口,这使得CPU使用率取决于窗口大小,这正是我想要避免的。所以我的问题得到了回答,但我的问题仍然存在。我会发一个新帖子来解决这个问题。 - Mattijs
@Mattijs:使用setOpaque(false)将避免填充。我已更新示例以显示绘制时间。差异是相当大的,但必须权衡更新管理的工作量。 - trashgod
@Mattijs:顺便说一下,我并不是想在你提出新问题之前就回答了它;绘制时间显示可能有助于缩小范围。 - trashgod
@trashgod:感谢您提供有用的补充。这是我的后续,我在其中详细阐述了这个测试代码并总结了我的发现:https://dev59.com/gk_Sa4cB1Zd3GeqP-DGk - Mattijs
显示剩余3条评论

2
我找到了一个解决办法。
我认为发生的情况是:每当需要更新JTextfield(即在每个光标闪烁时),就会调用JPanel的重写paintComponent(),但是使用的Graphics参数与repaint()调用时不同。因此,在每个光标闪烁时,我的矩形被清除并重新绘制在错误的Graphics实例上,导致屏幕上的Graphics无效。
这有意义吗?如果有,这不是Swing中的奇怪不便吗?
无论如何,通过保持一个boolean变量(activeRedraw)来记录调用来源,看起来我成功解决了这个问题。因此,似乎我终于找到了一种在不重绘整个屏幕区域的情况下进行活动绘图的方法,这意味着与窗口大小无关的低CPU使用率!
完整代码在此处:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Transparency;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;

public class NewTest extends JPanel implements 
    MouseListener, 
    ActionListener, 
    ComponentListener, 
    Runnable 
{

    JFrame f;
    Insets insets;
    private Timer t = new Timer(20, this);
    BufferedImage buffer1;
    boolean repaintBuffer1 = true;
    int initWidth = 640;
    int initHeight = 480;
    Rectangle rect;
    boolean activeRedraw = true;

    public static void main(String[] args) {
        EventQueue.invokeLater(new NewTest());
    }

    @Override
    public void run() {
        f = new JFrame("NewTest");
        f.addComponentListener(this);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(this);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
        createBuffers();
        insets = f.getInsets();
        t.start();
    }

    public NewTest() {
        super(true);
        this.setPreferredSize(new Dimension(initWidth, initHeight));
        this.setLayout(null);
        this.addMouseListener(this);
    }

    void createBuffers() {
        int width = this.getWidth();
        int height = this.getHeight();

        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice gs = ge.getDefaultScreenDevice();
        GraphicsConfiguration gc = gs.getDefaultConfiguration();

        buffer1 = gc.createCompatibleImage(width, height, Transparency.OPAQUE);        

        repaintBuffer1 = true;
    }

    @Override
    protected void paintComponent(Graphics g) {
        //super.paintComponent(g);
        int width = this.getWidth();
        int height = this.getHeight();

        if (activeRedraw) { 
            if (repaintBuffer1) {
                Graphics g1 = buffer1.getGraphics();
                g1.clearRect(0, 0, width, height);
                g1.setColor(Color.green);
                g1.drawRect(0, 0, width - 1, height - 1);
                g.drawImage(buffer1, 0, 0, null);
                repaintBuffer1 = false;
            }

            double time = 2* Math.PI * (System.currentTimeMillis() % 5000) / 5000.;
            g.setColor(Color.RED);
            if (rect != null) {
                g.drawImage(buffer1, rect.x, rect.y, rect.x + rect.width, rect.y + rect.height, rect.x, rect.y, rect.x + rect.width, rect.y + rect.height, this);
            }
            rect = new Rectangle((int)(Math.sin(time) * width/3 + width/2 - 20), (int)(Math.cos(time) * height/3 + height/2) - 20, 40, 40);
            g.fillRect(rect.x, rect.y, rect.width, rect.height);

            activeRedraw = false;
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        activeRedraw = true;
        this.repaint();
    }

    @Override
    public void componentHidden(ComponentEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void componentMoved(ComponentEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void componentResized(ComponentEvent e) {
        int width = e.getComponent().getWidth() - (insets.left + insets.right);
        int height = e.getComponent().getHeight() - (insets.top + insets.bottom);
        this.setSize(width, height);
        createBuffers();
    }

    @Override
    public void componentShown(ComponentEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseClicked(MouseEvent e) {
        JTextField field = new JTextField("test");
        field.setBounds(new Rectangle(e.getX(), e.getY(), 100, 20));
        this.add(field);
        repaintBuffer1 = true;
    }

    @Override
    public void mouseEntered(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseExited(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mousePressed(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseReleased(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }
}

注意:在Windows上,行为再次不同,解决方法不足。 - Mattijs
我在我的回答中进行了详细阐述。 - trashgod

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接