Subscribe

RSS Feed (xml)

Powered By

Skin Design:
Free Blogger Skins

Powered by Blogger

Monday, November 19, 2007

java Font

Description

The java.awt.Font class is used to create Font objects to set the font for drawing text, labels, text fields, buttons, etc.

Generic Font Names

There are three logical/generic font names. Java will select a font in the system that matches the general characteristics of the logical font.

serifThis text is in a serif font. Often used for blocks of text (eg, Times).
sansserifThis text is in a SansSerif font. Often used for titles (eg, Arial or Helvetica).
monospacedThis text is in a Monospaced font, often used for computer text (eg, Courier).

You can also get a list of the system fonts on the host computer. See below.

Constructor

Font f = new Font(name, style, size);

String nameint styleint size
"serif"
"sansserif"
"monospaced"

or a system font.
Font.PLAIN
Font.BOLD
Font.ITALIC
Font.BOLD+Font.ITALIC
Integer point size -- typically in range 10-48.

Example

JButton b = new JButton("OK");
b.setFont(new Font("sansserif", Font.BOLD, 32));

Available system fonts

For maximum portability, use the generic font names, but you can use any font installed in the system. It is suggested to use a font family name, and create the font from that, but you can also use the fonts directly. You can get an array of all available font family names or all fonts.

// Font info is obtained from the current graphics environment.
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();

//--- Get an array of font names (smaller than the number of fonts)
String[] fontNames = ge.getAvailableFontFamilyNames();

//--- Get an array of fonts. It's preferable to use the names above.
Font[] allFonts = ge.getAllFonts();

Using Fonts for Graphics

Font f;
f = new Font(String name, int style, int size); // creates a new font

name is "Serif", "SansSerif", or "Monospaced", or a font on the system. style is Font.PLAIN. Font.BOLD, Font.ITALIC, or Font.BOLD+Font.ITALIC. size is the point size, typically in the range 8-48.

Example

Font big = new Font("SansSerif", Font.Bold, 48);
. . .
g.setFont(big);
g.drawString("Greetings Earthling");

Unicode fonts

If you're running a recent version of Windows, you probably already have a Unicode font installed, Arial Unicode MS, which is a very extensive Unicode font. If you're not running windows, you can get a the Bitstream Cyberbit font, which is quite complete (about 30,000 characters), but lacks a few of the the lesser used characters (eg, Old Cyrillic).

Windows installation instructions:

  1. Download from ftp://ftp.netscape.com/pub/communicator/extras/fonts/windows/Cyberbit.ZIP [6.3MB Zipped]. It's also available other places on the Internet. It was originally written by Bitstream, but they no longer offer it for free download.
  2. Unzip into a temporary directory.
  3. Start the Fonts control panel, and add Bitstream Cyberbit font from that directory.

explain java.awt.Polygon in java

Straight-sided shapes (eg, triangles) can be created with Polygon class and the Graphics drawPolygon or fillPolygon methods. Add each vertex as an (x, y) pair.

Polygon poly = new Polygon();  // declare and create
poly.addPoint(x, y); // add points to polygon
. . .
g.drawPolygon(poly);

The polygon coordinates can be translated with:

poly.translate(deltaX, deltaY);

There is also a Polygon constructor which takes arrays of points:

 Polygon p = new Polygon(int[] xPoints, int[] yPoints, int nPoints);

Drawing an image using ImageIcon in java

Use java.awt.ImageIcon to load and draw JPEG, GIF, or PNG images.

java.awt.Color Class

Predefined colors (lowercase without underscores for pre-Java 1.4) Color.BLACK, Color.WHITE, Color.DARK_GRAY, Color.GRAY, Color.LIGHT_GRAY, Color.BLUE, Color.CYAN, Color.GREEN, Color.RED, Color.MAGENTA, Color.PINK, Color.ORANGE, Color.YELLOW, Color.BLUE, Color.CYAN
Creating a color c = new Color(int r, int g, int b); // creates a new color with RGB values (each 0-255)
Example: Color mediumBlue = new Color(128, 128, 255);

explain java.awt.Graphics Class - Basic drawing methods

Draw on a JComponent or JPanel by overriding paintComponent(). Assume g is a Graphics object, and all variables are type int unless otherwise declared. Angles (int startAngle, arcAngle) are in degrees counterclockwise from 3 o'clock. These methods use (x,y) at the top, left, corner and a width and height of the bounding box (except drawString() and drawLine()).

g.drawLine(x1, y1, x2, y2);
g.drawRect(x, y, width, height); // (x,y) is upper left corner
g.fillRect(x, y, width, height);
g.drawOval(x, y, width, height);
g.fillOval(x, y, width, height);
g.drawArc( x, y, width, height, startAngle, arcAngle);
g.fillArc( x, y, width, height, startAngle, arcAngle);
g.drawString(String s, x, y); // Draws s with the left base at (x,y)

g.setColor(Color c); // All drawing after this uses the Color c.
g.setFont(Font f); // All drawing after this uses the Font f.

g.drawPolyline(int[] xPoints, int[] yPoints, nPoints); // Draws line
g.drawPolygon( int[] xPoints, int[] yPoints, nPoints); // Draws polygon
g.drawPolygon( poly); // draws polygon, same for fillPolygon.
g.fillPolygon( int[] xPoints, int[] yPoints, nPoints); // Fills polygon

Graphics methods and related classes in java

A summary of java.awt.Graphics methods for drawing shapes, text, ... Other classes define more advanced graphics, eg, javax.swing.Graphics2D. Related classes: Fonts, Images - ImageIcon

java.awt.Graphics Class - Basic drawing methods

Draw on a JComponent or JPanel by overriding paintComponent(). Assume g is a Graphics object, and all variables are type int unless otherwise declared. Angles (int startAngle, arcAngle) are in degrees counterclockwise from 3 o'clock. These methods use (x,y) at the top, left, corner and a width and height of the bounding box (except drawString() and drawLine()).

