Personal notes on Java
For other technologies like HTML, CSS, .NET, PHP, etc. check my other blog

References:


Events

One important part of swing programming  is events: check the events page.

Top Containers

For a UI Component to appear on screen it must be inserted into the content pane of a top container.
(The content pane is the main container in all frames, applets, and dialogs).

Swing provides three generally useful top-level container classes:
  1. JFrame;
  2. JDialog;
  3. JApplet;
When using these classes, you should keep these facts in mind:
  • 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. We'll show you one in a bit.
  • 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.
  • 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.
  • 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. 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.

javax.swing.JComponent

For more info: The JComponent Class

With the exception of top-level containers (like JFrame and JDialog), all Swing components whose names begin with "J" descend from the JComponent class. For example, JPanel, JScrollPane, JButton, and JTable all inherit from JComponent.
The JComponent class provides the following functionality to its descendants:

Layout Managers

ref: Using Layout Managers
Test your knowledge: Questions and Exercises: Laying Out Components within a Container 
 
A layout manager is an object that implements the java.awt.LayoutManager interface and determines the size and position of the components within a container. Although components can provide size and alignment hints, a container's layout manager has the final say on the size and position of the components within the container.

Each Layout Manager has its own peculiarities check: How to Use Various Layout Managers to get information about how to use each one.

Types

For a visual representation and more info see: A Visual Guide to Layout Managers Several AWT and Swing classes provide layout managers for general use:
  • BorderLayout: default layout for content panes. Places components in up to five areas: top, bottom, left, right, and center. All extra space is placed in the center area. Tool bars that are created using JToolBar must be created within a BorderLayout container, if you want to be able to drag and drop the bars away from their starting positions;
  • BoxLayout: puts components in a single row or column;
  • CardLayout: lets you implement an area that contains different components at different times. An alternative to using CardLayout is using a tabbed pane component;
  • FlowLayout: default layout manager for every JPanel. It simply lays out components in a single row, starting a new row if its container is not sufficiently wide;
  • GridBagLayout: if you are not using a GUI builder (GridLayout) but want to manually build your GUI then this is recommended as the next most flexible and powerful layout manager - It aligns components by placing them within a grid of cells, allowing components to span more than one cell. The rows in the grid can have different heights, and grid columns can have different widths;
  • GridLayout: places components in a grid of cells. Each component takes all the available space within its cell, and each cell is exactly the same size;
  • GroupLayout: can be used manually but it was developed to be used by GUI builder tools (ex. NetBeans IDE GUI builder uses this layout by default). This layout works by defining group of components that related to each other (ex. align components together). The GUI builder will give you visual clues when you drag and drop the components next to each-other informing you how the elements will be grouped. For examples of this visual clues check this GroupLayout Example.
  • SpringLayout: a flexible layout manager designed for use by GUI builders;

Using Layout Managers

Set

As a rule, the only containers whose layout managers you need to worry about are:
  • JPanels (default is FlowLayout)
    JPanel panel = new JPanel(new BorderLayout());
  • content panes (default is BorderLayout)
    After a container has been created, you can set its layout manager using the setLayout method. For example:
    Container contentPane = frame.getContentPane();
    contentPane.setLayout(new FlowLayout());
Note: unless you are using JToolBar, the FlowLayout and BorderLayout managers are only useful for prototyping.

Add components

Depends on the Layout Manager you are using.

The how-to section for each layout manager has details on what, if any, arguments you need to specify to the add method. Some layout managers, such as GridBagLayout and SpringLayout, require elaborate setup procedures. Many layout managers, however, simply place components based on the order they were added to their container.
Example:
pane.add(aComponent, BorderLayout.PAGE_START);


NOTE: Swing containers other than JPanel and content panes generally provide API that you should use instead of the add method. For example, instead of adding a component directly to a scroll pane (or, actually, to its viewport), you either specify the component in the JScrollPane constructor or use setViewportView.

Set Size and Alignment hints

Sometimes you need to customize the size hints that a component provides to its container's layout manager, so that the component will be laid out well.
You can invoke the component's methods for:
  • setting size hints: setMinimumSize, setPreferredSize, and setMaximumSize;
  • setting alignment hints (for example, you can specify that the top edges of two components should be aligned): setAlignmentX and setAlignmentY methods;
NOTE: Many layout managers do not pay attention to a component's requested maximum size. However, BoxLayout and SpringLayout do. Furthermore, GroupLayout provides the ability to set the minimum, preferred or maximum size explicitly, without touching the component (How to Use BoxLayout).

Tips on Choosing a Layout Manager

Check the tips at the bottom of the page: Using Layout Managers

How Layout Managers work

Layout managers basically do two things: Calculate the minimum/preferred/maximum sizes for a container and lay out the container's children.

Some methods: 
  • Container.validate: used to validate an invalid container (isValid() returns true). For a container to be valid, all the container's children must be laid out already and must all be valid also. 
  • Window.pack: validates the window and lays out the window's component hierarchy for the first time. After a component is created it is in the invalid state by default. 
  • revalidate and repaint methods: If the size of a component changes, for example following a change of font, the component must be resized and repainted by calling the revalidate and repaint methods on that component. Both revalidate and repaint are thread-safe — you need not invoke them from the event-dispatching thread.

Code samples on how to use different Layout Managers Types

check this page

Borders

For more info check the: The Border API - contains tables listing the commonly used border methods

To put a border around a JComponent, you use its setBorder method.
You can use the BorderFactory class to create most of the borders that Swing provides.
If you need a reference to a border — say, because you want to use it in multiple components — you can save it in a variable of type Border.
Example:
JPanel pane = new JPanel();
pane.setBorder(BorderFactory.createLineBorder(Color.black));

Usefull Classes:
  • javax.swing.BorderFactory: used to create most of the borders that Swing provides. Returns objects that implement the Border interface.
  • javax.swing.border.Border: interface describing an object capable of rendering a border around the edges of a swing component. You often don't need to directly use anything in the border package, except when specifying constants that are specific to a particular border class or when referring to the Border type.

Components

TextComponents

All text components extend the class javax.swing.text.JTextComponent Types of text components:
  • JEditorPane;
  • JTextPane: also extends JEditorPane. Support for different styles on the text in it.
  • JTextArea: a text component that uses the same text style for all the text in it (supports only a single foreground color, background color and font); 
  • JTextField: one line text component;


Dialogs (modal window; popup)

For convenience, several Swing component classes can directly instantiate and display dialogs:
  • JOptionPane: use it to create simple, standard dialogs (error/warning/information popups);
  • ProgressMonitor: use it to put up a dialog that shows the progress of an operation;
  • JColorChooser and JFileChooser, also supply standard dialogs;
  • To bring up a print dialog, you can use the Printing API;
  • To create a custom dialog, use the JDialog class directly;
more info here: How to Make Dialogs 

JSplitPane



  • To set the initial split position use:
    setResizeWeight(.5d);
     - a value of 0 (default), indicates the right/bottom component gets all the extra space (the left/top component acts fixed)
     - a value of 1 specifies the left/top component gets all the extra space (the right/bottom component acts fixed).


Keyboard (detecting key pressed; keys)

Usefull resources:
TODO: Check out how key bindings work.

Mouse

Detecting mouse double click

someComponent.addMouseListener(new MouseAdapter(){
 public void mouseClicked(MouseEvent event){
  if (e.getClickCount() == 2 && !e.isConsumed()) {
   e.consume();
   //handle double click. 
  } 
 }
}
ref: How to detect double-click mouse events in Swing

TODO

Sem comentários:

Enviar um comentário