Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Java Swing - Components and Containment. 2 Components and Containers Components and Containers Components Components The building blocksThe building.

Similar presentations


Presentation on theme: "1 Java Swing - Components and Containment. 2 Components and Containers Components and Containers Components Components The building blocksThe building."— Presentation transcript:

1 1 Java Swing - Components and Containment

2 2 Components and Containers Components and Containers Components Components The building blocksThe building blocks Variety of uses and complexitiesVariety of uses and complexities Containers Containers The cementThe cement Hierarchical organisationHierarchical organisation Distinction is not always drawnDistinction is not always drawn

3 3 Containment hierarchies Top level containers Top level containers Intermediate containersIntermediate containers Atomic components Atomic components Viewing containment hierarchies Viewing containment hierarchies

4 4 Top-level containers At the root of every containment hierarchy At the root of every containment hierarchy All Swing programs have at least one All Swing programs have at least one Content panes Content panes Types of top-level containers Types of top-level containers FramesFrames DialogsDialogs AppletsApplets

5 5 Using Top-Level Containers To appear onscreen, every GUI component must be part of a containment hierarchy. To appear onscreen, every GUI component must be part of a containment hierarchy. A containment hierarchy is a tree of components that has a top-level container as its root. A containment hierarchy is a tree of components that has a top-level container as its root. We'll show you one in a bit. We'll show you one in a bit.

6 6 Using Top-Level Containers Each GUI component can be contained only once. Each GUI component can be contained only once. If a component is already in a container and you try to add it to another container, the component will be removed from the first container and then added to the second. If a component is already in a container and you try to add it to another container, the component will be removed from the first container and then added to the second.

7 7 Using Top-Level Containers Each top-level container has a content pane that, generally speaking, contains (directly or indirectly) the visible components in that top-level container's GUI. Each top-level container has a content pane that, generally speaking, contains (directly or indirectly) the visible components in that top-level container's GUI.

8 8 Using Top-Level Containers You can optionally add a menu bar to a top- level container. You can optionally add a menu bar to a top- level container. The menu bar is by convention positioned within the top-level container, but outside the content pane. The menu bar is by convention positioned within the top-level container, but outside the content pane. Some look and feels, such as the Mac OS look and feel, give you the option of placing the menu bar in another place more appropriate for the look and feel, such as at the top of the screen. Some look and feels, such as the Mac OS look and feel, give you the option of placing the menu bar in another place more appropriate for the look and feel, such as at the top of the screen.

9 9 Using Top-Level Containers

