user3148422
user3148422

Reputation: 73

Drawing a Huge Panel inside a ScrollPane through Java

My problem is I want to draw a huge Panel but its not possible to see this panel in a small size frame so i supposed to use ScrollPane and I used it..

But by scrolling clashes occurs so i cant see any panel there .i just want to fix it

Please anyone see my code and run it and help to 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!

Upvotes: 4

Views: 1241

Answers (1)

Andrew Thompson
Andrew Thompson

Reputation: 168825

Always make sure to call super.paintComponent(g); to redraw the rest of the component. Otherwise these types of painting artifacts are seen.

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

Upvotes: 6

Related Questions