Presentation is loading. Please wait.

Presentation is loading. Please wait.

Swing JComponents.

Similar presentations


Presentation on theme: "Swing JComponents."— Presentation transcript:

1 Swing JComponents

2 Layout Managers Java’s layout managers provide a level of abstraction to automatically map your user interface on all window systems. The UI components are placed in containers. Each container has a layout manager to arrange the UI components within the container. Layout managers are set in containers using the setLayout(LayoutManager) method in a container.

3 Layout Managers 2 Layout managers automate the positioning of components within containers. They free the programmer from the difficult task of figuring out the space needed for each component and the pixel coordinate positions for each component. The layout manager looks at the size of its container and the sizes of the container's components. It then tries to fit the components neatly into the container. If a user resizes the window, the layout manager takes that into account and adjusts the layout accordingly. If a programmer adjusts a component's size (e.g., by changing a label's font size), the layout manager takes that into account and adjusts the layout accordingly.

4 Layout Managers The four most common layout manager classes:
3 The four most common layout manager classes: FlowLayout BorderLayout GridLayout GridBagLayout All of these layout manager classes are in the java.awt package so import that package.

5 Assigning the Layout Manager
4 To assign a particular layout manager to a JFrame window, call the setLayout method as follows: setLayout(new <layout-manager-class>()); In the above code template, replace <layout­manager­class> by one of the layout manager classes (e.g., FlowLayout, BorderLayout, GridLayout). If setLayout is not called, then the BorderLayout manager is used (because that's the default layout manager for a JFrame window).

6 FlowLayout Manager 5 The FlowLayout class implements a simple one-compartment layout scheme that allows multiple components to be inserted into the compartment. When a component is added to the compartment, it is placed to the right of any components that were previously added to the compartment. If there is not enough room to add a component to the right of previously added components, then the new component is placed on the next line (i.e., it "flows" to the next line).

7 JFrame Example public class FrameTester {
public static void main (String args[]) { JFrame f = new JFrame ("JFrame Example"); Container c = f.getContentPane(); c.setLayout (new FlowLayout()); for (int i = 0; i < 5; i++) { c.add (new JButton ("No")); c.add (new Button ("Batter")); } c.add (new JLabel ("Swing")); f.setSize (300, 200); f.show(); 7

8 FlowLayout Alignment 6 By default, components are placed in a FlowLayout container using top, center alignment. There's no way to change the vertical alignment. But there is a way to change the horizontal alignment. To do so, insert one of the FlowLayout alignment constants (FlowLayout.LEFT, FlowLayout.CENTER, FlowLayout.RIGHT) in the FlowLayout constructor call. For example, here's how to specify left alignment: setLayout(new FlowLayout(FlowLayout.LEFT));

9 BorderLayout Manager 8 The BorderLayout manager provides five regions/compartments in which to insert components. The sizes of the five regions are determined at run time, and they're based on the contents of each region. Thus, if the west region contains a long label, the layout manager attempts to widen the west region. Likewise, if the west region contains a short label, the layout manager attempts to narrow the west region.

10 BorderLayout Manager 11 To add a component to a BorderLayout region, call the container's add method like this: add(<component>, <region>); Replace <component> by a component (a JLabel object, a JButton object, etc.) and replace <region> by one of these named constants: BorderLayout.NORTH, BorderLayout.SOUTH, BorderLayout.WEST, BorderLayout.EAST, BorderLayout.CENTER In the add method call, if the region argument is omitted, then the center region is used (because that's the default region). With a BorderLayout container, you can add only five components total, one for each of the five regions. If you add a component to a region that already has a component, then the new component overlays the old component.

11 AfricanCountries Program with Buttons
12 import javax.swing.*; import java.awt.*; public class AfricanCountries extends JFrame { private static final int WIDTH = 325; private static final int HEIGHT = 200; public AfricanCountries() setTitle("African Countries"); setSize(WIDTH, HEIGHT); setLayout(new BorderLayout()); setDefaultCloseOperation(EXIT_ON_CLOSE); add(new JButton("Tunisia"), BorderLayout.NORTH); add(new JButton("<html>South<br />Africa</html>"), BorderLayout.SOUTH); add(new JButton("Western Sahara"), BorderLayout.WEST); add(new JButton("Central African Republic"), BorderLayout.CENTER); add(new JButton("Somalia"), BorderLayout.EAST); setVisible(true); } // end AfricanCountries constructor //************************************** public static void main(String[] args) new AfricanCountries(); } // end main } // end class AfricanCountries

12 Exercise Program this The buttons set the colour of the left hand pane

13 Label Alignment 14 To specify a label's alignment within a BorderLayout region, instantiate the label with an alignment constant like this: new JLabel(<label's-text>, <alignment-constant>) Replace <alignment-constant> by one of these named constants: SwingConstants.LEFT, SwingConstants.CENTER, SwingConstants.RIGHT Here's an example that adds a center-aligned label to a BorderLayout north region: add(new JLabel("Tunisia", SwingConstants.CENTER), BorderLayout.NORTH);

14 GridLayout Manager 16 The GridLayout manager lays out a container's components in a rectangular grid. The grid is divided into equal-sized cells. Each cell can hold only one component. To specify the use of a GridLayout manager for a particular container, call setLayout like this: setLayout(new GridLayout(rows, cols, hGap, vGap)); # of rows Gap between columns, in pixels. Default value = 0. # of columns Gap between rows, in pixels. Default value = 0.

15 horizontal gap = 5 pixels
GridLayout Manager 18 Here's an example that displays a two-row, three-column table with six buttons: setLayout(new GridLayout(2, 3, 5, 5)); add(new JButton("1")); add(new JButton("2")); add(new JButton("3")); add(new JButton("4")); add(new JButton("5")); add(new JButton("6")); vertical gap = 5 pixels horizontal gap = 5 pixels

16 Setting text display with Alignment property of text field.

17 Embedded Layout Managers
26 What layout manager scheme should be used for this math-calculator window? The GridLayout manager is usually pretty good at positioning components in an organized tabular fashion, but it's limited by the fact that each of its cells must be the same size.

18 JPanel Class 28 A JPanel container object is a generic storage area for components. If you have a complicated window with lots of components, you may want to compartmentalize them by storing groups of components in JPanel containers. JPanel containers are particularly useful with GridLayout and BorderLayout windows because each compartment in those layouts can store only one component. If you need a compartment to store more than one component, let that one component be a JPanel container, and put multiple components into the JPanel container.

19 JPanel Class When using a JPanel container, do these things:
29 When using a JPanel container, do these things: Since JPanel is in the javax.swing package, import that package. Instantiate a JPanel object: JPanel <JPanel-reference> = new JPanel(<layout-manager>) Add the components to the JPanel object: <JPanel-reference>.add(<component>) Add the JPanel object to the window: add(<JPanel-reference>) Optional argument. The default is FlowLayout with center alignment. If the JPanel object uses a BorderLayout, then add a region argument. If the JFrame object uses a BorderLayout, then add a region argument.

20 JPanel Class 30 For example, to create the top-left cell's panel in the math-calculations program, do this in the createContents method: xPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); xPanel.add(xLabel); xPanel.add(xBox); add(xPanel);

21 This MathCalculator program uses embedded layout managers to display square root and logarithm calculations. 31 import javax.swing.*; import java.awt.*; import java.awt.event.*; public class MathCalculator extends JFrame { private static final int WIDTH = 380; private static final int HEIGHT = 110; private JTextField xBox; // user's input value private JTextField xSqrtBox; // generated square root private JTextField xLogBox; // generated logarithm //*************************************** public MathCalculator() setTitle("Math Calculator"); setSize(WIDTH, HEIGHT); setDefaultCloseOperation(EXIT_ON_CLOSE); createContents(); setVisible(true); } // end MathCalculator constructor

22 MathCalculator Program
32 //************************************** // Create components and add to window. private void createContents() { JPanel xPanel; // holds x label and its text box JPanel xSqrtPanel; // holds "sqrt x" label and its text box JPanel xLogPanel; // holds "log x" label and its text box JLabel xLabel; JButton xSqrtButton; JButton xLogButton; Listener listener; setLayout(new GridLayout(2, 2)); // Create the x panel: xLabel = new JLabel("x:"); xBox = new JTextField(8); xPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); xPanel.add(xLabel); xPanel.add(xBox);

23 MathCalculator Program
33 // Create the square-root panel: xSqrtButton = new JButton("sqrt x"); xSqrtBox = new JTextField(8); xSqrtBox.setEditable(false); xSqrtPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); xSqrtPanel.add(xSqrtButton); xSqrtPanel.add(xSqrtBox); // Create the logarithm panel: xLogButton = new JButton("log x"); xLogBox = new JTextField(8); xLogBox.setEditable(false); xLogPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); xLogPanel.add(xLogButton); xLogPanel.add(xLogBox); // Add panels to the window: add(xPanel); add(xSqrtPanel); add(new JLabel()); // dummy component add(xLogPanel);

24 MathCalculator Program
34 listener = new Listener(); xSqrtButton.addActionListener(listener); xLogButton.addActionListener(listener); } // end createContents //*************************************** // Inner class for event handling. private class Listener implements ActionListener { public void actionPerformed(ActionEvent e) double x; // numeric value for user entered x double result; // calculated value try x = Double.parseDouble(xBox.getText()); } catch (NumberFormatException nfe) x = -1; // indicates an invalid x

25 MathCalculator Program
35 if (e.getActionCommand().equals("sqrt x")) { if (x < 0) xSqrtBox.setText("undefined"); } else result = Math.sqrt(x); xSqrtBox.setText(String.format("%7.5f", result)); } // end if else // calculate logarithm xLogBox.setText("undefined"); result = Math.log(x); xLogBox.setText(String.format("%7.5f", result)); getActionCommand retrieves the label of the button that was clicked.

26 MathCalculator Program
36 } // end else } // end actionPerformed } // end class Listener //************************************** public static void main(String[] args) { new MathCalculator(); } // end main } // end class MathCalculator


Download ppt "Swing JComponents."

Similar presentations


Ads by Google