在添加到 jcomponent 的容器上绘制
我有一个 jrame,在其中添加一些 JComponent 对象。 每个 JComponent 都有一个我使用 JComponent.add( Component) 添加的容器列表。
现在,在我的主 JComponent 类(称为 MyComponent)中,我重写了受保护的方法 PaintComponent,我可以在其中绘制东西,效果非常好。
但我不想在主 JComponent 上绘画,我只想在添加到主 JComponent 的容器上绘画。
因此,在 PaintComponent 中的 MyComponent 中,我执行以下操作。
protected void paintComponent( Graphics g) {
super.paintComponent( g);
Graphics page_g = this.getPage( "main").getGraphics();
page_g.setColor( Color.RED);
page_g.drawRect( 10, 10, this.getWidth() - 20, this.getHeight() - 20);
page_g.setColor( Color.BLUE);
page_g.drawString( "HELLO WORLD", this.getWidth() / 2, this.getHeight() / 2);
}
行 this.getPage( "main").getGraphics();从我的容器之一获取 Graphics 对象,将其添加到容器的 MyComponents 列表中,当然还使用 JComponents add 方法添加到主组件列表中。通过调用 setVisible( true) 将容器设置为可见;方法。
但什么也没发生。屏幕是空的。当我用 g 替换 page_g 时,绘画就可以工作,因为它在我的 JComponent (MyComponent) 上绘画,但我想在本例中是 MyComponent 的子容器的容器上绘画。
我经常听到“永远不要使用 getGraphics()”。但是,当调用父组件的 PaintComponent 方法时,如何才能仅在父组件的子组件上进行绘制呢?
i have a jrame on which i add some JComponent objects.
Each JComponent has a list of containers i add by using JComponent.add( Component).
Now in my main JComponent class, called MyComponent, i override the protected method paintComponent where i can paint things, which works pretty fine.
But i dont want to paint on the main JComponent, i only want to paint on the containers i have added to my main JComponent.
So in MyComponent in paintComponent i do the following.
protected void paintComponent( Graphics g) {
super.paintComponent( g);
Graphics page_g = this.getPage( "main").getGraphics();
page_g.setColor( Color.RED);
page_g.drawRect( 10, 10, this.getWidth() - 20, this.getHeight() - 20);
page_g.setColor( Color.BLUE);
page_g.drawString( "HELLO WORLD", this.getWidth() / 2, this.getHeight() / 2);
}
The line this.getPage( "main").getGraphics(); takes the Graphics object from one of my containers added to the MyComponents list of containers and of course to the main component list using JComponents add method. The container is set to visible by calling the setVisible( true); method.
But nothing happens. The screen is empty. When i replace page_g with g, then painting works, because its painting on my JComponent (MyComponent), but i want to paint on the container which is a children of MyComponent in this case.
I often heard "Never use getGraphics()". But how else can ONLY draw on sub components of a parent component when the parents paintComponent method gets called?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实际上,最好的选择是让实际执行自定义绘制的类重写它们自己的 PaintComponent() 方法。让 AWT 关心图形上下文。
Really the best bet is to have the classes that are actually doing the custom painting override their own paintComponent() method. Let the AWT worry about the graphics contexts.