g.drawLine(x1, y1, x2, y2);
g.drawRect(x, y, width, height); // (x,y) is upper left corner
g.fillRect(x, y, width, height);
g.drawOval(x, y, width, height);
g.fillOval(x, y, width, height);
g.drawArc( x, y, width, height, startAngle, arcAngle);
g.fillArc( x, y, width, height, startAngle, arcAngle);
g.drawString(String s, x, y); // Draws s with the left base at (x,y)

g.setColor(Color c); // All drawing after this uses the Color c.
g.setFont(Font f); // All drawing after this uses the Font f.

g.drawPolyline(int[] xPoints, int[] yPoints, nPoints); // Draws line
g.drawPolygon( int[] xPoints, int[] yPoints, nPoints); // Draws polygon
g.drawPolygon( poly); // draws polygon, same for fillPolygon.
g.fillPolygon( int[] xPoints, int[] yPoints, nPoints); // Fills polygon

java.awt.Color Class

Predefined colors (lowercase without underscores for pre-Java 1.4) Color.BLACK, Color.WHITE, Color.DARK_GRAY, Color.GRAY, Color.LIGHT_GRAY, Color.BLUE, Color.CYAN, Color.GREEN, Color.RED, Color.MAGENTA, Color.PINK, Color.ORANGE, Color.YELLOW, Color.BLUE, Color.CYAN
Creating a color c = new Color(int r, int g, int b); // creates a new color with RGB values (each 0-255)
Example: Color mediumBlue = new Color(128, 128, 255);

Drawing an image using ImageIcon

Use java.awt.ImageIcon to load and draw JPEG, GIF, or PNG images.

java.awt.Polygon

Straight-sided shapes (eg, triangles) can be created with Polygon class and the Graphics drawPolygon or fillPolygon methods. Add each vertex as an (x, y) pair.

Polygon poly = new Polygon();  // declare and create
poly.addPoint(x, y); // add points to polygon
. . .
g.drawPolygon(poly);

The polygon coordinates can be translated with:

poly.translate(deltaX, deltaY);

There is also a Polygon constructor which takes arrays of points:

 Polygon p = new Polygon(int[] xPoints, int[] yPoints, int nPoints);

define java GridBagLayout

gbag = new GridBagLayout(); Creates GridBagLayout.

Must add with GridBagConstraints object (gbc below). Can (carefully) reuse same gbc object.
gbc = new GridBagConstraints(); Creates a new GridBagConsraints object.
gbc.gridx = i; Column, counting from 0. Always start at 0. Don't use default (RELATIVE).
gbc.gridy = i; Column, counting from 0. Always start at 0. Don't use default (RELATIVE)..
gbc.gridwidth = i; Number of columns wide (default 1).
gbc.gridheight = i; Number of rows high (default 1).
gbc.weightx = d; Relative horizontal space to allocate if container expands. Default 0.0.
gbc.weighty = d; Relative vertical space to allocate if container expands. Default 0.0.
gbc.fill = fill; How to expand comp if space larger than preferred size. fill can be GridBagConstraints.NONE, GridBagConstraints.VERTICAL, GridBagConstraints.HORIZONTAL, GridBagConstraints.BOTH.
gbc.anchor = anch; If component doesn't fill the space, tells how it should be aligned. anch can be one of these GridBagConstraints constants: CENTER (default), NORTH, SOUTH, NORTHEAST, SOUTHWEST, EAST, WEST, SOUTHEAST, NORTHWEST
gbc.insets = ins; Space around component. Eg, gbc.insets = new Insets(10,5,5,10);
gbc.ipadx = i; Horizontal padding internal to component. Can be negative!
gbc.ipady = i; Vertical padding internal to component. Can be negative!

CardLayout in java


Used to produce installer or wizard style interface as steps in process, or to select palette. Use JTabbedPanel if user should have control.
crdMgr = new CardLayout(); Sets layout to CardLayout.
crdMgr = new CardLayout(h, v)); Also can specify horizontal and vertical padding.

p.add(cardPanel); Adds next card to panel.

p.add(cardPanel, name); Adds next card to panel. Use String name to select it later.

crdMgr.first(p); Panel p displays the first card in the layout of p.

crdMgr.next(p); Panel p displays the next card in the layout of p.

crdMgr.previous(p); Panel p displays the previous card in the layout of p.

crdMgr.last(p); Panel p displays the last card in the layout of p.

crdMgr.show(p, name); Panel p displays card with String name name in panel p.

define java BoxLayout, Box

boxl = new BoxLayout(p, dir); Creates layout for container p. dir is BoxLayout.X_AXIS BoxLayout.Y_AXIS. Note: must have already created p.
box = new Box(dir); Creates a Container with vertical or horizontal layout.

p.add(widget); Adds widget to the next position.

These static Box methods create useful spacing components, which can be used in other layouts.

Box.createVerticalStrut(n) Creates a vertical spacer n pixels high.

Box.createHorizontalStrut(n) Creates a horizontal spacer n pixels wide.

Box.createRigidArea(dim) Spacer with width and height. dim is Dimension object, eg, new Dimension(10, 0).

Box.createHorizontalGlue() Creates expandable horizontal space.

Box.createVerticalGlue() Creates expandable vertical space.

new Box.Filler(mn,prf,mx) Creates a Box.Filler with min, preferred, and max sizes, each is Dimension object.

define and declaration of BoxLayout, CardLayout, GridbagLayout in java

Layout, layo, becomes that layout manager for container p (a JPanel or Container) with the following.

   p.setLayout(layo);

Layouts (BoxLayout, CardLayout, GridbagLayout)

BoxLayout, Box - Lays out components in single row or col. Add "glue" and rigid areas to control spacing.
boxl = new BoxLayout(p, dir); Creates layout for container p. dir is BoxLayout.X_AXIS BoxLayout.Y_AXIS. Note: must have already created p.
box = new Box(dir); Creates a Container with vertical or horizontal layout.

p.add(widget); Adds widget to the next position.

These static Box methods create useful spacing components, which can be used in other layouts.

Box.createVerticalStrut(n) Creates a vertical spacer n pixels high.

Box.createHorizontalStrut(n) Creates a horizontal spacer n pixels wide.

