在JScrollPane内的JPanel上绘画不会在正确的位置绘画

时间:2014-05-31 19:35:20

标签: java swing jpanel jscrollpane draw

所以我有JPanelJScrollPane内。 现在我想在面板上画一些东西,但它总是在同一个地方。 我可以向各个方向滚动,但它不会移动。无论我在面板上绘制什么,都不会滚动。

我已经尝试过:

  1. 自定义JViewPort
  2. 在Opaque = true和Opaque = false
  3. 之间切换

    此外,我考虑覆盖面板的paintComponent方法,但在我的代码中实现起来非常困难。

    public class ScrollPanePaint{
    
    public ScrollPanePaint() {
        JFrame frame = new JFrame();
        final JPanel panel = new JPanel();
        panel.setPreferredSize(new Dimension(1000, 1000));
        //I tried both true and false
        panel.setOpaque(false);
        JScrollPane scrollPane = new JScrollPane(panel);
        frame.add(scrollPane);
        frame.setSize(200, 200);
        frame.setVisible(true);
        //To redraw the drawing constantly because that wat is happening in my code aswell because
        //I am creating an animation by constantly move an image by a little
        new Thread(new Runnable(){
            public void run(){
                Graphics g = panel.getGraphics();
                g.setColor(Color.blue);
                while(true){
                    g.fillRect(64, 64, 3 * 64, 3 * 64);
                    panel.repaint();
                }
            }
        }).start();
    }
    
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
    
            @Override
            public void run() {
                new ScrollPanePaint();
            }
        });
    }
    

    }

    我犯的错误可能很容易解决,但我无法弄清楚如何。

1 个答案:

答案 0 :(得分:4)

如何在paintComponent()上实施JPanel

覆盖getPreferredSize()方法,而不是使用setPreferredSize()

final JPanel panel = new JPanel(){
    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        // your custom painting code here
    }

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

有些观点:

  1. 覆盖JComponent#getPreferredSize()而非使用setPreferredSize()

    了解更多Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?

  2. 使用更适合Swing应用程序的Swing Timer代替Java Timer

    了解更多How to Use Swing Timers

  3. 使用UIManager.setLookAndFeel()

    设置默认外观

    了解更多How to Set the Look and Feel

  4. How to fix animation lags in Java?