好的,所以我有一个JPAnel,其paintComponent方法被覆盖 .
它很简单,看起来像这样:
public class Panel1 extends JPanel {
public void paintComponent (Graphics g) {
super.paintComponent (g);
g.fillOval (0, 0, getWidth (), getHeight ());
}
}
现在,我将此JPanel作为属性添加到另一个JPanel类,如:
public class Panel2 extends JPanel {
Panel1 panel;
public Panel2 (Panel1 panel) {
this.panel = panel;
}
protected void paintComponent (Graphics g) {
super.paintComponent (g);
panel.paint (g); //This isn't working.
// panel.paintComponent (g); //Tried this too
g.drawOval (100, 100, getWidth () - 200, getHeight () - 200);
}
}
我想要的是Panel2被绘制与Panel1完全相同(没有硬编码)并且可能添加其他东西(比如三角形或者......,我不知道) .
这甚至可能吗?我调查了它,但没有找到任何办法 . 在此先感谢您的帮助!!
如果它有帮助, MAIN :
public class Main {
public static void main (String[] args) {
JFrame frame = new JFrame ();
frame.setSize (500, 500);
frame.add (new Panel2 (new Panel1 ()));
frame.setVisible (true);
}
}
编辑:以防万一,我不想继承;这就是为什么我把它作为一个属性添加,但如果有其他方式让我现在 .
3 回答
您可以尝试将
paintComponent
的Panel1
公开,然后在Panel2
的Panel2
中调用它:您还可以在
Panel1
类中创建一个方法来为您处理绘画然后在
Panel1
和Panel2
的paintComponent
方法中调用此方法它在问题中看不到的原因是
Panel1
的大小为0x0 . 要获得合理的尺寸,请从getPreferredSize()
返回尺寸,然后将面板尺寸设置为首选尺寸 .我认为应该有用