2

我正在尝试调整以下示例:http ://docs.oracle.com/javase/tutorial/uiswing/examples/zipfiles/components-ScrollDemoProject.zip

我想做的目的是允许用户在图片上导航到他们自己选择的坐标(但不是通过鼠标)。所以你有一张大图片,只有一小部分显示,图片上的这个窗口移动。这在使用鼠标时有效(参见 oracle 的示例)。但我想用用户选择的坐标来做到这一点。

ScrollablePicture类中可以看到可以通过鼠标拖动来移动图片

public void mouseDragged(MouseEvent e) {
    Rectangle r = new Rectangle(e.getX(), e.getY(), 1, 1);
    scrollRectToVisible(r);
}

我试着做同样的事情,所以我在 mouseDragged 函数下面添加了这个方法

public void moveMap(float X, float Y){

    Rectangle r = new Rectangle((int)X,(int) Y, 1, 1);
    System.err.println("Scroll to "+ r.x);
    scrollRectToVisible(r);
}

当我查看我的输出时,我可以看到我在方法中获得了坐标。但窗口不滚动。我现在的问题是:为什么它不滚动,我该如何解决这个问题?

ps:和价值观无关。因为我在这两个函数中都尝试了固定数字,例如:

Rectangle r = new Rectangle(2000,2000, 1, 1);

它在 mouseDragged 函数中有效,但在 moveMap 函数中无效

4

2 回答 2

3

您的代码工作正常。

以下是测试它的方法:

在课堂ScrollDemo上制作图片public

public ScrollablePicture picture;

createAndShowGUI()将变量的类型更改为JComponent newContentPane

ScrollDemo newContentPane = new ScrollDemo();

frame.setVisible(true);调用您的moveMap方法后:

frame.setVisible(true);
    
newContentPane.picture.moveMap(1, 250);

现在您可以看到图片被向下滚动,因此像素 at(1, 250)是可见的:

在此处输入图像描述

左侧:无moveMap(1, 250);通话。右侧:随叫随到。- 应用程序启动后的那一刻。

于 2011-12-13T15:07:59.607 回答
1

你可以从坐标移动JViewPort,那么你的代码应该是

final JViewport viewport = scrollPane.getViewport();
Rectangle rect = new Rectangle((int)X,(int) Y, 1, 1);
Rectangle r2 = viewport.getVisibleRect();
contentsInTheJScrollPane.scrollRectToVisible(new Rectangle(rect.x, rect.y, 
     (int) r2.getWidth(), (int) r2.getHeight()));
于 2011-12-08T14:42:39.230 回答