Creating a huge panel inside ScrollPane via Java

My problem is that I want to draw a huge panel, but it cannot be seen in a small size frame, so I have to use ScrollPane, and I used it.

But with the help of scrolling, collisions occur, so I do not see any panel there. I just want to fix it.

Please look at my code and run it and help solve the problem.

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

public class Swing{
    JFrame frame;
    Panel panel;
    public static void main(String [] args){
        Swing a  = new Swing();
        a.go();
    }
    public void go(){
        frame  = new JFrame();
        panel = new Panel();
        panel.setPreferredSize(new Dimension(5000, 5000));
        JScrollPane scroll = new JScrollPane(panel);
        frame.add(scroll);
        frame.pack();
        frame.setVisible(true);
    }

    class Panel extends JPanel{
        public void paintComponent(Graphics g){
            Graphics2D a = (Graphics2D)g;
            a.setColor(Color.RED);
            a.drawLine(50, 50, 5000, 5000);
        }
    }
}

Thanks in advance!

+4
source share
1 answer

Always make a call super.paintComponent(g);to redraw the rest of the component. Otherwise, these types of artifacts are visible.

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

public class Swing{
    JFrame frame;
    Panel panel;
    public static void main(String [] args){
        Swing a  = new Swing();
        a.go();
    }
    public void go(){
        frame  = new JFrame();
        panel = new Panel();
        panel.setPreferredSize(new Dimension(5000, 5000));
        JScrollPane scroll = new JScrollPane(panel);
        frame.add(scroll);
        frame.pack();
        frame.setVisible(true);
    }

    class Panel extends JPanel{
        public void paintComponent(Graphics g){
            super.paintComponent(g);  // VERY IMPORTANT!
            Graphics2D a = (Graphics2D)g;
            a.setColor(Color.RED);
            a.drawLine(50, 50, 5000, 5000);
        }
    }
}
+6
source

All Articles