📄 example1.html
字号:
document.cookie = 'tutorial_showLeftBar=no; path=/'; } } function toggleLeft() { showLeft(document.getElementById("LeftBar").className == "LeftBar_hidden"); document.getElementById("ToggleLeft").blur(); } function load() { showLeft(leftBar()); document.getElementById("ToggleLeft").style.display="inline"; } </script> </head><body onload="load()"> <div id=TopBar> <div id=TopBar_tr> <div id=TopBar_tl> <div id=TopBar_br> <div id=TopBar_bl> <div id=TopBar_right> <a target="_blank" href="http://java.sun.com/javase/6/download.jsp">Download the JDK</a> <br> <a href="../../search.html" target="_blank">Search the Tutorials</a> <br> <a href="javascript:toggleLeft()" id="ToggleLeft">Hide the TOC</a> </div> </div> </div> </div> </div> </div> <div class=PrintHeaders> <b>Trail:</b> Creating a GUI with JFC/Swing <br><b>Lesson:</b> Learning Swing by Example </div> <div id=LeftBar class=LeftBar_shown> <div id=Contents> <div class="linkLESSON"><a href="index.html">Learning Swing by Example</a></div><div class="nolinkAHEAD">Example One: Your First Swing Program</div><div class="linkAHEAD"><a href="example2.html">Example Two: <code>SwingApplication</code></a></div><div class="linkAHEAD"><a href="example3.html">Example Three: <code>CelsiusConverter</code></a></div><div class="linkAHEAD"><a href="example4.html">Example Four: An Improved <code>CelsiusConverter</code></a></div><div class="linkAHEAD"><a href="example5.html">Example Five: <code>LunarPhases</code></a></div><div class="linkAHEAD"><a href="example6.html">Example Six: <code>VoteDialog</code></a></div><div class="linkAHEAD"><a href="summary.html">Summary</a></div></div> </div> <div id=MainFlow class=MainFlow_indented> <span id=BreadCrumbs> <a href=../../index.html target=_top>Home Page</a> > <a href=../index.html target=_top>Creating a GUI with JFC/Swing</a> > <a href=index.html target=_top>Learning Swing by Example</a> </span> <div class=NavBit> <a target=_top href=index.html>« Previous</a> • <a target=_top href=../TOC.html>Trail</a> • <a target=_top href=example2.html>Next »</a> </div> <div id=PageTitle>Example One: Your First Swing Program</div> <blockquote><!--Example 1-->This is the first of several sections that teach Swing basics by looking at example code. This section examines the code for a simple program, <a class="SourceLink" target="_blank" href="examples/HelloWorldSwing.java"><code>HelloWorldSwing</code></a>. The examples in the following sections will become progressively more difficult as we introduce and explain more features.<P>Here's a snapshot of the <code>HelloWorldSwing</code> program:<p><center><IMG SRC="../../figures/uiswing/learn/1helloworldswing.gif" WIDTH="210" HEIGHT="49" ALIGN="BOTTOM" ALT="The HelloWorldSwing application."></center></p>And here's the full code for <code>HelloWorldSwing</code>:<blockquote><pre>import javax.swing.*; public class HelloWorldSwing { /** * Create the GUI and show it. For thread safety, * this method should be invoked from the * event-dispatching thread. */ private static void createAndShowGUI() { //Make sure we have nice window decorations. JFrame.setDefaultLookAndFeelDecorated(true); //Create and set up the window. JFrame frame = new JFrame("HelloWorldSwing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Add the ubiquitous "Hello World" label. JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label); //Display the window. frame.pack(); frame.setVisible(true); } public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); }}</pre></blockquote>This is one of the simplest Swing applications you can write. It doesn抰 do much, but the code demonstrates the basic code in every Swing program:<OL> <li>Import the pertinent packages. <li>Set up a top-level container. <li>Display the container. <li>Be thread-safe.</OL>The first line imports the main Swing package:<blockquote><pre>import javax.swing.*;</pre></blockquote>This is the only package that <code>HelloWorldSwing</code> needs. However, most Swing programs also need to import two AWT packages:<blockquote><pre>import java.awt.*;import java.awt.event.*;</pre></blockquote>These packages are required because Swing components use the AWT infrastructure, including the AWT event model. The event model governs how a component reacts to events such as button clicks and mouse motion. You'll learn more about events in the upcoming section <a class="TutorialLink" target="_top" href="example2.html#handlingEvents">Handling Events</a>.<P>Every program with a Swing GUI must have at least one top-level Swing container. A top-level Swing container provides the support Swing components need for painting and event handling. There are three commonly used top-level Swing containers: <code>JFrame</code>, <code>JDialog</code>, and (for applets) <code>JApplet</code>. Each <code>JFrame</code> object implements a single main window, and each <code>JDialog</code> implements a secondary window (a window dependent on another window). Each <code>JApplet</code> object implements an applet抯 display area within a browser window. (<code>JApplet</code> is covered in <a class="TutorialLink" target="_top" href="../components/applet.html">How to Make Applets</a>.)<P>The <code>HelloWorldSwing</code> example has only one top-level container, a <code>JFrame</code>. Imple璵ented as an instance of the <code>JFrame</code> class, a frame is a window that, by default, has dec璷rations such as a border, a title, and buttons for iconifying and closing the window. Applications with a GUI typically use at least one frame. <P>Here is the code that sets up and shows the frame:<blockquote><pre>JFrame.setDefaultLookAndFeelDecorated(true);JFrame frame = new JFrame("HelloWorldSwing");...frame.pack();frame.setVisible(true);</pre></blockquote><blockquote><hr><strong>Note:</strong> The following line of code applies decorative borders and window titles to frames. However, it works only as of v1.4. If you抮e using an earlier version, you抣l need to comment out this code.<blockquote><pre>JFrame.setDefaultLookAndFeelDecorated(true);</pre></blockquote><hr></blockquote>With the exception of top-level containers, such as <code>JFrame</code>, all Swing components descend from the <code>JComponent</code> class. <code>HelloWorldSwing</code> uses a <code>JComponent</code> descendant called <code>JLabel</code>, which displays the text <code>Hello World</code>. These two lines of code construct and then add the <code>JLabel</code> component to the frame:<blockquote><pre>JLabel label = new JLabel("Hello World");frame.getContentPane().add(label);</pre></blockquote>Note that the label is added to the frame抯 content pane instead of to the frame itself. Every top-level container has a content pane that contains, directly or indirectly, all the visible components (except for menus and window decorations) in the top-level container. <!--More information about content panes is in the Using Top-Level Containers section in lesson 3.--><blockquote><hr><strong>Version Note:</strong> We anticipate that in v1.5 invoking add on a top-level container will have the same effect as invoking it on the top-level container抯 content pane.<hr></blockquote>To make the program exit when the Close button <!--close button figure--><img src="../../images/../figures/uiswing/learn/2closebutton.gif" alt="close">is clicked, we include this code:<blockquote><pre>frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);</pre></blockquote><blockquote><hr><strong>Version Note:</strong> In older programs, instead of a call to <code>setDefaultCloseOperation</code>, you might see code like the following:<blockquote><pre>frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); }});</pre></blockquote>It still works, but unnecessarily adds a class, which bloats your program. You can find further information on window events in <a class="TutorialLink" target="_top" href="../components/frame.html">How to Make Frames (Main Windows)</a><hr></blockquote>The final bit of code in <code>HelloWorldSwing</code>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -