문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top