Swing jscrollpane border opacity

Hi guys,
quick question, how do you set the border of a jscrollpane to be opaque(invisable)?
In this program we have:
a textarea in a scrollpane, both are set to be opaque, as well as the veiwport for the scrollpane. The problem is we have about a 2 pixel thick border around it that we want to get rid of, so our question is how? Thanks!

scrollPane.setBorder(null);  (?)

Similar Messages

  • Swing/JScrollPane

    My problem is that I have this class that extends JApplet and has 3 JPanel and an instance from another class that extends JPanel (I will call it class2) inside it.
    My problem is that I'm inserting class2 inside a JScrollPane than I insert JScrollPane inside my JApplet, but whenever I move my JScrollPane which should just move the content from class2 (lines, numbers, ...), but I'm getting a messed screen like if the computer was mixing the old content (before using JScrollPane) with the new content (after moving)...something like the JScrollPane listener isnt refreshing the screen when I use it.
    If anyone know a fix for this, please contact me and if you want to check the code, email me ([email protected]).

    I'm posting all the code below...could anyone please help me out with this, there is a very weird behaviour when I move the JScrollPane
    * C�digo de Huffman - Applet
    * Arildo Fran�a Oliva Filho - 99/32810
    * Leonardo Lobo Pulcineli - 99/20064
    * Marcos Garrison Dytz - 99/20102
    * Octavio do Vale Rocha - 99/20129
    package huffman;
    // Bibliotecas que fazem parte da implementa��o do applet
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.util.*;
    import javax.swing.*;
    import java.io.*;
    import java.text.DecimalFormat;
    * Objetos que far�o parte da GUI do programa, onde se tem a ocorrencia de
    * tres botoes para o controle do fluxo do programa, uma caixa para a entrada
    * das probabilidades, um classe instanciada para controlar as mensagens ao
    * usu�rio e outra que far� a apresenta��o de todo conte�do
    * Declara��o de todas as vari�veis utilizadas para armazenar as probabilidades
    * onde o maior n�mero de vari�ives que podem ser implementadas � 200
    public class Huff extends JApplet implements ActionListener, ComponentListener {
    JButton reset_button, step_button, end_button;
    // JButton file_button, fix_button;
    JTextField input_string;
    cent Cent = new cent();
    ErrorCanvas stdout = new ErrorCanvas();
    DecimalFormat f = new DecimalFormat("0.000"); // Define um formato para os valores
    DecimalFormat f2 = new DecimalFormat("0.00");
    JScrollPane scroll = new JScrollPane(Cent);
    boolean inAnApplet = true; // Testa a validade do applet
    protected int numProbabilidade; // Numero total de probabilidades
    protected int numProbabilidadeTemp; // Numero total de probabilidades
    protected int[] marcador; // Marca a pr�xima probabilidade
    protected double[][] probabilidade;
    protected String[][] simbolo; // Guarda os c�digos bin�rios
    protected int passo; // Controle quanto ao fim das probs.
    protected boolean proximo = true; // Idem acima
    protected double entropia = 0.0; // Entropia;
    // protected boolean estArquivo = true; // Estado de um arquivo
    protected boolean inic = true;
    * Construtor para a classe Huff (inicializa todo o GUI)
    public Huff() {
    getContentPane().setLayout(new BorderLayout());
    scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    getContentPane().add("Center", scroll);
    Font def = new Font("Dialog", 0, 12);
    Cent.setFont(def);
    JPanel p = new JPanel(new GridLayout(2, 0));
    JPanel q = new JPanel(new GridLayout(2, 0));
    JPanel r = new JPanel(new FlowLayout());
    r.add(reset_button = new JButton("Reiniciar"));
    r.add(step_button = new JButton("Proximo"));
    r.add(end_button = new JButton("Concluir"));
    // r.add(file_button = new JButton("Arquivo");
    // r.add(file_button = new JButton("Corrigir arquivo");
    p.add(r);
    p.add(input_string = new JTextField());
    * O visualizador gr�fico (JPanel q) que � utilizado por ErrorCanvas para
    * emitir algumas mensagens para o usu�rio
    q.add(p);
    q.add(stdout);
    getContentPane().add("South", q);
    reset_button.addActionListener(this);
    step_button.addActionListener(this);
    end_button.addActionListener(this);
    input_string.addActionListener(this);
    scroll.addComponentListener(this);
    * M�todo utilizado para inicializar o �ndice dos arrays utilizados e zerar
    * o valor de todas as probabilidades utilizadas
    public void init() {
    marcador = new int[200];
    probabilidade = new double[200][400];
    simbolo = new String[200][250];
    for(int i = 0; i < 200; i++)
    for(int j = 0; j < 400; j++) {
    probabilidade[i][j]=0.0;
    JOptionPane.showMessageDialog(null, " ", "Bem vindo",
    JOptionPane.INFORMATION_MESSAGE);
    if(inic)
    iniciarProbabilidade(probabilidade[0]);
    this.reset();
    * Conta o n�mero de probabilidades que foram inseridos no TextField, assim
    * como testa a validade destes valores. � bem similar ao funcionamento de
    * parseProbabilidade
    void contarProbabilidade() {
    StringTokenizer st = new StringTokenizer(input_string.getText());
    double teste = 0.0;
    if(input_string.getText().length() > 0 && input_string.getText() != null) {
    while (st.hasMoreTokens()) {
    try {
    teste = Double.valueOf(st.nextToken()).doubleValue();
    if(teste < 0) {
    JOptionPane.showMessageDialog(null,"Probabilidade negativa.", "Erro",
    JOptionPane.ERROR_MESSAGE);
    input_string.setText("");
    numProbabilidade = 0;
    break;
    if(teste > 1.0) {
    JOptionPane.showMessageDialog(null,"Probabilidade maior que 1.", "Erro",
    JOptionPane.ERROR_MESSAGE);
    input_string.setText("");
    numProbabilidade = 0;
    break;
    if(teste == 0.0) {
    JOptionPane.showMessageDialog(null,"Probabilidade igual a 0.", "Erro",
    JOptionPane.ERROR_MESSAGE);
    input_string.setText("");
    numProbabilidade = 0;
    break;
    } catch (NumberFormatException e) {
    JOptionPane.showMessageDialog(null,"Numero incorreto.", "Erro",
    JOptionPane.ERROR_MESSAGE);
    input_string.setText("");
    numProbabilidade = 0;
    break;
    numProbabilidade++;
    if(numProbabilidade > 200 && st.hasMoreTokens()) {
    JOptionPane.showMessageDialog(null,"S�o permitidos at� 200 probabilidades",
    "Erro", JOptionPane.ERROR_MESSAGE);
    input_string.setText("");
    numProbabilidade = 0;
    break;
    } else
    JOptionPane.showMessageDialog(null,"Insira algum valor.",
    "Erro", JOptionPane.ERROR_MESSAGE);
    * Todos os m�todos abaixos far�o algum ajuste necess�rio quando ocorrer uma
    * mudan�a no ScrollPane
    public void componentResized(ComponentEvent e)
    scroll.getSize();
    public void componentMoved(ComponentEvent e)
    public void componentShown(ComponentEvent e)
    public void componentHidden(ComponentEvent e)
    * Listener utilizado por Java para fazer todo o controle dos Eventos que
    * ocorram no aplicativo, ou seja, o pressionar dos tr�s bot�es, assim como
    * a utiliza��o da tecla Enter dentro do TextField. Para cada uma destas
    * a��es se encontrar� um c�digo diferente para seu processamento correto
    public void actionPerformed(ActionEvent evt) {
    if(evt.getSource() == reset_button) {               // Bot�o de Reiniciar
    end_button.setEnabled(true);
    step_button.setEnabled(true);
    numProbabilidade = 0;
    contarProbabilidade();
    if(input_string.getText().length() > 0) {
    if(parseProbabilidade(input_string.getText()))
    this.reset();
    stdout.println("Applet reinicializado");
    this.reset();
    * O bot�o de Proximo pode ser visto abaixo e ele quem far� todo o controle
    * gr�fico, assim como matem�tico em rela��o aos pr�ximos valores a serem
    * impressos na tela utilizando diversos m�todo diferentes
    } else if(evt.getSource() == step_button) {
    if(proximo) {
    if(calcProbabilidade(passo)) {
    proximo = false;
    marcador[passo] = -1;
    passo--;
    } else {
    int tmp = 0;
    for(; tmp < 400; tmp++)
    if(probabilidade[passo-1][tmp] == 0.0)
    break;
    Cent.printNextStep(passo, probabilidade[passo], marcador[passo]);
    stdout.println("As duas probabilidades inferiores da coluna " + passo
    +" foram somadas: " +
    f.format(probabilidade[passo-1][tmp-1]) + " + " +
    f.format(probabilidade[passo-1][tmp-2]) + " = " +
    f.format(probabilidade[passo][marcador[passo]]), false);
    stdout.println(1, "A soma � mostrada em negrito na coluna 2.",false);
    passo++;
    if(!proximo) {
    if(passo < 0) {
    Cent.setReverseStep(-1,-1,-1);
    end_button.setEnabled(false);
    step_button.setEnabled(false);
    for(int k = 0; k < 200; k++) // C�lculo da entropia
    if (probabilidade[0][k] != 0)
    entropia += probabilidade[0][k]*(-Math.log(probabilidade[0][k])) *
    Math.log(10) / Math.log(2) * Math.log(Math.exp(1/(Math.log(10))));
    Double ent = new Double(entropia);
    entropia = 0;
    String cod = new String("Codigo correspondente:\n\n");
    for(int m = 0; m < 200; m++)
    if (simbolo[0][m].length() > 0)
    cod += simbolo[0][m] + "\n";
    JOptionPane.showMessageDialog(null, cod, "Codigo", JOptionPane.INFORMATION_MESSAGE);
    stdout.println("Num. Prob.: " + numProbabilidade +
    " Entropia: " + ent);
    } else {
    designaSimbolo(passo);
    Cent.printReverseStep(passo,simbolo[passo]);
    passo--;
    * O bot�o de Concluir e ele simplesmente executar� o mesmo c�digo do bot�o
    * Proximo, por�m at� o fim da execu��o do programa *
    } else if(evt.getSource() == end_button) {
    end_button.setEnabled(false);
    step_button.setEnabled(false);
    entropia = 0;
    for(int k = 0; k < 400; k++) {
    if(proximo) {
    if(calcProbabilidade(passo)) {
    proximo = false;
    marcador[passo] = -1;
    passo--;
    } else {
    int tmp = 0;
    for(; tmp < 400; tmp++)
    if(probabilidade[passo-1][tmp] == 0.0)
    break;
    Cent.printNextStep(passo, probabilidade[passo], marcador[passo]);
    passo++;
    if(!proximo) {
    if(passo < 0) {
    Cent.setReverseStep(-1,-1,-1);
    } else {
    designaSimbolo(passo);
    Cent.printReverseStep(passo,simbolo[passo]);
    passo--;
    } // C�lculo da entropia abaixo
    if (probabilidade[0][k] != 0)
    entropia += probabilidade[0][k]*(-Math.log(probabilidade[0][k])) *
    Math.log(10) / Math.log(2) * Math.log(Math.exp(1/(Math.log(10))));
    Double ent = new Double(entropia);
    entropia = 0;
    stdout.println("Entropia " + f.format(ent));
    String cod = new String("Codigo correspondente:\n\n");
    for(int m = 0; m < 200; m++)
    if (simbolo[0][m].length() > 0)
    cod += simbolo[0][m] + "\n";
    JOptionPane.showMessageDialog(null, cod, "Codigo", JOptionPane.INFORMATION_MESSAGE);
    stdout.println("Num. Prob.: " + numProbabilidade +
    " Entropia: " + ent);
    * O c�digo abaixo far� todo o papel de abrir um arquivo com probabilidades,
    * assim como salvar um arquivo com as probabilidades
    /* } else if(evt.getSource() == file_button) {
    if(estArquivo) {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY):
    fileChooser.showSaveDialog(this);
    File fileName = fileChooser.getSelectedFile();
    if (fileName == null || fileName.getName().equals(""))
    JOptionPane.showMessageDialog(null, "Arquivo inv�lido.", "Erro",
    JOptionPane.ERROR_MESSAGE);
    else {
    try {
    ObjectInputStream input = new ObjectInputStream(new FileInputStream(fileName));
    String arq = (String) input.readObject();
    input_string.setText(arq);
    if(input_string.getText().length() > 0) {
    if(parseProbabilidade(input_string.getText())) {
    estArquuivo = false;
    end_button.setEnabled(true);
    step_button.setEnabled(true);
    numProbabilidade = 0;
    contarProbabilidade();
    this.reset();
    stdout.println("Applet reinicializado");
    this.reset();
    } catch (EOFException e) {
    JOptionPane.showMessageDialog(null, "Erro de EOF.", "Erro",
    JOptionPane.ERROR_MESSAGE);
    } catch (ClassNotFoundException e) {
    JOptionPane.showMessageDialog(null, "Erro: Class Not Found.", "Erro",
    JOptionPane.ERROR_MESSAGE);
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "Erro ao abrir arquivo.", "Erro",
    JOptionPane.ERROR_MESSAGE);
    try {
    input.close();
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "Erro ao fechar arquivo.", "Erro",
    JOptionPane.ERROR_MESSAGE);
    } else {
    if (passos < 0) {
    try {
    ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("c:\codigo.txt"));
    for(int o = 0; o < 200; o++) {
    while(simbolo[0][o].length() != 0) {
    output.writeObject(simbolo[0][o])
    output.writeObject(" ");
    output.flush();
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "Erro ao salvar no arquivo.", "Erro",
    JOptionPane.ERROR_MESSAGE);
    try {
    output.close();
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "Erro ao fechar arquivo.", "Erro",
    JOptionPane.ERROR_MESSAGE);
    } else {
    JOptionPane.showMessageDialog(null, "Finalize o processo.", "Erro",
    JOptionPane.ERROR_MESSAGE);
    /* } else if(evt.getSource() == fix_button) {
    try {
    input.close();
    estArquivo = true;
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "Erro abrindo arquivo.", "Erro",
    JOptionPane.ERROR_MESSAGE);
    * A a��o que ocorre quando se pressiona o bot�o Enter dentro do TextField
    * pode ser vista abaixo e � bem similar ao pressionar do bot�o Reiniciar
    } else if(evt.getSource() == input_string) {        // Utiliza��o da TextBox
    end_button.setEnabled(true);
    step_button.setEnabled(true);
    numProbabilidade = 0;
    contarProbabilidade();
    if(input_string.getText().length() > 0) {
    if(parseProbabilidade(input_string.getText()))
    this.reset();
    stdout.println("Applet reinicializado");
    this.reset();
    } else {                                            // Problema!
    stdout.println("Evento desconhecido ");
    * M�todo utilizado quando o bot�o Reiniciar � pressionado, ele reinicia os
    * valores para todas vari�veis e coloca na primeira coluna os primeiros
    * valores utilizados na �ltima experimenta��o
    void reset() {
    int i = 0, j = 0;
    Cent.clearScreen(probabilidade[0]);
    proximo = true;
    passo = 1;
    for(i = 0; i < 200; i++)
    marcador[i] = -1;
    for(i = 0; i < 200; i++)
    for(j = 0; j < 250; j++)
    simbolo[i][j] = "";
    * Testa quanto a viabilidade das probabilidades inseridas no TextBox estarem
    * de acordo com os criterios adotados e � bem simples de ser compreendida
    boolean parseProbabilidade(String s) {
    int linha = 0, i = 0;
    double soma = 0.0;
    double[] d = new double[200];
    StringTokenizer st = new StringTokenizer(s); // Conta o n�mero de itens
    // dentro de input_string
    for(i = 0; i < 200; i++)
    d[i] = 0.0;
    i = 0;
    while (st.hasMoreTokens()) {                  // Testa se h� mais Tokens
    try {
    d[i] = Double.valueOf(st.nextToken()).doubleValue();
    if(d[i] < 0) {
    return(false);
    if(d[i] > 1.0) {
    return(false);
    if(d[i] == 0.0) {
    return(false);
    } catch (NumberFormatException e) {
    JOptionPane.showMessageDialog(null, "Os n�meros n�o estao em sua forma correta",
    "Erro", JOptionPane.ERROR_MESSAGE);
    return(false);
    i++;
    bubblesort(d);
    for(i = 0; i < 200; i++) {                  // Testa quanto a viabilidade da
    soma += d; // das vari�veis
    if((soma <= 0.999999) || (soma >= 1.000001)) {
    JOptionPane.showMessageDialog(null, "A soma das probabilidadades n�o e igual a 1." +
    "\nA soma das probabilidade foi " + soma, "Erro", JOptionPane.ERROR_MESSAGE);
    return(false);
    for(i = 0; i < 200; i++)
    probabilidade[0][i] = d[i];
    stdout.println("Entrada de probabilidades correta. Pressione " + '\"' +
    "Proximo" + '\"' + " para continuar.");
    return(true);
    * Este m�todo ser� utilizado como sentinela pra a inicializa��o das
    * probabilidades
    void iniciarProbabilidade(double[] p) {
    inic = false;
    iniciarProbabilidade(p, p.length-1);
    * Executa a inicializa��o para alguns valores das probabilidades a partir
    * do objeto Rand()
    void iniciarProbabilidade(double[] p, int n) {
    Random rand = new Random();
    double soma = 0.0, s = 0.0;
    int i = 0;
    String input = " ";
    stdout.println(null); // Limpa o texto abaixo
    for(; i < 20; i++) {
    p[i] = rand.nextDouble() + 0.1; // Gera os n�meros iniciais
    soma += p[i]; // onde se deseja valores pr�ximos
    for(i = 0; i < 20; i++) {
    p[i] /= soma; // Escalonamento
    p[i] = Math.floor(p[i]*100) / 100.0; // Truncamento
    s += p[i];
    for(i = 0; i < 20; i++) // Utilizado para equilibrar as
    if(p[i] < 0.001) {                      //  probabilidades
    p[i] += 0.01;
    s -= 0.01;
    if (s < 1.000) {                          // Utilizado para inteirar a soma
    double resto = 1.0 - s;
    p[0] += resto;
    bubblesort(p);
    for(int k = 0; k < 20; k++) // Constroi string a ser exibida
    input += f2.format(p[k]) + " "; // dentro de string_input
    String input2 = input.replace(',','.');
    input_string.setText(input2);
    contarProbabilidade();
    * Faz um sort bem comum de todos as probabilidades inseridas
    void bubblesort(double[] d) {
    for(int i = 0; i < (d.length - 1); i++)
    for(int j = 0; j < (d.length - 1); j++)
    if(d[j] < d[j+1]) {
    double t = d[j];
    d[j] = d[j+1];
    d[j+1] = t;
    * Calcula o valor da probabilidade resultante a partir da soma das duas
    * probabilidades anteriores e seu c�digo � representando somente por loops
    * que setam estes valores
    boolean calcProbabilidade(int passo) {
    int n = 0, i = 0;
    double soma = 0.0;
    if(passo >= 0) {
    for(; i < 400; i++)
    if(probabilidade[passo-1][i] == 0.0)
    break;
    n = i;
    soma = probabilidade[passo-1][n-1] + probabilidade[passo-1][n-2];
    for(i = 0; i < 200; i++)
    if(probabilidade[passo-1][i] >= soma) {
    probabilidade[passo][i] = probabilidade[passo-1][i];
    } else
    break;
    marcador[passo] = i;
    probabilidade[passo][i] = soma;
    for(; i < 200; i++)
    probabilidade[passo][i+1] = probabilidade[passo-1][i];
    probabilidade[passo][n-1] = 0.0;
    probabilidade[passo][n] = 0.0;
    if(n == 2)
    return(true);
    else
    return(false);
    return(true);
    * Designa todos os s�mbolos ou c�digos para as probabilidades inseridas
    * a partir do controle feito pelos m�todos "actionPerformed" e
    * "calcProbabilidade"
    void designaSimbolo(int passo) {
    int i = 0, m = marcador[passo+1];
    String str = "";
    if(m == -1) {
    simbolo[passo][0] = "0";
    simbolo[passo][1] = "1";
    stdout.println("Os primeiros valores (0 e 1) foram designados na coluna" +
    " da extrema direita.", false);
    } else {
    for(; i < 400; i++)
    if(probabilidade[passo+1][i] != 0.0) {
    if(m == i) {
    str = simbolo[passo+1][i];
    } else if(m < i) {
    simbolo[passo][i-1] = simbolo[passo+1][i];
    } else if(m > i) {
    simbolo[passo][i] = simbolo[passo+1][i];
    } else
    System.out.println("Problema!!!");
    } else
    break;
    Cent.setReverseStep(passo,i,m);
    stdout.println("O c�digo correspondente a probabilidade marcada (" +
    f.format(probabilidade[passo+1][m]) +
    ") foi usado como base para se designar os valores.", false);
    stdout.println(1,"O c�digo das duas probabilidade inferiores (" +
    f.format(probabilidade[passo][i-1]) + ")(" +
    f.format(probabilidade[passo][i]) + ")" +
    " foram modificados. Os outros c�digos permanecem" +
    " os mesmos.", false);
    simbolo[passo][i-1] = str + "0";
    simbolo[passo][i] = str + "1";
    * Inicializa todo o aplicativo caso seja feito stand-alone
    /* public static void main(String args[]) {
    JFrame f = new JFrame("C�digo de Huffman");
    Huff codigo = new Huff();
    codigo.inAnApplet = false;
    codigo.init();
    f.getContentPane().add("Center", codigo);
    f.setSize(800,600);
    f.show();
    codigo.start();
    * A classe abaixo � utilizada para o controle de todas as mensagens exibidas
    * ao usu�rio do applet a partir do JPanel stdout, assim como comunica��o
    * via interface MS-DOS
    class ErrorCanvas extends Canvas {
    private String output, output2;
    public void paint(Graphics g) {
    if(output == null) {
    g.drawString("C�digo de Huffman", 350, 20);
    g.drawString("Arildo Fran�a Oliva Filho - 99/32810", 20, 40);
    g.drawString("Leonardo Lobo Pulcineli - 99/20064", 20, 60);
    g.drawString("Marcos Garrison Dytz - 99/20102", 550, 40);
    g.drawString("Octavio do Vale Rocha - 99/20129", 550, 60);
    } else {
    g.drawString(output,20,20);
    void println(String s)
    println(0,s);
    void println(String s,boolean echo)
    println(0,s,echo);
    void println(int linha,String s)
    println(linha,s,true);
    void println(int linha,String s,boolean echo)
    if(linha == 0)
    output = s;
    output2 = "";
    } else
    output2 = s;
    this.repaint();
    if(s != null && echo)
    System.out.println(s);
    * A classe abaixo � utilizada na cria��o de toda a interface gr�fica utilizada
    * pelo programa como as diversas setas que ligam as probabilidades, a cria��o
    * das colunas e controle em rela��o as cores dos c�digos.
    * Grande parte do c�digo deste classe deve ser creditado a Paul Williams.
    class cent extends JPanel {
    private int reverse_step = -1;
    private int rs_y, rs_m;
    private String[][] buffer; // O conjunto de vari�veis abaixo controlam
    private int[] xoffsets; // todo o posicionamento dos diferentes
    private int[] yoffsets; // objetos na tela
    private int[] lines;
    private int yoffset,yhalfoffset,linexoffset,
    ybelowoffset,xrightoffset;
    protected boolean isinit = false;
    protected boolean repainting = false;
    Font boldfont = null, deffont;
    DecimalFormat f = new DecimalFormat("0.00");
    * Executa a inicializa��o de todas vari�veis e arrays, assim como dos objetos
    * que ser�o manipulados pela interface gr�fica caso eles n�o tenham ocorrido
    void init() {
    if(!isinit) {
    xoffsets = new int[200];
    for(int k =0; k < xoffsets.length; k++)
    xoffsets[k] = 40 + k * 60;
    yoffset = 16;
    yoffsets = new int[400];
    int i;
    for(i = 0; i < yoffsets.length; i++)
    yoffsets[i] = 30 * (i+1) + 60;
    buffer = new String[200][400];
    int j;
    for(i = 0; i < 200; i++)
    for(j = 0; j < 400; j++)
    buffer[i][j] = "";
    lines = new int[400];
    for(i = 0; i < lines.length; i++)
    lines[i] = -1;
    linexoffset = 45; // offset of left of line from left of text
    xrightoffset = 5; // offset between forward and reverse(red) text
    ybelowoffset = 12; // offset between forward and reverse(red) text
    yhalfoffset = 5; // offset for lines (half a character)
    deffont = new Font("Dialog", 0, 12);
    boldfont = new Font("Dialog", Font.BOLD, 12);
    if(deffont == null || boldfont == null) {
    boldfont = null;
    System.out.println("N�o foi poss�vel indicar o valor para as fontes.");
    isinit = true;
    repainting = false;
    * Construtor para essa classe e define que se a classe n�o tive sido inicia-
    * lizada, ent�o ser� por este construtor
    public cent()
    if(!isinit)
    this.init();
    * Limpa todo o conte�do exibido no JPanel Cent
    void clearScreen(double[] p) {
    int i,j;
    for(i = 0; i < 200; i++)
    for(j = 0; j < 400; j++)
    buffer[i][j] = "";
    for(i = 0;i < lines.length; i++)
    lines[i] = -1;
    for(i = 0; i < 200; i++) {
    if(p[i] == 0.0)
    buffer[0][i*2] = "";
    else
    buffer[0][i*2] = f.format(p[i]);
    repaint();

  • Swing (JScrollPane - scroll bar) help

    Hello all..
    I am new user in Swing. Currently I am developing a program using JSCrollPane. I have to draw a kind of chart in it. Therefore as a drawing media, I used the JPanel, in which I put it inside my JScrollPane. Then.. since my graphic is long.. then I set the
    setHorizontalScrollBarPolicy value to ALWAYS. Then I put my JPanel using the following commands :
    this.jScrollPane1.setViewportView(this.jPanel2);
    this.jScrollPane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    Fyi, my JPanel size is set to be wider than the jScrollPane3 size. Nevertheless.. during the run time the horizontal scroll bar is not shown. I am completely loss on how to solve this. Does anyone has any clue or solution for this problem. Thank you very much in advance.
    Kariyage.

    Fyi, my JPanel size is set to be wider than the jScrollPane3 sizeYou should use panel.setPreferredSize(...) not panel.setSize(...);

  • Nothing Appears in Swing until Border Resizes

    I'm creating a GUI using SWING, and everything compiles fine, except when it is interpretted nothing appears, like menus, buttons and labels, until I resize the application or click on the borders. Any suggestions on how to fix this would be appreiciated.

    Hi kizac
    I think ur sequence of bulding GUI is not proper.
    Proper seq should be like this
    1.Build the GUI(create all components and setSize or SetPreferredSize)
    2.Add all event Listeners
    3. At the last make ur Main Frame VISIBLE
    Hope this will help u
    Ashish

  • Displaying html in Swing

    I have downloaded a weather sticker from weatherbug. If I use it in an html page, it works fine. If I use the following code to put it in a swing frame, it does not. What I am doing incorrectly?
    import javax.swing.JEditorPane;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JScrollPane;
    import java.io.IOException;
    public class HtmlTest extends JPanel {
        /** Creates a new instance of HtmlTest */
        public HtmlTest() {
            //String htmlText = "<link rel='stylesheet' type='text/css' media='screen' title='160x600_v2' href='http://img.weather.weatherbug.com/Style/stickers/v2/Stickers_160x600.css' /><div class='wXbody'><div class='headerlogo'><a href='http://weather.weatherbug.com/default.html' target='_blank' onclick='Javascript:this.href='http://weather.weatherbug.com/IN/Rockville-weather.html?zcode=z5545&units=0''><img src='http://img.weather.weatherbug.com/images/stickers/v2/160x600/top-wxbug-logo.jpg' border='0' alt='WeatherBug' /></a></div><iframe id='WeatherBugSticker_160x600_v2' src='http://weather.weatherbug.com/desktop-weather/getSticker.html?ZipCode=47872&ZCode=z5545&Size=160x600&StationID=ROCKS&units=0&Version=2' width='146' height='296' frameborder='0' scrolling='no' allowtransparency='yes'></iframe><div class='wXlinks'><span class='link'><a href='http://weather.weatherbug.com/weather-forecast.html' target='_blank' onclick='Javascript:this.href='http://weather.weatherbug.com/IN/Rockville-weather/local-forecast/7-day-forecast.html?zcode=z5545&units=0''>Forecast</a></span><br /><br /><span class='link'><a href='http://weather.weatherbug.com/doppler-radar.html' target='_blank' onclick='Javascript:this.href='http://weather.weatherbug.com/IN/Rockville-weather/local-radar/doppler-radar.html?zcode=z5545&units=0''>Radar</a></span><br /><br /><span class='link'><a href='http://community-weather.weatherbug.com/community/weather-photos/photo-gallery.html' target='_blank' onclick='Javascript:this.href='http://community-weather.weatherbug.com/community/weather-photos/photo-gallery.html?zcode=z5545&units=0&zip=47872''>Photos</a></span></div><div class='wXlinks2'><span class='link'><a href='http://weather.weatherbug.com/weather-cams.html' target='_blank' onclick='Javascript:this.href='http://weather.weatherbug.com/IN/Rockville-weather/weather-cams/local-cams.html?zcode=z5545&units=0''>Cameras</a></span><br /><br /><span class='link'><a href='http://weather.weatherbug.com/weather-reports.html' target='_blank' onclick='Javascript:this.href='http://weather.weatherbug.com/weather-reports.html?zcode=z5545&units=0&zip=47872''>News</a></span><br /><br /><span class='link'><a href='http://weather.weatherbug.com/travel-forecast.html' target='_blank' onclick='Javascript:this.href='http://weather.weatherbug.com/travel-forecast.html?zcode=z5545&units=0&zip=47872''>Travel</a></span></div><div class='footer'><a href='http://weather.weatherbug.com/default.html' target='_blank' onclick='Javascript:this.href='http://weather.weatherbug.com/IN/Rockville-weather.html?zcode=z5545&units=0''><img src='http://img.weather.weatherbug.com/images/stickers/v2/160x600/local.jpg' border='0' alt='WeatherBug' /></a><br /><a href='http://weather.weatherbug.com/default.html' target='_blank' onclick='Javascript:this.href='http://weather.weatherbug.com/IN/Rockville-weather.html?zcode=z5545&units=0''><img src='http://img.weather.weatherbug.com/images/stickers/v2/160x600/bt-wxbug-logo.jpg' border='0' id='logo' alt='WeatherBug' /></a><br /><div class='footertext'>Your weather just got better.</div></div>";   
               String htmlText="<html><link rel='stylesheet' type='text/css' media='screen' title='160x600_v2' href='http://img.weather.weatherbug.com/Style/stickers/v2/Stickers_160x600.css' />" + 
               "<div class='wXbody'>" +
                "<div class='headerlogo'>" +
                "<a href='http://weather.weatherbug.com/default.html' target='_blank' onclick='Javascript:this.href='http://weather.weatherbug.com/IN/Rockville-weather.html?zcode=z5545&units=0''><img src='http://img.weather.weatherbug.com/images/stickers/v2/160x600/top-wxbug-logo.jpg' border='0' alt='WeatherBug' /></a></div>" +
                "<iframe id='WeatherBugSticker_160x600_v2' src='http://weather.weatherbug.com/desktop-weather/getSticker.html?ZipCode=47872&ZCode=z5545&Size=160x600&StationID=ROCKS&units=0&Version=2' width='146' height='296' frameborder='0' scrolling='no' allowtransparency='yes'></iframe>" +
                "<div class='wXlinks'>" +
                "<span class='link'><a href='http://weather.weatherbug.com/weather-forecast.html' target='_blank' onclick='Javascript:this.href='http://weather.weatherbug.com/IN/Rockville-weather/local-forecast/7-day-forecast.html?zcode=z5545&units=0''>Forecast</a></span><br /><br />" +
               "<span class='link'><a href='http://weather.weatherbug.com/doppler-radar.html' target='_blank' onclick='Javascript:this.href='http://weather.weatherbug.com/IN/Rockville-weather/local-radar/doppler-radar.html?zcode=z5545&units=0''>Radar</a></span><br /><br />" +
                 "<span class='link'><a href='http://community-weather.weatherbug.com/community/weather-photos/photo-gallery.html' target='_blank' onclick='Javascript:this.href='http://community-weather.weatherbug.com/community/weather-photos/photo-gallery.html?zcode=z5545&units=0&zip=47872''>Photos</a></span>" +
                "</div>" +
                "<div class='wXlinks2'>" +
                "<span class='link'><a href='http://weather.weatherbug.com/weather-cams.html' target='_blank' onclick='Javascript:this.href='http://weather.weatherbug.com/IN/Rockville-weather/weather-cams/local-cams.html?zcode=z5545&units=0''>Cameras</a></span><br /><br />" +
                 "<span class='link'><a href='http://weather.weatherbug.com/weather-reports.html' target='_blank' onclick='Javascript:this.href='http://weather.weatherbug.com/weather-reports.html?zcode=z5545&units=0&zip=47872''>News</a></span><br /><br />" +
                 "<span class='link'><a href='http://weather.weatherbug.com/travel-forecast.html' target='_blank' onclick='Javascript:this.href='http://weather.weatherbug.com/travel-forecast.html?zcode=z5545&units=0&zip=47872''>Travel</a></span>" +
                "</div>" +
               "<div class='footer'>" +
               "<a href='http://weather.weatherbug.com/default.html' target='_blank' onclick='Javascript:this.href='http://weather.weatherbug.com/IN/Rockville-weather.html?zcode=z5545&units=0''><img src='http://img.weather.weatherbug.com/images/stickers/v2/160x600/local.jpg' border='0' alt='WeatherBug' /></a><br />" +
               "<a href='http://weather.weatherbug.com/default.html' target='_blank' onclick='Javascript:this.href='http://weather.weatherbug.com/IN/Rockville-weather.html?zcode=z5545&units=0''><img src='http://img.weather.weatherbug.com/images/stickers/v2/160x600/bt-wxbug-logo.jpg' border='0' id='logo' alt='WeatherBug' /></a><br />" +
               "<div class='footertext'>Your weather just got better.</div>" +
               "</div>";
            JLabel label = new JLabel(htmlText);
            this.add(label);
        public static void main(String args[]) {
            JFrame frame = new JFrame();
            HtmlTest htmlTest = new HtmlTest();
            frame.add(htmlTest);
            frame.pack();
            frame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
    }

    Java's HTML support is pretty minimal. You can't use stylesheets. I'm skeptical as to whether DIV tags work either

  • BufferedImages and Swing's ScrollablePicture in a JPanel

    I'm referring to http://java.sun.com/developer/technicalArticles/Media/imagestrategies/index.html paper.
    As I read this excellent paper, I decided to go for the BufferedImage strategy.
    But I can't put my BufferedImage into my ScrollablePicture as below:
    JPanel picPanel = new JPanel(new GridBagLayout());
    //Set up the scroll pane.
    picture = new ScrollablePicture(imageIcon_, columnView.getIncrement()); // OK
    //picture = new ScrollablePicture(bImg, columnView.getIncrement()); // NOT OK = don't work
    ...How to bypass the message "java:542: cannot resolve symbol symbol : constructor ScrollablePicture (java.awt.image.BufferedImage,int)"
    It is very important as all my code is based on BufferedImage to apply many operations on the image.
    ? I believe the API does not allow to perform RGB to B&W operation on ImageIcon. ?
    Thanks to all.
    dimitryous r.

    Hi camickr,
    Hi all,
    I pass trough my SSCCE. Good advice from camickr. But it was not so easy:
    Short: not so short
    Self contained: believe so
    Correct: Java 1.4.2 code
    Compilable: yes
    I'm back with formatted code.
    I'm sure you will fire at me all of you. Anyway if I don't even try, I will never succeed.
    //  TooAwoo.java
    //  TooAwoo
    //     part of this code is from Sun's JavaTutorial 1.4.2
    import java.applet.Applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.GraphicsEnvironment;
    import java.awt.image.*;
    import java.lang.*;
    import java.lang.String;
    import java.lang.Object;
    import java.net.URL;
    import java.net.MalformedURLException;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.event.MouseInputAdapter;
    import javax.swing.ImageIcon;
    import javax.swing.JScrollPane;
    import javax.swing.JToggleButton;
    import java.io.FilePermission;
    public class TooAwoo extends JApplet implements
                                                                ChangeListener,
                                                                ActionListener,
                                                                ItemListener
         FilePermission p = new FilePermission("<<ALL FILES>>", "read,write");
        public BufferedImage bImg;
         Font newFont = new Font("SansSerif", Font.PLAIN, 10);
         ImageControls RightPanel;
         public static int initOx = 0;
         public static int initOy = 0;
         int init_ww, init_wh, set_x, set_y = 0;
         final int pSP_w = 520; // final width of pictureScrollPane
         final int pSP_h = 650; // final height of pictureScrollPane
         Dimension applet_window; // applet dimensions
         public Image image;
         public ImageIcon imageIcon_;
         public static BufferedImage binull;
         // ScrollablePicture stuff
         public Rule columnView;
        public Rule rowView;
         public JToggleButton isMetric;
        public ScrollablePicture picture;
         public JScrollPane pictureScrollPane;
         public TooAwoo() {
              // nothing here
        public void init() {
              applet_window = getSize();                                                            // read applet dimensions in TooAwoo.html
              init_ww = applet_window.width;
              init_wh = applet_window.height;
              // get the image to use width > 680 (see final int pSP_w above)
              image = getImage(getDocumentBase(), "images/ReallyBig.jpg");
              imageIcon_ = createImageIcon("images/ReallyBig.jpg");
              int iw = imageIcon_.getIconWidth();
              int ih = imageIcon_.getIconHeight();
              bImg = new BufferedImage(iw, ih, BufferedImage.TYPE_INT_RGB);
              // Panels
              // ImageDisplayPanel
            //Create the row and column headers.
            columnView = new Rule(Rule.HORIZONTAL, true);
            rowView = new Rule(Rule.VERTICAL, true);
            if (imageIcon_ != null) {
                columnView.setPreferredWidth(imageIcon_.getIconWidth());
                rowView.setPreferredHeight(imageIcon_.getIconHeight());
            } else {
                columnView.setPreferredWidth(640);
                rowView.setPreferredHeight(480);
            //Create the upper left corner.
            JPanel buttonCorner = new JPanel();                                                  //use FlowLayout
            isMetric = new JToggleButton("cm", true);
            isMetric.setFont(newFont);
            isMetric.setMargin(new Insets(2,2,2,2));
            isMetric.addItemListener(this);                                                       // !!! not OK = don't work: button is not firing
            buttonCorner.add(isMetric);
              JPanel ImageDisplayPanel = new JPanel(new GridBagLayout());
            //Set up the scroll pane.
              picture = new ScrollablePicture(imageIcon_, columnView.getIncrement());     // either
              //picture = new ScrollablePicture(bImp, columnView.getIncrement());          // or
              // ********** if bImp change the lines in ScrollablePicture.java **********
            Graphics g = bImg.getGraphics();
              g.drawImage(bImg, 0, 0, null);
              JScrollPane pictureScrollPane = new JScrollPane(picture);
            pictureScrollPane.setPreferredSize(new Dimension(pSP_w, pSP_h));
            pictureScrollPane.setViewportBorder(
                    BorderFactory.createLineBorder(Color.black));
            pictureScrollPane.setColumnHeaderView(columnView);
            pictureScrollPane.setRowHeaderView(rowView);
              //Set the corners.
            pictureScrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER, buttonCorner);
            pictureScrollPane.setCorner(JScrollPane.LOWER_LEFT_CORNER,
                                        new Corner());
            pictureScrollPane.setCorner(JScrollPane.UPPER_RIGHT_CORNER,
                                        new Corner());
              //set_y++;
              addToGridBag(ImageDisplayPanel,pictureScrollPane, set_x, set_y, 1, 1, 0, 0); // 0,0
              getContentPane().add( BorderLayout.WEST, ImageDisplayPanel);               // where to display the bImg: left
              RightPanel = new ImageControls();                                                  // call the ImageControls class
              RightPanel.setBackground(Color.black);
              getContentPane().add( BorderLayout.EAST, RightPanel);
              //getContentPane().add( BorderLayout.EAST, ToolsPanel);                         // where to display the tools: right
              JPanel GlobalPanel = new JPanel(new GridBagLayout());
              getContentPane().add( BorderLayout.NORTH, GlobalPanel);
         } // end public void init()
         public Graphics2D createGraphics2D(int width,
                                                    int height,
                                                    BufferedImage bi,
                                                    Graphics g) {                                   // called by ImageControls paint
              Graphics2D g2 = null;
              if (bi != null) {
                   System.out.println("TooAwoo createGraphics2D: bi != null : " + " w= " + width + " h= " + height);
                   g2 = bi.createGraphics();
              } else {
                   System.out.println("TooAwoo createGraphics2D: bi == null g2 = (Graphics2D) g");
                   g2 = (Graphics2D) g;
              return g2; // return to ImageControls paint
         } // end createGraphics2D
         class ImageControls extends JPanel {
              public void paint(Graphics g) {
                   Dimension applet_window = getSize();
                   if (bImg == null) {
                        bImg = createBufferedImage(applet_window.width, applet_window.height, 2);
                   } else {
                        Graphics2D g2 = createGraphics2D(applet_window.width, applet_window.height, bImg, g);
                        g.drawImage( bImg , initOx , initOy , null );
                        g2.dispose();
                        //toolkit.sync();
                   } // end else (bImg != null)
              } // end paint
         } // end ImageControls
         public Dimension setPreferredSize() {
              Dimension applet_window = getSize();
              return applet_window;
         public String getString(String key) {
              return key;
         public BufferedImage createBufferedImage(int w, int h, int imgType) {          // called by ImageControls paint
              BufferedImage bi = null;
              if (imgType == 0) {
                   bi = (BufferedImage) getGraphicsConfiguration().createCompatibleImage(w, h);
              } else if (imgType > 0 && imgType < 14) {
                   bi = new BufferedImage(w, h, imgType);
              System.out.println("TooAwoo createBufferedImage: imgType= " + imgType + " w= " + w + " h= " + h);
              return bi;
         public static void addToGridBag(JPanel panel, Component comp,
                                                 int x, int y, int w, int h, double weightx, double weighty) {
              GridBagLayout gbl = (GridBagLayout) panel.getLayout();
              GridBagConstraints c = new GridBagConstraints();
              c.fill = GridBagConstraints.BOTH;
              c.anchor = GridBagConstraints.WEST;
              c.gridx = x;
              c.gridy = y;
              c.gridwidth = w;
              c.gridheight = h;
              c.weightx = weightx;
              c.weighty = weighty;
              panel.add(comp);
              gbl.setConstraints(comp, c);
         } // end addToGridBag
         protected static ImageIcon createImageIcon(String path) {                         // Returns an ImageIcon, or null if the path was invalid.
              java.net.URL imgURL = TooAwoo.class.getResource(path);
              if (imgURL != null) {
                   return new ImageIcon(imgURL);
              } else {
                   System.err.println("Couldn't find file: " + path);
                   return null;
         } // end createImageIcon
         private static void createAndShowGUI() {                                             // called by main
              JFrame frame = new JFrame("TooAwoo");                                             //Create and set up the window.
              // Make sure we have nice window decorations.
              frame.setDefaultLookAndFeelDecorated(true);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // Create and set up content pane.
              frame.addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              JPanel masterPanel = new JPanel();
              frame.add("Center", masterPanel);
              // Display the window.
              frame.pack();
              frame.setSize(new Dimension( 1000 , 640 ));
              frame.setVisible(true);
         } // end createAndShowGUI
         public static void main(String s[]) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        createAndShowGUI();
         } // end main
         public void actionPerformed(ActionEvent e) {
              repaint(1024);
        public void stateChanged(ChangeEvent e) {
              repaint(1024);
         public void itemStateChanged(ItemEvent e) {
              Object obj = e.getSource();
              if ( obj == isMetric ) {
                   System.out.println("obj isMetric");
                //Turn it to metric.
                rowView.setIsMetric(true);
                columnView.setIsMetric(true);
                   picture.setMaxUnitIncrement(rowView.getIncrement());
            } else {
                System.out.println("obj isNotMetric");
                   //Turn it to inches.
                rowView.setIsMetric(false);
                columnView.setIsMetric(false);
                   picture.setMaxUnitIncrement(rowView.getIncrement());
         } // end itemStateChanged(ItemEvent e)
    } // end TooAwoo
    Next is ScrollablePicture.java
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class ScrollablePicture extends JLabel implements Scrollable {
        private int maxUnitIncrement = 1;
         private boolean missingPicture = false;
        public ScrollablePicture (ImageIcon imageIcon_, int m){                              //(BufferedImage bImg, int m)
            super(imageIcon_); // comment this line if bImg...
              if (imageIcon_ == null) { // change imageIcon_ to bImg if bImg...
                   missingPicture = true;
                   setText("No picture found.");
                   setHorizontalAlignment(CENTER);
                   setOpaque(true);
                   setBackground(Color.black);
              maxUnitIncrement = m;
        public Dimension getPreferredScrollableViewportSize() {
            return getPreferredSize();
        public int getScrollableUnitIncrement(Rectangle visibleRect,
                                              int orientation,
                                              int direction) {
            //Get the current position.
            int currentPosition = 0;
            if (orientation == SwingConstants.HORIZONTAL)
                currentPosition = visibleRect.x;
            else
                currentPosition = visibleRect.y;
            //Return the number of pixels between currentPosition
            //and the nearest tick mark in the indicated direction.
            if (direction < 0) {
                int newPosition = currentPosition -
                   (currentPosition / maxUnitIncrement) *
                   maxUnitIncrement;
                return (newPosition == 0) ? maxUnitIncrement : newPosition;
            } else {
                return ((currentPosition / maxUnitIncrement) + 1) *
                   maxUnitIncrement - currentPosition;
        public int getScrollableBlockIncrement(Rectangle visibleRect,
                                               int orientation,
                                               int direction) {
            if (orientation == SwingConstants.HORIZONTAL)
                return visibleRect.width - maxUnitIncrement;
            else
                return visibleRect.height - maxUnitIncrement;
        public boolean getScrollableTracksViewportWidth() {
            return false;
        public boolean getScrollableTracksViewportHeight() {
            return false;
        public void setMaxUnitIncrement(int pixels) {
            maxUnitIncrement = pixels;
    Next is Corner.java
    import java.awt.*;
    import javax.swing.*;
    public class Corner extends JComponent {
        protected void paintComponent(Graphics g) {
            g.setColor(new Color(230, 163, 4));
            g.fillRect(0, 0, getWidth(), getHeight());
    Next is Rule.java
    import java.awt.*;
    import javax.swing.*;
    public class Rule extends JComponent {
        public static final int INCH = Toolkit.getDefaultToolkit().
                getScreenResolution();
        public static final int HORIZONTAL = 0;
        public static final int VERTICAL = 1;
        public static final int SIZE = 30;
        public int orientation;
        public boolean isMetric;
        private int increment;
        private int units;
        public Rule(int o, boolean m) {
            orientation = o;
            isMetric = m;
            setIncrementAndUnits();
        public void setIsMetric(boolean isMetric) {
            this.isMetric = isMetric;
            setIncrementAndUnits();
            repaint();
        private void setIncrementAndUnits() {
            if (isMetric) {
                units = (int)((double)INCH / (double)2.54); // dots per centimeter
                increment = units;
            } else {
                units = INCH;
                increment = units / 2;
        public boolean isMetric() {
            return this.isMetric;
        public int getIncrement() {
            return increment;
        public void setPreferredHeight(int ph) {
            setPreferredSize(new Dimension(SIZE, ph));
        public void setPreferredWidth(int pw) {
            setPreferredSize(new Dimension(pw, SIZE));
        protected void paintComponent(Graphics g) {
            Rectangle drawHere = g.getClipBounds();
            // Fill clipping area with dirty brown/orange.
            g.setColor(new Color(230, 163, 4));
            g.fillRect(drawHere.x, drawHere.y, drawHere.width, drawHere.height);
            // Do the ruler labels in a small font that's black.
            g.setFont(new Font("SansSerif", Font.PLAIN, 10));
            g.setColor(Color.black);
            // Some vars we need.
            int end = 0;
            int start = 0;
            int tickLength = 0;
            String text = null;
            // Use clipping bounds to calculate first and last tick locations.
            if (orientation == HORIZONTAL) {
                start = (drawHere.x / increment) * increment;
                end = (((drawHere.x + drawHere.width) / increment) + 1)
                      * increment;
            } else {
                start = (drawHere.y / increment) * increment;
                end = (((drawHere.y + drawHere.height) / increment) + 1)
                      * increment;
            // Make a special case of 0 to display the number
            // within the rule and draw a units label.
            if (start == 0) {
                text = Integer.toString(0) + (isMetric ? " cm" : " in");
                tickLength = 8;//10;
                if (orientation == HORIZONTAL) {
                    g.drawLine(0, SIZE-1, 0, SIZE-tickLength-1);
                    g.drawString(text, 2, 21);
                } else {
                    g.drawLine(SIZE-1, 0, SIZE-tickLength-1, 0);
                    g.drawString(text, 9, 10);
                text = null;
                start = increment;
            // ticks and labels
            for (int i = start; i < end; i += increment) {
                if (i % units == 0)  {
                    tickLength = 7;//10;
                    text = Integer.toString(i/units);
                } else {
                    tickLength = 4;//7;
                    text = null;
                if (tickLength != 0) {
                    if (orientation == HORIZONTAL) {
                        g.drawLine(i, SIZE-1, i, SIZE-tickLength-1);
                        if (text != null)
                            g.drawString(text, i-3, 21);
                    } else {
                        g.drawLine(SIZE-1, i, SIZE-tickLength-1, i);
                        if (text != null)
                            g.drawString(text, 9, i+3);
    Here is TooAwoo.html
    <HTML>
    <HEAD>
    <TITLE>TooAwoo</TITLE>
    </HEAD>
    <BODY>
    <APPLET archive="TooAwoo.jar" code="TooAwoo" width=1024 height=800>
    Your browser does not support Java, so nothing is displayed.
    </APPLET>
    </BODY>
    </HTML>
    */Total number of lines: 486
    Weight: 15 199 bytes
    Total number of files: 5
    TooAwoo.java
    ScrollablePicture.java
    Corner.java
    Rule.java
    TooAwoo.html
    ... in that order in my code
    The major default is: I cannot have that BuffuredImage at the left of the screen if run using bImp at line 91 of TooAwoo.java.
    Minor bug: the JToggle button (inch/cm) does not fires-up correctly. Nothing change.
    Anyway feel free to fire at me if you believe its a good strategy. I will remain very positive to all comments and suggestions.
    Thanks.
    dimitryous r.

  • Unable to grow and shrink a JTable within a JScrollPane

    I need help with the following: I want to display a JTable component with a calendar like design. Dragging the size of the parent component (having a border to drag) should dynamically adapt the JTable' size and its cells. Since the JTable has a minimum size shrinking the parent component should show scrollbars if the minimum size is reached horizontal or vertical respectively.
    I have the JTable put ijnto the viewport of a scrollpane and the scrollpane is the child component of a JPanel. So dragging appears with the panel.
    The JTable cells do nicely but from a specific size on there is a grey area on the lower part of the JPanel which is not repainted. What is causing this? What do I have to do? I'm lost in the jungle of invalidate(), repaint(), update(), doLayout() etc.
    Here is my SSCCE (at least I hope it is one):
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.ListSelectionModel;
    import javax.swing.UIManager;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableModel;
    //public class MyComponent extends JScrollPane
    public class MyComponent extends JPanel
    ///   class data
         static public final long serialVersionUID = -1L;
         static public final int c_ColWidth = 29;
         static public final int c_RowHeight = 18;
         static public final int c_TableWidth = 930;
         static public final int c_TableHeight = 234;
    ///   instance data
         private String[] m_strColHeader = {
              "01", "02", "03", "04", "05", "06", "07", "08", "09", "10",
              "11", "12", "13", "14", "15", "16", "17", "18", "19", "20",
              "21", "22", "23", "24", "25", "26", "27", "28", "29", "30",
              "31",
         private Object[][] m_Data = new Object[12][33];// data array
         private TableModel m_DataModel = new AbstractTableModel() {
              static public final long serialVersionUID = -1L;
              public int getColumnCount() { return m_strColHeader.length; }
              public int getRowCount() { return m_Data != null ? m_Data.length : 0; }
              public Object getValueAt(int row, int col) { return m_Data[row][col]; }
              public String getColumnName(int col) { return m_strColHeader[col]; }
              public Class getColumnClass(int col) { return String.class; }
              public boolean isCellEditable(int row, int col) { return false; }
              public void setValueAt(Object aValue, int row, int col) {
                   m_Data[row][col] = aValue;
         protected BorderLayout myLayout = new BorderLayout();
         protected JTable tableView = new JTable(m_DataModel);
         protected JScrollPane scrollPane = new JScrollPane(tableView);
    ///   public class methods
         static public void main(String[] args)
              try
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch(Exception e)
                   e.printStackTrace();
              MyComponent comp1 = new MyComponent();
              JFrame frame = new JFrame("MyComponent");
              frame.addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              frame.getContentPane().add(comp1);
              frame.pack();
              frame.setVisible(true);
    ///   constructors
         public MyComponent()
              try
                   jbInit();
                   initTable();
              catch(Exception ex)
                   ex.printStackTrace();
    ///   protected instance methods
         protected void initTable()
              // do nor allow user interaction with calendar view
              tableView.getTableHeader().setReorderingAllowed(false);
              tableView.getTableHeader().setResizingAllowed(false);
              //tableView.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
              tableView.setRowHeight(c_RowHeight);
              // adapt all CellRenderers
              for (int i = 0; i < m_DataModel.getColumnCount(); i++)
                   TableColumn column = tableView.getColumn(tableView.getColumnName(i));
                   column.setMinWidth(c_ColWidth);
                   column.setPreferredWidth(c_ColWidth);
    ///   private instance methods
         private void jbInit() throws Exception
              this.setLayout(myLayout);
              this.add(scrollPane, BorderLayout.CENTER);
              scrollPane.getViewport().setMinimumSize(new Dimension(c_TableWidth, c_TableHeight));
              scrollPane.getViewport().setPreferredSize(new Dimension(c_TableWidth, c_TableHeight));
              tableView.setPreferredSize(new Dimension(c_TableWidth, c_TableHeight));
              addComponentListener(new MyComponent_componentAdapter(this));
    ///   event handling
         public void componentBoundsChanged(ComponentEvent e)
              scrollPane.setBounds(0, 0, getWidth(), getHeight());
              scrollPane.getViewport().setBounds(0, 0, getWidth(), getHeight());
              //tableView.setBounds(0, 0, getWidth(), getHeight());
              tableView.setSize(scrollPane.getViewport().getWidth(), scrollPane.getViewport().getHeight());
              tableView.setRowHeight(getBounds().height / 13 < c_RowHeight ?
                        c_RowHeight : getBounds().height / 13);
              System.out.println("componentBoundsChanged: getBounds() = " + getBounds());
              System.out.println("componentBoundsChanged: getSize() = " + getSize());
              System.out.println("componentBoundsChanged: getViewport().getBounds() = " + scrollPane.getViewport().getBounds());
              System.out.println("componentBoundsChanged: getViewport().getSize() = " + scrollPane.getViewport().getSize());
              System.out.println("componentBoundsChanged: tableView.getBounds() = " + tableView.getBounds());
              System.out.println("componentBoundsChanged: tableView.getSize() = " + tableView.getSize());
    ///   event adapters
    class MyComponent_componentAdapter extends ComponentAdapter
         protected MyComponent adaptee;
         MyComponent_componentAdapter(MyComponent adaptee)
              this.adaptee = adaptee;
         public void componentMoved(ComponentEvent e)
              adaptee.componentBoundsChanged(e);
         public void componentResized(ComponentEvent e)
              adaptee.componentBoundsChanged(e);
    }

    I guess i am facing exactly opposite problem.
    What i want to do is, I have nested tables in a scroll pane. So I don't want a scroll pane to show exactly whatever visible rows are there in Table (No extra space). If i expand any row, i want scroll pane to be able to show expanded.

  • JScrollPane will not expand

    I have added a JTree which has a default size of 92 x 72 pixels into a JScrollPane which is then added to a frame. My problem is that my JScrollPane has a Viewport size of 0 x 0, even after I set its minimum size to 150 x 150. I cannot view my JTree in the JScrollPane. I have been trying to figure out this problem for the past two days. This is getting really annoying. My code is below, comments or suggestions appreciated.
    public class GUI_Launch
    public static void main(String[] args)
    SpringLayout layout = new SpringLayout();
    JFrame frame = new JFrame();
    frame.setTitle("GUI Demo");
    frame.setSize(WIDTH, HEIGHT);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.show();
    SimpleTree tree = new SimpleTree(frame, layout);
    private static final int WIDTH = 700;
    private static final int HEIGHT = 700;
    class SimpleTree extends JFrame
    public SimpleTree(JFrame frame, SpringLayout layout)
    DefaultMutableTreeNode top =
    new DefaultMutableTreeNode("The World");
    Container contentPane = frame.getContentPane();
    contentPane.setLayout(layout);
    CreateNodes(top);
    JTree tree = new JTree(top);
    tree.getSelectionModel().setSelectionMode
    (TreeSelectionModel.SINGLE_TREE_SELECTION);
    JScrollPane treeView = new JScrollPane();
    treeView.add(tree);
    treeView.setHorizontalScrollBarPolicy(
    ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    treeView.setVerticalScrollBarPolicy(
    ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
    tree.setVisibleRowCount(5);
    JViewport port = treeView.getViewport();
    port.setMinimumSize(new Dimension(150,150));
    treeView.setMinimumSize(new Dimension(150,160));
    contentPane.add(treeView);
    Spring s = Spring.constant(100,300,800);
    layout.putConstraint(SpringLayout.EAST, treeView, s, SpringLayout.EAST, contentPane);
    layout.putConstraint(SpringLayout.WEST, treeView, s, SpringLayout.WEST, contentPane);
    layout.putConstraint(SpringLayout.NORTH, treeView, s, SpringLayout.NORTH, contentPane);
    layout.putConstraint(SpringLayout.SOUTH, treeView, s, SpringLayout.SOUTH, contentPane);
    treeView.revalidate();
    System.out.println(port.getViewSize());
    System.out.println(treeView.getX());
    System.out.println(treeView.getY());
    }

    Camickr,
    I think you are correct about the paint issue. However, after adding a frame.setVisible(true); command as the last statement in my SimpleTree method, the frame still shows up blank. I do not think that my layout manager is laying out the components. Even after issuing frame.setVisible and frame.show, my tree.getSize() still returns dimensions of 0 by 0. My JTree resides within a JScrollPane, but neither show up in the frame. There is 1 component in my frame and 4 inside of my JScrollPane. The JTree is the only component that I placed inside of the JScrollPane, but I suppose that the getComponentCount() method counted 4 by including all the components that make up a JTree. Anyway, if you have any insight as to why nothing shows up in my JFrame and the components are all sized to be 0 x 0, let me know. My code is below.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.JScrollPane.*;
    import java.awt.Dimension.*;
    import javax.swing.border.*;
    import javax.swing.SpringLayout.*;
    import java.lang.Integer.*;
    public class GUI_Launch
    public static void main(String[] args)
        SpringLayout layout = new SpringLayout();
        JFrame frame = new JFrame();
        frame.setTitle("GUI Demo");
        frame.setSize(WIDTH, HEIGHT);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        SimpleTree tree = new SimpleTree(frame, layout);
    private static final int WIDTH = 700;
    private static final int HEIGHT = 700;
    class SimpleTree extends JFrame
        public SimpleTree(JFrame frame, SpringLayout layout)
            DefaultMutableTreeNode top =
                    new DefaultMutableTreeNode("The World");
            Container contentPane = frame.getContentPane();
            contentPane.setLayout(layout);
            CreateNodes(top);
            JTree tree = new JTree(top);
            tree.getSelectionModel().setSelectionMode
                    (TreeSelectionModel.SINGLE_TREE_SELECTION);
            JScrollPane treeView = new JScrollPane();
            treeView.add(tree);
            treeView.setHorizontalScrollBarPolicy(
            ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            treeView.setVerticalScrollBarPolicy(
            ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
            tree.setVisibleRowCount(5);
            JViewport port = treeView.getViewport();
            port.setMinimumSize(new Dimension(150,150));
            treeView.setMinimumSize(new Dimension(150,160));
            contentPane.add(treeView);
            Spring s = Spring.constant(100,300,500);
            layout.putConstraint(SpringLayout.EAST, treeView, s, SpringLayout.EAST, contentPane);
            layout.putConstraint(SpringLayout.WEST, treeView, s, SpringLayout.WEST, contentPane);
            layout.putConstraint(SpringLayout.NORTH, treeView, s, SpringLayout.NORTH, contentPane);
            layout.putConstraint(SpringLayout.SOUTH, treeView, s, SpringLayout.SOUTH, contentPane);
            frame.setVisible(true);
            frame.show();
            System.out.println(port.getViewSize());
            System.out.println(frame.getComponentCount());
            System.out.println(treeView.getComponentCount());
            System.out.println(tree.getSize());
            System.out.println(treeView.getX());
            System.out.println(treeView.getY());
        private void CreateNodes(DefaultMutableTreeNode top)
            DefaultMutableTreeNode state = null;
            DefaultMutableTreeNode city = null;
            state = new DefaultMutableTreeNode("Oregon");
            city = new DefaultMutableTreeNode("Portland");
            state.add(city);
            city = new DefaultMutableTreeNode("Bend");
            state.add(city);
            city = new DefaultMutableTreeNode("Salem");
            state.add(city);
            top.add(state);
            state = new DefaultMutableTreeNode("Indiana");
            city = new DefaultMutableTreeNode("South Bend");
            state.add(city);
            top.add(state);
            state = new DefaultMutableTreeNode("New York");
            city = new DefaultMutableTreeNode("New York");
            state.add(city);    
            top.add(state);
    }

  • Clarification Regarding swings

    Can you suggest me why this exception is coming in Swings??
    java.lang.ArrayIndexOutOfBoundsException: 1
    at javax.swing.text.BoxView.layoutMajorAxis(Unknown Source)
    at javax.swing.text.BoxView.setSpanOnAxis(Unknown Source)
    at javax.swing.text.BoxView.layout(Unknown Source)
    at javax.swing.text.BoxView.setSize(Unknown Source)
    at javax.swing.text.WrappedPlainView.setSize(Unknown Source)
    at javax.swing.plaf.basic.BasicTextUI$RootView.setSize(Unknown Source)
    at javax.swing.plaf.basic.BasicTextUI.getPreferredSize(Unknown Source)
    at javax.swing.plaf.basic.BasicTextAreaUI.getPreferredSize(Unknown Sourc
    e)
    at javax.swing.JComponent.getPreferredSize(Unknown Source)
    at javax.swing.JTextArea.getPreferredSize(Unknown Source)
    at javax.swing.ScrollPaneLayout.layoutContainer(Unknown Source)
    at java.awt.Container.layout(Unknown Source)
    at java.awt.Container.doLayout(Unknown Source)
    at java.awt.Container.validateTree(Unknown Source)
    at java.awt.Container.validate(Unknown Source)
    at javax.swing.RepaintManager.validateInvalidComponents(Unknown Source)
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknow
    n Source)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at com.deceval.siidj.utilityclasses.ExceptionHandlingEventQueue.dispatch
    Event(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    ERROR - ExceptionHandlingEventQueue.dispatchEvent(?) | com.deceval.siidj.utility
    classes.ExceptionHandlingEventQueue@1082277
    java.lang.ArrayIndexOutOfBoundsException: 1
    at javax.swing.text.BoxView.layoutMajorAxis(Unknown Source)
    at javax.swing.text.BoxView.setSpanOnAxis(Unknown Source)
    at javax.swing.text.BoxView.layout(Unknown Source)
    at javax.swing.text.BoxView.setSize(Unknown Source)
    at javax.swing.text.WrappedPlainView.setSize(Unknown Source)
    at javax.swing.plaf.basic.BasicTextUI$RootView.setSize(Unknown Source)
    at javax.swing.plaf.basic.BasicTextUI.getPreferredSize(Unknown Source)
    at javax.swing.plaf.basic.BasicTextAreaUI.getPreferredSize(Unknown Sourc
    e)
    at javax.swing.JComponent.getPreferredSize(Unknown Source)
    at javax.swing.JTextArea.getPreferredSize(Unknown Source)
    at javax.swing.ScrollPaneLayout.layoutContainer(Unknown Source)
    at java.awt.Container.layout(Unknown Source)
    at java.awt.Container.doLayout(Unknown Source)
    at java.awt.Container.validateTree(Unknown Source)
    at java.awt.Container.validate(Unknown Source)
    at javax.swing.RepaintManager.validateInvalidComponents(Unknown Source)
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknow
    n Source)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at com.deceval.siidj.utilityclasses.ExceptionHandlingEventQueue.dispatch
    Event(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

    Thank you Darryl.Burke for your quick response,
    I am attaching my code.I have done same thinng which you have assested me.But the problems still persist.Code is,.......
    package com.deceval.siidj.siidtareasautomaticas;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.InetAddress;
    import java.net.UnknownHostException;
    import java.rmi.RemoteException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.Timer;
    import java.util.TimerTask;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.SwingConstants;
    import javax.swing.border.CompoundBorder;
    import javax.swing.border.EmptyBorder;
    import javax.swing.border.LineBorder;
    import org.apache.log4j.Logger;
    import com.deceval.siidj.securityentcmd.SecurityEntCmdConstants;
    import com.deceval.siidj.securityinterfaceobjects.NUMEROS_TABLASOBJ;
    import com.deceval.siidj.siidframework.CustomErrorException;
    import com.deceval.siidj.siidframework.FileObj;
    import com.deceval.siidj.siidframework.LOG_TRANSFERENCIAOBJ;
    import com.deceval.siidj.siidframework.ListElement;
    import com.deceval.siidj.siidframework.MailProcesosAutomaticosObj;
    import com.deceval.siidj.siidframework.SIIDExceptionUtil;
    import com.deceval.siidj.siidframework.SIIDFrameworkConstants;
    import com.deceval.siidj.siidframework.ServiceLocator;
    import com.deceval.siidj.siidresults.CmpLeerLogTransferencia_OutputParams;
    import com.deceval.siidj.siidresults.LeerNumeros_1_Tabla_OutputParams;
    import com.deceval.siidj.siidtareasautomaticas_client.ClaseBaseMasivoObj;
    import com.deceval.siidj.siidtareasautomaticas_client.TareasAutomaticasObj;
    import com.deceval.siidj.siidwinutilities.SIIDCommonWin;
    import com.deceval.siidj.siidwinutilities.SIIDWinUtilitiesConstants;
    import com.deceval.siidj.utilityclasses.FechaDomainConverter;
    import com.deceval.siidj.utilityclasses.IntegerConverter;
    import com.deceval.siidj.utilityclasses.MiniFramework;
    import com.deceval.siidj.utilityclasses.SIIDDateField;
    import com.deceval.siidj.utilityclasses.SIIDFileChooser;
    import com.deceval.siidj.utilityclasses.SIIDTextField;
    import com.deceval.siidj.utilityclasses.TextDataConverter;
    import com.gtl.ftoj.framework.DateFormat;
    import com.gtl.ftoj.framework.DateTimeData;
    import com.gtl.ftoj.framework.ForteFile;
    import com.gtl.ftoj.framework.TextData;
    import com.jgoodies.binding.adapter.BasicComponentFactory;
    import com.jgoodies.binding.value.ValueModel;
    import com.jgoodies.forms.builder.PanelBuilder;
    import com.jgoodies.forms.layout.CellConstraints;
    import com.jgoodies.forms.layout.FormLayout;
    * class OperacionBcoRepAutomaticoWin which extends SIIDCommonWin
    * @author GoldStone
    * @version 2.0
    public class OperacionBcoRepAutomaticoWin extends SIIDCommonWin {
         private static final long serialVersionUID = 1L;
         private CellConstraints cc = null;
         private static Logger mLog = Logger
                   .getLogger(OperacionBcoRepAutomaticoWin.class);
         private CTLOperacionBcoRepAutomaticoWin theCt;
         private JTextArea logEnvioTxtTa;
         private TareasAutomaticasObj TareasAutomaticasTIDISSvc;
         private ForteFile LocalFileSystem;
         private JButton btnOcultarBtn;
         private JButton btnBorrarLogBtn;
         private JButton brnGrabarLogBtn;
         private JButton btnTerminarProcesoBtn;
         private JComponent panel;
         private ArrayList<ForteFile> files;
         private Timer timer;
         * constructs a new <OperacionBcoRepAutomaticoWin> object
         public OperacionBcoRepAutomaticoWin() {
              super();
              cc = new CellConstraints();
              theCt = new CTLOperacionBcoRepAutomaticoWin();
              initialize();
              theCt.setHabilitado(false);
              theCt.setContador(60);
              theCt.setRunning(false);
              cargaConfiguracion();
              theCt.setOpcSecuencia(true);
              theCt.setOpcPrimeroSLuegoRs(true);
              theCt.setOpcOrdenGrabacion(false);
              theCt.setOpcSrecibido(true);
              TareasAutomaticasTIDISSvc = TareasAutomaticasObj.getInstance();
              mLog.info("Directorio Local");
              mLog.info(theCt.getDirectorioEntrada());
              mLog.info("Directorio Remoto");
              mLog.info(theCt.getDirectorioRemoto());
              try {
                   theCt.getFechaCambioDdf().setValue(theCt.setCurrentServerSO());
              } catch (RemoteException e) {
                   SIIDExceptionUtil.unwrap(e);
              for (int i = 0; i < theCt.getNumero_replicas(); i++) {
                   ClaseBaseMasivoObj item = new ClaseBaseMasivoObj();
                   theCt.getOpS().add(item);
                   theCt.getOpS().get(i).setTipoDeEstructura(14);
                   theCt.getOpS().get(i).estableceEstructurasAUsar();
              for (int i = 0; i < theCt.getNumero_replicas(); i++) {
                   ClaseBaseMasivoObj item = new ClaseBaseMasivoObj();
                   theCt.getOpR().add(item);
                   theCt.getOpR().get(i).setTipoDeEstructura(15);
                   theCt.getOpR().get(i).estableceEstructurasAUsar();
              window.addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        if (JOptionPane.showConfirmDialog(getInstance(),
                                  screenLanguageCat.getMessageCatalogString("10003038"),
                                  "Question", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                             theCt.setTERMINANDO(true);
                             theCt.setRunning(false);
                             timer.cancel();
                             window.dispose();
                        } else {
                             window.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
              window.setTitle(screenLanguageCat.getMessageCatalogString("10003246"));
         * To initialize the window
         private void initialize() {
              panel = this.buildPanel();
              logEnvioTxtTa.setEditable(false);
              btnOcultarBtn.setToolTipText(screenLanguageCat.getMessageCatalogString("10003041"));
              btnBorrarLogBtn.setToolTipText(screenLanguageCat.getMessageCatalogString("10003042"));
              brnGrabarLogBtn.setToolTipText(screenLanguageCat.getMessageCatalogString("10003043"));
              btnTerminarProcesoBtn.setToolTipText(screenLanguageCat.getMessageCatalogString("100092"));
         * Used to build the components on the TabbedPane
         * @return JComponent
         public JComponent buildPanel() {
              PanelBuilder operacionBursatilGrd = new PanelBuilder(new FormLayout(
                        "fill:pref:grow", "fill:pref:grow"));
              operacionBursatilGrd.add(logEnvioTxtPanel("fill:350dlu:grow",
                        createArea(true, 0, new Dimension(200, 200))), cc.xy(1, 1));
              return operacionBursatilGrd.getPanel();
         * Used to create the TextArea on the JScrollPane
         * @param lineWrap
         * boolean
         * @param columns
         * int
         * @param minimumSize
         * Dimension
         * @return JScrollPane
         private JScrollPane createArea(boolean lineWrap, int columns,
                   Dimension minimumSize) {
              ValueModel logEnvioTxtModel = theCt.getPresentModel().getBufferedModel("logEnvioTxt");
              TextDataConverter logEnvioTxtConv = new TextDataConverter(logEnvioTxtModel);
              logEnvioTxtTa = MiniFramework.getTextArea(logEnvioTxtConv);
              JScrollPane pane = new JScrollPane();
              pane.setViewportView(logEnvioTxtTa);
              pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
              pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
              logEnvioTxtTa.setBorder(new CompoundBorder(new LineBorder(Color.GRAY),
                        new EmptyBorder(1, 3, 1, 1)));
              logEnvioTxtTa.setLineWrap(lineWrap);
              logEnvioTxtTa.setWrapStyleWord(true);
              logEnvioTxtTa.setColumns(columns);
              if (minimumSize != null) {
                   logEnvioTxtTa.setMinimumSize(new Dimension(150, 200));
              return pane;
         * Used to build the components on the logEnvioTxtPanel
         * @param columnSpec
         * String
         * @param area
         * JScrollPane
         * @return JComponent
         private JComponent logEnvioTxtPanel(String columnSpec, JScrollPane area) {
              FormLayout layout = new FormLayout(columnSpec,
                        "pref,pref,pref,fill:150dlu:grow,2dlu,pref");
              PanelBuilder builder = new PanelBuilder(layout);
              builder.setDefaultDialogBorder();
              builder.add(fechaCodigoPlazaPnl(), cc.xy(1, 2));
              builder.add(area, cc.xy(1, 4));
              builder.add(btnOcultarPanel(), cc.xy(1, 6, "center,center"));
              return builder.getPanel();
         * Used to build the components on the fechaCodigoPlazaPnl
         * @return JComponent
         private JComponent fechaCodigoPlazaPnl() {
              PanelBuilder CodigoPlazaGrd = new PanelBuilder(new FormLayout(
                        "pref,pref", "pref"));
              CodigoPlazaGrd.add(fechaCambioGrfPanel(), cc.xy(1, 1, "center,top"));
              CodigoPlazaGrd.add(codigoPlazaGrdPanel(), cc.xy(2, 1));
              return CodigoPlazaGrd.getPanel();
         * Used to add the components on the fechaCambioGrfPanel
         * @return JComponent
         private JComponent fechaCambioGrfPanel() {
              FormLayout formLayout = new FormLayout("2dlu,pref,2dlu,60dlu",
                        "pref,2dlu,pref,2dlu,pref");
              PanelBuilder fechaCambioGrfPnl = new PanelBuilder(formLayout);
              JLabel fechaCambioTxgLbl = MiniFramework.getLabel(screenLanguageCat
                        .getMessageCatalogString("1000166"));
              ValueModel fechaCambioDdfModel = theCt.getPresentModel()
                        .getBufferedModel("fechaCambioDdf");
              FechaDomainConverter fechaCambioDdfConv = new FechaDomainConverter(
                        fechaCambioDdfModel);
              SIIDDateField fechaCambioDdfTf = new SIIDDateField(fechaCambioDdfConv);
              setWidgetState(fechaCambioDdfTf, FS_DISABLED);
              JLabel numero_replicasLbl = MiniFramework.getLabel(screenLanguageCat
                        .getMessageCatalogString("10003044"));
              ValueModel numero_replicasModel = theCt.getPresentModel()
                        .getBufferedModel("numero_replicas");
              IntegerConverter numero_replicasConv = new IntegerConverter(
                        numero_replicasModel);
              SIIDTextField numero_replicasTf = MiniFramework
                        .getNumericTextField(numero_replicasConv);
              numero_replicasTf.setHorizontalAlignment(SwingConstants.RIGHT);
              setWidgetState(numero_replicasTf, FS_DISABLED);
              fechaCambioGrfPnl.add(fechaCambioTxgLbl, cc.xy(2, 1));
              fechaCambioGrfPnl.add(fechaCambioDdfTf, cc.xy(4, 1));
              fechaCambioGrfPnl.add(numero_replicasLbl, cc.xy(2, 3));
              fechaCambioGrfPnl.add(numero_replicasTf, cc.xy(4, 3));
              ValueModel verultimalineaModel = theCt.getPresentModel()
                        .getBufferedModel("verUltimaLinea");
              JCheckBox verultimalineaChb = BasicComponentFactory.createCheckBox(
                        verultimalineaModel, screenLanguageCat
                                  .getMessageCatalogString("10003239"));
              verultimalineaChb.addItemListener(new ItemListener() {
                   public void itemStateChanged(ItemEvent ie) {
                        theCt.getTrigger().triggerCommit();
                        if (theCt.isVerUltimaLinea()) {
                             logEnvioTxtTa.setCaretPosition(logEnvioTxtTa.getText()
                                       .length());
              fechaCambioGrfPnl.add(verultimalineaChb, cc.xyw(2, 5, 3));
              return fechaCambioGrfPnl.getPanel();
         * It adds the components to the panel
         * @return JComponent
         private JComponent codigoPlazaGrdPanel() {
              FormLayout formlayout = new FormLayout("pref", "pref,pref,pref,pref");
              PanelBuilder fechadeProcesoPnl = new PanelBuilder(formlayout);
              ValueModel opcOrdenGrabacionModel = theCt.getPresentModel()
                        .getBufferedModel("opcOrdenGrabacion");
              JCheckBox opcOrdenGrabacionChb = BasicComponentFactory.createCheckBox(
                        opcOrdenGrabacionModel, screenLanguageCat
                                  .getMessageCatalogString("10003247"));
              opcOrdenGrabacionChb.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ae) {
                        theCt.getTrigger().triggerCommit();
                        enviaMensajeCorreo(SIIDFrameworkConstants.EVTBANREP_CAMBIACONFIGURACION,
                                  new TextData("CAMBIA configuraci�n por orden de grabacion modificado, nuevo valor: ")
                                            .concat(theCt.isOpcOrdenGrabacion()));
              ValueModel opcPrimeroSLuegoRsModel = theCt.getPresentModel().getBufferedModel("opcPrimeroSLuegoRs");
              JCheckBox opcPrimeroSLuegoRsChb = BasicComponentFactory.createCheckBox(
                        opcPrimeroSLuegoRsModel, screenLanguageCat
                                  .getMessageCatalogString("10003248"));
              opcPrimeroSLuegoRsChb.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ae) {
                        theCt.getTrigger().triggerCommit();
                        enviaMensajeCorreo(SIIDFrameworkConstants.EVTBANREP_CAMBIACONFIGURACION,
                                  new TextData("CAMBIA configuraci�n primero S luego R modificado, nuevo valor: ")
                                            .concat(theCt.isOpcPrimeroSLuegoRs()));
              ValueModel opcSecuenciaModel = theCt.getPresentModel()
                        .getBufferedModel("opcSecuencia");
              JCheckBox opcSecuenciaChb = BasicComponentFactory.createCheckBox(
                        opcSecuenciaModel, screenLanguageCat
                                  .getMessageCatalogString("10003249"));
              opcSecuenciaChb.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ae) {
                        theCt.getTrigger().triggerCommit();
                        enviaMensajeCorreo(
                                  SIIDFrameworkConstants.EVTBANREP_CAMBIACONFIGURACION,
                                  new TextData(
                                            "CAMBIA configuraci�n por orden de secuencia, nuevo valor:")
                                            .concat(theCt.isOpcSecuencia()));
              ValueModel opcSrecibidoModel = theCt.getPresentModel()
                        .getBufferedModel("opcSrecibido");
              JCheckBox opcSrecibidoChb = BasicComponentFactory.createCheckBox(
                        opcSrecibidoModel, screenLanguageCat
                                  .getMessageCatalogString("10003250"));
              opcSrecibidoChb.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ae) {
                        theCt.getTrigger().triggerCommit();
                        enviaMensajeCorreo(
                                  SIIDFrameworkConstants.EVTBANREP_CAMBIACONFIGURACION,
                                  new TextData(
                                            "CAMBIA configuraci�n esperar S de un E enviado, nuevo valor:")
                                            .concat(theCt.isOpcSrecibido()));
              fechadeProcesoPnl.add(opcOrdenGrabacionChb, cc.xy(1, 1));
              fechadeProcesoPnl.add(opcPrimeroSLuegoRsChb, cc.xy(1, 2));
              fechadeProcesoPnl.add(opcSecuenciaChb, cc.xy(1, 3));
              fechadeProcesoPnl.add(opcSrecibidoChb, cc.xy(1, 4));
              return fechadeProcesoPnl.getPanel();
         * It adds the buttons to the panel
         * @return JComponent
         private JComponent btnOcultarPanel() {
              FormLayout form3 = new FormLayout(
                        "2dlu,pref,2dlu,pref,2dlu,pref,2dlu,pref,2dlu",
                        "3dlu,pref,3dlu");
              PanelBuilder btnOcultarPnl = new PanelBuilder(form3);
              btnOcultarBtn = MiniFramework.getButton(screenLanguageCat
                        .getMessageCatalogString("10003240"));
              btnOcultarBtn.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ae) {
                        window.setVisible(false);
                        close();
              btnBorrarLogBtn = MiniFramework.getButton(screenLanguageCat
                        .getMessageCatalogString("10003241"));
              btnBorrarLogBtn.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ae) {
                        if (theCt.getLogEnvioTxt().getActualSize() == 0) {
                             // continue;
                        borrarLog();
              btnTerminarProcesoBtn = MiniFramework.getButton(screenLanguageCat
                        .getMessageCatalogString("10003242"));
              btnTerminarProcesoBtn.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ae) {
                        if (JOptionPane.showConfirmDialog(getInstance(),
                                  screenLanguageCat.getMessageCatalogString("10003038"),
                                  "Question", JOptionPane.YES_NO_OPTION,
                                  JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
                             theCt.setTERMINANDO(true);
                             theCt.setRunning(false);
                             timer.cancel();
                             window.dispose();
              brnGrabarLogBtn = MiniFramework.getButton(screenLanguageCat
                        .getMessageCatalogString("10003243"));
              brnGrabarLogBtn.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ae) {
                        grabarLog();
              btnTerminarProcesoBtn.setMargin(new Insets(1, 4, 1, 4));
              btnOcultarPnl.add(btnOcultarBtn, cc.xy(2, 2));
              btnOcultarPnl.add(btnBorrarLogBtn, cc.xy(4, 2));
              btnOcultarPnl.add(brnGrabarLogBtn, cc.xy(6, 2));
              btnOcultarPnl.add(btnTerminarProcesoBtn, cc.xy(8, 2));
              return btnOcultarPnl.getPanel();
         * Method addLog
         * @param str
         * Textdata
         public void addLog(TextData str) {
              addLog(str, true, 0);
         * Method addLog
         * @param str
         * TextData
         * @param confecha
         * boolean
         public void addLog(TextData str, boolean confecha) {
              addLog(str, confecha, 0);
         * Method addLog
         * @param str
         * TextData
         * @param confecha
         * boolean
         * @param hilo
         * int
         public void addLog(TextData str, boolean confecha, int hilo) {
              // TODO topline = <logEnvioTxt>.topline ;
              // theCt.setTopline(logEnvioTxtTa.topline);
              if (hilo > 0) {
                   theCt.getLogEnvioTxt().concat("(");
                   theCt.getLogEnvioTxt().concat(hilo);
                   theCt.getLogEnvioTxt().concat(")");
              if (confecha) {
                   theCt.getLogEnvioTxt().concat(theCt.getNow().setCurrent());
                   theCt.getLogEnvioTxt().concat(":");
              theCt.getLogEnvioTxt().concat(str);
              theCt.getLogEnvioTxt().concat(System.getProperty("line.separator"));
              theCt.setLogEnvioTxt(theCt.getLogEnvioTxt());
              //theCt.getPresentModel().setBean(null);
              theCt.getPresentModel().setBean(theCt);
              hastaLaUltimaLinea();
              // EJBHelper ejbHelper = new EJBHelper();
              // Please copy this Helper class to the current directory
              // ejbHelper.publishNews("hastaLaUltimaLinea","");
         * until It completes Line
         public void hastaLaUltimaLinea() {
              if (theCt.isVerUltimaLinea()) {
                   // logEnvioTxtTa.setSelectionStart(logEnvioTxtTa.getText().length());
                   logEnvioTxtTa.setCaretPosition(logEnvioTxtTa.getText().length());
              } else {
                   // logEnvioTxtTa.setCaretPosition(logEnvioTxtTa);
                   // logEnvioTxtTa.setSelectionStart(logEnvioTxtTa.getText().length());
         * To erase LoG
         public void borrarLog() {
              int resp = JOptionPane.showConfirmDialog(getInstance(),
                        screenLanguageCat.getMessageCatalogString("10003039"),
                        "Question", JOptionPane.YES_NO_OPTION);
              if (resp == JOptionPane.YES_OPTION) {
                   theCt.getLogEnvioTxt().clear();
              theCt.getPresentModel().setBean(null);
              theCt.getPresentModel().setBean(theCt);
         * Method getInstance
         * @return <OperacionBcoRepAutomaticoWin>
         public OperacionBcoRepAutomaticoWin getInstance() {
              return this;
         * load Configuration
         public void cargaConfiguracion() {
              theCt.setDirectorioEntrada("c:\\BVC\\entrada");
              theCt.setDirectorioNoProcesados("c:\\BVC\\noprocesados");
              theCt.setDirectorioProcesados("c:\\BVC\\procesados");
              theCt.setDirectorioSalida("c:\\BVC\\salida");
              theCt.setDirectorioTemporal("c:\\BVC\\temporal");
              InetAddress localhost = null;
              try {
                   localhost = InetAddress.getLocalHost();
              } catch (UnknownHostException e) {
                   mLog.info(e.getMessage(), e);
              try {
                   List temp = null;
                   temp = theCt
                             .operacionBcoRepAutomaticoWin_runSql(
                                       theCt.SecurityClientSvc.LoginUser.getUserLogin()
                                                 .trim(), localhost.getHostName()
                                                 .toUpperCase(),
                                       theCt.SecurityClientSvc.LoginUser
                                                 .getUserProfileId().trim());
                   if (temp != null) {
                        if (temp.size() == 1) {
                             Map returnRow = (Map) temp.get(0);
                             theCt.setDirectorioEntrada(String.valueOf(returnRow
                                       .get("carpeta_entrada")));
                             theCt.setDirectorioSalida(String.valueOf(returnRow
                                       .get("carpeta_salida")));
                             theCt.setDirectorioTemporal(String.valueOf(returnRow
                                       .get("carpeta_temporal")));
                             theCt.setDirectorioProcesados(String.valueOf(returnRow
                                       .get("carpeta_procesados")));
                             theCt.setDirectorioNoProcesados(String.valueOf(returnRow
                                       .get("carpeta_no_procesados")));
                             theCt.setNumero_replicas(Integer.parseInt(returnRow.get(
                                       "numero_replicas").toString()));
                             theCt.setHabilitado(true);
              } catch (Exception e) {
                   mLog
                             .info(screenLanguageCat.getMessageCatalogString("10006723"));
                   mLog.info(e.getMessage());
                   JOptionPane.showMessageDialog(getInstance(), new TextData(
                             screenLanguageCat.getMessageCatalogString("1003937")
                                       .concat(e.getMessage())));
                   if (theCt.pAlErrors != null && theCt.pAlErrors.size() > 0) {
                        theCt.pAlErrors.remove(0);
         * the data base the bags
         * @return ArrayList<ListElement>
         public ArrayList<ListElement> cargaDropBolsas() {
              // Jos� Miguel de Priego
              // Agosto 03, 2004
              // Se lee desde la base de datos las bolsas
              ArrayList<NUMEROS_TABLASOBJ> arreglo_bolsas = new ArrayList<NUMEROS_TABLASOBJ>();
              int wnumero_filas_afectadas = 0;
              ArrayList<NUMEROS_TABLASOBJ> arreglo_numeros = null;
              try {
                   LeerNumeros_1_Tabla_OutputParams obj = null;
                   obj = theCt.listadeNumeros1TablaSO(46, wnumero_filas_afectadas);
                   arreglo_numeros = obj.retVal;
                   wnumero_filas_afectadas = obj.prows;
              } catch (RemoteException e) {
                   SIIDExceptionUtil.unwrap(e);
              ArrayList<ListElement> dropBolsas = null;
              if (arreglo_numeros != null) {
                   NUMEROS_TABLASOBJ i = new NUMEROS_TABLASOBJ();
                   int size = 0;
                   if (arreglo_numeros != null) {
                        size = arreglo_numeros.size();
                   for (int j = 0; j < size; j++) {
                        i = (NUMEROS_TABLASOBJ) arreglo_numeros.get(j);
                        // si es 1 es bolsa, o tiene como mecanismo bursatil
                        if (((i.getIndicador_4() == 1) && ("OK".equals(i
                                  .getIndicador_1())))
                                  || (i.getCodigo_numerico() == 0)) {
                             arreglo_bolsas.add(i);
                   dropBolsas = theCt.getToolSO().deNumParametrosAListElement(
                             arreglo_bolsas);
                   if (dropBolsas != null) {
                        for (ListElement each : dropBolsas) {
                             // task.part.logMgr.PutLine( TextData("-> ").concat(
                             // each.integerValue).concat( " -> ").concat( each.textvalue
                   arreglo_bolsas = null;
                   arreglo_numeros = null;
              return dropBolsas;
         * It consults Encripcion Parameter
         public void consultaParametroEncripcion() {
              // MFBI-JUNIO-4-1-2:2005/06/21 Metodo nuevo
              try {
                   theCt.setParametroEncripcion("S");
                   theCt.setParametroEncripcion(theCt.operacionBcoRepAutomaticoWin_runSql1());
              } catch (Exception e) {
                   addLog(new TextData(screenLanguageCat.getMessageCatalogString("10006724")));
                   addLog(new TextData(e.getMessage()));
                   if (theCt.pAlErrors != null && theCt.pAlErrors.size() > 0) {
                        theCt.pAlErrors.remove(0);
         * Method copy
         * @param proceso
         * String
         * @param NombreArchivo
         * String
         * @param replica
         * String
         * @return String
         public String copiar2(String proceso, String NombreArchivo, int replica) {
              // Jose Miguel de Priego Julio 09, 2004
              // Se agrega la variable es encriptada para
              // manejo de archivos encriptados
              boolean esEncriptada = false;
              TextData nombreDirectorioArchivoDdf = new TextData(NombreArchivo);
              if (nombreDirectorioArchivoDdf.moveToString(
                        SecurityEntCmdConstants.FILE_SECURE_EXTENSION, true)) {
                   if (nombreDirectorioArchivoDdf.getOffset() == nombreDirectorioArchivoDdf
                             .getActualSize()) {
                        esEncriptada = true;
              nombreDirectorioArchivoDdf.setOffset(0);
              try {
                   if (!esEncriptada) {
                        ejecutarCopia(NombreArchivo, replica);
                   } else {
                        String dir = theCt.defineDirectorioRemotoSO();
                        ForteFile f = new ForteFile();
                        f.setLocalName(nombreDirectorioArchivoDdf.getValue());
                        TextData fn = f.getLocalName();
                        if (fn.moveToLastChar("/")) {
                             fn.cutRange(0, fn.getOffset() + 1);
                        //TODO for verifying impact Prashanth 01/08/2008
                        return SIIDWinUtilitiesConstants.Empty_String;/*ServiceLocator.getInstance().getEntCmdServicesSO().moveDecriptedFile(proceso,
                                  fn.getValue(), dir);*/// temp
              } catch (Exception e) {
                   // TODO if(e.getreasonCode == OS_FE_FILEEXISTENCE ){
                   addLog(new TextData("Error Archivo no existe .."), true, replica);
                   addLog(new TextData(e.getMessage()), true, replica);
                   if (theCt.pAlErrors != null && theCt.pAlErrors.size() > 0) {
                        theCt.pAlErrors.remove(0);
              return SIIDWinUtilitiesConstants.Empty_String;
         * To display the current window
         public void display() {
              theCt.setTERMINANDO(false);
              // Recuperacion archivos E
              theCt.setProcesoA(false);
              // Envio de Archios S, R
              theCt.setProcesoB(false);
              theCt.setRunning(false);
              int delay = 0;
              int period = 1000;
              timer = new Timer();
              timer.scheduleAtFixedRate(new TimerTask() {
                   public void run() {
                        if (theCt.getContador() % 30 == 0) {
                             theCt.setContador(0);
                        // Cada 2 minutos va el proceso de recuperacion de archivos E
                        // Cada 30 segundos va el proceso de envio de archivos R,S
                        if (theCt.getContador() == 0) {
                             if (!theCt.isProcesoA()) {
                                  new Thread(){
                                       public void run() {
                                            recuperaOtrosArchivos(1);
                                  }.start();
                        if (theCt.getContador() % 10 == 0){
                             theCt.getPresentModel().setBean(null);
                             theCt.getPresentModel().setBean(theCt);
                        if (theCt.getContador() % 30 == 15) {
                             if (!theCt.isProcesoB()) {     
                                  new Thread(){
                                       public void run() {
                                            preprocesa(1);
                                  }.start();
                        theCt.setContador(theCt.getContador() + 1);
              }, delay, period);
              open(panel);
         * To execute Copy
         * @param pArchivo
         * String
         * @param replica
         * int
         * @return boolean
         public boolean ejecutarCopia(String pArchivo, int replica) {
              LocalFileSystem = new ForteFile();
              // RemotoFileSystem : FileSystem = ServidorTareaSO.CreaProxy();
              // localFileSystem.SetRemoteFS(remotoFileSystem);
              // remotoFileSystem.SetRemoteFS(localFileSystem);
              TextData remoteFile = null;
              try {
                   remoteFile = theCt.getServidorTarea().estableceDirectorio(
                             SIIDFrameworkConstants.DIR_APLIC_CLIENTE,
                             theCt.SecurityClientSvc.LoginUser.getUserPath(),
                             theCt.pAppContext, theCt.pAlErrors);
              } catch (RemoteException e) {
                   SIIDExceptionUtil.unwrap(e);
              if (remoteFile != null) {
                   theCt.setDirectorioRemoto(remoteFile.getValue());
              TextData directorioRemoto = null;
              try {
                   directorioRemoto = new TextData(theCt.defineDirectorioRemotoSO());
              } catch (RemoteException e1) {
                   SIIDExceptionUtil.unwrap(e1);
              int NroCar = theCt.getToolSO().lenStr(directorioRemoto.getValue());
              NroCar = NroCar - 1;
              directorioRemoto = new TextData(theCt.getToolSO().subStr(
                        directorioRemoto.getValue(), 1, NroCar));
              // localFileSystem.SetLocalDir( theCt.getDirectorioEntrada() );
              // localFileSystem.SetRemoteDir( directorioRemoto );
              ArrayList<TextData> ListaArchivos = new ArrayList<TextData>();
              try {
                   while (true) {
                        ListaArchivos.clear();
                        ListaArchivos.add(new TextData(pArchivo));
                        File srcPath = new File(LocalFileSystem.getPortableName(true,false).getValue());
                        try {
                             copyFile(srcPath);
                        } catch (IOException e) {
                             mLog.error(e.getMessage(), e);
                        LocalFileSystem = null;
                        // RemotoFileSystem = null;
                        ListaArchivos = null;
                        return true;
              } catch (Exception e) {
                   addLog(new TextData("*EjecutarCopia: ").concat(e.getMessage()),
                             true, replica);
                   if (theCt.pAlErrors != null && theCt.pAlErrors.size() > 0) {
                        theCt.pAlErrors.remove(0);
                   // // return false;
                   nsegundos(5);
              return true;
         * It establishes the directories on who he worked
         * @param srcPath
         * File
         * @throws IOException
         @SuppressWarnings( { "unused", "unchecked" })
         public void copyFile(File srcPath) throws IOException {
              ArrayList fileList = new ArrayList();
              InputStream in = null;
              try {
                   if (srcPath.isDirectory()) {
                        String[] files = srcPath.list();
                        for (int i = 0; i < files.length; i++) {
                             FileObj fObj = new FileObj();
                             File pFile = new File(srcPath, files);
                             in = new FileInputStream(pFile);
                             int size = (int) pFile.length();
                             byte[] buf = new byte[size];
                             int len = 0;
                             while ((len = in.read(buf)) > 0) {
                                  fObj.setName(files[i]);
                                  fObj.setContent(buf);
                                  fileList.add(fObj);
                             in.close();
                        theCt.pushFiles(fileList, theCt.getDirectorioRemoto());
                   } else {
                        if (!srcPath.exists()) {
                             mLog.info("File or directory does not exist.");
                        if (srcPath.isFile()) {
                             in = new FileInputStream(srcPath);
                             int size = (int) srcPath.length();
                             byte[] buf = new byte[size];
                             int len;
                             FileObj fObj = new FileObj();
                             while ((len = in.read(buf)) > 0) {
                                  fObj.setName(srcPath.getName());
                                  fObj.setContent(buf);
                                  fileList.add(fObj);
                             in.close();
                             theCt.pushFiles(fileList, theCt.getDirectorioRemoto());
              } catch (Exception e) {
                   mLog.error(e);
              } finally {
                   in.close();
         * It sends Message Mail
         * @param evento
         * int
         * @param obs
         * TextData
         public void enviaMensajeCorreo(int evento, TextData obs) {
              try {
                   if (theCt.getEnvios() == null || theCt.getEnvios().size() == 0) {
                        theCt.setEnvios(TareasAutomaticasTIDISSvc.a_ObtieneParametrosCorreo(2, theCt.pAppContext,theCt.pAlErrors));
              } catch (Exception e) {
                   addLog(new TextData("enviamensajecorreo(1): ").concat(e.getMessage()));
                   if (theCt.pAlErrors != null && theCt.pAlErrors.size() > 0) {
                        theCt.pAlErrors.remove(0);
                   theCt.setEnvios(null);
              if (theCt.getEnvios() == null) {
                   return;
              MailProcesosAutomaticosObj each = null;
              int size = 0;
              if (theCt.getEnvios() != null) {
                   size = theCt.getEnvios().size();
              for (int i = 0; i < size; i++) {
                   each = (MailProcesosAutomaticosObj) theCt.getEnvios().get(i);
                   if ((each.getEstado() == 1) && (each.getEvento() == evento)) {
                        try {
                             each.setMensaje(obs.getTextValue().getValue());
                             TareasAutomaticasTIDISSvc.a_EnviaMensajeCorreo(each);
                        } catch (Exception e) {
                             addLog(new TextData("enviamensajecorreo(2): ").concat(e
                                       .getMessage()));
                             if (theCt.pAlErrors != null && theCt.pAlErrors.size

  • Swing and Jar

    Hi!
    I have a project with a GUI in it. The GUI includes a panel with GridLayout with a grid of labels. When I run the program through my IDE (i'm using Eclipse), it works fine but when I pack it up into a .jar file and run the .jar file the grid simply does not appear.
    Does anyone have any ideas to how I can solve this?
    Regards,
    Krt_malta

    I do have quite a few import statements: These are what I have in my package:
    import java.util.Random;
    import java.util.Scanner;
    import java.util.ArrayList;
    import java.awt.Toolkit;
    import java.awt.BorderLayout;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import java.awt.GridBagLayout;
    import java.awt.GridBagConstraints;
    import java.awt.Rectangle;
    import javax.swing.BoxLayout;
    import javax.swing.JTextArea;
    import javax.swing.JLabel;
    import javax.swing.JButton;
    import java.awt.FlowLayout;
    import java.awt.Insets;
    import javax.swing.BorderFactory;
    import javax.swing.border.EtchedBorder;
    import java.awt.CardLayout;
    import java.awt.GridLayout;
    import java.awt.Point;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.awt.Font;
    import javax.swing.JScrollPane;
    import java.awt.event.KeyEvent;
    import javax.swing.AbstractAction;
    import java.awt.event.ActionEvent;
    import java.util.ArrayList;
    import javax.swing.JOptionPane;
    As far as I know they are all in the JRE.

  • How to prevent displaying outer rectangle of JscrollPane

    HI All,
    I want prevent the displaying JSrollPane outer rectanlge means no outer rectangle formed JSrollPane should be displayed
    below is the code, if the code is run then Rectagle will appear which is title fitted to JScrollPane.
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Rectangle;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    public class Sample extends JFrame
         private static final long serialVersionUID = 1L;
         public Sample()
              Dimension size = new Dimension(
                   150, 150);
              Dimension FRAME_SIZE = new Dimension(
                   700, 500);
              setLocation(size.width, size.height);
              setSize(FRAME_SIZE);
              setBackground(Color.WHITE);
              setTitle("JFrame ");
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JPanel panel = new JPanel();
              JScrollPane sp = new JScrollPane(
                   panel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                   JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
              sp.setBounds(new Rectangle(
                   10, 10, 400, 400));
              this.setLayout(null);
              super.getContentPane().add(sp);
         public static void main(String[] args)
              JFrame frame = new Sample();
              frame.setVisible(true);
    }any helps arround this will deeply appreciated.
    Thanks
    Dorairaj M

    Yes I realized about the solution
    by setting empty border (BorderFactory.createEmptyBorder())
    Thanks
    Dorairaj M

  • Java Swing application problem in Windows vista

    When we execute the Swing application in windows vista environment.
    The look and feel of the swing components are displayed improperly.
    Do we need to put any specific look and feel for windows vista environment or any specific hardware configuration is required to setup windows vista environment.
    Please give some inputs to solve the problem.
    We have tried with the following sample code to run in windows vista.
    * Vista.java
    * Created on December 5, 2006, 5:39 PM
    public class Vista extends javax.swing.JFrame {
    /** Creates new form Vista */
    public Vista() {
    initComponents();
    pack();
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
    jButton1 = new javax.swing.JButton();
    jToggleButton1 = new javax.swing.JToggleButton();
    jPanel1 = new javax.swing.JPanel();
    jCheckBox1 = new javax.swing.JCheckBox();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();
    jTextField1 = new javax.swing.JTextField();
    getContentPane().setLayout(null);
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jButton1.setText("Button 1");
    getContentPane().add(jButton1);
    jButton1.setBounds(20, 20, 170, 30);
    jToggleButton1.setText("Togle btn");
    getContentPane().add(jToggleButton1);
    jToggleButton1.setBounds(100, 80, 90, 20);
    jPanel1.setLayout(null);
    jCheckBox1.setText("jCheckBox1");
    jCheckBox1.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
    jCheckBox1.setMargin(new java.awt.Insets(0, 0, 0, 0));
    jPanel1.add(jCheckBox1);
    jCheckBox1.setBounds(10, 40, 130, 13);
    getContentPane().add(jPanel1);
    jPanel1.setBounds(10, 150, 200, 130);
    jTextArea1.setColumns(20);
    jTextArea1.setRows(5);
    jScrollPane1.setViewportView(jTextArea1);
    getContentPane().add(jScrollPane1);
    jScrollPane1.setBounds(210, 150, 164, 94);
    jTextField1.setText("jTextField1");
    getContentPane().add(jTextField1);
    jTextField1.setBounds(240, 30, 140, 30);
    pack();
    }// </editor-fold>//GEN-END:initComponents
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new Vista().setVisible(true);
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JToggleButton jToggleButton1;
    // End of variables declaration//GEN-END:variables
    }

    When we execute the Swing application in windows
    vista environment.
    The look and feel of the swing components are
    displayed improperly.Improperly means what? You must be aware that Vista's native L&F certainly isn't supported yet.

  • JTable, JScrollPane, and JinternalFrame problems.

    I have this internal frame in my application that has a scrollpane and table in it. Some how it won't let me selelct anything in the table. Also it scrolls really weird. There's a lot of chopping going on. Here's my code for the internal frame:
    public class BCDEObjectWindow extends javax.swing.JInternalFrame{
        private Vector bcdeObjects = new Vector();
        private DefaultTableModel tModel;
        public BCDEObjectWindow(JavaDrawApp p) {
            initComponents();
            this.setMaximizable(false);
            this.setClosable(false);
            this.setIconifiable(true);
            this.setDoubleBuffered(true);
            objectTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
            listScrollPane.setColumnHeaderView(new ObjectWindowHeader());
            pack();
            this.setVisible(true);
            parent = p;
            getAllBCDEFigures();
            setPopupMenu();
            tModel = (DefaultTableModel) objectTable.getModel();
            objectTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        public void getAllBCDEFigures() {
            bcdeObjects.removeAllElements();
            int i;
            for (i = 0; i < bcdeObjects.size(); i++) {
                tModel.removeRow(0);
        public void addBCDEFigure(BCDEFigure b) {
            bcdeObjects.add(b);
            tModel.addRow(new Object[]{b.BCDEName, "incomplete"});
        public void changeLabelName(BCDEFigure b) {
            if (bcdeObjects.contains(b)) {
                int index = bcdeObjects.indexOf(b);
                tModel.removeRow(index);
                tModel.insertRow(index, new Object[]{b.BCDEName, "incomplete"});
        public void removeBCDEFigure(BCDEFigure b) {
            int index = 0;
            if (bcdeObjects.contains(b)) {
                index = bcdeObjects.indexOf(b);
                bcdeObjects.remove(b);
                tModel.removeRow(index);
        public void removeAllBCDEFigures(){
            int i;
            for (i = 0; i < bcdeObjects.size(); i++) {
                tModel.removeRow(0);
            bcdeObjects.removeAllElements();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
        private void initComponents() {
            jPanel1 = new javax.swing.JPanel();
            listScrollPane = new javax.swing.JScrollPane();
            objectTable = new javax.swing.JTable();
            getContentPane().setLayout(new java.awt.FlowLayout());
            setBackground(new java.awt.Color(255, 255, 255));
            setIconifiable(true);
            setTitle("BCDE Objects");
            listScrollPane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
            listScrollPane.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
            listScrollPane.setPreferredSize(new java.awt.Dimension(250, 150));
            objectTable.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                new String [] {
                    "Name", "Status"
                boolean[] canEdit = new boolean [] {
                    true, false
                public boolean isCellEditable(int rowIndex, int columnIndex) {
                    return canEdit [columnIndex];
            objectTable.setColumnSelectionAllowed(true);
            listScrollPane.setViewportView(objectTable);
            jPanel1.add(listScrollPane);
            getContentPane().add(jPanel1);
            pack();
        }// </editor-fold>
        // Variables declaration - do not modify
        private javax.swing.JPanel jPanel1;
        private javax.swing.JScrollPane listScrollPane;
        private javax.swing.JTable objectTable;
        // End of variables declaration
    }and this is how i create the object in my JFrame:
    bcdeOW = new BCDEObjectWindow(this);
            bcdeOW.setLocation(400, 0);
            if (getDesktop() instanceof JDesktopPane) {
                ((JDesktopPane)getDesktop()).setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
                ((JDesktopPane)getDesktop()).add(bcdeOW, JLayeredPane.PALETTE_LAYER);
            } else
                getDesktop().add(bcdeOW);Any help would be great. Thanks a lot.

    Rajb1 wrote:
    to get the table name to appear
    create a scollpane and put the table in the scrollpane and then add the the scollpane to the component:
    //declare
    scrollpane x;
    //body code
    scrollpane x - new scrollpane();
    table y = new table();
    getContentPane().add(x(y));What language is this in, the lambda calculus -- add(x(y))!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  • Trying to scroll a JComponent with JScrollPane but can't do it. :(

    Hi, what im trying to do seems to be simple but I gave up after trying the whole day and I beg you guys help.
    I created a JComponent that is my map ( the map consists only in squared cells ). but the map might be too big for the screen, so I want to be able to scroll it. If the map is smaller than the screen,
    everything works perfect, i just add the map to the frame container and it shows perfect. But if I add the map to the ScrollPane and them add the ScrollPane to the container, it doesnt work.
    below is the code for both classes Map and the MainWindow. Thanks in advance
    package main;
    import java.awt.Color;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowStateListener;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JViewport;
    public class MainWindow implements WindowStateListener {
         private JFrame frame;
         private static MainWindow instance = null;
         private MenuBar menu;
         public Map map = new Map();
         public JScrollPane Scroller =
              new JScrollPane( map,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS );
         public JViewport viewport = new JViewport();
         private MainWindow(int width, int height) {
              frame = new JFrame("Editor de Cen�rios v1.0");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(width,height);
              frame.setVisible(true);
              menu = MenuBar.createMenuBar();
              JFrame.setDefaultLookAndFeelDecorated(false);
              frame.setJMenuBar(menu.create());
              frame.setBackground(Color.WHITE);
              frame.getContentPane().setBackground(Color.WHITE);
                                    // HERE IS THE PROBLEM, THIS DOESNT WORKS   <---------------------------------------------------------------------------------------
              frame.getContentPane().add(Scroller);
              frame.addWindowStateListener(this);
    public static MainWindow createMainWindow(int width, int height)
         if(instance == null)
              instance = new MainWindow(width,height);
              return instance;               
         else
              return instance;
    public static MainWindow returnMainWindow()
         return instance;
    public static void main(String[] args) {
         MainWindow mWindow = createMainWindow(800,600);
    public JFrame getFrame() {
         return frame;
    public Map getMap(){
         return map;
    @Override
    public void windowStateChanged(WindowEvent arg0) {
         map.repaint();
    package main;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import javax.swing.JComponent;
    import javax.swing.Scrollable;
    public class Map extends JComponent  implements Scrollable{
         private Cell [] mapCells;
         private String mapPixels;
         private String mapAltura;
         private String mapLargura;
         public void createMap(String pixels , String altura, String largura)
              mapPixels = pixels;
              mapAltura = altura;
              mapLargura = largura;
              int cells = Integer.parseInt(altura) * Integer.parseInt(largura);
              mapCells = new Cell[cells];
              //MainWindow.returnMainWindow().getFrame().getContentPane().add(this);
              Graphics2D grafico = (Graphics2D)getGraphics();
              for(int i=0, horiz = 0 , vert = 0; i < mapCells.length; i++)
                   mapCells[i] = new Cell( horiz, vert,Integer.parseInt(mapPixels));
                   MainWindow.returnMainWindow().getFrame().getContentPane().add(mapCells);
                   grafico.draw(mapCells[i].r);
                   horiz = horiz + Integer.parseInt(mapPixels);
                   if(horiz == Integer.parseInt(mapLargura)*Integer.parseInt(mapPixels))
                        horiz = 0;
                        vert = vert + Integer.parseInt(mapPixels);
              repaint();
         @Override
         protected void paintComponent(Graphics g) {
              super.paintComponent(g);
              System.out.println("entrou");
              Graphics2D g2d = (Graphics2D)g;
              if(mapCells !=null)
                   for(int i=0, horiz = 0 , vert = 0; i < mapCells.length; i++)
                        g2d.draw(mapCells[i].r);
                        horiz = horiz + Integer.parseInt(mapPixels);
                        if(horiz == Integer.parseInt(mapLargura)*Integer.parseInt(mapPixels))
                             horiz = 0;
                             vert = vert + Integer.parseInt(mapPixels);
         @Override
         public Dimension getPreferredScrollableViewportSize() {
              return super.getPreferredSize();
         @Override
         public int getScrollableBlockIncrement(Rectangle visibleRect,
                   int orientation, int direction) {
              // TODO Auto-generated method stub
              return 5;
         @Override
         public boolean getScrollableTracksViewportHeight() {
              // TODO Auto-generated method stub
              return false;
         @Override
         public boolean getScrollableTracksViewportWidth() {
              // TODO Auto-generated method stub
              return false;
         @Override
         public int getScrollableUnitIncrement(Rectangle visibleRect,
                   int orientation, int direction) {
              // TODO Auto-generated method stub
              return 5;

    Im so sorry Darryl here are the other 3 classes
    package main;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.filechooser.FileNameExtensionFilter;
    public class MenuActions {
         public void newMap(){
              final JTextField pixels = new JTextField(10);
              final JTextField hCells = new JTextField(10);
              final JTextField wCells = new JTextField(10);
              JButton btnOk = new JButton("OK");
              final JFrame frame = new JFrame("Escolher dimens�es do mapa");
              frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(),BoxLayout.Y_AXIS));
              btnOk.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
              String txtPixels = pixels.getText();
              String hTxtCells = hCells.getText();
              String wTxtCells = wCells.getText();
              frame.dispose();
              MainWindow.returnMainWindow().map.createMap(txtPixels,hTxtCells,wTxtCells);         
              frame.getContentPane().add(new JLabel("N�mero de pixels em cada c�lula:"));
              frame.getContentPane().add(pixels);
              frame.getContentPane().add(new JLabel("Altura do mapa (em c�lulas):"));
              frame.getContentPane().add(hCells);
              frame.getContentPane().add(new JLabel("Largura do mapa (em c�lulas):"));
              frame.getContentPane().add(wCells);
              frame.getContentPane().add(btnOk);
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setSize(300, 165);
              frame.setResizable(false);
             frame.setVisible(true);
         public Map openMap (){
              //Abre somente arquivos XML
              JFileChooser fc = new JFileChooser();
              FileNameExtensionFilter filter = new FileNameExtensionFilter("XML file", "xml" );
              fc.addChoosableFileFilter(filter);
              fc.showOpenDialog(MainWindow.returnMainWindow().getFrame());
              //TO DO: manipular o mapa aberto
              return new Map();          
         public void save(){
         public void saveAs(){
              //Abre somente arquivos XML
              JFileChooser fc = new JFileChooser();
              FileNameExtensionFilter filter = new FileNameExtensionFilter("XML file", "xml" );
              fc.addChoosableFileFilter(filter);
              fc.showSaveDialog(MainWindow.returnMainWindow().getFrame());
              //TO DO: Salvar o mapa aberto
         public void exit(){
              System.exit(0);          
         public void copy(){
         public void paste(){
    package main;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.KeyStroke;
    public class MenuBar implements ActionListener{
         private JMenuBar menuBar;
         private final Color color = new Color(250,255,245);
         private String []menuNames = {"Arquivo","Editar"};
         private JMenu []menus = new JMenu[menuNames.length];
         private String []arquivoMenuItemNames = {"Novo","Abrir", "Salvar","Salvar Como...","Sair" };
         private KeyStroke []arquivoMenuItemHotkeys = {KeyStroke.getKeyStroke(KeyEvent.VK_N,ActionEvent.CTRL_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_A,ActionEvent.CTRL_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_S,ActionEvent.CTRL_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_S,ActionEvent.SHIFT_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_F4,ActionEvent.ALT_MASK)};
         private JMenuItem []arquivoMenuItens = new JMenuItem[arquivoMenuItemNames.length];
         private String []editarMenuItemNames = {"Copiar","Colar"};
         private KeyStroke []editarMenuItemHotKeys = {KeyStroke.getKeyStroke(KeyEvent.VK_C,ActionEvent.CTRL_MASK),
                                                                 KeyStroke.getKeyStroke(KeyEvent.VK_V,ActionEvent.CTRL_MASK)};
         private JMenuItem[]editarMenuItens = new JMenuItem[editarMenuItemNames.length];
         private static MenuBar instance = null;
         public JMenuItem lastAction;
         private MenuBar()
         public static MenuBar createMenuBar()
              if(instance == null)
                   instance = new MenuBar();
                   return instance;                    
              else
                   return instance;
         public JMenuBar create()
              //cria a barra de menu
              menuBar = new JMenuBar();
              //adiciona items a barra de menu
              for(int i=0; i < menuNames.length ; i++)
                   menus[i] = new JMenu(menuNames);
                   menuBar.add(menus[i]);
              //seta a hotkey da barra como F10
              menus[0].setMnemonic(KeyEvent.VK_F10);
              //adiciona items ao menu arquivo
              for(int i=0; i < arquivoMenuItemNames.length ; i++)
                   arquivoMenuItens[i] = new JMenuItem(arquivoMenuItemNames[i]);
                   arquivoMenuItens[i].setAccelerator(arquivoMenuItemHotkeys[i]);
                   menus[0].add(arquivoMenuItens[i]);
                   arquivoMenuItens[i].setBackground(color);
                   arquivoMenuItens[i].addActionListener(this);
              //adiciona items ao menu editar
              for(int i=0; i < editarMenuItemNames.length ; i++)
                   editarMenuItens[i] = new JMenuItem(editarMenuItemNames[i]);
                   editarMenuItens[i].setAccelerator(editarMenuItemHotKeys[i]);
                   menus[1].add(editarMenuItens[i]);
                   editarMenuItens[i].setBackground(color);
                   editarMenuItens[i].addActionListener(this);
              menuBar.setBackground(color);
              return menuBar;                    
         @Override
         public void actionPerformed(ActionEvent e) {
              lastAction = (JMenuItem) e.getSource();
              MenuActions action = new MenuActions();
              if(lastAction.getText().equals("Novo"))
                   action.newMap();
              else if(lastAction.getText().equals("Abrir"))
                   action.openMap();
              else if(lastAction.getText().equals("Salvar"))
                   action.save();               
              else if(lastAction.getText().equals("Salvar Como..."))
                   action.saveAs();               
              else if(lastAction.getText().equals("Sair"))
                   action.exit();               
              else if(lastAction.getText().equals("Copiar"))
                   action.copy();               
              else if(lastAction.getText().equals("Colar"))
                   action.paste();               
    package main;
    import java.awt.geom.Rectangle2D;
    import javax.swing.JComponent;
    public class Cell extends JComponent{
         public float presSub = 0;
         public double errPressInfer = 0.02;
         public double errPressSup = 0.02;
         public float profundidade = 1;
         public Rectangle2D r ;
         public Cell(double x, double y, double pixel)
              r = new Rectangle2D.Double(x,y,pixel,pixel);          
    Edited by: xnunes on May 3, 2008 6:26 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • JAWS does not always read  Swing menus

    I have come across a problem that involves JAWS 4.51 and Java menus in Internet Explorer.
    I have a Java application that has a JMenuBar. The menu bar contains several JMenus that in turn contain several JMenuItems.
    When navigating through a menu, JAWS reads every JMenuItem. However, once a disabled JMenuItem is reached, JAWS no longer reads the JMenuItems below the disabled one in the open JMenu.
    The problem occurs only in Internet Explorer on "plain" menu items that follow a disabled menu item. The problem does not affect "complex" menu items, such as those that open sub menus.
    I can only reproduce this problem in Internet Explorer 6. Netscape Communicator 7, Web Start clients and a command line launch do not suffer from this problem. Also, JAWS 4.02 is fine as well; only 4.51 has this problem.
    Attached at the end is a sample application that recreates the issue. You'll notice in the sample application that JAWS will not read "A check box menu item" and "Another one" while it will read "A submenu."
    Does anyone have a solution to this? Thanks a lot!
    Sample application:
    ======================================================
    Note: The code below is a modification of the Sun menu tutorial found at http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html
    middle.gif can be downloaded from http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/images/middle.gif
    MenuLookDemoApplet.java:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JCheckBoxMenuItem;
    import javax.swing.JRadioButtonMenuItem;
    import javax.swing.ButtonGroup;
    import javax.swing.JMenuBar;
    import javax.swing.KeyStroke;
    import javax.swing.ImageIcon;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.JApplet;
    /* MenuLookDemoApplet.java is a 1.4 application that requires images/middle.gif. */
    * This class exists solely to show you what menus look like.
    * It has no menu-related event handling.
    public class MenuLookDemoApplet extends JApplet {
        JTextArea output;
        JScrollPane scrollPane;
        public JMenuBar createMenuBar() {
            JMenuBar menuBar;
            JMenu menu, submenu;
            JMenuItem menuItem;
            JRadioButtonMenuItem rbMenuItem;
            JCheckBoxMenuItem cbMenuItem;
            //Create the menu bar.
            menuBar = new JMenuBar();
            //Build the first menu.
            menu = new JMenu("A Menu");
            menu.setMnemonic(KeyEvent.VK_A);
            menu.getAccessibleContext().setAccessibleDescription(
                    "The only menu in this program that has menu items");
            menuBar.add(menu);
            //a group of JMenuItems
            menuItem = new JMenuItem("A text-only menu item",
                                     KeyEvent.VK_T);
            //menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
            menuItem.setAccelerator(KeyStroke.getKeyStroke(
                    KeyEvent.VK_1, ActionEvent.ALT_MASK));
            menuItem.getAccessibleContext().setAccessibleDescription(
                    "This doesn't really do anything");
            menu.add(menuItem);
            ImageIcon icon = createImageIcon("images/middle.gif");
            menuItem = new JMenuItem("Both text and icon", icon);
            menuItem.setMnemonic(KeyEvent.VK_B);
            menu.add(menuItem);
            menuItem = new JMenuItem(icon);
            menuItem.setMnemonic(KeyEvent.VK_D);
            menu.add(menuItem);
            //a group of radio button menu items
            menu.addSeparator();
            ButtonGroup group = new ButtonGroup();
            rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
            rbMenuItem.setSelected(true);
            rbMenuItem.setMnemonic(KeyEvent.VK_R);
            group.add(rbMenuItem);
            menu.add(rbMenuItem);
            rbMenuItem = new JRadioButtonMenuItem("Another one");
            rbMenuItem.setMnemonic(KeyEvent.VK_O);
            group.add(rbMenuItem);
            menu.add(rbMenuItem);
            rbMenuItem.setEnabled(false);   //@dpb
            //a group of check box menu items
            menu.addSeparator();
            cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
            cbMenuItem.setMnemonic(KeyEvent.VK_C);
            menu.add(cbMenuItem);
            cbMenuItem = new JCheckBoxMenuItem("Another one");
            cbMenuItem.setMnemonic(KeyEvent.VK_H);
            menu.add(cbMenuItem);
            //a submenu
            menu.addSeparator();
            submenu = new JMenu("A submenu");
            submenu.setMnemonic(KeyEvent.VK_S);
            menuItem = new JMenuItem("An item in the submenu");
            menuItem.setAccelerator(KeyStroke.getKeyStroke(
                    KeyEvent.VK_2, ActionEvent.ALT_MASK));
            submenu.add(menuItem);
            menuItem = new JMenuItem("Another item");
            submenu.add(menuItem);
            menu.add(submenu);
            //Build second menu in the menu bar.
            menu = new JMenu("Another Menu");
            menu.setMnemonic(KeyEvent.VK_N);
            menu.getAccessibleContext().setAccessibleDescription(
                    "This menu does nothing");
            menuBar.add(menu);
            return menuBar;
        public Container createContentPane() {
            //Create the content-pane-to-be.
            JPanel contentPane = new JPanel(new BorderLayout());
            contentPane.setOpaque(true);
            //Create a scrolled text area.
            output = new JTextArea(5, 30);
            output.setEditable(false);
            scrollPane = new JScrollPane(output);
            //Add the text area to the content pane.
            contentPane.add(scrollPane, BorderLayout.CENTER);
            return contentPane;
        /** Returns an ImageIcon, or null if the path was invalid. */
        protected static ImageIcon createImageIcon(String path) {
            java.net.URL imgURL = MenuLookDemo.class.getResource(path);
            if (imgURL != null) {
                return new ImageIcon(imgURL);
            } else {
                System.err.println("Couldn't find file: " + path);
                return null;
        public void init() {
            MenuLookDemoApplet demo = new MenuLookDemoApplet();
            setJMenuBar(demo.createMenuBar());
            setContentPane(demo.createContentPane());
    applet.html:
    <html>
    <head>
        <title>Menu Test Page </title>
    </head>
    <body>
    Here's the applet:
    <applet code="MenuLookDemoApplet.class" width="300" height="300">
    </applet>
    </body>
    </html>

    Unfortunately the menu items are fully accessible (or so our internal accessibility tool claims). It doesn't seem to be a problem on that level, but I was hoping that perhaps something else was interfeering.
    As for the JTable reading the previous cell, I've notice that it reads the last non-empty cell (regardless of whether it was the previous cell or not) when clicking or moving with the arrow keys to an empty cell. It works fine when clicking or moving to non-empty cells.
    I don't have any empty cells in the actual application so I did not try to fix it. My suspicions are that either an event is not being fired or the selection position is not being updated on the empty cells.

Maybe you are looking for