title: Using a variable with paintComponent
body: <p>For a homework assignment, I am trying to paint a box with <code>paintComponent</code> using user inputed variables. I have been able to build what I am need to do using fixed numbers. I have been working on this all day and have not been able to find a way to implement variables. Here is a stripped down version of what I am working on:</p>
  
  <pre><code>import javax.swing.*;
  import java.awt.*;
  
  public class Problem3 extends JFrame{
  
    public static void main(String[] args) {  
      int xCoord = Integer.parseInt(
              JOptionPane.showInputDialog("Enter an X cord."));
  
      JFrame gd = new JFrame();
      gd.setLocationRelativeTo(null);
      gd.setSize(300, 300);
      gd.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      gd.setVisible(true);
  
      gd.add(new NewPanel());   
    }
  
    public int getX(){
      return xCoord;
    }
  }
  
  class NewPanel extends JPanel {
  
    int xCoord = getX();
  
    protected void paintComponent(Graphics g){
      super.paintComponent(g);
  
      g.drawRect(10,10,xCoord,50);
    }
  }
  </code></pre>
  
  <p><strong>EDIT</strong></p>
  
  <p>Since posting here I have tried using a setter method inside the NewPanel class</p>
  
  <pre><code>public void setX() {
      xCoord = Integer.parseInt(
              JOptionPane.showInputDialog("Enter an X cord."));
  }
  </code></pre>
  
  <p>Running this lead to a strange error I have never seen before: I get a StackOverFlow error and then the dialog box pops up multiple/hundreds of times and won't stop popping up.  </p>
  
  <p><strong>EDIT 3</strong> Using Hovercraft Full Of Eels solution, I got it to work! <strong>Thank you Full Of Eels for your time, help, and patience.</strong></p>
  
  <pre><code>public class Problem3 extends JFrame{
      public static void main(String[] args) {  
  
          JFrame gd = new JFrame();
          gd.setLocationRelativeTo(null);
          gd.setSize(300, 300);
          gd.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          gd.setVisible(true);
  
          NewPanel panel = new NewPanel();
  
          panel.setX(50); 
          gd.add(panel);
      } 
  }
  class NewPanel extends JPanel {
  
      int xCoord;
  
      public void setX(int x){
          xCoord = x;
      }
  
      public int getX(){
          return xCoord;
      }
  
      protected void paintComponent(Graphics g){
          super.paintComponent(g);
  
          g.drawRect(10,10,xCoord,50);
      }
  
  }
  </code></pre>