将JTextField字符串转换为Int
问题描述:
我刚刚开始编程,我的老师给了我这个任务,使用分发的类文件创建图形显示,并从该文件调用方法列表。将JTextField字符串转换为Int
我正在使用GUI,我想要三个JTextFields
,在那里你可以输入一个数字来改变图形。我目前正在挣扎着第一个文本字段,我称之为期间(它改变了图表上的时间段)。
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);
}
}
这是很重要(跳过了很多代码),这发生在我运行程序的代码:http://i.imgur.com/tC6ZY2C.png
这我已在代码(重要部件)这样写说期间是45,这是正确的,因为我将它设置为45.但textfield
显示360,这是默认数字。并且int期间的值为0!
我可以使用一些帮助我不知道什么是错的。
答
尝试
System.out.println(Integer.parseInt(scg.getPeriod()));
答
必须使用Integer类将字符串转换为整数。
你在哪里都想要的整数
Integer.parseInt(scg.getPeriod());
答
利用整数包装类方法..
Integer.parseInt("your string");
谷歌“包装类”,它的方法的详细信息在铸造中的数据