2014-08-28 107 views
0

這是我的代碼 它向我要求將changeName設置爲一個靜態變量。這沒有意義,因爲我試圖捕獲用戶輸入。getText由於某種原因不會在JTextField上工作

import java.awt.Color; 
import java.awt.GridBagConstraints; 
import java.awt.GridBagLayout; 
import java.awt.Insets; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.*; 
import javax.swing.*; 

import CourseProject.General.exitApp; 

public class Options extends JPanel{ 

    private JLabel changeLabel; 
    private JTextField changeName; 
    private JButton setName; 
    private JButton exitButton; 

    public Options(){ 
     GridBagLayout gridbag = new GridBagLayout(); 
     GridBagConstraints c = new GridBagConstraints(); 
     c.fill = GridBagConstraints.NORTH; 
     setBackground(Color.WHITE); 
     super.setLayout(gridbag); 
     c.insets = new Insets(10, 10, 10, 10); 

     changeLabel = new JLabel("Change Company Name:"); 
     changeName = new JTextField(10); 
     setName = new JButton("Set New Name"); 
     exitButton = new JButton("Exit");  

     c.gridx = 0; 
     c.gridy = 0; 
     c.gridwidth = 2; 
     add(changeLabel, c);   

     c.gridx = 0; 
     c.gridy = 1;  
     add(changeName, c);  

     c.gridx = 0; 
     c.gridy = 2; 
     c.gridwidth = 1; 
     add(setName, c); 
     setName.addActionListener(new setNameAction()); 


     c.gridx = 1; 
     c.gridy = 2;  
     add(exitButton, c); 
     exitButton.addActionListener(new exitApp()); 
     exitButton.setSize(40,40); 

    } 
    static class setNameAction implements ActionListener 
    { 
     public void actionPerformed(ActionEvent e) 
     { 
      String str = ""; 
      str = changeName.getText(); 
     } 
    } 

    static class exitApp implements ActionListener 
    { 
     public void actionPerformed(ActionEvent e) 
     { 
      System.exit(0); 
     } 
    } 
} 

我專門具有與該代碼

static class setNameAction implements ActionListener 
{ 
    public void actionPerformed(ActionEvent e) 
    { 
     String str = ""; 
     str = changeName.getText(); 
    } 
} 

它問我設置changeName靜態變量,這部分問題。這沒有意義,因爲我試圖捕獲用戶輸入。

回答

1

您內部類被聲明爲static ...

static class setNameAction ... 

,如果你希望能夠引用外部類的實例字段從類中刪除聲明中static參考...

否則,您需要將OptionsJTextField的實例傳遞給setNameAction類。

你可能想通過Code Conventions for the Java TM Programming Language有讀,它將使人們更容易閱讀您的代碼,供您閱讀別人

+0

笑這就是我得到試圖通過複製偷工減料和粘貼沒有真正知道我在我身上做什麼。謝謝! – helloWorldIsAlliKnow 2014-08-28 03:05:53

+0

@helloWorldIsAlliKnow歡迎來到我的世界;) – MadProgrammer 2014-08-28 03:06:18

相關問題