Box.createRigidArea(dim) Spacer with width and height. dim is Dimension object, eg, new Dimension(10, 0).

Box.createHorizontalGlue() Creates expandable horizontal space.

Box.createVerticalGlue() Creates expandable vertical space.

new Box.Filler(mn,prf,mx) Creates a Box.Filler with min, preferred, and max sizes, each is Dimension object.
CardLayout - Panels are placed on top of each other like stack of cards -- only one visible at a time.

Used to produce installer or wizard style interface as steps in process, or to select palette. Use JTabbedPanel if user should have control.
crdMgr = new CardLayout(); Sets layout to CardLayout.
crdMgr = new CardLayout(h, v)); Also can specify horizontal and vertical padding.

p.add(cardPanel); Adds next card to panel.

p.add(cardPanel, name); Adds next card to panel. Use String name to select it later.

crdMgr.first(p); Panel p displays the first card in the layout of p.

crdMgr.next(p); Panel p displays the next card in the layout of p.

crdMgr.previous(p); Panel p displays the previous card in the layout of p.

crdMgr.last(p); Panel p displays the last card in the layout of p.

crdMgr.show(p, name); Panel p displays card with String name name in panel p.
GridBagLayout - Panel divided into rows&cols of possibly unequal size. Overall best, but difficult.
gbag = new GridBagLayout(); Creates GridBagLayout.

Must add with GridBagConstraints object (gbc below). Can (carefully) reuse same gbc object.
gbc = new GridBagConstraints(); Creates a new GridBagConsraints object.
gbc.gridx = i; Column, counting from 0. Always start at 0. Don't use default (RELATIVE).
gbc.gridy = i; Column, counting from 0. Always start at 0. Don't use default (RELATIVE)..
gbc.gridwidth = i; Number of columns wide (default 1).
gbc.gridheight = i; Number of rows high (default 1).
gbc.weightx = d; Relative horizontal space to allocate if container expands. Default 0.0.
gbc.weighty = d; Relative vertical space to allocate if container expands. Default 0.0.
gbc.fill = fill; How to expand comp if space larger than preferred size. fill can be GridBagConstraints.NONE, GridBagConstraints.VERTICAL, GridBagConstraints.HORIZONTAL, GridBagConstraints.BOTH.
gbc.anchor = anch; If component doesn't fill the space, tells how it should be aligned. anch can be one of these GridBagConstraints constants: CENTER (default), NORTH, SOUTH, NORTHEAST, SOUTHWEST, EAST, WEST, SOUTHEAST, NORTHWEST
gbc.insets = ins; Space around component. Eg, gbc.insets = new Insets(10,5,5,10);
gbc.ipadx = i; Horizontal padding internal to component. Can be negative!
gbc.ipady = i; Vertical padding internal to component. Can be negative!

FlowLayout, BorderLayout, GridLayout in java

Set the layout manager for a container p (usually a JPanel or Container) can be set with something like the following.

   p.setLayout(new FlowLayout());

Layouts (FlowLayout, BorderLayout, GridLayout)

FlowLayout - Arranges widgets left-to-right, top-to-bottom.
flow = new FlowLayout(); Creates FlowLayout, centered with 5 pixel gaps.
flow = new FlowLayout(align); Specifies alignment (FlowLayout.LEFT, FlowLayout.CENTER, FlowLayout.RIGHT).
flow = new FlowLayout(align, h, v); Specifies alignment and horizontal (h) and vertical (v) gaps in pixels.

p.add(widget); Adds widget to the next left-to-right, top-to-bottom position.
BorderLayout - Lays out components in BorderLayout.NORTH, EAST, SOUTH, WEST, and CENTER sections.
bord = new BorderLayout(); Creates BorderLayout. Widgets added with constraint to tell where.
bord = new BorderLayout(h, v); Creates BorderLayout with horizonal and vertical gaps sizes in pixels.

p.add(widget, pos); Adds widget to one of the 5 border layout regions, pos (see list above).
GridLayout - Lays out components in equal sized rectangular grid, added r-t-l, top-to-bottom.
grid = new GridLayout(r, c); Creates GridLayout with specified rows and columns.
grid = new GridLayout(r,c,h,v); As above but also specifies horizontal and vertical space between cells.

p.add(widget); Adds widget to the next left-to-right, top-to-bottom cell.

Low-level java gui Containers - special purpose - JSrollPane, JTabbedPane

JScrollPane - Holds textarea, list, (or large images in label) and adds scroll bars as necessary.
scr = new JScrollPane(textarea); Surrounds textarea with scrollbars as needed.
JTabbedPane - Display tabs to allow user to select one of many panels.
tp = new JTabbledPane(); Constructor. Creates new tabbed pane.
tp = new JTabbledPane(place); Constructor. placement is JTabbedPane.TOP (default), BOTTOM, LEFT, or RIGHT.
tp = new JTabbledPane(place, ovrfl); Constructor. ovrfl tells what to do if too many tabs: JTabbedPane.WRAP_TAB_LAYOUT or .SCROLL_TAB_LAYOUT.

tp.addTab(title, comp); Adds tab labelled with string title which displays comp (usually JPanel).

tp.addTab(title, icon, comp); Used string and icon for tab label.

Low-level Container supporting layouts in java - JPanel

JPanel - Set layout and add components to JPanel.
p = new JPanel(); Creates new JPanel

p.setLayout(layout); Sets the panel's layout.

p.add(widget); Add widget to next position - FlowLayout, GridLayout, BoxLayout.

p.add(widget, constraint); Add widget at position constraint = BorderLayout, GridbagLayout).

java JFrame - window, typically subclassed

w = new JFrame(); Constructor
w = new JFrame(t); Constructor. Sets titlebar to t.

w.setTitle(t); Sets titlebar text to t

w.setDefaultCloseOperation(opt); JFrame.EXIT_ON_CLOSE terminates program when close box clicked.

w.setVisible(true/false); Make visible (and start GUI thread) or hide.

w.pack(); Calculates layout on all inner containers and sets size of JFrame.

