简体   繁体   中英

Scrolling a JFrame inside a JPanel

I used this example to draw polygons as base to make my own polygon drawer, but kept the most important part:

public class Main extends JPanel {

public void paintComponent(Graphics g) {
    super.paintComponent(g);

    // polygon maker
}

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setTitle("DrawPoly");
    frame.setSize(1000, 1000);
    frame.setLocationRelativeTo(null);
    frame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });
    Container contentPane = frame.getContentPane();
    contentPane.add(new Main());
    frame.show();
}
}

I discovered that if the polygons have negative coordinate values, they just go off the screen and I'm unable to see them whole. To this I imagine some sort of scrolling or zooming to the JFrame created inside the main, or maybe to the content pane. How do I implement a simple scroll, using the linked code as base?

I discovered that if the polygons have negative coordinate values, they just go off the screen

You can't use a JScrollPane with negative values.

Instead you need to:

  1. Create all the Polygons you want to paint and add them to an ArrayList.
  2. Iterate through the ArrayList to find the largest negative x/y value of all the Polygons
  3. If you find a negative "x" or "y" coordinate then you iterate through the ArrayList again and invoke the translate(...) method by the absolute value of the x or y coordinate to shift all the Polygons on the panel to they will all be visible
  4. Finally you iterate through the ArrayList and draw each Polygon.

Note. ideally you would create the Polygons and add then do the ArrayList outside of the paintComponent() method. Then do the translate. So now the paintComponent() method only needs to iterate the ArrayList and paint them without doing the creation/translate each time the component needs to repaint itself.

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