1 / 19

JFC and Swing JFC is short for Java Foundation Classes JFC contains a group of features for

JFC and Swing JFC is short for Java Foundation Classes JFC contains a group of features for 1. building graphical user interfaces (GUIs) 2. adding rich graphics functionality and interactivity to Java applications.

kcummings
Télécharger la présentation

JFC and Swing JFC is short for Java Foundation Classes JFC contains a group of features for

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. JFC and Swing JFC is short for Java Foundation Classes JFC contains a group of features for 1. building graphical user interfaces (GUIs) 2. adding rich graphics functionality and interactivity to Java applications. "Swing" refers to the package names for the Swing API which begin with javax.swing

  2. import javax.swing.*; public class HelloWorldSwing { 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(); } }); } }

  3. Every program with a Swing GUI must have at least one top-level Swing container. Commonly used top-level Swing containers: JFrame - implements a single main window JDialog - implements a secondary window (a window dependent on another window) JApplet - implements an applet’s display area within a browser window. JFrame frame = new JFrame("HelloWorldSwing");

  4. The code that sets up and shows the frame: JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("HelloWorldSwing"); ... frame.pack(); frame.setVisible(true);

  5. HelloWorldSwing uses a JComponent descendant called JLabel, which displays the text Hello World. These two lines of code construct and then add the JLabel component to the frame: • JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label); • label is added to the frame’s 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.

  6. This call causes the program to exit when the Close button (the x in th upper right corner) is clicked. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); In older programs, instead of the above call, the following code performed the same function: frame.addWindowListener(newWindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } });

  7. Example Two: SwingApplication.java

  8. try { UIManager.setLookAndFeel(lookAndFeel); } catch (ClassNotFoundException e) { System.err.println("Couldn't find class for specified look and feel: " + lookAndFeel); System.err.println("Did you include the L&F library in the class path?"); System.err.println("Using the default look and feel."); } catch (UnsupportedLookAndFeelException e) { System.err.println("Can't use the specified look and feel (" + lookAndFeel + ") on this platform."); System.err.println("Using the default look and feel."); } catch (Exception e) { System.err.println("Couldn't get specified look and feel (" + lookAndFeel + "), for some reason."); System.err.println("Using the default look and feel."); e.printStackTrace(); } } } /** * Create the GUI and show it. For thread safety, * this method should be invoked from the * event-dispatching thread. */ private static void createAndShowGUI() { //Set the look and feel. initLookAndFeel(); //Make sure we have nice window decorations. JFrame.setDefaultLookAndFeelDecorated(true); //Create and set up the window. JFrame frame = new JFrame("SwingApplication"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); SwingApplication app = new SwingApplication(); Component contents = app.createComponents(); frame.getContentPane().add(contents, 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(); } }); } } import javax.swing.*; import java.awt.*; import java.awt.event.*; public class SwingApplication implements ActionListener { private static String labelPrefix = "Number of button clicks: "; private int numClicks = 0; final JLabel label = new JLabel(labelPrefix + "0 "); //Specify the look and feel to use. Valid values: //null (use the default), "Metal", "System", "Motif", "GTK+" final static String LOOKANDFEEL = "System"; public Component createComponents() { JButton button = new JButton("I'm a Swing button!"); button.setMnemonic(KeyEvent.VK_I); button.addActionListener(this); 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 * * and its contents is to put the contents in a JPanel * that has an "empty" border. */ JPanel pane = new JPanel(new GridLayout(0, 1)); pane.add(button); pane.add(label); pane.setBorder(BorderFactory.createEmptyBorder( 30, //top 30, //left 10, //bottom 30) //right ); return pane; } public void actionPerformed(ActionEvent e) { numClicks++; label.setText(labelPrefix + numClicks); } private static void initLookAndFeel() { String lookAndFeel = null; if (LOOKANDFEEL != null) { if (LOOKANDFEEL.equals("Metal")) { lookAndFeel = UIManager.getCrossPlatformLookAndFeelClassName(); } else if (LOOKANDFEEL.equals("System")) { lookAndFeel = UIManager.getSystemLookAndFeelClassName(); } else if (LOOKANDFEEL.equals("Motif")) { lookAndFeel = "com.sun.java.swing.plaf.motif.MotifLookAndFeel"; } else if (LOOKANDFEEL.equals("GTK+")) { //new in 1.4.2 lookAndFeel = "com.sun.java.swing.plaf.gtk.GTKLookAndFeel"; } else { System.err.println("Unexpected value of LOOKANDFEEL specified: " + LOOKANDFEEL); lookAndFeel = UIManager.getCrossPlatformLookAndFeelClassName(); }

  9. Simpler Example: SimpleSwingButton.java

  10. import javax.swing.*; public class SimpleSwingButton { /** * Create the GUI and show it. For thread safety, this method should be * invoked from the event-dispatching thread. */ private static void createAndShowGUI() { // specify system look and feel try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { System.err.println("Using the default look and feel."); e.printStackTrace(); } //Create and set up the window. JFrame frame = new JFrame("Button Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create button labeled "I'm a Swing Button" JButton PMButton = new JButton ("I'm a Swing Button!"); PMButton.setBorder(BorderFactory.createEmptyBorder(20,20,20,20)); //T,L,B,R frame.getContentPane().add(PMButton); //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(); } }); } }

  11. Handling Events Every time the user types a character or pushes a mouse button, an event occurs. Any object can be notified of the event. All the object has to do is implement the appropriate interface and be registered as an event listener on the appropriate event source. • Every event handler requires three pieces of code: • In the declaration for the event handler class, one line of code specifies that the class either implements a listener interface or extends a class that implements a listener interface. • public class MyClass implements ActionListener { • 2. Another line of code registers an instance of the event handler class as a listener on one or more components. For example: someComponent.addActionListener(instanceOfMyClass); • The event handler class has code that implements the methods in the listener interface. For example: • public void actionPerformed(ActionEvent e) { ...//code that reacts to the action... }

  12. public class SwingApplication implements ActionListener { ... JButton button = new JButton("I'm a Swing button!"); button.addActionListener(this); .... public void actionPerformed(ActionEvent e) { numClicks++; label.setText(labelPrefix + numClicks); } }

  13. The JComponent Class The JComponent Class With the exception of top-level containers, all Swing components whose names begin with "J" descend from the JComponent class. For example, JPanel, JScrollPane, JButton, and JTable all inherit features and methods from JComponent. JFrame and JDialog don't because they implement top-level containers.

  14. The JComponent Class Customizing Component Appearance

  15. The JComponent Class Setting and Getting Component State

  16. The JComponent Class Handling Events (Writing Event Listeners)

  17. JButton

  18. Setting or Getting the Button's Contents

More Related