w.setContentPane(cont); Sets the content pane - common to pass a JPanel here.
cont = w.getContentPane(); Returns the window's content pane.

w.setJMenuBar(mb); Adds a JMenuBar.

w.setResizable(false); Prevent user from resizing window.

w.setLocation(x, y); Positions window's top left corner at screen coordinates (x, y).

w.setSize(w, h); Sets window size, but use layouts and pack() instead.

w.show(); Deprecated. Use w.setVisible(true).

w.hide(); Deprecated. Use w.setVisible(false).

short notes on Java GUI Containers

Top-level Container: javax.swing.JFrame

JFrame - window, typically subclassed
w = new JFrame(); Constructor
w = new JFrame(t); Constructor. Sets titlebar to t.

w.setTitle(t); Sets titlebar text to t

w.setDefaultCloseOperation(opt); JFrame.EXIT_ON_CLOSE terminates program when close box clicked.

w.setVisible(true/false); Make visible (and start GUI thread) or hide.

w.pack(); Calculates layout on all inner containers and sets size of JFrame.

w.setContentPane(cont); Sets the content pane - common to pass a JPanel here.
cont = w.getContentPane(); Returns the window's content pane.

w.setJMenuBar(mb); Adds a JMenuBar.

w.setResizable(false); Prevent user from resizing window.

w.setLocation(x, y); Positions window's top left corner at screen coordinates (x, y).

w.setSize(w, h); Sets window size, but use layouts and pack() instead.

w.show(); Deprecated. Use w.setVisible(true).

w.hide(); Deprecated. Use w.setVisible(false).

Top-level Containers: Dialogs: JOptionPane, JFileChooser, JColorChooser, JDialog

JOptionPane - Commonly used to create dialogs.

Low-level Container supporting layouts - JPanel

JPanel - Set layout and add components to JPanel.
p = new JPanel(); Creates new JPanel

p.setLayout(layout); Sets the panel's layout.

p.add(widget); Add widget to next position - FlowLayout, GridLayout, BoxLayout.

p.add(widget, constraint); Add widget at position constraint = BorderLayout, GridbagLayout).

Low-level Containers - special purpose - JSrollPane, JTabbedPane

JScrollPane - Holds textarea, list, (or large images in label) and adds scroll bars as necessary.
scr = new JScrollPane(textarea); Surrounds textarea with scrollbars as needed.
JTabbedPane - Display tabs to allow user to select one of many panels.
tp = new JTabbledPane(); Constructor. Creates new tabbed pane.
tp = new JTabbledPane(place); Constructor. placement is JTabbedPane.TOP (default), BOTTOM, LEFT, or RIGHT.
tp = new JTabbledPane(place, ovrfl); Constructor. ovrfl tells what to do if too many tabs: JTabbedPane.WRAP_TAB_LAYOUT or .SCROLL_TAB_LAYOUT.

tp.addTab(title, comp); Adds tab labelled with string title which displays comp (usually JPanel).

tp.addTab(title, icon, comp); Used string and icon for tab label.

declaration of JCheckBox - Check box followed by text. Use either listener or check with isSelected().

cb = new JCheckBox(text); Creates check box initially unchecked.

cb = new JCheckBox(text, bool); Creates check box with checked state tf.
b = cb.isSelected(); Returns bool if box is checked/unchecked.

cb.setSelected(bool); Sets checked state to tf.

cb.addActionListener(actlstnr); Adds ActionListener, which is called whenever user clicks.


cb.setEnabled(bool); Used to enable/disable check box.

declaration of JTextArea in java - Box containing multiple lines of text separated by '\n'.

ta = new JTextArea(rows, cols); Creates textarea with specifed number of rows and columns.
s = ta.getText(); Returns string in text area.

ta.setText(s); Sets text to s.

ta.append(s); Adds s to end of existing text.


ta.insert(s, pos); Inserts s at position pos.


ta.setEditable(bool); Don't allow user to edit textarea if used for output.


ta.setLineWrap(bool); Allow/disallow long lines to wrap.


ta.setWrapStyleWord(bool); Call setLineWrap(true) first. true wraps at word boundaries, false (default) at characters.


ta.setBorder(brdr); Add space between text and edge. Eg, to add 4 pixels use brdr BorderFactory.createEmptyBorder(4,4,4,4)

declaration of java JButton - Standard clickable button.

btn = new JButton(t); Creates button with text t.

btn = new JButton(img); Creates button with icon img.

btn = new JButton(t, img); Creates button with both text and icon.

btn.addActionListener(actlstnr); Action listener actlstnr called when button clicked.


btn.setEnabled(bool); Used to enable/disable button.

about JTextField in java gui components - Box containing one line of text.

tf = new JTextField(n); Creates textfield n characters wide.
s = tf.getText(); Returns string in textfield.

tf.setText(s); Sets text to s.


tf.addActionListener(lst); Action listener lst will be called if enter typed.


tf.setEditable(bool); Don't allow user to edit text field used for output.


tf.setHorizontalAlignment(align); JTextField.LEFT (default), JTextField.CENTER, or JTextField.RIGHT

about JLabel in java gui component - For fixed text.

lbl = new JLabel(t) Creates JLabel with text t on it.

lbl = new JLabel(t, align) Align text JLabel.LEFT, JLabel.CENTER, or JLabel.RIGHT.

lbl = new JLabel(icon) Displays icon (eg, ImageIcon).

lbl = new JLabel(icon, align) Align icon to JLabel.LEFT, JLabel.CENTER, or JLabel.RIGHT.

java Basic GUI Components

Components share many common methods, for example:


cmp.requestFocus(); Puts focus (eg, blinking cursor) in field, select button, etc.


cmp.setFont(f); Sets font.
JLabel - For fixed text.
lbl = new JLabel(t) Creates JLabel with text t on it.

lbl = new JLabel(t, align) Align text JLabel.LEFT, JLabel.CENTER, or JLabel.RIGHT.

lbl = new JLabel(icon) Displays icon (eg, ImageIcon).

