TextBox

TextBox

Open source code to display text neatly inside any given rectangle in a Java GUI.

  • Language: Java
  • Released: Mar 23, 2011
    Last Update: Mar 22, 2011

TextBox displays text on a window, very much like a java.util.JLabel field, but it will use multiple lines as needed. Text can be justified any way, horizontally and vertically. Given a rectangular area and a String of any length, it will always display the string as nicely as possible. A TextBox object may be used like a JLabel and placed in any Container or extended for use as a renderer in JTables, JLists, etc. It can also place text in a rectangle in any graphics context without being added to the canvas. (In other words, it can do immediate mode text graphics as well as retained mode text graphics.)

TextBox is useful anywhere that a display area for text can change frequently, especially when the change is under a user's control. In addition to maintaining a pleasant appearance, it can effectively put a lot more text into a given space because the user can quickly adjust boundaries to show more useful text at the expense of the less useful.
(It is also handy when an overworked programmer wants to display static text, but does not want to spend time formatting it.) Works well providing multi-line displays in JTables' rows and, more impressively, in their headers.

A demonstration program is included that shows TextBoxes being used in place of JLabels in Containers and extended as TableCellRenderers in a JTable. Fully Javadoc'ed.

The screenshots show TextBox formatting text as a component on a simple window and as cells and column headers in a JTable. The text is reformatted instantly as the window/cell sizes change. The program producing this is included with the open source TextBox code. The TextBox class can also format text dynamically in a java.awt.Graphics context.

Hide

Usage Example

The following is the code for the main demonstration window, somewhat simplified:

package rrc12;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;
import rrc12.util.components.*;

/** A demonstration of the powers of the TextBox class. */
public class TextBoxExample  extends JFrame  {
    public static void main( String args[] )  {
        new TextBoxExample().setVisible( true );
    }

    private byte          hFlag;
    private TextBox       textBox;
    private JRadioButton  leftCheck, rightCheck, centerCheck;
    private JCheckBox     topCheck, bottomCheck, middleCheck;
    private boolean       topAlign, bottomAlign, middleAlign;

    public TextBoxExample()  {
        setTitle( "TextBox Example" );
        setSize( 300, 292 );
        setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

        textBox = new TextBox();
        textBox.setText( "It is a truth universally acknowledged, " +
                    "that a single man in possession of a good " +
                    "fortune must be in want of a wife." );
        textBox.setBorder( BasicBorders.getTextFieldBorder() );
        Container  cp = getContentPane();
        cp.add( textBox, BorderLayout.CENTER );

        ButtonGroup  buttonGroup = new ButtonGroup();

        leftCheck = new JRadioButton( "Left" );
        leftCheck.addActionListener( new ActionListener()  {
            public void actionPerformed( ActionEvent evt )  {
                hFlag = TextBox.LEFT;
                textBox.setAlignment( hFlag );
            }
        } );
        buttonGroup.add( leftCheck );
        leftCheck.setSelected( true );
        hFlag = TextBox.LEFT;

        centerCheck = new JRadioButton( "Center" );
        centerCheck.addActionListener( new ActionListener()  {
            public void actionPerformed( ActionEvent evt )  {
                hFlag = TextBox.CENTER;
                textBox.setAlignment( hFlag );
            }
        } );
        buttonGroup.add( centerCheck );

        rightCheck = new JRadioButton( "Right" );
        rightCheck.addActionListener( new ActionListener()  {
            public void actionPerformed( ActionEvent evt )  {
                hFlag = TextBox.RIGHT;
                textBox.setAlignment( hFlag );
            }
        } );
        buttonGroup.add( rightCheck );

        topCheck = new JCheckBox( "Top" );
        topCheck.addActionListener( new ActionListener()  {
            public void actionPerformed( ActionEvent evt )  {
                topAlign = topCheck.isSelected();
                if (topAlign)  {
                    bottomAlign = false;
                    bottomCheck.setSelected( false );
                }
                resetV();
            }
        } );

        middleCheck = new JCheckBox( "Center" );
        middleCheck.addActionListener( new ActionListener()  {
            public void actionPerformed( ActionEvent evt )  {
                middleAlign = middleCheck.isSelected();
                resetV();
            }
        } );

        bottomCheck = new JCheckBox( "Bottom" );
        bottomCheck.addActionListener( new ActionListener()  {
            public void actionPerformed( ActionEvent evt )  {
                bottomAlign = bottomCheck.isSelected();
                if (bottomAlign)  {
                    topAlign = false;
                    topCheck.setSelected( false );
                }
                resetV();
            }
        } );

        Box  buttonBox = Box.createHorizontalBox();
        buttonBox.add( Box.createHorizontalStrut( 10 ) );
        {
            Box  leftBox = Box.createVerticalBox() ;
            leftBox.add( leftCheck );
            leftBox.add( centerCheck );
            leftBox.add( rightCheck );
            buttonBox.add( leftBox );

            Box  rightBox = Box.createVerticalBox() ;
            rightBox.add( topCheck );
            rightBox.add( middleCheck );
            rightBox.add( bottomCheck );
            buttonBox.add( rightBox );
        }
        buttonBox.add( Box.createHorizontalStrut( 10 ) );

        cp.add( buttonBox, BorderLayout.SOUTH );
    }

    private void resetV()  {
        byte  flag = 0;
        if (topAlign)  flag |= TextBox.TOP;
        if (bottomAlign)  flag |= TextBox.BOTTOM;
        if (middleAlign)  flag |= TextBox.MIDDLE;
        textBox.setVerticalAlignment( flag );
    }
}
Hide

TextBox Javadoc

