JAVA 无法从另一个 class 中绘制到 JFrame 上

JAVA can't paint onto JFrame from within another class

我知道这是我的错误。我的问题是为什么这不起作用我错过了什么我可以称之为我把它放在一个方法而不是 class 所以我假设他们的第三个 class 有问题?

Class 1:

package assignment.pkg1.java;

import java.awt.Color;
import javax.swing.JFrame;

public class JVMVeiwer  {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    final int FRAME_WIDTH = 1000; // Frame Width
    final int FRAME_HEIGHT = 800; // Frame Height
    JFrame frame = new JFrame();

    frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); //Sets Frame Size
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setTitle("JVM Diagram");// Sets the Title       
    JVMComponent component = new JVMComponent();
    frame.setBackground(Color.WHITE);
    frame.add(component); // adds the diagram to the JFrame       
    frame.setVisible(true); // Makes the frame visible
}

}

Class 2:

package assignment.pkg1.java;

import java.awt.*;
import javax.swing.JComponent;


public class JVMComponent extends  JComponent { 

@Override
public void  paintComponent(Graphics g) {      
    super.paintComponent(g);        
    Graphics2D g2 = (Graphics2D) g; // recover the graphic  
    JVMDiagram diagram = new JVMDiagram(); // creates an instance of JVM Diagram
    diagram.draw(g2);
  }
}

Class 3 这是我不能使用 o paint 到 jframe 的那个:

package assignment.pkg1.java;

import java.awt.Color;
import java.awt.Graphics2D;
import javax.swing.JComponent;

public class JVMDiagram {
// Constructor
public JVMDiagram() {

}
// Draw method for shape
public  void draw(Graphics2D g2) {
// Detailed instructions to draw shape
    int x = getWidth();
    int y = getHeight();
    int temp, temp2;
    int width = x / 2;
    int height = x / 2;
    x = (x - width) / 2;
    y= (y - height) / 2; 

    g2.setColor(Color.RED);
    g2.drawOval(x, y, width, height);
    g2.drawRect(x, y, width, height);
    g2.setColor(Color.RED);
    g2.drawLine(x, y, width + x, height + y);
    g2.drawRoundRect(x, y, width, height, y, y);

    g2.drawLine(x + width, y, x, height + y);
}

}

你的问题是你滥用了继承。您的 JVMDiagram 正在扩展 JVMComponent 而它不应该。是的,您获得了 JVMComponent 的 getWidth() 和 getHeight() 方法,但它们没有任何意义,因为 JVMDiagram 没有作为组件添加到 GUI,不应该作为组件添加,并且它的高度为 0 并且宽度(打印出来)。

重新考虑您的设计,不要为此使用继承。如果需要,而是将值从一个对象传递到另一个对象。例如,在 JVMComponent 中创建一个 JVMDiagram 字段并对其进行初始化。在JVMComponent的paintComponent方法中用Graphics2D在JVMDiagram draw方法中传入宽高。

附带问题:永远不要从绘画方法中或从绘画方法中调用的代码中调用 repaint()