【问题标题】:Painting on a JPanel inside a JScrollPane doesn't paint in the right location在 JScrollPane 内的 JPanel 上绘画不会在正确的位置绘画
【发布时间】:2014-05-31 19:35:19
【问题描述】:

所以我有一个JPanel,它位于JScrollPane 中。 现在我想在面板上画一些东西,但它总是在同一个地方。 我可以向各个方向滚动,但它不动。我在面板上绘制的任何内容都不会滚动。

我已经试过了:

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

我还考虑过覆盖面板的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();
        }
    });
}

}

我犯的错误可能很容易改正,但我就是不知道怎么改。

【问题讨论】:

  • 为什么很难在JPanel上实现paintComponent()方法?
  • 因为我所有的绘图代码都必须在 JPanels paintComponent 方法中。我需要从其他子程序中借鉴它。就像我在 JPanel 上绘制实体的实体类一样,不能在 paintComponent 方法中。或者我可能做的事情真的很傻。

标签: java swing jpanel jscrollpane draw


【解决方案1】:

如何在JPanel上实现paintComponent()

覆盖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 Timer 代替Java Timer 更适合Swing 应用程序。

    阅读更多How to Use Swing Timers

  3. 使用UIManager.setLookAndFeel()设置默认外观

    阅读更多How to Set the Look and Feel

  4. How to fix animation lags in Java?

【讨论】:

  • 仍在寻找如何在我的游戏中实现此代码,但它确实可以满足我的需求。谢谢:)
  • 如此有用的链接也是如此。再次感谢您。
  • 听起来不错。欢迎您。如果问题得到解决,请不要忘记关闭线程。
  • 通过点击答案中的绿色右标记。 :) 以2 minute tour of StackOverflow.
  • 我只是想再次感谢您。我终于找到了实现此代码的方法。它最终按预期工作。太感谢了!! :)。
猜你喜欢
  • 2014-02-03
  • 2013-06-22
  • 1970-01-01
  • 1970-01-01
  • 2011-07-16
  • 2017-01-13
  • 1970-01-01
  • 2021-10-28
相关资源
最近更新 更多