Java 如何传递绘制组件和对象所需的逻辑?
因此,我实例化了一个对象,其中包含与该对象关联的二维数据矩阵。我在这个数据矩阵上执行我的所有逻辑,现在我准备看到这个2D矩阵的视觉效果 我想根据矩阵中的值打印实心矩形或空心矩形 以下是我在伪代码方面遇到的问题:Java 如何传递绘制组件和对象所需的逻辑?,java,swing,graphics,jframe,paintcomponent,Java,Swing,Graphics,Jframe,Paintcomponent,因此,我实例化了一个对象,其中包含与该对象关联的二维数据矩阵。我在这个数据矩阵上执行我的所有逻辑,现在我准备看到这个2D矩阵的视觉效果 我想根据矩阵中的值打印实心矩形或空心矩形 以下是我在伪代码方面遇到的问题: public void paintComponent(Graphics g) { g.setColor(Color.gray); g.fillRect(0,0, 500, 500); // I need the logic from the instantiat
public void paintComponent(Graphics g)
{
g.setColor(Color.gray);
g.fillRect(0,0, 500, 500);
// I need the logic from the instantiated logic from the main method but I cant pass the object into the paintComponent method when I tried. How can I access the objectGrid object from the main method in this method?
}
public static void main(String[] args) {
Class newObject = new Class();
//Do operations on newly instantiated object
newObject.performOperation;
// Start a new JFrame object which will call the paintComponent method automatically
// But I want to pass newObject to paintComponent method and I don't know how to do it
JFrame window = new JFrame();
window.setSize(500, 500);
window.setVisible(true);
}
我希望这是有道理的。谢谢您需要一个扩展
JFrame
public class MyClass{
//...
}
public class MyFrame extends JFrame{
private MyClass obj;
public MyFrame(MyClass obj){
this.obj = obj;
//...
}
//...
public void paintComponent(Graphics g){
// Paint obj in here
}
}
然后,您可以这样使用:
MyClass obj = new MyClass();
MyFrame frame = new MyFrame(obj);
//...
frame.setVisible(true);
谢谢你。这工作做得很好。谢谢你。它甚至导致干净的代码将我的逻辑类和视图类分开。