使用构造函数的 Graphics2D
我想使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
绘画总是有方法的。特别是 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.
1)
我想使用Line2D.Double在JFrame中画一条直线
,这是不可能的,你必须放在那里JLabel, JPanel 或普通 JComponent,例如此处2)如果你想直接
paint
到JFrame
,那么你必须(使用方法paint()
) 到GlassPane
或RootPane
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 here2) if you want to
paint
directly to theJFrame
, then you have to (use methodpaint()
) to theGlassPane
orRootPane
3) for Swing is there method
painComponent
(as mentioned both posters), notpaint
绘图/绘画发生事件驱动。也就是说,当必须(重新)绘制 JFrame 的一部分时,将调用 PaintComponent。
您只需在构造函数中将组件添加到 JFrame 的内容窗格即可。然后通过重写paintComponent来绘制线条。
您可以创建一个 JPanel,其中有一个:
,然后在 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:
and then in paintComponent draw all shapes. But that is overdone.
您的意思是如何使用构造函数获取 Graphics2D 对象?这不是这样做的方法,
Graphics2D
是一个接口,并且实现类不在 API 中。但是,您可以使用以下命令从任何组件获取图形对象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