lbl = new JLabel(icon, align) Align icon to JLabel.LEFT, JLabel.CENTER, or JLabel.RIGHT.
JTextField - Box containing one line of text.
tf = new JTextField(n); Creates textfield n characters wide.
s = tf.getText(); Returns string in textfield.

tf.setText(s); Sets text to s.


tf.addActionListener(lst); Action listener lst will be called if enter typed.


tf.setEditable(bool); Don't allow user to edit text field used for output.


tf.setHorizontalAlignment(align); JTextField.LEFT (default), JTextField.CENTER, or JTextField.RIGHT
JButton - Standard clickable button.
btn = new JButton(t); Creates button with text t.

btn = new JButton(img); Creates button with icon img.

btn = new JButton(t, img); Creates button with both text and icon.

btn.addActionListener(actlstnr); Action listener actlstnr called when button clicked.


btn.setEnabled(bool); Used to enable/disable button.
JTextArea - Box containing multiple lines of text separated by '\n'.
ta = new JTextArea(rows, cols); Creates textarea with specifed number of rows and columns.
s = ta.getText(); Returns string in text area.

ta.setText(s); Sets text to s.

ta.append(s); Adds s to end of existing text.


ta.insert(s, pos); Inserts s at position pos.


ta.setEditable(bool); Don't allow user to edit textarea if used for output.


ta.setLineWrap(bool); Allow/disallow long lines to wrap.


ta.setWrapStyleWord(bool); Call setLineWrap(true) first. true wraps at word boundaries, false (default) at characters.


ta.setBorder(brdr); Add space between text and edge. Eg, to add 4 pixels use brdr BorderFactory.createEmptyBorder(4,4,4,4)
JCheckBox - Check box followed by text. Use either listener or check with isSelected().
cb = new JCheckBox(text); Creates check box initially unchecked.

cb = new JCheckBox(text, bool); Creates check box with checked state tf.
b = cb.isSelected(); Returns bool if box is checked/unchecked.

cb.setSelected(bool); Sets checked state to tf.

cb.addActionListener(actlstnr); Adds ActionListener, which is called whenever user clicks.


cb.setEnabled(bool); Used to enable/disable check box.

java 3d arrays Initial values

You can assign initial values to an array when in a manner very similar to one-dimensional arrays, but with an extra level of braces. The dimension sizes are computed by the compiler from the number of values. This would allocated a 3x3 board

int[][] board = new int[][] {{1,0,0},{0,1,0},{1,2,1}};

usage of static in java array sizes

It's very useful to define constants for the number of rows and columns.

static final int ROWS = 2;
static final int COLS = 3;
. . .
int[][] board = new int[ROWS][COLS];

Many row and column indexes (indices is the traditional English plural) have a meaning, and aren't just simply arbitrary numbers. The following example might be used to represent the number of accidents on by day of the month and the hour of the day. See programming problems below for some examples using this array.

static final int DAYS  = 31;
static final int HOURS = 24;
. . .
int[][] accidents = new int[DAYS][HOURS];

Visualizing java two-dimensional arrays

2-dimensional arrays are usually represented with a row-column "spreadsheet" style. Assume we have an array, a, with two rows and four columns.

int[][] a = new int[2][3];  // Two rows and three columns.
a[0][0]a[0][1]a[0][2]a[0][3]
a[1][0]a[1][1]a[1][2]a[1][3]
Two-dimensional arrays are usually visualized as a matrix, with rows and columns. This diagram shows the array a with its corresponding subscripts.

define java 2-dimensional Arrays

1-, 2-, and higher-dimensional arrays

Java, as with most languages, supports multi-dimensional arrays - 1-dimensional, 2-dimensional, 3-dimensional, ... In practice most arrays are one-dimensional, and two-dimensional (rows and columns) are also quite common. Higher dimensional arrays are less common so they aren't used in the examples, but there's nothing mysterious about them and the same principles apply.

Two-dimensional arrays are used whenever the model data is best represented with rows and columns, or has two varying aspects (eg, gender and age, weight and height, ...). It's also the idea, altho not the implementation, of graphics that specifies a two (or three) dimensional position with an x and y (and z) coordinate.

Terminology. Other terms you will see for a two-dimensional array are matrix or table.

Visualizing two-dimensional arrays

2-dimensional arrays are usually represented with a row-column "spreadsheet" style. Assume we have an array, a, with two rows and four columns.

int[][] a = new int[2][3];  // Two rows and three columns.
a[0][0]a[0][1]a[0][2]a[0][3]
a[1][0]a[1][1]a[1][2]a[1][3]
Two-dimensional arrays are usually visualized as a matrix, with rows and columns. This diagram shows the array a with its corresponding subscripts.

Style: Use constants for the array sizes

It's very useful to define constants for the number of rows and columns.

static final int ROWS = 2;
static final int COLS = 3;
. . .
int[][] board = new int[ROWS][COLS];

Many row and column indexes (indices is the traditional English plural) have a meaning, and aren't just simply arbitrary numbers. The following example might be used to represent the number of accidents on by day of the month and the hour of the day. See programming problems below for some examples using this array.

static final int DAYS  = 31;
static final int HOURS = 24;
. . .
int[][] accidents = new int[DAYS][HOURS];

Initial values

You can assign initial values to an array when in a manner very similar to one-dimensional arrays, but with an extra level of braces. The dimension sizes are computed by the compiler from the number of values. This would allocated a 3x3 board

int[][] board = new int[][] {{1,0,0},{0,1,0},{1,2,1}};

Use nested for loops to process 2-dimensional arrays

Two-dimensional arrays are almost always processed with nested for loops.

static final int ROWS = 2;
static final int COLS = 4;
. . .
int[][] a2 = new int[ROWS][COLS];
. . .
//... Print array in rectangular form
for (int i =0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
System.out.print(" " + a2[i][j]);
}
System.out.println("");
}

Programming problems

  1. For the accidents array above write code that does the following:
    1. Display the total number of accidents? Hint: Use nested loops to add all elements.
    2. At what hour do the most accidents occur? Hint: Use on outer loop over hours, where the inner loop goes down the column and adds all the accidents for that hour. Keep max as you would for a one-dimensional array.
    3. How would you declare a three-dimensional array that had an additional dimension for the 12 months?

