摘自: http://www.ntu.edu.sg/home/ehchua/programming/java/J4a_GUI.html Writing Swing Applications In summary, to write a Swing application, you have: Use the Swing components with prefix "J" in package javax.swing, e.g., JFrame, JButton, JTextField, JLabel, etc. A top-level container (such as JFrame or JApplet) is needed. The JComponents should be added directly onto the top-level container. They shall be added onto the content-pane of the top-level container. You can retrieve a reference to the content-pane by invoking method getContentPane() from the top-level container, or set the content-pane to the main JPanel created in your program. Swing applications uses AWT event-handling classes, e.g., ActionEvent/ActionListener, MouseEvent/MouseListener, etc. Run the constructor in the Event Dispatcher Thread (instead of Main thread) for thread safety, as shown in the following program template. 1、 import java.awt.*; // Using AWT containers and components import java.awt.event.*; // Using AWT events and listener interfaces import javax.swing.*; // Using Swing components and containers // A Swing GUI application inherits from top-level container javax.swing.JFrame public class SwingCounter extends JFrame { private JTextField tfCount; // Use Swing's JTextField instead of AWT's TextField private int count = 0; /** Constructor to setup the GUI */ public SwingCounter () { // Retrieve the content-pane of the top-level container JFrame // All operations done on the content-pane Container cp = getContentPane(); cp.setLayout(new FlowLayout()); cp.add(new JLabel("Counter")); tfCount = new JTextField("0", 10); tfCount.setEditable(false); cp.add(tfCount); JButton btnCount = new JButton("Count"); cp.add(btnCount); // Allocate an anonymous instance of an anonymous inner class that // implements ActionListener as ActionEvent listener btnCount.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ++count; tfCount.setText(count + ""); } }); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit program if close-window button clicked setTitle("Swing Counter"); // "this" JFrame sets title setSize(300, 100); // "this" JFrame sets initial size setVisible(true); // "this" JFrame shows } /** The entry main() method */ public static void main(String[] args) { // Run the GUI construction in the Event-Dispatching thread for thread-safety SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new SwingCounter(); // Let the constructor do the job } }); } } 2、练习 import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SwingCalculator extends JFrame { private JTextField tfDisplay; private String numberInStr = ""; private char previousOpr = ' '; private char currentOpr = ' '; private int previousNum = 0; private int currentNum = 0; private int result = 0; private JButton[] btns; private char[] btnsText = { '7', '8', '9', '+', '4', '5', '6', '-', '1', '2', '3', '*', 'C', '0', '=', '/' }; public SwingCalculator() { tfDisplay = new JTextField("0"); tfDisplay.setEditable(false); // 设置内容右对齐 tfDisplay.setHorizontalAlignment(JTextField.RIGHT); JPanel btnPanel = new JPanel(); btnPanel.setLayout(new GridLayout(4, 4, 4, 4)); // btns只是引用,并没有内存空间 btns = new JButton[16]; for (int i = 0; i < btns.length; ++i) { //使用引用的对象时,需要为每个对象引用申请空间 //将char转为String btns[i] = new JButton(btnsText[i] + ""); if(btnsText[i] >= '0' && btnsText[i] <= '9') btns[i].addActionListener(new NumberBtnListener()); else btns[i].addActionListener(new OprBtnListener()); btnPanel.add(btns[i]); } Container cp = getContentPane(); cp.setLayout(new BorderLayout()); cp.add(tfDisplay, BorderLayout.NORTH); cp.add(btnPanel, BorderLayout.CENTER); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); //将所有component打包成一块 setTitle("calculator"); setVisible(true); requestFocus(); //聚焦 } public static void main(String[] args) { // TODO Auto-generated method stub SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new SwingCalculator(); } }); } class NumberBtnListener implements ActionListener { @Override public void actionPerformed(ActionEvent evt) { numberInStr += evt.getActionCommand(); //保存第一次输入的数字
previousNum = currentNum;
//获取输入的数字 currentNum = evt.getActionCommand().charAt(0) - '0'; tfDisplay.setText(numberInStr); } } // Operator buttons listener (inner class) class OprBtnListener implements ActionListener { @Override public void actionPerformed(ActionEvent evt) { previousOpr = currentOpr; // save currentOpr = evt.getActionCommand().charAt(0);
//字符'C’,清空所有内容 if (currentOpr == 'C') { numberInStr = ""; previousOpr = ' '; currentOpr = ' '; previousNum = 0; currentNum = 0; result = 0; tfDisplay.setText("0"); } else if (currentOpr == '=') { switch (previousOpr) { case '+': result = previousNum + currentNum; break; case '-': result = previousNum - currentNum; break; case '*': result = previousNum * currentNum; break; case '/': result = previousNum / currentNum; break; }
//计算结果保存为第一个数字,可以继续作为后面的被除数使用 currentNum = result; numberInStr = result + ""; tfDisplay.setText(result + ""); } else { numberInStr += evt.getActionCommand(); tfDisplay.setText(numberInStr); } } } }