码迷,mamicode.com
首页 > Windows程序 > 详细

swing

时间:2016-02-21 12:49:35      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:

摘自:
    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. 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 } }); } }

 

swing

标签:

原文地址:http://www.cnblogs.com/helloworldtoyou/p/5204708.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!