写一个eclipse程序,画一个长方形并可以用鼠标滚轮和键盘快捷键进行图形放大缩小
时间: 2024-03-12 22:42:57 浏览: 53
鼠标拖放滚轮放大缩小
好的,以下是一个简单实现该功能的Eclipse程序:
```java
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseWheelListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class RectangleDrawing {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
shell.setText("Rectangle Drawing");
// 创建一个画布并在其中绘制长方形
Canvas canvas = new Canvas(shell, SWT.NONE);
canvas.addPaintListener(event -> {
GC gc = event.gc;
gc.setForeground(new Color(display, 255, 0, 0));
gc.drawRectangle(50, 50, 100, 80);
});
// 监听鼠标滚轮事件并缩放画布
canvas.addMouseWheelListener(new MouseWheelListener() {
@Override
public void mouseScrolled(MouseEvent event) {
int zoom = event.count > 0 ? 1 : -1;
canvas.setScale(canvas.getScale() + zoom);
canvas.redraw();
}
});
// 监听键盘事件并缩放画布
canvas.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent event) {
if (event.keyCode == '+') {
canvas.setScale(canvas.getScale() + 1);
canvas.redraw();
} else if (event.keyCode == '-') {
canvas.setScale(canvas.getScale() - 1);
canvas.redraw();
}
}
@Override
public void keyReleased(KeyEvent event) { }
});
// 设置画布的缩放和滚动条
canvas.setScale(1);
canvas.setOrigin(new Point(0, 0));
canvas.setMinSize(500, 400);
canvas.addControlListener(event -> {
Rectangle clientArea = canvas.getClientArea();
canvas.setMinSize(clientArea.width, clientArea.height);
});
shell.setSize(600, 500);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
```
程序中创建了一个画布`Canvas`,使用`GC`对象在其中绘制了一个长方形。同时,监听了鼠标滚轮事件和键盘事件,实现了画布的缩放功能。其中,鼠标滚轮事件通过`Canvas`对象的`setScale`方法实现,键盘事件则根据不同的按键实现缩放的方向。最后,设置了画布的缩放和滚动条的属性,确保画布可以被正确缩放和显示。
阅读全文