在线等!Java Swing,利用两个文本框对象接受用户输入两个数据,点击计算将两个数的和显示出来。
发布网友
发布时间:2022-05-06 16:20
我来回答
共1个回答
热心网友
时间:2023-10-11 16:05
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Test456 {
public static void main(String[] str) {
final JFrame frame = new JFrame();
frame.setSize(500, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
JPanel panel = new JPanel();
final JTextField input1 = new JTextField(10);
final JTextField input2 = new JTextField(10);
JLabel label = new JLabel(" + ");
final JTextField sum = new JTextField(10);
sum.setEditable(false);
JButton button = new JButton("等于");
panel.add(input1);
panel.add(label);
panel.add(input2);
panel.add(button);
panel.add(sum);
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0) {
String str1 = input1.getText().trim();
String str2 = input2.getText().trim();
try {
double in1 = Integer.parseInt(str1);
double in2 = Integer.parseInt(str2);
sum.setText("" + (in1 + in2));
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(frame, "输入错误信息!");
}
}
});
frame.add(panel, BorderLayout.NORTH );
frame.setVisible(true);
}
}追问没有输出框呢。。
追答“等于”按钮的右边,它被设置为不可编辑了。
热心网友
时间:2023-10-11 16:05
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Test456 {
public static void main(String[] str) {
final JFrame frame = new JFrame();
frame.setSize(500, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
JPanel panel = new JPanel();
final JTextField input1 = new JTextField(10);
final JTextField input2 = new JTextField(10);
JLabel label = new JLabel(" + ");
final JTextField sum = new JTextField(10);
sum.setEditable(false);
JButton button = new JButton("等于");
panel.add(input1);
panel.add(label);
panel.add(input2);
panel.add(button);
panel.add(sum);
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0) {
String str1 = input1.getText().trim();
String str2 = input2.getText().trim();
try {
double in1 = Integer.parseInt(str1);
double in2 = Integer.parseInt(str2);
sum.setText("" + (in1 + in2));
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(frame, "输入错误信息!");
}
}
});
frame.add(panel, BorderLayout.NORTH );
frame.setVisible(true);
}
}追问没有输出框呢。。
追答“等于”按钮的右边,它被设置为不可编辑了。