Java: JScrollPane not working with GridBagLayout

In my Java application, I am writing a component that is used to view PDF files. I had a pretty realistic implementation where a user could click on and drag a PDF file to view areas that did not fit on the screen. But my boss didn’t like it, so now I have to use the scroll bars. So I did the obvious thing and just put it in JScrollPane, but almost regardless of what I do, it refuses to work.

The PDF is simply converted to BufferedImage, and then I convert it to ImageIcon, so I can add it to JLabel, which is added to JScrollPane.

I have a PDFViewer class that subclasses JScrollPane and important code here:

private void drawPDF() {
    PDFRenderer renderer = new PDFDrawer(pdfFile);
    BufferedImage image = renderer.makeImage(page);
    JLabel img = new JLabel(new ImageIcon(image));
    this.setViewportView(img);
}

Now I have a separate class, which is subclasses of JFrame, which I need to add to my PDFViewer. It works until I use the layout and add the PDFViewer directly to the JFrame. If I even just add a JScrollPane to the JPanel and then add the JPanel to the JFrame, the scroll bars disappear and it looks like I just added JLabel directly. The image is too large for this and it is easy to crop.
I also need to add some controls to the frame, so I installed a really basic GridBagLayout with PDFViewer as the only component to add. And with the following code, I get a window that looks like this.

GridBagLayout glayout = new GridBagLayout();
GridBagConstraints c;
setLayout(glayout);
PDFViewer viewer = new PDFViewer("foo.pdf");
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.gridheight = 1;
c.gridwidth = 1;
add(viewer, c);
setVisible(true);

JScrollPane , JFrame? , GridLayout, GridLayout - , .

+3
5

GridBagLayout , weightx/y .

c.weightx = 1;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;

, , . GridBagLayout .

+7

:

c.fill = GridBagConstraints.BOTH;

. , , BorderLayout BorderLayout.CENTER.

+1
c.weightx = 1.0;
c.weighty = 1.0;
c.fill = GridBagConstraints.BOTH;

viewer.

+1

(), minimumSize() maximumSize() , JScrollpane. , ,

c.weightx = 1;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;

GridBagConstraints.

+1

prefferedsize (setPrefferedSize()) , ScrollPane.

-1

Source: https://habr.com/ru/post/1775866/


All Articles