为什么JFrame无法显示任何形状?

时间:2014-11-19 14:58:33

标签: java swing jframe jpanel

我写了一个简单的程序,用户将输入一个int值,JFrame必须绘制矩形& JPannel上的椭圆形。但在我的情况下,该程序只能显示没有任何形状的窗口。我的代码出了什么问题:

Shapes.java:

package shapestest;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class ShapesTest{

    public static void main(String[] args) {
        String input=JOptionPane.showInputDialog(
        "Enter 1 to draw a rectangles\n"+
        "Enter 2 to draw ovals"
            );
        int choise=Integer.parseInt(input);
        Shapes panel=new Shapes(choise);

        JFrame application=new JFrame();
        application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        application.add(panel);
        application.setSize(300, 300);
        application.setVisible(true);

    }

}

ShapesTest.java:

package shapestest;
import java.awt.Graphics;
import javax.swing.JPanel;

public class Shapes extends JPanel{
    private int choice;
public Shapes(int userChoise){
  userChoise=choice;  
}
public void paintComponent(Graphics g){
    super.paintComponent(g);
    for(int i=0; i<10;i++)
    {
        switch(choice)
        {
            case 1:
                g.drawRect(10+i * 10,10+i * 10,50+i * 10,50+i * 10);
                break;
                case 2:
                    g.drawOval(10+i*10,10+i*10,50+i*10,50+i*10);
                    break;
        }
    }
}

}

1 个答案:

答案 0 :(得分:1)

像这样改变

public Shapes(int userChoise){
    choice = userChoise;  
}

因为您指定了userChoise = choice。所以选择默认值为0,永远不会得到更新。在paintComponent中没有0的情况,所以不会绘制任何东西