我的程序中有三个按钮和一个JTextArea。我想要做的是,当用户按下按钮时,我希望JTextArea具有按下按钮1的文本,按下按钮2等等。例如。
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 :(得分:2)
您需要向按钮添加动作侦听器,如下所示:
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
textArea.append("button 1 was pressed");
}
});
别忘了在班级声明textArea。
希望这有帮助
答案 1 :(得分: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");
如果要在文本区域的开头添加新行。
答案 2 :(得分:1)
在将按钮添加到框架之前,请执行以下操作:
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
//Here write what you want to be execute when button is pressed
}
});
有关此次访问的更多详情:http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html