java画矩形

要像WINDOWS选定框一样,鼠标拖动时有一个矩形框,鼠标released时填满矩形框.只要告诉我那几个event怎么写就行了.... 要像WINDOWS选定框一样,鼠标拖动时有一个矩形框,鼠标released时填满矩形框.
只要告诉我那几个event怎么写就行了.
展开
 我来答
Irreappearable
推荐于2018-04-11 · TA获得超过4956个赞
知道大有可为答主
回答量:1423
采纳率:25%
帮助的人:3122万
展开全部
直接说event是简单,不过总要试一试才敢拿上来讲,所以就全写上来了。。。

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.event.MouseInputAdapter;
import javax.swing.event.MouseInputListener;

public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new PaintingPanel());
frame.setBounds(100, 100, 400, 400);
frame.setVisible(true);
}
}

class PaintingPanel extends JPanel {

ArrayList<Rectangle> list;
Rectangle current;

public PaintingPanel() {
list = new ArrayList<Rectangle>();
addMouseMotionListener(mouseHandler);
addMouseListener(mouseHandler);
}

MouseInputListener mouseHandler = new MouseInputAdapter() {
Point startPoint;

public void mousePressed(MouseEvent e) {
startPoint = e.getPoint();
current = new Rectangle();
}

public void mouseReleased(MouseEvent e) {
makeRectangle(startPoint, e.getPoint());
if (current.width > 0 && current.height > 0) {
list.add(current);
current = null;
repaint();
}
}

public void mouseDragged(MouseEvent e) {
if (current != null) {
makeRectangle(startPoint, e.getPoint());
repaint();
}
}

private void makeRectangle(Point p1, Point p2) {
int x = Math.min(p1.x, p2.x);
int y = Math.min(p1.y, p2.y);
int w = Math.abs(p1.x - p2.x);
int h = Math.abs(p1.y - p2.y);
current.setBounds(x, y, w, h);
}
};

public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.BLACK);

for (Rectangle rect : list) {
g.fillRect(rect.x, rect.y, rect.width, rect.height);
}

if (current != null) {
g.drawRect(current.x, current.y, current.width, current.height);
}
}

}
本回答被提问者和网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式