user3319742
user3319742

Reputation: 1

Converting a JTextField string to an Int

I have just started programming and my teacher have given me this assignment to create a graph display using a class file that was handed out, and a list of methods to call from this file.

I'm using GUI and i want to have three JTextFields, where you can enter a number to alter the graph. I'm currently struggling with the first text field, which I'm calling period(it alters the period on the graph). I have written like this in the code(the important parts):

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class Name extends Jpanel implements ActionListener
{
private SinCosGraph scg = new SinCosGraph //SinCosGraph is the name of the class file that im using.

//delclaring all the components, dont think it is neccecary to write them all(JButtons, JPanels etc.)

 public Name() 
 {
 setLayout(new BorderLayout());
 add("Center", scg);

 scg.setPeriod(45);
 System.out.println("The period is = " + scg.getPeriod());
 System.out.println("Intperiod is = " + scg.getPeriod());

 initComponent();
 }
 public void initComponent()
 {
 e = new JPanel();
 e.setLayout(new GridLayout(5,1, 40, 40));

 p1 = new JPanel();
 p1.setPreferredSize(new Dimension(200, 50));
 p1.setBorder( BorderFactory.createTitledBorder("Period") );
 period = new JTextField(5);
 period.setText("" + scg.getPeriod());
 int intperiod = Integer.praseInt(period.getText());

 p1.add(period);
 e.add(p1);

 add("East",e);

 .
 .
 . 
 .

 public void actionPerformed(ActionEvent e)
{
//Redrawing the graph
if(e.getSource() == reDraw)
{

scg.setPeriod(intperiod);
repaint();
    }

public static void main(String[]args)
{
JFrame jf = new JFrame("Name");
jf.setSize(1000, 700);
jf.setContentPane(new Name());
jf.setVisible(true);

}
}

this is the code that is important(Skipped a lot of code), this happened when i run the program: http://i.imgur.com/tC6ZY2C.png

It says that the period is 45, which is correct because i set it as 45. But the textfield is showing 360, which is the default number. And int period have the value 0!

I could use some help I have no idea what is wrong.

Upvotes: 0

Views: 128

Answers (3)

Praful Surve
Praful Surve

Reputation: 788

use Integer wrapper class method..

Integer.parseInt("your string");

Google "Wrapper class" and it methods for more info on casting the data

Upvotes: 0

jrowe08
jrowe08

Reputation: 391

You must use the Integer class to convert string to integer.

Where ever you want the integer:

Integer.parseInt(scg.getPeriod());

Upvotes: 1

Hugo Sousa
Hugo Sousa

Reputation: 1936

Try

System.out.println(Integer.parseInt(scg.getPeriod()));

Upvotes: 0

Related Questions