Shuffling (randomizing) an array in java

import java.util.*;
. . .
List labc = Arrays.asList(abc);
. . .
Collections.shuffle(labc);
System.out.println(labc);

Which gave the following output. Note that the List overrides toString() to give reasonable output.

[b, a, c]

Inefficient? Not necessarily. Constructing a new List object from the array is only inefficient if you're doing it frequently. If you do it very often then you want to avoid creating a new list each time. Creating the list one time is not a problem because the list that is produced is backed by this one array -- you can change elements in the array and the list will reflect those changes.

Can't shuffle arrays of primitives this way!

Lists and other Collections classes only work on objects, not on primitive values, so you have to do the shuffling "by hand". See Random Numbers - shuffling for how to do it yourself.

Use of java Arrays.asList(...) for Collections view of array

Make a list. The Arrays class has some useful methods for working with arrays, but there are a lot more if you make your array look like a List. The Collections class has many useful methods, eg, shuffle, reverse, max, .... See Collections Class.

import java.util.*;
. . .
List listabc = Arrays.asList(abc);
// The Collections methods can now be use with listabc.

View of underlying array. The list that is created is not a regular ArrayList. It is based only on the original array, so you can't do things like adding elements to the list because this would cause reallocation of a larger underlying array.

Uses the underlying array. One of the really nice things about this is that you can still use the underlying array, which means that creating this list doesn't prevent you from taking advantage of the efficiency of array access for example.

Objects only. The java.util.Arrays.asList(...) method only works for arrays of object types. If you try to use it with an array of primitives, you will get a compilation error.

java.util.Arrays.toString(...) for debugging

AVOID default toString(). Using the common debugging technique of printing intermediate values on the console with arrays is good, but requires calling a library method to get the results you expect. Arrays are a subclass of Object as ever other object is, and therefore the toString() method is defined for every array. The results will very likely disappoint you.

String[] abc = {"a", "b", "c"};
System.out.println(abc); // println calls toString() on object parameters.

This displays the relatively unhelpful "[L", element type, ";@", and hexadecimal memory address of the array.

