Loading...

java ラバーバンドを表現するためのした調べ

rubber band を表現するための試作

参考:
JListのアイテムを範囲指定で選択 - Java Swing Tips

工夫したのは、点線が動いているようにみせるために、Timerを使って書きはじめの位置をずらして交互に表示させていること。

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.SystemColor;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.geom.Line2D;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;

class TestRubberband extends JPanel {

private static final long serialVersionUID = 1L;
private final Color rcolor;
private final Polygon polygon = new Polygon();
private final Line2D line = new Line2D.Double();
Point srcPoint = null;

public TestRubberband() {
rcolor = SystemColor.activeCaption;

setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
if (srcPoint == null)
srcPoint = e.getPoint();

Point destPoint = e.getPoint();

polygon.reset();
polygon.addPoint(srcPoint.x, srcPoint.y);
polygon.addPoint(destPoint.x, srcPoint.y);
polygon.addPoint(destPoint.x, destPoint.y);
polygon.addPoint(srcPoint.x, destPoint.y);
if (srcPoint.getX() == destPoint.getX()
|| srcPoint.getY() == destPoint.getY()) {
line.setLine(srcPoint.getX(), srcPoint.getY(), destPoint
.getX(), destPoint.getY());

}
repaint();
}
});
addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
repaint();
}

public void mousePressed(MouseEvent e) {

}
});

Timer timer = new Timer();
TimerTask task = new TimerTask() {

@Override
public void run() {
repaint();
}
};

timer.schedule(task, 0, 300);
}

/*
* ラバーバンドが動いて見えるようにするために使用しています。
*/
boolean b = true;

public void paintComponent(Graphics g) {
super.paintComponent(g);
if (srcPoint == null)
return;
Graphics2D g2d = (Graphics2D) g;

float[] pattern = { 5, 5, 5, 5 };

b = b ? false : true;
BasicStroke bs = new BasicStroke(2f, BasicStroke.CAP_SQUARE,
BasicStroke.JOIN_ROUND, 1f, pattern, b ? 0f : 3f);

g2d.setStroke(bs);
g2d.setPaint(rcolor);
g2d.drawPolygon(polygon);

}

protected Color makeColor(Color c) {
int r = c.getRed();
int g = c.getGreen();
int b = c.getBlue();
if (r > g)
return (r > b) ? new Color(r, 0, 0) : new Color(0, 0, b);
else
return (g > b) ? new Color(0, g, 0) : new Color(0, 0, b);
}

public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new TestRubberband());
frame.setVisible(true);
}

}
リアクション: 
,
ui 4496653242924833901

コメントを投稿

ホーム item

このブログを検索

Random Posts

Popular Posts

Labels

ADS