1 / 34

MIT AITI 2003 Lecture 16. Swing Part I

MIT AITI 2003 Lecture 16. Swing Part I. Let’s swing and have some fun !!!. Lecture Preview. Over the next 2 lectures, we will introduce you to the techniques necessary to build graphic user interfaces (GUI) for your applications.

branxton
Télécharger la présentation

MIT AITI 2003 Lecture 16. Swing Part I

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. MIT AITI 2003Lecture 16. Swing Part I Let’s swing and have some fun !!!

  2. Lecture Preview • Over the next 2 lectures, we will introduce you to the techniques necessary to build graphic user interfaces (GUI) for your applications. • Learning Swing basic concepts: components and containers, fonts, colors, borders, layout; • Constructing Swing interfaces; • Using the Swing Event Model.

  3. What is a Swing Application? -- A simple Greeting Swing Application

  4. import javax.swing.*; public class MyTest extends JFrame { JLabel myLabel = new JLabel(" Hello, World!"); public MyTest() { super("MyTest"); setSize(350, 100); getContentPane().add(myLabel); setVisible(true); setDefaultCloseOperation( EXIT_ON_CLOSE ); } public static void main (String args[]) { MyTest m = new MyTest(); } }

  5. Categories of GUI Classes • Jcomponents: The base class for all Swing components except top-level containers (notice it is an abstract class) • some JComponents present information or interact with the user • Examples: labels (JLabel), buttons (JButton), text fields (JTextField) • some JComponents are designed to hold other components, not present or interact, they are called Containers. • Examples: JPanel , JScrollPane • Top Level Windows: are containers that are not contained by any other containers; they can be iconified or dragged and interact with the native windowing system • Example: JFrame, JDialog (not JComponents at all)

  6. Anatomy of a JFrame Look and Feel and platform dependent Interacts with the window system The contentPane is an inner container that holds your content

  7. Swing Application Termination Any program that makes a Swing component visible, including a dialog created via JOptionPane, must explicitly exit by • calling System.exit( int code ); • using setDefaultCloseOperation( EXIT_ON_CLOSE ); to tell Swing what to do when the window system attempts to close the window, (e.g. by clicking the window close box.) Why? Because as soon as you put up a GUI window, you start a separate GUI thread that won't end when you run off the end of the main() method. the window close box

  8. Display the Greeting ApplicationTry 1, Critique • It’s too small and the colors don’t stand out. • We need to choose a custom Font and text (foreground) Color. import java.awt.Font; import java.awt.Color;

  9. Fonts • Standard constructor: Font myFont = new Font( String name, int style, int size ); • Font name: safe approach is to use a logical font name, one of • “Times New Roman”, "Serif", "Monospaced", "Dialog", "DialogInput", "Symbol" • Four font styles are present: Font.y where y is • PLAIN, BOLD, ITALIC, UNDERLINE • Font.BOLD + Font.ITALIC • Size is point size; 12 corresponds to standard printed text

  10. Colors • 13 predefined colors: Color.x where x is • orange, pink, cyan, magenta, yellow, black, blue, white, gray, lightGray, darkGray, red, green • You can define your own colors // RGB or (red-green-blue) Color ugly= new Color(30, 90, 120);

  11. Displaying the Greeting, Try 2 myFont = new Font( "Serif", Font.BOLD, 24 ); myLabel.setFont( myFont ); myLabel.setForeground( Color.red ); myLabel.setBackground( Color.white ); • Why doesn't the background change? Not all JComponents are opaque by default. • The JFrame crowds the label.

  12. Borders • In Swing, borders are objects. • The best way to get some space around our label is to give it an empty border. • The best way to create a border is to use the factory methods in class BorderFactory: import javax.swing.border.*; . . . Border empty = BorderFactory.createEmptyBorder( top,left, bottom,right);

  13. Displaying the Greeting, Try 3 JLabel background is transparent in some look & feels by default myLabel.setOpaque( true ); Border empty = BorderFactory.createEmptyBorder(10,20,10,20); myLabel.setBorder( empty ); myLabel.setHorizontalAlignment( SwingConstants.CENTER ); Add our empty border to the label and center it

  14. Building GUI with Components • As simple as our first application is, we can build some very interesting variations with little additional code. • JLabels can hold images as well as or instead of text. • A contentPane has 5 zones where you can add a component.

  15. Complex Components • A JLabel is just about as simple as a component gets. But using a more complicated component is identical. • Components encapsulate their functionality spatially and conceptually.

  16. Constructing GUIs • We will build the GUI by nesting simpler components into containers, and then combining the containers into larger containers. • JPanel is the workhorse of most complicated interfaces. It is • a good all purpose container • the standard drawing surface • a base class for many composite components

  17. Layout Management, 1 • Layout management is the process of determining the size and location of a container's components. • Java containers do not handle their own layout. They delegate that task to their layout manager, an instance of another class. • If you do not like a container's default layout manager, you can change it. Container content = getContentPane(); content.setLayout( new FlowLayout() );

  18. Layout Management, 2 • Layout management is intrinsically recursive and proceeds top down in the containment hierarchy. • If a container encloses another container, the enclosing container can not position the inner container nor size itself until it knows how big the inner container needs to be.

  19. Turning off Layout Management • Although layout managers can introduce additional complexity, they are there for a very good reason. • The effect of layout management can be turned off by eliminating a container's layout manager via a call to setLayout(null). • The user must then explicitly lay out each component in absolute pixel coordinates through calls to setSize() and setLocation() or a single call to setBounds(). • The problem with this strategy is that it lacks flexibility.

  20. Greeting Application Without Layout Management public MyTest( String dStr ) { . . . getContentPane().setLayout( null ); getContentPane().add( myLabel ); myLabel.setBounds( 50, 20, 250, 80 ); setSize( 350, 150 ); }

  21. myLabel.setBounds( 50, 20, 250, 80 ); setSize( 350, 150 ); Coordinates • Measured in pixels (e.g. 640 by 480, 1024 by 768, etc.) • Upper left hand corner is origin (0,0) • X axis goes from left to right, y from top to bottom • Each component is anchored in its parent's coordinate system. 50 20 80 250

  22. 3 Good Reasons to Use Layout Management • Often you do not know how large your application will be. Even if you call setSize(), the user can still physically resize the window of an application. • Java knows better than you how large components should be. It is hard to gauge the size of a JLabel, for instance, except by trial and error. And if you get the size correct on one system and then run it on another with a different set of fonts, the JLabel will not be correctly sized. • Once you lay out a GUI, you may want to make changes that will compromise a layout done by hand. If you use layout management, the new layout happens automatically, but if you are laying out the buttons by hand, you have an annoying task ahead of you.

  23. Size Methods • Components communicate their layout needs to their enclosing container's layout manager via the methods: • public Dimension getMinimumSize() • public Dimension getPreferredSize() • public Dimension getMaximumSize() • There are three corresponding set methods that allow you to change a component's size hints. • public Dimension setMinimumSize( Dimension d ) • Dimension d = new Dimension( int width, int height ) • public Dimension setPreferredSize( Dimension d ) • public Dimension setMaximumSize( Dimension d )

  24. Size Methods, 2 • Using these methods to change a component's size is far surer in general than using the explicit setSize() method. • The effect of a setSize() will only last until the Java environment lays the container out again. • Most components provide good default implementations for the get methods. For instance, a button sets its preferred size to accommodate its image and/or its label and font size.

  25. When does Layout Occur? Swing will automatically (re)layout a GUI • when it first becomes visible, • when a component is added or deleted, or • when a component changes its size because the user physically changes its size (by resizing the window) or because the contents have changed (for instance, changing a label).

  26. Layout Managers • There are six layout manager classes supplied by Swing. They range from the simple FlowLayout to the flexible but at times frustrating GridBagLayout. Each manager class implements a particular layout policy. • Swing containers have default layout managers. A JFrame content pane uses BorderLayout and a JPanel uses FlowLayout.

  27. FlowLayout • The FlowLayout, the simplest of the managers, simply adds components left to right until it can fit no more within its container's width. • It then starts a second line of components, fills that, starts a third, etc. • Each line is centered within the enclosing container. • FlowLayout respects each component's preferred size and will use it to override a size set by setSize().

  28. FlowLayout Example, 1 public class Flow extends JFrame { private Font labelFont; private Border labelBorder; public Flow( ) { setDefaultCloseOperation( EXIT_ON_CLOSE ); labelFont = new Font( "SansSerif",Font.BOLD,24 ); labelBorder = BorderFactory.createLineBorder(Color.red,1); getContentPane().setLayout( new FlowLayout() ); setSize(200, 200 ); }

  29. FlowLayout Example, 2 public void addLabel( String labelStr ) { JLabel label = new JLabel( labelStr ); label.setFont( labelFont ); label.setBorder( labelBorder ); getContentPane().add( label ); } public static void main (String args[]) { Flow flow = new Flow(); flow.addLabel( “Hello1" ); flow.addLabel( “Hello2" ); . . . flow.addLabel( “Hello10" ); flow.setVisible( true ); } }

  30. BorderLayout Zones North West Center East South

  31. BorderLayout Policy • You specify the zone via a second String argument in the add() method. For example, the following line of code adds the button labeled “DoIt" to the middle of a container. add( new JButton( “DoIt" ), "Center" ); // "Center" == BorderLayout.CENTER • A BorderLayout may horizontally stretch its North and South components (if they exist), vertically stretch its East and West components, and stretch the Center component both ways to accommodate its container's size and the constraints of its other four sectors. • This can be useful. If you put a JPanel in the Center zone of a container managed by a BorderLayout, the manager will always resize the JPanel to take up all extra space, which is usually what you want if you are using it as a drawing surface.

  32. Grid Layout • The GridLayout class is a layout manager that lays out a container's components in a rectangular grid. • The container is divided into equal-sized rectangles, and one component is placed in each rectangle. • In the normal constructor you specify the number of rows or columns but not both. The one that is not zero has a fixed number of elements; the other grows as you add components. getContentPane().setLayout( new GridLayout(0,2)); would set a JFrame's layout to a two column grid. The number of rows would depend on the number of added components.

  33. Exercises 1. Create a Swing application with a button saying “click me”. 2. Create a Swing application with a label saying “Sawa Sawa”, and a button saying “Karibu”. Put the button at the center of the frame, and the label at the bottom of the frame. (hint: use border layout) 3. Create a Swing application with: 1) two red color labels, font size 14, bold, your favorite font style. One label saying “mimi”, the other saying “wewe”; 2) a button (green foreground color, black background), saying “kucheza”; 3) add two labels in a JPanel, using flow layout, 4) add the JPanel object (center) and the button (north) to the contentPane, using border layout

More Related