开发者

paint on a container being added to jcomponent

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