4

我编写了这个简单的程序,它显示按键,绘制短语“Hello World”,其中一个光标移动(单​​击时带有轨迹模式),并且还循环选择“Hello World”的颜色,当鼠标滚轮滚动。但是这样做有一个问题:当鼠标滚轮滚动时,整个窗口变为空白(显示从您第一次使组件可见时的默认灰色),然后将随着颜色的变化而重新绘制(仅对“Hello World”似乎不需要重绘整个框架。

出现空白的时间似乎与滚动鼠标滚轮的力相关,如果我轻轻滚动,只有很小的一瞬间没有显示所有内容,但是非常用力滚动会使窗口变为空白2-3 秒。

我试过双缓冲——认为这可能是某种屏幕闪烁——但它没有改变,我不知道是什么导致了这种奇怪的效果。就好像在 Wheel 运动事件发生时正在加载帧图像。(有没有办法立即退出轮子事件以减少加载时间?(这只是我对可能解决方案的猜测))。

代码如下。任何想法将不胜感激。

package keymouse;

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferStrategy;
    import java.util.LinkedList;
    import javax.swing.JFrame;

    public class KeyMouse implements KeyListener,
            MouseMotionListener, MouseListener, MouseWheelListener, Runnable {

        boolean trailMode = false;
        boolean exists = false;
        display window;
        LinkedList wordList;
        LinkedList trailList;
        LinkedList colorList;
        Point mousePoint;
        int TRAIL_SIZE = 10;
        boolean init = true;
        int FONT_SIZE = 32;
        int mouseY;
        int mouseX;
        int y;
        int colorCount = 0;

        public static void main(String[] args) {
            KeyMouse k = new KeyMouse();
            k.run();
        }

        public KeyMouse() {
            window = new display();
            window.addKeyListener(this);
            window.addMouseMotionListener(this);
            window.addMouseListener(this);
            window.addMouseWheelListener(this);
            window.setBackground(Color.WHITE);
            window.setForeground(Color.BLACK);
            wordList = new LinkedList();
            trailList = new LinkedList();
            colorList = new LinkedList();
            colorList.add(Color.BLACK);
            colorList.add(Color.BLUE);
            colorList.add(Color.YELLOW);
            colorList.add(Color.GREEN);
            colorList.add(Color.PINK);

        }

        @Override
        public void keyTyped(KeyEvent e) {
            // do nothing
        }

        @Override
        public void keyPressed(KeyEvent e) {
            int keyCode;
            if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
                stop();
            }

            keyCode = e.getKeyCode();
            addMessage("Pressed:" + e.getKeyText(keyCode));
        }

        @Override
        public void keyReleased(KeyEvent e) {
            //do nothing
        }

        @Override
        public void mouseDragged(MouseEvent e) {
            Point p = new Point(e.getX(), e.getY());
            addLocation(p);
        }

        @Override
        public void mouseMoved(MouseEvent e) {
            Point p = new Point(e.getX(), e.getY());
            addLocation(p);
        }

        @Override
        public void mouseClicked(MouseEvent e) {
        }

        @Override
        public void mousePressed(MouseEvent e) {
            trailMode = true;

        }

        @Override
        public void mouseReleased(MouseEvent e) {
            trailMode = false;
        }

        @Override
        public void mouseEntered(MouseEvent e) {
            //do nothing
        }

        @Override
        public void mouseExited(MouseEvent e) {
            //do nothing
        }

        @Override
        public void mouseWheelMoved(MouseWheelEvent e) {


            System.out.println(e.getWheelRotation());
            colorCount++;
            if (colorCount > 4) {
                colorCount = 0;
            }


            window.setForeground((Color) colorList.get(colorCount));

        }

        @Override
        public void run() {
            window.createBufferStrategy(2);
            BufferStrategy strategy = window.getBufferStrategy();

            while (true) {
                draw(strategy.getDrawGraphics());
                strategy.show();
                try {
                    Thread.sleep(20);
                } catch (Exception ex) {
                }
            }
        }

        public void draw(Graphics g) {
            //draw background

            g.setColor(window.getBackground());
            g.fillRect(0, 0, window.getWidth(), window.getHeight());

            //draw Text
            g.setColor(window.getForeground());
            g.setFont(new Font("sansserif", Font.BOLD, 32));

            int count = trailList.size();
            if (trailList.size() > 1 && trailMode == false) {
                count = 1;
            }

            if (exists == true) {
                for (int i = 0; i < count; i++) {
                    Point p = (Point) trailList.get(i);
                    g.drawString("Hello World", p.x, p.y);
                }
            }

            g.setColor(Color.BLACK);
            y = 56;
            for (int i = 0; i < wordList.size(); i++) {
                String word = (String) wordList.get(i);
                g.drawString((String) wordList.get(i), 100, y);
                y += 32;
            }


        }

        public void addMessage(String message) {
            if (y >= window.getHeight()) {
                wordList.remove(0);
            }
            wordList.add(message);
        }

        public void addLocation(Point h) {
            exists = true;
            trailList.addFirst(h);
            if (trailList.size() > TRAIL_SIZE) {
                trailList.removeLast();

            }
        }

        public void printMessages() {
            for (int i = 0; i < wordList.size(); i++) {
                System.out.println(wordList.get(i));
            }
        }

        private void stop() {
            System.exit(0);
        }
4

1 回答 1

3

没有完整的例子,我无法重现你描述的效果。您可以将您的代码与此示例进行比较,该示例没有显示明显的空白。

一般来说,

  • JPanel默认情况下是双缓冲的;需要不同的缓冲策略是不寻常的。
  • AnimationTest说明 SwingTimer以及如何显示平均绘制周期。
  • MouseAdapter方便覆盖少量方法。
  • 如果可能,请使用泛型参数以确保类型安全。

ColorWheel 图像

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseWheelEvent;
import java.util.LinkedList;
import java.util.Queue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
* @see https://stackoverflow.com/a/10970892/230513
*/
public class ColorWheel extends JPanel {

    private static final int N = 32;
    private final Queue<Color> clut = new LinkedList<Color>();
    private final JLabel label = new JLabel();

    public ColorWheel() {
        for (int i = 0; i < N; i++) {
            clut.add(Color.getHSBColor((float) i / N, 1, 1));
        }
        this.setBackground(clut.peek());
        label.setText(getBackground().toString());
        this.add(label);
        this.addMouseWheelListener(new MouseAdapter() {

            @Override
            public void mouseWheelMoved(MouseWheelEvent e) {
                setBackground(clut.peek());
                label.setText(getBackground().toString());
                clut.add(clut.remove());
            }
        });
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(320, 240);
    }

    private void display() {
        JFrame f = new JFrame("ColorWheel");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(this);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

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

            @Override
            public void run() {
                new ColorWheel().display();
            }
        });
    }
}
于 2012-06-10T17:46:10.910 回答