Other Useful Classes

The following kinds of objects are used in most graphical user interface applications.

Color — java.awt.Color

The easiest way to get a Color is to just use one of the Color class fields such as Color.red. You can also use a Color constructor that has parameters for specifying the red, green, and blue components of the color. Other constructors have an additional parameter for the alpha (opacity) component of the color.

Font — java.awt.Font

Fonts are usually created with a constructor that has parameters for the font family, the font style, and the point size.

Border — javax.swing.Border

Borders are usually created using static methods in the javax.swing.BorderFactory class. The API for the BorderFactory class is shown below.

For best results, when you want a border for a component, the component should be added to a JPanel and the border should be applied to the JPanel.

One type of border, a titled border, is a good alternative to using a label for labeling components.

Dimension — java.awt.Dimension

In most cases you do not need to set the preferred, minimum, and maximum sizes of simple components — they are set automatically. However, you often do need to set the sizes of some containers, especially scroll panes. Then you need a Dimension object to specify a size. Dimensions are usually created with a constructor that has parameters for the width and height.

String — java.lang.String

The String class is treated specially in Java. Unlike other classes, there is a Java syntax form for string literals: a sequence of characters enclosed in double quotes. Java also has an operator + that is used to concatenate strings end-to-end. When the Java compiler sees a string folowed by +, followed by an expression, the compiler can convert the expression to a string in a sensible way, no matter what its type is.

Since the compiler treats string specially, you rarely need the String constructor. The following methods are frequently useful.

The characters numbers in the substring() methods start at 0 for the first character in the string. In both versions, the returned string starts at the character indicated by the frm parameter. In the first version, everything from that point on is returned. In the second version, everything from that point up to, but not including the character indicated by the to parameter is returned.