The following is a plain text, simplified version of the javadoc for TextBox:

rrc12.util.components Class TextBox

java.lang.Object
  java.awt.Component
      java.awt.Container
          javax.swing.JComponent
              rrc12.util.components.TextBox

All Implemented Interfaces: java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable

Direct Known Subclasses: TextCellRenderer

public class TextBox extends javax.swing.JComponent

This produces a simple label with multiple lines. Basically, given dimensions and a text, it displays the text as nicely as possible.

While a TextBox object is a Component, it can be used as a simple way to place formated text anywhere in a graphics context using the paintAt method. All the complexities of placing or printing a Component can be avoided. Simply create a text box, give it the text and desired options, and call paintAt as needed. By changing the text (and options) between calls inefficient multiple instantiations can be avoided.

Method Detail

getText()

public java.lang.String getText()

Gets the text for this TextBox. (Never returns null.)

setText()

public void setText(java.lang.String s)

Sets the text for this TextBox.

Parameters:

  • s - the string for the text. May be null.

getAlignment()

public byte getAlignment()

Gets the alignment of this TextBox, one of: LEFT, CENTER, or RIGHT.

setAlignment()

public void setAlignment(byte alignment)

Sets the alignment of this TextBox. If not specified by this method or otherwise, the alignment will be LEFT.

Parameters:

  • alignment - the alignment, one of: LEFT, CENTER, or RIGHT.

getVerticalAlignment()

public byte getVerticalAlignment()

Gets the vertical alignment of this TextBox, one or more of: TOP, MIDDLE, or BOTTOM.

setVerticalAlignment()

public void setVerticalAlignment(byte alignment)

Sets the vertical alignment of this TextBox. If not specified by this method or otherwise, the alignment will be MIDDLE orred with TOP.

Parameters:

  • alignment - the alignment, one or more of: TOP, MIDDLE, or BOTTOM. Adding TOP or BOTTOM to MIDDLE will cause the text to be vertically centered if there is more room than necessary and to align at the top or bottom if the text overflows the space.

setBold()

public void setBold(boolean  b)

Sets the text to bold. Default text is not bold.

Parameters:

  • b - true for bold text, false for normal text.

setItalic()

public void setItalic(boolean b)

Sets the text to italic. Default text is not italic.

Parameters:

  • b - true for italic text, false for normal text.

getBorder()

public javax.swing.border.Border getBorder()

Gets the border for this TextBox. May be null if there is none.

Overrides: getBorder in class javax.swing.JComponent

setBorder()

public void setBorder(javax.swing.border.Border b)

Sets the border for this TextBox. (If this method is not called, there will be no border.) This border will not appear when the paintAt method is used, but only during a proper Component.paint call.

Overrides: setBorder in class javax.swing.JComponent

Parameters:

  • b - the new border. Set null if no border is desired.

setMargin()

public void setMargin(int m)

Sets the horizontal margin for this TextBox. For all lines but the bottom one, this applies to both sides. For the bottom row, for left justified and centered, it applies to the left side. For right justified, it applies on the right. The default value is two, which usually looks pretty nice. Larger values will look impressive, while a zero or a one will squeeze in more text.

Parameters:

  • m - the margin, an integer between zero and 100.

setPreferredSize()

public void setPreferredSize(int width,
                             int height)

Sets a preferred size for this component. The size is arbitrary, but this method is not dependent on a graphics context.

Parameters:

  • width - the preferred width.
  • height - the preferred height.

forcePreferredSize()

public void forcePreferredSize(int w)

Forces this TextBox to have a preferred size using the passed width and calculating a height.

Parameters:

  • w - the preferred-width-to-be. Pass negative value to skip preferences at this level.

Throws: java.awt.IllegalComponentStateException - when this TextBox is not displayable or has no graphics context for other reasons.

forceMinimumSize()

public void forceMinimumSize(int w)

Forces this TextBox to have a minimum size using the passed width and calculating a height.

Parameters:

  • w - the preferred-width-to-be. Pass negative value to skip preferences at this level.

Throws: java.awt.IllegalComponentStateException - when this TextBox is not displayable or has no graphics context for other reasons.

paintAt()

public void paintAt(java.awt.Graphics g,
                java.awt.Color c,
                java.awt.Rectangle position)

Paints this TextBox at any arbitrary spot in any arbitrary graphics context. Only does the text, leaving the background untouched. Borders are likewise ignored. Useful for formatting a text display with no emotional baggage.

Parameters:

  • g - the graphics context.
  • c - the text color. Set to null to use the graphics context's default.
  • position - the place to put the text.

paint()

public void paint(java.awt.Graphics g)

Overrides: paint in class javax.swing.JComponent

getMinimumSize()

public java.awt.Dimension getMinimumSize()

Overrides: getMinimumSize in class javax.swing.JComponent

getPreferredSize()

public java.awt.Dimension getPreferredSize()

Overrides: getPreferredSize in class javax.swing.JComponent

getMaximumSize()

public java.awt.Dimension getMaximumSize()

Overrides: getMaximumSize in class javax.swing.JComponent

You need to log-in or create an account
  • Create an account
  • Log-in
Please use your real name.
Activation link will be sent to this address.
Minimum 8 characters
Enter your password again

Clicking this button confirms you read and agreed to the terms of use and privacy policy.

X

Save your watchlist

Fill your details below to receive project updates from your watch list - including new versions, price changes and discounts.

I agree to the terms of use and privacy policy.

2 licenses, starting from From » FREE 14 day money-back guarantee View Licenses
or Get a quote

for customization or integration services

Post a comment

Or enter your name and Email
No comments have been posted yet.