2016-05-02 79 views
0

我的程序試圖用Java JFrame和FPanel繪製東西時遇到了問題,我還查看了另一個問題,標記爲相似方式(Shapes not drawing in Java),但來自問題我無法確定我的程序出了什麼問題。所以現在,即使這是某種意義上的副本,我在尋求幫助指出我有什麼錯誤。我也在我的媒體上使用netbeans。Java,形狀不繪圖

import java.awt.Graphics; 
import java.awt.Color; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import java.awt.Font; 


public class BullsEye extends JPanel{ 

@Override 
    public void printComponent(Graphics g) 
    { 
    super.paintComponent(g); 
    //for(int x =0; x>10;x++) 
    //{ 
    int x=10; 

     int y =(100-10*(x-1)); 
     //if((x%2)==0) 
     //{ 
      g.setColor(Color.RED);//setting color 
      g.drawRect(100, 10, 10, 15);//drawing 
      g.drawOval(0, 0, 100, 100);//drawing 
     //} 
     // else 
     //{ 
      g.setColor(Color.GREEN);//setting color 
      g.fillOval(10, 10, 50, 50);//drawing 
     //} 
    //} 


    } 
    public static void main(String[] args) 
    { 
     BullsEye b = new BullsEye();//creating b varaible for drawings 
    JFrame jf = new JFrame();//frame varaible for the frame 
    jf.setTitle("BullsEye");//setting title 
    jf.setSize(500,400);//setting size 

    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//opertion close 
    jf.add(b);//adding to the frame 

    jf.setVisible(true);//setting it to visible 
    } 

} 

回答

0

你重寫錯誤的方法。覆蓋paintComponent而不是printComponent,因爲它僅用於打印。好教程更多信息:https://docs.oracle.com/javase/tutorial/uiswing/painting/

import java.awt.Graphics; 
import java.awt.Color; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import java.awt.Font; 


public class BullsEye extends JPanel{ 

@Override 
    public void paintComponent(Graphics g) 
    { 
    super.paintComponent(g); 
    //for(int x =0; x>10;x++) 
    //{ 
    int x=10; 

     int y =(100-10*(x-1)); 
     //if((x%2)==0) 
     //{ 
      g.setColor(Color.RED);//setting color 
      g.drawRect(100, 10, 10, 15);//drawing 
      g.drawOval(0, 0, 100, 100);//drawing 
     //} 
     // else 
     //{ 
      g.setColor(Color.GREEN);//setting color 
      g.fillOval(10, 10, 50, 50);//drawing 
     //} 
    //} 


    } 
    public static void main(String[] args) 
    { 
     BullsEye b = new BullsEye();//creating b varaible for drawings 
    JFrame jf = new JFrame();//frame varaible for the frame 
    jf.setTitle("BullsEye");//setting title 
    jf.setSize(500,400);//setting size 

    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//opertion close 
    jf.add(b);//adding to the frame 

    jf.setVisible(true);//setting it to visible 
    } 

} 
+0

謝謝你,修復它。 –