10 10 Using Top-Level Containers package components; import java.awt.*; import java.awt.event.*; import javax.swing.*; /* TopLevelDemo.java requires no other files. */ public class TopLevelDemo { /** /** * Create the GUI and show it. For thread safety, * Create the GUI and show it. For thread safety, * this method should be invoked from the * this method should be invoked from the * event-dispatching thread. * event-dispatching thread. */ */ private static void createAndShowGUI() { private static void createAndShowGUI() { //Create and set up the window. //Create and set up the window. JFrame frame = new JFrame("TopLevelDemo"); JFrame frame = new JFrame("TopLevelDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE ); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE ); //Create the menu bar. Make it have a green background. //Create the menu bar. Make it have a green background. JMenuBar greenMenuBar = new JMenuBar(); JMenuBar greenMenuBar = new JMenuBar(); greenMenuBar.setOpaque(true); greenMenuBar.setOpaque(true); greenMenuBar.setBackground(new Color(154, 165, 127)); greenMenuBar.setBackground(new Color(154, 165, 127)); greenMenuBar.setPreferredSize(new Dimension(200, 20)); greenMenuBar.setPreferredSize(new Dimension(200, 20)); //Create a yellow label to put in the content pane. //Create a yellow label to put in the content pane. JLabel yellowLabel = new JLabel(); JLabel yellowLabel = new JLabel(); yellowLabel.setOpaque(true); yellowLabel.setOpaque(true); yellowLabel.setBackground(new Color(248, 213, 131)); yellowLabel.setBackground(new Color(248, 213, 131)); yellowLabel.setPreferredSize(new Dimension(200, 180)); yellowLabel.setPreferredSize(new Dimension(200, 180)); //Set the menu bar and add the label to the content pane. //Set the menu bar and add the label to the content pane. frame.setJMenuBar(greenMenuBar); frame.setJMenuBar(greenMenuBar); frame.getContentPane().add(yellowLabel, BorderLayout.CENTER); frame.getContentPane().add(yellowLabel, BorderLayout.CENTER); //Display the window. //Display the window. frame.pack(); frame.pack(); frame.setVisible(true); frame.setVisible(true); } public static void main(String[] args) { public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { public void run() { createAndShowGUI(); createAndShowGUI(); } }); }); }}

11 11 Using Top-Level Containers package components; import java.awt.*; import java.awt.event.*; import javax.swing.*; /* TopLevelDemo.java requires no other files. */ public class TopLevelDemo { /** /** * Create the GUI and show it. For thread safety, * Create the GUI and show it. For thread safety, * this method should be invoked from the * this method should be invoked from the * event-dispatching thread. * event-dispatching thread. */ */ private static void createAndShowGUI() { private static void createAndShowGUI() { //Create and set up the window. //Create and set up the window. JFrame frame = new JFrame("TopLevelDemo"); JFrame frame = new JFrame("TopLevelDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create the menu bar. Make it have a green background. //Create the menu bar. Make it have a green background. JMenuBar greenMenuBar = new JMenuBar(); JMenuBar greenMenuBar = new JMenuBar(); greenMenuBar.setOpaque(true); greenMenuBar.setOpaque(true); greenMenuBar.setBackground(new Color(154, 165, 127)); greenMenuBar.setBackground(new Color(154, 165, 127)); greenMenuBar.setPreferredSize(new Dimension(200, 20)); greenMenuBar.setPreferredSize(new Dimension(200, 20)); //Create a yellow label to put in the content pane. //Create a yellow label to put in the content pane. JLabel yellowLabel = new JLabel(); JLabel yellowLabel = new JLabel(); yellowLabel.setOpaque(true); yellowLabel.setOpaque(true); yellowLabel.setBackground(new Color(248, 213, 131)); yellowLabel.setBackground(new Color(248, 213, 131)); yellowLabel.setPreferredSize(new Dimension(200, 180)); yellowLabel.setPreferredSize(new Dimension(200, 180)); //Set the menu bar and add the label to the content pane. //Set the menu bar and add the label to the content pane. frame.setJMenuBar(greenMenuBar); frame.setJMenuBar(greenMenuBar); frame.getContentPane().add(yellowLabel, BorderLayout.CENTER); frame.getContentPane().add(yellowLabel, BorderLayout.CENTER); //Display the window. //Display the window. frame.pack(); frame.pack(); frame.setVisible(true); frame.setVisible(true); } public static void main(String[] args) { public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { public void run() { createAndShowGUI(); createAndShowGUI(); } }); }); }}

12 12 Using Top-Level Containers package components; import java.awt.*; import java.awt.event.*; import javax.swing.*; /* TopLevelDemo.java requires no other files. */ public class TopLevelDemo { /** /** * Create the GUI and show it. For thread safety, * Create the GUI and show it. For thread safety, * this method should be invoked from the * this method should be invoked from the * event-dispatching thread. * event-dispatching thread. */ */ private static void createAndShowGUI() { private static void createAndShowGUI() { //Create and set up the window. //Create and set up the window. JFrame frame = new JFrame("TopLevelDemo"); JFrame frame = new JFrame("TopLevelDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create the menu bar. Make it have a green background. //Create the menu bar. Make it have a green background. JMenuBar greenMenuBar = new JMenuBar(); JMenuBar greenMenuBar = new JMenuBar(); greenMenuBar.setOpaque(true); greenMenuBar.setOpaque(true); greenMenuBar.setBackground(new Color(154, 165, 127)); greenMenuBar.setBackground(new Color(154, 165, 127)); greenMenuBar.setPreferredSize(new Dimension(200, 20)); greenMenuBar.setPreferredSize(new Dimension(200, 20)); //Create a yellow label to put in the content pane. //Create a yellow label to put in the content pane. JLabel yellowLabel = new JLabel(); JLabel yellowLabel = new JLabel(); yellowLabel.setOpaque(true); yellowLabel.setOpaque(true); yellowLabel.setBackground(new Color(248, 213, 131)); yellowLabel.setBackground(new Color(248, 213, 131)); yellowLabel.setPreferredSize(new Dimension(200, 180)); yellowLabel.setPreferredSize(new Dimension(200, 180)); //Set the menu bar and add the label to the content pane. //Set the menu bar and add the label to the content pane. frame.setJMenuBar(greenMenuBar); frame.setJMenuBar(greenMenuBar); frame.getContentPane().add(yellowLabel, BorderLayout.CENTER); frame.getContentPane().add(yellowLabel, BorderLayout.CENTER); //Display the window. //Display the window. frame.pack(); frame.pack(); frame.setVisible(true); frame.setVisible(true); } public static void main(String[] args) { public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { public void run() { createAndShowGUI(); createAndShowGUI(); } }); }); }}

13 13 Using Top-Level Containers package components; import java.awt.*; import java.awt.event.*; import javax.swing.*; /* TopLevelDemo.java requires no other files. */ public class TopLevelDemo { /** /** * Create the GUI and show it. For thread safety, * Create the GUI and show it. For thread safety, * this method should be invoked from the * this method should be invoked from the * event-dispatching thread. * event-dispatching thread. */ */ private static void createAndShowGUI() { private static void createAndShowGUI() { //Create and set up the window. //Create and set up the window. JFrame frame = new JFrame("TopLevelDemo"); JFrame frame = new JFrame("TopLevelDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create the menu bar. Make it have a green background. //Create the menu bar. Make it have a green background. JMenuBar greenMenuBar = new JMenuBar(); JMenuBar greenMenuBar = new JMenuBar(); greenMenuBar.setOpaque(true); greenMenuBar.setOpaque(true); greenMenuBar.setBackground(new Color(154, 165, 127)); greenMenuBar.setBackground(new Color(154, 165, 127)); greenMenuBar.setPreferredSize(new Dimension(200, 20)); greenMenuBar.setPreferredSize(new Dimension(200, 20)); //Create a yellow label to put in the content pane. //Create a yellow label to put in the content pane. JLabel yellowLabel = new JLabel(); JLabel yellowLabel = new JLabel(); yellowLabel.setOpaque(true); yellowLabel.setOpaque(true); yellowLabel.setBackground(new Color(248, 213, 131)); yellowLabel.setBackground(new Color(248, 213, 131)); yellowLabel.setPreferredSize(new Dimension(200, 180)); yellowLabel.setPreferredSize(new Dimension(200, 180)); //Set the menu bar and add the label to the content pane. //Set the menu bar and add the label to the content pane. frame.setJMenuBar(greenMenuBar); frame.setJMenuBar(greenMenuBar); frame.getContentPane().add(yellowLabel, BorderLayout.CENTER); frame.getContentPane().add(yellowLabel, BorderLayout.CENTER); //Display the window. //Display the window. frame.pack(); frame.pack(); frame.setVisible(true); frame.setVisible(true); } public static void main(String[] args) { public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { public void run() { createAndShowGUI(); createAndShowGUI(); } }); }); }}

14 14 Using Top-Level Containers package components; import java.awt.*; import java.awt.event.*; import javax.swing.*; /* TopLevelDemo.java requires no other files. */ public class TopLevelDemo { /** /** * Create the GUI and show it. For thread safety, * Create the GUI and show it. For thread safety, * this method should be invoked from the * this method should be invoked from the * event-dispatching thread. * event-dispatching thread. */ */ private static void createAndShowGUI() { private static void createAndShowGUI() { //Create and set up the window. //Create and set up the window. JFrame frame = new JFrame("TopLevelDemo"); JFrame frame = new JFrame("TopLevelDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create the menu bar. Make it have a green background. //Create the menu bar. Make it have a green background. JMenuBar greenMenuBar = new JMenuBar(); JMenuBar greenMenuBar = new JMenuBar(); greenMenuBar.setOpaque(true); greenMenuBar.setOpaque(true); greenMenuBar.setBackground(new Color(154, 165, 127)); greenMenuBar.setBackground(new Color(154, 165, 127)); greenMenuBar.setPreferredSize(new Dimension(200, 20)); greenMenuBar.setPreferredSize(new Dimension(200, 20)); //Create a yellow label to put in the content pane. //Create a yellow label to put in the content pane. JLabel yellowLabel = new JLabel(); JLabel yellowLabel = new JLabel(); yellowLabel.setOpaque(true); yellowLabel.setOpaque(true); yellowLabel.setBackground(new Color(248, 213, 131)); yellowLabel.setBackground(new Color(248, 213, 131)); yellowLabel.setPreferredSize(new Dimension(200, 180)); yellowLabel.setPreferredSize(new Dimension(200, 180)); //Set the menu bar and add the label to the content pane. //Set the menu bar and add the label to the content pane. frame.setJMenuBar(greenMenuBar); frame.setJMenuBar(greenMenuBar); frame.getContentPane().add(yellowLabel, BorderLayout.CENTER); frame.getContentPane().add(yellowLabel, BorderLayout.CENTER); //Display the window. //Display the window. frame.pack(); frame.pack(); frame.setVisible(true); frame.setVisible(true); } public static void main(String[] args) { public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { public void run() { createAndShowGUI(); createAndShowGUI(); } }); }); }}

15 15 Using Top-Level Containers package components; import java.awt.*; import java.awt.event.*; import javax.swing.*; /* TopLevelDemo.java requires no other files. */ public class TopLevelDemo { /** /** * Create the GUI and show it. For thread safety, * Create the GUI and show it. For thread safety, * this method should be invoked from the * this method should be invoked from the * event-dispatching thread. * event-dispatching thread. */ */ private static void createAndShowGUI() { private static void createAndShowGUI() { //Create and set up the window. //Create and set up the window. JFrame frame = new JFrame("TopLevelDemo"); JFrame frame = new JFrame("TopLevelDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create the menu bar. Make it have a green background. //Create the menu bar. Make it have a green background. JMenuBar greenMenuBar = new JMenuBar(); JMenuBar greenMenuBar = new JMenuBar(); greenMenuBar.setOpaque(true); greenMenuBar.setOpaque(true); greenMenuBar.setBackground(new Color(154, 165, 127)); greenMenuBar.setBackground(new Color(154, 165, 127)); greenMenuBar.setPreferredSize(new Dimension(200, 20)); greenMenuBar.setPreferredSize(new Dimension(200, 20)); //Create a yellow label to put in the content pane. //Create a yellow label to put in the content pane. JLabel yellowLabel = new JLabel(); JLabel yellowLabel = new JLabel(); yellowLabel.setOpaque(true); yellowLabel.setOpaque(true); yellowLabel.setBackground(new Color(248, 213, 131)); yellowLabel.setBackground(new Color(248, 213, 131)); yellowLabel.setPreferredSize(new Dimension(200, 180)); yellowLabel.setPreferredSize(new Dimension(200, 180)); //Set the menu bar and add the label to the content pane. //Set the menu bar and add the label to the content pane. frame.setJMenuBar(greenMenuBar); frame.setJMenuBar(greenMenuBar); frame.getContentPane().add(yellowLabel, BorderLayout.CENTER); frame.getContentPane().add(yellowLabel, BorderLayout.CENTER); //Display the window. //Display the window. frame.pack(); frame.pack(); frame.setVisible(true); frame.setVisible(true); } public static void main(String[] args) { public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { public void run() { createAndShowGUI(); createAndShowGUI(); } }); }); }}

16 16 Frames Window with border, title and buttons Window with border, title and buttons Making frames Making frames JFrame frame = new JFrame();JFrame frame = new JFrame(); Or extend JFrame class (often better code this way). Style defined with Style defined withUIManager.setLookAndFeel(looknfeel);SwingUtilities.updateComponentTreeUI(frame);frame.pack();

17 17 a JFrame example //this won’t compile… public static void main(String[] args) { JFrame frame = new JFrame(“A JFrame"); //Just like any //other class // do things with frame frame.setJMenuBar(menuBar);frame.setContentPane(contentPane);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // set frame size frame.pack(); // realize frame frame.setVisible(true); } // end main

18 18 a JFrame example import java.awt.*; import java.awt.event.*; import javax.swing.*; /* FrameDemo.java requires no other files. */ public class FrameDemo { /** /** * Create the GUI and show it. For thread safety, * Create the GUI and show it. For thread safety, * this method should be invoked from the * this method should be invoked from the * event-dispatching thread. * event-dispatching thread. */ */ private static void createAndShowGUI() { private static void createAndShowGUI() { //Create and set up the window. //Create and set up the window. JFrame frame = new JFrame("FrameDemo"); JFrame frame = new JFrame("FrameDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel emptyLabel = new JLabel(""); JLabel emptyLabel = new JLabel(""); emptyLabel.setPreferredSize(new Dimension(175, 100)); emptyLabel.setPreferredSize(new Dimension(175, 100)); frame.getContentPane().add(emptyLabel, BorderLayout.CENTER); frame.getContentPane().add(emptyLabel, BorderLayout.CENTER); //Display the window. //Display the window. frame.pack(); frame.pack(); frame.setVisible(true); frame.setVisible(true); } public static void main(String[] args) { public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { public void run() { createAndShowGUI(); createAndShowGUI(); } }); }); }}

19 19 a JFrame example import java.awt.*; import java.awt.event.*; import javax.swing.*; /* FrameDemo.java requires no other files. */ public class FrameDemo { /** /** * Create the GUI and show it. For thread safety, * Create the GUI and show it. For thread safety, * this method should be invoked from the * this method should be invoked from the * event-dispatching thread. * event-dispatching thread. */ */ private static void createAndShowGUI() { private static void createAndShowGUI() { //Create and set up the window. //Create and set up the window. JFrame frame = new JFrame("FrameDemo"); JFrame frame = new JFrame("FrameDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel emptyLabel = new JLabel(""); JLabel emptyLabel = new JLabel(""); emptyLabel.setPreferredSize(new Dimension(175, 100)); emptyLabel.setPreferredSize(new Dimension(175, 100)); frame.getContentPane().add(emptyLabel, BorderLayout.CENTER); frame.getContentPane().add(emptyLabel, BorderLayout.CENTER); //Display the window. //Display the window. frame.pack(); frame.pack(); frame.setVisible(true); frame.setVisible(true); } public static void main(String[] args) { public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { public void run() { createAndShowGUI(); createAndShowGUI(); } }); }); }} Adding Components to the Content Pane.

20 20 a JFrame example import java.awt.*; import java.awt.event.*; import javax.swing.*; /* FrameDemo.java requires no other files. */ public class FrameDemo { /** /** * Create the GUI and show it. For thread safety, * Create the GUI and show it. For thread safety, * this method should be invoked from the * this method should be invoked from the * event-dispatching thread. * event-dispatching thread. */ */ private static void createAndShowGUI() { private static void createAndShowGUI() { //Create and set up the window. //Create and set up the window. JFrame frame = new JFrame("FrameDemo"); JFrame frame = new JFrame("FrameDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel emptyLabel = new JLabel(""); JLabel emptyLabel = new JLabel(""); emptyLabel.setPreferredSize(new Dimension(175, 100)); emptyLabel.setPreferredSize(new Dimension(175, 100)); frame.getContentPane().add(emptyLabel, BorderLayout.CENTER); frame.getContentPane().add(emptyLabel, BorderLayout.CENTER); //Display the window. //Display the window. frame.pack(); frame.pack(); frame.setVisible(true); frame.setVisible(true); } public static void main(String[] args) { public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { public void run() { createAndShowGUI(); createAndShowGUI(); } }); }); }}

21 21 a JFrame example import java.awt.*; import java.awt.event.*; import javax.swing.*; /* FrameDemo.java requires no other files. */ public class FrameDemo { /** /** * Create the GUI and show it. For thread safety, * Create the GUI and show it. For thread safety, * this method should be invoked from the * this method should be invoked from the * event-dispatching thread. * event-dispatching thread. */ */ private static void createAndShowGUI() { private static void createAndShowGUI() { //Create and set up the window. //Create and set up the window. JFrame frame = new JFrame("FrameDemo"); JFrame frame = new JFrame("FrameDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel emptyLabel = new JLabel(""); JLabel emptyLabel = new JLabel(""); emptyLabel.setPreferredSize(new Dimension(175, 100)); emptyLabel.setPreferredSize(new Dimension(175, 100)); frame.getContentPane().add(emptyLabel, BorderLayout.CENTER); frame.getContentPane().add(emptyLabel, BorderLayout.CENTER); //Display the window. //Display the window. frame.pack(); frame.pack(); frame.setVisible(true); frame.setVisible(true); } public static void main(String[] args) { public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { public void run() { createAndShowGUI(); createAndShowGUI(); } }); }); }}

22 22 Examples 1 + 2 SwingApplication.java SwingApplication.java Messy way.Messy way. BetterSwingApp.java BetterSwingApp.java Neater way.Neater way.

23 23 Examples 1 //--- SwingApplication.java //--- //--- This is a poor example of how to make a window appear. //--- It clearly illustrates what is happening, but does not scale well. //--- The next example improves upon the design. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class SwingApplication { public Component createComponents() { final JLabel label = new JLabel("THIS IS A LABEL IN A WINDOW"); /* * 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.add(label); return pane; } public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); } catch (Exception e) { } //Create the top-level container and JFrame frame = new JFrame("SwingApplication"); //Create an instance of the SwingApplication Class SwingApplication app = new SwingApplication(); //Create the components Component contents = app.createComponents(); //Create new Jpanel for content pane JPanel contentPane = new JPanel(); //add them to the content pane of the main frame contentPane.add(contents); //Make new panel the content pane //contentPane.setOpaque(true);frame.setContentPane(contentPane); //enable the frame to close. //NOTE - This is the old way, but included as an example of // - code you may see on the web frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0);}}); //layout and then show frame.pack(); frame.setVisible(true); //replaces frame.show() / frame.hide() }}

24 24 Examples 1 //--- SwingApplication.java //--- //--- This is a poor example of how to make a window appear. //--- It clearly illustrates what is happening, but does not scale well. //--- The next example improves upon the design. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class SwingApplication { public Component createComponents() { final JLabel label = new JLabel("THIS IS A LABEL IN A WINDOW"); /* * 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.add(label); return pane; } public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); } catch (Exception e) { } //Create the top-level container and JFrame frame = new JFrame("SwingApplication"); //Create an instance of the SwingApplication Class SwingApplication app = new SwingApplication(); //Create the components Component contents = app.createComponents(); //Create new Jpanel for content pane JPanel contentPane = new JPanel(); //add them to the content pane of the main frame contentPane.add(contents); //Make new panel the content pane //contentPane.setOpaque(true);frame.setContentPane(contentPane); //enable the frame to close. //NOTE - This is the old way, but included as an example of // - code you may see on the web frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0);}}); //layout and then show frame.pack(); frame.setVisible(true); //replaces frame.show() / frame.hide() }}

25 25 Examples 1 //--- SwingApplication.java //--- //--- This is a poor example of how to make a window appear. //--- It clearly illustrates what is happening, but does not scale well. //--- The next example improves upon the design. import javax.swing.*; import java.awt.*; import java.awt.event.*; public static void main(String[] args) { try { UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName()); } catch (Exception e) { } //Create the top-level container and JFrame frame = new JFrame("SwingApplication"); //Create an instance of the SwingApplication Class SwingApplication app = new SwingApplication(); //Create the components Component contents = app.createComponents(); //Create new Jpanel for content pane JPanel contentPane = new JPanel(); //add them to the content pane of the main frame contentPane.add(contents); //Make new panel the content pane //contentPane.setOpaque(true);frame.setContentPane(contentPane); //enable the frame to close. //NOTE - This is the old way, but included as an example of // - code you may see on the web frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0);}}); //layout and then show frame.pack(); frame.setVisible(true); //replaces frame.show() / frame.hide() }}

26 26 Examples 1 //--- SwingApplication.java //--- //--- This is a poor example of how to make a window appear. //--- It clearly illustrates what is happening, but does not scale well. //--- The next example improves upon the design. import javax.swing.*; import java.awt.*; import java.awt.event.*; public static void main(String[] args) { try { UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName()); } catch (Exception e) { } //Create the top-level container and JFrame frame = new JFrame("SwingApplication"); //Create an instance of the SwingApplication Class SwingApplication app = new SwingApplication(); //Create the components Component contents = app.createComponents(); //Create new Jpanel for content pane JPanel contentPane = new JPanel(); //add them to the content pane of the main frame contentPane.add(contents); //Make new panel the content pane //contentPane.setOpaque(true);frame.setContentPane(contentPane); //enable the frame to close. //NOTE - This is the old way, but included as an example of // - code you may see on the web frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0);}}); //layout and then show frame.pack(); frame.setVisible(true); //replaces frame.show() / frame.hide() }}

27 27 Examples 1 //--- SwingApplication.java //--- //--- This is a poor example of how to make a window appear. //--- It clearly illustrates what is happening, but does not scale well. //--- The next example improves upon the design. import javax.swing.*; import java.awt.*; import java.awt.event.*; public static void main(String[] args) { try { UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName()); } catch (Exception e) { } //Create the top-level container and JFrame frame = new JFrame("SwingApplication"); //Create an instance of the SwingApplication Class SwingApplication app = new SwingApplication(); //Create the components Component contents = app.createComponents(); //Create new Jpanel for content pane JPanel contentPane = new JPanel(); //add them to the content pane of the main frame contentPane.add(contents); //Make new panel the content pane //contentPane.setOpaque(true);frame.setContentPane(contentPane); //enable the frame to close. //NOTE - This is the old way, but included as an example of // - code you may see on the web frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0);}}); //layout and then show frame.pack(); frame.setVisible(true); //replaces frame.show() / frame.hide() }}

28 28 Examples 1 //--- SwingApplication.java //--- //--- This is a poor example of how to make a window appear. //--- It clearly illustrates what is happening, but does not scale well. //--- The next example improves upon the design. import javax.swing.*; import java.awt.*; import java.awt.event.*; public static void main(String[] args) { try { //Make new panel the content pane //contentPane.setOpaque(true);frame.setContentPane(contentPane); //enable the frame to close. //NOTE - This is the old way, but included as an example of // - code you may see on the web frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0);}}); //layout and then show frame.pack(); frame.setVisible(true); //replaces frame.show() / frame.hide() }}

29 29 Examples 2 // Example Java program to show some Swing ideas in practice // First, import our swing packages (and the AWT stuff we usually need) import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; public class SwingExample extends JFrame implements ActionListener { // declare variables static JPanel contentPane; static JMenuBar menuBar; static JMenu fileMenu; JMenuItem menuItem; JButton helloButton; JButton goodbyeButton; JLabel label; BorderLayout borderLayout; public SwingExample(String title) { //Set title - passed in the constructor setTitle(title); //enable to close - The new way setDefaultCloseOperation(EXIT_ON_CLOSE); // set up menu bar menuBar = new JMenuBar(); menuBar.setLayout(new BoxLayout(menuBar, BoxLayout.X_AXIS)); fileMenu = new JMenu("File"); menuBar.add(fileMenu); menuItem = new JMenuItem("Exit"); menuItem.setActionCommand("Exit");menuItem.addActionListener(this);fileMenu.add(menuItem);setJMenuBar(menuBar); // set up label label = new JLabel("Hello"); label.setHorizontalAlignment(JLabel.CENTER); // set up buttons helloButton = new JButton("Hello"); helloButton.setActionCommand("Hi");helloButton.addActionListener(this); goodbyeButton = new JButton("Goodbye"); goodbyeButton.setActionCommand("Bye");goodbyeButton.addActionListener(this); //set up layout - not worry about now borderLayout = new BorderLayout(); borderLayout.setHgap(5);borderLayout.setVgap(10); // set layout of content pane getContentPane().setLayout(borderLayout); //add the contents getContentPane().add(label, BorderLayout.NORTH); getContentPane().add(helloButton, BorderLayout.EAST); getContentPane().add(goodbyeButton, BorderLayout.WEST); //--- Now in 1.5 we can just use add() directly //--- //add(label, BorderLayout.NORTH); //add(helloButton, BorderLayout.EAST); //add(goodbyeButton, BorderLayout.WEST); } // end constructor //Message handlers - don't worry too much at this stage. public void actionPerformed(ActionEvent e) { if ((e.getActionCommand()).equals("Exit")) {System.exit(0);} else if ((e.getActionCommand()).equals("Hi")) {label.setText("Hello");} else if ((e.getActionCommand()).equals("Bye")) {label.setText("Goodbye");} } // end actionPerformed //Where it all begins - the main method public static void main(String[] args) { //create instance of this class SwingExample example = new SwingExample("Swing Example"); //layout and display the JFrame & its contents example.pack();example.setVisible(true); } // end main } // end class Swing example

30 30 Examples 2 // Example Java program to show some Swing ideas in practice // First, import our swing packages (and the AWT stuff we usually need) import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; public class SwingExample extends JFrame implements ActionListener { public SwingExample(String title) { //Set title - passed in the constructor setTitle(title); //enable to close - The new way setDefaultCloseOperation(EXIT_ON_CLOSE); // set up menu bar menuBar = new JMenuBar(); menuBar.setLayout(new BoxLayout(menuBar, BoxLayout.X_AXIS)); fileMenu = new JMenu("File"); menuBar.add(fileMenu); menuItem = new JMenuItem("Exit"); menuItem.setActionCommand("Exit");menuItem.addActionListener(this);fileMenu.add(menuItem);setJMenuBar(menuBar); // set up label label = new JLabel("Hello"); label.setHorizontalAlignment(JLabel.CENTER); // set up buttons helloButton = new JButton("Hello"); helloButton.setActionCommand("Hi");helloButton.addActionListener(this); goodbyeButton = new JButton("Goodbye"); goodbyeButton.setActionCommand("Bye");goodbyeButton.addActionListener(this); //set up layout - not worry about now borderLayout = new BorderLayout(); borderLayout.setHgap(5);borderLayout.setVgap(10); // set layout of content pane getContentPane().setLayout(borderLayout); //add the contents getContentPane().add(label, BorderLayout.NORTH); getContentPane().add(helloButton, BorderLayout.EAST); getContentPane().add(goodbyeButton, BorderLayout.WEST); //--- Now in 1.5 we can just use add() directly //--- //add(label, BorderLayout.NORTH); //add(helloButton, BorderLayout.EAST); //add(goodbyeButton, BorderLayout.WEST); } // end constructor //Message handlers - don't worry too much at this stage. public void actionPerformed(ActionEvent e) { if ((e.getActionCommand()).equals("Exit")) {System.exit(0);} else if ((e.getActionCommand()).equals("Hi")) {label.setText("Hello");} else if ((e.getActionCommand()).equals("Bye")) {label.setText("Goodbye");} } // end actionPerformed //Where it all begins - the main method public static void main(String[] args) { //create instance of this class SwingExample example = new SwingExample("Swing Example"); //layout and display the JFrame & its contents example.pack();example.setVisible(true); } // end main } // end class Swing example

31 31 Examples 2 // Example Java program to show some Swing ideas in practice // First, import our swing packages (and the AWT stuff we usually need) import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; public class SwingExample extends JFrame implements ActionListener { // set up label label = new JLabel("Hello"); label.setHorizontalAlignment(JLabel.CENTER); // set up buttons helloButton = new JButton("Hello"); helloButton.setActionCommand("Hi");helloButton.addActionListener(this); goodbyeButton = new JButton("Goodbye"); goodbyeButton.setActionCommand("Bye");goodbyeButton.addActionListener(this); //set up layout - not worry about now borderLayout = new BorderLayout(); borderLayout.setHgap(5);borderLayout.setVgap(10); // set layout of content pane getContentPane().setLayout(borderLayout); //add the contents getContentPane().add(label, BorderLayout.NORTH); getContentPane().add(helloButton, BorderLayout.EAST); getContentPane().add(goodbyeButton, BorderLayout.WEST); //--- Now in 1.5 we can just use add() directly //--- //add(label, BorderLayout.NORTH); //add(helloButton, BorderLayout.EAST); //add(goodbyeButton, BorderLayout.WEST); } // end constructor //Message handlers - don't worry too much at this stage. public void actionPerformed(ActionEvent e) { if ((e.getActionCommand()).equals("Exit")) {System.exit(0);} else if ((e.getActionCommand()).equals("Hi")) {label.setText("Hello");} else if ((e.getActionCommand()).equals("Bye")) {label.setText("Goodbye");} } // end actionPerformed //Where it all begins - the main method public static void main(String[] args) { //create instance of this class SwingExample example = new SwingExample("Swing Example"); //layout and display the JFrame & its contents example.pack();example.setVisible(true); } // end main } // end class Swing example

32 32 Examples 2 // Example Java program to show some Swing ideas in practice // First, import our swing packages (and the AWT stuff we usually need) import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; public class SwingExample extends JFrame implements ActionListener { //add the contents getContentPane().add(label, BorderLayout.NORTH); getContentPane().add(helloButton, BorderLayout.EAST); getContentPane().add(goodbyeButton, BorderLayout.WEST); //--- Now in 1.5 we can just use add() directly //--- //add(label, BorderLayout.NORTH); //add(helloButton, BorderLayout.EAST); //add(goodbyeButton, BorderLayout.WEST); } // end constructor //Message handlers - don't worry too much at this stage. public void actionPerformed(ActionEvent e) { if ((e.getActionCommand()).equals("Exit")) {System.exit(0);} else if ((e.getActionCommand()).equals("Hi")) {label.setText("Hello");} else if ((e.getActionCommand()).equals("Bye")) {label.setText("Goodbye");} } // end actionPerformed //Where it all begins - the main method public static void main(String[] args) { //create instance of this class SwingExample example = new SwingExample("Swing Example"); //layout and display the JFrame & its contents example.pack();example.setVisible(true); } // end main } // end class Swing example

33 33 Examples 2 //Message handlers - don't worry too much at this stage. public void actionPerformed(ActionEvent e) { if ((e.getActionCommand()).equals("Exit")) {System.exit(0);} else if ((e.getActionCommand()).equals("Hi")) {label.setText("Hello");} else if ((e.getActionCommand()).equals("Bye")) {label.setText("Goodbye");} } // end actionPerformed //Where it all begins - the main method public static void main(String[] args) { //create instance of this class SwingExample example = new SwingExample("Swing Example"); //layout and display the JFrame & its contents example.pack();example.setVisible(true); } // end main } // end class Swing example

34 34 Examples 2 //Where it all begins - the main method public static void main(String[] args) { //create instance of this class SwingExample example = new SwingExample("Swing Example"); //layout and display the JFrame & its contents example.pack();example.setVisible(true); } // end main } // end class Swing example

35 35 Dialog boxes Dialog boxes More limited than frames More limited than frames Modality Modality Types of dialogs Types of dialogs JOptionPaneJOptionPane ProgressMonitorProgressMonitor JColorChooserJColorChooser JDialogJDialog

36 36 Showing dialogs JOptionPane.showXYZDialog(…) JOptionPane.showXYZDialog(…) Option and Message dialogsOption and Message dialogs JOptionPane.showMessageDialog(frame, ”Error!”, ”An error message”, JOptionPane.ERROR_MESSAGE); JOptionPane.showOptionDialog(frame, “Save?”, “A save dialog”, JOptionPane.YES_NO_CANCEL_OPTION); JOptionPane.showOptionDialog(frame, “Save?”, “A save dialog”, JOptionPane.YES_NO_CANCEL_OPTION); Input, ConfirmInput, Confirm Customisation Customisation showOptionDialog - Fairly customisableshowOptionDialog - Fairly customisable JDialog - Totally customisableJDialog - Totally customisable

37 37 Showing dialogs JOptionPane.showMessageDialog(frame, "Eggs are not supposed to be green.");

38 38 Example 3 DialogDemo.java DialogDemo.java DialogDemo.java Not looking at code in detail…Not looking at code in detail…

39 39 Example 3 //default icon, custom title int n = JOptionPane.showConfirmDialog( frame, "Would you like green eggs and ham?", "An Inane Question", JOptionPane.YES_NO_OPTION); Object[] options = {"Yes, please", "No way!"}; int n = JOptionPane.showOptionDialog(frame, "Would you like green eggs and ham?", "A Silly Question", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, //do not use a custom Icon options, //the titles of buttons options[0]); //default button title

40 40 Applets Not covered in great detail here Not covered in great detail here JApplet is a top-level container JApplet is a top-level container has menu bar and content pane supporthas menu bar and content pane support JApplet supports assistive technologies JApplet supports assistive technologies Requires Java plug-in for browser Requires Java plug-in for browser consider user groupconsider user group

41 41 Intermediate containers – Panels (or ‘panes’) Root panes Root panes Root panes Root panes The content paneThe content pane Layered panesLayered panes Glass panesGlass panes optional menu baroptional menu bar

42 42 Intermediate containers – Panels (or ‘panes’) Root panes Root panes Root panes Root panes The content paneThe content pane Layered panesLayered panes Glass panesGlass panes optional menu baroptional menu bar You get a JRootPane (whether you want it or not!) when you instantiate JInternalFrame or one of the top-level Swing containers, such as JApplet, JDialog, and JFrame. JInternalFrameJAppletJDialog JFrame

43 43 Root panes ‘Invisibly’ attached to top-level container ‘Invisibly’ attached to top-level container Created by Swing on realizing frame Created by Swing on realizing frame Manages everything between top-level container and components Manages everything between top-level container and components Places menu bar and content pane in an instance of JLayeredPane (see a couple of slides on) Places menu bar and content pane in an instance of JLayeredPane (see a couple of slides on)

44 44 Content panes Usually use a JPanel Usually use a JPanel Contains everything except menu bar for most Swing applications Contains everything except menu bar for most Swing applications Can be explicitly, or Can be explicitly, or implicitly created, see (simplified) codesee (simplified) code //Create a panel and add components to it. JPanel contentPane = new JPanel(); contentPane.add(someComponent); contentPane.add(anotherComponet); //Make it the content pane. contentPane.setOpaque(true); topLevelContainer.setContentPane(contentPane);

45 45 Example 4 TopLevelDemo.java TopLevelDemo.java Illustrates the Content Pane, and Menu Bar positioning (see slides 10 -15).Illustrates the Content Pane, and Menu Bar positioning (see slides 10 -15).

46 46 Layered panes Provided by root pane, but can also be created Provided by root pane, but can also be created Provides depth (z-buffering) to components Provides depth (z-buffering) to components ‘Depth’ is specified as integer ‘Depth’ is specified as integer Frame content (-30000, content pane, menu bar)Frame content (-30000, content pane, menu bar) Default (0, components)Default (0, components) Palette (100, toolbars and palettes)Palette (100, toolbars and palettes) Modal (200, internal dialogs)Modal (200, internal dialogs) Popup (300, external dialogs)Popup (300, external dialogs) Drag (400, component when dragged)Drag (400, component when dragged)

47 47 Layered panes Provided by root pane, but can also be created Provided by root pane, but can also be created Provides depth (z-buffering) to components Provides depth (z-buffering) to components ‘Depth’ is specified as integer ‘Depth’ is specified as integer Frame content (-30000, content pane, menu bar)Frame content (-30000, content pane, menu bar) Default (0, components)Default (0, components) Palette (100, toolbars and palettes)Palette (100, toolbars and palettes) Modal (200, internal dialogs)Modal (200, internal dialogs) Popup (300, external dialogs)Popup (300, external dialogs) Drag (400, component when dragged)Drag (400, component when dragged) overlapping components can appear one on top of the other How to use toot pane

48 48 Example 5 LayeredPaneDemo.java LayeredPaneDemo.java

49 49 Example 5 import javax.swing.*; import javax.swing.border.*; import javax.accessibility.*; import java.awt.*; import java.awt.event.*; public class LayeredPaneDemo extends JFrame { private String[] layerStrings = { "Yellow (0)", "Magenta (1)", private String[] layerStrings = { "Yellow (0)", "Magenta (1)", "Cyan (2)", "Red (3)", "Cyan (2)", "Red (3)", "Green (4)" }; "Green (4)" }; private Color[] layerColors = { Color.yellow, Color.magenta, private Color[] layerColors = { Color.yellow, Color.magenta, Color.cyan, Color.red, Color.cyan, Color.red, Color.green }; Color.green }; private JLayeredPane layeredPane; private JLayeredPane layeredPane; private JLabel dukeLabel; private JLabel dukeLabel; public LayeredPaneDemo() { public LayeredPaneDemo() { super("LayeredPaneDemo"); super("LayeredPaneDemo"); //Create and load the duke icon. //Create and load the duke icon. final ImageIcon icon = new ImageIcon("duke.gif"); final ImageIcon icon = new ImageIcon("duke.gif"); //Create and set up the layered pane. //Create and set up the layered pane. layeredPane = new JLayeredPane(); layeredPane = new JLayeredPane(); layeredPane.setPreferredSize(new Dimension(300, 310)); layeredPane.setPreferredSize(new Dimension(300, 310)); layeredPane.setBorder(BorderFactory.createTitledBorder( layeredPane.setBorder(BorderFactory.createTitledBorder( "Move the Mouse to Move Duke")); "Move the Mouse to Move Duke")); layeredPane.addMouseMotionListener(new MouseMotionAdapter() { layeredPane.addMouseMotionListener(new MouseMotionAdapter() { final int XFUDGE = 40; final int XFUDGE = 40; final int YFUDGE = 57; final int YFUDGE = 57; public void mouseEntered(MouseEvent e) { public void mouseEntered(MouseEvent e) { dukeLabel.setLocation(e.getX()-XFUDGE, e.getY()-YFUDGE); dukeLabel.setLocation(e.getX()-XFUDGE, e.getY()-YFUDGE); } public void mouseMoved(MouseEvent e) { public void mouseMoved(MouseEvent e) { dukeLabel.setLocation(e.getX()-XFUDGE, e.getY()-YFUDGE); dukeLabel.setLocation(e.getX()-XFUDGE, e.getY()-YFUDGE); } }); }); //This is the origin of the first label added. //This is the origin of the first label added. Point origin = new Point(10, 20); Point origin = new Point(10, 20); //This is the offset for computing the origin for the next label. //This is the offset for computing the origin for the next label. int offset = 35; int offset = 35; //Add several overlapping, colored labels to the layered pane //Add several overlapping, colored labels to the layered pane //using absolute positioning/sizing. //using absolute positioning/sizing. for (int i = 0; i < layerStrings.length; i++) { for (int i = 0; i < layerStrings.length; i++) { JLabel label = createColoredLabel(layerStrings[i], JLabel label = createColoredLabel(layerStrings[i], layerColors[i], origin); layerColors[i], origin); layeredPane.add(label, new Integer(i)); layeredPane.add(label, new Integer(i)); origin.x += offset; origin.x += offset; origin.y += offset; origin.y += offset; } //Create and add the Duke label to the layered pane. //Create and add the Duke label to the layered pane. dukeLabel = new JLabel(icon); dukeLabel = new JLabel(icon); dukeLabel.setBounds(15, 225, dukeLabel.setBounds(15, 225, icon.getIconWidth(), icon.getIconWidth(), icon.getIconHeight()); icon.getIconHeight()); layeredPane.add(dukeLabel, new Integer(2), 0); layeredPane.add(dukeLabel, new Integer(2), 0); //Add control pane and layered pane to frame. //Add control pane and layered pane to frame. Container contentPane = getContentPane(); Container contentPane = getContentPane(); contentPane.setLayout(new BoxLayout(contentPane, contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS)); BoxLayout.Y_AXIS)); contentPane.add(Box.createRigidArea(new Dimension(0, 10))); contentPane.add(Box.createRigidArea(new Dimension(0, 10))); contentPane.add(createControlPanel()); contentPane.add(createControlPanel()); contentPane.add(Box.createRigidArea(new Dimension(0, 10))); contentPane.add(Box.createRigidArea(new Dimension(0, 10))); contentPane.add(layeredPane); contentPane.add(layeredPane); } //Create and set up a colored label. //Create and set up a colored label. private JLabel createColoredLabel(String text, private JLabel createColoredLabel(String text, Color color, Color color, Point origin) { Point origin) { JLabel label = new JLabel(text); JLabel label = new JLabel(text); label.setVerticalAlignment(JLabel.TOP); label.setVerticalAlignment(JLabel.TOP); label.setHorizontalAlignment(JLabel.CENTER); label.setHorizontalAlignment(JLabel.CENTER); label.setOpaque(true); label.setOpaque(true); label.setBackground(color); label.setBackground(color); label.setForeground(Color.black); label.setForeground(Color.black); label.setBorder(BorderFactory.createLineBorder(Color.black)); label.setBorder(BorderFactory.createLineBorder(Color.black)); label.setBounds(origin.x, origin.y, 140, 140); label.setBounds(origin.x, origin.y, 140, 140); return label; return label; } //Create the control pane for the top of the frame. //Create the control pane for the top of the frame. private JPanel createControlPanel() { private JPanel createControlPanel() { final JCheckBox onTop = new JCheckBox("Top Position in Layer"); final JCheckBox onTop = new JCheckBox("Top Position in Layer"); onTop.setSelected(true); onTop.setSelected(true); onTop.addActionListener(new ActionListener() { onTop.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) { if (onTop.isSelected()) if (onTop.isSelected()) layeredPane.moveToFront(dukeLabel); layeredPane.moveToFront(dukeLabel); else else layeredPane.moveToBack(dukeLabel); layeredPane.moveToBack(dukeLabel); } }); }); final JComboBox layerList = new JComboBox(layerStrings); final JComboBox layerList = new JComboBox(layerStrings); layerList.setSelectedIndex(2); //Cyan layer layerList.setSelectedIndex(2); //Cyan layer layerList.addActionListener(new ActionListener () { layerList.addActionListener(new ActionListener () { public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) { int position = onTop.isSelected() ? 0 : 1; int position = onTop.isSelected() ? 0 : 1; layeredPane.setLayer(dukeLabel, layeredPane.setLayer(dukeLabel, layerList.getSelectedIndex(), layerList.getSelectedIndex(), position); position); } }); }); JPanel controls = new JPanel(); JPanel controls = new JPanel(); controls.add(layerList); controls.add(layerList); controls.add(onTop); controls.add(onTop); controls.setBorder(BorderFactory.createTitledBorder( controls.setBorder(BorderFactory.createTitledBorder( "Choose Duke's Layer and Position")); "Choose Duke's Layer and Position")); return controls; return controls; } public static void main(String[] args) { public static void main(String[] args) { JFrame frame = new LayeredPaneDemo(); JFrame frame = new LayeredPaneDemo(); frame.addWindowListener(new WindowAdapter() { frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { public void windowClosing(WindowEvent e) { System.exit(0); System.exit(0); } }); }); frame.pack(); frame.pack(); frame.setVisible(true); frame.setVisible(true); }}

50 50 Example 5 //Create and set up the layered pane. //Create and set up the layered pane. layeredPane = new JLayeredPane(); layeredPane = new JLayeredPane(); layeredPane.setPreferredSize(new Dimension(300, 310)); layeredPane.setPreferredSize(new Dimension(300, 310)); layeredPane.setBorder(BorderFactory.createTitledBorder( layeredPane.setBorder(BorderFactory.createTitledBorder( "Move the Mouse to Move Duke")); "Move the Mouse to Move Duke")); layeredPane.addMouseMotionListener(new MouseMotionAdapter() { layeredPane.addMouseMotionListener(new MouseMotionAdapter() { final int XFUDGE = 40; final int XFUDGE = 40; final int YFUDGE = 57; final int YFUDGE = 57; public void mouseEntered(MouseEvent e) { public void mouseEntered(MouseEvent e) { dukeLabel.setLocation(e.getX()-XFUDGE, e.getY()- YFUDGE); dukeLabel.setLocation(e.getX()-XFUDGE, e.getY()- YFUDGE); } public void mouseMoved(MouseEvent e) { public void mouseMoved(MouseEvent e) { dukeLabel.setLocation(e.getX()-XFUDGE, e.getY()- YFUDGE); dukeLabel.setLocation(e.getX()-XFUDGE, e.getY()- YFUDGE); } }); });

51 51 Example 5 //Create and add the Duke label to the layered pane. dukeLabel = new JLabel(icon); dukeLabel = new JLabel(icon); dukeLabel.setBounds(15, 225, dukeLabel.setBounds(15, 225, icon.getIconWidth(), icon.getIconWidth(), icon.getIconHeight()); icon.getIconHeight()); layeredPane.add(dukeLabel, new Integer(2), 0); layeredPane.add(dukeLabel, new Integer(2), 0); //Add control pane and layered pane to frame. //Add control pane and layered pane to frame. Container contentPane = getContentPane(); Container contentPane = getContentPane(); contentPane.setLayout(new BoxLayout(contentPane, contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS)); BoxLayout.Y_AXIS)); contentPane.add(Box.createRigidArea(new Dimension(0, 10))); contentPane.add(Box.createRigidArea(new Dimension(0, 10))); contentPane.add(createControlPanel()); contentPane.add(createControlPanel()); contentPane.add(Box.createRigidArea(new Dimension(0, 10))); contentPane.add(Box.createRigidArea(new Dimension(0, 10))); contentPane.add(layeredPane); contentPane.add(layeredPane); }

52 52 Example 5 //Create the control pane for the top of the frame. private JPanel createControlPanel() { private JPanel createControlPanel() { final JCheckBox onTop = new JCheckBox("Top Position in Layer"); final JCheckBox onTop = new JCheckBox("Top Position in Layer"); onTop.setSelected(true); onTop.setSelected(true); onTop.addActionListener(new ActionListener() { onTop.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) { if (onTop.isSelected()) if (onTop.isSelected()) layeredPane.moveToFront(dukeLabel); layeredPane.moveToFront(dukeLabel); else else layeredPane.moveToBack(dukeLabel); layeredPane.moveToBack(dukeLabel); } }); });

53 53 Glass panes Not structured into components Not structured into components event catchingevent catching paintingpainting Used for ‘weird’ interface behavior, rarely used. Used for ‘weird’ interface behavior, rarely used. Either created explicitly or root version used Either created explicitly or root version used

54 54 Example 6 GlassPaneDemo.java GlassPaneDemo.java

55 55 Example 6 It contains a check box that lets you set whether the glass pane is "visible" — whether it can get events and paint itself onscreen. It contains a check box that lets you set whether the glass pane is "visible" — whether it can get events and paint itself onscreen. When the glass pane is visible, it blocks all input events from reaching the components in the content pane. When the glass pane is visible, it blocks all input events from reaching the components in the content pane. It also paints a red dot in the place where it last detected a mouse-pressed event. It also paints a red dot in the place where it last detected a mouse-pressed event.

56 56 Components Content of your interface Content of your interface http://java.sun.com/docs/books/tutorial/uiswi ng/components/components.htmlhttp://java.sun.com/docs/books/tutorial/uiswi ng/components/components.htmlhttp://java.sun.com/docs/books/tutorial/uiswi ng/components/components.htmlhttp://java.sun.com/docs/books/tutorial/uiswi ng/components/components.html Created just like any class instance Created just like any class instance JButton button_ok = new JButton(“OK”);JButton button_ok = new JButton(“OK”); Range in complexity from very simple (e.g. JButton) to very detailed (e.g. JColorChooser) Range in complexity from very simple (e.g. JButton) to very detailed (e.g. JColorChooser)

57 57 Swing and AWT components - a quick reminder Mix Swing and AWT components as little as possible (not at all in most cases) Mix Swing and AWT components as little as possible (not at all in most cases) Put ‘J’ in front of everything AWT provides to get Swing’s counterpart Put ‘J’ in front of everything AWT provides to get Swing’s counterpart AWT: ButtonAWT: Button Swing: JButtonSwing: JButton

58 58 Atomic components Buttons Buttons Combo boxes Combo boxes Lists Lists Menus Menus Sliders Sliders Text Fields Text Fields Labels Labels

59 59 Atomic components Tool tips Tool tips Progress bars Progress bars Colour choosers Colour choosers File choosers File choosers Tables Tables Text Text Trees Trees

60 60 Atomic components Impossible to teach the working of every type of component Impossible to teach the working of every type of component Very few people know it all! – Swing is HUGE. Very few people know it all! – Swing is HUGE. Remember to refer to: Remember to refer to: Swing tutorialSwing tutorial The Java 2 API Documentation.The Java 2 API Documentation. The Visual index to components & containers at java.sun.com:The Visual index to components & containers at java.sun.com: http://java.sun.com/docs/books/tutorial/uiswing/components/com ponents.html http://java.sun.com/docs/books/tutorial/uiswing/components/com ponents.html http://java.sun.com/docs/books/tutorial/uiswing/components/com ponents.html http://java.sun.com/docs/books/tutorial/uiswing/components/com ponents.html

61 61 Summary Containers (Frames and Dialogs) Containers (Frames and Dialogs) HierarchyHierarchy Root PanesRoot Panes Layered PanesLayered Panes Content PanesContent Panes Glass PanesGlass Panes Components Components Lots of ‘em…Lots of ‘em… Next time Next time Layout Management.Layout Management.


Download ppt "1 Java Swing - Components and Containment. 2 Components and Containers Components and Containers Components Components The building blocksThe building."

Similar presentations


Ads by Google