Ryan
Ryan

Reputation: 87

Why JFrame can't display any shape?

I wrote a simple program where a user will input an int value and JFrame have to draw rectangle & oval shape on the JPannel. But in my case the program is only able to show the window without any shape on it. What's wrong with my code:

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

}

Upvotes: 1

Views: 114

Answers (1)

subash
subash

Reputation: 3115

change like this

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

because you assign userChoise = choice. so choice default value is 0 and it is never gets update. in paintComponent there is no case for 0. so nothing will be drawn

Upvotes: 1

Related Questions