Kimia
Kimia

Reputation: 11

Java Adding JScrollPane to JComponent

Java: I have a JComponent that draws an image which can be rescaled. I need to have scroll bars that will appear when the image becomes large. I passed the JComponent to a JScrollPane and then added the JScrollPane to the north section of my JFrame, but the scroll bars only appeared when the JFrame is resized not when the image is rescaled. I also set the preferred size of the JComponent but it didn't work.

I tried adding the JComponent to a JPanel first then passing the JPanel to the JScrollPane but that didn't work either.

Here is a portion of my code inside the constructor of the JFrame:

JComponent component = new JComponent() {
    public void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
            g2.drawImage(image1, zoom, this);
    }
};

component.setPreferredSize(new Dimension(800, 600));
JScrollPane scroller = new JScrollPane(component);
add(scroller, BorderLayout.CENTER);

Upvotes: 1

Views: 486

Answers (1)

mKorbel
mKorbel

Reputation: 109815

  1. override getPreferredScrollableViewportSize for JScrollPane

  2. override getPreferredSize instead of component.setPreferredSize(new Dimension(800, 600));

  3. Dimension that returns JPanel must be larger that Dimension from JViewport (visible Rectangle from JScrollPane), otheriwse JScrollBar(s) is/are not visible

  4. for better help sooner, post an SSCCE, short, runnable, compilable, JFrame with JComponent inside JScrollPane

  5. add super.paintComponent(g); as 1st. code line inside paintComponent, coordinates for zoom_in/out to take from getHeight/Weight (see point 2nd. about getPreferredSize)

Upvotes: 2

Related Questions