Painting on a JPanel inside a JScrollPane doesn't paint in the right location

断了今生、忘了曾经 提交于 2019-12-13 01:24:10

问题


So I have a JPanel that's inside a JScrollPane. Now I am trying to paint something on the panel, but it's always in same spot. I can scroll in all directions but it's not moving. Whatever I paint on the panel does not get scrolled.

I already tried:

  1. A custom JViewPort
  2. switching between Opaque = true and Opaque = false

Also I considered overriding the paintComponent method of the panel but that would be really hard to implement in my code.

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();
        }
    });
}

}

The mistake I make is probably very easy to fix, but I just can't figure out how.


回答1:


How to implement the paintComponent() on JPanel?

Override getPreferredSize() method instead of using 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);
    }
};

Some points:

  1. Override JComponent#getPreferredSize() instead of using setPreferredSize()

    Read more Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?

  2. Use Swing Timer instead of Java Timer that is more suitable for Swing application.

    Read more How to Use Swing Timers

  3. Set default look and feel using UIManager.setLookAndFeel()

    Read more How to Set the Look and Feel

  4. How to fix animation lags in Java?



来源:https://stackoverflow.com/questions/23974009/painting-on-a-jpanel-inside-a-jscrollpane-doesnt-paint-in-the-right-location

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!