2016-10-05 47 views
0

我知道這是我的錯誤。我的問題是爲什麼不是這個工作我錯過了什麼我可以調用這是我把它放在一個方法而不是一個類,所以我假設他們的第三類錯了嗎?JAVA無法從另一個類中繪製到JFrame上

第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 
} 

}

二級:

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); 
    } 
} 

3該類是一個II不能使用Ò油漆到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); 
} 

}

+3

注:'paintComponent'被稱爲每次有重繪的需要。你真的確定要在那裏創建數百個'JVMDiagram'對象嗎? – BackSlash

回答

4

你的問題是你濫用繼承。您的JVMDiagram正在擴展JVMComponent,它不應該。是的,你獲得了JVMComponent的getWidth()和getHeight()方法,但它們並不意味着什麼,因爲JVMDiagram並未作爲組件添加到GUI中,不應該作爲組件添加,並且它具有0高度和寬度(打印出來)。

重新考慮你的設計,用於該用途的繼承。相反,如果需要,將值從一個對象傳遞到另一個對象。例如,在JVMComponent中創建一個JVMDiagram字段並初始化它。在JVMComponent的paintComponent方法的JVMDiagram draw方法中傳入Graphics2D的寬度和高度。

枝節問題:不調用repaint()從畫法中,或從從繪畫方法中調用的代碼。

+0

謝謝,我只是嘗試了一段時間,試圖讓它工作,因此重繪和擴展JVMComponent,但問題仍然存在。 – Ryan

+0

對不起,問題是,在繪製方法getWidth()和getHeight()給我空值,所以沒有出現,因爲那是我用作座標。 – Ryan