[Ljava.lang.String;@f6f1b6

USE java.util.Arrays.toString(...) and you'll get something much more readable. An import java.util.*; statement avoids the extra package qualifier.

String[] abc = {"a", "b", "c"};
System.out.println(java.util.Arrays.toString(abc));

This produces the following output, which is the same as toString() applied to a List.

[a, b, c]

java arrays library methods

Static methods for manipulating arrays are available in the java.util.Arrays and java.System classes. Assume the following declarations, where T is the array element type, either a primitive, object or either kind of type depending on which method is being called.

T       x, key;  // This type T can be either a primitive or object type.
T[] a, a2; // This type T can be either a primitive or object type.
List lst; // Only object types T.
Comparator comp; // Only object types T.
int i; // Index returned from search.
int i1, i2;
int from; // Lower bound of subscript range. Includes this element.
int to; // Upper bound of subscript range. Does not include this element.
String s;
boolean b; // Normally the method result will be used in an if.
lst = Arrays.asList(a); List based on the array.
s = Arrays.toString(a);String form surrounded by "[]", elements separated by ", ".
s = Arrays.deepToString(a);String form by recursively converting subarrays.
b = Arrays.equals(a, a2);True if arrays are same size and all elements are equal (== or equals as appropriate).
b = Arrays.deepEquals(a, a2);As above, recursively applied to subarrays.

Arrays.fill(a, x); Fills array with a value.

Arrays.fill(a, from, to, x); Fills subrange (from inclusive, to exclusive) with a value.
Making a copy of part of an array

System.arraycopy(a, i1, a2, i2, len); Shallow copy len elements from a[i1] to a2[i2]. Case!
a2 = Arrays.copyOf(a, newLength); New shallow copy of array with new length. If longer, uses default values.
a2 = Arrays.copyOfRange(a, from, to); New shallow copy of portion of array.
Searching
i = Arrays.binarySearch(a, key);A O(log N)search of array sorted in ascending order. If the key is not found, a negative number, -insertionPoint-1, is returned.
i = Arrays.binarySearch(a, key, comp);Binary search of a sorted array of objects (not primitives).
Sorting. See Sorting Arrays for more on sorting and comparators.

Arrays.sort(a); Sorts in "natural" order. If object type, elements must be comparable.

Arrays.sort(a, comp); Sorts objects (not primitives) using comparator.

Arrays.sort(a, from, to); Sorts subrange, including a[from] excluding a[to].

Arrays.sort(a, from, to, comp);Sorts objects (not primitives) in subrange using comparator.

Use java.util.Arrays.toString(...) for debugging

AVOID default toString(). Using the common debugging technique of printing intermediate values on the console with arrays is good, but requires calling a library method to get the results you expect. Arrays are a subclass of Object as ever other object is, and therefore the toString() method is defined for every array. The results will very likely disappoint you.

String[] abc = {"a", "b", "c"};
System.out.println(abc); // println calls toString() on object parameters.

This displays the relatively unhelpful "[L", element type, ";@", and hexadecimal memory address of the array.

[Ljava.lang.String;@f6f1b6

USE java.util.Arrays.toString(...) and you'll get something much more readable. An import java.util.*; statement avoids the extra package qualifier.

String[] abc = {"a", "b", "c"};
System.out.println(java.util.Arrays.toString(abc));

This produces the following output, which is the same as toString() applied to a List.

[a, b, c]

Use Arrays.asList(...) for Collections view of array

Make a list. The Arrays class has some useful methods for working with arrays, but there are a lot more if you make your array look like a List. The Collections class has many useful methods, eg, shuffle, reverse, max, .... See Collections Class.

import java.util.*;
. . .
List listabc = Arrays.asList(abc);
// The Collections methods can now be use with listabc.

View of underlying array. The list that is created is not a regular ArrayList. It is based only on the original array, so you can't do things like adding elements to the list because this would cause reallocation of a larger underlying array.

Uses the underlying array. One of the really nice things about this is that you can still use the underlying array, which means that creating this list doesn't prevent you from taking advantage of the efficiency of array access for example.

Objects only. The java.util.Arrays.asList(...) method only works for arrays of object types. If you try to use it with an array of primitives, you will get a compilation error.

Shuffling (randomizing) an array

import java.util.*;
. . .
List labc = Arrays.asList(abc);
. . .
Collections.shuffle(labc);
System.out.println(labc);

Which gave the following output. Note that the List overrides toString() to give reasonable output.

[b, a, c]

Inefficient? Not necessarily. Constructing a new List object from the array is only inefficient if you're doing it frequently. If you do it very often then you want to avoid creating a new list each time. Creating the list one time is not a problem because the list that is produced is backed by this one array -- you can change elements in the array and the list will reflect those changes.

Can't shuffle arrays of primitives this way!

Lists and other Collections classes only work on objects, not on primitive values, so you have to do the shuffling "by hand". See Random Numbers - shuffling for how to do it yourself.

Commentary

A shuffle(...) method that works with primitive types should be added to the Arrays class.

Iterating over an array in java

Length/sizeThe size of an array can be found by referencing the length field, eg, scores.length .
For loopsFor loops are the most common way to iterate over array elements. The normal for loop is good for going forwards, backwards, subranges, comparing two elements, or on every nth element. If you are just going forward over the entire array, the enhanced for loop is more readable.
//... Using standard for loop.
int[] scores = new int[12];
. . . Set values in the scores array.
int total = 0;
for (int i = 0; i <> {
total += scores[i];
}
//... Using enhanced for loop.
int[] scores = new int[12];
. . . Set values in the scores array.
int total = 0;
for (int scr : scores) {
total += scr;
}

java array Subscripts - Accessing elements of the array

Integers Selecting a particular position in an array is done by specifying an integer value.
enums Enum values may also be used in index an array.
Square bracketsSubscripts are written after an array variable, enclosed in square brackets.
scores[5] = 86;   // Assigns the value 86 as the 5th value.
scores[ss]++; // Increments the score of element whose number is in ss.
Start at 0 The first subscript value is zero, not one.
Bounds check ArrayIndexOutOfBoundsException is thrown if subscripts are out of the legal range.
Names When a subscript has no meaning, it's common to use i, j, k. Otherwise use a descriptive name.

java Array initial values

zero/null/false If no initial values are specified for array elements (see below), array elements are initialized to zero for numbers, null for object references, and false for booleans. This is the same as for all object fields.
Initialization A curly brace surrounded list of values can be specified on the declaration. This allocates exactly enough space to hold the array. The following are equivalent.
String[] names = {"Mickey", "Minnie", "Donald"};
String[] names = new String[3];
names[0] = "Mickey";
names[1] = "Minnie";
names[2] = "Donald";

Array Declaration in java

Same type All elements in an array must be the same type, either primitive or object.
DeclarationPrecede variable with element type and square brackets. Eg,
int[] scores;
AllocationMemory to store array elements must be allocated with new. Eg,
int[] scores;                // Declares that scores is an array of integers.
scores = new int[12]; // Allocate memory to hold up to 12 score values.
Combined It's very common to combine the declaration with the allocation.
int[] scores = new int[12];  // Declare and allocate memory in one statement.
Fixed size When memory is allocated for an array, it is a fixed size block. It does not expand.
Plural namesThe most common naming advice is to use plural names or collective nouns.
References Array variables are references to array objects. Two variables can reference the same array.

short notes on java summary

Array Summary - main points
Purpose To save large numbers of data elements, either primitives or objects.
UniversalAlmost all programming languages have arrays.
Array Declaration
Same type All elements in an array must be the same type, either primitive or object.
DeclarationPrecede variable with element type and square brackets. Eg,
int[] scores;
AllocationMemory to store array elements must be allocated with new. Eg,
int[] scores;                // Declares that scores is an array of integers.
scores = new int[12]; // Allocate memory to hold up to 12 score values.
Combined It's very common to combine the declaration with the allocation.
int[] scores = new int[12];  // Declare and allocate memory in one statement.
Fixed size When memory is allocated for an array, it is a fixed size block. It does not expand.
Plural namesThe most common naming advice is to use plural names or collective nouns.
References Array variables are references to array objects. Two variables can reference the same array.
Array initial values
zero/null/false If no initial values are specified for array elements (see below), array elements are initialized to zero for numbers, null for object references, and false for booleans. This is the same as for all object fields.
Initialization A curly brace surrounded list of values can be specified on the declaration. This allocates exactly enough space to hold the array. The following are equivalent.
String[] names = {"Mickey", "Minnie", "Donald"};
String[] names = new String[3];
names[0] = "Mickey";
names[1] = "Minnie";
names[2] = "Donald";
Subscripts - Accessing elements of the array
Integers Selecting a particular position in an array is done by specifying an integer value.
enums Enum values may also be used in index an array.
Square bracketsSubscripts are written after an array variable, enclosed in square brackets.
scores[5] = 86;   // Assigns the value 86 as the 5th value.
scores[ss]++; // Increments the score of element whose number is in ss.
Start at 0 The first subscript value is zero, not one.
Bounds check ArrayIndexOutOfBoundsException is thrown if subscripts are out of the legal range.
Names When a subscript has no meaning, it's common to use i, j, k. Otherwise use a descriptive name.
Iterating over an array
Length/sizeThe size of an array can be found by referencing the length field, eg, scores.length .
For loopsFor loops are the most common way to iterate over array elements. The normal for loop is good for going forwards, backwards, subranges, comparing two elements, or on every nth element. If you are just going forward over the entire array, the enhanced for loop is more readable.
//... Using standard for loop.
int[] scores = new int[12];
. . . Set values in the scores array.
int total = 0;
for (int i = 0; i <> {
total += scores[i];
}
//... Using enhanced for loop.
int[] scores = new int[12];
. . . Set values in the scores array.
int total = 0;
for (int scr : scores) {
total += scr;
}

explain javastringbuffer - java.util.StringBuilder and java.util.StringBuffer

Strings are immutable (can't be changed), so manipulating strings often causes many temporary string objects to be created, which can be quite inefficient. StringBuilder (or StringBuffer) are better choices in these cases. Their toString() method can be used get a String value. It isn't necessary to create them with a specific size, it will expand as necessary. Many StringBuilder methods return the same StringBuilder so that the call chaining style of programming can be used.

StringBuilder is basically identical to the older StringBuffer, but is slightly faster because it isn't synchronized.

Constructors
sb = new StringBuilder() Creates empty StringBuilder
sb = new StringBuilder(n) Creates empty StringBuilder with initial capacity n.
sb = new StringBuilder(s) Creates StringBuilder with value initialized to String s.
Length
i = sb.length() Length of the current contents of sb.
Modifying the content - These methods return the original StingBuilder to allow call chaining.
sb =sb.append(x) Appends x (char, int, String, ...) to end of sb.
sb =sb.insert(offset, x) Inserts x (char, int, String, ...) at position offset.
sb =sb.setCharAt(index, c) Replaces char at index with c
sb =sb.deleteCharAt(i) Deletes char at index i.
sb =sb.delete(beg, end) Deletes chars at index beg thru end.
sb =sb.reverse() Reverses the contents.
sb =sb.replace(beg, end, s) Replaces characters beg thru end with s.
Getting parts
c = sb.charAt(i) char at position i in sb.
s = sb.substring(i) substring from index i to the end of sb.
s = sb.substring(i, j) substring from index i to BEFORE index j of sb.
Misc
s = sb.toString() Returns a String for the contents of sb.
Searching -- Note: All "indexOf" methods return -1 if the string/char is not found
i = sb.indexOf(s) index of the first occurrence of String s in s.
i = sb.indexOf(s, i) index of String s at or after position i in sb.
i = sb.lastIndexOf(s) index of last occurrence of s in sb.
i = sb.lastIndexOf(s, i) index of last occurrence of s on or before i in sb.
Comparison (note: use this instead of == and !=)
b = sb.equals(sb2) true if the two StringBuilders contain equal values

ANSI/ASCII and Extended Latin Sections of Unicode

Unicode attempts to represent the characters in all current human languages, as well as numerous special symbols. The most common implmentation of it uses 16 bits, which is 65,536 characters (many are not yet assigned a graphic). The first 128 codes are identical to ANSI/ASCII (American National Standards Institute / American Standard Code for Information Interchange). Of the ASCII codes, the first 32 are control codes. The first 256 codes are the same as ISO-8859-1 (Latin-1), which includes ASCII of course. Below is a table which shows this common first part of the Unicode character set. The table below is in HTML, so the actual characters that are displayed are determined by your browser, not Java.


+0+1+2+3+4+5+6+7+8+9+10+11+12+13+14+15
32 !"#$%&'()*+,-./
480123456789:;<=>?
64@ABCDEFGHIJKLMNO
80PQRSTUVWXYZ[\]^_
96`abcdefghijklmno
112pqrstuvwxyz{|}~
128€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž�
144�‘’“”•–—˜™š›œ�žŸ
160 ¡¢£¤¥¦§¨©ª«¬­®¯
176°±²³´µ·¸¹º»¼½¾¿
192ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏ
208ÐÑÒÓÔÕÖרÙÚÛÜÝÞß
224àáâãäåæçèéêëìíîï
240ðñòóôõö÷øùúûüýþÿ

An applet (written in old Java 1 in a rather unique style) that displays the Unicode characters can be found at mindprod.com/jgloss/reuters.html. For more information on Unicode, see www.alanwood.net/unicode/.

character data types in java

Character class static methods

Character Class Methods
Character class is used mostly for static methods to test char values.
b = Character.isDigit(c) true if c is digit character.
b = Character.isLetter(c) true if c is letter character.
b = Character.isLetterOrDigit(c) true if c is letter or digit.
b = Character.isLowerCase(c) true if c is lowercase char.
b = Character.isUpperCase(c) true if c is uppercase char.
b = Character.isWhitespace(c) true if c is space, tab, ....
c = Character.toLowerCase(c) Lowercase version of c.
c = Character.toUpperCase(c) Uppercase version of c.

ANSI/ASCII and Extended Latin Sections of Unicode

Unicode attempts to represent the characters in all current human languages, as well as numerous special symbols. The most common implmentation of it uses 16 bits, which is 65,536 characters (many are not yet assigned a graphic). The first 128 codes are identical to ANSI/ASCII (American National Standards Institute / American Standard Code for Information Interchange). Of the ASCII codes, the first 32 are control codes. The first 256 codes are the same as ISO-8859-1 (Latin-1), which includes ASCII of course. Below is a table which shows this common first part of the Unicode character set. The table below is in HTML, so the actual characters that are displayed are determined by your browser, not Java.


+0+1+2+3+4+5+6+7+8+9+10+11+12+13+14+15
32 !"#$%&'()*+,-./
480123456789:;<=>?
64@ABCDEFGHIJKLMNO
80PQRSTUVWXYZ[\]^_
96`abcdefghijklmno
112pqrstuvwxyz{|}~
128€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž�
144�‘’“”•–—˜™š›œ�žŸ
160 ¡¢£¤¥¦§¨©ª«¬­®¯
176°±²³´µ·¸¹º»¼½¾¿
192ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏ
208ÐÑÒÓÔÕÖרÙÚÛÜÝÞß
224àáâãäåæçèéêëìíîï
240ðñòóôõö÷øùúûüýþÿ

An applet (written in old Java 1 in a rather unique style) that displays the Unicode characters can be found at mindprod.com/jgloss/reuters.html. For more information on Unicode, see www.alanwood.net/unicode/.

example program on java Inner class listener (xicl)

One good way to implement a listener is to define an inner class that implements ActionListener. An inner class has access to the outer class's fields, so can get work with components defined in an outer JFrame subclass.

  1
2
3
4
5
6
7
8
   
///////////////////////////////////////////////////////////////// ${Identifier}
class ${Identifier} implements ActionListener {
public void actionPerformed(ActionEvent e) {
//... Do something.
}
}

Archives