2014-02-19 114 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”);' –