我有两个类。第一类称为Fishy1,第二类称为Fishy2。这是我第一堂课的代码:
import java.awt.Graphics;
import javax.swing.JPanel;
public class Fishy1 extends JPanel {
Fishy1 fishy1 = new Fishy1();
/* Graphics goes here */
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawOval(50, 50, 50, 50);
}
}
如您所见,代码基本上在 fishy1 中绘制一个椭圆形。这是我第二节课的代码:
import java.awt.Graphics;
import javax.swing.JPanel;
public class Fishy2 extends JPanel {
Fishy2 fishy2 = new Fishy2();
}
如您所见,在第二类中,没有 paintComponet 方法来绘制到 fishy2。所以,我的问题是,有没有办法在第一堂课中使用paintComponent方法绘制到第二类?如果没有办法,请告诉我。谢谢。
同时实现 2 个摆动类之间的图形复制
public class Fishs extends JPanel {
//Static list, all fishes panel will display the same objects at same positions
private static List<OvalObj> lstOvalObjects;
public Fishs() {
//if the list is null just initialize it.
lstOvalObjects = lstOvalObjects == null? new ArrayList():lstOvalObjects;
}
/* Graphics goes here */
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
lstOvalObjects.forEach(ovalObject -> g.drawOval(ovalObject.getX(), ovalObject.getY(), ovalObject.getWidth(), ovalObject.getHeight()));
}
public static List<OvalObj> getLstOvalObjects() {
return lstOvalObjects;
}
public static void setLstOvalObjects(List<OvalObj> lstOvalObjects) {
Fishs.lstOvalObjects = lstOvalObjects;
}
}
椭圆形对象:
public class OvalObj{
private int x,y,width,height;
public OvalObj(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
}
实现:
//First Frame
JFrame frame1 = new JFrame();
frame1.setLayout(new BorderLayout());
//First Fish Panel that will go to frame1
Fishs fish1 = new Fishs();
fish1.setVisible(true);
frame1.add(fish1, BorderLayout.CENTER);
frame1.pack();
frame1.setVisible(true);
//Second Frame
JFrame frame2 = new JFrame();
//Second Fish Panel that will go to frame2
Fishs fish2 = new Fishs();
fish2.setVisible(true);
frame2.setLayout(new BorderLayout());
frame2.add(fish2, BorderLayout.CENTER);
frame2.pack();
frame2.setVisible(true);
/// you can add many objects to draw as you like in a static way anywhere in your code, they will render in every fish panel at same time
Fishs.getLstOvalObjects().add(new OvalObj(0, 0, 50, 50));
Fishs.getLstOvalObjects().add(new OvalObj(20, 20, 50, 50));