Add 2 MC scrollpane

I can add a lot of text to scrollpane and scrollbars appear
but how do I also add another movie clip? I want text and images to
appear in the scrollpane .
I cant do both as in contentPath I add the name of the movie
clip but only 1?

You can create a movie clip, add images, add text, then set a
linkage id in the library, use contentPath to load it.

Similar Messages

  • Add Dynamic Content to ScrollPane

    I have created a Address Class that uses Remote Hosting to
    get addresses for site locations and creates the appropriate
    listings in a MovieClip.
    I am trying to use this class as the source for a scroll pane
    inside another movie clip.
    I get the site locations to show up in the scrollPane but
    they will not scroll.
    I believe I need to pause some how in the constructor until I
    have all the site addresses created.
    Anyone know how I would do that or know how to get the
    scrollpane to scroll.
    Thanks
    Adam
    Here are some snippets
    The container MovieClip
    import FlashCFMXApplication.AL_Addresses;
    import fl.containers.ScrollPane;
    var scrollPane:ScrollPane;
    scrollPane = new ScrollPane;
    scrollPane.scrollDrag = true;
    scrollPane.width = 270;
    scrollPane.height = 380;
    scrollPane.y = -180;
    scrollPane.source = new AL_Addresses;
    addChild(scrollPane);
    stop();
    AL_Addresses.as
    package FlashCFMXApplication{
    import flash.display.Sprite
    public class AL_Addresses extends Sprite
    import flash.display.*;
    import flash.text.TextField;
    import flash.text.TextFormat;
    import flash.net.Responder;
    import fl.data.DataProvider;
    import FlashCFMXApplication.ArrayCollectionDP
    private var siteTitleFormat:TextFormat;
    private var siteCityFormat:TextFormat;
    private var requestObject = new Object;
    private var getStateSites = new Responder(getSites,
    onFault);
    private var getStats = new Responder(getSiteStats, onFault);
    public var maxWidth:int;
    public var Addresses_mc = new MovieClip();
    public var getStateSites_mc:MovieClip;
    public var box:Shape = new Shape();
    public function AL_Addresses() {
    import flash.net.NetConnection;
    var myService:NetConnection;
    myService = new NetConnection();
    //set encoding to AMF0 for complex objects
    myService.objectEncoding = 0;
    myService.connect("
    http://site.com/flashservices/gateway")
    requestObject.requestType = "rs"
    requestObject.requestData = "AL";
    myService.call( "sites.functions.getStateSites" ,
    getStateSites,requestObject);
    private function getSites(result){
    siteTitleFormat = new TextFormat();
    siteTitleFormat.font = "Arial";
    siteTitleFormat.size = 13; //12
    siteTitleFormat.color = 0xBCBCBC;
    siteTitleFormat.bold = true;
    siteCityFormat = new TextFormat();
    siteCityFormat.font = "Arial";
    siteCityFormat.size = 13; //12
    siteCityFormat.color = 0xF87A04;
    siteCityFormat.bold = true;
    var myDataProvider:DataProvider;
    myDataProvider = new DataProvider();
    myDataProvider =
    ArrayCollectionDP.toDataProvider(result.SITES_RS);
    var x:int = 10;
    var y:int = 5;
    var tmp_mc:MovieClip;
    for (var i:int = 0; i <= myDataProvider.length-1; i++){
    var x_text:int = 0;
    var y_text:int = 0;
    tmp_mc = new MovieClip;
    var Name:TextField = new TextField();
    Name.width = 270;
    Name.x = x_text;
    Name.y = y_text;
    Name.text = myDataProvider.getItemAt(i).NAME;
    Name.setTextFormat(siteTitleFormat);
    tmp_mc.addChild(Name);
    y_text = y_text + 15
    var Address:TextField = new TextField();
    Address.width = 270;
    Address.x = x_text;
    Address.y = y_text;
    Address.text = myDataProvider.getItemAt(i).ADDRESS;
    Address.setTextFormat(siteTitleFormat);
    tmp_mc.addChild(Address);
    y_text = y_text + 15
    var City:TextField = new TextField();
    City.x = x_text;
    City.y = y_text;
    City.text = myDataProvider.getItemAt(i).CITY;
    City.setTextFormat(siteCityFormat);
    tmp_mc.addChild(City);
    x_text = x_text + City.textWidth + 5;
    var State:TextField = new TextField();
    State.width = 100;
    State.x = x_text;
    State.y = y_text;
    State.text = myDataProvider.getItemAt(i).STATE;
    State.setTextFormat(siteTitleFormat);
    tmp_mc.addChild(State);
    x_text = x_text + State.textWidth + 3;
    var Zip:TextField = new TextField();
    Zip.x = x_text;
    Zip.y = y_text;
    Zip.text = myDataProvider.getItemAt(i).ZIP;
    Zip.setTextFormat(siteTitleFormat);
    tmp_mc.addChild(Zip);
    tmp_mc.x = x;
    tmp_mc.y = y;
    Addresses_mc.addChild(tmp_mc);
    y = y + 120;
    getStateSites_mc.addChild(Addresses_mc);
    public function onFault( f){
    trace("There was a problem: " + f.description);
    }//class
    } //package

    I don't see it in your code anywhere, but maybe you removed
    it (or I'm just not seeing it). You should update it only after you
    have filled the scrollpane, not when you add the scrollpane to the
    stage. It is not likely the scrollpane is filled by the time these
    two lines are processed, especially if you are loading content from
    a server...
    scrollPane.source = new AL_Addresses;
    addChild(scrollPane);

  • 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.

  • Need to change pgm to add graphics to deskpane (desk) not the overlay panel

    Hello everybody.
    I recently had help in adding graphics to my program and I unintentionally requested that my graphics be added to a overlay panel. After further development I realized that I actually need the graphics to be painted to jdeskpane DESK. I assume that by doing this that the graphics will remain where I placed them (relative to the associated frames) when the scrollbar is utilized.
    This might be a simple question, but I am new to graphics. Once I have the answer, I will analyze it and educate my self further.
    Thank you in advance,
    BAJH
    * Copyright (c) 2007 BAH
    * All rights reserved.
    package com.newsystem.common;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import java.awt.RenderingHints;
    import java.awt.geom.Line2D;
    import java.awt.geom.Point2D;
    import java.awt.geom.Rectangle2D;
    import java.beans.PropertyVetoException;
    import javax.swing.*;
    import javax.swing.JButton;
    import javax.swing.JDesktopPane;
    import javax.swing.JFrame;
    import javax.swing.JInternalFrame;
    import javax.swing.JList;
    import javax.swing.JMenuBar;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.ListModel;
    import javax.swing.ScrollPaneConstants;
    import javax.swing.UIManager;
    import javax.swing.event.InternalFrameEvent;
    import javax.swing.event.InternalFrameListener;
    public class A_Test_of_Frame_Connectors extends JDesktopPane {
         private static final long serialVersionUID = 1L;
         JDesktopPane desk;
         JScrollPane scrollpane;
         JInternalFrame iframe;
         JFrame frame;
         JList jList1;
         String currentframetitle;
         String currentframetip;
         String title;
         Integer maxwidth;
         Boolean definingsecondaryconnector;
         Boolean definingparentsecondaryconnector;
         Boolean definingchildsecondaryconnector;
         Rectangle secondaryparentrectangle;
         Rectangle secondarychildrectangle;
        double barb = 10.0;
        double phi = Math.toRadians(20.0);
        RenderingHints hints;
        Boolean drawline = false;
        Integer connectorcount;
        String[] connectiontype;
        String[] connectorparentframe;
        String[] connectorchildframe;
        JInternalFrame[] allframes;
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHints(hints);
            g2.setPaint(Color.blue);
            if (drawline){
                  drawConnector(g2, secondaryparentrectangle, secondarychildrectangle);
        private void drawConnector(Graphics2D g2,Rectangle r1,Rectangle r2) {
            double dx = r2.getCenterX() - r1.getCenterX();
            double dy = r2.getCenterY() - r1.getCenterY();
            double theta = Math.atan2(dy, dx);
            Point2D.Double p1 = getIntersectionPoint(r1, theta);
            Point2D.Double p2 = getIntersectionPoint(r2, theta+Math.PI);
            Line2D.Double line = new Line2D.Double(p1, p2);
            drawArrowHeads(line, g2);
            g2.draw(line);
         public A_Test_of_Frame_Connectors(){
            hints = new RenderingHints(null);
            hints.put(RenderingHints.KEY_ANTIALIASING,
                      RenderingHints.VALUE_ANTIALIAS_ON);
            hints.put(RenderingHints.KEY_STROKE_CONTROL,
                      RenderingHints.VALUE_STROKE_PURE);
              definingsecondaryconnector = false;
              frame = new JFrame("All Frames in a JDesktopPane Container");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              scrollpane = new JScrollPane(desk,
                        ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
                        ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
              scrollpane.setPreferredSize(new java.awt.Dimension(9925, 9580));
              desk = new JDesktopPane();
              desk.setPreferredSize(new java.awt.Dimension(15000, 30000));
                   int i = 5;
                   for (int j = 1; j <= i; j++){
                        UIManager.getDefaults().put("InternalFrame.icon", "");
                             ListModel jList1Model =
                                  new DefaultComboBoxModel(
                                            new String[] { "Item One" });
                             title = "Frame " + j;
                             jList1 = new JList();
                             jList1.setModel(jList1Model);
                        jList1.setBounds(1, 1, 45, 54);
                        jList1.setEnabled(false);
                        iframe = new JInternalFrame("Internal Frame: " + j, false, false, false, false);
                        iframe.setName(String.valueOf(j));
                        iframe.setTitle(title);
                        Integer titlewidth;
                        if (title.length() < 30){
                             titlewidth = 265;
                        else{
                             titlewidth = title.length()*8 + 20;
                        iframe.setBounds(j*20, j*20,titlewidth , j*18 + 35);
                        iframe.add(jList1);
                        iframe.addInternalFrameListener(new InternalFrameListener(){
                             public void internalFrameClosing(InternalFrameEvent e) {}
                             public void internalFrameClosed(InternalFrameEvent e) {}
                             public void internalFrameOpened(InternalFrameEvent e) {}
                             public void internalFrameIconified(InternalFrameEvent e) {}
                             public void internalFrameDeiconified(InternalFrameEvent e) {}
                             public void internalFrameActivated(InternalFrameEvent e) {
                                  currentframetitle = e.getInternalFrame().getTitle();
                                  currentframetip = e.getInternalFrame().getToolTipText();
                                  // Connectors
                                  if (definingsecondaryconnector.equals(true)){
                                       if (definingparentsecondaryconnector.equals(true)){
                                            // Build dummy rectangle for creating connector                         
                                            secondaryparentrectangle = new Rectangle(e.getInternalFrame().getBounds());
                                            System.out.println("f name - "+e.getInternalFrame().getName());
                                            definingparentsecondaryconnector = false;
                                            definingchildsecondaryconnector = true;
                                       } else {
                                       if (definingchildsecondaryconnector.equals(true)){
                                            // Build dummy rectangle for creating connector                         
                                            secondarychildrectangle = new Rectangle(e.getInternalFrame().getBounds());
                                            // draw connector
                                               drawline = true;
                                               repaint();
                                               definingchildsecondaryconnector = false;
                             public void internalFrameDeactivated(InternalFrameEvent e) {}
                        iframe.setToolTipText("Internal Frame :" + j);
                        iframe.setVisible(true);
                        desk.add(iframe);
              scrollpane.setViewportView(desk);
              JMenuBar menubar = new JMenuBar();
              JButton SecondaryConnector = new JButton("Secondary Connector");
              SecondaryConnector.addMouseListener(new java.awt.event.MouseAdapter() {
                   public void mousePressed(java.awt.event.MouseEvent e) {
                        definingsecondaryconnector = true;
                        definingparentsecondaryconnector = true;
                        definingchildsecondaryconnector = false;                    
                        try {
                             desk.getSelectedFrame().setSelected(false);
                        } catch (PropertyVetoException e1) {
                             // TODO Auto-generated catch block
                             e1.printStackTrace();
              JPanel overlayPanel = new JPanel();
                 OverlayLayout overlay = new OverlayLayout(overlayPanel);
                 overlayPanel.setLayout(overlay);
                 this.setOpaque(false);
                 overlayPanel.add(this);
                 overlayPanel.add(scrollpane);
              menubar.add(SecondaryConnector);
              frame.setJMenuBar(menubar);
    //          frame.add(scrollpane);
              frame.add(overlayPanel);
              scrollpane.setVisible(true);
              frame.setSize(800,600);
              frame.setVisible(true);
        private Point2D.Double getIntersectionPoint(Rectangle r, double theta) {
            double cx = r.getCenterX();
            double cy = r.getCenterY();
            double w = r.getWidth()/2;
            double h = r.getHeight()/2;
            double radius = Point2D.distance(0,0,w,h);
            double x = cx + radius * Math.cos(theta);
            double y = cy + radius * Math.sin(theta);
            Point2D.Double p = new Point2D.Double();
            int outcode = r.outcode(x, y);
            switch(outcode) {
                case Rectangle2D.OUT_TOP:             // 2
                    p.x = cx - h*((x - cx)/(y - cy));
                    p.y = cy - h;
                    break;
                case Rectangle2D.OUT_LEFT:            // 1
                    p.x = cx - w;
                    p.y = cy - w*((y - cy)/(x - cx));
                    break;
                case Rectangle2D.OUT_BOTTOM:          // 8
                    p.x = cx + h*((x - cx)/(y - cy));
                    p.y = cy + h;
                    break;
                case Rectangle2D.OUT_RIGHT:           // 4
                    p.x = cx + w;
                    p.y = cy + w*((y - cy)/(x - cx));
                    break;
                default:
                    System.out.println("Non-cardinal outcode: " + outcode);
            return p;
        private void drawArrowHeads(Line2D.Double line, Graphics2D g2) {
            double dy = line.getY2() - line.getY1();
            double dx = line.getX2() - line.getX1();
            double theta = Math.atan2(dy, dx);
            drawArrowHead(line.getP2(), theta, g2);
            drawArrowHead(line.getP1(), theta+Math.PI, g2);
        private void drawArrowHead(Point2D tip, double theta, Graphics2D g2) {
            double x = tip.getX() - barb * Math.cos(theta+phi);
            double y = tip.getY() - barb * Math.sin(theta+phi);
            g2.draw(new Line2D.Double(tip.getX(), tip.getY(), x, y));
            x = tip.getX() - barb * Math.cos(theta-phi);
            y = tip.getY() - barb * Math.sin(theta-phi);
            g2.draw(new Line2D.Double(tip.getX(), tip.getY(), x, y));
         public static void main(String[] args) {
              A_Test_of_Frame_Connectors d = new A_Test_of_Frame_Connectors();
    }

    Hello everybody.
    I recently had help in adding graphics to my program and I unintentionally requested that my graphics be added to a overlay panel. After further development I realized that I actually need the graphics to be painted to jdeskpane DESK. I assume that by doing this that the graphics will remain where I placed them (relative to the associated frames) when the scrollbar is utilized.
    This might be a simple question, but I am new to graphics. Once I have the answer, I will analyze it and educate my self further.
    Thank you in advance,
    BAJH
    * Copyright (c) 2007 BAH
    * All rights reserved.
    package com.newsystem.common;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import java.awt.RenderingHints;
    import java.awt.geom.Line2D;
    import java.awt.geom.Point2D;
    import java.awt.geom.Rectangle2D;
    import java.beans.PropertyVetoException;
    import javax.swing.*;
    import javax.swing.JButton;
    import javax.swing.JDesktopPane;
    import javax.swing.JFrame;
    import javax.swing.JInternalFrame;
    import javax.swing.JList;
    import javax.swing.JMenuBar;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.ListModel;
    import javax.swing.ScrollPaneConstants;
    import javax.swing.UIManager;
    import javax.swing.event.InternalFrameEvent;
    import javax.swing.event.InternalFrameListener;
    public class A_Test_of_Frame_Connectors extends JDesktopPane {
         private static final long serialVersionUID = 1L;
         JDesktopPane desk;
         JScrollPane scrollpane;
         JInternalFrame iframe;
         JFrame frame;
         JList jList1;
         String currentframetitle;
         String currentframetip;
         String title;
         Integer maxwidth;
         Boolean definingsecondaryconnector;
         Boolean definingparentsecondaryconnector;
         Boolean definingchildsecondaryconnector;
         Rectangle secondaryparentrectangle;
         Rectangle secondarychildrectangle;
        double barb = 10.0;
        double phi = Math.toRadians(20.0);
        RenderingHints hints;
        Boolean drawline = false;
        Integer connectorcount;
        String[] connectiontype;
        String[] connectorparentframe;
        String[] connectorchildframe;
        JInternalFrame[] allframes;
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHints(hints);
            g2.setPaint(Color.blue);
            if (drawline){
                  drawConnector(g2, secondaryparentrectangle, secondarychildrectangle);
        private void drawConnector(Graphics2D g2,Rectangle r1,Rectangle r2) {
            double dx = r2.getCenterX() - r1.getCenterX();
            double dy = r2.getCenterY() - r1.getCenterY();
            double theta = Math.atan2(dy, dx);
            Point2D.Double p1 = getIntersectionPoint(r1, theta);
            Point2D.Double p2 = getIntersectionPoint(r2, theta+Math.PI);
            Line2D.Double line = new Line2D.Double(p1, p2);
            drawArrowHeads(line, g2);
            g2.draw(line);
         public A_Test_of_Frame_Connectors(){
            hints = new RenderingHints(null);
            hints.put(RenderingHints.KEY_ANTIALIASING,
                      RenderingHints.VALUE_ANTIALIAS_ON);
            hints.put(RenderingHints.KEY_STROKE_CONTROL,
                      RenderingHints.VALUE_STROKE_PURE);
              definingsecondaryconnector = false;
              frame = new JFrame("All Frames in a JDesktopPane Container");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              scrollpane = new JScrollPane(desk,
                        ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
                        ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
              scrollpane.setPreferredSize(new java.awt.Dimension(9925, 9580));
              desk = new JDesktopPane();
              desk.setPreferredSize(new java.awt.Dimension(15000, 30000));
                   int i = 5;
                   for (int j = 1; j <= i; j++){
                        UIManager.getDefaults().put("InternalFrame.icon", "");
                             ListModel jList1Model =
                                  new DefaultComboBoxModel(
                                            new String[] { "Item One" });
                             title = "Frame " + j;
                             jList1 = new JList();
                             jList1.setModel(jList1Model);
                        jList1.setBounds(1, 1, 45, 54);
                        jList1.setEnabled(false);
                        iframe = new JInternalFrame("Internal Frame: " + j, false, false, false, false);
                        iframe.setName(String.valueOf(j));
                        iframe.setTitle(title);
                        Integer titlewidth;
                        if (title.length() < 30){
                             titlewidth = 265;
                        else{
                             titlewidth = title.length()*8 + 20;
                        iframe.setBounds(j*20, j*20,titlewidth , j*18 + 35);
                        iframe.add(jList1);
                        iframe.addInternalFrameListener(new InternalFrameListener(){
                             public void internalFrameClosing(InternalFrameEvent e) {}
                             public void internalFrameClosed(InternalFrameEvent e) {}
                             public void internalFrameOpened(InternalFrameEvent e) {}
                             public void internalFrameIconified(InternalFrameEvent e) {}
                             public void internalFrameDeiconified(InternalFrameEvent e) {}
                             public void internalFrameActivated(InternalFrameEvent e) {
                                  currentframetitle = e.getInternalFrame().getTitle();
                                  currentframetip = e.getInternalFrame().getToolTipText();
                                  // Connectors
                                  if (definingsecondaryconnector.equals(true)){
                                       if (definingparentsecondaryconnector.equals(true)){
                                            // Build dummy rectangle for creating connector                         
                                            secondaryparentrectangle = new Rectangle(e.getInternalFrame().getBounds());
                                            System.out.println("f name - "+e.getInternalFrame().getName());
                                            definingparentsecondaryconnector = false;
                                            definingchildsecondaryconnector = true;
                                       } else {
                                       if (definingchildsecondaryconnector.equals(true)){
                                            // Build dummy rectangle for creating connector                         
                                            secondarychildrectangle = new Rectangle(e.getInternalFrame().getBounds());
                                            // draw connector
                                               drawline = true;
                                               repaint();
                                               definingchildsecondaryconnector = false;
                             public void internalFrameDeactivated(InternalFrameEvent e) {}
                        iframe.setToolTipText("Internal Frame :" + j);
                        iframe.setVisible(true);
                        desk.add(iframe);
              scrollpane.setViewportView(desk);
              JMenuBar menubar = new JMenuBar();
              JButton SecondaryConnector = new JButton("Secondary Connector");
              SecondaryConnector.addMouseListener(new java.awt.event.MouseAdapter() {
                   public void mousePressed(java.awt.event.MouseEvent e) {
                        definingsecondaryconnector = true;
                        definingparentsecondaryconnector = true;
                        definingchildsecondaryconnector = false;                    
                        try {
                             desk.getSelectedFrame().setSelected(false);
                        } catch (PropertyVetoException e1) {
                             // TODO Auto-generated catch block
                             e1.printStackTrace();
              JPanel overlayPanel = new JPanel();
                 OverlayLayout overlay = new OverlayLayout(overlayPanel);
                 overlayPanel.setLayout(overlay);
                 this.setOpaque(false);
                 overlayPanel.add(this);
                 overlayPanel.add(scrollpane);
              menubar.add(SecondaryConnector);
              frame.setJMenuBar(menubar);
    //          frame.add(scrollpane);
              frame.add(overlayPanel);
              scrollpane.setVisible(true);
              frame.setSize(800,600);
              frame.setVisible(true);
        private Point2D.Double getIntersectionPoint(Rectangle r, double theta) {
            double cx = r.getCenterX();
            double cy = r.getCenterY();
            double w = r.getWidth()/2;
            double h = r.getHeight()/2;
            double radius = Point2D.distance(0,0,w,h);
            double x = cx + radius * Math.cos(theta);
            double y = cy + radius * Math.sin(theta);
            Point2D.Double p = new Point2D.Double();
            int outcode = r.outcode(x, y);
            switch(outcode) {
                case Rectangle2D.OUT_TOP:             // 2
                    p.x = cx - h*((x - cx)/(y - cy));
                    p.y = cy - h;
                    break;
                case Rectangle2D.OUT_LEFT:            // 1
                    p.x = cx - w;
                    p.y = cy - w*((y - cy)/(x - cx));
                    break;
                case Rectangle2D.OUT_BOTTOM:          // 8
                    p.x = cx + h*((x - cx)/(y - cy));
                    p.y = cy + h;
                    break;
                case Rectangle2D.OUT_RIGHT:           // 4
                    p.x = cx + w;
                    p.y = cy + w*((y - cy)/(x - cx));
                    break;
                default:
                    System.out.println("Non-cardinal outcode: " + outcode);
            return p;
        private void drawArrowHeads(Line2D.Double line, Graphics2D g2) {
            double dy = line.getY2() - line.getY1();
            double dx = line.getX2() - line.getX1();
            double theta = Math.atan2(dy, dx);
            drawArrowHead(line.getP2(), theta, g2);
            drawArrowHead(line.getP1(), theta+Math.PI, g2);
        private void drawArrowHead(Point2D tip, double theta, Graphics2D g2) {
            double x = tip.getX() - barb * Math.cos(theta+phi);
            double y = tip.getY() - barb * Math.sin(theta+phi);
            g2.draw(new Line2D.Double(tip.getX(), tip.getY(), x, y));
            x = tip.getX() - barb * Math.cos(theta-phi);
            y = tip.getY() - barb * Math.sin(theta-phi);
            g2.draw(new Line2D.Double(tip.getX(), tip.getY(), x, y));
         public static void main(String[] args) {
              A_Test_of_Frame_Connectors d = new A_Test_of_Frame_Connectors();
    }

  • Adding a progress loader to a dynamic text field / scrollPane

    I have a dynamic text field which is loading images from an external html.  This text is named scrollPaneImage and is a child of a movieClip called scrollPaneContent.  I then load scrollPaneContent into a scroll pane named scrollPane
    When the user interacts with my swf different images are loaded into scrollPaneImage.  Since some of the images take a few seconds to load, I'd like there to be a progress loader displayed in the scrollpane.
    I have tried adding the progress event listner to the dynamic text, the movie clip and the scrollpane and cannot get it to respond or track the loading.
    scrollPaneContent.addEventListener(ProgressEvent.PROGRESS,reportProgress);
    function reportProgress(e:ProgressEvent):void {
        trace(e.bytesLoaded + " loaded out of " + e.bytesTotal);
         trace("LOADED");
    Can anyone suggest what I might be doing wrong or of another approach?
    thanks in advance,
    Josh

    Hi KGLAD.  Thanks for the response.  Yes my code is a little messy.  Here I have included everything and tried to do a little cleaning.  Is there enough code here for you to get an idea of how/when things are firing?
    import com.google.maps.LatLng;
    import com.google.maps.Map;
    import com.google.maps.MapEvent;
    import com.google.maps.MapType;
    import com.distriqt.gmaps.kml.utils.*;
    import com.greensock.*;
    import com.greensock.easing.*;
    import com.greensock.TweenLite;
    import flash.geom.Point;
    import com.greensock.plugins.*;
    TweenPlugin.activate([AutoAlphaPlugin]);
    import com.google.maps.controls.NavigationControl;
    import com.google.maps.controls.MapTypeControl;
    import com.google.maps.controls.OverviewMapControl;
    import com.google.maps.overlays.GroundOverlay;
    import com.google.maps.overlays.GroundOverlayOptions;
    import com.google.maps.LatLng;
    import com.google.maps.LatLngBounds;
    import com.google.maps.MapMouseEvent;
    import com.google.maps.controls.*;
    import com.google.maps.overlays.Marker;
    import com.google.maps.InfoWindowOptions;
    import com.google.maps.overlays.MarkerOptions;
    import com.anttikupila.utils.JPGSizeExtractor;
    import flash.display.StageAlign;
    import flash.display.StageScaleMode;
    import flash.events.Event;
    import flash.net.URLLoader;
    import fl.controls.UIScrollBar;
    import flash.events.Event;
    import fl.events.ScrollEvent;
    import flash.sampler.NewObjectSample;
    [Embed(source="ICONS/PHOTO_BLACK.png")]var photoIcon:Class;
    [Embed(source="ICONS/BLOG_BLACK.png")]var blogIcon:Class;
    scrollPane
    // GMAP PARAMETERS
    var map:Map = new Map();
    map.key = "map key";
    //map.key = "api key";
    //define the size of the map extent....
    map.sensor = "false";
    map.setSize(new Point(stage.stageWidth, stage.stageHeight));
    map.addEventListener(MapEvent.MAP_READY, onMapReady);
    map.addEventListener(MapEvent.MAP_READY, createmarkers);
    map.addEventListener(MapEvent.MAP_READY, createMarkerArrays);
    map.addEventListener(MapEvent.MAP_READY, createPhotoPingers);
    this.addChild(map);
    map.setSize(new Point(stage.stageWidth, stage.stageHeight));
    //on map ready params
    function onMapReady(event:Event):void
    map.setCenter(new LatLng(48,-113.5), 8, MapType.PHYSICAL_MAP_TYPE);
    map.enableScrollWheelZoom();
    map.disableContinuousZoom();
    //Marker options for a photo piece
    var photoMarkerOptions:MarkerOptions = new MarkerOptions();
    photoMarkerOptions.icon = new photoIcon();
    photoMarkerOptions.hasShadow=false;
    //Marker options for a blog piece
    var blogMarkerOptions:MarkerOptions = new MarkerOptions();
    blogMarkerOptions.icon = new photoIcon();
    blogMarkerOptions.hasShadow=false;
    //load xml tester
    var pntloader:URLLoader = new URLLoader();
    var pntxml:XML = new XML();
    pntloader.addEventListener(Event.COMPLETE, loadpntXML);
    pntloader.load(new URLRequest("map_feed.xml"));
    // create an array of jpgs to index
    var JPGIndexArray:Array = new Array();
    //Create array that will be populated with points
    var pointsArray:Array = new Array();
    //Load the XML
    function loadpntXML(e:Event):void {
        pntxml=new XML(e.target.data);
        pntxml.ignoreWhite = true;
         for (var i:int = 0; i< pntxml.row.length(); i++){
         pointsArray[i]="mrk"+i;
         JPGIndexArray[i]="JPG"+i;
         //trace(pntxml);
    //Create the markers and add them to the map
    function createmarkers(event:Event):void
         for (var i:Number = 0; i < pntxml.row.length(); i++) {
         var markerOptions:MarkerOptions = new MarkerOptions();
          if (pntxml.row[i].TYPE=="PHOTO")
               markerOptions.icon = new photoIcon();
               markerOptions.tooltip = "Photo";
               markerOptions.hasShadow=false;
          else if(pntxml.row[i].TYPE=="BLOG")
               markerOptions.icon = new blogIcon();
               markerOptions.tooltip = "Blog Entry";
               markerOptions.hasShadow=false;
          else
               null     
          pointsArray[i] = new Marker(new LatLng(pntxml.row[i].LAT,pntxml.row[i].LONG),markerOptions);
         markerA.push(pointsArray[i]);
          map.addOverlay(pointsArray[i]);
          pointsArray[i].addEventListener(MapMouseEvent.CLICK,indexCalledMarkerRecord);
          pointsArray[i].addEventListener(MapMouseEvent.CLICK,scrollPanePopulate);
    // PING PHOTO DIMENSIONS BEFORE LOADING //
    var je : JPGSizeExtractor = new JPGSizeExtractor( );
    je.addEventListener( JPGSizeExtractor.PARSE_COMPLETE, jeLoadHandler );
    je.addEventListener( JPGSizeExtractor.PARSE_FAILED, jeParseFailed );
    function createPhotoPingers(event:Event):void{
         for (var k:Number=0; k <pntxml.row.length(); k++){
         JPGIndexArray[k]=new JPGSizeExtractor();
         JPGIndexArray[k].debug = false;
         JPGIndexArray[k].addEventListener(JPGSizeExtractor.PARSE_COMPLETE, jeLoadHandler );
         trace("madeit");
         pingPhotoUrls();
    function pingPhotoUrls():void
         for (var i:Number = 0; i < pntxml.row.length(); i++) {     
          var calledMarkerUrl=pntxml.row[i].URL_OF_CONTENT;
          JPGIndexArray[i].extractSize(calledMarkerUrl);     
    var JPG1=null;
    function jeLoadHandler(e:Event) : void {
         trace(e.currentTarget.width + "x" + e.currentTarget.height );
         imageWidths.push(e.currentTarget.width);
    function jeParseFailed( event : Event ) : void {
         trace( "Parse failed" );
    var imageWidths = new Array;
    // FUNCTIONS FOR INDEXING CALLED MARKERS//
    //Create blank array for use in indexing
    var markerA:Array=[];
    //VAR FOR USE IN INDEXING CALLED MARKER
    var pointindex=null;
    //INDEX CALLED MARKER POINT XML RECORD
    function indexCalledMarkerRecord(e:MapMouseEvent):void{
         pointindex=genIndexPos(markerA,Marker(e.currentTarget));
         //trace(pntxml.row[pointindex].DESC);
    //FUNCTION FOR INDEXING CALLED MARKER
    function genIndexPos(a:Array,e:Marker):uint{
         for(var i:uint=0;i<a.length;i++){
              if(a[i]==e){
                   return i;               
                   return null;
    //           SCROLLPANE FUNCTIONS              //
    this.addChild(scrollPane);
    scrollPane.setSize(255,300);
    scrollPane.x=-200;
    scrollPane.y=-200;
    scrollPane.alpha=0;
    scrollPaneContent.mouseEnabled=false;
    spHeader.closeBox.addEventListener(MouseEvent.CLICK, function(eMouseEvent):void
                                                                TweenLite.to(scrollPane, .5,{autoAlpha:0,overwrite:true});                                                            
    spHeader.forDrag.addEventListener(MouseEvent.MOUSE_DOWN, function (e:MouseEvent):void
              scrollPane.startDrag();          
    spHeader.forDrag.addEventListener(MouseEvent.MOUSE_UP, function (e:MouseEvent):void
              scrollPane.stopDrag();
    spHeader.forDrag.buttonMode=true;
    spHeader.forDrag.useHandCursor=true;
    spHeader.width=300;
    scrollPane.source = scrollPaneContent;
    scrollPaneContent.scrollPaneText.autoSize='left';
    scrollPaneContent.scrollPaneImage.autoSize='center';
    scrollPaneContent.scrollPaneImage.autoSize=TextFieldAutoSize.CENTER;
    scrollPaneContent.mouseEnabled=false;
    scrollPaneContent.scrollPaneText.condenseWhite = true;
    // Add listener.
    scrollPane.addEventListener(Event.COMPLETE, completeListener);
    scrollPaneContent.addEventListener(ProgressEvent.PROGRESS,reportProgress);
    function completeListener(event:Event):void {
    trace('Scrollpane content loaded');
    function reportProgress(e:ProgressEvent):void {
        trace(e.bytesLoaded + " loaded out of " + e.bytesTotal);
        trace("LOADED");
    function scrollPanePopulate(event:Event){     
         //show scroll pane
         scrollPane.x=33;
         scrollPane.y=33;
         TweenLite.to(scrollPane, .5,{autoAlpha:1,overwrite:true});
         TweenLite.to(spHeader, .5,{autoAlpha:1,overwrite:true});
         //create the temp variables
         var calledMarkerIndex=pntxml.row[pointindex].ID;
         var calledMarkerDate=pntxml.row[pointindex].DATE;
         var calledMarkerDescription=pntxml.row[pointindex].DESC;
         var calledMarkerContent=pntxml.row[pointindex].URL_OF_CONTENT;     
         var imgWidth=JPGIndexArray[pointindex].width;
         var imgHeight=JPGIndexArray[pointindex].height;
         scrollPaneContent.scrollPaneText.htmlText="<font size='12' color='#000000'>"+calledMarkerDescription;
         var imgBoxHeight=scrollPaneContent.scrollPaneImage.height;
        var txtHeight=scrollPaneContent.scrollPaneText.height;
        var contentHeight=(imgBoxHeight+txtHeight);
        scrollPane.setSize(300,(contentHeight+15));     
         //size the text box
         scrollPaneContent.scrollPaneText.width=270;
         //if image is wide or tall, scale accordingly and create a string that will be used
         if(imgWidth>=imgHeight){          
              var imgSource:String = "<img src="+"'"+calledMarkerContent+"'"+"width='"+250+"'"+"height='"+150+"'"+"/>";                    
              var calledImgHgh=160;          
         else
              var imgSource:String = "<img src="+"'"+calledMarkerContent+"'"+"width='"+110+"'"+"height='"+167+"'"+"/>";          
              var calledImgHgh=177;          
         //fill in the text
         scrollPaneContent.scrollPaneImage.htmlText=imgSource;
         //scrollPaneContent.scrollPaneText.htmlText="<font size='12' color='#000000'>"+calledMarkerDescription;     
         //pan the map to the called position
         map.panTo(pointsArray[calledMarkerIndex-1].getLatLng())
         //add the header to the SP and scale accordingly
         scrollPane.addChild(spHeader);
         spHeader.x=-1;
         spHeader.y=1;
         spHeader.width=299;
         if (txtHeight>=250){          
              scrollPane.setSize(300,275);          
              scrollPaneContent.scrollPaneText.htmlText="<font size='12' color='#000000'>"+calledMarkerDescription+"<br><br>";
         if (txtHeight<=5){
              scrollPane.setSize(300,200);
              scrollPaneContent.scrollPaneText.htmlText="<font size='12' color='#000000'>"+calledMarkerDescription;
         if (txtHeight>=5){
              scrollPane.setSize(300,275);
              scrollPaneContent.scrollPaneText.htmlText="<font size='12' color='#000000'>"+calledMarkerDescription+"<br><br>";
         // CREATE TEMP VARIABLES FOR POSITIONING AND PLACE DYNAMIC TEXT
         var scTextY=scrollPaneContent.scrollPaneText.y;
         var scImageY=scrollPaneContent.scrollPaneImage.y;
         var scTextHeight=scrollPaneContent.scrollPaneText.height;
         scrollPaneContent.scrollPaneText.y=scImageY+calledImgHgh;
         //update the scrollpane and reset the scrollbar
         scrollPane.update();
         scrollPane.verticalScrollPosition=(0);
         scrollPane.verticalScrollBar.height=270;
         scrollPane.verticalScrollBar.x=281;
         scrollPane.verticalScrollBar.y=3;
    spHeader.alpha=0;
    this.addChild(spHeader);
    var photoMarkersArray=new Array();
    var photoMarkersIndexArray=new Array();
    //CREATE ARRAY OF PHOTO MARKERS
    function createMarkerArrays(e:Event):void{
    for (var j:int=0; j<pntxml.row.(TYPE=="PHOTO").ID.length(); j++){
              var tempMarkerIndex=pntxml.row.(TYPE=="PHOTO").ID[j];
              var tempMarkerRef="mrk"+tempMarkerIndex;
              photoMarkersArray.push(tempMarkerRef);
              photoMarkersIndexArray.push(tempMarkerIndex);

  • Scrollpane Not Working

    I am trying to have a JFrame with multiple panels, one of which will allow scrolling. I assign a scrollpane to a JPanel, which will contain multiple (dynamically changing) Labels. When the number of Labels exceeds the size that the JPanel is allocated (which is the reason the scrollpane is needed in the firstplace), the scrollable feature kicks in (which is good), but the entire list of labels appears, exceeding the region allocated to the JPanel and appearing over the panels below this one. How do I correct this? Thanks!
    import javax.swing.*;
    import java.awt.*;
    class TestScrollPane
         public static void main(String[] args)
              JFrame jf = new JFrame("Test Frame");
              jf.setLayout(new GridLayout(2,2));
              jf.setSize(400,500);
    jf.add(new Label("Top Left Panel"));
    JPanel jp1 = new JPanel(new BorderLayout());
              jp1.add("North", new Label("On top"));
              JPanel jp = new JPanel(new GridLayout(20,1));
              for(int i=0; i<20; i++)
                   Label l = new Label(i+ "th Label");
                   l.setBackground(Color.WHITE);
                   jp.add(l);
              JScrollPane scrollPane = new JScrollPane(jp);
              scrollPane.setPreferredSize(new Dimension(50, 50));
              jp1.add("Center", scrollPane);
              jf.add(jp1);
              jf.add(new Label("Bottom Left Panel"));
              jf.add(new Label("Bottom Right Panel"));
              jf.setVisible(true);
    }

    Your problem is one of the unexpected results that come from mixing AWT and Swing visual components. My answer: don't do this -- change all of your "Labels" to "JLabels".

  • Add Image to an Applet

    How do I add an image to an applet (along with other components:button, choice etc)? Sample code would be appreciated. I do not see any component to add image.
    Thanks.

    If you are using one of the getImage methods, they don't wait around for the image to load; they return immediately. So we use a MediaTracker to block program execution until the image is completely loaded. This is older java technology and will work in older versions of java. If you are using j2se 1.4+ then you can use the ImageIO class for loading an image.
    /*  <applet code="AppletImage" width="400" height="400"></applet>
    *  use: >appletviewer AppletImage.java
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    public class AppletImage extends Applet
        public void init()
            Button button = new Button("Button");
            Choice choice = new Choice();
            choice.add("item 1");
            choice.add("item 2");
            Panel north = new Panel();
            north.add(button);
            north.add(choice);
            TextField tf = new TextField("text field", 12);
            Panel fieldPanel = new Panel();
            fieldPanel.add(tf);
            ScrollPane scrollPane = new ScrollPane();
            scrollPane.add(new AppletImagePanel());
            Panel panel = new Panel(new BorderLayout());
            panel.add(scrollPane);
            panel.add(fieldPanel, "South");
            setLayout(new BorderLayout());
            add(north, "North");
            add(panel);
        public static void main(String[] args)
            Applet applet = new AppletImage();
            Frame f = new Frame();
            f.addWindowListener(new WindowAdapter()
                public void windowClosing(WindowEvent e)
                    System.exit(0);
            f.add(applet);
            f.setSize(400,400);
            f.setLocation(200,200);
            applet.init();
            applet.start();
            f.setVisible(true);
    class AppletImagePanel extends Panel
        Image image;
        public AppletImagePanel()
            loadImage();
        public void paint(Graphics g)
            super.paint(g);
            int w = getWidth();
            int h = getHeight();
            int imageWidth = image.getWidth(this);
            int imageHeight = image.getHeight(this);
            int x = (w - imageWidth)/2;
            int y = (h - imageHeight)/2;
            g.drawImage(image, x, y, this);
        public Dimension getPreferredSize()
            return new Dimension(image.getWidth(this), image.getHeight(this));
        private void loadImage()
            String fileName = "images/owls.jpg";
            MediaTracker tracker = new MediaTracker(this);
            URL url = getClass().getResource(fileName);
            image = Toolkit.getDefaultToolkit().getImage(url);
            tracker.addImage(image, 0);
            try
                tracker.waitForID(0);
            catch(InterruptedException ie)
                System.err.println("interrupt: " + ie.getMessage());
    }

  • I don't see the scrollpane...here's my code

    I am trying to add a scrollpane to scoll in my JTextArea, here is my code:
    JTextArea statText = new JTextArea(
              "The starting probability threshhold is: " + STARTING_PROB + "\n", 5, 20);
    JScrollPane textScroller = new JScrollPane(statText,
                    JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                 JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    textScroller.setPreferredSize(new Dimension(220, 80));
    statText.setLineWrap(true);
    statText.setBackground(TEXT_AREA_BG_COLOR);
    statText.setEditable(false);
    mazeGUI.getContentPane().add(statText, BorderLayout.EAST);
    runStatistics(statText);
    mazeGUI.pack();the (220, 80) I used for the preferredsize was from the
    getPreferredScrollableViewportSize()
    method called on the statText (JTextArea). I don't see any scroller when I run this program...am I misunderstanding how this is suppose to be done?

    You are adding statText to the contentPane when you should be adding textScroller, your scroll pane container.

  • ScrollPane Help

    initially i didn't split the panel and data..
    the scrollPane was showing good (table - JTable)...
                table = mainPanel.atmBean.getReturnTable();
                //Set Mode, Border, Size
                table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                table.setBorder(BorderFactory.createEtchedBorder());
                table.setPreferredScrollableViewportSize(mainPanel.getPopupTablePreferredSize());
                //Add table to Scroll Pane
                scrollPane = new JScrollPane(table);
                scrollPane.setPreferredSize(mainPanel.getPopupTablePreferredSize());after splitting the data, i changed like
    add()
    scrollPane = new JScrollPane();
    set()
                table = mainPanel.atmBean.getReturnTable();
                //Set Mode, Border, Size
                table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                table.setBorder(BorderFactory.createEtchedBorder());
                table.setPreferredScrollableViewportSize(mainPanel.getPopupTablePreferredSize());
                //Add table to Scroll Pane
               //THIS IS THE DIFFERENCE
                scrollPane.add(table);
                scrollPane.validate();
                scrollPane.repaint();
               //c is contentPane()
               c.validate();
               c.repaint();
    }the scrollpane doesn't seem to contain the table..

    if i add 1 more panel, the problem gets solved, but wondering why shouldn't the scrollPane work ..
    ie
    add()
      JPanel panel = new JPanel();
    set()
      ..all other steps as shown above
      scrollPane = new JScrollPane(table)
      //one more panel
      panel.removeAll();
      panel.add(scrollPane);
      panel.validate();
      panel.repaint();
    }

  • ScrollPane inside MC loaded with attachMovie

    I'm stuck.
    I need to use a ScrollPane in my site to show several photos.
    My site is set up to load MC's to the MainStage using attachMovie.
    One of my MC's is named Photos.  If I add a ScrollPane to Photos with content called Pics (another MC containing all the photos.) it won't scroll.  What is the proper method of adding a ScrollPane to a MC called with attachMovie?
    Thanks!
    Rick

    Yes, I have the Linkage ID also set to pics as well as Export to Actionscript and Export to Frame 2.
    Could it have something to do with my menu setup?
    My main timeline has one 'container' (EmptyMC) and several buttons.  Each button points to a frame on the main timeline that has another MC (a transition animation).  This transition MC contains an attachMovie, loading a MC into the original container on the main stage.  (I hope this all makes sense...)
    Well, everything works great, until I throw the ScrollPane into the mix.  Even if the ScrollPane is just sitting in the Library, not even on a stage or MC, the whole menu system fails, and won't load any MC's from that point on.
    I'm pulling my hair out on this one...
    Thanks for your help so far, I really appricaite it.

  • Advise on scrollpane?

    Hello,
    Below are the main parts of my SetConstructor class, the idea was to display an image in the centre of a panel.
    I wondered if anyone could advise how to add a scrollpane, when the image is too large for the screen the scroll bars would appear. Is this possible?
    Thank you
    static JPanel contentPane;
    SetConstructor(){
       JLabel imageLb = new JLabel(new ImageIcon("testImage.jpg"));
       contentPane = new JPanel(new BorderLayout());
       contentPane.add(imageLb, BorderLayout.CENTER);
    public static void main(String args[]){
      JFrame newFrame = new JFrame("Test display");
      SetConstructor constructor = new SetConstructor();
      newFrame.setContentPane(contentPane);
      newFrame.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e)
                                                        {System.exit(0);}});
      newFrame.pack();
      newFrame.setLocationRelativeTo(null);
      newFrame.setVisible(true);
    }

    Meaning this?
    Thanks
    public class SetConStructor{
    static JPanel contentPane;
    SetConstructor(){
    JLabel imageLb = new JLabel(new ImageIcon("testImage.jpg"));
    contentPane = new JPanel(new BorderLayout());
    contentPane.add(imageLb, BorderLayout.CENTER);
    public static void main(String args[]){
    JFrame newFrame = new JFrame("Test display");
    SetConstructor constructor = new SetConstructor();
    JScrollPane scrollPane = new JScrollPane(new contentPanel);
    newFrame.setContentPane(scrollPane);
    newFrame.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e)
                                                        {System.exit(0);}});
    newFrame.pack();
    newFrame.setLocationRelativeTo(null);
    newFrame.setVisible(true);
    }

  • I cant use ScrollPane in JList

    JList list=new JList(kaynak);
    list.setBounds(0,0,40,40);
    JScrollPane sc=new JScrollPane(list);
    add(list);
    add(sc);
    setVisible(true);
    why I do not have scrollBars arround my jlist? what is the problem?

    JList list=new JList(kaynak);
    list.setBounds(0,0,40,40);
    ScrollPane sc=new JScrollPane(list);
    add(list);
    add(sc);
    setVisible(true);
    why I do not have scrollBars arround my jlist? what
    is the problem?You've added the list to the scroll pane, but then you add the list to the frame. And then you add the scrollpane to the frame.
    This approach contains two flaws:
    A. You can't add a component to two different parents. When you try to do so, the component is removed from the original parent and added to the new parent. So, when your code says
    add(list);the list is removed from the scrollpane and added to the frame.
    B. You can't add two different components to the same container without indicating where to put them. Assuming your container has a default BorderLayout, your code adds the list at the CENTER position, and then adds the scrollpane at the CENTER position. As a result, your list is removed from the container and the scrollpane is added. but since the first flaw in your code removed the list from the scrollpane, nothing appears. The scrollpane is there, but it has nothing in it so the frame appears empty.
    Remove the line:
    add(list);and things should work.
    Jim S.

  • Scrollpane for internal frame

    I want to add a scrollpane to a blank JInternalFrame.How should i do it.The Internal frame has a null layout.Thanx

    Hi , sorry you have to add the JScrollpane direct to the ContentPane. Let the Layout
    of the ContentPane unchanged. (BorderLayout).
    Using Flowlayout won't get you any benifit from extra space.
    You can use setResizeable(true) and resize the Frame to check if the Scrollbars appear's.
    They will only apper if nessary.
    During Runntime:
    do something like this: (f2 is an InternalFrame)
    f2.setVisible(false); // it's important, to enable an correct repainting-proze�
    f2.getContentPane().removeAll(); // If you wnt to remove some old components
    f2.getContentPane().add(new JScrollPane(yourPanel) ); //your Components
    f2.setVisible(true );Hope this helps.
    Greetings Michael

  • Retrieving datas with ArrayList

    Below, im trying to get 6 columned records from the access database.
    //PNL 1:
                                  PNL1=new JPanel();
                                  PNL1.setLayout(new BorderLayout(15,15));
                                                    java.awt.List veri;
                                                    ArrayList veri2;
                                  lblABaslik=new JLabel("Arama Sonuclari :");
                                  String[] sutunAdlari={"Tarih","Arac","Kategori","Aciklama","Detay","Miktar"};
                                  int sayac=-1;
                                  java.util.Date tarih;int arac;int kategori;int aciklama;String detay;int tutar;
                                       try {
                                            String url="jdbc:odbc:Driver={MicroSoft Access Driver (*.mdb)};DBQ=..\\bekir.mdb";
                                            String query="select * from harcamalar where tarih between # 2003-11-14 # and #2003-12-14 #";
                                            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                                            Connection con=DriverManager.getConnection(url,"serdar","serdar");
                                            Statement stmt=con.createStatement();
                                            ResultSet rs = stmt.executeQuery(query);
                                                                     veri=new java.awt.List(6);
                                                                     veri2=new ArrayList();
                                                                     String ekle;
                                                                     while(rs.next()) {
                                                                       ekle=new String(rs.getString("tarih"));
                                                                           veri.add(ekle);
                                                                       ekle=new String(rs.getString("arac_id"));
                                                                           veri.add(ekle);
                                                                       ekle=new String(rs.getString("kategori_id"));
                                                                           veri.add(ekle);
                                                                       ekle=new String(rs.getString("aciklama_id"));
                                                                           veri.add(ekle);
                                                                       ekle=new String(rs.getString("detay"));
                                                                           veri.add(ekle);
                                                                       ekle=new String(rs.getString("miktar"));
                                                                           veri.add(ekle);
                                                                     veri2.add(veri);
                                            rs.close();
                                            stmt.close();
                                            con.close();
                                       catch (ClassNotFoundException e2){
                                            e2.printStackTrace(System.err);
                                       catch (SQLException e2){
                                       System.err.println("SQL state: " + e2.getSQLState());
                                       System.err.println("SQL error: " + e2.getErrorCode());
                                       e2.printStackTrace(System.err);
                                                    table=new JTable(veri2,sutunAdlari);
                                  table.setPreferredScrollableViewportSize(new Dimension(600,100));
                                  JScrollPane scrollpane=new JScrollPane(table);
                                  PNL1.add("North",lblABaslik);
                                  PNL1.add("Center",scrollpane);
                                  table.addMouseListener(new MouseAdapter() {
                                       public void mouseClicked(MouseEvent e) {
                                            System.out.println(table.getSelectedRow());
    but i get the error :
    "BekirAna2.java": cannot resolve symbol: constructor JTable (java.util.ArrayList,java.lang.String[])in class javax.swing.JTable at line 1928, column 55
    which represents the line :
    table=new JTable(veri2,sutunAdlari);
    thanx

    i changed the codes with Vector definitions;
                             //PNL1 :
                                  PNL1=new JPanel();
                                  PNL1.setLayout(new BorderLayout(15,15));
                                                     Vector veri;
                                                     Vector veri2;
                                                     //ArrayList veri2;
                                  lblABaslik=new JLabel("Arama Sonuclari :");
                                  //Object[][] veri=new Object[10][7];
                                  //veri[0][0] = new String("foo"); //etc.
                                  String[] sutunAdlari={"Tarih","Arac","Kategori","Aciklama","Detay","Miktar"};
                                  int sayac=-1;
                                  java.util.Date tarih;int arac;int kategori;int aciklama;String detay;int tutar;
                                       try {
                                            String url="jdbc:odbc:Driver={MicroSoft Access Driver (*.mdb)};DBQ=..\\bekir.mdb";
                                            //String query="select * from harcamalar";
                                            String query="select * from harcamalar where tarih between # 2003-11-14 # and #2003-12-14 #";
                                            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                                            Connection con=DriverManager.getConnection(url,"serdar","serdar");
                                            Statement stmt=con.createStatement();
                                            ResultSet rs = stmt.executeQuery(query);
                                                                     veri=new Vector();
                                                                     //veri2=new ArrayList();
                                                                     veri2 = new Vector();
                                                                     String ekle;
                                                                     while(rs.next()) {
                                                                       ekle=new String(rs.getString("tarih"));
                                                                           veri.add(ekle);
                                                                       ekle=new String(rs.getString("arac_id"));
                                                                           veri.add(ekle);
                                                                       ekle=new String(rs.getString("kategori_id"));
                                                                           veri.add(ekle);
                                                                       ekle=new String(rs.getString("aciklama_id"));
                                                                           veri.add(ekle);
                                                                       ekle=new String(rs.getString("detay"));
                                                                           veri.add(ekle);
                                                                       ekle=new String(rs.getString("miktar"));
                                                                           veri.add(ekle);
                                                                     veri2.add(veri);
                                            rs.close();
                                            stmt.close();
                                            con.close();
                                       catch (ClassNotFoundException e2){
                                            e2.printStackTrace(System.err);
                                       catch (SQLException e2){
                                       System.err.println("SQL state: " + e2.getSQLState());
                                       System.err.println("SQL error: " + e2.getErrorCode());
                                       e2.printStackTrace(System.err);
                                  //table=new JTable(veri,sutunAdlari);
                                                    table=new JTable(veri2,sutunAdlari);
                                  table.setPreferredScrollableViewportSize(new Dimension(600,100));
                                  JScrollPane scrollpane=new JScrollPane(table);
                                  PNL1.add("North",lblABaslik);
                                  PNL1.add("Center",scrollpane);
                                  table.addMouseListener(new MouseAdapter() {
                                       public void mouseClicked(MouseEvent e) {
                                            System.out.println(table.getSelectedRow());
                                  });but i still get the error alike:
    "BekirAna2.java": cannot resolve symbol: constructor JTable (java.util.Vector,java.lang.String[])in class javax.swing.JTable at line 1931, column 55
    pointing the line;
    table=new JTable(veri2,sutunAdlari);

  • How to scroll a JPanel?

    I have class, which extends JPanel, in which I override
    the paintComponent(Graphics g) method
    I am drawing a graph and, depending on the input values, the graph can be wider than the JPanel. I would like to be able to add a scroll bar so the whole of the graph can be viewed.
    I have tried to make the JPanel implement scrollable
    and I have tried putting the JPanel within a JScrollpane
    but neithor work.
    please help!
    Simon

    You should be able to add the JPanel to the JScrollPane by doing the following (setting the scrollbars as required)
    // create a panel to hols the scrollpane
    JPanel aPanel = new JPanel();
    // create the scrollpane with your graph in it = yourPanel
    // disable the vertical scrollbar and enable the hoziontal
    JScrollPane aScrollPane = new JScrollPane(yourGraph, JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    // set the scrollpane to the same size as the panel
    aScrollPane.setSize(aPanel.getSize());
    // add the scrollpane to the panel
    aPanel.add(aScrollPane);
    // refresh the layout
    aScrollPane.doLayout();
    Hope this helps - I had the same problem a couple of days ago!

  • MDI JTable Overlap Area Repaint Problem

    Hi all,
    I have a problem for my application in MDI mode.
    I open many windows (JInternalFrame contain JTable) under JDesktopPane. Some of the windows are overlapping and when they receive update in the table, it seems repaint all of the overlapping windows, not only itself. This make my application performance become poor, slow respond for drap & drop an existing window or open a new window.
    To prove this, i make a simple example for open many simple table and have a thread to update the table's value for every 200 mill second. After i open about 20 windows, the performance become poor again.
    If anyone face the same problem with me and any suggestions to solve the problem ?
    Please help !!!!!
    Following are my sources:
    public class TestMDI extends JFrame {
        private static final long serialVersionUID = 1L;
        private JPanel contentPanel;
        private JDesktopPane desktopPane;
        private JMenuBar menuBar;
        private List<TestPanel> allScreens = new ArrayList<TestPanel>();
        private List<JDialog> freeFloatDialogs = new ArrayList<JDialog>();
        private List<JInternalFrame> mdiInternalFrm = new ArrayList<JInternalFrame>();
        int x = 0;
        int y = 0;
        int index = 0;
        private static int MDI_MODE = 0;
        private static int FREE_FLOAT_MODE = 1;
        private int windowMode = MDI_MODE;
        public TestMDI() {
            init();
        public static void main(String[] args) {
            new TestMDI().show();
        public void init() {
            contentPanel = new JPanel();
            desktopPane = new JDesktopPane();
            desktopPane.setDragMode(JDesktopPane.LIVE_DRAG_MODE);
            desktopPane.setFocusTraversalKeysEnabled(false);
            desktopPane.setFocusTraversalPolicyProvider(false);
            desktopPane.setBorder(null);
            desktopPane.setIgnoreRepaint(true);
            desktopPane.setPreferredSize(new Dimension(1000, 800));
            this.setSize(new Dimension(1000, 800));
            menuBar = new JMenuBar();
            JMenu menu1 = new JMenu("Test");
            JMenuItem menuItem1 = new JMenuItem("Open Lable Screen");
            menuItem1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    for (int i = 1; i < 4; i++) {
                        final TestJLableScreen screen = new TestJLableScreen("Screen  " + (allScreens.size() + 1));
                        screen.startTime();
                        if (windowMode == MDI_MODE) {
                            JInternalFrame frame = createInternalFram(screen);
                            desktopPane.add(frame);
                            mdiInternalFrm.add(frame);
                            if (allScreens.size() * 60 + 100 < 1000) {
                                x = allScreens.size() * 60;
                                y = 60;
                            } else {
                                x = 60 * index;
                                y = 120;
                                index++;
                            frame.setLocation(x, y);
                            frame.setVisible(true);
                        } else {
                            JDialog dialog = createJDialog(screen);
                            freeFloatDialogs.add(dialog);
                            if (i * 60 + 100 < 1000) {
                                x = i * 60;
                                y = 60;
                            } else {
                                x = 60 * index;
                                y = 120;
                                index++;
                            dialog.setLocation(x, y);
                            dialog.setVisible(true);
                        allScreens.add(screen);
            JMenuItem menuItem2 = new JMenuItem("Open Table Screen");
            menuItem2.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    for (int i = 1; i < 4; i++) {
                        TestTableScreen screen = new TestTableScreen("Screen  " + (allScreens.size() + 1));
                        screen.startTime();
                        if (windowMode == MDI_MODE) {
                            JInternalFrame frame = createInternalFram(screen);
                            desktopPane.add(frame);
                            mdiInternalFrm.add(frame);
                            if (allScreens.size() * 60 + 100 < 1000) {
                                x = allScreens.size() * 60;
                                y = 60;
                            } else {
                                x = 60 * index;
                                y = 120;
                                index++;
                            frame.setLocation(x, y);
                            frame.setVisible(true);
                        } else {
                            JDialog dialog = createJDialog(screen);
                            freeFloatDialogs.add(dialog);
                            if (i * 60 + 100 < 1000) {
                                x = i * 60;
                                y = 60;
                            } else {
                                x = 60 * index;
                                y = 120;
                                index++;
                            dialog.setLocation(x, y);
                            dialog.setVisible(true);
                        allScreens.add(screen);
            menu1.add(menuItem1);
            menu1.add(menuItem2);
            this.setJMenuBar(menuBar);
            this.getJMenuBar().add(menu1);
            this.getJMenuBar().add(createSwitchMenu());
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.add(desktopPane);
            desktopPane.setDesktopManager(null);
        public JInternalFrame createInternalFram(final TestPanel panel) {
            final CustomeInternalFrame internalFrame = new CustomeInternalFrame(panel.getTitle(), true, true, true, true) {
                public void doDefaultCloseAction() {
                    super.doDefaultCloseAction();
                    allScreens.remove(panel);
            internalFrame.setPanel(panel);
            // internalFrame.setOpaque(false);
            internalFrame.setSize(new Dimension(1010, 445));
            internalFrame.add(panel);
            internalFrame.setFocusTraversalKeysEnabled(false);
            internalFrame.setFocusTraversalPolicyProvider(false);
            desktopPane.getDesktopManager();
            // internalFrame.setFocusTraversalKeysEnabled(false);
            internalFrame.setIgnoreRepaint(true);
            return internalFrame;
        public JDialog createJDialog(final TestPanel panel) {
            JDialog dialog = new JDialog(this, panel.getTitle());
            dialog.setSize(new Dimension(1010, 445));
            dialog.add(panel);
            dialog.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    allScreens.remove(panel);
            return dialog;
        public JMenu createSwitchMenu() {
            JMenu menu = new JMenu("Test2");
            JMenuItem menuItem1 = new JMenuItem("Switch FreeFloat");
            menuItem1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    windowMode = FREE_FLOAT_MODE;
                    for (JInternalFrame frm : mdiInternalFrm) {
                        frm.setVisible(false);
                        frm.dispose();
                        frm = null;
                    mdiInternalFrm.clear();
                    remove(desktopPane);
                    desktopPane.removeAll();
    //                revalidate();
                    repaint();
                    add(contentPanel);
                    index = 0;
                    for (JDialog dialog : freeFloatDialogs) {
                        dialog.setVisible(false);
                        dialog.dispose();
                        dialog = null;
                    freeFloatDialogs.clear();
                    for (int i = 0; i < allScreens.size(); i++) {
                        JDialog dialog = createJDialog(allScreens.get(i));
                        freeFloatDialogs.add(dialog);
                        if (i * 60 + 100 < 1000) {
                            x = i * 60;
                            y = 60;
                        } else {
                            x = 60 * index;
                            y = 120;
                            index++;
                        dialog.setLocation(x, y);
                        dialog.setVisible(true);
            JMenuItem menuItem2 = new JMenuItem("Switch MDI");
            menuItem2.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    windowMode = MDI_MODE;
                    remove(contentPanel);
                    add(desktopPane);
                    for (int i = 0; i < freeFloatDialogs.size(); i++) {
                        freeFloatDialogs.get(i).setVisible(false);
                        freeFloatDialogs.get(i).dispose();
                    freeFloatDialogs.clear();
    //                revalidate();
                    repaint();
                    for (JInternalFrame frm : mdiInternalFrm) {
                        frm.setVisible(false);
                        frm.dispose();
                        frm = null;
                    mdiInternalFrm.clear();
                    index = 0;
                    for (int i = 0; i < allScreens.size(); i++) {
                        JInternalFrame frame = createInternalFram(allScreens.get(i));
                        desktopPane.add(frame);
                        mdiInternalFrm.add(frame);
                        if (i * 60 + 100 < 1000) {
                            x = i * 60;
                            y = 60;
                        } else {
                            x = 60 * index;
                            y = 120;
                            index++;
                        frame.setLocation(x, y);
                        frame.setVisible(true);
            menu.add(menuItem1);
            menu.add(menuItem2);
            return menu;
    public class TestTableScreen extends TestPanel {
        private static final long serialVersionUID = 1L;
        JTable testTable = new JTable();
        MyTableModel tableModel1 = new MyTableModel(1);
        private boolean notRepaint = false;
        int start = 0;
        JScrollPane scrollPane = new JScrollPane();
        private Timer timmer = new Timer(200, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Random indexRandom = new Random();
                final int index = indexRandom.nextInt(50);
                Random valRandom = new Random();
                final int val = valRandom.nextInt(600);
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        notRepaint = false;
                        TestTableScreen.this.update(index + "|" + val);
        public TestTableScreen(String title) {
            this.title = title;
            init();
            tableModel1.setTabelName(title);
        public void startTime() {
            timmer.start();
        public String getTitle() {
            return title;
        public void update(String updateStr) {
            String[] val = updateStr.split("\\|");
            if (val.length == 2) {
                int index = Integer.valueOf(val[0]);
                List vals = tableModel1.getVector();
                if (vals.size() > index) {
                    vals.set(index, val[1]);
    //                 tableModel1.fireTableRowsUpdated(index, index);
                } else {
                    vals.add(val[1]);
    //                 tableModel1.fireTableRowsUpdated(vals.size() - 1, vals.size() - 1);
                tableModel1.fireTableDataChanged();
        public TableModel getTableModel() {
            return tableModel1;
        public void init() {
            testTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            testTable.setRowSelectionAllowed(true);
            this.testTable.setModel(tableModel1);
            int[] width = { 160, 80, 45, 98, 60, 88, 87, 88, 80, 70, 88, 80, 75, 87, 87, 41, 88, 82, 75, 68, 69 };
            TableColumnModel columnModel = testTable.getColumnModel();
            for (int i = 0; i < width.length; i++) {
                columnModel.getColumn(i).setPreferredWidth(width[i]);
            testTable.setRowHeight(20);
            tableModel1.fireTableDataChanged();
            this.setLayout(new BorderLayout());
            TableColumnModel columnMode2 = testTable.getColumnModel();
            int[] width2 = { 200 };
            for (int i = 0; i < width2.length; i++) {
                columnMode2.getColumn(i).setPreferredWidth(width2[i]);
            scrollPane.getViewport().add(testTable);
            scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            this.add(scrollPane, BorderLayout.CENTER);
        class MyTableModel extends DefaultTableModel {
            public List list = new ArrayList();
            String titles[] = new String[] { "袨怓1", "袨怓2", "袨怓3", "袨怓4", "袨怓5", "袨怓6", "袨怓7", "袨怓8", "袨怓9", "袨怓10", "袨怓11",
                    "袨怓12", "袨怓13", "袨怓14", "袨怓15", "袨怓16", "袨怓17", "袨怓18", "袨怓19", "袨怓20", "袨怓21" };
            String tabelName = "";
            int type_head = 0;
            int type_data = 1;
            int type = 1;
            public MyTableModel(int type) {
                super();
                this.type = type;
                for (int i = 0; i < 50; i++) {
                    list.add(i);
            public void setTabelName(String name) {
                this.tabelName = name;
            public int getRowCount() {
                if (list != null) {
                    return list.size();
                return 0;
            public List getVector() {
                return list;
            public int getColumnCount() {
                if (type == 0) {
                    return 1;
                } else {
                    return titles.length;
            public String getColumnName(int c) {
                if (type == 0) {
                    return "head";
                } else {
                    return titles[c];
            public boolean isCellEditable(int nRow, int nCol) {
                return false;
            public Object getValueAt(int r, int c) {
                if (list.size() == 0) {
                    return null;
                switch (c) {
                default:
                    if (type == 0) {
                        return r + " " + c + "  test ";
                    } else {
                        return list.get(r) + "   " + c;
        public boolean isNotRepaint() {
            return notRepaint;
        public void setNotRepaint(boolean notRepaint) {
            this.notRepaint = notRepaint;
    public class TestPanel extends JPanel {
        protected String title = "";
        protected boolean needRepaint = false;
        protected boolean isFirstOpen = true;
        public String getTitle() {
            return title;
        public void setNeedRepaint(boolean flag) {
            this.needRepaint = flag;
        public boolean isNeedRepaint() {
            return needRepaint;
        public boolean isFirstOpen() {
            return isFirstOpen;
        public void setFirstOpen(boolean isFirstOpen) {
            this.isFirstOpen = isFirstOpen;
    public class TestJLableScreen extends TestPanel {
        private static final long serialVersionUID = 1L;
        private JLabel[] allLables = new JLabel[20];
        private Timer timmer = new Timer(20, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Random indexRandom = new Random();
                final int index = indexRandom.nextInt(10);
                Random valRandom = new Random();
                final int val = valRandom.nextInt(600);
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        TestJLableScreen.this.setNeedRepaint(true);
                        TestJLableScreen.this.update(index + "|" + val);
        public TestJLableScreen(String title) {
            this.title = title;
            init();
        public void startTime() {
            timmer.start();
        public String getTitle() {
            return title;
        public void update(String updateStr) {
            String[] val = updateStr.split("\\|");
            if (val.length == 2) {
                int index = Integer.valueOf(val[0]);
                allLables[index * 2 + 1].setText(val[1]);
        public void init() {
            this.setLayout(new GridLayout(10, 2));
            boolean flag = true;
            for (int i = 0; i < allLables.length; i++) {
                allLables[i] = new JLabel() {
                    // public void setText(String text) {
                    // super.setText(text);
                    // // System.out.println("  setText " + getTitle() + "   ; " + this.getName());
                    public void paint(Graphics g) {
                        super.paint(g);
                        // System.out.println("  paint " + getTitle() + "   ; " + this.getName());
                    // public void repaint() {
                    // super.repaint();
                    // System.out.println("  repaint " + getTitle() + "   ; " + this.getName());
                allLables[i].setName("" + i);
                if (i % 2 == 0) {
                    allLables[i].setText("Name " + i + "  : ");
                } else {
                    allLables[i].setOpaque(true);
                    if (flag) {
                        allLables[i].setBackground(Color.YELLOW);
                        flag = false;
                    } else {
                        allLables[i].setBackground(Color.CYAN);
                        flag = true;
                    allLables[i].setText(i * 8 + "");
            for (int i = 0; i < allLables.length; i++) {
                this.add(allLables[i]);
    public class CustomeInternalFrame extends JInternalFrame {
        protected TestPanel panel;
        public CustomeInternalFrame() {
            this("", false, false, false, false);
        public CustomeInternalFrame(String title) {
            this(title, false, false, false, false);
        public CustomeInternalFrame(String title, boolean resizable) {
            this(title, resizable, false, false, false);
        public CustomeInternalFrame(String title, boolean resizable, boolean closable) {
            this(title, resizable, closable, false, false);
        public CustomeInternalFrame(String title, boolean resizable, boolean closable, boolean maximizable) {
            this(title, resizable, closable, maximizable, false);
        public CustomeInternalFrame(String title, boolean resizable, boolean closable, boolean maximizable,
                boolean iconifiable) {
            super(title, resizable, closable, maximizable, iconifiable);
        public TestPanel getPanel() {
            return panel;
        public void setPanel(TestPanel panel) {
            this.panel = panel;

    i had the same problem with buttons and it seemed that i overlayed my button with something else...
    so check that out first do you put something on that excact place???
    other problem i had was the VAJ one --> VisualAge for Java (terrible program)
    it does strange tricks even when you don't use the drawing tool...
    dunno 2 thoughts i had... check it out...
    SeJo

Maybe you are looking for