Please follow me here!

Saturday, June 1, 2013

JAVA Program: Displaying Unlimited Strings on a GUI Program

Hello, everyone.

Here's an experimental program I had to do for one of my Data Structures assignments I have recently completed.

When you run the program, you type in the string, without seeing what it looks like, then press Enter to display it on the green canvas. It's not really a fun program, but this is to demonstrate the power of what's called action listeners. They are vitally important for GUI applications like this one.

Documentation is provided for your convenience. And you can copy and modify this code at your convenience, using a text editor or an IDE.


 *     Data Structures and Object-Oriented Programming - Assignment 7
 *     Question 16.10 of Introduction to Java Programming (by Daniel Liang)
 *     Enter and Display a String
 *     This is an example on how to use a keyboard listener. You type in a sequence
 *     of characters, then when you press enter, what you type in is displayed on
 *     the screen.
 *     It's not really fancy, but this is to show off what a keyboard listener is
 *     about. You can resize the window to make it wider or narrower, but only one
 *     line of text is displayed and is always at the top of the panel, right below
 *     the frame's top side.
 *     Programmed by Gregory Desrosiers
 *     Start Date: March 24, 2013
 *     End Date: March 24, 2013
 *     File Name:
 *     Teacher: Amin Ranj Bar

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Chapter16Exercise10 extends JPanel
    private static final long serialVersionUID = -7300674970023098222L;
    // Text Entered
    private StringBuilder text = new StringBuilder("");
    // Font Family
    private Font font = new Font("Tahoma", Font.PLAIN, 12);

    public static void main(String[] args)
        JFrame frame = new JFrame();
        Chapter16Exercise10 panel = new Chapter16Exercise10();
        frame.setSize(400, 100);
    public Chapter16Exercise10()
        setBackground(new Color(0, 128, 0));
        addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e)
                if (e.getKeyCode() == KeyEvent.VK_ENTER)
    protected void paintComponent(Graphics g)
        g.drawString(text.toString(), 0, 15);
        text.delete(0, text.length());

Google+ Followers

Popular Posts by Gregory