2014-02-19 115 views
0

我的程序中有三個按鈕和一個JTextArea。我想要做的是,當用戶按下按鈕時,我希望JTextArea有文本說按鈕1被按下,按鈕2被按下等等。例如。如何將文本添加到JTextArea? java

JButton button1 = new JButton(); 
JButton button2 = new JButton(); 
JButton button3 = new JButton(); 

JTextArea text = new JTextArea(); 
JFrame frame = new JFrame(); 
frame.add(button1); 
frame.add(button2); 
frame.add(button3); 
frame.add(text); 
frame.setVisible(true); 

我想要做的是,當用戶按下按鈕1,我想JTextArea中有短信說扣1是按,然後如果用戶按下按鈕2,我想JTextArea中有以前的文本和按鈕2的文本。所以它應該說類似的東西;

button 1 was pressed 
button 2 was pressed 

編輯:

等有文字像這樣,

button 1 was pressed button 2 was pressed 
button 3 was pressed 

,如果我有更多的按鈕,它看起來像這樣

button 1 was pressed button 2 was pressed 
button 3 was pressed button 4 was pressed 
button 5 was pressed button 6 was pressed 

等。

+0

你看過@文檔嗎? http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextArea.html - 它擴展了JTextComponent(http://docs.oracle.com/javase/7/docs/api/javax/ swing/text/JTextComponent.html),它有一個'setText'方法。 –

+0

使您的文本變量成爲實例字段,而不是本地字段,然後在您的ActionListener中使用它。 –

回答

2

actionListener添加到每個將調用的圖片

yourTextArea.append("button X was pressed\n"); 

下面是簡單的演示

JFrame frame = new JFrame(); 
frame.setLayout(new FlowLayout()); 

final JTextArea area = new JTextArea(2,20); 
frame.getContentPane().add(area); 

JButton button1 = new JButton("press me"); 
JButton button2 = new JButton("press me"); 

button1.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
     area.append("button 1 was pressed\n"); 
    } 
}); 
button2.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
     area.append("button 2 was pressed\n"); 
    } 
}); 

frame.getContentPane().add(button1); 
frame.getContentPane().add(button2); 

frame.setSize(300,300); 
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
frame.setVisible(true); 

您還可以使用

try { 
    area.getDocument().insertString(0,"button 1 was pressed\n", null); 
} catch (BadLocationException e1) { 
    e1.printStackTrace(); 
} 

,而不是

yourTextArea.append("button X was pressed\n"); 

,如果你想在開始添加新線文本區域。

+0

你好新JTextArea(2,20); 2,20是什麼意思? – Seeker

+0

@ user3288493它是默認的行數和列數。看看[這個構造函數的文檔](http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextArea.html#JTextArea%28int,%20int%29)。 – Pshemo

+0

有沒有JTextPane的附加函數? – Seeker

2

您需要到動作偵聽器添加到您的按鈕是這樣的:

button1.addActionListener(new ActionListener() { 

    @Override 
    public void actionPerformed(ActionEvent arg0) { 
     textArea.append("button 1 was pressed"); 

    } 
}); 

不要忘了在類級別聲明文本區域。

希望這有助於

+0

感謝您的糾正。更新:) – Sanjeev

+0

Sanjeev,嗨,謝謝,追加是我需要補充的。但有一個問題,你如何將文本帶到下一行? – Seeker

+0

'textArea.append(「\ n」);' –