我有一个 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方法时,怎么才能只在父组件的子组件上绘制呢?