在Java中,使用Line2D类进行颜色填充通常涉及到以下几个步骤:
import java.awt.*;
import java.awt.geom.*;
Path2D path = new Path2D.Double();
path.moveTo(50, 50);
path.lineTo(200, 50);
path.lineTo(200, 200);
path.lineTo(50, 200);
path.closePath();
Graphics2D g2d = (Graphics2D) g;
g2d.setPaint(Color.BLUE);
g2d.fill(path);
g2d.setStroke(new BasicStroke(5));
g2d.setPaint(Color.BLACK);
g2d.stroke(path);
将以上代码整合到一个完整的示例中:
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
public class Line2DColorFillExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Line2D Color Fill Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.add(new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// Create a Path2D object
Path2D path = new Path2D.Double();
path.moveTo(50, 50);
path.lineTo(200, 50);
path.lineTo(200, 200);
path.lineTo(50, 200);
path.closePath();
// Set the fill color
g2d.setPaint(Color.BLUE);
// Fill the path
g2d.fill(path);
// Set the stroke color and width (optional)
g2d.setStroke(new BasicStroke(5));
g2d.setPaint(Color.BLACK);
// Stroke the path (optional)
g2d.stroke(path);
}
});
frame.setVisible(true);
});
}
}
运行此示例,将显示一个蓝色填充的矩形。