get two data from two textfield, and then click different button to calculate addition, subtraction, multiplication and division. The result is shown in textarea,
but textField.getText ()
can only get String, and TextArea.setText ()
can only give String
code as follows
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.image.Kernel;
public class e4_1 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
caculateGUI();
}
});
}
private static void caculateGUI(){
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame();
frame.setTitle("caculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("caculator");
frame.setLayout(new GridLayout(5,2));
//add label
frame.add(new JLabel("1st num"));
frame.add(new JLabel("2nd num"));
//creat and add textfield
JTextField textField1 = new JTextField();
JTextField textField2 = new JTextField();
frame.add(textField1);
frame.add(textField2);
//transfer String to int for caulating
String m = textField1.getText();
String n = textField2.getText();
int a = Integer.parseInt(m);
int b = Integer.parseInt(n);
//add result_label and result_textarea
frame.add(new JLabel("result"));
JTextArea jTextArea = new JTextArea();
frame.add(jTextArea);
//creat buttons
JButton jButton1 = new JButton("+");
JButton jButton2 = new JButton("-");
JButton jButton3 = new JButton("*");
JButton jButton4 = new JButton("/");
//buttonActions
frame.add(jButton1);
jButton1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
jTextArea.setText(Integer.toString(a+b));
}
});
frame.add(jButton2);
jButton2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
jTextArea.setText(Integer.toString(a-b));
}
});
frame.add(jButton3);
jButton3.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
jTextArea.setText(Integer.toString(a*b));
}
});
frame.add(jButton4);
jButton4.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
jTextArea.setText(Integer.toString(a/b));
}
});
int frameWidth = 400;
int frameHeight = 800;
Dimension screenSize =
Toolkit.getDefaultToolkit().getScreenSize();
frame.setBounds((int)screenSize.getWidth() - frameWidth,0,frameWidth,frameHeight);
frame.setVisible(true);
}
}