2014-02-17 269 views
0

我剛剛開始編程,我的老師給了我這個任務,使用分發的類文件創建圖形顯示,並從該文件調用方法列表。將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!

我可以使用一些幫助我不知道什麼是錯的。

回答

0

嘗試

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

必須使用Integer類將字符串轉換爲整數。

你在哪裏都想要的整數

Integer.parseInt(scg.getPeriod()); 
0

利用整數包裝類方法..

Integer.parseInt("your string"); 

谷歌「包裝類」,它的方法的詳細信息在鑄造中的數據