简体   繁体   English

在 JPanel 内滚动 JFrame

[英]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.我发现如果多边形具有负坐标值,它们只是 go 离开屏幕,我无法看到它们的整体。 To this I imagine some sort of scrolling or zooming to the JFrame created inside the main, or maybe to the content pane.为此,我想象某种滚动或缩放到在主内部创建的 JFrame,或者可能到内容窗格。 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我发现如果多边形具有负坐标值,它们只是 go 离开屏幕

You can't use a JScrollPane with negative values.您不能使用具有负值的 JScrollPane。

Instead you need to:相反,您需要:

  1. Create all the Polygons you want to paint and add them to an ArrayList.创建所有要绘制的多边形并将它们添加到 ArrayList。
  2. Iterate through the ArrayList to find the largest negative x/y value of all the Polygons遍历 ArrayList 以找到所有多边形的最大负 x/y 值
  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如果您找到负的“x”或“y”坐标,则再次遍历 ArrayList 并通过 x 或 y 坐标的绝对值调用translate(...)方法以将面板上的所有多边形移动到它们都将可见
  4. Finally you iterate through the ArrayList and draw each Polygon.最后,您遍历 ArrayList 并绘制每个多边形。

Note.笔记。 ideally you would create the Polygons and add then do the ArrayList outside of the paintComponent() method.理想情况下,您将创建多边形并添加,然后在 paintComponent() 方法之外执行 ArrayList。 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.所以现在 paintComponent() 方法只需要迭代 ArrayList 并绘制它们,而无需在每次组件需要重新绘制自身时进行创建/翻译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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