【问题标题】:Converting a JTextField string to an Int将 JTextField 字符串转换为 Int
【发布时间】:2014-03-17 00:34:06
【问题描述】:

我刚刚开始编程,我的老师给了我这个任务,使用分发的类文件创建图形显示,以及从该文件调用的方法列表。

我正在使用 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 period 的值为 0!

我可以寻求帮助,但我不知道出了什么问题。

【问题讨论】:

    标签: java swing integer jtextfield parseint


    【解决方案1】:

    您必须使用 Integer 类将字符串转换为整数。

    你想要整数的地方:

    Integer.parseInt(scg.getPeriod());
    

    【讨论】:

      【解决方案2】:

      试试

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

      【讨论】:

        【解决方案3】:

        使用整数包装类方法..

        Integer.parseInt("your string");
        

        谷歌“包装类”和它的方法来获取更多关于转换数据的信息

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-10-02
          • 2011-03-06
          • 1970-01-01
          • 2018-07-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多