交个作业,交个作业
题目:
求和工具。编写一个程序:
设计如图8.24所示的界面。在第一个文本框中输入第一个家属;
在第二个文本框中输入第二个家属;
当单机 ‘=’ 按钮时,在第三个文本框中显示出前面两个加数之和。
代码:
用匿名内部类的:
import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; public class Sum extends JFrame{ public static void main(String argc[]){ JFrame jf = new JFrame("Sum"); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setSize(360, 100); Container c = jf.getContentPane(); c.setLayout(new FlowLayout()); JTextField [] t = { new JTextField(6), new JTextField(6), new JTextField(6) }; JButton [] b = { new JButton("+"), new JButton("=") }; c.add(t[0]); c.add(b[0]); c.add(t[1]); c.add(b[1]); c.add(t[2]); b[1].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ t[2].setText(Integer.parseInt(t[0].getText()) + Integer.parseInt(t[1].getText())+""); } }); jf.setVisible(true); } }
用接口的:
import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; public class Sum extends JFrame implements ActionListener{ private JTextField [] t = { new JTextField(6), new JTextField(6), new JTextField(6) }; private JButton [] b = { new JButton("+"), new JButton("=") }; public Sum(){ super("Sum"); init(); } public void showView(){ setVisible(true); } public void init(){ Container c = getContentPane(); c.setLayout(new FlowLayout()); setSize(360, 100); c.add(t[0]); c.add(b[0]); c.add(t[1]); c.add(b[1]); c.add(t[2]); b[1].addActionListener(this); } public static void main(String argc[]){ Sum s = new Sum(); s.showView(); } public void actionPerformed(ActionEvent e){ t[2].setText(Integer.parseInt(t[0].getText()) + Integer.parseInt(t[1].getText())+""); } }