3

我的组件比屏幕大,它的一部分没有显示(我将使用滚动条)。
当我接到一个电话时,paintComponent(g)我怎么知道我应该画什么区域?

4

3 回答 3

1

您可以通过查询对象的剪辑边界来找出实际必须绘制的区域Graphics

对于这种方法,JavaDoc 似乎有点过时了:它说它可能会返回一个null剪辑。然而,这显然不是这种情况(并且其他 Swing 类也依赖于剪辑从不存在null!)。

以下MCVE说明了使用剪辑或绘制整个组件之间的区别:

剪辑演示

它包含一个JPanel大小为 800x800 的滚动窗格。面板绘制一组矩形,并打印已绘制的矩形数量。

可以使用“使用剪辑边界”复选框来启用和禁用剪辑。使用剪辑时,仅重绘面板的可见区域,矩形的数量要少得多。(注意这里测试一个矩形是否必须被绘制比较简单:它只执行矩形与可见区域的相交测试。对于实际应用程序,可以直接使用剪辑边界来找出哪些矩形必须画)。

这个例子还展示了滚动窗格的一些棘手的内部结构:当闪烁关闭并且滚动条被移动时,人们可以看到——尽管整个可见区域发生了变化——实际上只有一个很小的区域需要重新绘制(即由于滚动而变得可见的区域)。另一部分简单地按原样移动,通过 blitting 先前的内容。可以使用JViewport.html#setScrollMode修改此行为。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class PaintRegionTest
{
    public static void main(String[] args) throws Exception
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final PaintRegionPanel paintRegionPanel = new PaintRegionPanel();
        paintRegionPanel.setPreferredSize(new Dimension(800, 800));

        final Timer timer = new Timer(1000, new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                paintRegionPanel.changeColor();
            }
        });
        timer.setInitialDelay(1000);
        timer.start();

        JScrollPane scrollPane = new JScrollPane(paintRegionPanel);
        frame.getContentPane().setLayout(new BorderLayout());
        frame.getContentPane().add(scrollPane, BorderLayout.CENTER);

        JPanel controlPanel = new JPanel(new FlowLayout());

        final JCheckBox blinkCheckbox = new JCheckBox("Blink", true);
        blinkCheckbox.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                if (blinkCheckbox.isSelected())
                {
                    timer.start();
                }
                else
                {
                    timer.stop();
                }
            }
        });
        controlPanel.add(blinkCheckbox);


        final JCheckBox useClipCheckbox = new JCheckBox("Use clip bounds");
        useClipCheckbox.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                paintRegionPanel.setUseClipBounds(
                    useClipCheckbox.isSelected());
            }
        });
        controlPanel.add(useClipCheckbox);

        frame.getContentPane().add(controlPanel, BorderLayout.SOUTH);

        frame.setPreferredSize(new Dimension(400, 400));
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

class PaintRegionPanel extends JPanel
{
    private Color color = Color.BLACK;
    private boolean useClipBounds = false;

    void setUseClipBounds(boolean useClipBounds)
    {
        this.useClipBounds = useClipBounds; 
    }

    void changeColor()
    {
        if (color == Color.BLACK)
        {
            color = Color.RED;
        }
        else
        {
            color = Color.BLACK;
        }
        repaint();
    }

    @Override
    protected void paintComponent(Graphics gr)
    {
        super.paintComponent(gr);
        Graphics2D g = (Graphics2D)gr;

        g.setColor(color);

        Rectangle clipBounds = g.getClipBounds();
        Rectangle ownBounds = new Rectangle(0,0,getWidth(),getHeight());

        System.out.println("clipBounds: " + clipBounds);
        System.out.println(" ownBounds: " + ownBounds);

        Rectangle paintedRegion = null;
        if (useClipBounds)
        {
            System.out.println("Using clipBounds");
            paintedRegion = clipBounds;
        }
        else
        {
            System.out.println("Using ownBounds");
            paintedRegion = ownBounds;
        }

        int counter = 0;

        // This loop performs a a simple test see whether the objects 
        // have to be painted. In a real application, one would 
        // probably use the clip information to ONLY create the
        // rectangles that actually have to be painted:
        for (int x = 0; x < getWidth(); x += 20)
        {
            for (int y = 0; y < getHeight(); y += 20)
            {
                Rectangle r = new Rectangle(x + 5, y + 5, 10, 10);
                if (r.intersects(paintedRegion))
                {
                    g.fill(r);
                    counter++;
                }
            }
        }
        System.out.println("Painted "+counter+" rectangles ");
    }

}

