logo
GUIs in Java Swing
The basic window
Containers and basic components
Add Remove
Visibility
Opacity
Size
Enable / Disable
Border
Tooltip
Cursor
Get an icon
Use html and unicode characters
The buttons
The text fields
Placement of components and LayoutManager
FlowLayout
GridLayout
BorderLayout

GUIs in Java Swing

The purpose of this article is to remember which are the main swing components and how to use it.

The basic window

What I call basic windows are windows, dialog boxes...
JFrameconventional window
JWindowwindow without bar
JDialogdialog box
JAppletweb applet
We must make these objects visible and give them a size to see them appear on your screen. It is possible to use pack() to ask the window itself to get its preferred size. Apart for applets, it is possible to center the position of the container via the method setLocationRelativeTo(null) with null parameter. De plus il est possible pour les JFrame de spécifier l'opération à faire au clic sur la croix via setDefaultCloseOperation , les quatre opérations possibles sont: In addition it is possible to specify the cross click operation for the JFrame using the setDefaultCloseOperation method, there are four possible operations:
DO_NOTHING_ON_CLOSEdo nothing
HIDE_ON_CLOSEmakes it invisible (default)
DISPOSE_ON_CLOSEmakes it invisible and frees resources
EXIT_ON_CLOSEterminates the program
Here is a small example:
public class hello {
    public static void main(String[] args) {
	JFrame f=new JFrame("hello window");
	f.setSize(new Dimension(200,100));
	//center the window on the screen
	f.setLocationRelativeTo(null);
	f.setVisible(true);
    }
}

Containers and basic components

Here are some useful methods common to all components.

Add Remove

Most objects extend swing container. So they can almost all contain each other. To add/remove a component contained in a container component, we use the add/remove methods of the container with the content as parameter like this:
container.add(content);
You can add multiple components in a component. Note that as the method "add" return the container itself, and so you can do:
container.add(content1).add(content2);
In addition, the components are arranged according to the LayoutManager (discussed below).

Visibility

To determine whether a component is visible or make it visible, you can use its methods setVisible/isVisible.

Opacity

A component may be opaque or not, for this its setOpaque method is used, but be careful! The component is not refreshed.

Size

The different size properties of the components are as follows.
set/getSizethe current size
set/getPreferredSizethe preferred size
set/getMinimumSizethe minimum size
set/getMaximumSizethe maximum size
These sizes are used by the LayoutManager to dispose the components.

Enable / Disable

It is possible to enable and disable components. Eg a disabled button becomes grayed out. The method used here is setEnabled. To determine whether a component is enabled, the method called is isEnabled.

Border

To add a border to the components, they have the setBorder method. The border itself can be created using the class BorderFactory.

Tooltip

To add a tooltip when mousing over a component, the method to use on it is setToolTipText.

Cursor

At the overflight of the component, it is also possible to change the mouse cursor. The method here is setCursor. To use one of the predefined cursors it is possible to do so using this method: Cursor.getPredefinedCursor(Cursor.XXX_CURSOR). So it would give:
composent.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

Get an icon

It is possible to obtain an icon using an image that is placed in the project class directory.
static final ImageIcon icon=new ImageIcon(MaClass.class.getResource("myImage.png"));

Use html and unicode characters

The string in components often accept the basic html code. Thus it is possible to set a color, text in italics. For example:
JButton b=new JButton("<html><i><font color=\"#FF0000\">I am red and italic</font></i></html>");
To use a Unicode character you enter, for example: \ u0645

The buttons

There are two families of buttons, the traditional buttons JButton. And buttons that remain pressed JToggleButton, JCheckBox and JRadioButton. These can be tested using the isSelected method.
It is possible to react to this buttons events via an actionListener. We add an actionListener which is an interface that contains only one method, void actionPerformed (ActionEvent e). So we catch the actions on the buttons as follows:
JButton b=new JButton();
b.addActionListener(new ActionListener() {
   @Override
   public void actionPerformed(ActionEvent e) {
      System.out.println("bouton pressed");
   }
});
Buttons also have a method DoClick() that simulates a click. For radio buttons, it is useful to select only one button from a group. We create a ButtonGroup object and add it using its add medthod all relevant radio button. It is good to preselect one of them by default to prevent the user does not choose any.

The text fields

JTextFielda text line
JFormattedTextFielda formatted text line (email, ip ..)
JPasswordFielda text line, replaced by stars
JTextAreamultiple lines of text
JEditorPanemultiline formatted text
JTextPanemultiline formatted text
The text fields can be editable or not. To switch from one mode to another, use setEditable.

Placement of components and LayoutManager

The LayoutManager is an object whose role is to calculate the size and position of components that are hosted. We manage the layout of a container with setLayout and getLayout.

FlowLayout

This layout manager which is almost always the default. Provides the components from left to right at their preferred size. When there is no more space it takes up from the bottom left. It is possible to change the orientation. It is also possible to change the alignment, center left right leading trailing (last two depend on the orientation).

GridLayout

This time the components are placed in a grid, a table. Its first parameter is the number of cells in height, the second, the number of cells in width. You can adjust the spacing between components horizontally hgap or vertically vgap. And once again the orientation can be changed.

BorderLayout

The JFrame default layout provides the components in five areas BorderLayout.CENTER (par defaut), BorderLayout.north, BorderLayout.south, BorderLayout.west, BorderLayout.east and only takes a component by area (it can have childrens).
Be The First To Comment.

Add a comment:





You can use these HTML tags: <br><a><i><b>