在Java中,Line2D是一個用于表示二維空間中兩條線的類,它可以用于創建各種圖形和交互。要設計一個基于Line2D的圖形交互,你需要遵循以下步驟:
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
JPanel
的自定義類,用于繪制Line2D圖形:class Line2DPanel extends JPanel {
private Line2D line;
public Line2DPanel(double x1, double y1, double x2, double y2) {
line = new Line2D.Double(x1, y1, x2, y2);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(new BasicStroke(2));
g2d.draw(line);
}
}
JFrame
中創建一個Line2DPanel
實例,并設置其位置和大小:public class Line2DInteractionDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("Line2D Interaction Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
Line2DPanel linePanel = new Line2DPanel(50, 50, 350, 350);
frame.add(linePanel);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class Line2DPanel extends JPanel {
// ...
private Color lineColor = Color.BLUE;
private float lineWidth = 2.0f;
public Line2DPanel(double x1, double y1, double x2, double y2) {
// ...
}
@Override
protected void paintComponent(Graphics g) {
// ...
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(new BasicStroke(lineWidth));
g2d.setColor(lineColor);
g2d.draw(line);
}
public void setLineColor(Color color) {
this.lineColor = color;
repaint();
}
public void setLineWidth(float width) {
this.lineWidth = width;
repaint();
}
}
// 在Line2DInteractionDemo類中添加鼠標事件監聽器
public class Line2DInteractionDemo {
// ...
public static void main(String[] args) {
// ...
Line2DPanel linePanel = new Line2DPanel(50, 50, 350, 350);
linePanel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
linePanel.setLineColor(Color.RED);
linePanel.setLineWidth(4.0f);
}
});
frame.add(linePanel);
// ...
}
}
現在,當用戶單擊Line2D時,線的顏色將更改為紅色,線寬將更改為4.0。你可以根據需要添加更多的交互功能,例如更改線的起點和終點坐標,或者實現其他圖形交互。