2016-05-02 80 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

谢谢你,修复它。 –