我的程序中有三个按钮和一个 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
等等。
最佳答案
将 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");
如果您想在文本区域的开头添加新行。
关于java - 如何向 JTextArea 添加文本? java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21882363/