java用按钮方法实现按数字并平方并在文本框输入
时间: 2024-02-01 22:15:28 浏览: 26
您可以通过以下步骤来实现这个功能:
1. 创建一个 JFrame,并在其中添加一个 JTextField 和十个 JButton,分别对应数字 0-9。
2. 在每个按钮上添加 ActionListener,以便在用户单击按钮时触发事件。
3. 在 ActionListener 中获取用户单击的按钮上的数字,并将其平方。
4. 将计算结果转换为字符串,并将其设置为 JTextField 的文本。
以下是示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SquareNumbers extends JFrame implements ActionListener {
private JTextField textField;
public SquareNumbers() {
super("Square Numbers");
// Create the text field
textField = new JTextField(10);
textField.setEditable(false);
// Create the buttons
JButton button0 = new JButton("0");
JButton button1 = new JButton("1");
JButton button2 = new JButton("2");
JButton button3 = new JButton("3");
JButton button4 = new JButton("4");
JButton button5 = new JButton("5");
JButton button6 = new JButton("6");
JButton button7 = new JButton("7");
JButton button8 = new JButton("8");
JButton button9 = new JButton("9");
// Add action listeners to the buttons
button0.addActionListener(this);
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
button4.addActionListener(this);
button5.addActionListener(this);
button6.addActionListener(this);
button7.addActionListener(this);
button8.addActionListener(this);
button9.addActionListener(this);
// Add the components to the frame
JPanel panel = new JPanel(new GridLayout(4, 3));
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(button4);
panel.add(button5);
panel.add(button6);
panel.add(button7);
panel.add(button8);
panel.add(button9);
panel.add(button0);
panel.add(new JLabel());
panel.add(new JLabel());
getContentPane().add(panel, BorderLayout.CENTER);
getContentPane().add(textField, BorderLayout.NORTH);
// Set frame properties
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(250, 250);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
int number = Integer.parseInt(button.getText());
int square = number * number;
textField.setText(String.valueOf(square));
}
public static void main(String[] args) {
new SquareNumbers();
}
}
```
在这个示例中,我们创建了一个 JFrame,并在其中添加了一个 JTextField 和十个 JButton。我们还添加了一个实现 ActionListener 接口的类,以便在用户单击按钮时触发事件。在 actionPerformed 方法中,我们获取用户单击的按钮上的数字并将其平方。最后,我们将计算结果转换为字符串并将其设置为 JTextField 的文本。