日期:2014-05-20 浏览次数:20663 次
import java.awt.EventQueue; 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; import javax.swing.border.EmptyBorder; public class Test extends JFrame { private JPanel contentPane; private JTextField n1; private JTextField n2; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Test frame = new Test(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public Test() { setTitle("test"); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 280, 99); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); n1 = new JTextField(); n1.setBounds(47, 10, 66, 21); contentPane.add(n1); n1.setColumns(10); n2 = new JTextField(); n2.setBounds(180, 10, 66, 21); contentPane.add(n2); n2.setColumns(10); JButton button = new JButton("\u4EA4\u6362"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { exchange(); } }); button.setBounds(57, 41, 74, 23); contentPane.add(button); JLabel label = new JLabel("\u6570\u5B571\uFF1A"); label.setBounds(0, 10, 47, 21); contentPane.add(label); JLabel label_1 = new JLabel("\u6570\u5B572\uFF1A"); label_1.setBounds(127, 10, 47, 21); contentPane.add(label_1); JButton button_1 = new JButton("\u6E05\u7A7A"); button_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { n1.setText(""); n2.setText(""); } }); button_1.setBounds(147, 41, 74, 23); contentPane.add(button_1); } private void exchange(){ try { int numberInt_1=Integer.parseInt(n1.getText()); int numberInt_2=Integer.parseInt(n2.getText()); System.out.println("交换前:\n\t数字一:"+numberInt_1+"\n\t数字二:"+numberInt_2); int temp; /* * 先交换值,再显示在文本框中。 * 当然也可以直接显示,不用在顶定义个变量。这样只需 * n1.setText(""+numberInt_2); * n2.setText(""+numberInt_1); */ temp=numberInt_1; numberInt_1=numberInt_2; numberInt_2=temp; System.out.println("交换后:\n\t数字一:"+numberInt_1+"\n\t数字二:"+numberInt_2); n1.setText(""+numberInt_1); n2.setText(""+numberInt_2); } catch (Exception e) { JOptionPane.showMessageDialog(n1, "只能输入数字。"); } } }