使用构造函数的 Graphics2D

发布于 2024-12-16 16:50:22 字数 304 浏览 3 评论 0原文

我想使用 Line2D.Double 在 JFrame 中绘制一条直线,我也想使用构造函数(而不是通过方法)来绘制直线。我必须如何声明变量 g,如 docs.oracle.com?

public void paint (Graphics g) {
Graphics2D g2 = (Graphics2D) g;
...
}

I want to draw a straight line in JFrame using Line2D.Double, also I want do it with constructor (not through method). How I must declare variable g like in example on docs.oracle.com?

public void paint (Graphics g) {
Graphics2D g2 = (Graphics2D) g;
...
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

萌逼全场 2024-12-23 16:50:22

绘画总是有方法的。特别是 Swing 中的自定义绘制是在 Swing 组件(如 JComponent 或 JPanel)的 PaintComponent() 方法中完成的。

阅读 自定义绘画 上的 Swing 教程,以获得更好的解释和示例。

Painting is always done in a method. In particular custom painting in Swing is done in the paintComponent() method of a Swing component like JComponent or JPanel.

Read the Swing tutorial on Custom Painting for a better explanation and examples.

一杆小烟枪 2024-12-23 16:50:22

1)我想使用Line2D.Double在JFrame中画一条直线,这是不可能的,你必须放在那里JLabel, JPanel 或普通 JComponent,例如此处

2)如果你想直接paintJFrame,那么你必须(使用方法paint()) 到 GlassPaneRootPane

3) 对于 Swing,有方法 painComponent(如两张海报所述),而不是绘制

1) I want to draw a straight line in JFrame using Line2D.Double, that not possible you have to put there JLabel, JPanel or plain JComponent, example here

2) if you want to paint directly to the JFrame, then you have to (use method paint()) to the GlassPane or RootPane

3) for Swing is there method painComponent(as mentioned both posters), not paint

弱骨蛰伏 2024-12-23 16:50:22

绘图/绘画发生事件驱动。也就是说,当必须(重新)绘制 JFrame 的一部分时,将调用 PaintComponent。

您只需在构造函数中将组件添加到 JFrame 的内容窗格即可。然后通过重写paintComponent来绘制线条。

您可以创建一个 JPanel,其中有一个:

List<Shape> shapes;
shapes.add(new Line2D.Double(...));

,然后在 PaintComponent 中绘制所有形状。但这太过分了。

The drawing/painting occurs event driven. That is when a part of the JFrame has to be (re-)drawn paint and paintComponent will be called.

You can merely add a component to the content pane of the JFrame in the constructor. That would then draw the line by overriding paintComponent.

You could create a JPanel, which has a:

List<Shape> shapes;
shapes.add(new Line2D.Double(...));

and then in paintComponent draw all shapes. But that is overdone.

凉城 2024-12-23 16:50:22

您的意思是如何使用构造函数获取 Graphics2D 对象?这不是这样做的方法,Graphics2D 是一个接口,并且实现类不在 API 中。但是,您可以使用以下命令从任何组件获取图形对象

(Graphics2D)component.getGraphics()

You mean how to get a Graphics2D object from with a constructor? That is not the way to do it, Graphics2D is an interface and the implementation classes are not in the API. However, you can get a graphics object from any component with

(Graphics2D)component.getGraphics()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文