设计界面并完成事件。界面包括2个jlabel,2个textfield,实现在一个文本框中输入1个
时间: 2023-06-24 21:05:14 浏览: 166
jquery实现点击label的同时触发文本框点击事件的方法
数字,点击按钮后在另一个文本框中显示这个数字的平方。
以下是示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SquareCalculator implements ActionListener {
private JFrame frame;
private JLabel inputLabel, outputLabel;
private JTextField inputField, outputField;
private JButton calculateButton;
public SquareCalculator() {
// Create the JFrame and set its properties
frame = new JFrame("Square Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 150);
frame.setLayout(new GridLayout(3, 2));
// Create the input label and field
inputLabel = new JLabel("Enter a number:");
inputField = new JTextField();
frame.add(inputLabel);
frame.add(inputField);
// Create the output label and field
outputLabel = new JLabel("Result:");
outputField = new JTextField();
outputField.setEditable(false);
frame.add(outputLabel);
frame.add(outputField);
// Create the calculate button and add an action listener to it
calculateButton = new JButton("Calculate");
calculateButton.addActionListener(this);
frame.add(calculateButton);
// Show the JFrame
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// Get the input value from the input field
String inputString = inputField.getText();
try {
// Convert the input value to a double and calculate its square
double input = Double.parseDouble(inputString);
double output = input * input;
// Set the output value in the output field
outputField.setText(String.valueOf(output));
} catch (NumberFormatException ex) {
// Show an error message if the input value is not a valid number
JOptionPane.showMessageDialog(frame, "Please enter a valid number.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String[] args) {
// Create a new SquareCalculator object
new SquareCalculator();
}
}
```
运行上述代码后,将会弹出一个界面,其中包含一个输入框、一个输出框和一个按钮。在输入框中输入一个数字,然后点击按钮,就会在输出框中显示这个数字的平方。如果输入的不是数字,则会弹出一个错误对话框提示用户输入一个有效的数字。
阅读全文