java - Drawing from one panel class to another panel class. -
i have 2 classes. first class called fishy1, , second class called fishy2. code first class:
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); } }
as can see, code draws oval in fishy1. , here code second class:
import java.awt.graphics; import javax.swing.jpanel; public class fishy2 extends jpanel { fishy2 fishy2 = new fishy2(); }
as can see, in second class, there no paintcomponet method draw fishy2. so, question is, there way draw second class using paintcomponent method in first class? if there's no way it, please let me know. thank you.
to achieve graphics replication between 2 swing classes @ same time
public class fishs extends jpanel { //static list, fishes panel display same objects @ same positions private static list<ovalobj> lstovalobjects; public fishs() { //if list null 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; } }
the oval object:
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; } }
implementation:
//first frame jframe frame1 = new jframe(); frame1.setlayout(new borderlayout()); //first fish panel go 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 go frame2 fishs fish2 = new fishs(); fish2.setvisible(true); frame2.setlayout(new borderlayout()); frame2.add(fish2, borderlayout.center); frame2.pack(); frame2.setvisible(true); /// can add many objects draw in static way anywhere in code, render in every fish panel @ same time fishs.getlstovalobjects().add(new ovalobj(0, 0, 50, 50)); fishs.getlstovalobjects().add(new ovalobj(20, 20, 50, 50));
Comments
Post a Comment