Home > Back-end >  How can I create a JPanel larger than the size of the display
How can I create a JPanel larger than the size of the display

Time:10-07

I am trying to create a JPanel to draw on where the drawing area is larger than the display size. I was expecting a JPanel with a scrollpane to appear, to account for the huge size. I cannot seem to get that to work. I see a scrollbar on the bottom, with a left arrow but not a right, and no scrollbar on the right side of the screen. I put this example together from code I found in other examples. It is complete but ugly. What do I need to change to get what I want - an area to draw on that can be scrolled up-down-left-right? --- all the drawing by program, no user interaction.

package com.example.paneltest;
 
import java.awt.*;
import java.util.Random;
import javax.swing.*;

public class Paneltest {
  private static void createAndShowGUI() {
    JFrame frame = new JFrame("JPanel Test");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setExtendedState(JFrame.MAXIMIZED_BOTH); 
    
    Toolkit tk = Toolkit.getDefaultToolkit();
    int frameWidth = tk.getScreenSize().width;
    int frameHeight = tk.getScreenSize().height;
 
    JPanel redPanel = new paintablePanel();
    redPanel.setOpaque(true);
    redPanel.setBackground(new Color(128, 0, 0));
    redPanel.setPreferredSize(new Dimension(6000,6000));
    frame.getContentPane().add(new JScrollPane(redPanel), BorderLayout.WEST);
    //frame.pack();
    frame.setVisible(true);
 }
public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
            }
        });
    }
}
class paintablePanel extends JPanel {
  private void doDrawing(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    g2d.setPaint(Color.white);
    int w = 6000;
    int h = 6000;
    Random r = new Random();
    for (int i = 0; i < 10000; i  ) {
        int x = Math.abs(r.nextInt()) % w;
        int y = Math.abs(r.nextInt()) % h;
        g2d.drawLine(x, y, x, y);
    }
}
@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    doDrawing(g);
    }
}

CodePudding user response:

Change:

//frame.getContentPane().add(new JScrollPane(redPanel), BorderLayout.WEST);
frame.getContentPane().add(new JScrollPane(redPanel), BorderLayout.CENTER);

This will add the scroll pane to the CENTER of the BorderLayout. This will allow the scroll pane to take all the available space in the frame. Then the scrollbars will appear for the part of the panel that can't be displayed within the bounds of the scroll pane.

When you add the scroll pane to the WEST, it will attempt to respect the preferred width of the scroll pane, which is greater than the width of your desktop and appears to be causing the issue.

  • Related