简体   繁体   English

将容器上的涂料添加到jcomponent

[英]paint on a container being added to jcomponent

i have a jrame on which i add some JComponent objects. 我有一个jrame,在上面添加了一些JComponent对象。 Each JComponent has a list of containers i add by using JComponent.add( Component). 每个JComponent都有我通过使用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. 现在在我的主要JComponent类(称为MyComponent)中,我重写了受保护的方法paintComponent,可以在其中绘画东西,效果很好。

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. 但是我不想在主JComponent上绘画,我只想在我添加到主JComponent的容器上绘画。

So in MyComponent in paintComponent i do the following. 因此,在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);
}

The line this.getPage( "main").getGraphics(); 这行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. 从添加到容器的MyComponents列表中的我的一个容器中获取Graphics对象,当然也使用JComponents add方法将其添加到主组件列表中。 The container is set to visible by calling the setVisible( true); 通过调用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. 当我用g替换page_g时,绘画就可以了,因为它在我的JComponent(MyComponent)上绘画,但是在这种情况下,我想在作为MyComponent的子代的容器上绘画。

I often heard "Never use getGraphics()". 我经常听到“从不使用getGraphics()”。 But how else can ONLY draw on sub components of a parent component when the parents paintComponent method gets called? 但是,当调用父paintComponent方法时,只能如何利用父组件的子组件呢?

Really the best bet is to have the classes that are actually doing the custom painting override their own paintComponent() method. 最好的选择是让正在实际进行自定义绘制的类覆盖其自己的paintComponent()方法。 Let the AWT worry about the graphics contexts. 让AWT担心图形上下文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM