我想从每个Ellipse2D中的ArrayList<>()中绘制线条。我知道我可以对每行的位置进行硬编码,使其看起来像是连接每个Ellipse2D,但是如果有更好的方法,我想让它与getCenterX()或getCenterY()或其他东西一起高效工作。我发布了一个关于我正在使用的最小的自包含示例。
那里的线显然不在正确的位置。我尝试通过访问ArrayList的元素来添加坐标,但我无法找到使其工作的方法。任何帮助表示赞赏!
import java.awt.*;
import java.awt.geom.*;
import java.util.*;
import javax.swing.*;
public class SelfContainedExample extends JPanel {
private ArrayList<Shape> shapes = new ArrayList<>();
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public SelfContainedExample()
{
//Circle of Radios
shapes.add(new Ellipse2D.Double(110, 70, 15, 15));
shapes.add(new Ellipse2D.Double(90, 80, 15, 15));
shapes.add(new Ellipse2D.Double(70, 100, 15, 15));
shapes.add(new Ellipse2D.Double(70, 120, 15, 15));
shapes.add(new Ellipse2D.Double(90, 140, 15, 15));
shapes.add(new Ellipse2D.Double(110, 150, 15, 15));
shapes.add(new Ellipse2D.Double(130, 140, 15, 15));
shapes.add(new Ellipse2D.Double(150, 120, 15, 15));
shapes.add(new Ellipse2D.Double(150, 100, 15, 15));
shapes.add(new Ellipse2D.Double(130, 80, 15, 15));
//for this line I want to use getCenterX() of the Ellipses added to this ArrayList
shapes.add(new Line2D.Double(10,10,90,10));
}
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g.create();
g2d.setColor(Color.BLUE);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
for(Shape shape : shapes) {
g2d.fill(shape);
g2d.draw(shape);
}
g2d.dispose();
}
private static void createAndShowGUI()
{
//Make the big window be indented 50 pixels from each edge
//of the screen.
int inset = 50;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
JFrame frame = new JFrame("Example");
JDesktopPane desktopPane = new JDesktopPane();
JInternalFrame internalFrame = new JInternalFrame("Example",
false, //resizable
false, //closable
false, //maximizable
true); //iconifiable
internalFrame.setSize(260, 260);
internalFrame.add(new SelfContainedExample());
internalFrame.setVisible(true);
desktopPane.add(internalFrame);
desktopPane.setVisible(true);
desktopPane.setBounds(inset, inset,
screenSize.width - inset * 7,
screenSize.height - inset * 4);
frame.add(desktopPane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(desktopPane.getSize());
frame.setLocationByPlatform( false );
frame.setLocationRelativeTo( null );
frame.setContentPane( desktopPane );
frame.setVisible( true );
}
}
答案 0 :(得分:4)
您希望在绘制形状之前绘制线条,以便将形状绘制在线条的顶部。
代码如下:
for (int i = 0; i < shapes.size() - 1; i++)
{
Rectangle r1 = shapes.get(i).getBounds();
Rectangle r2 = shapes.get(i+1).getBounds();
int x1 = r1.x + r1.width / 2;
int y1 = r1.y + r1.height / 2;
int x2 = r2.x + r2.width / 2;
int y2 = r2.y + r2.height / 2;
g.drawLine(x1, y1, x2, y2);
}
for(Shape shape : shapes) {