如何使得按多个按钮传到文本框上面,就是字符串拼接,用添加事件来写,代码实现
时间: 2024-02-15 13:02:37 浏览: 59
好的,下面是一个基于添加事件的字符串拼接示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Calculator extends JFrame implements ActionListener {
private JButton button0, button1, button2, button3, button4, button5, button6, button7, button8, button9;
private JButton buttonPlus, buttonMinus, buttonMultiply, buttonDivide, buttonEqual, buttonClear;
private JTextField textField;
private String text = "";
public Calculator() {
setTitle("简单计算器");
setLayout(new BorderLayout());
textField = new JTextField();
textField.setEditable(false);
add(textField, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4));
button7 = addButton("7", buttonPanel);
button8 = addButton("8", buttonPanel);
button9 = addButton("9", buttonPanel);
buttonPlus = addButton("+", buttonPanel);
button4 = addButton("4", buttonPanel);
button5 = addButton("5", buttonPanel);
button6 = addButton("6", buttonPanel);
buttonMinus = addButton("-", buttonPanel);
button1 = addButton("1", buttonPanel);
button2 = addButton("2", buttonPanel);
button3 = addButton("3", buttonPanel);
buttonMultiply = addButton("*", buttonPanel);
button0 = addButton("0", buttonPanel);
buttonClear = addButton("C", buttonPanel);
buttonEqual = addButton("=", buttonPanel);
buttonDivide = addButton("/", buttonPanel);
add(buttonPanel, BorderLayout.CENTER);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
private JButton addButton(String label, JPanel panel) {
JButton button = new JButton(label);
button.addActionListener(this);
panel.add(button);
return button;
}
@Override
public void actionPerformed(ActionEvent e) {
String buttonValue = e.getActionCommand();
switch (buttonValue) {
case "C":
text = "";
break;
case "=":
calculate();
break;
default:
text += buttonValue;
break;
}
textField.setText(text);
}
private void calculate() {
// 进行计算,这里省略具体实现
text = "";
}
public static void main(String[] args) {
new Calculator();
}
}
```
在这个例子中,我们创建了一个简单的计算器界面,包含了数字和操作符的按钮以及一个文本框。每当用户点击按钮时,程序会调用actionPerformed方法,将按钮对应的字符拼接到text字符串中,并在文本框中显示拼接后的字符串。当用户点击清空按钮或计算按钮时,我们会清空text字符串或进行计算,并更新文本框中的内容。
需要注意的是,我们在创建按钮时调用了addButton方法,并将当前对象作为ActionListener传入。这样,当用户点击按钮时,程序就会调用该对象的actionPerformed方法,从而实现字符串拼接和计算等功能。
阅读全文