开发者

How to prevent flickering when resizing a component in swing?

If I run the following example I get flickering in the right side of the JSplitPane. Is there a way to avoid this?

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
im开发者_如何学运维port javax.swing.*;

public class FlickerTest
{
    int width = 1;

    private void create()
    {
        final JFrame f = new JFrame("JSplitPane");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel p1 = new JPanel();
        p1.setPreferredSize(new Dimension(100, 300));

        JPanel p2 = new JPanel();
        p2.setPreferredSize(new Dimension(0,0));
        p2.setBackground(Color.gray);

        JSplitPane jsp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, p1, p2);
        jsp.setSize(new Dimension(400, 800));

        Timer timer = new Timer(1, new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                width++;

                if (width == 2)
                {
                    try
                    {
                        Thread.sleep(1500);
                    }
                    catch (Exception ex)
                    {
                    }
                }

                int frameWidth = f.getWidth() + width;
                Dimension d    = new Dimension(frameWidth, f.getHeight());
                f.setSize(d);

                if (width > 20)
                {
                    Timer t = (Timer) e.getSource();
                    t.stop();
                }

            }
        });

        f.add(jsp);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
        timer.start();
    }

    public static void main(String[] args) throws Exception
    {
        new FlickerTest().create();
    }
}


Just for notice: flickering while resizing is known problem at Win 7 with Aero: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6898838 http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6873928


Don't use a Thread.sleep() in the Timer. You are prevent the EDT from responding to events and from doing painting.


Does this work for you?

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class FlickerTest
{
    int width = 1;

    private void create()
    {
        final JFrame f = new JFrame("JSplitPane");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel p1 = new JPanel();
        p1.setPreferredSize(new Dimension(100, 300));

        JPanel p2 = new JPanel();
        p2.setPreferredSize(new Dimension(0,0));
        p2.setBackground(Color.gray);

        JSplitPane jsp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, p1, p2);
        jsp.setSize(new Dimension(400, 800));

        Timer timer = new Timer(1, new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                width++;

                int frameWidth = f.getWidth() + width;
                if (width>1502) {
                    frameWidth = f.getWidth() + width - 1500;
                }
                Dimension d    = new Dimension(frameWidth, f.getHeight());
                f.setSize(d);
                if (width > 1520)
                {
                    Timer t = (Timer) e.getSource();
                    t.stop();
                }

            }
        });

        f.add(jsp);
        f.pack();
        //f.setLocationRelativeTo(null);
        f.setVisible(true);
        timer.start();
    }

    public static void main(String[] args) throws Exception
    {
        new FlickerTest().create();
    }
}

BTW - a lot of us do not have monitors 1500(+ to account for the fact that the UI starts in the middle of the screen) pixels wide.


Couple suggestions:

  • Use a delay of 30ms instead of 1ms. 30ms gives you a smooth 30 frames per second, which is plenty.
  • Use setBounds instead of setSize. Not sure if this makes a difference, but gives more control over the coordinates.
  • Instead of calling sleep() in your Timer, set an initial delay on the timer
  • Take out call to setPreferredSize(0, 0)

public static class FlickerTest {

    int width = 1;

    private void create() {
        final JFrame f = new JFrame("JSplitPane");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel p1 = new JPanel();
        p1.setPreferredSize(new Dimension(100, 300));

        JPanel p2 = new JPanel();
        p2.setBackground(Color.gray);

        JSplitPane jsp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, p1, p2);
        jsp.setSize(new Dimension(400, 800));

        Timer timer = new Timer(30, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                width++;


                int frameWidth = f.getWidth() + width;
                Dimension d = new Dimension(frameWidth, f.getHeight());
                f.setBounds(f.getX(), f.getY(), frameWidth, f.getHeight());
                //f.setSize(frameWidth, f.getHeight());

                if (width > 20) {
                    Timer t = (Timer) e.getSource();
                    t.stop();
                }

            }
        });

        f.add(jsp);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
        timer.setInitialDelay(1500);
        timer.start();
    }

}


This trick improves repaint rate in Win7+Aero: setting resizable to null, and providing own resize hook. Its aint perfect, but still alot better.. check my example:

How to prevent flickering when resizing a component in swing?

import java.awt.event.*;
import java.awt.*;
import javax.swing.event.*;
import javax.swing.*;

class ResizeHookDemo extends JDialog {
  private final static int width = 580, height = 350;
  private final JFileChooser fc;
  private java.awt.geom.GeneralPath gp;

  public ResizeHookDemo() {
    super((JDialog)null, "Choose File", true);

    fc = new JFileChooser() {

     @Override
     public void paint(Graphics g) {
       super.paint(g);
       int w = getWidth();
       int h = getHeight();
       g.setColor(new Color(150, 150, 150, 200));
       g.drawLine(w-7, h, w, h-7);
       g.drawLine(w-11, h, w, h-11);
       g.drawLine(w-15, h, w, h-15);

       gp = new java.awt.geom.GeneralPath();      
       gp.moveTo(w-17, h);
       gp.lineTo(w, h-17);
       gp.lineTo(w, h);
       gp.closePath();
     }

    };
    fc.addActionListener(new ActionListener() {

      public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals("CancelSelection")) {
          setVisible(false);
          // action...
        }
        else if (e.getActionCommand().equals("ApproveSelection")) {
          setVisible(false);
          // action...
        }
      }
    });

    MouseInputListener resizeHook = new MouseInputAdapter() {
      private Point startPos = null;

      public void mousePressed(MouseEvent e) {
        if (gp.contains(e.getPoint())) 
          startPos = new Point(getWidth()-e.getX(), getHeight()-e.getY());
      }

      public void mouseReleased(MouseEvent mouseEvent) {
        startPos = null;
      }

      public void mouseMoved(MouseEvent e) {
        if (gp.contains(e.getPoint()))
          setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR));
        else
          setCursor(Cursor.getDefaultCursor());
      }

      public void mouseDragged(MouseEvent e) {
        if (startPos != null) {

          int dx = e.getX() + startPos.x;
          int dy = e.getY() + startPos.y;

          setSize(dx, dy);
          repaint();
        }
      }         
    };

    fc.addMouseMotionListener(resizeHook);
    fc.addMouseListener(resizeHook);
    fc.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 20));
    add(fc);

    setResizable(false);

    setMinimumSize(new Dimension(width, height));
    setDefaultCloseOperation(HIDE_ON_CLOSE);
    setLocationRelativeTo(null);
  }

  public static void main(String args[]) {
    System.out.println("Starting demo...");
    SwingUtilities.invokeLater(new Runnable() {

      @Override
      public void run() {
        new ResizeHookDemo().setVisible(true);
      }
    });
  }
}


For me turning noerasebackround to true worked:

System.setProperty("sun.awt.noerasebackground", "true");


Sorry about that - I dashed off my answer without much thought. Yes, update should not be used in Swing.

To make amends, I found this blog post by an OS X Swing guy who writes in the 2nd paragraph, "Programmatic resizing currently causes flickering in Java on the Mac."

http://explodingpixels.wordpress.com/2008/09/28/the-heads-up-display-hud/

Since your code doesn't cause flicker when I run it (on an old XP machine here at work) it seems the above is still true.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