顺便说一句:对于许多应用案例,几乎不需要这样的“优化”。无论如何,绘制的元素与剪辑相交,因此可能不会获得太多性能。当“准备”要绘制的元素在计算上很昂贵时,可以将其视为一种选择。(在示例中,“准备”是指创建Rectangle实例,但可能有更复杂的模式)。但在这些情况下,可能还有比手动检查剪辑边界更优雅、更简单的解决方案。

于 2014-08-15T19:43:42.983 回答
1

我不确定这是否是您的意思,但问题是您每次接到电话repaint()时都必须拨打电话,否则更新将在.JScrollPanepaintComponent(Graphics g)JPanelJPanelJScrollPane

我还看到您想使用JScrollBar(或者您可能混淆了术语)?我推荐一个JScrollPane

我做了一个小例子,它JPanel有一个网格,每 2 秒改变一次颜色(从红色变为黑色,反之亦然)。/ JPanelGrid 大于JScrollPane; 无论我们必须调用实例repaint()JScrollPane否则网格不会改变颜色:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class Test {

    public static void main(String[] args) throws Exception {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new Test().createAndShowUI();
            }
        });
    }

    private void createAndShowUI() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        initComponents(frame);
        frame.setPreferredSize(new Dimension(400, 400));
        frame.pack();
        frame.setVisible(true);
    }

    private void initComponents(JFrame frame) {
        JScrollPane jsp = new JScrollPane();
        jsp.setViewportView(new Panel(800, 800, jsp));
        frame.getContentPane().add(jsp);
    }
}

class Panel extends JPanel {

    private int across, down;
    private Panel.Tile[][] tiles;
    private Color color = Color.black;
    private final JScrollPane jScrollPane;

    public Panel(int width, int height, JScrollPane jScrollPane) {
        this.setPreferredSize(new Dimension(width, height));
        this.jScrollPane = jScrollPane;
        createTiles();
        changePanelColorTimer();//just something to do to check if its repaints fine
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (int i = 0; i < across; i++) {
            for (int j = 0; j < down; j++) {
                g.setColor(color);
                for (int k = 0; k < 5; k++) {
                    g.drawRect(tiles[i][j].x + k, tiles[i][j].y + k, tiles[i][j].side - k * 2, tiles[i][j].side - 2 * k);
                }
            }
        }
        updateScrollPane();//refresh the pane after every paint
    }

    //calls repaint on the scrollPane instance
    private void updateScrollPane() {
        jScrollPane.repaint();
    }

    private void createTiles() {
        across = 13;
        down = 9;
        tiles = new Panel.Tile[across][down];

        for (int i = 0; i < across; i++) {
            for (int j = 0; j < down; j++) {
                tiles[i][j] = new Panel.Tile((i * 50), (j * 50), 50);
            }
        }
    }

    //change the color of the grid lines from black to red and vice versa every 2s
    private void changePanelColorTimer() {
        Timer timer = new Timer(2000, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (color == Color.black) {
                    color = Color.red;
                } else {
                    color = Color.black;
                }
            }
        });
        timer.setInitialDelay(2000);
        timer.start();
    }

    private class Tile {

        int x, y, side;

        public Tile(int inX, int inY, int inSide) {
            x = inX;
            y = inY;
            side = inSide;
        }
    }
}

Panel课堂上,如果我们评论该行updateScrollPane();paintComponent(Graphics g)我们不会看到网格改变颜色。

于 2012-09-29T15:55:49.583 回答
0

所有的答案都是错误的。所以我决定回答这个问题,尽管这个问题已经有两年了。

我相信正确的答案是在方法g.getClipBounds()内部调用paintComponent(Graphics g)。它将返回控件坐标系中无效且必须重绘的区域的矩形。

于 2014-08-15T18:34:11.667 回答