0

我使用的是 Java JRE 1.6.7,并且有一个 JComponent 和一个 JScrollPane。我无法获得双缓冲来解决这个问题,这总是导致闪烁。如果我使用 Canvas,我会处理缓冲,但是当与 JScrollPane 结合使用时会导致问题。

所以我下载了 JRE 1.6.18,希望能解决其中一个问题。好吧,现在 JScrollPane 中的 JComponent 根本没有正确绘制。它只绘制 JComponent 的外部区域,就好像 JScrollPane 是在它上面绘制一样,除了边框。

这是一个不绘图的代码示例。这会导致应该进行绘图的区域出现 1 像素宽的白色轮廓:

public void paint(Graphics arg0) {



Graphics2D graphics = (Graphics2D) arg0;

  graphics.setColor(Color.WHITE);
  graphics.fillRect(0, 0, (int) getWidth(), (int) getHeight());

任何帮助是极大的赞赏!-克雷格

4

3 回答 3

2

尝试从而paintComponent(Graphics g)不是paint(Graphics g). paintComponent 是您必须为服装绘图覆盖的方法。

你确定你能看到白色的矩形,尝试使用红色或其他你能看到好的东西。

于 2010-02-02T18:36:37.477 回答
2

看起来您正在取得进展,但您可能也希望查看教程示例

Martijn Courteaux 的分析是正确的:你应该覆盖paintComponent(). 此外,混合 AWT 和 Swing 组件也是一个坏主意。这两个想法都在 AWT 和 Swing 中的绘画中进行了讨论。

滚动不应导致闪烁。这是一个滚动组件网格并在背景上绘制棋盘格的示例。

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

public class Scrolling extends JFrame {

    private static final int MAX = 8;
    private static final int SIZE = 480;
    private static final Color light = new Color(0x40C040);
    private static final Color dark  = new Color(0x408040);

    private static class MyPanel extends JPanel {

        public MyPanel() {
            super(true);
            this.setLayout(new GridLayout(MAX, MAX, MAX, MAX));
            this.setPreferredSize(new Dimension(SIZE, SIZE));
            for (int i = 0; i < MAX * MAX; i++) {
                this.add(new JLabel(String.valueOf(i), JLabel.HORIZONTAL));
            }
        }

        @Override
        public void paintComponent(final Graphics g) {
            int w = this.getWidth()/MAX;
            int h = this.getHeight()/MAX;
            for (int row = 0; row < MAX; row++) {
                for (int col = 0; col < MAX; col++) {
                    g.setColor((row + col) % 2 == 0 ? light : dark);
                    g.fillRect(col * w, row * h, w, h);
                }
            }
        }
    }

    public Scrolling() {

        this.setLayout(new BorderLayout());
        final MyPanel panel = new MyPanel();
        final JScrollPane scrollPane = new JScrollPane(panel);
        scrollPane.getHorizontalScrollBar().setUnitIncrement(16);
        scrollPane.getVerticalScrollBar().setUnitIncrement(16);
        this.add(scrollPane, BorderLayout.CENTER);
        this.pack();
        this.setSize(SIZE - SIZE / 3, SIZE - SIZE / 3);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
    }

    public static void main(final String[] args) {

        EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Scrolling().setVisible(true);
            }
        });
    }
}
于 2010-02-03T01:36:51.677 回答
1

好的,我想出了一个简单的答案。而不是打电话

scrollPane.add(containerCanvas);

我打电话

new JScrollPane(containerCanvas);

这在某种意义上是有效的。但是,它现在不允许显示 JScrollPane 栏。我不知道为什么会这样,但目前正在调查它。但至少该组件再次绘制。

于 2010-02-02T19:26:20.087 回答