2014-11-14 65 views
0

我想創建一個小的swing應用程序,它將文本字段的輸入內容放入ArrayList。代碼無法正常工作,我需要一些幫助。將textField數據添加到列表。 Swing

編輯。修正了語法。現在我不能讓代碼工作。它不會將文本框數據添加到列表中。請幫忙。

下面是代碼:

public class GUI extends JPanel implements ActionListener{ 

JButton button = new JButton(" >> CLICK ME <<"); 
final JTextField txt = new JTextField("Enter player name."); 
static List <String> player = new ArrayList <String>(); 

public GUI(){ 

    txt.setBounds(1, 1, 300, 30); 

    JButton button = new JButton(" >> ADD PLAYER <<"); 

    button.setBounds(40, 40, 200, 40); 

    setLayout(null); 
    add(txt); 
    add(button); 

    button.addActionListener(this); 


} 

public void actionPerformed(ActionEvent e) { 

    if (e.getSource().equals(button)) { 
     player.add(txt.getText()); 
     System.out.println("Added: " + txt.getText() + " to the list."); 
    } 
    else 
     System.out.println("Adding the textField data to the list did not work."); 


} 


public static void main(String[] args) { 

    JFrame frame1 = new JFrame("Memory Game. Add player function."); 
    frame1.getContentPane().add(new GUI()); 

    frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame1.setSize(310, 130); 
    frame1.setVisible(true); 

} 

我新的擺動,只被編碼爲兩個星期。 :/

+0

1)Java的圖形用戶界面必須工作在不同的操作系統',屏幕大小,屏幕分辨率等。因此,它們不利於像素的完美佈局。請使用佈局管理器或[它們的組合](http://stackoverflow.com/a/5630271/418556)以及[white space]的佈局填充和邊框(http://stackoverflow.com/a/17874718/ 418556)。 2)源代碼中的單個空白行是所有需要的。 '{'之後或'}'之前的空行通常也是多餘的。 – 2014-11-14 12:17:13

+0

@AbdiTem你的新問題是什麼? – 2014-11-14 12:37:46

+0

@LukasHieronimusAdler的添加功能不起作用。 – Kharbora 2014-11-14 12:51:34

回答

2

您可以從JtextFieldgetText()方法獲取文本並使用add()將它添加到一個list player。以下是代碼。

player.add(txt.getText()); 

檢查下面的詳細信息的鏈接:

1

你只需要得到從文本框的文本。

player.add(txt.getText()) 

這會做你想要的。

在那裏你會得到TextField中的當前String。所以你可以將它添加到你的列表中。

+0

謝謝。我已經更新了我的問題,請隨時通讀它。 :) – Kharbora 2014-11-14 12:30:41

2

您需要的的ActionListener添加到的JButton與

button.addActionListener(this); 

然後在actionPerformed JTextField中的文本添加到列表:

player.add(txt.getText()); 
+0

謝謝。我已經更新了我的問題,請隨時通讀它。 :) – Kharbora 2014-11-14 12:31:08

+0

嘗試瞭解(使用system.out.println或調試模式)e.getSource()中的源代碼是什麼,如果它真的是您的按鈕。 – dor47 2014-11-14 13:09:25