Java/Swing JFC/Basics
Содержание
- 1 CelsiusConverter: the use of JButton, JTextField and JLabel
- 2 Creates two JPanels (opaque), one containing another opaque JPanel, and the other containing a non-opaque JPanel
- 3 GUI invoked from the event-dispatching thread
- 4 Hello World Swing
- 5 LunarPhases: the use of JButton, JTextField and JLabel
- 6 Separating GUI logic and business objects
- 7 Standalone GUI program that shows paint, repaint, and update
- 8 Swing Application
- 9 The revalidate method to dynamically update the
- 10 This example demonstrates the use of JButton, JTextField and JLabel
CelsiusConverter: the use of JButton, JTextField and JLabel
<source lang="java">
/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * -Redistribution of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * -Redistribution in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or intended * for use in the design, construction, operation or maintenance of any * nuclear facility. */
// v 1.3 import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.UIManager; // This example demonstrates the use of JButton, JTextField and JLabel. public class CelsiusConverter implements ActionListener {
JFrame converterFrame; JPanel converterPanel; JTextField tempCelsius; JLabel celsiusLabel, fahrenheitLabel; JButton convertTemp; // Constructor public CelsiusConverter() { // Create the frame and container. converterFrame = new JFrame("Convert Celsius to Fahrenheit"); converterPanel = new JPanel(); converterPanel.setLayout(new GridLayout(2, 2)); // Add the widgets. addWidgets(); // Add the panel to the frame. converterFrame.getContentPane() .add(converterPanel, BorderLayout.CENTER); // Exit when the window is closed. converterFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Show the converter. converterFrame.pack(); converterFrame.setVisible(true); } // Create and add the widgets for converter. private void addWidgets() { // Create widgets. tempCelsius = new JTextField(2); celsiusLabel = new JLabel("Celsius", SwingConstants.LEFT); convertTemp = new JButton("Convert..."); fahrenheitLabel = new JLabel("Fahrenheit", SwingConstants.LEFT); // Listen to events from Convert button. convertTemp.addActionListener(this); // Add widgets to container. converterPanel.add(tempCelsius); converterPanel.add(celsiusLabel); converterPanel.add(convertTemp); converterPanel.add(fahrenheitLabel); celsiusLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); fahrenheitLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); } // Implementation of ActionListener interface. public void actionPerformed(ActionEvent event) { // Parse degrees Celsius as a double and convert to Fahrenheit. int tempFahr = (int) ((Double.parseDouble(tempCelsius.getText())) * 1.8 + 32); fahrenheitLabel.setText(tempFahr + " Fahrenheit"); } // main method public static void main(String[] args) { // Set the look and feel. try { UIManager.setLookAndFeel(UIManager .getCrossPlatformLookAndFeelClassName()); } catch (Exception e) { } CelsiusConverter converter = new CelsiusConverter(); }
}
</source>
Creates two JPanels (opaque), one containing another opaque JPanel, and the other containing a non-opaque JPanel
<source lang="java">
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class OpaqueExample extends JFrame {
public OpaqueExample() { super("Opaque JPanel Demo"); setSize(400, 200); setDefaultCloseOperation(EXIT_ON_CLOSE); JPanel opaque = createNested(true); JPanel notOpaque = createNested(false); // Throw it all together getContentPane().setLayout(new FlowLayout()); getContentPane().add(opaque); getContentPane().add(notOpaque); } public static void main(String[] args) { OpaqueExample oe = new OpaqueExample(); oe.setVisible(true); } public JPanel createNested(boolean opaque) { JPanel outer = new JPanel(new FlowLayout()); JPanel inner = new JPanel(new FlowLayout()); outer.setBackground(Color.white); inner.setBackground(Color.black); inner.setOpaque(opaque); inner.setBorder(BorderFactory.createLineBorder(Color.gray)); inner.add(new JButton("Button")); outer.add(inner); return outer; }
}
</source>
GUI invoked from the event-dispatching thread
<source lang="java">
/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * -Redistribution of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * -Redistribution in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or intended * for use in the design, construction, operation or maintenance of any * nuclear facility. */
import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenuBar; /* TopLevelDemo.java requires no other files. */ public class TopLevelDemo {
/** * 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("TopLevelDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create the menu bar. Make it have a cyan background. JMenuBar cyanMenuBar = new JMenuBar(); cyanMenuBar.setOpaque(true); cyanMenuBar.setBackground(Color.cyan); cyanMenuBar.setPreferredSize(new Dimension(200, 20)); //Create a yellow label to put in the content pane. JLabel yellowLabel = new JLabel(); yellowLabel.setOpaque(true); yellowLabel.setBackground(Color.yellow); yellowLabel.setPreferredSize(new Dimension(200, 180)); //Set the menu bar and add the label to the content pane. frame.setJMenuBar(cyanMenuBar); frame.getContentPane().add(yellowLabel, BorderLayout.CENTER); //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(); } }); }
}
</source>
Hello World Swing
<source lang="java">
import javax.swing.JFrame; import javax.swing.JLabel; public class HelloWorldSwing {
public static void main(String[] args) { JFrame frame = new JFrame("HelloWorldSwing"); final JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); }
}
</source>
LunarPhases: the use of JButton, JTextField and JLabel
<source lang="java">
/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * -Redistribution of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * -Redistribution in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or intended * for use in the design, construction, operation or maintenance of any * nuclear facility. */
// v 1.3 import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URL; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.UIManager; // This example demonstrates the use of JButton, JTextField // and JLabel. public class LunarPhases implements ActionListener {
final static int NUM_IMAGES = 8; final static int START_INDEX = 3; ImageIcon[] images = new ImageIcon[NUM_IMAGES]; JPanel mainPanel, selectPanel, displayPanel; JComboBox phaseChoices = null; JLabel phaseIconLabel = null; // Constructor public LunarPhases() { // Create the phase selection and display panels. selectPanel = new JPanel(); displayPanel = new JPanel(); // Add various widgets to the sub panels. addWidgets(); // Create the main panel to contain the two sub panels. mainPanel = new JPanel(); mainPanel.setLayout(new GridLayout(2, 1, 5, 5)); mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); // Add the select and display panels to the main panel. mainPanel.add(selectPanel); mainPanel.add(displayPanel); } // Create and the widgets to select and display the phases of the moon. private void addWidgets() { // Get the images and put them into an array of ImageIcon. for (int i = 0; i < NUM_IMAGES; i++) { String imageName = "images/image" + i + ".jpg"; System.out.println("getting image: " + imageName);
// URL iconURL = ClassLoader.getSystemResource(imageName);
// ImageIcon icon = new ImageIcon(iconURL); images[i] = icon; } // Create label for displaying moon phase images and put a border around // it. phaseIconLabel = new JLabel(); phaseIconLabel.setHorizontalAlignment(JLabel.CENTER); phaseIconLabel.setVerticalAlignment(JLabel.CENTER); phaseIconLabel.setVerticalTextPosition(JLabel.CENTER); phaseIconLabel.setHorizontalTextPosition(JLabel.CENTER); phaseIconLabel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLoweredBevelBorder(), BorderFactory .createEmptyBorder(5, 5, 5, 5))); phaseIconLabel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(0, 0, 10, 0), phaseIconLabel .getBorder())); // Create combo box with lunar phase choices. String[] phases = { "New", "Waxing Crescent", "First Quarter", "Waxing Gibbous", "Full", "Waning Gibbous", "Third Quarter", "Waning Crescent" }; phaseChoices = new JComboBox(phases); phaseChoices.setSelectedIndex(START_INDEX); // Display the first image. phaseIconLabel.setIcon(images[START_INDEX]); phaseIconLabel.setText(""); // Add border around the select panel. selectPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory .createTitledBorder("Select Phase"), BorderFactory .createEmptyBorder(5, 5, 5, 5))); // Add border around the display panel. displayPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory .createTitledBorder("Display Phase"), BorderFactory .createEmptyBorder(5, 5, 5, 5))); // Add moon phases combo box to select panel and image label to // displayPanel. selectPanel.add(phaseChoices); displayPanel.add(phaseIconLabel); // Listen to events from combo box. phaseChoices.addActionListener(this); } // Implementation of ActionListener interface. public void actionPerformed(ActionEvent event) { if ("comboBoxChanged".equals(event.getActionCommand())) { // update the icon to display the new phase phaseIconLabel.setIcon(images[phaseChoices.getSelectedIndex()]); } } // main method public static void main(String[] args) { // create a new instance of LunarPhases LunarPhases phases = new LunarPhases(); // Create a frame and container for the panels. JFrame lunarPhasesFrame = new JFrame("Lunar Phases"); // Set the look and feel. try { UIManager.setLookAndFeel(UIManager .getCrossPlatformLookAndFeelClassName()); } catch (Exception e) { } lunarPhasesFrame.setContentPane(phases.mainPanel); // Exit when the window is closed. lunarPhasesFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Show the converter. lunarPhasesFrame.pack(); lunarPhasesFrame.setVisible(true); }
}
</source>
Separating GUI logic and business objects
<source lang="java">
// : c14:Separation.java // Separating GUI logic and business objects. // <applet code=Separation width=250 height=150></applet> // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; class BusinessLogic {
private int modifier; public BusinessLogic(int mod) { modifier = mod; } public void setModifier(int mod) { modifier = mod; } public int getModifier() { return modifier; } // Some business operations: public int calculation1(int arg) { return arg * modifier; } public int calculation2(int arg) { return arg + modifier; }
} public class Separation extends JApplet {
private JTextField t = new JTextField(15), mod = new JTextField(15); private JButton calc1 = new JButton("Calculation 1"), calc2 = new JButton( "Calculation 2"); private BusinessLogic bl = new BusinessLogic(2); public static int getValue(JTextField tf) { try { return Integer.parseInt(tf.getText()); } catch (NumberFormatException e) { return 0; } } class Calc1L implements ActionListener { public void actionPerformed(ActionEvent e) { t.setText(Integer.toString(bl.calculation1(getValue(t)))); } } class Calc2L implements ActionListener { public void actionPerformed(ActionEvent e) { t.setText(Integer.toString(bl.calculation2(getValue(t)))); } } // If you want something to happen whenever // a JTextField changes, add this listener: class ModL implements DocumentListener { public void changedUpdate(DocumentEvent e) { } public void insertUpdate(DocumentEvent e) { bl.setModifier(getValue(mod)); } public void removeUpdate(DocumentEvent e) { bl.setModifier(getValue(mod)); } } public void init() { Container cp = getContentPane(); cp.setLayout(new FlowLayout()); cp.add(t); calc1.addActionListener(new Calc1L()); calc2.addActionListener(new Calc2L()); JPanel p1 = new JPanel(); p1.add(calc1); p1.add(calc2); cp.add(p1); mod.getDocument().addDocumentListener(new ModL()); JPanel p2 = new JPanel(); p2.add(new JLabel("Modifier:")); p2.add(mod); cp.add(p2); } public static void main(String[] args) { run(new Separation(), 250, 100); } public static void run(JApplet applet, int width, int height) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(applet); frame.setSize(width, height); applet.init(); applet.start(); frame.setVisible(true); }
} ///:~
</source>
Standalone GUI program that shows paint, repaint, and update
<source lang="java">
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002. * All rights reserved. Software written by Ian F. Darwin and others. * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS"" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s, * pioneering role in inventing and promulgating (and standardizing) the Java * language and environment is gratefully acknowledged. * * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for * inventing predecessor languages C and C++ is also gratefully acknowledged. */
/// import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.JLabel; /** Standalone GUI program that shows paint, repaint, and update */ public class PaintMethods extends JLabel {
/** "main program" method - construct and show */ public static void main(String[] av) { final JFrame f = new JFrame("PaintMethods demo"); f.getContentPane().add("Center", new PaintMethods("Testing 1 2 3")); f.pack(); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public PaintMethods(String s) { super(s); } public void paint(Graphics g) { System.out.println("Paint"); super.paint(g); } public void repaint() { System.out.println("repaint"); super.repaint(); } public void update(Graphics g) { System.out.println("update"); super.update(g); }
}
</source>
Swing Application
<source lang="java">
/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * -Redistribution of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * -Redistribution in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or intended * for use in the design, construction, operation or maintenance of any * nuclear facility. */
// v 1.3 import java.awt.BorderLayout; import java.awt.ruponent; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.UIManager; public class SwingApplication {
private static String labelPrefix = "Number of button clicks: "; private int numClicks = 0; public Component createComponents() { final JLabel label = new JLabel(labelPrefix + "0 "); JButton button = new JButton("I"m a Swing button!"); button.setMnemonic(KeyEvent.VK_I); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { numClicks++; label.setText(labelPrefix + numClicks); } }); label.setLabelFor(button); /* * An easy way to put space between a top-level container and its * contents is to put the contents in a JPanel that has an "empty" * border. */ JPanel pane = new JPanel(); pane.setBorder(BorderFactory.createEmptyBorder(30, //top 30, //left 10, //bottom 30) //right ); pane.setLayout(new GridLayout(0, 1)); pane.add(button); pane.add(label); return pane; } public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager .getCrossPlatformLookAndFeelClassName()); } catch (Exception e) { } //Create the top-level container and add contents to it. JFrame frame = new JFrame("SwingApplication"); SwingApplication app = new SwingApplication(); Component contents = app.createComponents(); frame.getContentPane().add(contents, BorderLayout.CENTER); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); }
}
</source>
The revalidate method to dynamically update the
<source lang="java">
import java.awt.Container; import java.awt.FlowLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; public class RevalidateExample extends JFrame {
public RevalidateExample() { super("Revalidation Demo"); setSize(300, 150); setDefaultCloseOperation(EXIT_ON_CLOSE); Font font = new Font("Dialog", Font.PLAIN, 10); final JButton b = new JButton("Add"); b.setFont(font); Container c = getContentPane(); c.setLayout(new FlowLayout()); c.add(b); b.addActionListener(new ActionListener() { // Increase the size of the button"s font each time it"s clicked int size = 20; public void actionPerformed(ActionEvent ev) { b.setFont(new Font("Dialog", Font.PLAIN, ++size)); b.revalidate(); // invalidates the button & validates its root pane } }); } public static void main(String[] args) { RevalidateExample re = new RevalidateExample(); re.setVisible(true); }
}
</source>
This example demonstrates the use of JButton, JTextField and JLabel
<source lang="java">
/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * -Redistribution of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * -Redistribution in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or intended * for use in the design, construction, operation or maintenance of any * nuclear facility. */
// v 1.3 import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.UIManager; // This example demonstrates the use of JButton, JTextField and JLabel. public class CelsiusConverter2 implements ActionListener {
JFrame converterFrame; JPanel converterPanel; JTextField tempCelsius; JLabel celsiusLabel, fahrenheitLabel; JButton convertTemp; // Constructor public CelsiusConverter2() { // Create the frame and container. converterFrame = new JFrame("Convert Celsius to Fahrenheit"); converterPanel = new JPanel(); converterPanel.setLayout(new GridLayout(2, 2)); // Add the widgets. addWidgets(); // Add the panel to the frame. converterFrame.getContentPane() .add(converterPanel, BorderLayout.CENTER); // Exit when the window is closed. converterFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Show the converter. converterFrame.pack(); converterFrame.setVisible(true); } // Create and add the widgets for converter. private void addWidgets() { // Create widgets. ImageIcon icon = new ImageIcon("images/convert.gif", "Convert temperature"); tempCelsius = new JTextField(2); celsiusLabel = new JLabel("Celsius", SwingConstants.LEFT); convertTemp = new JButton(icon); fahrenheitLabel = new JLabel("Fahrenheit", SwingConstants.LEFT); celsiusLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); fahrenheitLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); // Listen to events from Convert button. convertTemp.addActionListener(this); // Add widgets to container. converterPanel.add(tempCelsius); converterPanel.add(celsiusLabel); converterPanel.add(convertTemp); converterPanel.add(fahrenheitLabel); } // Implementation of ActionListener interface. public void actionPerformed(ActionEvent event) { // Parse degrees Celsius as a double and convert to Fahrenheit. int tempFahr = (int) ((Double.parseDouble(tempCelsius.getText())) * 1.8 + 32); // Set fahrenheitLabel to new value and set font color based on the // temperature. if (tempFahr <= 32) { fahrenheitLabel .setText("<html>" + tempFahr + "° Fahrenheit</html>"); } else if (tempFahr <= 80) { fahrenheitLabel .setText("<html>" + tempFahr + "° Fahrenheit </html>"); } else { fahrenheitLabel .setText("<html>" + tempFahr + "° Fahrenheit</html>"); } } // main method public static void main(String[] args) { // set the look and feel try { UIManager.setLookAndFeel(UIManager .getCrossPlatformLookAndFeelClassName()); } catch (Exception e) { } CelsiusConverter2 converter = new CelsiusConverter2(); }
}
</source>