How to add a scrollbar to applet

This is the source code of my applet.I wat to have an autoscroll on this applet
i think it is usefull if i put here all the code for my project.
======================================================
Class ConsolePanel:
The file defines a class ConsolePanel. Objects of type
ConsolePanel can be used for simple input/output exchanges with
the user. Various routines are provided for reading and writing
values of various types from the output. (This class gives all
the I/O behavior of another class, Console, that represents a
separate window for doing console-style I/O.)
This class is dependent on another class, ConsoleCanvas.
Note that when the console has the input focus, it is outlined with
a bright blue border. If, in addition, the console is waiting for
user input, then there will be a blinking cursor. If the console
is not outlined in light blue, the user has to click on it before
any input will be accepted.
This is an update an earlier version of the same class,
rewritten to use realToString() for output of floating point
numbers..
package myproj;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JScrollPane;
import javax.swing.JScrollBar;
import javax.swing.*;
public class ConsolePanel extends JTextArea{
static public JScrollPane scrollPane;
// ***************************** Constructors *******************************
public ConsolePanel() { // default constructor just provides default window title and size
setBackground(Color.white);
setLayout(new BorderLayout(0, 0));
canvas = new ConsoleCanvas(500,1000);
scrollPane = new JScrollPane(canvas);
scrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize( new Dimension( 1000,10000) );
add("Center", scrollPane);
//scrollPane.getVerticalScrollBar().setUnitIncrement(1);
try {
jbInit();
} catch (Exception ex) {
ex.printStackTrace();
public void clear() { // clear all characters from the canvas
canvas.clear();
// *************************** I/O Methods *********************************
// Methods for writing the primitive types, plus type String,
// to the console window, with no extra spaces.
// Note that the real-number data types, float
// and double, a rounded version is output that will
// use at most 10 or 11 characters. If you want to
// output a real number with full accuracy, use
// "con.put(String.valueOf(x))", for example.
public void put(int x) {
put(x, 0);
} // Note: also handles byte and short!
public void put(long x) {
put(x, 0);
public void put(double x) {
put(x, 0);
} // Also handles float.
public void put(char x) {
put(x, 0);
public void put(boolean x) {
put(x, 0);
public void put(String x) {
put(x, 0);
// Methods for writing the primitive types, plus type String,
// to the console window,followed by a carriage return, with
// no extra spaces.
public void putln(int x) {
put(x, 0);
newLine();
} // Note: also handles byte and short!
public void putln(long x) {
put(x, 0);
newLine();
public void putln(double x) {
put(x, 0);
newLine();
} // Also handles float.
public void putln(char x) {
put(x, 0);
newLine();
public void putln(boolean x) {
put(x, 0);
newLine();
public void putln(String x) {
put(x, 0);
newLine();
// Methods for writing the primitive types, plus type String,
// to the console window, with a minimum field width of w,
// and followed by a carriage return.
// If outut value is less than w characters, it is padded
// with extra spaces in front of the value.
public void putln(int x, int w) {
put(x, w);
newLine();
} // Note: also handles byte and short!
public void putln(long x, int w) {
put(x, w);
newLine();
public void putln(double x, int w) {
put(x, w);
newLine();
} // Also handles float.
public void putln(char x, int w) {
put(x, w);
newLine();
public void putln(boolean x, int w) {
put(x, w);
newLine();
public void putln(String x, int w) {
put(x, w);
newLine();
// Method for outputting a carriage return
public void putln() {
newLine();
// Methods for writing the primitive types, plus type String,
// to the console window, with minimum field width w.
public void put(int x, int w) {
dumpString(String.valueOf(x), w);
} // Note: also handles byte and short!
public void put(long x, int w) {
dumpString(String.valueOf(x), w);
public void put(double x, int w) {
dumpString(realToString(x), w);
} // Also handles float.
public void put(char x, int w) {
dumpString(String.valueOf(x), w);
public void put(boolean x, int w) {
dumpString(String.valueOf(x), w);
public void put(String x, int w) {
dumpString(x, w);
// Methods for reading in the primitive types, plus "words" and "lines".
// The "getln..." methods discard any extra input, up to and including
// the next carriage return.
// A "word" read by getlnWord() is any sequence of non-blank characters.
// A "line" read by getlnString() or getln() is everything up to next CR;
// the carriage return is not part of the returned value, but it is
// read and discarded.
// Note that all input methods except getAnyChar(), peek(), the ones for lines
// skip past any blanks and carriage returns to find a non-blank value.
// getln() can return an empty string; getChar() and getlnChar() can
// return a space or a linefeed ('\n') character.
// peek() allows you to look at the next character in input, without
// removing it from the input stream. (Note that using this
// routine might force the user to enter a line, in order to
// check what the next character.)
// Acceptable boolean values are the "words": true, false, t, f, yes,
// no, y, n, 0, or 1; uppercase letters are OK.
// None of these can produce an error; if an error is found in input,
// the user is forced to re-enter.
// Available input routines are:
// getByte() getlnByte() getShort() getlnShort()
// getInt() getlnInt() getLong() getlnLong()
// getFloat() getlnFloat() getDouble() getlnDouble()
// getChar() getlnChar() peek() getAnyChar()
// getWord() getlnWord() getln() getString() getlnString()
// (getlnString is the same as getln and is onlyprovided for consistency.)
public byte getlnByte() {
byte x = getByte();
emptyBuffer();
return x;
public short getlnShort() {
short x = getShort();
emptyBuffer();
return x;
public int getlnInt() {
int x = getInt();
emptyBuffer();
return x;
public long getlnLong() {
long x = getLong();
emptyBuffer();
return x;
public float getlnFloat() {
float x = getFloat();
emptyBuffer();
return x;
public double getlnDouble() {
double x = getDouble();
emptyBuffer();
return x;
public char getlnChar() {
char x = getChar();
emptyBuffer();
return x;
public boolean getlnBoolean() {
boolean x = getBoolean();
emptyBuffer();
return x;
public String getlnWord() {
String x = getWord();
emptyBuffer();
return x;
public String getlnString() {
return getln();
} // same as getln()
public String getln() {
StringBuffer s = new StringBuffer(100);
char ch = readChar();
while (ch != '\n') {
s.append(ch);
ch = readChar();
return s.toString();
public byte getByte() {
return (byte) readInteger( -128L, 127L);
public short getShort() {
return (short) readInteger( -32768L, 32767L);
public int getInt() {
return (int) readInteger((long) Integer.MIN_VALUE,
(long) Integer.MAX_VALUE);
public long getLong() {
return readInteger(Long.MIN_VALUE, Long.MAX_VALUE);
public char getAnyChar() {
return readChar();
public char peek() {
return lookChar();
public char getChar() { // skip spaces & cr's, then return next char
char ch = lookChar();
while (ch == ' ' || ch == '\n') {
readChar();
if (ch == '\n') {
dumpString("? ", 0);
ch = lookChar();
return readChar();
public float getFloat() { // can return positive or negative infinity
float x = 0.0F;
while (true) {
String str = readRealString();
if (str.equals("")) {
errorMessage("Illegal floating point input.",
"Real number in the range " + Float.MIN_VALUE +
" to " + Float.MAX_VALUE);
} else {
Float f = null;
try {
f = Float.valueOf(str);
} catch (NumberFormatException e) {
errorMessage("Illegal floating point input.",
"Real number in the range " + Float.MIN_VALUE +
" to " + Float.MAX_VALUE);
continue;
if (f.isInfinite()) {
errorMessage("Floating point input outside of legal range.",
"Real number in the range " + Float.MIN_VALUE +
" to " + Float.MAX_VALUE);
continue;
x = f.floatValue();
break;
return x;
public double getDouble() {
double x = 0.0;
while (true) {
String str = readRealString();
if (str.equals("")) {
errorMessage("Illegal floating point input",
"Real number in the range " + Double.MIN_VALUE +
" to " + Double.MAX_VALUE);
} else {
Double f = null;
try {
f = Double.valueOf(str);
} catch (NumberFormatException e) {
errorMessage("Illegal floating point input",
"Real number in the range " + Double.MIN_VALUE +
" to " + Double.MAX_VALUE);
continue;
if (f.isInfinite()) {
errorMessage("Floating point input outside of legal range.",
"Real number in the range " + Double.MIN_VALUE +
" to " + Double.MAX_VALUE);
continue;
x = f.doubleValue();
break;
return x;
public String getWord() {
char ch = lookChar();
while (ch == ' ' || ch == '\n') {
readChar();
if (ch == '\n') {
dumpString("? ", 0);
ch = lookChar();
StringBuffer str = new StringBuffer(50);
while (ch != ' ' && ch != '\n') {
str.append(readChar());
ch = lookChar();
return str.toString();
public boolean getBoolean() {
boolean ans = false;
while (true) {
String s = getWord();
if (s.equalsIgnoreCase("true") || s.equalsIgnoreCase("t") ||
s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("y") ||
s.equals("1")) {
ans = true;
break;
} else if (s.equalsIgnoreCase("false") || s.equalsIgnoreCase("f") ||
s.equalsIgnoreCase("no") || s.equalsIgnoreCase("n") ||
s.equals("0")) {
ans = false;
break;
} else {
errorMessage("Illegal boolean input value.",
"one of: true, false, t, f, yes, no, y, n, 0, or 1");
return ans;
// ***************** Everything beyond this point is private *******************
// ********************** Utility routines for input/output ********************
private ConsoleCanvas canvas; // the canvas where I/O is displayed
private String buffer = null; // one line read from input
private int pos = 0; // position next char in input line that has
// not yet been processed
private String readRealString() { // read chars from input following syntax of real numbers
StringBuffer s = new StringBuffer(50);
char ch = lookChar();
while (ch == ' ' || ch == '\n') {
readChar();
if (ch == '\n') {
dumpString("? ", 0);
ch = lookChar();
if (ch == '-' || ch == '+') {
s.append(readChar());
ch = lookChar();
while (ch == ' ') {
readChar();
ch = lookChar();
} while (ch >= '0' && ch <= '9') {
s.append(readChar());
ch = lookChar();
if (ch == '.') {
s.append(readChar());
ch = lookChar();
while (ch >= '0' && ch <= '9') {
s.append(readChar());
ch = lookChar();
if (ch == 'E' || ch == 'e') {
s.append(readChar());
ch = lookChar();
if (ch == '-' || ch == '+') {
s.append(readChar());
ch = lookChar();
} while (ch >= '0' && ch <= '9') {
s.append(readChar());
ch = lookChar();
return s.toString();
private long readInteger(long min, long max) { // read long integer, limited to specified range
long x = 0;
while (true) {
StringBuffer s = new StringBuffer(34);
char ch = lookChar();
while (ch == ' ' || ch == '\n') {
readChar();
if (ch == '\n') {
dumpString("? ", 0);
ch = lookChar();
if (ch == '-' || ch == '+') {
s.append(readChar());
ch = lookChar();
while (ch == ' ') {
readChar();
ch = lookChar();
} while (ch >= '0' && ch <= '9') {
s.append(readChar());
ch = lookChar();
if (s.equals("")) {
errorMessage("Illegal integer input.",
"Integer in the range " + min + " to " + max);
} else {
String str = s.toString();
try {
x = Long.parseLong(str);
} catch (NumberFormatException e) {
errorMessage("Illegal integer input.",
"Integer in the range " + min + " to " + max);
continue;
if (x < min || x > max) {
errorMessage("Integer input outside of legal range.",
"Integer in the range " + min + " to " + max);
continue;
break;
return x;
private static String realToString(double x) {
// Goal is to get a reasonable representation of x in at most
// 10 characters, or 11 characters if x is negative.
if (Double.isNaN(x)) {
return "undefined";
if (Double.isInfinite(x)) {
if (x < 0) {
return "-INF";
} else {
return "INF";
if (Math.abs(x) <= 5000000000.0 && Math.rint(x) == x) {
return String.valueOf((long) x);
String s = String.valueOf(x);
if (s.length() <= 10) {
return s;
boolean neg = false;
if (x < 0) {
neg = true;
x = -x;
s = String.valueOf(x);
if (x >= 0.00005 && x <= 50000000 &&
(s.indexOf('E') == -1 && s.indexOf('e') == -1)) { // trim x to 10 chars max
s = round(s, 10);
s = trimZeros(s);
} else if (x > 1) { // construct exponential form with positive exponent
long power = (long) Math.floor(Math.log(x) / Math.log(10));
String exp = "E" + power;
int numlength = 10 - exp.length();
x = x / Math.pow(10, power);
s = String.valueOf(x);
s = round(s, numlength);
s = trimZeros(s);
s += exp;
} else { // constuct exponential form
long power = (long) Math.ceil( -Math.log(x) / Math.log(10));
String exp = "E-" + power;
int numlength = 10 - exp.length();
x = x * Math.pow(10, power);
s = String.valueOf(x);
s = round(s, numlength);
s = trimZeros(s);
s += exp;
if (neg) {
return "-" + s;
} else {
return s;
private static String trimZeros(String num) { // used by realToString
if (num.indexOf('.') >= 0 && num.charAt(num.length() - 1) == '0') {
int i = num.length() - 1;
while (num.charAt(i) == '0') {
i--;
if (num.charAt(i) == '.') {
num = num.substring(0, i);
} else {
num = num.substring(0, i + 1);
return num;
private static String round(String num, int length) { // used by realToString
if (num.indexOf('.') < 0) {
return num;
if (num.length() <= length) {
return num;
if (num.charAt(length) >= '5' && num.charAt(length) != '.') {
char[] temp = new char[length + 1];
int ct = length;
boolean rounding = true;
for (int i = length - 1; i >= 0; i--) {
temp[ct] = num.charAt(i);
if (rounding && temp[ct] != '.') {
if (temp[ct] < '9') {
temp[ct]++;
rounding = false;
} else {
temp[ct] = '0';
ct--;
if (rounding) {
temp[ct] = '1';
ct--;
// ct is -1 or 0
return new String(temp, ct + 1, length - ct);
} else {
return num.substring(0, length);
private void dumpString(String str, int w) { // output string to console
for (int i = str.length(); i < w; i++) {
canvas.addChar(' ');
for (int i = 0; i < str.length(); i++) {
if ((int) str.charAt(i) >= 0x20 && (int) str.charAt(i) != 0x7F) { // no control chars or delete
canvas.addChar(str.charAt(i));
} else if (str.charAt(i) == '\n' || str.charAt(i) == '\r') {
newLine();
private void errorMessage(String message, String expecting) {
// inform user of error and force user to re-enter.
newLine();
dumpString(" *** Error in input: " + message + "\n", 0);
dumpString(" *** Expecting: " + expecting + "\n", 0);
dumpString(" *** Discarding Input: ", 0);
if (lookChar() == '\n') {
dumpString("(end-of-line)\n\n", 0);
} else {
while (lookChar() != '\n') {
canvas.addChar(readChar());
dumpString("\n\n", 0);
dumpString("Please re-enter: ", 0);
readChar(); // discard the end-of-line character
private char lookChar() { // return next character from input
if (buffer == null || pos > buffer.length()) {
fillBuffer();
if (pos == buffer.length()) {
return '\n';
return buffer.charAt(pos);
private char readChar() { // return and discard next character from input
char ch = lookChar();
pos++;
return ch;
private void newLine() { // output a CR to console
canvas.addCR();
private void fillBuffer() { // Wait for user to type a line and press return,
// and put the typed line into the buffer.
buffer = canvas.readLine();
pos = 0;
private void emptyBuffer() { // discard the rest of the current line of input
buffer = null;
public void clearBuffers() { // I expect this will only be called by
// CanvasApplet when a program ends. It should
// not be called in the middle of a running program.
buffer = null;
canvas.clearTypeAhead();
private void jbInit() throws Exception {
this.setNextFocusableComponent(scrollPane);
this.setToolTipText("");
} // end of class Console
============================================================
Class ConsoleCanvas:
/* A class that implements basic console-oriented input/output, for use with
Console.java and ConsolePanel.java. This class provides the basic character IO.
Higher-leve fucntions (reading and writing numbers, booleans, etc) are provided
in Console.java and ConolePanel.java.
(This vesion of ConsoleCanvas is an udate of an earilier version, rewritten to
be compliand with Java 1.1. David Eck; July 17, 1998.)
(Modified August 16, 1998 to add the
a mousePressed method to ConsoleCanvas. The mousePressed method requests
the focus. This is necessary for Sun's Java implementation -- though not,
apparently for anyone else's. Also added: an isFocusTraversable() method)
MouseListener interface and
Minor modifications, February 9, 2000, some glitches in the graphics.
package myproj;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class ConsoleCanvas extends JTextArea implements FocusListener, KeyListener,
MouseListener {
// public interface, constructor and methods
public ConsoleCanvas(int u,int y) {
addFocusListener(this);
addKeyListener(this);
try {
jbInit();
} catch (Exception ex) {
ex.printStackTrace();
public final String readLine() { // wait for user to enter a line of input;
// Line can only contain characters in the range
// ' ' to '~'.
return doReadLine();
public final void addChar(char ch) { // output PRINTABLE character to console
putChar(ch);
public final void addCR() { // add a CR to the console
putCR();
public synchronized void clear() { // clear console and return cursor to row 0, column 0.
if (OSC == null) {
return;
currentRow = 0;
currentCol = 0;
OSCGraphics.setColor(Color.white);
OSCGraphics.fillRect(4, 4, getSize().width - 8, getSize().height - 8);
OSCGraphics.setColor(Color.black);
repaint();
try {
Thread.sleep(25);
} catch (InterruptedException e) {}
// focus and key event handlers; not meant to be called excpet by system
public void keyPressed(KeyEvent evt) {
doKey(evt.getKeyChar());
public void keyReleased(KeyEvent evt) {}
public void keyTyped(KeyEvent evt) {}
public void focusGained(FocusEvent evt) {
doFocus(true);
public void focusLost(FocusEvent evt) {
doFocus(false);
public boolean isFocusTraversable() {
// Allows the user to move the focus to the canvas
// by pressing the tab key.
return true;
// Mouse listener methods -- here just to make sure that the canvas
// gets the focuse when the user clicks on it. These are meant to
// be called only by the system.
public void mousePressed(MouseEvent evt) {
requestFocus();
public void mouseReleased(MouseEvent evt) {}
public void mouseClicked(MouseEvent evt) {}
public void mouseEntered(MouseEvent evt) {}
public void mouseExited(MouseEvent evt) {}
// implementation section: protected variables and methods.
protected StringBuffer typeAhead = new StringBuffer();
// Characters typed by user but not yet processed;
// User can "type ahead" the charcters typed until
// they are needed to satisfy a readLine.
protected final int maxLineLength = 256;
// No lines longer than this are returned by readLine();
// The system effectively inserts a CR after 256 chars
// of input without a carriage return.
protected int rows, columns; // rows and columns of chars in the console
protected int currentRow, currentCol; // current curson position
protected Font font; // Font used in console (Courier); All font
// data is set up in the doSetup() method.
protected int lineHeight; // height of one line of text in the console
protected int baseOffset; // distance from top of a line to its baseline
protected int charWidth; // width of a character (constant, since a monospaced font is used)
protected int leading; // space between lines
protected int topOffset; // distance from top of console to top of text
protected int leftOffset; // distance from left of console to first char on line
protected Image OSC; // off-screen backup for console display (except cursor)
protected Graphics OSCGraphics; // graphics context for OSC
protected boolean hasFocus = false; // true if this canvas has the input focus
protected boolean cursorIsVisible = false; // true if cursor is currently visible
private int pos = 0; // exists only for sharing by next two methods
public synchronized void clearTypeAhead() {
// clears any unprocessed user typing. This is meant only to
// be called by ConsolePanel, when a program being run by
// console Applet ends. But just to play it safe, pos is
// set to -1 as a signal to doReadLine that it should return.
typeAhead.setLength(0);
pos = -1;
notify();
protected synchronized String doReadLine() { // reads a line of input, up to next CR
if (OSC == null) { // If this routine is called before the console has
// completely opened, we shouldn't procede; give the
// window a chance to open, so that paint() can call doSetup().
try {
wait(5000);
} catch (InterruptedException e) {} // notify() should be set by doSetup()
if (OSC == null) { // If nothing has happened for 5 seconds, we are probably in
// trouble, but when the heck, try calling doSetup and proceding anyway.
doSetup();
if (!hasFocus) { // Make sure canvas has input focus
requestFocus();
StringBuffer lineBuffer = new StringBuffer(); // buffer for constructing line from user
pos = 0;
while (true) { // Read and process chars from the typeAhead buffer until a CR is found.
while (pos >= typeAhead.length()) { // If the typeAhead buffer is empty, wait for user to type something
cursorBlink();
try {
wait(500);
} catch (InterruptedException e) {}
if (pos == -1) { // means clearTypeAhead was called;
return ""; // this is an abnormal return that should not happen
if (cursorIsVisible) {
cursorBlink();
if (typeAhead.charAt(pos) == '\r' || typeAhead.charAt(pos) == '\n') {
putCR();
pos++;
break;
if (typeAhead.charAt(pos) == 8 || typeAhead.charAt(pos) == 127) {
if (lineBuffer.length() > 0) {
lineBuffer.setLength(lineBuffer.length() - 1);
eraseChar();
pos++;
} else if (typeAhead.charAt(pos) >= ' ' &&
typeAhead.charAt(pos) < 127) {
putChar(typeAhead.charAt(pos));
lineBuffer.append(typeAhead.charAt(pos));
pos++;
} else {
pos++;
if (lineBuffer.length() == maxLineLength) {
putCR();
pos = typeAhead.length();
break;
if (pos >= typeAhead.length()) { // delete all processed chars from typeAhead
typeAhead.setLength(0);
} else {
int len = typeAhead.length();
for (int i = pos; i < len; i++) {
typeAhead.setCharAt(i - pos, typeAhead.charAt(i));
typeAhead.setLength(len - pos);
return lineBuffer.toString(); // return the string that was entered
protected synchronized void doKey(char ch) { // process key pressed by user
typeAhead.append(ch);
notify();
private void putCursor(Graphics g) { // draw the cursor
g.drawLine(leftOffset + currentCol * charWidth + 1,
topOffset + (currentRow * lineHeight),
leftOffset + currentCol * charWidth + 1,
topOffset + (currentRow * lineHeight + baseOffset));
protected synchronized void putChar(char ch) { // draw ch at cursor position and move cursor
if (OSC == null) { // If this routine is called before the console has
// completely opened, we shouldn't procede; give the
// window a chance to open, so that paint() can call doSetup().
try {
wait(5000);
} catch (InterruptedException e) {} // notify() should be set by doSetup()
if (OSC == null) { // If nothing has happened for 5 seconds, we are probably in
// trouble, but when the heck, try calling doSetup and proceding anyway.
doSetup();
if (currentCol >= columns) {
putCR();
currentCol++;
Graphics g = getGraphics();
g.setColor(Color.black);
g.setFont(font);
char[] fudge = new char[1];
fudge[0] = ch;
g.drawChars(fudge, 0, 1, leftOffset + (currentCol - 1) * charWidth,
topOffset + currentRow * lineHeight + baseOffset);
g.dispose();
OSCGraphics.drawChars(fudge, 0, 1,
leftOffset + (currentCol - 1) * charWidth,
topOffset + currentRow * lineHeight + baseOffset);
protected void eraseChar() { // erase char before cursor position and move cursor
if (currentCol == 0 && currentRow == 0) {
return;
currentCol--;
if (currentCol < 0) {
currentRow--;
currentCol = columns - 1;
Graphics g = getGraphics();
g.setColor(Color.white);
g.fillRect(leftOffset + (currentCol * charWidth),
topOffset + (currentRow * lineHeight),
charWidth, lineHeight - 1);
g.dispose();
OSCGraphics.setColor(Color.white);
OSCGraphics.fillRect(leftOffset + (currentCol * charWidth),
topOffset + (currentRow * lineHeight),
charWidth, lineHeight - 1);
OSCGraphics.setColor(Color.black);
protected synchronized void putCR() { // move cursor to start of next line, scrolling window if necessary
if (OSC == null) { // If this routine is called before the console has
// completely opened, we shouldn't procede; give the
// window a chance to open, so that paint() can call doSetup().
try {
wait(5000);
} catch (InterruptedException e) {} // notify() should be set by doSetup()
if (OSC == null) { // If nothing has happened for 5 seconds, we are probably in
// trouble, but when the heck, try calling doSetup and proceding anyway.
doSetup();
currentCol = 0;
currentRow++;
if (currentRow < rows) {
return;
OSCGraphics.copyArea(leftOffset, topOffset + lineHeight,
columns * charWidth,
(rows - 1) * lineHeight - leading, 0, -lineHeight);
OSCGraphics.setColor(Color.white);
OSCGraphics.fillRect(leftOffset, topOffset + (rows - 1) * lineHeight,
columns * charWidth, lineHeight - leading);
OSCGraphics.setColor(Color.black);
currentRow = rows - 1;
Graphics g = getGraphics();
paint(g);
g.dispose();
try {
Thread.sleep(20);
} catch (InterruptedException e) {}
protected void cursorBlink() { // toggle visibility of cursor (but don't show it if focus has been lost)
if (cursorIsVisible) {
Graphics g = getGraphics();
g.setColor(Color.white);
putCursor(g);
cursorIsVisible = false;
g.dispose();
} else if (hasFocus) {
Graphics g = getGraphics();
g.setColor(Color.black);
putCursor(g);
cursorIsVisible = true;
g.dispose();
protected synchronized void doFocus(boolean focus) { // react to gain or loss of focus
if (OSC == null) {
doSetup();
hasFocus = focus;
if (hasFocus) { // the rest of the routine draws or erases border around canvas
OSCGraphics.setColor(Color.cyan);
} else {
OSCGraphics.setColor(Color.white);
int w = getSize().width;
int h = getSize().height;
for (int i = 0; i < 3; i++) {
OSCGraphics.drawRect(i, i, w - 2 * i, h - 2 * i);
OSCGraphics.drawLine(0, h - 3, w, h - 3);
OSCGraphics.drawLine(w - 3, 0, w - 3, h);
OSCGraphics.setColor(Color.black);
repaint();
try {
Thread.sleep(50);
} catch (InterruptedException e) {}
notify();
protected void doSetup() { // get font parameters and create OSC
int w = getSize().width;
int h = getSize().height;
font = new Font("Courier", Font.PLAIN, getFont().getSize());
FontMetrics fm = getFontMetrics(font);
lineHeight = fm.getHeight();
leading = fm.getLeading();
baseOffset = fm.getAscent();
charWidth = fm.charWidth('W');
columns = (w - 12) / charWidth;
rows = (h - 12 + leading) / lineHeight;
leftOffset = (w - columns * charWidth) / 2;
topOffset = (h + leading - rows * lineHeight) / 2;
OSC = createImage(w, h);
OSCGraphics = OSC.getGraphics();
OSCGraphics.setFont(font);
OSCGraphics.setColor(Color.white);
OSCGraphics.fillRect(0, 0, w, h);
OSCGraphics.setColor(Color.black);
notify();
public void update(Graphics g) {
paint(g);
public synchronized void paint(Graphics g) {
if (OSC == null) {
doSetup();
g.drawImage(OSC, 0, 0, this);
private void jbInit() throws Exception {
===============================================================
and finally Consola:
package myproj;
/* The Consola provides a basis for writing applets that simulate
line-oriented consola-type input/output. The class ConsoleCanvas is
used to provide the I/O routines; these routines type output into
the ConsoleCanvas and read input typed there by the user. See the
files CanvasPanel.java and ConsoleCanvas.java for information.
A consola applet is set up to run one particular program. The applet
includes a button that the user presses to run the program (or to
abort it when it is running). It also includes a label, which by default
is "Java I/O consola". The default program, defined in this file,
is a simple Hello World program.
To write a new consola applet, with a more interesting program, you
should create a subclass of Consola. The subclass should
override the method program() , which represents the program to
be run. The program should use the instance variable, consola, to
do input/output. For example, consola.putln("HelloWorld.")
or N=consola.getInt(). All the public methods of class ConsolePanel
can be called in the program.
(Of course, you could also just modify this file, instead of
writing a subclass.)
import java.awt.*;
import java.awt.event.*;
import myproj.ConsoleCanvas;
import myproj.ConsolePanel;
import java.util.*;
import javax.swing.JScrollPane;
import javax.swing.JList;
import javax.swing.*;
import java.io.*;
public class Consola extends java.applet.Applet implements Runnable,
ActionListener {
public Consola() {
try {
jbInit();
} catch (Exception ex) {
ex.printStackTrace();
protected String title = "Configure Vlan "; // (Used for compatibility with previous versions of consola Applet)
protected String getTitle() {
// Return a label to appears over the consola;
// If you want to change the label, override this
// method to return a different string.
return title;
//variabilele mele
static String[] Foo={"Fa0/1","Fa0/2","Fa0/3","Fa0/4","Fa0/5","Fa0/6","Fa0/7","Fa0/8","Fa0/9","F a0/10","Fa0/11","Fa0/12"};
static String[] vlan={"","","","","","","","","","","",""};
static String [] showdefault={"","","","","","","","","","","",""};
stat

First thing...you made a mistake
import javax.swing.JScrollPane;
import javax.swing.JScrollBar;
import javax.swing.*;When you import javax.swing.*; You automatically
import JScrollPane & JScrollBar class, there's no
need for you to re import again...
That is not always a mistake. There are cases where it makes sense to do both (i.e., to import both '*' and a specific class name from that package at the same time). I believe the common example is:
import java.awt.*;
import java.util.*;
import java.util.List;Now you can use "List" as a short name for "java.util.List", but must use "java.awt.List" in full for "java.awt.List" objects. If you just did:
import java.awt.*;
import java.util.*;Then you couldn't use List as a short name for anything--because it is ambiguous. You'd have to use both "java.awt.List" and "java.util.List" spelled out in full.
Or, if you did:
import java.awt.*;
import java.util.*;
import java.awt.List; // NOTE CHANGEThen "List" is short for "java.awt.List", and you must use "java.util.List" in full for "java.awt.List" objects.

Similar Messages

  • How to add vertical scrollbar to a tree region

    Hi,
    I have a page containing two regions. The first is a tree region displayed on the left hand side of the page. The second is form region displayed to the right of the tree, showing details relating to the selected node from the tree.
    How can I add a vertical scrollbar to the tree, so that I can I browse all nodes in the tree without affecting the position of the form? Currently, if my tree extends beyond the height of the page I have to use the page vertical scrollbar to view the bottom of the tree. This obviously means that the form is no longer in view.
    Thanks
    Andrew.

    Hi Andrew,
    You can't add a scrollbar directly to the region's contents, but you can wrap the contents within a DIV tag.
    In the Region Header add in:
    &lt;DIV style="height:500px; overflow:auto"&gt;
    In the Region Footer add in:
    &lt;/DIV&gt;
    Obviously, change the height value to suit your needs.
    Regards
    Andy

  • How to Add Horizontal scrollbar to JTextPane

    when i try to add Horizontal scrollbar to JTextPane it is not apperaing..plase help me..
    nagesh

    I tried in all ways
    1)HORIZONTAL_SCROLLBAR_ALWAYS and VERTICAL_SCROLLBAR_ALWAYS
    2)JTextPane textPane = new JTextPane();
    JScollPane scroller = new JScrollPane(textPane);
    or :
    3)JScollPane scroller = new JScrollPane(textPane, VERTICAL_SCROLLBAR_ALWAYS, HORIZONTAL_SCROLLBAR_ALWAYS);
    4)JScrollPane.setHorizontalScrollBarPolicy(
                   ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
                   JScrollPane.setVerticalScrollBarPolicy(
                   ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    and also we tried to overwrite the setbounds also, but nothing is diplaying..

  • How to add jar files to applet's classpath

    hi everyone,
    i got an issue to add jar file's to applt's classpath,
    i looked around accross many resources but getting no solution on this.
    i have a commons-httpclient3.1.jar and i have to make it available it to a an applet class bundled in a jar file say myjar.jar
    how can i achieve it?
    any help would be much appreciated
    thanks

    That's a long time I haven't written applets, but if I remind well, we are able to set multilple jar in the classapth parameter, separated by semicolon.
    Look the page http://java.sun.com/docs/books/tutorial/deployment/applet/html.html
    Edited by: jswim on Dec 6, 2007 3:51 PM

  • How to add scrollbar to jpopup menu

    Hi everyone,
    Do u know how to add a scrollbar to jpopup menu ?

    Menus don't scroll, and shouldn't scroll. Given that, you shouldn't try and use JPopupMenu at all... rather, create your own component that implements the look and behavior you want. It will be far easier and less frustrating.
    Either that... or you should re-think what functionality you are trying to provide, and how you are trying to implement it. A scrolling menu just seems like a counterintuitive wacky UI design to me.

  • How to add images into a java application (not applet)

    Hello,
    I am new in java programming. I would like to know how to add images into a java application (not an applet). If i could get an standard example about how to add a image to a java application, I would apreciated it. Any help will be greatly apreciated.
    Thank you,
    Oscar

    Your' better off looking in the java 2d forum.
    package images;
    import java.awt.*;
    import java.awt.image.*;
    import java.io.FileInputStream;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    /** * LogoImage is a class that is used to load images into the program */
    public class LogoImage extends JPanel {
         private BufferedImage image;
         private int factor = 1; /** Creates a new instance of ImagePanel */
         public LogoImage() {
              this(new Dimension(600, 50));
         public LogoImage(Dimension sz) {
              //setBackground(Color.green);      
              setPreferredSize(sz);
         public void setImage(BufferedImage im) {
              image = im;
              if (im != null) {
                   setPreferredSize(
                        new Dimension(image.getWidth(), image.getHeight()));
              } else {
                   setPreferredSize(new Dimension(200, 200));
         public void setImageSizeFactor(int factor) {
              this.factor = factor;
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
              //paint background 
              Graphics2D g2D = (Graphics2D) g;
              //Draw image at its natural size first. 
              if (image != null) {
                   g2D.drawImage(image, null, 0, 0);
         public static LogoImage createImage(String filename) { /* Stream the logo gif file into an image object */
              LogoImage logoImage = new LogoImage();
              BufferedImage image;
              try {
                   FileInputStream fileInput =
                        new FileInputStream("images/" + filename);
                   image = ImageIO.read(fileInput);
                   logoImage =
                        new LogoImage(
                             new Dimension(image.getWidth(), image.getHeight()));
                   fileInput.close();
                   logoImage.setImage(image);
              } catch (Exception e) {
                   System.err.println(e);
              return logoImage;
         public static void main(String[] args) {
              JFrame jf = new JFrame("testImage");
              Container cp = jf.getContentPane();
              cp.add(LogoImage.createImage("logo.gif"), BorderLayout.CENTER);
              jf.setVisible(true);
              jf.pack();
    }Now you can use this class anywhere in your pgram to add a JPanel

  • How to add scroll function in  the applet launched by  Java Web Start?

    I have Java Web Start installed in order for the applet to launch.The applet size: width:700 height:1000
    my compuer resolution:800*600
    the applet launched by Java Web Start can only be seen partly,especially height.How to add scroll function in the applet launched by Java Web Start?
    Thanks for help.
    email:[email protected]

    You can very easily add a JScrollPane manually between the Applet and your content. Perhaps it would be beter if javaws did this automatically. In the browser, an applet can be any size. In Java Web Start an applet is directly contained within a JFrame, so it cannot be smaller than the minimum size of a JFrame, or Larger than the max.

  • How to add scrollbar to the JInternal Frame

    How to add scrollbar to JInternal Frame?
    I have One JInternal frame i want it should have a scrollbar when we reduces its size.

    [url http://java.sun.com/docs/books/tutorial/uiswing/components/scrollpane.html]How to Use Scroll Panes

  • How to add checkboxes to frame

    So I have two classes in my package. I am having trouble adding the checkbox group to my frame. I got it to add to my applet but I can not figure out how to add it to my frame. Here is what I have so far. When I run this program it puts the checkboxes in my applet and not in my frame.
    this is my painter class:
    package pt;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2006</p>
    * <p>Company: </p>
    * @author unascribed
    * @version 1.0
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    public class painter extends Applet {
    private int xValue=-10, yValue=-10;
    MyFrame x;
    Checkbox Red, Black, Magenta, Blue, Green, Yellow;
    CheckboxGroup cbg;
    public void init()
    x= new MyFrame("Christie's Window");
    x.show();
    x.resize(250,100);
    cbg = new CheckboxGroup();
           Red = new Checkbox("Red", cbg,true);
           Black = new Checkbox("Black", cbg,false);
           Magenta = new Checkbox("Magenta",cbg,false);
           Blue = new Checkbox("Blue", cbg, false);
           Green = new Checkbox("Green", cbg, false);
           Yellow = new Checkbox("Yellow", cbg, false);
           add(Red);
           add(Black);
           add(Magenta);
           add(Blue);
           add(Green);
           add(Yellow);
         addMouseMotionListener(new MotionHandler(this));
    public void paint(Graphics g)
    g.drawString("Drag the mouse to draw", 10, 20);
    g.fillOval(xValue, yValue, 4,4);
    //Override Component class update method to allow all ovals
    // to remain on the screen by not clearing the background
    public void update(Graphics g)   { paint(g); }
    // set the drawing coordinates and repaint
    public void setCoordinates(int x, int y)
      xValue = x;
      yValue = y;
      repaint();
    // Class to handle only mouse drag events for the Drag applet
    class MotionHandler extends MouseMotionAdapter {
      private painter dragger;
      public MotionHandler(painter d)  { dragger = d; }
      public void mouseDragged( MouseEvent e)
        { dragger.setCoordinates( e.getX(), e.getY() );   }
        } and here is MyFrame class:
    package pt;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2006</p>
    * <p>Company: </p>
    * @author unascribed
    * @version 1.0
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    public class MyFrame extends Frame {
    MyFrame(String x){
       super(x);
        public boolean handleEvent(Event evtObj) {
          if(evtObj.id==Event.WINDOW_DESTROY) {
            hide();
            return true;
          return super.handleEvent(evtObj);
    }

    here's your conversion, with listeners to change the color
    //import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    //public class painter extends Applet {
    class painter extends Frame {
    Color color = Color.RED;
    private int xValue=-10, yValue=-10;
    //MyFrame x;
    Checkbox Red, Black, Magenta, Blue, Green, Yellow;
    CheckboxGroup cbg;
    //public void init()
    public painter()
    //x= new MyFrame("Christie's Window");
    setTitle("Christie's Window");
    //x.show();
    //x.resize(250,100);
    setSize(600,400);
    setLocation(200,100);
    cbg = new CheckboxGroup();
           Red = new Checkbox("Red", cbg,true);
           Red.addItemListener(new ItemListener(){
            public void itemStateChanged(ItemEvent ie){
              if(Red.getState()) color = Color.RED;}});
           Black = new Checkbox("Black", cbg,false);
           Black.addItemListener(new ItemListener(){
            public void itemStateChanged(ItemEvent ie){
              if(Black.getState()) color = Color.BLACK;}});
           Magenta = new Checkbox("Magenta",cbg,false);
           Magenta.addItemListener(new ItemListener(){
            public void itemStateChanged(ItemEvent ie){
              if(Magenta.getState()) color = Color.MAGENTA;}});
           Blue = new Checkbox("Blue", cbg, false);
           Blue.addItemListener(new ItemListener(){
            public void itemStateChanged(ItemEvent ie){
              if(Blue.getState()) color = Color.BLUE;}});
           Green = new Checkbox("Green", cbg, false);
           Green.addItemListener(new ItemListener(){
            public void itemStateChanged(ItemEvent ie){
              if(Green.getState()) color = Color.GREEN;}});
           Yellow = new Checkbox("Yellow", cbg, false);
           Yellow.addItemListener(new ItemListener(){
            public void itemStateChanged(ItemEvent ie){
              if(Yellow.getState()) color = Color.YELLOW;}});
    Panel p = new Panel();
           p.add(Red);
           p.add(Black);
           p.add(Magenta);
           p.add(Blue);
           p.add(Green);
           p.add(Yellow);
    add(p,BorderLayout.NORTH);
         addMouseMotionListener(new MotionHandler(this));
    addWindowListener(new WindowAdapter(){
          public void windowClosing(WindowEvent we) { System.exit(0); }});
    public void paint(Graphics g)
    super.paint(g);
    g.setColor(color);
    g.drawString("Drag the mouse to draw", 10, 75);
    g.fillOval(xValue, yValue, 4,4);
    //Override Component class update method to allow all ovals
    // to remain on the screen by not clearing the background
    public void update(Graphics g)   { paint(g); }
    // set the drawing coordinates and repaint
    public void setCoordinates(int x, int y)
      xValue = x;
      yValue = y;
      repaint();
    // Class to handle only mouse drag events for the Drag applet
    class MotionHandler extends MouseMotionAdapter {
      private painter dragger;
      public MotionHandler(painter d)  { dragger = d; }
      public void mouseDragged( MouseEvent e)
        { dragger.setCoordinates( e.getX(), e.getY() );   }
      public static void main(String[] args){new painter().setVisible(true);}
    }

  • How to add a scroll bar within a view window ?I want to display x and y axis outside the scoll window and keep those axis static and move the graph within scroll area

    how to add a scroll bar within a view window ?I want to display x and y axis outside the scoll window and keep those axis static and move the graph within scroll area
    ananya

    Hey Ananya,
    I believe what you want to do is possible, but it will not be
    easy.  If you want to add a scroll bar that will scroll the graph
    back and forth but keep the axis set, you would want to add a
    horizontal or vertical scrollbar.  Then you would create an event
    handler for the scroll event.  You would have to manually plot
    different data within this scroll event.  Unfortunately, there is
    not really a built in way to do this with the Measurement Studio plot
    control.
    Thanks,
    Pat P.
    Software Engineer
    National Instruments

  • How to add Panel in JScrollPane? URGENT!

    I need to add a Panel in JScrollPane
    I have try to add JPanel into JScrollPane, but apparently, the JPanel did not show up at all in the JScrollPane (all i see is the border of JScrollPane)
    Then I switch my JPanel to Panel (awt) and it does appear on the JScrollPane, but scrollbars are not visible even i have set the size of the panel is larger than the JScrollPane. (and i also set the VERTICAL_SCROLLBARS_ALWAYS) I can scroll with my mousewhieel, but the panel can scroll out of place(ie outside of the Jscrollpane)
    Can someone teach me how to add a Panel or JPanel to a JScrollPane Please~ Thanks!!!

    here is an example that illustrate my problem:
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.filechooser.*;
    public class testing extends JFrame
         public testing()
              Container pane=getContentPane();
              pane.setLayout(null);
              setSize(600,600);
              JPanel backgroundpanel= new JPanel();
              backgroundpanel.setLayout(null);
              backgroundpanel.setSize(500,500);
              backgroundpanel.setLocation(0,0);
              Panel insidepanel = new Panel();
              insidepanel.setLayout(null);
              insidepanel.setSize(300,300);
              insidepanel.setLocation(0,0);
              JLabel something= new JLabel("something");
              JTextField someTF= new JTextField(10);
              something.setSize(100,20);
              something.setLocation (20,20);
              someTF.setSize(100,20);
              someTF.setLocation(50,60);
              insidepanel.add(something);
              insidepanel.add(someTF);
              JScrollPane scrollpane= new JScrollPane(insidepanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS );
              scrollpane.setSize(200,200);
              scrollpane.setLocation(10,10);
              backgroundpanel.add(scrollpane);
              pane.add(backgroundpanel);
              setVisible(true);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
         public static void main(String args[]) throws FileNotFoundException, IOException
                        testing test=new testing();
    apparently, the panel i add in teh scrollpane is on the top layer instead of inside the scroll... can anyone help?

  • How to call JSP page from applet?

    I have some page1.jsp from which I call applet.
    User works with this applet but some information does not in date inside applet.
    So user click on some component at applet (some button etc.) and now I would like to do this:
    1) open new window;
    2) call page2.jsp at this new window.
    The reason is that page2.jsp will read some data from database and then displays it in HTML inside page2.jsp itself. It is not necessary to pass these date back to applet for displaying them inside of applet.
    So user then can have 2 windows: page1.jsp with applet and page2.jsp with some details information.
    But I DO NOT know how to call page2.jsp from applet, and do ti in a new window. Is it possible and how?
    Thanks
    Mirek

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class MainMenu extends JApplet implements ActionListener
         private JMenuBar mbar;
         private JMenu Master,Leave,Report,Logout;
         private JMenuItem UserMaster,DeptMaster,DesignationMaster,LeaveAvailable,LeaveApply,Generate;
         private JPanel jp;
         public void init()
              mbar=new JMenuBar();
              Master=new JMenu("Master");
              Leave=new JMenu("Leave");
         Report=new JMenu("Report");
              Logout=new JMenu("Logout");
              UserMaster=new JMenuItem("UserMaster");
              UserMaster.setMnemonic('U');
              DeptMaster=new JMenuItem("DeptMaster");
              DeptMaster.setMnemonic('D');
              DesignationMaster=new JMenuItem("DesignationMaster");
              DesignationMaster.setMnemonic('D');
              LeaveAvailable=new JMenuItem("LeaveAvailable");
              LeaveAvailable.setMnemonic('L');
              LeaveApply=new JMenuItem("LeaveApply");
              LeaveApply.setMnemonic('L');
              Generate=new JMenuItem("Generate");
              Generate.setMnemonic('G');
              Master.add(UserMaster);
              Master.add(DeptMaster);
              Master.add(DesignationMaster);
              mbar.add(Master);
              Leave.add(LeaveAvailable);
              Leave.add(LeaveApply);
              mbar.add(Leave);
              Report.add(Generate);
              mbar.add(Report);
              mbar.add(Logout);
              UserMaster.addActionListener(this);
              DeptMaster.addActionListener(this);
              DesignationMaster.addActionListener(this);
              LeaveAvailable.addActionListener(this);
              LeaveApply.addActionListener(this);
              Generate.addActionListener(this);
              Logout.addActionListener(this);
              mbar.setVisible(true);
              Container con=getContentPane();
              con.add(mbar,BorderLayout.NORTH);
         public void actionPerformed(ActionEvent ae){
              if(ae.getSource()==UserMaster)
              }

  • How to add scroll bar to JDesktopPane?

    Hi All,
         After download the "InternalFrameDemo.java" from the swing tutorial, I want to add scrollbars to JDesktopPane so that whenever a internal frame moves off the desktop view port, a scrollbar will display. I have tried many ways to implement this but no success.
    Do you know how to add scrollbars to JDesktopPane?
    Thanks
    Anson

    You can't get there from here! Assuming that wou want is to make the desktop scrollable that is.
    The trick to make somthing scrollable is to make JScrollPane CONTAIN the component to be scrolled. If you could ask the desktop to return the component it contains, you might have a chance but no luck, the desktop pane actually inherits a layered pane which is most likey is what you would like JScrollPane to contain.
    Now here's another angle to this story... the desktop is complex enough without scrollbars, why would you want to complicate things by adding a scroll bar anyway? Say one of its window is maximized and has a scrollbar of its own AND the desktop has one.... that makes TWO scroll bars side by side. Talk about confusing.
    I believe the desktop was designed so scroll bars can't be added for a very good reason: good UI practises.

  • How to add javafx image project in my jsp page ?

    how to add javafx image project in my jsp page ?

    Create your JavaFX application as an Applet... then embed the applet object inside your html. I'm sure if you create a javafx netbeans project and hit build... you get a html file that shows you how to load the built binary output into the page.

  • How to add control buttons using Java thorugh serial port?

    Hi everyone,
    I'm new to this forum.
    I have some questions on Java and serial port.
    I want to write a Java program to control my robot, through serial port. For example, when I click "Forward", the robot will go forward, and so on.
    Now I already have the buttons, so next I would like to ask how to interface the buttons with the serial port.
    I already have all the javax.comm things installed.
    below is the code for my buttons:
    import java.awt.*;
    public class ControlButtons extends java.applet.Applet
         GridLayout myLayout = new GridLayout(3, 3);
         Button button1 = new Button(" ");
         Button buttonForward = new Button("Forward");
         Button button2 = new Button(" ");
         Button buttonLeft = new Button("Left");
         Button buttonStop = new Button("Stop");
         Button buttonRight = new Button("Right");
         Button button3 = new Button(" ");
         Button buttonReverse = new Button("Reverse");
         Button button4 = new Button(" ");
         public void init()
              setLayout(myLayout);
              add(button1);
              button1.setVisible(false);
              add(buttonForward);
              add(button2);
              button2.setVisible(false);
              add(buttonLeft);
              add(buttonStop);
              add(buttonRight);
              add(button3);
              button3.setVisible(false);
              add(buttonReverse);
              add(button4);
              button4.setVisible(false);
    }Now I would like to ask for direction on how to add in the code to make it work with serial port.
    Thanks

    The plan is, I have a robot device connected to the serial port.We don't know anything about that device. We don't know how to control it. We don't know what you have to write to the device to make it do anything. Only you know what.
    For example, when I click "Forward", the robot will go forward, and so on.So what do you have to send to make it do that? and same for the other buttons.
    Next, you need to work out from the javax.comm API how to open the serial port and send data to it. This is a standard exercise in learning a new API. You must be able to do this. Again and again.
    But the program is useless. The button can be clicked, but didn't do anything.Because (a) they have no ActionListeners and (b) there is no code to send anything to the serial port.
    You have to write all that. So you also have to look up ActionListener in the Java API and how to attach it to a button. You can do that. We all do that kind of thing every day.
    So next I would like to ask how to interface the buttons with the serial port.You've been asking nothing else since you started, but you've also only done enough investigation of your own to create the buttons. That's only the start.
    The problem is what method and command should I use to make those buttons actually functioning.See above. You've been told part of it several times. The rest only you can answer, because it's your robot.

Maybe you are looking for

  • I dont see computers on the network on the side bar in finder

    Hi I am new to mac ( 2 days ) I am connected to a wireless network with a couple of pc's but I cant see them in the finder bar or any other network items.... I have enabled sharing on the Pc's and I can see the mac book on them and transfer files etc

  • Two cameras at the same time Lab view (NI MAX)

    I have two similar Point Grey Firefly MV cameras. I need to use them simultaneously in LabVIEW, but NI MAX only detects one at the same time (the two cameras are detected properly separately). I think that NI MAX identifies both camera as the same ca

  • Getting sucess message as output could not be issued after the printout

    hi, in the Transacation VF02 i want to print my Z smartform. so in the NACE transaction i have copied the RD00 and created Z entry and the Zsmartform.but the After printing the smartform i am getting the success message in the bottom of the screen as

  • Flex swc library in Flash CS3 project

    Is it possible to use a swc library created in Flex in a Flash CS3 project?

  • Service via Automator not showing up

    I checked to make sure the service was enabled (in system preferences), and it was.  Any body have any ideas on other reasons the service isn't available in the app? Thanks in advance