为了账号安全,请及时绑定邮箱和手机立即绑定

java button action and text change

java button action and text change

繁花如伊 2019-01-19 00:16:46
从两个textfield获取两个数据,然后点击不同的button计算加减乘除,结果显示在textarea,但是textField.getText()只能获取String,而且TextArea.setText()只能给String代码如下 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); } }
查看完整描述

1 回答

  • 1 回答
  • 0 关注
  • 523 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信