简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM